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

Scala mutable类代码示例

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

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



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

示例1: CreateSaltedTable

//设置package包名称以及导入依赖的类
package com.cloudera.sa.apptrans.setup.hbase

import java.io.File

import org.apache.commons.lang.StringUtils
import org.apache.hadoop.hbase.{HBaseConfiguration, HColumnDescriptor, HTableDescriptor, TableName}
import org.apache.hadoop.hbase.client.ConnectionFactory
import org.apache.hadoop.hbase.io.compress.Compression
import org.apache.hadoop.hbase.regionserver.{BloomType, ConstantSizeRegionSplitPolicy}
import org.apache.hadoop.hbase.util.Bytes

import scala.collection.mutable


object CreateSaltedTable {
  def main(args:Array[String]): Unit = {

    if (args.length == 0) {
      println("<tableName> <columnFamily> <regionCount> <numOfSalts> <hbaseConfigFolder>")
    }
    val tableName = args(0)
    val columnFamilyName = args(1)
    val regionCount = args(2).toInt
    val numOfSalts = args(3).toInt
    val hbaseConfigFolder = args(4)

    val conf = HBaseConfiguration.create()

    conf.addResource(new File(hbaseConfigFolder + "hbase-site.xml").toURI.toURL)

    val connection = ConnectionFactory.createConnection(conf)

    val admin = connection.getAdmin

    val tableDescriptor = new HTableDescriptor(TableName.valueOf(tableName))

    val columnDescriptor = new HColumnDescriptor(columnFamilyName)

    columnDescriptor.setCompressionType(Compression.Algorithm.SNAPPY)
    columnDescriptor.setBlocksize(64 * 1024)
    columnDescriptor.setBloomFilterType(BloomType.ROW)

    tableDescriptor.addFamily(columnDescriptor)

    tableDescriptor.setMaxFileSize(Long.MaxValue)
    tableDescriptor.setRegionSplitPolicyClassName(classOf[ConstantSizeRegionSplitPolicy].getName)

    val splitKeys = new mutable.MutableList[Array[Byte]]
    for (i <- 0 to regionCount) {
      val regionSplitStr = StringUtils.leftPad((i*(numOfSalts/regionCount)).toString, 4, "0")
      splitKeys += Bytes.toBytes(regionSplitStr)
    }
    admin.createTable(tableDescriptor, splitKeys.toArray)
  }
} 
开发者ID:tmalaska,项目名称:AppTrans,代码行数:56,代码来源:CreateSaltedTable.scala


示例2: MetadataExtractor

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

import org.apache.spark.input.PortableDataStream
import org.apache.tika.io.TikaInputStream
import org.apache.tika.metadata.Metadata
import org.apache.tika.parser.{AutoDetectParser, ParseContext}
import org.apache.tika.sax.BodyContentHandler

import scala.collection.mutable


class MetadataExtractor extends Serializable {

  def extract(
               file: (String, PortableDataStream)
             ) : (BodyContentHandler, Metadata, mutable.Map[String, String]) = {

    val tis = TikaInputStream.get(file._2.open())
    val parser = new AutoDetectParser()
    val handler = new BodyContentHandler(-1)
    val metadata = new Metadata()
    parser.parse(tis, handler, metadata, new ParseContext())
    val lowerCaseToCaseSensitive = mutable.Map[String, String]()
    for (name <- metadata.names()) {
      lowerCaseToCaseSensitive += (name.toLowerCase -> name)
    }
    (handler, metadata, lowerCaseToCaseSensitive)
  }

} 
开发者ID:jasonfeist,项目名称:tika-spark-datasource,代码行数:31,代码来源:MetadataExtractor.scala


示例3: KeyByAndMergeSyntax

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

import scala.collection.GenTraversableOnce
import scala.collection.mutable

object `package` {
  implicit class KeyByAndMergeSyntax[A](val _xs: GenTraversableOnce[A]) extends AnyVal {
    
    def keyByAndMerge[K](keyFn: A => K, merge: (A, A) => Option[A]): Map[K, A] = {
      val m = mutable.Map.empty[K, A]
      for (elem <- _xs) {
        val key = keyFn(elem)
        val value = m get key match {
          case None    => elem
          case Some(a) =>
            merge(a, elem) getOrElse
              (sys error s"Multiple elements for the same key $key:\n\t$a\n\t$elem")
        }
        m(key) = value
      }
      m.toMap
    }
  }
} 
开发者ID:typesafehub,项目名称:sbt-whitesource,代码行数:25,代码来源:package.scala


示例4: TestEnv

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

import java.util.concurrent.locks.{ReentrantLock, Lock}
import scala.collection.mutable



object TestEnv extends Env {

  override val osUtil: OSUtil = new TestOsUtil

  class TestOsUtil extends OSUtil {

    private[this] val systemVariableMap: mutable.Map[String,String] = mutable.Map("foo" -> "bar")
    private[this] val systemPropertiesMap: mutable.Map[String,String] = mutable.Map("user.home" -> System.getProperty("user.home"))
    private[this] val lock :Lock = new ReentrantLock()

    override def getSystemVariable(variable: String): Option[String] = {
      systemVariableMap get variable
    }

    def getSystemProperties(variable: String): Option[String] = {
      systemPropertiesMap get variable
    }

    def withSysVar(map: scala.collection.Map[String,String])(body : => Unit): Unit = {
      try {
        lock.lock()
        systemVariableMap.clear()
        systemVariableMap ++= map.toSeq
        body
      }
      catch {
        case e: Throwable => throw e
      }
      finally {
        lock.unlock()
      }
    }
  }

} 
开发者ID:gitter-badger,项目名称:artemisia,代码行数:43,代码来源:TestEnv.scala


示例5: maintainSum

//设置package包名称以及导入依赖的类
package hu.bme.mit.ire.nodes.unary

import hu.bme.mit.ire.datatypes._
import hu.bme.mit.ire.messages.ChangeSet
import hu.bme.mit.ire.util.GenericMath

import scala.collection.immutable.VectorBuilder
import scala.collection.mutable

trait SumLike {
  val sums = new mutable.HashMap[Tuple, Any].withDefault(d => 0)

  def maintainSum(changeSet: ChangeSet, aggregationKeys: Vector[Int], sumKey: Int): ChangeSet = {
    val oldValues = new mutable.HashMap[Tuple, Any]

    for (tuple <- changeSet.positive;
         key = aggregationKeys.map(tuple(_))) {
      if (!oldValues.contains(key)) {
        oldValues(key) = sums(key)
      }
      sums(key) = GenericMath.plus(sums(key), tuple(sumKey))
    }

    for (tuple <- changeSet.negative;
         key = aggregationKeys.map(tuple(_))) {
      if (!oldValues.contains(key)) {
        oldValues(key) = sums(key)
      }
      sums(key) = GenericMath.minus(sums(key), tuple(sumKey))
    }

    val positive = new VectorBuilder[Tuple]
    val negative = new VectorBuilder[Tuple]
    for ((key, oldValue) <- oldValues) {
      if (oldValue != 0) {
        negative += key :+ oldValues(key)
      }
      if (sums(key) != 0) {
        positive += key :+ sums(key)
      }
    }

    return ChangeSet(positive = positive.result(), negative = negative.result())
  }
} 
开发者ID:FTSRG,项目名称:ire,代码行数:46,代码来源:SumLike.scala


示例6: HelloSpec

//设置package包名称以及导入依赖的类
import org.scalatest._

import scala.collection.mutable

class HelloSpec extends FlatSpec with Matchers {
  "Hello" should "have tests" in {
    true should === (true)
  }

  "A Stack" should "pop values in last-in-first-out order" in {
    val stack = new mutable.Stack[Int]

    stack.push(1)
    stack.push(2)
    stack.pop should be (2)
    stack.pop should be (1)
  }

  it should "throw NoSuchElementException if an empty stack is popped " in {
    val emptyStack = new mutable.Stack[Int]
    a [NoSuchElementException] should be thrownBy {
      emptyStack.pop()
    }
  }
} 
开发者ID:greatdreams,项目名称:simple-scala-applciation-template,代码行数:26,代码来源:HelloSpec.scala


示例7: PlayRenderer

//设置package包名称以及导入依赖的类
package eu.tznvy.jancy.transpiler.rendering

import eu.tznvy.jancy.core.Play
import eu.tznvy.jancy.transpiler.helpers.ArraysHelper

import scala.collection.JavaConverters._
import scala.collection.mutable


object PlayRenderer extends Renderer[Play] {

  override def render(play: Play): String =
    YamlContext.get.dump(buildModel(play).asJava)

  override def renderAll(plays: Array[Play]): String = {
    val model = plays.map(buildModel(_).asJava).toArray
    YamlContext.get.dump(model)
  }

  private def buildModel(play: Play): mutable.LinkedHashMap[String, Any] = {
    val orderedPairs = "name" -> play.getName :: List[(String, Any)](
        "hosts" -> ArraysHelper.flattenAnArray(play.getHosts),
        "roles" -> play.getRoles,
        "tasks" -> play.getTasks.map(new TasklikeRenderer().buildModel(_).asJava),
        "handlers" -> play.getHandlers.map(new TasklikeRenderer().buildModel(_).asJava))
      .filter((p) => !ArraysHelper.isAnEmptyArray(p._2))
      .sortBy(_._1)

    mutable.LinkedHashMap[String, Any](orderedPairs: _*)
  }
} 
开发者ID:brthanmathwoag,项目名称:jancy,代码行数:32,代码来源:PlayRenderer.scala


示例8: EnvironmentCacheEntry

//设置package包名称以及导入依赖的类
package com.galacticfog.gestalt.lambda.impl

import java.util.concurrent.TimeoutException

import org.apache.mesos.Protos
import org.joda.time.DateTime
import scala.collection.mutable
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._

case class EnvironmentCacheEntry( lambdaId : String, env : Protos.Environment, queuedTime : DateTime = DateTime.now )
class EnvironmentCache {

  val cache : mutable.Map[String, EnvironmentCacheEntry] = mutable.Map[String, EnvironmentCacheEntry]()
  val EXPIRATION_SECONDS = sys.env.getOrElse( "ENV_CACHE_EXPIRATION_SECONDS", "900" ).toInt

  def getEnvironment( lambdaId : String, env : Future[Map[String,String]] ) : Protos.Environment = {

    val cacheEntry = cache.get( lambdaId )

    if( !cacheEntry.isDefined || cacheEntry.get.queuedTime.plusSeconds( EXPIRATION_SECONDS ).isBeforeNow ) {
      //wait for the future
      try {
        val result = Await.result( env, 5 seconds )
        val builder = Protos.Environment.newBuilder
        result.foreach{ entry =>
          builder.addVariables( Protos.Environment.Variable.newBuilder
            .setName( entry._1 )
            .setValue( entry._2 )
          )
        }

        val newEnv =  builder.build
        cache( lambdaId ) = new EnvironmentCacheEntry( lambdaId, newEnv )
        newEnv
      }
      catch {
        case ex : TimeoutException => {
          println( "TIMEOUT" )
          Protos.Environment.newBuilder.build
        }
      }
    }
    else {
      cache( lambdaId ).env
    }
  }
} 
开发者ID:GalacticFog,项目名称:gestalt-lambda,代码行数:49,代码来源:EnvironmentCache.scala


示例9: MysqlDbDriver

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

import javax.sql.DataSource

import com.criteo.qwebmon.{RunningQuery, DbDriver}

import scala.collection.mutable

class MysqlDbDriver(val name: String, dataSource: DataSource) extends DbDriver {

  private val runningQueriesSql = "show processlist"

  override def runningQueries: Seq[RunningQuery] = {
    val runningQueries: Seq[RunningQuery] = JdbcHelpers.executeQuery(dataSource, runningQueriesSql) { rs =>
      val acc = mutable.ListBuffer.empty[RunningQuery]
      while (rs.next()) {
        Option(rs.getString(8)).foreach { query =>
          acc += RunningQuery(
            user = rs.getString(2),
            runSeconds = rs.getInt(6),
            query = query,
            hostname = rs.getString(3)
          )
        }
      }
      acc
    }
    runningQueries
  }

} 
开发者ID:jqcoffey,项目名称:qwebmon,代码行数:32,代码来源:MysqlDbDriver.scala


示例10: VerticaDbDriver

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

import javax.sql.DataSource

import com.criteo.qwebmon.{RunningQuery, DbDriver}

import scala.collection.mutable

class VerticaDbDriver(val name: String, dataSource: DataSource) extends DbDriver {

  private val runningQueriesSql =
    """
      |SELECT
      |  user_name as user_name,
      |  DATEDIFF('second', statement_start, clock_timestamp()) as exec_time,
      |  current_statement as current_statement,
      |  client_hostname as client_hostname
      |FROM
      |  sessions
      |WHERE
      |  transaction_id <> -1 and
      |  statement_id is not null
      |ORDER BY
      |  exec_time desc
    """.stripMargin

  override def runningQueries: Seq[RunningQuery] = {
    val runningQueries: Seq[RunningQuery] = JdbcHelpers.executeQuery(dataSource, runningQueriesSql) { rs =>
      val acc = mutable.ListBuffer.empty[RunningQuery]
      while (rs.next()) {
        acc += RunningQuery(
          user = rs.getString(1),
          runSeconds = rs.getInt(2),
          query = rs.getString(3),
          hostname = rs.getString(4)
        )
      }
      acc
    }
    runningQueries
  }

} 
开发者ID:jqcoffey,项目名称:qwebmon,代码行数:44,代码来源:VerticaDbDriver.scala


示例11: Application

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

import java.io.{IOException, InputStream}

import models.TheWord
import play.api._
import play.api.mvc._

import scala.collection.mutable

object Application extends Controller {

  implicit val app = Play.current

  def index = Action {
    val real = getThatText("sample1.txt")
    val result = doTheJobFun {
      mutable.Seq(real: _*)
    }
    Ok(views.html.index(real.mkString("\n"), result))

  }

  def test = Action {
    Ok(getThatText("sample1.txt").mkString("\n"))
  }

  def load(filePath: String): InputStream = {
    Play.resourceAsStream("public/inputs/" concat filePath).getOrElse(throw new IOException("file not found: " + filePath))
  }

  def getThatText(fileName: String) = {
    //    val source = scala.io.Source.fromFile(app.getFile(fileName))("UTF-8")
    val source = scala.io.Source.fromInputStream(load(fileName))("UTF-8")
    try source.getLines().toList
    catch {
      case e: Exception => e.printStackTrace(); null
    }
    finally source.close()
  }

  val doTheJobFun = (text: mutable.Seq[String]) => {
    text.flatMap(_.split("[.?!:]"))
      .map(_.split("\\s+").find(_.nonEmpty).getOrElse(""))
      .filter(_.matches("[a-zA-Z].*"))
      .filter(!_.equals(""))
      .map { p => TheWord(p, p.reverse) }
      .toList
  }

} 
开发者ID:muhrifqii,项目名称:learn-to-play-scala,代码行数:52,代码来源:Application.scala


示例12: OSMParser

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

import scala.collection.mutable
import scala.xml.XML


class OSMParser {

  def parse = {
    val xml = XML.loadFile("data/shadyside.osm")

    // Parse all the streets from the xml file
    val streets = for {
      way <- xml \ "way"
      tags = way \\ "tag"
      streetness <- tags.map(t => (t \ "@k").toString -> (t \ "@v").toString).filter {
        case (k, v) =>
          (k == "highway") &&
            (v == "trunk" || v == "primary" || v == "secondary" || v == "tertiary" || v == "residential")
      }
    } yield way

    // Find the intersections where *three* or more streets share a node
    val nodeToWays = new mutable.HashMap[String, mutable.ListBuffer[String]]()
    for {
      street <- streets
      node <- street \\ "nd"
    } {
      val wayId = (street \ "@id").toString
      val nodeId = (node \ "@ref").toString
      if (nodeToWays.contains(wayId)) {
        nodeToWays(wayId) += nodeId
      } else {
        nodeToWays(wayId) = mutable.ListBuffer(nodeId)
      }
    }

    val intersectionNodeIds = nodeToWays.filter(_._2.length > 2).keys

    // Split the streets at intersections
    for {
      street <- streets
    } {
      val nodes = (street \\ "nd").map(_ \ "@ref").map(_.toString)
      println(nodes)
    }
  }

} 
开发者ID:kotarohara,项目名称:ToSidewalk,代码行数:50,代码来源:OSMParser.scala


示例13: FriendsListCache

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

import scala.collection.mutable


private[db] class FriendsListCache(dbFriendsList: Seq[DbFriend]) {

  private val cache = (mutable.HashMap.newBuilder ++= dbFriendsList.groupBy(_.user_id)).result()

  def get(id: Long) = cache.get(id)

  def insert(user_id: Long, friend_position: Int, friend_id: Long, friend_name: String): DbFriend = {
    val dbFriend = DbFriend(user_id = user_id, friend_position = friend_position, friend_id = friend_id, friend_name = friend_name)

    cache += cache
      .get(user_id)
      .fold(user_id -> Seq(dbFriend))(seq => user_id -> (seq :+ dbFriend))
    DAO.saveInsertedFriend(dbFriend)

    dbFriend
  }

  def update(user_id: Long, friend_position: Int, friend_id: Long, friend_name: String): DbFriend = {
    val dbFriend = DbFriend(user_id = user_id, friend_position = friend_position, friend_id = friend_id, friend_name = friend_name)

    cache
      .get(user_id)
      .foreach(seq => user_id -> (seq :+ dbFriend))
    DAO.saveUpdatedFriend(dbFriend)

    dbFriend
  }

  def delete(user_id: Long, friend_position: Int): DbFriend = {
    val dbFriend = cache(user_id)(friend_position - 1)

    cache
      .get(user_id)
      .foreach(seq => {
        cache += user_id -> ((0 until friend_position - 1).map(seq) ++
        (friend_position until seq.length).map(i => {
          val newDbFriend = seq(i).copy(friend_position = i)
          DAO.saveUpdatedFriend(newDbFriend)
          newDbFriend
        }))
        DAO.saveDeletedFriend(dbFriend)
      })

    dbFriend
  }
} 
开发者ID:fjaros,项目名称:init6,代码行数:52,代码来源:FriendsListCache.scala


示例14: TopInfoSeq

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

import akka.actor.ActorRef
import com.init6.users.TopInfo

import scala.collection.mutable


object TopInfoSeq {
  val DEFAULT_LIMIT = 25

  def apply(limit: Int = DEFAULT_LIMIT) = new TopInfoSeq(limit)
}

// Should be implemented using a MinMaxPriorityQueue (PriorityDeque)
// Doesn't seem scala offers any such thing so let's cheese it
sealed class TopInfoSeq(val limit: Int) {

  private val alreadyLogged = mutable.HashSet.empty[ActorRef]
  private var _l = mutable.PriorityQueue.empty[TopInfo](Ordering.by[TopInfo, Long](_.connectionInfo.connectedTime).reverse)
  private var lastConnectionTime: Long = 0

  def +=(elem: TopInfo): Unit = {
    if (!alreadyLogged.contains(elem.connectionInfo.actor)) {
      if (limit > _l.size) {
        _l += elem
        alreadyLogged += elem.connectionInfo.actor

        if (elem.connectionInfo.connectedTime > lastConnectionTime) {
          lastConnectionTime = elem.connectionInfo.connectedTime
        }

      } else if (elem.connectionInfo.connectedTime < lastConnectionTime) {
        _l += elem
        alreadyLogged += elem.connectionInfo.actor

        // gross as fuck
        val oldQ = _l.dequeueAll
        oldQ.dropRight(1).foreach(_l += _)
      }
    }
  }

  // also gross
  def values: Seq[TopInfo] = _l.clone().dequeueAll
} 
开发者ID:fjaros,项目名称:init6,代码行数:47,代码来源:TopInfoSeq.scala


示例15: CaseInsensitiveFiniteHashSet

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

import scala.collection.mutable


object CaseInsensitiveFiniteHashSet {
  def apply(limit: Int) = new CaseInsensitiveFiniteHashSet(limit)
}

sealed class CaseInsensitiveFiniteHashSet(limit: Int) extends mutable.LinkedHashSet[String] {

  override def contains(elem: String): Boolean = super.contains(elem.toLowerCase)
  override def remove(elem: String): Boolean = super.remove(elem.toLowerCase)

  override def add(elem: String): Boolean = {
    if (size == limit) {
      super.remove(head)
    }
    super.add(elem.toLowerCase)
  }
} 
开发者ID:fjaros,项目名称:init6,代码行数:22,代码来源:CaseInsensitiveFiniteHashSet.scala


示例16: apply

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

import akka.actor.ActorRef

import scala.collection.mutable


  def apply(value: String) = {
    val lCaseValue = value.toLowerCase
    filter {
      case (_, names) => names.contains(lCaseValue)
    }
    .keySet
  }

  def +=(value: (ActorRef, String)): BannedMap = {
    val bannedSet = get(value._1)
      .getOrElse({
        val bannedSet = mutable.LinkedHashSet.empty[String]
        this += value._1 -> bannedSet
        bannedSet
      })

    if (bannedSet.size >= limit) {
      bannedSet -= bannedSet.head
    }

    bannedSet += value._2.toLowerCase
    this
  }

  def ++=(bannedMap: Seq[(ActorRef, Seq[String])]) = {
    bannedMap.foreach {
      case (actor, bannedSeq) =>
        bannedSeq.foreach(banned => +=(actor -> banned))
    }
  }

  def -=(key: ActorRef, value: String) = {
    val lCaseValue = value.toLowerCase
    get(key).foreach(_ -= lCaseValue)
  }

  def -=(value: String) = {
    val lCaseValue = value.toLowerCase
    values.foreach(_ -= lCaseValue)
  }

  def toImmutable: Seq[(ActorRef, Seq[String])] = {
    mapValues(_.toSeq).toSeq
  }
} 
开发者ID:fjaros,项目名称:init6,代码行数:53,代码来源:BannedMap.scala


示例17: TopicManagementTest

//设置package包名称以及导入依赖的类
package org.hpi.esb.util

import org.scalatest.FunSuite
import org.scalatest.mockito.MockitoSugar

import scala.collection.mutable

class TopicManagementTest extends FunSuite with MockitoSugar {

  test("testGetMatchingTopics") {

    val topicsToDelete = mutable.Buffer("ESB_IN_0", "ESB_OUT_O", "ESB_STATISTICS_0")
    val topicsToKeep = mutable.Buffer("esb_new_IN_0", "esb_new_OUT_0", "esb_new_STATISTICS_0", "topic1", "topic2")
    val allTopics = topicsToDelete ++ topicsToKeep
    val prefix =  "ESB_"

    assert(allTopics.containsSlice(topicsToDelete))
    assert(allTopics.containsSlice(topicsToKeep))
    assert(allTopics.size == topicsToDelete.size + topicsToKeep.size)
    assert(TopicManagement.getMatchingTopics(allTopics, prefix) == topicsToDelete)
  }
} 
开发者ID:BenReissaus,项目名称:EnterpriseStreamingBenchmark,代码行数:23,代码来源:TopicManagementTest.scala


示例18: IgnoreLastElements

//设置package包名称以及导入依赖的类
package org.hpi.esb.datavalidator.validation.graphstage

import akka.stream.{Attributes, FlowShape, Inlet, Outlet}
import akka.stream.stage.{GraphStage, GraphStageLogic, InHandler, OutHandler}

import scala.collection.mutable


final class IgnoreLastElements[E](ignoreCount: Int)
  extends GraphStage[FlowShape[E, E]] {

  val in = Inlet[E]("IgnoreLastElement.in")
  val out = Outlet[E]("IgnoreLastElement.out")

  override def shape = FlowShape.of(in, out)

  override def createLogic(inheritedAttributes: Attributes) = new GraphStageLogic(shape) {

    var isBuffered = false
    val buffer: mutable.Queue[E] = new mutable.Queue[E]

    setHandlers(in, out, new InHandler with OutHandler {

      override def onPush(): Unit = {

        buffer.enqueue(grab(in))
        if(buffer.size == ignoreCount + 1) {
          push(out, buffer.dequeue())
        } else {
          // As long as the buffer is not full, nothing will be sent downstream.
          // As a result the downstream component will not call 'onPull' and we have
          // to manually pull upstream
          pull(in)
        }
      }

      override def onPull(): Unit = {
        pull(in)
      }

      override def onUpstreamFinish(): Unit = {
        completeStage()
      }
    })
  }
} 
开发者ID:BenReissaus,项目名称:EnterpriseStreamingBenchmark,代码行数:47,代码来源:IgnoreLastElements.scala


示例19: UndoManager

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

import scala.collection.mutable
import scala.util.{Failure, Try}


case class UndoManager(
                        var undoStack: mutable.Stack[Command] = mutable.Stack(),
                        var redoStack: mutable.Stack[Command] = mutable.Stack()
                      ) {
  def clearUndoStack(): Unit = undoStack.clear()
  def doIt(com: Command): Try[_] = {
    val result = com.doIt()
    if (result.isSuccess) {
      undoStack.push(com)
      redoStack.clear()
    }
    result
  }
  def undo(): Try[_] = {
    if (undoStack.nonEmpty) {
      val temp = undoStack.pop()
      val result = temp.undo()
      if (result.isSuccess) {
        redoStack.push(temp)
      }
      result
    } else {
      Failure(new Exception("Can't undo now!"))
    }
  }
  def redo(): Try[_] = {
    if (redoStack.nonEmpty) {
      val temp = redoStack.pop()
      val result = temp.doIt()
      if (result.isSuccess) {
        undoStack.push(temp)
      }
      result
    } else {
      Failure(new Exception("Can't redo now!"))
    }
  }

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


示例20: restart

//设置package包名称以及导入依赖的类
package de.htwg.se.scotlandyard.controller

import java.util

import de.htwg.se.scotlandyard.model.impl.Player

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.swing.Publisher


trait TScotlandYardController extends Publisher {

  var field : de.htwg.se.scotlandyard.model.TField
  var players: Array[Player]
  var caught : Boolean
  var statusText : String
  var startPosList : ListBuffer[Int]
  var playerlist : Array[Player]
  var moveList : util.ArrayList[String]
  var moveListPublic : util.ArrayList[String]
  var moveStackAll : mutable.Stack[(Int, Int, String, Int)]
  var roundCounter : Int
  var currentPlayer : Int
  var previousPlayer : Int
  var chosenCard : String

  def restart(): Unit
  def move(connectionPos: Int): Unit
  def moveGUI(newPosition: Int, usedCard: String, optionsNeeded: Boolean): Unit
  def checkOcc(pos: Int): Boolean
  def enoughCards(typ: String, player: Int): Boolean
  def useCard(typ: String, player: Int): Unit
  def startPos(player:Int): Unit
  def misterxMoves(): util.ArrayList[String]
  def addMisterxMoves(newPos: Int, usedCard: String): Unit
  def playerPositions(): String
  def playerInfo(player: Int) : String
  def undoMove(): Unit
  def toXml() : scala.xml.Node
  def fromXml (node: scala.xml.Node): String
  def saveGame() : Unit
} 
开发者ID:maximiliangraebel,项目名称:ScotlandYard,代码行数:44,代码来源:TScotlandYardController.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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