code
stringlengths
5
1M
repo_name
stringlengths
5
109
path
stringlengths
6
208
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1M
/* * ____ ____ _____ ____ ___ ____ * | _ \\ | _ \\ | ____| / ___| / _/ / ___| Precog (R) * | |_) | | |_) | | _| | | | | /| | | _ Advanced Analytics Engine for NoSQL Data * | __/ | _ < | |___ | |___ |/ _| | | |_| | Copyright (C) 2010 - 2013 SlamData, Inc. * |_| |_| \\_\\ |_____| \\____| /__/ \\____| All Rights Reserved. * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version * 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this * program. If not, see <http://www.gnu.org/licenses/>. * */ package com.precog.yggdrasil package actor import metadata.ColumnMetadata import metadata.ColumnMetadata._ import vfs.UpdateSuccess import com.precog.util._ import com.precog.common._ import com.precog.yggdrasil.vfs._ import akka.actor.Actor import akka.actor.ActorRef import akka.actor.PoisonPill import akka.dispatch.Promise import akka.util.Timeout import com.weiglewilczek.slf4s.Logging import scalaz.{NonEmptyList => NEL, _} import scalaz.syntax.monoid._ case class BatchComplete(requestor: ActorRef, checkpoint: YggCheckpoint) case class BatchFailed(requestor: ActorRef, checkpoint: YggCheckpoint) class BatchCompleteNotifier(p: Promise[BatchComplete]) extends Actor { def receive = { case complete : BatchComplete => p.complete(Right(complete)) self ! PoisonPill case other => p.complete(Left(new RuntimeException("Received non-complete notification: " + other.toString))) self ! PoisonPill } } /** * A batch handler actor is responsible for tracking confirmation of persistence for * all the messages in a specific batch. It sends */ class BatchHandler(ingestActor: ActorRef, requestor: ActorRef, checkpoint: YggCheckpoint, ingestTimeout: Timeout) extends Actor with Logging { private var remaining = -1 override def preStart() = { logger.debug("Starting new BatchHandler reporting to " + requestor) context.system.scheduler.scheduleOnce(ingestTimeout.duration, self, PoisonPill) } def receive = { case ProjectionUpdatesExpected(count) => remaining += (count + 1) logger.trace("Should expect %d more updates (total %d)".format(count, remaining)) if (remaining == 0) self ! PoisonPill case InsertComplete(path) => logger.trace("Insert complete for " + path) remaining -= 1 if (remaining == 0) self ! PoisonPill case UpdateSuccess(path) => logger.trace("Update complete for " + path) remaining -= 1 if (remaining == 0) self ! PoisonPill // These next two cases are errors that should not terminate the batch case PathOpFailure(path, ResourceError.PermissionsError(msg)) => logger.warn("Permissions failure on %s: %s".format(path, msg)) remaining -= 1 if (remaining == 0) self ! PoisonPill case PathOpFailure(path, ResourceError.IllegalWriteRequestError(msg)) => logger.warn("Illegal write failure on %s: %s".format(path, msg)) remaining -= 1 if (remaining == 0) self ! PoisonPill case PathOpFailure(path, err) => logger.error("Failure during batch update on %s:\\n %s".format(path, err.toString)) self ! PoisonPill case ArchiveComplete(path) => logger.info("Archive complete for " + path) remaining -= 1 if (remaining == 0) self ! PoisonPill case other => logger.warn("Received unexpected message in BatchHandler: " + other) } override def postStop() = { // if the ingest isn't complete by the timeout, ask the requestor to retry if (remaining != 0) { logger.info("Sending incomplete with %d remaining to %s".format(remaining, requestor)) ingestActor ! BatchFailed(requestor, checkpoint) } else { // update the metadatabase, by way of notifying the ingest actor // so that any pending completions that arrived out of order can be cleared. logger.info("Sending complete on batch to " + requestor) ingestActor ! BatchComplete(requestor, checkpoint) } } } // vim: set ts=4 sw=4 et:
precog/platform
yggdrasil/src/main/scala/com/precog/yggdrasil/actor/BatchHandler.scala
Scala
agpl-3.0
4,557
package pt.tecnico.dsi import org.joda.time.DateTime package object kadmin { implicit def dateTime2AbsoluteDateTime(dateTime: DateTime): AbsoluteDateTime = AbsoluteDateTime(dateTime) }
ist-dsi/kadmin
src/main/scala/pt/tecnico/dsi/kadmin/package.scala
Scala
mit
189
package com.twitter.finagle.http.service import org.specs.SpecificationWithJUnit import com.twitter.finagle.http.{Request, Status} import com.twitter.finagle.http.path._ import com.twitter.finagle.http.path.{Path => FPath} import com.twitter.util.Await class RoutingServiceSpec extends SpecificationWithJUnit { "RoutingServiceSpec" should { "RoutingService.byPath" in { val service = RoutingService.byPath { case "/test.json" => NullService } Await.result(service(Request("/test.json"))).status must_== Status.Ok Await.result(service(Request("/unknown"))).status must_== Status.NotFound } "RoutingService.byPathObject" in { val service = RoutingService.byPathObject { case Root / "test" ~ "json" => NullService } Await.result(service(Request("/test.json"))).status must_== Status.Ok Await.result(service(Request("/unknown"))).status must_== Status.NotFound } } }
firebase/finagle
finagle-http/src/test/scala/com/twitter/finagle/http/service/RoutingServiceSpec.scala
Scala
apache-2.0
958
/* * Copyright 2007-2011 WorldWide Conferencing, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.liftweb package util import java.lang.ref.{ReferenceQueue, SoftReference}; import java.util._ import Map._ import concurrent.locks._ import common._ import util._ import Helpers._ import Schedule._ import java.lang.Thread._ /** * Companion module that has the role of monitoring garbage collected references and remove the orphaned * keys from the cache. The monitor is started by calling <i>initialize</i> function and terminated by * calling <i>shutDown</i>. It monitors all SoftReferenceCache instances in the context of the same classloader. * It can also be used as a factory for obtaining new instances of SoftReferenceCache class */ object SoftReferenceCache { @volatile private var terminated = false; private[util] val refQueue = new ReferenceQueue[Any](); /** * Create a new SoftReferenceCache instance */ def apply[K, V](size: Int) = new SoftReferenceCache[K, V](size) /** * Initialize the orphan keys monitor */ def initialize = { // A daemon thread is more approapriate here then an Actor as // we'll do blocking reads from the reference queue val thread = new Thread(new Runnable() { def run() { processQueue } }) thread.setDaemon(true) thread setContextClassLoader null thread.start } /** * ShutDown the monitoring */ def shutDown = { terminated = true; } private def processQueue { while (!terminated) { tryo { // Wait 30 seconds for something to appear in the queue. val sftVal = refQueue.remove(30000).asInstanceOf[SoftValue[_, _]]; if (sftVal != null) { sftVal.cache.remove(sftVal.key); } } } } } case object ProcessQueue case object Done /** * A Map that holds the values as SoftReference-s. It also applies a LRU policy for the cache entries. */ class SoftReferenceCache[K, V](cacheSize: Int) { val cache = new LinkedHashMap[K, SoftValue[K, V]]() { override def removeEldestEntry(eldest: Entry[K, SoftValue[K, V]]): Boolean = { return size() > cacheSize; } } val rwl = new ReentrantReadWriteLock(); val readLock = rwl.readLock val writeLock = rwl.writeLock private def lock[T](l: Lock)(block: => T): T = { l lock; try { block } finally { l unlock } } /** * Returns the cached value mapped with this key or Empty if not found * * @param key * @return Box[V] */ def apply(key: K): Box[V] = lock(readLock) { Box.!!(cache.get(key)) match { case Full(value) => Box.!!(value.get) or { remove(key); Empty } case _ => Empty } } /** * Puts a new keyed entry in cache * @param tuple: (K, V)* * @return this */ def +=(tuple: (K, V)*) = { lock(writeLock) { for (t <- tuple) yield { cache.put(t._1, new SoftValue(t._1, t._2, this, SoftReferenceCache.refQueue)); } } this } /** * Removes the cache entry mapped with this key * * @return the value removed */ def remove(key: Any): Box[V] = { lock(writeLock) { for {value <- Box.!!(cache.remove(key).asInstanceOf[SoftValue[K, V]]) realValue <- Box.!!(value.get) } yield realValue } } def keys = cache.keySet } class SoftValue[K, V](k: K, v: V, lruCache: SoftReferenceCache[K, V], queue: ReferenceQueue[Any]) extends SoftReference[V](v, queue) { def key: K = k def cache: SoftReferenceCache[K, V] = lruCache }
pbrant/framework
core/util/src/main/scala/net/liftweb/util/SoftReferenceCache.scala
Scala
apache-2.0
4,188
package scalafiddle.shared case class FiddleId(id: String, version: Int) { override def toString: String = s"$id/$version" } case class Library( name: String, organization: String, artifact: String, version: String, compileTimeOnly: Boolean, scalaVersions: Seq[String], scalaJSVersions: Seq[String], extraDeps: Seq[String], group: String, docUrl: String, exampleUrl: Option[String] ) object Library { def stringify(lib: Library) = if (lib.compileTimeOnly) s"${lib.organization} %% ${lib.artifact} % ${lib.version}" else s"${lib.organization} %%% ${lib.artifact} % ${lib.version}" } case class FiddleData( name: String, description: String, sourceCode: String, libraries: Seq[Library], available: Seq[Library], scalaVersion: String, scalaJSVersion: String, author: Option[UserInfo], modified: Long )
scalafiddle/scalafiddle-editor
shared/src/main/scala/scalafiddle/shared/FiddleData.scala
Scala
apache-2.0
907
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package models.renewal import models.Country import play.api.libs.json.{JsSuccess, Json} import utils.AmlsSpec import scala.collection.Seq class RenewalSpec extends AmlsSpec { "The Renewal model" must { "succesfully validate if model is complete" when { "json is complete" in { val completeRenewal = Renewal(customersOutsideIsUK = Some(CustomersOutsideIsUK(true)), customersOutsideUK = Some(CustomersOutsideUK(Some(Seq(Country("United Kingdom", "GB")))))) val json = Json.obj( "customersOutsideIsUK" -> Json.obj( "isOutside" -> true ), "customersOutsideUK" -> Json.obj( "countries" -> Seq("GB") ), "hasChanged" -> false, "hasAccepted" -> true ) json.as[Renewal] must be(completeRenewal) } } "succesfully validate json" when { "CustomersOutsideIsUK is false" in { val renewal = Renewal(customersOutsideIsUK = Some(CustomersOutsideIsUK(false)), customersOutsideUK = Some(CustomersOutsideUK(None))) val json = Json.obj( "customersOutsideUK" -> Json.obj( "isOutside" -> false ), "hasChanged" -> false, "hasAccepted" -> true ) json.as[Renewal] must be(renewal) } } "serialize to and from JSON" in { val completeRenewal = Renewal( Some(InvolvedInOtherYes("test")), Some(BusinessTurnover.First), Some(AMLSTurnover.First), Some(AMPTurnover.First), Some(CustomersOutsideIsUK(false)), Some(CustomersOutsideUK(None)), Some(PercentageOfCashPaymentOver15000.First), Some(CashPayments(CashPaymentsCustomerNotMet(true), Some(HowCashPaymentsReceived(PaymentMethods(true,true,Some("other")))))), Some(TotalThroughput("01")), Some(WhichCurrencies(Seq("EUR"), None, Some(MoneySources(None, None, None)))), Some(TransactionsInLast12Months("1500")), Some(SendTheLargestAmountsOfMoney(Seq(Country("United Kingdom", "GB")))), Some(MostTransactions(Seq(Country("United Kingdom", "GB")))), Some(CETransactionsInLast12Months("123")), hasChanged = true ) val json = Json.parse(""" {"involvedInOtherActivities": {"involvedInOther":true,"details":"test"}, "businessTurnover":{"businessTurnover":"01"}, "turnover":{"turnover":"01"}, "ampTurnover":{"percentageExpectedTurnover":"01"}, "customersOutsideIsUK":{"isOutside":false}, "percentageOfCashPaymentOver15000":{"percentage":"01"}, "receiveCashPayments":{"receivePayments":true,"paymentMethods":{"courier":true,"direct":true,"other":true,"details":"other"}}, "totalThroughput":{"throughput":"01"}, "whichCurrencies":{"currencies":["EUR"], "usesForeignCurrencies":null,"moneySources":{}}, "transactionsInLast12Months":{"transfers":"1500"}, "sendTheLargestAmountsOfMoney":{"country_1":"GB"}, "mostTransactions":{"mostTransactionsCountries":["GB"]}, "ceTransactionsInLast12Months":{"ceTransaction":"123"}, "hasChanged":true, "hasAccepted":true} """.stripMargin) Json.fromJson[Renewal](json) mustBe JsSuccess(completeRenewal) } "roundtrip through json" in { val completeRenewal = Renewal( Some(InvolvedInOtherYes("test")), Some(BusinessTurnover.First), Some(AMLSTurnover.First), Some(AMPTurnover.First), Some(CustomersOutsideIsUK(false)), Some(CustomersOutsideUK(Option(Nil))), Some(PercentageOfCashPaymentOver15000.First), Some(CashPayments(CashPaymentsCustomerNotMet(true), Some(HowCashPaymentsReceived(PaymentMethods(true,true,Some("other")))))), Some(TotalThroughput("01")), Some(WhichCurrencies(Seq("EUR"), None, Some(MoneySources(None, None, None)))), Some(TransactionsInLast12Months("1500")), Some(SendTheLargestAmountsOfMoney(Seq(Country("United Kingdom", "GB")))), Some(MostTransactions(Seq(Country("United Kingdom", "GB")))), Some(CETransactionsInLast12Months("123")), hasChanged = true ) Json.fromJson[Renewal](Json.toJson(completeRenewal)) mustEqual JsSuccess(completeRenewal) } } "successfully validate json" when { "receiveCashPayments is false" in { val renewal = Renewal( customersOutsideUK = Some(CustomersOutsideUK(None)), receiveCashPayments = Some(CashPayments(CashPaymentsCustomerNotMet(false), None)) ) val json = Json.obj( "receiveCashPayments" -> Json.obj( "receivePayments" -> false, "paymentMethods" -> Json.obj() ), "hasChanged" -> false, "hasAccepted" -> true ) json.as[Renewal] must be(renewal) } } }
hmrc/amls-frontend
test/models/renewal/RenewalSpec.scala
Scala
apache-2.0
5,496
import sbt._ class Plugins(info: ProjectInfo) extends PluginDefinition(info) { val sbtIdeaRepo = "sbt-idea-repo" at "http://mpeltonen.github.com/maven/" val sbtIdea = "com.github.mpeltonen" % "sbt-idea-plugin" % "0.1-SNAPSHOT" }
egervari/scaladbtest
project/plugins/Plugins.scala
Scala
apache-2.0
238
package com.outr.stripe.support import com.outr.stripe._ import com.outr.stripe.price.{Price, Recurring, Tier, TransformQuantity} import scala.concurrent.Future class PricesSupport(stripe: Stripe) extends Implicits { def create(currency: String, active: Option[Boolean] = None, billingScheme: Option[String] = None, lookupKey: Option[String] = None, metadata: Map[String, String] = Map.empty, nickname: Option[String] = None, recurring: Option[Recurring] = None, tiers: List[Tier] = List(), tiersMode: Option[String] = None, transferLookupKey: Option[Boolean] = None, transformQuantity: Option[TransformQuantity] = None, unitAmount: Option[Int] = None, unitAmountDecimal: Option[BigDecimal] = None): Future[Either[ResponseError, Price]] = { val data = List( write("active", active), write("billing_scheme", billingScheme), write("currency", currency), write("lookup_key", lookupKey), write("metadata", metadata), write("nickname", nickname), write("recurring", recurring), write("tiers", tiers), write("tiers_mode", tiersMode), write("transfer_lookup_key", transferLookupKey), write("transform_quantity", transformQuantity), write("unit_amount", unitAmount), write("unit_amount_decimal", unitAmountDecimal) ).flatten stripe.post[Price]("prices", QueryConfig.default, data: _*) } def byId(priceId: String): Future[Either[ResponseError, Price]] = { stripe.get[Price](s"prices/$priceId", QueryConfig.default) } def update(priceId: String, active: Option[Boolean] = None, lookupKey: Option[String] = None, metadata: Map[String, String] = Map.empty, nickname: Option[String] = None, transferLookupKey: Option[Boolean] = None): Future[Either[ResponseError, Price]] = { val data = List( write("active", active), write("lookup_key", lookupKey), write("metadata", metadata), write("nickname", nickname), write("transfer_lookup_key", transferLookupKey) ).flatten stripe.post[Price](s"prices/$priceId", QueryConfig.default, data: _*) } def delete(priceId: String): Future[Either[ResponseError, Deleted]] = { stripe.delete[Deleted](s"prices/$priceId", QueryConfig.default) } def list(active: Option[Boolean] = None, currency: Option[String] = None, created: Option[TimestampFilter] = None, config: QueryConfig = QueryConfig.default, endingBefore: Option[String] = None, limit: Option[Int] = None, productId: Option[String] = None, `type`: Option[String] = None): Future[Either[ResponseError, StripeList[Price]]] = { val data = List( write("active", active), write("created", created), write("currency", currency), write("ending_before", endingBefore), write("limit", limit), write("product", productId), write("type", `type`) ).flatten stripe.get[StripeList[Price]]("prices", config, data: _*) } }
outr/scala-stripe
core/jvm/src/main/scala/com/outr/stripe/support/PricesSupport.scala
Scala
mit
3,205
/** * Copyright (C) 2012 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.webapp import org.orbeon.oxf.util.StringUtils._ object RunMode { val RunModeProperty = "oxf.run-mode" val ProdRunMode = "prod" val DevRunMode = "dev" val DefaultRunMode = ProdRunMode // Return the web app's run mode def getRunMode(contextParams: Map[String, String]) = contextParams.get(RunModeProperty) flatMap trimAllToOpt getOrElse DefaultRunMode }
brunobuzzi/orbeon-forms
src/main/scala/org/orbeon/oxf/webapp/RunMode.scala
Scala
lgpl-2.1
1,044
package examples.actors object seq extends App { import scala.actors.Actor._ val a = actor { { react { case 'A => println("received 1st message") }; () } andThen react { case 'A => println("received 2nd message") } } a ! 'A a ! 'A }
chenc10/Spark-PAF
build/scala-2.10.5/examples/actors/seq.scala
Scala
apache-2.0
276
package org.akka.essentials.zeromq.example1 import akka.actor.Actor import akka.actor.ActorLogging import akka.zeromq.Connect import akka.zeromq.Listener import akka.zeromq.SocketType import akka.zeromq.Subscribe import akka.zeromq.ZMQMessage import akka.zeromq.ZeroMQExtension class WorkerTaskB extends Actor with ActorLogging { val subSocket = ZeroMQExtension(context.system).newSocket(SocketType.Sub, Connect("tcp://127.0.0.1:1234"), Listener(self), Subscribe("someTopic")) def receive = { case m: ZMQMessage => var mesg = new String(m.payload(1)) log.info("Received Message @ B -> {}", mesg) } }
rokumar7/trial
AkkaWithZeroMQ/src/main/scala/org/akka/essentials/zeromq/example1/WorkerTaskB.scala
Scala
unlicense
623
package wallet import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.client.RestTemplate import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List @RunWith(classOf[SpringJUnit4ClassRunner]) @SpringApplicationConfiguration(classes = Array(classOf[Application])) @WebAppConfiguration class ApplicationTests { @Test def testRoute(route: String): String = { DisableSSLCertificateCheckUtil.disableChecks() val restTemplate = new RestTemplate() val URL = "https://www.routingnumbers.info/api/data.json?rn="+route val response = restTemplate.getForEntity(URL, classOf[String]) var objectMapper: ObjectMapper = new ObjectMapper(); var responseJson: JsonNode = objectMapper.readTree(response.getBody()); var statusCode = responseJson.get("code").asInt() if (statusCode == 200) { var name = responseJson.get("customer_name").asText() return name } else { throw new BankRecordNotFoundException("Not found") } return "" } }
shreedhar22/Restful-Digital-Wallet
src/main/scala/wallet/ApplicationTests.scala
Scala
mit
1,381
package windows import gui._ /** * Window class. */ abstract class Window(windowTitle: String) extends Frame(UIParent) { setAllPoints() setFrameStrata(Fullscreen) protected val actualWindow: Frame = new Frame(this) actualWindow.setPoint(Center) actualWindow.setSize(300) actualWindow.registerForDrag(actualWindow) actualWindow.setClampedToFrame(this) private val bg: Texture = actualWindow.createTexture() bg.setAllPoints() bg.setVertexColor(89.0 / 255, 157.0 / 255, 220.0 / 255) private val title: FontString = actualWindow.createFontString() title.setSize(actualWindow.width, 30) title.setPoint(Top) title.setText(windowTitle) title.setTextColor(0,0,0) def setTitle(t: String): Unit = title.setText(t) private object CloseButton extends Button(this) { setSize(75, 30) setText("Close") private val bg = createTexture() bg.setAllPoints() bg.setVertexColor(0.5, 0.5, 0.5) setScript(ScriptKind.OnMouseReleased)((_: Frame, _: Double, _: Double, button: Int) => { if (button == 0) { parent.get.hide() } }) } CloseButton.setPoint(TopRight, actualWindow, BottomRight) actualWindow.setFrameLevel(CloseButton.frameLevel + 1) private val border: Texture = actualWindow.createTexture("", Overlay) border.lineWidth = 5 border.setMode(LineMode) border.setAllPoints() border.setVertexColor(0,0,0) private var lastColorChanged: Double = 0 private var changed: Int = 1 private def shake(): Unit = { border.setVertexColor(1, 69.0 / 255, 0) lastColorChanged = 0 changed = 1 setScript(ScriptKind.OnUpdate)((_: Frame, dt: Double) => { lastColorChanged += dt if (lastColorChanged > 100) { lastColorChanged -= 100 if (changed % 2 == 0) { border.setVertexColor(1, 69.0 / 255, 0) } else { border.setVertexColor(0,0,0) } changed += 1 if (changed > 5) { border.setVertexColor(0,0,0) setScript(ScriptKind.OnUpdate)((_: Frame, _: Double) => {}) } } }) } setScript(ScriptKind.OnClick)((_: Frame, _: Double, _: Double, _: Int) => shake()) }
sherpal/holomorphic-maps
src/main/scala/windows/Window.scala
Scala
mit
2,257
package demo import org.apache.spark.SparkConf import org.apache.spark.SparkContext import org.apache.spark.sql.Row import org.apache.spark.sql.SparkSession import org.apache.spark.sql.types.DataTypes import org.apache.spark.sql.types.StructField import org.apache.spark.sql.types.StructType object MotcDataSql { def main(args: Array[String]) { val inputFile = args(0) val outputFile = args(1) val conf = new SparkConf() val sc = new SparkContext(conf) val spark = SparkSession.builder().appName(this.getClass.getName).config(conf).getOrCreate() val struct = StructType( StructField("vd_id", DataTypes.StringType, false) :: StructField("status", DataTypes.IntegerType, false) :: StructField("vsr_dir", DataTypes.IntegerType, false) :: StructField("vsr_id", DataTypes.IntegerType, false) :: StructField("speed", DataTypes.IntegerType, false) :: StructField("s_volume", DataTypes.IntegerType, false) :: StructField("t_volume", DataTypes.IntegerType, false) :: StructField("l_volume", DataTypes.IntegerType, false) :: StructField("m_volume", DataTypes.IntegerType, false) :: StructField("occ", DataTypes.IntegerType, false) :: StructField("err_tp", DataTypes.StringType, true) :: StructField("datacollecttime", DataTypes.StringType, false) :: Nil ) //the most straight-forward way is to load the csv directly, //however, data type transformation required for the schema defined... //val df = spark.read.option("sep", "\\t").schema(struct).csv("hdfs://spark-node1:9000/user/hadoop/motc/*") //create a RDD, transform it, and then convert to table val files = sc.textFile(inputFile) val rowRdd = files.map(x => x.split("\\t").transform(x => x.trim)) .map(x => Row(x(0), x(1).toInt, x(3).toInt, x(4).toInt, x(5).toInt, x(6).toInt, x(7).toInt, x(8).toInt, x(9).toInt, x(10).toInt, x(11), x(14))) spark.createDataFrame(rowRdd, struct).createOrReplaceTempView("motc") //SQL doing hourly aggregation and then save the output into file spark.sql( "SELECT vd_id, data_collect_hour, vsr_id, vsr_dir, " + " data_count, occ, speed, " + " l_volume, FLOOR(l_volume/data_count*60) fixed_l_volume, " + " s_volume, FLOOR(s_volume/data_count*60) fixed_s_volume, " + " m_volume, FLOOR(m_volume/data_count*60) fixed_m_volume, " + " t_volume, FLOOR(t_volume/data_count*60) fixed_t_volume, " + " l_volume+s_volume+m_volume+t_volume sum_volume, "+ " FLOOR((l_volume+s_volume+m_volume+t_volume)/data_count*60) fixed_sum_volume" + " FROM ( " + " SELECT vd_id, data_collect_hour, vsr_id, vsr_dir, " + " COUNT(*) data_count, AVG(occ) occ, " + " SUM(speed * (l_volume + s_volume + m_volume + t_volume)) / SUM(l_volume + s_volume + m_volume + t_volume) speed, " + " SUM(l_volume) l_volume, SUM(s_volume) s_volume, SUM(m_volume) m_volume, SUM(t_volume) t_volume " + " FROM ( " + " SELECT vd_id, SUBSTR(datacollecttime, 1, 13) data_collect_hour, vsr_id, vsr_dir, " + " occ, speed, " + " IF(l_volume >= 0, l_volume, 0) l_volume, " + " IF(s_volume >= 0, s_volume, 0) s_volume, " + " IF(m_volume >= 0, m_volume, 0) m_volume, " + " IF(t_volume >= 0, t_volume, 0) t_volume " + " FROM motc " + " WHERE status = 0 and err_tp = 'diag0' " + " ) a " + " GROUP BY vd_id, data_collect_hour, vsr_id, vsr_dir " + " ) a " + " ORDER BY vd_id, vsr_id, data_collect_hour ").rdd.map(x => x.mkString(",")).saveAsTextFile(outputFile) } }
kekemonster/iisi-spark
src/main/scala/demo/MotcDataSql.scala
Scala
mit
3,815
/* * The MIT License * * Copyright (c) 2016 Fulcrum Genomics * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.fulcrumgenomics.umi import com.fulcrumgenomics.FgBioDef._ import com.fulcrumgenomics.bam.api.{SamRecord, SamSource, SamWriter} import com.fulcrumgenomics.cmdline.{ClpGroups, FgBioTool} import com.fulcrumgenomics.commons.io.Io import com.fulcrumgenomics.commons.util.LazyLogging import com.fulcrumgenomics.sopt._ import com.fulcrumgenomics.util.{ProgressLogger, _} import htsjdk.samtools.util._ @clp(description = """ |Extracts unique molecular indexes from reads in a BAM file into tags. | |Currently only unmapped reads are supported. | |Only template bases will be retained as read bases (stored in the `SEQ` field) as specified by the read structure. | |A read structure should be provided for each read of a template. For example, paired end reads should have two |read structures specified. The tags to store the molecular indices will be associated with the molecular index |segment(s) in the read structure based on the order specified. If only one molecular index tag is given, then the |molecular indices will be concatenated and stored in that tag. Otherwise the number of molecular indices in the |read structure should match the number of tags given. In the resulting BAM file each end of a pair will contain |the same molecular index tags and values. Additionally, when multiple molecular indices are present the |`--single-tag` option may be used to write all indices, concatenated, to a single tag in addition to the tags |specified in `--molecular-index-tags`. | |Optionally, the read names can be annotated with the molecular indices directly. In this case, the read name |will be formatted `<NAME>+<UMIs1><UMIs2>` where `<UMIs1>` is the concatenation of read one's molecular indices. |Similarly for `<UMIs2>`. | |Mapping information will not be adjusted, as such, this tool should not be used on reads that have been mapped since |it will lead to an BAM with inconsistent records. | |The read structure describes the structure of a given read as one or more read segments. A read segment describes |a contiguous stretch of bases of the same type (ex. template bases) of some length and some offset from the start |of the read. Read structures are made up of `<number><operator>` pairs much like the CIGAR string in BAM files. |Four kinds ofoperators are recognized: | |1. `T` identifies a template read |2. `B` identifies a sample barcode read |3. `M` identifies a unique molecular index read |4. `S` identifies a set of bases that should be skipped or ignored | |The last `<number><operator>` pair may be specified using a '+' sign instead of number to denote "all remaining |bases". This is useful if, e.g., fastqs have been trimmed and contain reads of varying length. | |An example would be `10B3M7S100T` which describes 120 bases, with the first ten bases being a sample barcode, |bases 11-13 being a molecular index, bases 14-20 ignored, and bases 21-120 being template bases. See |[Read Structures](https://github.com/fulcrumgenomics/fgbio/wiki/Read-Structures) for more information. """, group = ClpGroups.SamOrBam) class ExtractUmisFromBam ( @arg(flag='i', doc = "Input BAM file.") val input: PathToBam, @arg(flag='o', doc = "Output BAM file.") val output: PathToBam, @arg(flag='r', doc = "The read structure, one per read in a template.") val readStructure: Seq[ReadStructure], @arg(flag='t', doc = "SAM tag(s) in which to store the molecular indices.", minElements=0) val molecularIndexTags: Seq[String] = Seq.empty, @arg(flag='s', doc = "Single tag into which to concatenate all molecular indices.") val singleTag: Option[String] = None, @arg(flag='a', doc = "Annotate the read names with the molecular indices. See usage for more details.") val annotateReadNames: Boolean = false, @arg(flag='c', doc = "The SAM tag with the position in read to clip adapters (e.g. `XT` as produced by Picard's `MarkIlluminaAdapters`).") val clippingAttribute: Option[String] = None ) extends FgBioTool with LazyLogging { val progress = ProgressLogger(logger, verb="written", unit=5e6.toInt) Io.assertReadable(input) Io.assertCanWriteFile(output) val (rs1, rs2) = readStructure match { case Seq(r1, r2) => (r1.withVariableLastSegment, Some(r2.withVariableLastSegment)) case Seq(r1) => (r1.withVariableLastSegment, None) case Seq() => invalid("No read structures given") case _ => invalid("More than two read structures given") } // This can be removed once the @deprecated molecularBarcodeTags is removed if (molecularIndexTags.isEmpty) invalid("At least one molecular-index-tag must be specified.") // validate the read structure versus the molecular index tags { // create a read structure for the entire template val rsMolecularBarcodeSegmentCount = readStructure.map(_.molecularBarcodeSegments.size).sum // make sure each tag is of length 2 molecularIndexTags.foreach(tag => if (tag.length != 2) invalid("SAM tags must be of length two: " + tag)) // ensure we either have one tag, or we have the same # of tags as molecular indices in the read structure. if (molecularIndexTags.size > 1 && rsMolecularBarcodeSegmentCount != molecularIndexTags.size) { invalid("Either a single SAM tag, or the same # of SAM tags as molecular indices in the read structure, must be given.") } } // Verify that if a single tag was specified that it is valid and not also contained in the per-index tags singleTag.foreach { tag => if (tag.length != 2) invalid(s"All tags must be two characters: ${tag}") if (molecularIndexTags.contains(tag)) invalid(s"$tag specified as single-tag and also per-index tag") } // Validate the molecular index tags against the read structures and then split them out private val (molecularIndexTags1, molecularIndexTags2) = molecularIndexTags match { case Seq(one) => val t1 = Seq.fill(rs1.molecularBarcodeSegments.length)(one) val t2 = Seq.fill(rs2.map(_.molecularBarcodeSegments.length).getOrElse(0))(one) (t1, t2) case tags => // Validate that the # of molecular barcodes in the read structure matches the tags val total = rs1.molecularBarcodeSegments.length + rs2.map(_.molecularBarcodeSegments.length).getOrElse(0) validate(tags.length == total, s"Read structures contains $total molecular barcode segments, but ${tags.length} tags provided.") (tags.take(rs1.molecularBarcodeSegments.length), tags.drop(rs1.molecularBarcodeSegments.length)) } override def execute(): Unit = { val in = SamSource(input) val iterator = in.iterator.buffered val out = SamWriter(output, in.header) while (iterator.hasNext) { val r1 = iterator.next() if (r1.paired) { // get the second read and make sure there's a read structure. if (!iterator.hasNext) fail(s"Could not find mate for read ${r1.name}") if (rs2.isEmpty) fail(s"Missing read structure for read two (required for paired end data).") val r2 = iterator.next() // verify everything is in order for paired end reads Seq(r1, r2).foreach(r => { if (!r.paired) fail(s"Read ${r.name} was not paired") if (r.mapped) fail(s"Read ${r.name} was not unmapped") }) if (!r1.firstOfPair) fail(s"Read ${r1.name} was not the first end of a pair") if (!r2.secondOfPair) fail(s"Read ${r2.name} was not the second end of a pair") if (!r1.name.equals(r2.name)) fail(s"Read names did not match: '${r1.name}' and '${r2.name}'") // now do some work val bases1 = ExtractUmisFromBam.annotateRecord(record=r1, readStructure=rs1, molecularIndexTags=molecularIndexTags1, clippingAttribute=clippingAttribute) val bases2 = ExtractUmisFromBam.annotateRecord(record=r2, readStructure=rs2.get, molecularIndexTags=molecularIndexTags2, clippingAttribute=clippingAttribute) if (annotateReadNames) { // Developer Note: the delimiter must be an ascii character less than what is usually in the read names. For // example "|" doesn't work. I am not completely sure why. r1.name = r1.name + "+" + bases1 + bases2 r2.name = r2.name + "+" + bases1 + bases2 } require(r1.name.equals(r2.name), s"Mismatching read name. R1: '$r1' R2: '$r2'") // If we have duplicate tags, then concatenate them in the same order across the read pair. val tagAndValues = (molecularIndexTags1.map { tag => (tag, r1[String](tag)) } ++ molecularIndexTags2.map { tag => (tag, r2[String](tag)) }).toList tagAndValues.groupBy(_._1).foreach { case (tag, tuples) => val attr = tuples.map(_._2).mkString(ExtractUmisFromBam.UmiDelimiter) r1(tag) = attr r2(tag) = attr } // If we have a single-tag, then also output values there singleTag.foreach { tag => val value = tagAndValues.map { case (t,v) => v }.mkString(ExtractUmisFromBam.UmiDelimiter) r1(tag) = value r2(tag) = value } val recs = Seq(r1, r2) out ++= recs recs.foreach(progress.record) } else { // verify everything is in order for single end reads if (r1.mapped) fail(s"Read ${r1.name} was not unmapped") // now do some work val bases1 = ExtractUmisFromBam.annotateRecord(record=r1, readStructure=rs1, molecularIndexTags=molecularIndexTags1, clippingAttribute=clippingAttribute) if (annotateReadNames) { // Developer Note: the delimiter must be an ascii character less than what is usually in the read names. For // example "|" doesn't work. I am not completely sure why. r1.name = r1.name + "+" + bases1 } // If we have duplicate tags, then concatenate them in the same order across the read val tagAndValues = molecularIndexTags1.map { tag => (tag, r1[String](tag)) } tagAndValues.groupBy(_._1).foreach { case (tag, tuples) => val attr = tuples.map(_._2).mkString(ExtractUmisFromBam.UmiDelimiter) r1(tag) = attr } out += r1 progress.record(r1) } } out.close() CloserUtil.close(iterator) } } object ExtractUmisFromBam { val UmiDelimiter = "-" /** * Extracts bases associated with molecular indices and adds them as SAM tags. The read's bases will only contain * template bases as defined in the given read structure. */ private[umi] def annotateRecord(record: SamRecord, readStructure: ReadStructure, molecularIndexTags: Seq[String], clippingAttribute: Option[String] = None): String = { val bases = record.basesString val qualities = record.qualsString // get the bases associated with each segment val readStructureBases = readStructure.extract(bases, qualities) // get the molecular index segments val molecularIndexBases = readStructureBases.filter(_.kind == SegmentType.MolecularBarcode).map(_.bases) // set the index tags // TODO: when we remove the deprecated molecularBarcodeTags option, consider whether or not we still // need to have support for specifying a single tag via molecularIndexTags. molecularIndexTags match { case Seq(tag) => record(tag) = molecularIndexBases.mkString(UmiDelimiter) case _ => if (molecularIndexTags.length < molecularIndexBases.length) throw new IllegalStateException("Found fewer molecular index SAM tags than molecular indices in the read structure.") else if (molecularIndexTags.length > molecularIndexBases.length) throw new IllegalStateException("Found fewer molecular indices in the read structure than molecular index SAM tags.") molecularIndexTags.zip(molecularIndexBases).foreach { case (tag, b) => record(tag) = b } } // keep only template bases and qualities in the output read val basesAndQualities = readStructureBases.filter(_.kind == SegmentType.Template) // update any clipping information updateClippingInformation(record=record, clippingAttribute=clippingAttribute, readStructure=readStructure) record.bases = basesAndQualities.map(_.bases).mkString record.quals = basesAndQualities.map(_.quals).mkString // return the concatenation of the molecular indices in sequencing order molecularIndexBases.mkString } /** * Update the clipping information produced by Picard's MarkIlluminaAdapters to account for any non-template bases * that will be removed from the read. */ private[umi] def updateClippingInformation(record: SamRecord, clippingAttribute: Option[String], readStructure: ReadStructure): Unit = { clippingAttribute.map(tag => (tag, record.get[Int](tag))) match { case None => () case Some((tag, None)) => () case Some((tag, Some(clippingPosition))) => val newClippingPosition = readStructure.takeWhile(_.offset < clippingPosition).filter(_.kind == SegmentType.Template).map { t => if (t.length.exists(l => t.offset + l < clippingPosition)) t.length.get else clippingPosition - t.offset }.sum record(tag) = newClippingPosition } } }
fulcrumgenomics/fgbio
src/main/scala/com/fulcrumgenomics/umi/ExtractUmisFromBam.scala
Scala
mit
14,722
package mr.merc.ai import mr.merc.map.hex.TerrainHex import mr.merc.unit.Soldier import mr.merc.unit.Attack object AttackSelectionHelper { def selectBestAttack(attacker: Soldier, defender: Soldier, attackerHex: TerrainHex, defenderHex: TerrainHex): Int = { // arguments are attacks with index def selectBestAttack(attacks: List[(Attack, Int)]): Int = { attacks.map { case (a, n) => val defenderAttack = Attack.selectBestAttackForDefender(attacker, defender, a) val damage = Attack.possibleAttackersDamage(true, attacker, defender, a, defenderAttack) * a.count val chance = a.chanceOfSuccess(Attack.calculateSoldierDefence(defender, defenderHex)) (damage * chance.chanceNumber, n) }.sortBy(-_._1).head._2 } val attacksWithoutAnswer = attacker.soldierType.attacks.zipWithIndex.flatMap { case (a, i) => val defenderAttack = Attack.selectBestAttackForDefender(attacker, defender, a) defenderAttack match { case Some(_) => None case None => Some(a, i) } } if (attacksWithoutAnswer.nonEmpty) { selectBestAttack(attacksWithoutAnswer) } else { selectBestAttack(attacker.soldierType.attacks.zipWithIndex) } } }
RenualdMarch/merc
src/main/scala/mr/merc/ai/AttackSelectionHelper.scala
Scala
gpl-3.0
1,266
package io.github.loustler.kase.simple /** * @author loustler * @since 10/20/2018 */ object Matcher { def deeplySize(x: List[_]): Int = x match { case Nil => 0 case List(a: List[_], b: List[_]) => x.size + a.size + b.size case List(_*) => x.size } def shallowSize(x: List[_]): Int = x match { case Nil => 0 case List(_) => x.size case _ => -1 } }
loustler/sKaLa
src/main/scala/io/github/loustler/kase/simple/Matcher.scala
Scala
apache-2.0
397
/* SCALA Implementation of Insertion Sort. Though the corner cases are covered. But still if you find any additions to it, please do add a test for it. Any improvements/tests in the code is highly appreciated. */ class InsertionSort { def insertionSort(listToBeSorted: List[Int]): List[Int] = { listToBeSorted match { case List() => List() case x :: xs1 => insertNum(x, insertionSort(xs1)) } } def insertNum(x: Int, xs: List[Int]): List[Int] = { xs match { case List() => List(x) case y :: ys => if (x <= y) x :: xs else y :: insertNum(x, ys) } } }
warreee/Algorithm-Implementations
Insertion_Sort/Scala/aayushKumarJarvis/InsertionSort.scala
Scala
mit
610
package main import org.scalatest.FlatSpec import org.mockito.Mockito._ import org.scalatestplus.mockito.MockitoSugar import org.scalatest.{FlatSpec, PrivateMethodTester} import maths.integration.RungeKuttaIntegration import io.config.Configuration class BiologicalModelTest extends FlatSpec with MockitoSugar with PrivateMethodTester { // "Biological model" should "initialise" in { // val mockIntegrator = mock[RungeKuttaIntegration] // val mockClock = mock[SimulationClock] // val mockConfig = mock[Configuration] // val model = new BiologicalModel(mockConfig, mockClock, mockIntegrator) // assert(model != null) // } // it should "...." in { // // } }
shawes/zissou
src/test/scala/main/BiologicalModelTest.scala
Scala
mit
691
import scala.tools.partest._ object Test extends DirectTest { override def extraSettings: String = "-usejavacp -Yrangepos -Vprint:patmat -Vprint-pos -d " + testOutput.path override def code = """ abstract class A[T] { val foo: Set[_ <: T] = null val bar: Set[_ <: T] }""".trim override def show(): Unit = Console.withErr(System.out)(compile()) }
martijnhoekstra/scala
test/files/run/existential-rangepos.scala
Scala
apache-2.0
359
/* * Copyright 2017 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package controllers.registration.business import itutil.ControllerISpec import models.ApplicantDetails import models.api.EligibilitySubmissionData import play.api.http.HeaderNames import play.api.libs.json.Json import play.api.libs.ws.WSResponse import play.api.test.Helpers._ import scala.concurrent.Future class PartnershipNameControllerISpec extends ControllerISpec { val partnershipName = "testPartnershipName" "show Partnership Name page" should { "return OK" in new Setup { given() .user.isAuthorised() .audit.writesAudit() .audit.writesAuditMerged() .s4lContainer[ApplicantDetails].isEmpty .vatScheme.has("applicant-details", Json.toJson(validFullApplicantDetails)(ApplicantDetails.writes)) .registrationApi.getSection[EligibilitySubmissionData](Some(testEligibilitySubmissionData)) insertCurrentProfileIntoDb(currentProfile, sessionId) val response: Future[WSResponse] = buildClient("/partnership-official-name").get() whenReady(response) { res => res.status mustBe OK } } } "submit Partnership Name page" should { "return SEE_OTHER" in new Setup { given() .user.isAuthorised() .audit.writesAudit() .audit.writesAuditMerged() .vatScheme.has("applicant-details", Json.toJson(validFullApplicantDetails)(ApplicantDetails.writes)) .vatScheme.isUpdatedWith( validFullApplicantDetails.copy( entity = Some(testPartnership.copy( companyName = Some(partnershipName) )) )) .s4lContainer[ApplicantDetails].isEmpty .s4lContainer[ApplicantDetails].clearedByKey .registrationApi.getSection[EligibilitySubmissionData](Some(testEligibilitySubmissionDataPartner)) insertCurrentProfileIntoDb(currentProfile, sessionId) val response: Future[WSResponse] = buildClient("/partnership-official-name").post(Map("partnershipName" -> Seq(partnershipName))) whenReady(response) { res => res.status mustBe SEE_OTHER res.header(HeaderNames.LOCATION) mustBe Some(routes.TradingNameController.show.url) } } } }
hmrc/vat-registration-frontend
it/controllers/registration/business/PartnershipNameControllerISpec.scala
Scala
apache-2.0
2,771
/* * Copyright 2017 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.hmrcemailrenderer.templates.amls import uk.gov.hmrc.hmrcemailrenderer.domain.MessageTemplate import uk.gov.hmrc.hmrcemailrenderer.templates.ServiceIdentifier.AntiMoneyLaunderingSupervision import uk.gov.hmrc.hmrcemailrenderer.templates.FromAddress.govUkTeamAddress object AmlsTemplates { val templates = Seq( MessageTemplate.create( templateId = "amls_notification_received_template", fromAddress = govUkTeamAddress, service = AntiMoneyLaunderingSupervision, subject = "New message", plainTemplate = txt.amlsNotificationReceived.f, htmlTemplate = html.amlsNotificationReceived.f) ) }
saurabharora80/hmrc-email-renderer
app/uk/gov/hmrc/hmrcemailrenderer/templates/amls/AmlsTemplates.scala
Scala
apache-2.0
1,257
/* * Copyright 2013 David Savage * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.chronologicalthought.modula.reflect import ref.Reference /** * Created by IntelliJ IDEA. * User: dave * Date: 28/06/2012 * Time: 13:31 * To change this template use File | Settings | File Templates. */ trait GarbageCollector { // TODO hooks could return a Future to get value from onCollect? def phantomHook[T <: AnyRef](value: T)(onCollect: => Unit) def phantomRefHook[T <: AnyRef](value: T)(onCollect: Reference[T] => Unit): Reference[T] def weakHook[T <: AnyRef](value: T)(onCollect: => Unit) def weakRefHook[T <: AnyRef](value: T)(onCollect: Reference[T] => Unit): Reference[T] def softHook[T <: AnyRef](value: T)(onCollect: => Unit) def softRefHook[T <: AnyRef](value: T)(onCollect: Reference[T] => Unit): Reference[T] }
davemssavage/modula
api/src/main/scala/org/chronologicalthought/modula/reflect/GarbageCollector.scala
Scala
apache-2.0
1,364
/* * Copyright (c) 2016, Team Mion * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package io.teammion.morefood.recipes import io.teammion.morefood.{Items, Registry} import net.minecraft.item.ItemStack /** * Smelting recipes (sorted alphabetically by output) * * @author Stefan Wimmer <[email protected]> */ object SmeltingRecipes { def register() : Unit = { Registry.addSmelting( Items.APPLE_CHOCOLATE, Items.APPLE_CHOCOLATE_COATED.stack ) Registry.addSmelting( Items.BREAD_DOUGH, new ItemStack(Items.BREAD) ) Registry.addSmelting( Items.EGG, Items.EGG_BOILED.stack ) Registry.addSmelting( Items.FISH_STICK_RAW, Items.FISH_STICK.stack ) Registry.addSmelting( Items.FRENCH_FRIES_RAW, Items.FRENCH_FRIES.stack ) Registry.addSmelting( new ItemStack(Items.DYE, 1, 3), Items.COCOA_BEAN_ROASTED.stack ) Registry.addSmelting( Items.SCHNITZEL_RAW, Items.SCHNITZEL.stack ) Registry.addSmelting( Items.STRAWBERRY_CHOCOLATE, Items.STRAWBERRY_CHOCOLATE_COATED.stack ) } }
teammion/tm-morefood
src/main/scala/io/teammion/morefood/recipes/SmeltingRecipes.scala
Scala
isc
2,064
package org.jetbrains.plugins.scala.lang.refactoring.mock import com.intellij.openapi.editor.impl.DocumentImpl import com.intellij.openapi.editor._ /** * Pavel Fatin */ class EditorMock(text: String, offset: Int) extends EditorStub { private val selection = new SelectionModelStub() override def offsetToLogicalPosition(offset: Int) = { val s = text.take(offset) new LogicalPosition(s.count(_ == '\\n'), s.reverse.takeWhile(_ != '\\n').size) // Workaround for SI-5971 (should be "s.view.reverse.") } override def logicalPositionToOffset(pos: LogicalPosition) = text.split('\\n').view.map(_.length + 1).take(pos.line).sum + pos.column override def getDocument: Document = new DocumentImpl(text) override def getSelectionModel: SelectionModel = selection override def getCaretModel: CaretModel = new CaretModelMock(offset, offsetToLogicalPosition(offset)) override def offsetToVisualPosition(i: Int, b: Boolean, b1: Boolean): VisualPosition = null }
LPTK/intellij-scala
test/org/jetbrains/plugins/scala/lang/refactoring/mock/EditorMock.scala
Scala
apache-2.0
993
trait B extends A { type F = S[Int] }
jamesward/xsbt
sbt/src/sbt-test/source-dependencies/abstract-type/B.scala
Scala
bsd-3-clause
39
/******************************************************************************* * Copyright (c) 2019. Carl Minden * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package com.anathema_roguelike package environment.features import com.anathema_roguelike.environment.Location import com.anathema_roguelike.main.display.VisualRepresentation import com.anathema_roguelike.stats.effects.{AdditiveCalculation, Effect, Modifier} import com.anathema_roguelike.stats.locationstats.{Brightness, LocationStat} class Brazier(location: Location) extends Feature( new VisualRepresentation('\\u0436'), new VisualRepresentation('\\u0436'), foreground = true, passable = false, opacity = 1.0, damping = 1.0) { override def getEffect: Option[Effect[Location, LocationStat]] = { new Effect[Location, LocationStat](this, List(new Modifier[Brightness](AdditiveCalculation.fixed(20.0)))) } }
carlminden/anathema-roguelike
src/com/anathema_roguelike/environment/features/Brazier.scala
Scala
gpl-3.0
1,574
package latis.reader.tsml.ml import scala.xml.Node import latis.util.StringUtils import scala.xml.UnprefixedAttribute import scala.xml.Null import scala.xml.transform.RewriteRule import scala.xml.Elem import scala.xml.transform.RuleTransformer import scala.xml.ProcInstr /** * Wrapper for TSML that defines a Dataset. */ class DatasetMl(val xml: Node) extends TupleMl(xml) { //TODO: Dataset is no longer a Tuple //TODO: deal with aggregation tsml /** * Get a list of top level (i.e. direct children) variable definitions for this dataset node. * Handle implicit Functions. If the first variable definition is "index" or "time" * wrap in a function with those as a 1D domain. * If there are multiple top level variables, wrap in a Tuple. */ def getVariableMl: VariableMl = { val es = Tsml.getVariableNodes(xml) if (es.isEmpty) throw new RuntimeException("TSML does not define any variables.") //TODO: wrap multiple vars in tuple //if (es.length > 1) ??? //Handle implicit Functions. If the first variable definition is "index" or "time" // wrap in a function with those as a 1D domain. val label = es.head.label //first variable def if (label == "index" || label == "time") wrapWithImplicitFunction(es.head, es.tail) else VariableMl(es.head) } /** * Get all the processing instructions (ProcInstr) for the Dataset * as a Seq of the type (target) and String value (proctext). */ lazy val processingInstructions: Seq[(String,String)] = { val pis: Seq[ProcInstr] = xml.child.collect { case pi: ProcInstr => pi } pis.map(pi => pi.target -> pi.proctext) } /** * Given tsml nodes representing the domain and range variables, * wrap them to look like a "function" variable. */ private def wrapWithImplicitFunction(d: Seq[Node], r: Seq[Node]): VariableMl = { val domain = <domain/>.copy(child = d.head) //assume one domain variable, <domain>d.head</domain> //TODO: make sure r.length > 0 val range = <range/>.copy(child = r) //the rest, <range>r</range> VariableMl(<function/>.copy(child = Seq(domain, range))) //will recurse and make all descendants } /** * Put the XML attributes from the "adapter" element into a Map. * Any properties parameterized with "${property} will be resolved. */ def getAdapterAttributes(): Map[String,String] = { val atts = (xml \ "adapter").head.attributes val seq = for (att <- atts) yield (att.key, StringUtils.resolveParameterizedString(att.value.text)) seq.toMap } /** * Create a new Tsml with the adapter.location attribute updated. */ def setLocation(loc: String): Tsml = { val newloc = new UnprefixedAttribute("location", loc, Null) val rr = new RewriteRule { override def transform(n: Node): Seq[Node] = n match { case e: Elem if(e.label == "adapter") => e % newloc case other => other } } val rt = new RuleTransformer(rr) Tsml(rt.transform(xml).head) } }
dlindhol/LaTiS
src/main/scala/latis/reader/tsml/ml/DatasetMl.scala
Scala
epl-1.0
3,025
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 Andre White. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.truthencode.ddo.model.feats import io.truthencode.ddo.activation.OnToggleEvent import io.truthencode.ddo.model.classes.HeroicCharacterClass import io.truthencode.ddo.model.classes.HeroicCharacterClass.Artificer import io.truthencode.ddo.model.misc.DefaultCoolDown import io.truthencode.ddo.support.requisite.{FeatRequisiteImpl, GrantsToClass, RequiresAllOfClass} /** * [[https://ddowiki.com/page/Rune_Arm_Use Rune Arm Use]] Passively, you are able to equip and use * magical relics called Rune Arms. When this feat is toggled on, it will set the rune arm to * automatically begin charging whenever it can. While you have a Rune Arm charging, tapping the * Rune Arm Key (default: Alt) will fire the Rune Arm. You can freely perform most other actions * while charging the Rune Arm. Created by adarr on 2/16/2017. */ protected[feats] trait RuneArmUse extends FeatRequisiteImpl with ActiveFeat with OnToggleEvent with Passive with GrantsToClass with RequiresAllOfClass with DefaultCoolDown { override def allOfClass: Seq[(HeroicCharacterClass, Int)] = List((Artificer, 2)) override def grantToClass: Seq[(HeroicCharacterClass, Int)] = List((Artificer, 2)) }
adarro/ddo-calc
subprojects/common/ddo-core/src/main/scala/io/truthencode/ddo/model/feats/RuneArmUse.scala
Scala
apache-2.0
1,876
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.serializer import scala.concurrent._ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ import org.apache.spark.{SparkConf, SparkContext} import org.apache.spark.benchmark.{Benchmark, BenchmarkBase} import org.apache.spark.internal.config._ import org.apache.spark.internal.config.Kryo._ import org.apache.spark.launcher.SparkLauncher.EXECUTOR_EXTRA_JAVA_OPTIONS import org.apache.spark.serializer.KryoTest._ import org.apache.spark.util.ThreadUtils /** * Benchmark for KryoPool vs old "pool of 1". * To run this benchmark: * {{{ * 1. without sbt: * bin/spark-submit --class <this class> --jars <spark core test jar> * 2. build/sbt "core/test:runMain <this class>" * 3. generate result: * SPARK_GENERATE_BENCHMARK_FILES=1 build/sbt "core/test:runMain <this class>" * Results will be written to "benchmarks/KryoSerializerBenchmark-results.txt". * }}} */ object KryoSerializerBenchmark extends BenchmarkBase { var sc: SparkContext = null val N = 500 override def runBenchmarkSuite(mainArgs: Array[String]): Unit = { val name = "Benchmark KryoPool vs old\\"pool of 1\\" implementation" runBenchmark(name) { val benchmark = new Benchmark(name, N, 10, output = output) Seq(true, false).foreach(usePool => run(usePool, benchmark)) benchmark.run() } } private def run(usePool: Boolean, benchmark: Benchmark): Unit = { lazy val sc = createSparkContext(usePool) benchmark.addCase(s"KryoPool:$usePool") { _ => val futures = for (_ <- 0 until N) yield { Future { sc.parallelize(0 until 10).map(i => i + 1).count() } } val future = Future.sequence(futures) ThreadUtils.awaitResult(future, 10.minutes) } } def createSparkContext(usePool: Boolean): SparkContext = { val conf = new SparkConf() // SPARK-29282 This is for consistency between JDK8 and JDK11. conf.set(EXECUTOR_EXTRA_JAVA_OPTIONS, "-XX:+UseParallelGC -XX:-UseDynamicNumberOfGCThreads") conf.set(SERIALIZER, "org.apache.spark.serializer.KryoSerializer") conf.set(KRYO_USER_REGISTRATORS, classOf[MyRegistrator].getName) conf.set(KRYO_USE_POOL, usePool) if (sc != null) { sc.stop() } sc = new SparkContext("local-cluster[4,1,1024]", "test", conf) sc } override def afterAll(): Unit = { if (sc != null) { sc.stop() } } }
goldmedal/spark
core/src/test/scala/org/apache/spark/serializer/KryoSerializerBenchmark.scala
Scala
apache-2.0
3,256
/** * Created by alec on 2/6/17. */ package scalation.plot import javafx.application.Application import javafx.scene.Scene import javafx.scene.chart.NumberAxis import javafx.scene.chart.LineChart import javafx.scene.chart.XYChart import javafx.scene.chart.Axis import javafx.scene.paint.Color import javafx.stage.Stage import javafx.scene.Node import javafx.scene.control.ToggleButton import javafx.scene.Group; import javafx.scene.layout.HBox import javafx.scene.layout.VBox import javafx.event.ActionEvent import javafx.event.EventHandler import javafx.geometry.Insets import scalation.linalgebra.{VectoD, VectoI} import scalation.scala2d.{Panel, VizFrame} import scala.math.pow //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `PlotFX` class takes 'x' and 'y' vectors of data values and plots the '(x, y)' * data points. For more vertical vectors use `PlotM`. * @param x the x vector of data values (horizontal) * @param y the y vector of data values (primary vertical) * @param z the z vector of data values (secondary vertical) to compare with y * @param _title the title of the plot */ class PlotFX (x: VectoD, y: VectoD, z: VectoD, _title: String = "Plot y vs. x") extends VizFrame (_title, null) { // getContentPane ().add (new Canvas (x, y, z, getW, getH)) // setVisible (true) val c = new CanvasFX(_title, 800, 700) // defining the axes val xAxis: NumberAxis = new NumberAxis() val yAxis: NumberAxis = new NumberAxis() // creating the chart var lineChart: LineChart[Number, Number] = new LineChart[Number, Number](xAxis, yAxis) // creating labels xAxis.setLabel("X Axis") yAxis.setLabel("Y Axis") lineChart.setTitle("Data Overview") // defining the series var series1: XYChart.Series[Number, Number] = new XYChart.Series[Number, Number]() //if (z != null) { var series2: XYChart.Series[Number, Number] = new XYChart.Series[Number, Number]() //} // if series1.setName("Quadratic") series2.setName("Cubic") for (i <- 0 until x.dim) { val xy = new XYChart.Data[Number, Number](x(i), y(i)) series1.getData.add(xy) } // for for (i <- 0 until x.dim) { val xz = new XYChart.Data[Number, Number](x(i), z(i)) series2.getData.add(xz) } // for lineChart.getData.add(series1) lineChart.getData.add(series2) lineChart.setPrefSize(800, 600); val scene: Scene = new Scene(new Group()) val vbox: VBox = new VBox() val hbox: HBox = new HBox() val btn1: ToggleButton = new ToggleButton() btn1.setText("Hide " + series1.getName()) btn1.setOnAction(new EventHandler[ActionEvent]() { override def handle(event: ActionEvent): Unit = { val source: ToggleButton = event.getSource.asInstanceOf[ToggleButton] if (source.isSelected()) { setT(0, lineChart) btn1.setText("Show " + series1.getName()) } else { setC(0, lineChart) btn1.setText("Hide " + series1.getName()) } } }) val btn2: ToggleButton = new ToggleButton() btn2.setText("Hide " + series2.getName()) btn2.setOnAction(new EventHandler[ActionEvent]() { override def handle(event: ActionEvent): Unit = { val source: ToggleButton = event.getSource.asInstanceOf[ToggleButton] if (source.isSelected()) { setT(1, lineChart) btn2.setText("Show " + series2.getName()) } else { setC(1, lineChart) btn2.setText("Hide " + series2.getName()) } } }) hbox.setSpacing(10) hbox.getChildren.addAll(btn1) hbox.getChildren.addAll(btn2) vbox.getChildren.addAll(lineChart, hbox) hbox.setPadding(new Insets(10, 10, 10, 50)) c.nodes.getChildren.addAll(vbox) c.show() def setT(n: Int, x: LineChart[Number, Number]): Unit = { x.lookup(".default-color" + n + ".chart-series-line").setStyle("-fx-stroke: transparent;") } //setT def setC(n: Int, x: LineChart[Number, Number]): Unit = { x.lookup(".default-color" + n + ".chart-series-line").setStyle("-fx-stroke: DEFAULT_COLOR+(nextClearBit%8);") } //setT } // PlotFX class object PlotFXTest extends App { import scalation.linalgebra.VectorD /* val x = VectorD (0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) val y = VectorD (0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 16.0, 9.0, 4.0, 1.0, 0.0) */ val n = 40 val x = new VectorD (n) val y = new VectorD (n) val z = new VectorD (n) for (i <- 0 until n) { x(i) = i / 10.0; y(i) = pow (x(i) - 5, 2) } for (i <- 0 until n) { x(i) = i / 10.0; z(i) = pow (x(i) - 5, 3) } val plot = new PlotFX (x, y, z) println ("plot = " + plot) } // PlotFXTest
scalation/fda
scalation_1.3/scalation_mathstat/src/main/scala/scalation/plot/PlotFX.scala
Scala
mit
4,691
package edu.uw.at.iroberts.wirefugue.analyze.ip.defragment import akka.actor.{Actor, ActorRef} import akka.stream.{Attributes, FlowShape, Inlet, Outlet} import akka.stream.stage.{GraphStage, GraphStageLogic} import akka.util.{ByteString, ByteStringBuilder} import edu.uw.at.iroberts.wirefugue.pcap.{IPAddress, InternetChecksum} import edu.uw.at.iroberts.wirefugue.protocol.overlay.IPV4Datagram import scala.annotation.tailrec import scala.collection.immutable.SortedMap /** * Created by Ian Robertson <[email protected]> on 5/30/17. */ object Defragment extends GraphStage[FlowShape[IPV4Datagram, IPV4Datagram]] { val in = Inlet[IPV4Datagram]("fragmented-packets-in") val out = Outlet[IPV4Datagram]("non-fragmented-packets-out") override val shape = FlowShape.of(in, out) override def createLogic(attrs: Attributes): GraphStageLogic = new GraphStageLogic(shape) { var defragger: Map[(IPAddress, IPAddress, Short), Actor] = ??? // For each packet received: // 1. If MF = 0 && offset = 0 pass the packet as-is // 2. If MF = 0 set totalLength to offset + length // 3. otherwise, store the payload at the offset // 4. check for missing fragments, if none, concat & send } } class Defragger(key: FragmentKey, sender: ActorRef) extends Actor { private var dataLength: Option[Int] = None private var bytesYet: Int = 0 private var fragments: SortedMap[Int, IndexedSeq[Byte]] = SortedMap.empty private var firstHeader: Option[IndexedSeq[Byte]] = None private[this] def missingFragments: Boolean = { @tailrec def r(next: Int): Boolean = fragments.get(next) match { case Some(f) => r(next + f.length + 1) case None => true } if (dataLength.isEmpty || firstHeader.isEmpty) true else r(0) } private[this] def assembledPayload: IndexedSeq[Byte] = { val b: ByteStringBuilder = ByteString.createBuilder fragments.foldLeft((b, 0)) { case ((b, next),(offset,bytes)) => (b ++= bytes, offset + bytes.length) } b.result() } override def receive = { case p: IPV4Datagram => val isLastFragment = !p.flagMF val isFirstFragment = p.offset == 0 if (isLastFragment) dataLength = Some(p.offset*8 + p.data.length) if (isFirstFragment) firstHeader = Some(p.bytes.take(p.ihl * 4)) fragments += p.offset * 8 -> p.data if (!missingFragments) { // Starting with the header for the first fragment, remove the MF flag, // update totalLength, recompute header checksum. // TODO This won't be pretty until we have a proper builder for packets val headerBytes = IPV4Datagram(firstHeader.get).ihl * 4 val totalLength = headerBytes + dataLength.get val newPacket: Array[Byte] = new Array[Byte](totalLength) firstHeader.get.copyToArray(newPacket) newPacket(2) = (totalLength >>> 8).toByte newPacket(3) = totalLength.toByte newPacket(7) = (newPacket(7) & ~0x20).toByte newPacket(10) = 0 newPacket(11) = 0 // Avoid copying the buffer when calculating the checksum val checksum = InternetChecksum.internetChecksum( newPacket.view(0, headerBytes) ) newPacket(10) = (checksum >>> 8).toByte newPacket(11) = checksum.toByte sender ! IPV4Datagram(ByteString(newPacket)) } } }
robertson-tech/wirefugue
sensor/src/main/scala/edu/uw/at/iroberts/wirefugue/analyze/ip/defragment/Defragment.scala
Scala
gpl-3.0
3,356
package eu.phisikus.plotka.examples.scala case class TextMessage(text : String)
phisikus/plotka
examples/scala-docker-example/src/main/scala/eu/phisikus/plotka/examples/scala/TextMessage.scala
Scala
bsd-3-clause
80
/* Copyright 2011-2013 Spiral Arm Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.package bootstrap.liftmodules */ package net.liftmodules.imapidle import javax.mail._ import javax.mail.event._ import com.sun.mail.imap._ import java.util.Properties import net.liftweb.actor._ import net.liftweb.common._ import net.liftweb.util._ import net.liftweb.util.Helpers._ import org.joda.time._ import scala.language.postfixOps, scala.language.implicitConversions case class Credentials(username: String, password: String, host: String = "imap.gmail.com") case class Callback(h: MessageHandler) /** * Actor which manages the connection to the IMAP server * and dispatches javax.mail.Messages to the user function * given during `ImapIdle.init`. * This actor is started automatically during init. */ object EmailReceiver extends LiftActor with Loggable { private var inbox: Box[Folder] = Empty private var store: Box[Store] = Empty private var credentials: Box[Credentials] = Empty private var callback: Box[MessageHandler] = Empty // To be able to remove listeners during a clean up, we need to keep a list of them. private var listeners: List[java.util.EventListener] = Nil // If the connection to the IMAP server goes away, we manually disconnect (reap) idle connections that are older than 30 minutes private var idleEnteredAt: Box[DateTime] = Empty // Idle the connection. "Idle" in the sense of "run slowly while disconnected from a load or out of gear" perhaps. RFC2177 private def idle { idleEnteredAt = Full(new DateTime) // IMAPFolder.idle() blocks until the server has an event for us, so we call this in a separate thread. def safeIdle(f: IMAPFolder) : Unit = Schedule { () => try { logger.debug("IMAP Actor idle block entered") f.idle logger.debug("IMAP Actor idle block exited") } catch { // If the idle fails, we want to restart the connection because we will no longer be waiting for messages. case x : Throwable=> logger.warn("IMAP Attempt to idle produced " + x) EmailReceiver ! 'restart } idleEnteredAt = Empty } inbox match { case Full(f: IMAPFolder) => safeIdle(f) case x => logger.error("IMAP Can't idle " + x) } } // Connect to the IMAP server and pipe all events to this actor private def connect = { logger.debug("IMAP Connecting") require(credentials.isEmpty == false) require(callback.isEmpty == false) val props = new Properties props.put("mail.store.protocol", "imaps") props.put("mail.imap.enableimapevents", "true") val session = Session.getDefaultInstance(props) session.setDebug(Props.getBool("mail.session.debug", true)) val store = session.getStore() val connectionListener = new ConnectionListener { def opened(e: ConnectionEvent): Unit = EmailReceiver ! e def closed(e: ConnectionEvent): Unit = EmailReceiver ! e def disconnected(e: ConnectionEvent): Unit = EmailReceiver ! e } listeners = connectionListener :: Nil store.addConnectionListener(connectionListener) // We may be able to live without store event listeners as they only seem to be notices. val storeListener = new StoreListener { def notification(e: StoreEvent): Unit = EmailReceiver ! e } listeners = storeListener :: listeners store.addStoreListener(storeListener) credentials foreach { c => store.connect(c.host, c.username, c.password) val inbox = store.getFolder("INBOX") if (inbox.exists) inbox.open(Folder.READ_WRITE) else logger.error("IMAP - folder INBOX not found. Carrying on in case it reappears") val countListener = new MessageCountAdapter { override def messagesAdded(e: MessageCountEvent): Unit = EmailReceiver ! e } inbox.addMessageCountListener(countListener) listeners = countListener :: listeners logger.info("IMAP Connected, listeners ready") this.inbox = Box !! inbox this.store = Box !! store } } private def disconnect { logger.debug("IMAP Disconnecting") // We un-bind the listeners before closing to prevent us receiving disconnect messages // which... would make us want to reconnect again. inbox foreach { i => listeners foreach { case mcl: MessageCountListener => i.removeMessageCountListener(mcl) case _ => } if (i.isOpen) i.close(true) } store foreach { s => listeners foreach { case cl: ConnectionListener => s.removeConnectionListener(cl) case sl: StoreListener => s.removeStoreListener(sl) case _ => } if (s.isConnected) s.close() } inbox = Empty store = Empty listeners = Nil } private def retry(f: => Unit): Unit = try { f } catch { case e : Throwable => logger.warn("IMAP Retry failed - will retry: "+e.getMessage) Thread.sleep(1 minute) retry(f) } private def reconnect { disconnect Thread.sleep(15 seconds) connect } private def processEmail(messages: Array[Message]) { for (m <- messages; c <- callback if c(m)) { m.setFlag(Flags.Flag.DELETED, true) } inbox foreach { _.expunge } } // Useful for debugging from the console: //def getInbox = inbox def messageHandler = { case c: Credentials => credentials = Full(c) case Callback(h) => callback = Full(h) case 'startup => connect EmailReceiver ! 'collect EmailReceiver ! 'idle EmailReceiver ! 'reap case 'idle => idle case 'shutdown => disconnect case 'restart => logger.info("IMAP Restart request received") retry { reconnect } // manual collection in case we missed any notifications during restart or during error handling EmailReceiver ! 'collect EmailReceiver ! 'idle case 'collect => logger.info("IMAP Manually checking inbox") inbox map { _.getMessages } foreach { msgs => processEmail(msgs) } case e: MessageCountEvent if !e.isRemoved => logger.info("IMAP Messages available") processEmail(e.getMessages) EmailReceiver ! 'idle case 'reap => logger.debug("IMAP Reaping old IDLE connections") Schedule.schedule(this, 'reap, 1 minute) for { when <- idleEnteredAt dur = new Duration(when, new DateTime) if dur.getMillis() > (30 minutes) } EmailReceiver ! 'restart case e: StoreEvent => logger.warn("IMAP Store event reported: " + e.getMessage) case e: ConnectionEvent if e.getType == ConnectionEvent.OPENED => logger.debug("IMAP Connection opened") case e: ConnectionEvent if e.getType == ConnectionEvent.DISCONNECTED => logger.warn("IMAP Connection disconnected") case e: ConnectionEvent if e.getType == ConnectionEvent.CLOSED => logger.info("IMAP Connection closed - reconnecting") reconnect case e => logger.warn("IMAP Unhandled email event: "+e) } }
d6y/liftmodules-imap-idle
src/main/scala/net/liftmodules/imapidle/EmailReceiver.scala
Scala
apache-2.0
7,548
/* * Copyright (c) 2013-2014 Telefónica Investigación y Desarrollo S.A.U. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package es.tid.cosmos.api.controllers.admin import scalaz._ import com.wordnik.swagger.annotations._ import play.api.libs.json.Json import play.api.mvc.{Action, Controller} import es.tid.cosmos.api.auth.request.RequestAuthentication import es.tid.cosmos.api.controllers.common._ import es.tid.cosmos.api.controllers.common.auth.ApiAuthController import es.tid.cosmos.api.profile.{Capability, CosmosProfile} /** Admin resource representing the maintenance status of the system */ @Api(value = "/cosmos/v1/maintenance", listingPath = "/doc/cosmos/v1/maintenance", description = "Maintenance status of the Cosmos platform") class MaintenanceResource( override val auth: RequestAuthentication, maintenanceStatus: MaintenanceStatus) extends Controller with ApiAuthController with JsonController { @ApiOperation(value = "Maintenance status of the system", httpMethod = "GET", responseClass = "scala.Boolean") def get = Action { request => for { profile <- requireAuthenticatedApiRequest(request) } yield currentStatusResponse } @ApiOperation(value = "Change maintenance status", httpMethod = "PUT", notes = "The returned body is the new maintenance status as a bare boolean") @ApiErrors(Array( new ApiError(code = 400, reason = "Invalid JSON payload"), new ApiError(code = 401, reason = "Unauthorized user"), new ApiError(code = 403, reason = "Not an operator") )) @ApiParamsImplicit(Array( new ApiParamImplicit(paramType = "body", dataType = "scala.Boolean") )) def put() = Action(parse.tolerantJson) { request => for { profile <- requireAuthenticatedApiRequest(request) _ <- requireOperatorProfile(profile) wantedStatus <- validJsonBody[Boolean](request) } yield { if (wantedStatus) maintenanceStatus.enterMaintenance() else maintenanceStatus.leaveMaintenance() currentStatusResponse } } private def requireOperatorProfile(profile: CosmosProfile): ActionValidation[Unit] = { import Scalaz._ if (profile.capabilities.hasCapability(Capability.IsOperator)) ().success else Forbidden(Json.toJson(Message("Action reserved to operators"))).failure } private def currentStatusResponse = Ok(Json.toJson(maintenanceStatus.isUnderMaintenance)) }
telefonicaid/fiware-cosmos-platform
cosmos-api/app/es/tid/cosmos/api/controllers/admin/MaintenanceResource.scala
Scala
apache-2.0
2,932
package scife.enumeration package lzy import combinators._ import scala.collection.mutable import scife.util._ object ConcatInfinite { def apply[T](s1: Infinite[T], s2: Infinite[T]) = new ConcatInfinite( Array(s1, s2) ) def apply[T](streams: Array[Infinite[T]]) = new ConcatInfinite(streams) } class ConcatInfinite[T] (val enumArray: Array[Infinite[T]]) extends ConcatMul[T] with Infinite[T] with HasLogger { // assert(enums.forall(_.size == -1), "RoundRobbinInfinite should be constructed " + // "with infinite streams. " + // "(sizes are %s)".format(enums.map(_.size).distinct)) override def enums = enumArray.toSeq override def apply(ind: Int) = { val arrInd = ind % enumArray.length val elInd = ind / enumArray.length enumArray(arrInd)(elInd) } }
kaptoxic/SciFe
src/main/scala/scife/enumeration/lzy/ConcatInfinite.scala
Scala
gpl-2.0
803
package edu.umass.ciir.kbbridge.nlp import collection.mutable.ListBuffer import scala.collection.JavaConversions._ import edu.umass.ciir.kbbridge.nlp.NlpData.NlpXmlMention import edu.umass.ciir.models.StopWordList import edu.umass.ciir.kbbridge.data.EntityMention class NlpQueryContextBuilder { val normalizeText = TextNormalizer.normalizeText _ def acronymText(name: String): String = { normalizeText(name).filter(_.isUpper) } val stopPosTags = Set("PRP", "IN", "TO", "PRP$") def acronymTexts(mention: NlpXmlMention): Set[String] = { val mainTokens = mention.tokens.filter(token => { !(StopWordList.isStopWord(token.word.toLowerCase)) || (!(stopPosTags contains token.pos)) }) val acronym1 = mainTokens.map(_.word.head).mkString("") Set(acronymText(mention.text), acronym1) } //================================== //== Coref == //-- //- def corefChainOfMention(query: EntityMention): Seq[NlpXmlMention] = { val name = query.entityName val normName = normalizeText(name) val corefChains = query.nerNeighbors // val corefChains = NerExtractor.getXmlCorefForMentionFromFullText(() => {elQuery.fullText}, mention.docId, source = source) val chainsWithName = corefChains.filter(mention => { TextNormalizer.normalizeText(mention.text) equals normName }) chainsWithName } def getAlternateNamesFromCoref(query: EntityMention, chain: Seq[NlpXmlMention]): Seq[String] = { val chains = for (m <- chain; if (m.tokens.exists(_.pos.startsWith("NNP")))) yield { // extract sequences of proper nouns var buffer = new ListBuffer[NlpData.Token] var sequences = new ListBuffer[String]() for (token <- m.tokens) { if (token.pos.startsWith("NNP")) { buffer += token } else { if (buffer.size > 0) { sequences += (for (tok <- buffer) yield tok.word).mkString(" ") buffer = new ListBuffer[NlpData.Token] } } } if (buffer.size > 0) { sequences += (for (tok <- buffer) yield tok.word).mkString(" ") } // filter the proper nouns to probable name matches to our original query val filteredSequences = for (sequence <- sequences.toList; if (normalizeText(sequence) contains normalizeText(query.entityName)) || // in sync with... (acronymText(sequence) equals normalizeText(query.entityName))) yield sequence filteredSequences.toSeq } chains.flatten } // warning, these offsets refer to the clean text, which might be modified from the galago full text def getPositionsFromCoref(chain: Seq[NlpXmlMention]): Seq[(Int, Int)] = { for (m <- chain) yield (m.charBegin, m.charEnd) } //================================== //== NER == //-- //- def allNers(query: EntityMention): scala.Seq[(String, NlpXmlMention)] = { val fullners = query.nerNeighbors for (mention <- fullners) yield { (mention.ner, mention) } // // var nlpFile = NlpExtractor.getOrQueueNlp(() => { // query.fullText // }, query.docId, query.source) // val ners = NlpExtractReader.getNersDetails(nlpFile.get) // ners } def nerSpansOfMention(normAltNames: Set[String], ners: Seq[(String, NlpXmlMention)]) = { val nersForQuery = for ((ner, mention) <- ners; if (normAltNames contains normalizeText(mention.text))) // keep in sync with... yield mention nersForQuery } // // def relaxedNerMatches(query:TacELQuery2, ners:Seq[(String, NlpXmlMention)]) = { // val name = query.name // for((ner, mention) <- ners) { // val (left, right) = mention.text.split(name) // if((left == "" || left.last = " ") && (right == "" || right.head = " ")){ // // substring match at word boundary // } // // for(tok <- mention.tokens) { // // } // } // } //================================== //== Sentences == //-- //- // def allSentences(query: EntityMention): scala.Seq[String] = { // //NlpReader.allSentences(query) // } // def allSentences(query: TacELQuery2): scala.Seq[String] = { // if (ConfInfo.useKbaNlpReader) { // val kbaSearcher = KnowledgeBaseSearcher.getSearcher("kba") // val r = kbaSearcher.getDocument(docId, true) // if (r != null) { // val nerData = r.metadata.get("nerData") // val sents = NerLineReader.extractSentencesFromNerData(nerData) // sents.map(_.text) // } else Seq() // } else { // // var nlpFile = NlpExtractor.getOrQueueNlp(() => { // query.fullText // }, query.docId, query.source) // if (nlpFile.isDefined){ // val sentences = TokenXmlReader.getSentences(nlpFile.get) // sentences.map(sent => sent.tokens.map(_.word).mkString(" ")) // } else { // query.fullText.replace("\\\\s+", " ").split(".").toSeq.map(_.trim) // } // } // } //================================== //== put everything together == //-- //- def buildContext(query: EntityMention): QueryContext = { val corefChains = corefChainOfMention(query) val altNamesFromCoref = getAlternateNamesFromCoref(query, corefChains) buildContextFromAltNames(query, altNamesFromCoref, corefChains) } def buildContextFromAltNames(query: EntityMention, altNamesFromCoref: Seq[String], corefChainsIfAvail: Seq[NlpXmlMention] = Seq()): QueryContext = { val ners = allNers(query) val corefChains = if (!corefChainsIfAvail.isEmpty) corefChainsIfAvail else { ners.map(_._2).filter(ner => { val normText = normalizeText(ner.text) altNamesFromCoref.exists(name => normalizeText(name) == normText) }) } // println(ners.mkString("$$$$ All Ners with NLP \\n", "\\n","")) // println(ners.map(_._2.text).mkString("$$$$ All Ners ",", ", "")) val normalizedQuery = normalizeText(query.entityName) val normNamesSet = (altNamesFromCoref.map(name => normalizeText(name)) ++ Seq(normalizedQuery)).toSet val nersForMention = nerSpansOfMention(normNamesSet, ners) val sentenceSet = ( nersForMention.map(_.sentenceId) ++ corefChains.map(_.sentenceId) ).toSet val nersNotForMention: Seq[(String, NlpXmlMention)] = ners.filter(nm => !nersForMention.contains(nm._2)) val nersInSentence = for ((ner, mention) <- nersNotForMention; if (sentenceSet.contains(mention.sentenceId))) yield mention // val sentencesForMention = { // val sents = allSentences(query) // if (sentenceSet contains 0) { // sents.filter(sent => normNamesSet.exists(nameVar => sent.contains(nameVar))) // } else { // sentenceSet.toSeq.sorted.map(idx => sents.get(idx - 1)) // } // } val queryOffsets = nersForMention.flatMap(ner => Seq(ner.charBegin, ner.charEnd)) val nersByOffsetDistance = if (queryOffsets.isEmpty) { //System.err.println("TacNlpQUeryContextBuilder: No queryOffsets found for "+query+". Not returning Ners.") nersNotForMention.map(_._2.text) } else { val sortedNersWithOffset: Seq[(String, Int)] = nersNotForMention.map(nm => { val mention = nm._2 val distance = computeDistanceToOffsets(mention, queryOffsets) (nm._2.text, distance) }).sortBy(_._2) // println("ners with distance = "+ sortedNersWithOffset.mkString(", ")) val nersByOffsetDistance = sortedNersWithOffset.map(_._1.toLowerCase).distinct nersByOffsetDistance } // println("dedup ners = "+nersByOffsetDistance) // var fullTextSeq = new ListBuffer[String] // fullTextSeq += query.fullText val names = ((normNamesSet ++ (nersForMention.map(ner => normalizeText(ner.text)))) - normalizedQuery).toSeq // println("all coref: " + query.queryId + ": " + query.name + ":" + corefChains.mkString("\\t")) // println("coref alt: " + query.queryId + ": " + query.name + ":" + altNamesFromCoref.mkString("\\t")) // println("NERs: " + query.queryId + ": "+ query.name + ":" + nersForMention.mkString("\\t")) // println("contextual NERs: " + query.queryId + ": "+ query.name + ":" + nersInSentence.mkString("\\t")) // println("altNames " + query.queryId + ": "+ query.name + ":" + names.mkString("\\t")) QueryContext(altNames = names, contextNers = nersInSentence.map(_.text), allNersSorted = nersByOffsetDistance) } def computeDistanceToOffsets(mention: NlpData.NlpXmlMention, queryOffsets: Seq[Int]): Int = { val cb = mention.charBegin val ce = mention.charEnd val distance = queryOffsets.map(offset => math.min(math.abs(cb - offset), math.abs(ce - offset))).min distance } }
daltonj/KbBridge
src/main/scala/edu/umass/ciir/kbbridge/nlp/NlpQueryContextBuilder.scala
Scala
apache-2.0
8,906
package chapter07 import java.util.Scanner object MatchImplementation { def main(args: Array[String]): Unit = { val scanner = new Scanner(System.in) println("Enter the choice (salt, chips, eggs) : ") val userinput = scanner.next() userinput match { case "salt" => println("pepper") case "chips" => println("salsa") case "eggs" => println("bacon") case _ => println("huh?") } val sidedish = userinput match { case "salt" => "water" case "chips" => "juice" case "eggs" => "tea" case _ => "what?" } println(sidedish) } }
aakashmathai/ScalaTutorial
src/main/scala/chapter07/MatchImplementation.scala
Scala
apache-2.0
622
import akka.actor.ActorSystem import component.chat.actor.Chat import api.actor.SprayServiceActor import scaldi.Module import scaldi.akka.AkkaInjectable import spray.can.server.ServerSettings package object api { object url { object static { private[api] val root = "/" private[api] val signIn = "/signin" private[api] val signUp = "/signUp" } } val ApiRoot = "api" object scheme { private[api] val https = "https" private[api] val http = "http" } private[api] val resourceDir = "theme" class HttpModule extends Module { binding to ServerSettings(inject [ActorSystem]) binding toProvider new SprayServiceActor() binding toProvider new Chat() binding identifiedBy 'sprayActor to { implicit val system = inject [ActorSystem] AkkaInjectable.injectActorRef[SprayServiceActor]("spray-service") } } }
onurzdg/spray-app
src/main/scala/api/package.scala
Scala
apache-2.0
885
package play.api.libs.iteratee import play.api.libs.iteratee.Execution.Implicits.{ defaultExecutionContext => dec } import play.api.libs.iteratee.internal.{ eagerFuture, executeFuture } import scala.concurrent.{ ExecutionContext, Future, Promise } import scala.util.{ Try, Success, Failure } import scala.language.reflectiveCalls /** * A producer which pushes input to an [[play.api.libs.iteratee.Iteratee]]. * * @define paramEcSingle @param ec The context to execute the supplied function with. The context is prepared on the calling thread before being used. * @define paramEcMultiple @param ec The context to execute the supplied functions with. The context is prepared on the calling thread before being used. */ trait Enumerator[E] { parent => /** * Attaches this Enumerator to an [[play.api.libs.iteratee.Iteratee]], driving the * Iteratee to (asynchronously) consume the input. The Iteratee may enter its * [[play.api.libs.iteratee.Done]] or [[play.api.libs.iteratee.Error]] * state, or it may be left in a [[play.api.libs.iteratee.Cont]] state (allowing it * to consume more input after that sent by the enumerator). * * If the Iteratee reaches a [[play.api.libs.iteratee.Done]] state, it will * contain a computed result and the remaining (unconsumed) input. */ def apply[A](i: Iteratee[E, A]): Future[Iteratee[E, A]] /** * Alias for `apply`, produces input driving the given [[play.api.libs.iteratee.Iteratee]] * to consume it. */ def |>>[A](i: Iteratee[E, A]): Future[Iteratee[E, A]] = apply(i) /** * Attaches this Enumerator to an [[play.api.libs.iteratee.Iteratee]], driving the * Iteratee to (asynchronously) consume the enumerator's input. If the Iteratee does not * reach a [[play.api.libs.iteratee.Done]] or [[play.api.libs.iteratee.Error]] * state when the Enumerator finishes, this method forces one of those states by * feeding `Input.EOF` to the Iteratee. * * If the iteratee is left in a [[play.api.libs.iteratee.Done]] * state then the promise is completed with the iteratee's result. * If the iteratee is left in an [[play.api.libs.iteratee.Error]] state, then the * promise is completed with a [[java.lang.RuntimeException]] containing the * iteratee's error message. * * Unlike `apply` or `|>>`, this method does not allow you to access the * unconsumed input. */ def |>>>[A](i: Iteratee[E, A]): Future[A] = apply(i).flatMap(_.run)(dec) /** * Alias for `|>>>`; drives the iteratee to consume the enumerator's * input, adding an Input.EOF at the end of the input. Returns either a result * or an exception. */ def run[A](i: Iteratee[E, A]): Future[A] = |>>>(i) /** * A variation on `apply` or `|>>` which returns the state of the iteratee rather * than the iteratee itself. This can make your code a little shorter. */ def |>>|[A](i: Iteratee[E, A]): Future[Step[E, A]] = apply(i).flatMap(_.unflatten)(dec) /** * Sequentially combine this Enumerator with another Enumerator. The resulting enumerator * will produce both input streams, this one first, then the other. * Note: the current implementation will break if the first enumerator * produces an Input.EOF. */ def andThen(e: Enumerator[E]): Enumerator[E] = new Enumerator[E] { def apply[A](i: Iteratee[E, A]): Future[Iteratee[E, A]] = parent.apply(i).flatMap(e.apply)(dec) //bad implementation, should remove Input.EOF in the end of first } def interleave[B >: E](other: Enumerator[B]): Enumerator[B] = Enumerator.interleave(this, other) /** * Alias for interleave */ def >-[B >: E](other: Enumerator[B]): Enumerator[B] = interleave(other) /** * Compose this Enumerator with an Enumeratee. Alias for through */ def &>[To](enumeratee: Enumeratee[E, To]): Enumerator[To] = new Enumerator[To] { def apply[A](i: Iteratee[To, A]): Future[Iteratee[To, A]] = { val transformed = enumeratee.applyOn(i) val xx = parent |>> transformed xx.flatMap(_.run)(dec) } } /** * Creates an Enumerator which calls the given callback when its final input has been consumed. * * @param callback The callback to call * $paramEcSingle */ def onDoneEnumerating(callback: => Unit)(implicit ec: ExecutionContext) = new Enumerator[E] { val pec = ec.prepare() def apply[A](it: Iteratee[E, A]): Future[Iteratee[E, A]] = parent.apply(it).map { a => callback; a }(pec) } /** * Compose this Enumerator with an Enumeratee */ def through[To](enumeratee: Enumeratee[E, To]): Enumerator[To] = &>(enumeratee) /** * Alias for `andThen` */ def >>>(e: Enumerator[E]): Enumerator[E] = andThen(e) /** * maps the given function f onto parent Enumerator * @param f function to map * $paramEcSingle * @return enumerator */ def map[U](f: E => U)(implicit ec: ExecutionContext): Enumerator[U] = parent &> Enumeratee.map[E](f)(ec) /** * Creates an Enumerator, based on this one, with each input transformed by the given function. * * @param f Used to transform the input. * $paramEcSingle */ def mapInput[U](f: Input[E] => Input[U])(implicit ec: ExecutionContext): Enumerator[U] = parent &> Enumeratee.mapInput[E](f)(ec) /** * flatmaps the given function f onto parent Enumerator * @param f function to map * $paramEcSingle * @return enumerator */ def flatMap[U](f: E => Enumerator[U])(implicit ec: ExecutionContext): Enumerator[U] = { val pec = ec.prepare() import Execution.Implicits.{ defaultExecutionContext => ec } // Shadow ec to make this the only implicit EC in scope new Enumerator[U] { def apply[A](iteratee: Iteratee[U, A]): Future[Iteratee[U, A]] = { val folder = Iteratee.fold2[E, Iteratee[U, A]](iteratee) { (it, e) => for { en <- Future(f(e))(pec) newIt <- en(it) done <- Iteratee.isDoneOrError(newIt) } yield ((newIt, done)) }(dec) parent(folder).flatMap(_.run) } } } } /** * Enumerator is the source that pushes input into a given iteratee. * It enumerates some input into the iteratee and eventually returns the new state of that iteratee. * * @define paramEcSingle @param ec The context to execute the supplied function with. The context is prepared on the calling thread before being used. * @define paramEcMultiple @param ec The context to execute the supplied functions with. The context is prepared on the calling thread before being used. */ object Enumerator { def flatten[E](eventuallyEnum: Future[Enumerator[E]]): Enumerator[E] = new Enumerator[E] { def apply[A](it: Iteratee[E, A]): Future[Iteratee[E, A]] = eventuallyEnum.flatMap(_.apply(it))(dec) } /** * Creates an enumerator which produces the one supplied * input and nothing else. This enumerator will NOT * automatically produce Input.EOF after the given input. */ def enumInput[E](e: Input[E]) = new Enumerator[E] { def apply[A](i: Iteratee[E, A]): Future[Iteratee[E, A]] = i.fold { case Step.Cont(k) => eagerFuture(k(e)) case _ => Future.successful(i) }(dec) } /** * Interleave multiple enumerators together. * * Interleaving is done based on whichever enumerator next has input ready, if multiple have input ready, the order * is undefined. */ def interleave[E](e1: Enumerator[E], es: Enumerator[E]*): Enumerator[E] = interleave(e1 +: es) /** * Interleave multiple enumerators together. * * Interleaving is done based on whichever enumerator next has input ready, if multiple have input ready, the order * is undefined. */ def interleave[E](es: Seq[Enumerator[E]]): Enumerator[E] = new Enumerator[E] { import scala.concurrent.stm._ def apply[A](it: Iteratee[E, A]): Future[Iteratee[E, A]] = { val iter: Ref[Iteratee[E, A]] = Ref(it) val attending: Ref[Option[Seq[Boolean]]] = Ref(Some(es.map(_ => true))) val result = Promise[Iteratee[E, A]]() def redeemResultIfNotYet(r: Iteratee[E, A]) { if (attending.single.transformIfDefined { case Some(_) => None }) result.success(r) } def iteratee[EE <: E](f: Seq[Boolean] => Seq[Boolean]): Iteratee[EE, Unit] = { def step(in: Input[EE]): Iteratee[EE, Unit] = { val p = Promise[Iteratee[E, A]]() val i = iter.single.swap(Iteratee.flatten(p.future)) in match { case Input.El(_) | Input.Empty => val nextI = i.fold { case Step.Cont(k) => val n = k(in) n.fold { case Step.Cont(kk) => p.success(Cont(kk)) Future.successful(Cont(step)) case _ => p.success(n) Future.successful(Done((), Input.Empty: Input[EE])) }(dec) case _ => p.success(i) Future.successful(Done((), Input.Empty: Input[EE])) }(dec) Iteratee.flatten(nextI) case Input.EOF => { if (attending.single.transformAndGet { _.map(f) }.forall(_ == false)) { p.complete(Try(Iteratee.flatten(i.feed(Input.EOF)))) } else { p.success(i) } Done((), Input.Empty) } } } Cont(step) } val ps = es.zipWithIndex.map { case (e, index) => e |>> iteratee[E](_.patch(index, Seq(true), 1)) } .map(_.flatMap(_.pureFold(any => ())(dec))) Future.sequence(ps).onComplete { case Success(_) => redeemResultIfNotYet(iter.single()) case Failure(e) => result.failure(e) } result.future } } /** * Interleave two enumerators together. * * Interleaving is done based on whichever enumerator next has input ready, if both have input ready, the order is * undefined. */ def interleave[E1, E2 >: E1](e1: Enumerator[E1], e2: Enumerator[E2]): Enumerator[E2] = new Enumerator[E2] { import scala.concurrent.stm._ def apply[A](it: Iteratee[E2, A]): Future[Iteratee[E2, A]] = { val iter: Ref[Iteratee[E2, A]] = Ref(it) val attending: Ref[Option[(Boolean, Boolean)]] = Ref(Some(true, true)) val result = Promise[Iteratee[E2, A]]() def redeemResultIfNotYet(r: Iteratee[E2, A]) { if (attending.single.transformIfDefined { case Some(_) => None }) result.success(r) } def iteratee[EE <: E2](f: ((Boolean, Boolean)) => (Boolean, Boolean)): Iteratee[EE, Unit] = { def step(in: Input[EE]): Iteratee[EE, Unit] = { val p = Promise[Iteratee[E2, A]]() val i = iter.single.swap(Iteratee.flatten(p.future)) in match { case Input.El(_) | Input.Empty => val nextI = i.fold { case Step.Cont(k) => val n = k(in) n.fold { case Step.Cont(kk) => p.success(Cont(kk)) Future.successful(Cont(step)) case _ => p.success(n) Future.successful(Done((), Input.Empty: Input[EE])) }(dec) case _ => p.success(i) Future.successful(Done((), Input.Empty: Input[EE])) }(dec) Iteratee.flatten(nextI) case Input.EOF => { if (attending.single.transformAndGet { _.map(f) } == Some((false, false))) { p.complete(Try(Iteratee.flatten(i.feed(Input.EOF)))) } else { p.success(i) } Done((), Input.Empty) } } } Cont(step) } val itE1 = iteratee[E1] { case (l, r) => (false, r) } val itE2 = iteratee[E2] { case (l, r) => (l, false) } val r1 = e1 |>>| itE1 val r2 = e2 |>>| itE2 r1.flatMap(_ => r2).onComplete { case Success(_) => redeemResultIfNotYet(iter.single()) case Failure(e) => result.failure(e) } result.future } } trait Pushee[E] { def push(item: E): Boolean def close() } /** * Like [[play.api.libs.iteratee.Enumerator.unfold]], but allows the unfolding to be done asynchronously. * * @param s The value to unfold * @param f The unfolding function. This will take the value, and return a future for some tuple of the next value * to unfold and the next input, or none if the value is completely unfolded. * $paramEcSingle */ def unfoldM[S, E](s: S)(f: S => Future[Option[(S, E)]])(implicit ec: ExecutionContext): Enumerator[E] = checkContinue1(s)(new TreatCont1[E, S] { val pec = ec.prepare() def apply[A](loop: (Iteratee[E, A], S) => Future[Iteratee[E, A]], s: S, k: Input[E] => Iteratee[E, A]): Future[Iteratee[E, A]] = { executeFuture(f(s))(pec).flatMap { case Some((newS, e)) => loop(k(Input.El(e)), newS) case None => Future.successful(Cont(k)) }(dec) } }) /** * Unfold a value of type S into input for an enumerator. * * For example, the following would enumerate the elements of a list, implementing the same behavior as * Enumerator.enumerate: * * {{{ * Enumerator.sequence[List[Int], Int]{ list => * list.headOption.map(input => list.tail -> input) * } * }}} * * @param s The value to unfold * @param f The unfolding function. This will take the value, and return some tuple of the next value to unfold and * the next input, or none if the value is completely unfolded. * $paramEcSingle */ def unfold[S, E](s: S)(f: S => Option[(S, E)])(implicit ec: ExecutionContext): Enumerator[E] = checkContinue1(s)(new TreatCont1[E, S] { val pec = ec.prepare() def apply[A](loop: (Iteratee[E, A], S) => Future[Iteratee[E, A]], s: S, k: Input[E] => Iteratee[E, A]): Future[Iteratee[E, A]] = Future(f(s))(pec).flatMap { case Some((s, e)) => loop(k(Input.El(e)), s) case None => Future.successful(Cont(k)) }(dec) }) /** * Repeat the given input function indefinitely. * * @param e The input function. * $paramEcSingle */ def repeat[E](e: => E)(implicit ec: ExecutionContext): Enumerator[E] = checkContinue0(new TreatCont0[E] { val pec = ec.prepare() def apply[A](loop: Iteratee[E, A] => Future[Iteratee[E, A]], k: Input[E] => Iteratee[E, A]) = Future(e)(pec).flatMap(ee => loop(k(Input.El(ee))))(dec) }) /** * Like [[play.api.libs.iteratee.Enumerator.repeat]], but allows repeated values to be asynchronously fetched. * * @param e The input function * $paramEcSingle */ def repeatM[E](e: => Future[E])(implicit ec: ExecutionContext): Enumerator[E] = checkContinue0(new TreatCont0[E] { val pec = ec.prepare() def apply[A](loop: Iteratee[E, A] => Future[Iteratee[E, A]], k: Input[E] => Iteratee[E, A]) = executeFuture(e)(pec).flatMap(ee => loop(k(Input.El(ee))))(dec) }) /** * Like [[play.api.libs.iteratee.Enumerator.repeatM]], but the callback returns an Option, which allows the stream * to be eventually terminated by returning None. * * @param e The input function. Returns a future eventually redeemed with Some value if there is input to pass, or a * future eventually redeemed with None if the end of the stream has been reached. */ def generateM[E](e: => Future[Option[E]])(implicit ec: ExecutionContext): Enumerator[E] = checkContinue0(new TreatCont0[E] { val pec = ec.prepare() def apply[A](loop: Iteratee[E, A] => Future[Iteratee[E, A]], k: Input[E] => Iteratee[E, A]) = executeFuture(e)(pec).flatMap { case Some(e) => loop(k(Input.El(e))) case None => Future.successful(Cont(k)) }(dec) }) trait TreatCont0[E] { def apply[A](loop: Iteratee[E, A] => Future[Iteratee[E, A]], k: Input[E] => Iteratee[E, A]): Future[Iteratee[E, A]] } def checkContinue0[E](inner: TreatCont0[E]) = new Enumerator[E] { def apply[A](it: Iteratee[E, A]): Future[Iteratee[E, A]] = { def step(it: Iteratee[E, A]): Future[Iteratee[E, A]] = it.fold { case Step.Done(a, e) => Future.successful(Done(a, e)) case Step.Cont(k) => inner[A](step, k) case Step.Error(msg, e) => Future.successful(Error(msg, e)) }(dec) step(it) } } trait TreatCont1[E, S] { def apply[A](loop: (Iteratee[E, A], S) => Future[Iteratee[E, A]], s: S, k: Input[E] => Iteratee[E, A]): Future[Iteratee[E, A]] } def checkContinue1[E, S](s: S)(inner: TreatCont1[E, S]) = new Enumerator[E] { def apply[A](it: Iteratee[E, A]): Future[Iteratee[E, A]] = { def step(it: Iteratee[E, A], state: S): Future[Iteratee[E, A]] = it.fold { case Step.Done(a, e) => Future.successful(Done(a, e)) case Step.Cont(k) => inner[A](step, state, k) case Step.Error(msg, e) => Future.successful(Error(msg, e)) }(dec) step(it, s) } } /** * Like [[play.api.libs.iteratee.Enumerator.generateM]], but `retriever` accepts a boolean * value that is `true` on its first call only. * * @param retriever The input function. Returns a future eventually redeemed with Some value if there is input to pass, or a * future eventually redeemed with None if the end of the stream has been reached. * @param onComplete Called when the end of the stream is reached. * @param onError FIXME: Never called. * $paramEcMultiple */ def fromCallback1[E](retriever: Boolean => Future[Option[E]], onComplete: () => Unit = () => (), onError: (String, Input[E]) => Unit = (_: String, _: Input[E]) => ())(implicit ec: ExecutionContext) = new Enumerator[E] { val pec = ec.prepare() def apply[A](it: Iteratee[E, A]): Future[Iteratee[E, A]] = { var iterateeP = Promise[Iteratee[E, A]]() def step(it: Iteratee[E, A], initial: Boolean = false) { val next = it.fold { case Step.Cont(k) => { executeFuture(retriever(initial))(pec).map { case None => { val remainingIteratee = k(Input.EOF) iterateeP.success(remainingIteratee) None } case Some(read) => { val nextIteratee = k(Input.El(read)) Some(nextIteratee) } }(dec) } case _ => { iterateeP.success(it); Future.successful(None) } }(dec) next.onComplete { case Success(Some(i)) => step(i) case Success(None) => Future(onComplete())(pec) case Failure(e) => iterateeP.failure(e) }(dec) } step(it, true) iterateeP.future } } /** * Create an enumerator from the given input stream. * * This enumerator will block on reading the input stream, in the default iteratee thread pool. Care must therefore * be taken to ensure that this isn't a slow stream. If using this with slow input streams, consider setting the * value of iteratee-threadpool-size to a value appropriate for handling the blocking. * * @param input The input stream * @param chunkSize The size of chunks to read from the stream. */ def fromStream(input: java.io.InputStream, chunkSize: Int = 1024 * 8)(implicit ec: ExecutionContext): Enumerator[Array[Byte]] = { implicit val pec = ec.prepare() generateM({ val buffer = new Array[Byte](chunkSize) val chunk = input.read(buffer) match { case -1 => None case read => val input = new Array[Byte](read) System.arraycopy(buffer, 0, input, 0, read) Some(input) } Future.successful(chunk) })(pec).onDoneEnumerating(input.close)(pec) } /** * Create an enumerator from the given input stream. * * Note that this enumerator will block when it reads from the file. * * @param file The file to create the enumerator from. * @param chunkSize The size of chunks to read from the file. */ def fromFile(file: java.io.File, chunkSize: Int = 1024 * 8)(implicit ec: ExecutionContext): Enumerator[Array[Byte]] = { fromStream(new java.io.FileInputStream(file), chunkSize)(ec) } /** * Create an Enumerator of bytes with an OutputStream. * * Note that calls to write will not block, so if the iteratee that is being fed to is slow to consume the input, the * OutputStream will not push back. This means it should not be used with large streams since there is a risk of * running out of memory. * * @param a A callback that provides the output stream when this enumerator is written to an iteratee. * $paramEcSingle */ def outputStream(a: java.io.OutputStream => Unit)(implicit ec: ExecutionContext): Enumerator[Array[Byte]] = { Concurrent.unicast[Array[Byte]] { channel => val outputStream = new java.io.OutputStream() { override def close() { channel.end() } override def flush() {} override def write(value: Int) { channel.push(Array(value.toByte)) } override def write(buffer: Array[Byte]) { write(buffer, 0, buffer.length) } override def write(buffer: Array[Byte], start: Int, count: Int) { channel.push(buffer.slice(start, start + count)) } } a(outputStream) }(ec) } /** * An enumerator that produces EOF and nothing else. */ def eof[A] = enumInput[A](Input.EOF) /** * Create an Enumerator from a set of values * * Example: * {{{ * val enumerator: Enumerator[String] = Enumerator("kiki", "foo", "bar") * }}} */ def apply[E](in: E*): Enumerator[E] = in.length match { case 0 => Enumerator.empty case 1 => new Enumerator[E] { def apply[A](i: Iteratee[E, A]): Future[Iteratee[E, A]] = i.pureFoldNoEC { case Step.Cont(k) => k(Input.El(in.head)) case _ => i } } case _ => new Enumerator[E] { def apply[A](i: Iteratee[E, A]): Future[Iteratee[E, A]] = enumerateSeq(in, i) } } /** * Create an Enumerator from any TraversableOnce like collection of elements. * * Example of an iterator of lines of a file : * {{{ * val enumerator: Enumerator[String] = Enumerator( scala.io.Source.fromFile("myfile.txt").getLines ) * }}} */ def enumerate[E](traversable: TraversableOnce[E])(implicit ctx: scala.concurrent.ExecutionContext): Enumerator[E] = { val it = traversable.toIterator Enumerator.unfoldM[scala.collection.Iterator[E], E](it: scala.collection.Iterator[E])({ currentIt => if (currentIt.hasNext) Future[Option[(scala.collection.Iterator[E], E)]]({ val next = currentIt.next Some((currentIt -> next)) })(ctx) else Future.successful[Option[(scala.collection.Iterator[E], E)]]({ None }) })(dec) } /** * An empty enumerator */ def empty[E]: Enumerator[E] = new Enumerator[E] { def apply[A](i: Iteratee[E, A]) = Future.successful(i) } private def enumerateSeq[E, A]: (Seq[E], Iteratee[E, A]) => Future[Iteratee[E, A]] = { (l, i) => l.foldLeft(Future.successful(i))((i, e) => i.flatMap(it => it.pureFold { case Step.Cont(k) => k(Input.El(e)) case _ => it }(dec))(dec)) } private[iteratee] def enumerateSeq1[E](s: Seq[E]): Enumerator[E] = checkContinue1(s)(new TreatCont1[E, Seq[E]] { def apply[A](loop: (Iteratee[E, A], Seq[E]) => Future[Iteratee[E, A]], s: Seq[E], k: Input[E] => Iteratee[E, A]): Future[Iteratee[E, A]] = if (!s.isEmpty) loop(k(Input.El(s.head)), s.tail) else Future.successful(Cont(k)) }) private[iteratee] def enumerateSeq2[E](s: Seq[Input[E]]): Enumerator[E] = checkContinue1(s)(new TreatCont1[E, Seq[Input[E]]] { def apply[A](loop: (Iteratee[E, A], Seq[Input[E]]) => Future[Iteratee[E, A]], s: Seq[Input[E]], k: Input[E] => Iteratee[E, A]): Future[Iteratee[E, A]] = if (!s.isEmpty) loop(k(s.head), s.tail) else Future.successful(Cont(k)) }) }
michaelahlers/team-awesome-wedding
vendor/play-2.2.1/framework/src/iteratees/src/main/scala/play/api/libs/iteratee/Enumerator.scala
Scala
mit
24,302
package collins.util import collins.util.config.Feature import collins.models.Asset import collins.models.AssetMeta import collins.models.AssetMetaValue import collins.models.IpAddresses import collins.models.IpmiInfo import collins.models.State import collins.models.Status import collins.models.conversions.dateToTimestamp import java.util.Date case class AssetStateMachine(asset: Asset) { def canDecommission(): Boolean = asset.isCancelled || asset.isDecommissioned || asset.isMaintenance || asset.isUnallocated def decommission(): Option[Asset] = if (canDecommission) { val sid = State.Terminated.map(_.id).getOrElse(0) // FIXME change to partial update val newAsset = asset.copy(statusId = Status.Decommissioned.get.id, deleted = Some(new Date().asTimestamp), stateId = sid) val res = Asset.update(newAsset) match { case 1 => Some(newAsset) case n => None } if (Feature.deleteIpmiOnDecommission) { IpmiInfo.deleteByAsset(asset) } if (Feature.deleteIpAddressOnDecommission) { IpAddresses.deleteByAsset(asset) } if (Feature.deleteMetaOnDecommission) { AssetMetaValue.deleteByAsset(asset) } else { if (Feature.useWhiteListOnRepurpose) { if (Feature.keepSomeMetaOnRepurpose.size > 0) { val keepAttributes: Set[Long] = Feature.keepSomeMetaOnRepurpose.map(_.id) val allAttributes: Set[Long] = AssetMetaValue.findByAsset(asset).map(_.getMetaId()).toSet val deleteAttributes = allAttributes -- keepAttributes if (deleteAttributes.size > 0) { AssetMetaValue.deleteByAssetAndMetaId(asset, deleteAttributes) } } } else { if (Feature.deleteSomeMetaOnRepurpose.size > 0) { val deleteAttributes: Set[Long] = Feature.deleteSomeMetaOnRepurpose.map(_.id) AssetMetaValue.deleteByAssetAndMetaId(asset, deleteAttributes) } } } res } else { throw new Exception("Asset must be Unallocated, Cancelled or Decommissioned") } }
box/collins
app/collins/util/StateMachines.scala
Scala
apache-2.0
2,043
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 Andre White. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.truthencode.ddo.support.requisite trait DefaultRequirementSort { def alphaSortKey: String }
adarro/ddo-calc
subprojects/common/ddo-core/src/main/scala/io/truthencode/ddo/support/requisite/DefaultRequirementSort.scala
Scala
apache-2.0
750
package PaperCode.Sec4OA import PaperCode.Common object Code30 extends Common { //BEGIN_BASE_OA_PARSER_BAD trait ExprOAParser[E] { lexical.delimiters += "+" val pLit: ExprAlg[E] => Parser[E] = alg => numericLit ^^ { x => alg.lit(x.toInt) } val pAdd: ExprAlg[E] => Parser[E] = alg => { val p = pExpr(alg) p ~ ("+" ~> p) ^^ { case e1 ~ e2 => alg.add(e1, e2) } } val pExpr: ExprAlg[E] => Parser[E] = alg => pLit(alg) ||| pAdd(alg) } //END_BASE_OA_PARSER_BAD } object Code3 extends Common { //BEGIN_BASE_OA_PARSER trait ExprOAParser[E] { lexical.delimiters += "+" val alg: ExprAlg[E] val pLit: Parser[E] = numericLit ^^ { x => alg.lit(x.toInt) } val pAdd: Parser[E] = pE ~ ("+" ~> pE) ^^ { case e1 ~ e2 => alg.add(e1, e2) } val pExpr: Parser[E] = pLit ||| pAdd val pE: Parser[E] = pExpr } //END_BASE_OA_PARSER //BEGIN_EXT_OA_PARSER trait VarExprOAParser[E] extends ExprOAParser[E] { override val alg: VarExprAlg[E] val pVar: Parser[E] = ident ^^ alg.varE val pVarExpr: Parser[E] = pExpr ||| pVar override val pE: Parser[E] = pVarExpr } //END_EXT_OA_PARSER //BEGIN_EXT_OA_PARSER_CLIENT val p = new VarExprOAParser[String] { override val alg = new VarExprPrint {} } val r = parse(p.pE)("1 + x") // "(1 + x)" //END_EXT_OA_PARSER_CLIENT def main(args: Array[String]): Unit = { println(r) } }
hy-zhang/parser
Scala/Parser/src/PaperCode/Sec4OA/Code3.scala
Scala
bsd-3-clause
1,339
/* * Copyright 2016 The BigDL Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intel.analytics.bigdl.dllib.keras.layers import com.intel.analytics.bigdl.dllib.nn.ConvLSTMPeephole3D import com.intel.analytics.bigdl.dllib.tensor.Tensor import com.intel.analytics.bigdl.dllib.utils.Shape import com.intel.analytics.bigdl.dllib.keras.ZooSpecHelper import com.intel.analytics.bigdl.dllib.keras.serializer.ModuleSerializationTest class ConvLSTM3DSpec extends ZooSpecHelper { "ConvLSTM3D" should "forward and backward properly with correct output shape" in { val layer = ConvLSTM3D[Float](10, 3, inputShape = Shape(5, 4, 8, 10, 12), borderMode = "same") layer.build(Shape(-1, 5, 4, 8, 10, 12)) val input = Tensor[Float](Array(3, 5, 4, 8, 10, 12)).rand() val output = layer.forward(input) val expectedOutputShape = layer.getOutputShape().toSingle().toArray val actualOutputShape = output.size() require(expectedOutputShape.drop(1).sameElements(actualOutputShape.drop(1))) val gradInput = layer.backward(input, output) } "ConvLSTM3D return sequences and go backwards" should "forward and backward " + "properly with correct output shape" in { val layer = ConvLSTM3D[Float](12, 4, returnSequences = true, goBackwards = true, borderMode = "same", inputShape = Shape(20, 3, 12, 12, 12)) layer.build(Shape(-1, 20, 3, 12, 12, 12)) val input = Tensor[Float](Array(4, 20, 3, 12, 12, 12)).rand() val output = layer.forward(input) val expectedOutputShape = layer.getOutputShape().toSingle().toArray val actualOutputShape = output.size() require(expectedOutputShape.drop(1).sameElements(actualOutputShape.drop(1))) val gradInput = layer.backward(input, output) } "ConvLSTM3D with same padding" should "be the same as BigDL" in { val blayer = com.intel.analytics.bigdl.dllib.nn.Recurrent[Float]() .add(ConvLSTMPeephole3D[Float](4, 4, 2, 2, withPeephole = false)) val zlayer = ConvLSTM3D[Float](4, 2, returnSequences = true, borderMode = "same", inputShape = Shape(12, 4, 8, 8, 8)) zlayer.build(Shape(-1, 12, 4, 8, 8, 8)) val input = Tensor[Float](Array(4, 12, 4, 8, 8, 8)).rand() compareOutputAndGradInputSetWeights(blayer, zlayer, input) } "ConvLSTM3D with valid padding" should "work" in { val zlayer = ConvLSTM3D[Float](4, 2, returnSequences = true, borderMode = "valid", inputShape = Shape(12, 4, 8, 8, 8)) zlayer.build(Shape(-1, 12, 4, 8, 8, 8)) val input = Tensor[Float](Array(4, 12, 4, 8, 8, 8)).rand() zlayer.forward(input) } } class ConvLSTM3DSerialTest extends ModuleSerializationTest { override def test(): Unit = { val layer = ConvLSTM3D[Float](10, 3, inputShape = Shape(5, 4, 8, 10, 12)) layer.build(Shape(2, 5, 4, 8, 10, 12)) val input = Tensor[Float](2, 5, 4, 8, 10, 12).rand() runSerializationTest(layer, input) } }
intel-analytics/BigDL
scala/dllib/src/test/scala/com/intel/analytics/bigdl/dllib/keras/layers/ConvLSTM3DSpec.scala
Scala
apache-2.0
3,420
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.catalyst.csv import java.io.InputStream import scala.util.control.NonFatal import com.univocity.parsers.csv.CsvParser import org.apache.spark.SparkUpgradeException import org.apache.spark.internal.Logging import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions.{ExprUtils, GenericInternalRow} import org.apache.spark.sql.catalyst.util._ import org.apache.spark.sql.catalyst.util.LegacyDateFormats.FAST_DATE_FORMAT import org.apache.spark.sql.sources.Filter import org.apache.spark.sql.types._ import org.apache.spark.unsafe.types.UTF8String /** * Constructs a parser for a given schema that translates CSV data to an [[InternalRow]]. * * @param dataSchema The CSV data schema that is specified by the user, or inferred from underlying * data files. * @param requiredSchema The schema of the data that should be output for each row. This should be a * subset of the columns in dataSchema. * @param options Configuration options for a CSV parser. * @param filters The pushdown filters that should be applied to converted values. */ class UnivocityParser( dataSchema: StructType, requiredSchema: StructType, val options: CSVOptions, filters: Seq[Filter]) extends Logging { require(requiredSchema.toSet.subsetOf(dataSchema.toSet), s"requiredSchema (${requiredSchema.catalogString}) should be the subset of " + s"dataSchema (${dataSchema.catalogString}).") def this(dataSchema: StructType, requiredSchema: StructType, options: CSVOptions) = { this(dataSchema, requiredSchema, options, Seq.empty) } def this(schema: StructType, options: CSVOptions) = this(schema, schema, options) // A `ValueConverter` is responsible for converting the given value to a desired type. private type ValueConverter = String => Any // This index is used to reorder parsed tokens private val tokenIndexArr = requiredSchema.map(f => java.lang.Integer.valueOf(dataSchema.indexOf(f))).toArray // When column pruning is enabled, the parser only parses the required columns based on // their positions in the data schema. private val parsedSchema = if (options.columnPruning) requiredSchema else dataSchema val tokenizer: CsvParser = { val parserSetting = options.asParserSettings // When to-be-parsed schema is shorter than the to-be-read data schema, we let Univocity CSV // parser select a sequence of fields for reading by their positions. if (parsedSchema.length < dataSchema.length) { parserSetting.selectIndexes(tokenIndexArr: _*) } new CsvParser(parserSetting) } // Pre-allocated Some to avoid the overhead of building Some per each-row. private val requiredRow = Some(new GenericInternalRow(requiredSchema.length)) // Pre-allocated empty sequence returned when the parsed row cannot pass filters. // We preallocate it avoid unnecessary allocations. private val noRows = None private lazy val timestampFormatter = TimestampFormatter( options.timestampFormat, options.zoneId, options.locale, legacyFormat = FAST_DATE_FORMAT, isParsing = true) private lazy val dateFormatter = DateFormatter( options.dateFormat, options.zoneId, options.locale, legacyFormat = FAST_DATE_FORMAT, isParsing = true) private val csvFilters = new CSVFilters(filters, requiredSchema) // Retrieve the raw record string. private def getCurrentInput: UTF8String = { val currentContent = tokenizer.getContext.currentParsedContent() if (currentContent == null) null else UTF8String.fromString(currentContent.stripLineEnd) } // This parser first picks some tokens from the input tokens, according to the required schema, // then parse these tokens and put the values in a row, with the order specified by the required // schema. // // For example, let's say there is CSV data as below: // // a,b,c // 1,2,A // // So the CSV data schema is: ["a", "b", "c"] // And let's say the required schema is: ["c", "b"] // // with the input tokens, // // input tokens - [1, 2, "A"] // // Each input token is placed in each output row's position by mapping these. In this case, // // output row - ["A", 2] private val valueConverters: Array[ValueConverter] = { requiredSchema.map(f => makeConverter(f.name, f.dataType, f.nullable)).toArray } private val decimalParser = ExprUtils.getDecimalParser(options.locale) /** * Create a converter which converts the string value to a value according to a desired type. * Currently, we do not support complex types (`ArrayType`, `MapType`, `StructType`). * * For other nullable types, returns null if it is null or equals to the value specified * in `nullValue` option. */ def makeConverter( name: String, dataType: DataType, nullable: Boolean = true): ValueConverter = dataType match { case _: ByteType => (d: String) => nullSafeDatum(d, name, nullable, options)(_.toByte) case _: ShortType => (d: String) => nullSafeDatum(d, name, nullable, options)(_.toShort) case _: IntegerType => (d: String) => nullSafeDatum(d, name, nullable, options)(_.toInt) case _: LongType => (d: String) => nullSafeDatum(d, name, nullable, options)(_.toLong) case _: FloatType => (d: String) => nullSafeDatum(d, name, nullable, options) { case options.nanValue => Float.NaN case options.negativeInf => Float.NegativeInfinity case options.positiveInf => Float.PositiveInfinity case datum => datum.toFloat } case _: DoubleType => (d: String) => nullSafeDatum(d, name, nullable, options) { case options.nanValue => Double.NaN case options.negativeInf => Double.NegativeInfinity case options.positiveInf => Double.PositiveInfinity case datum => datum.toDouble } case _: BooleanType => (d: String) => nullSafeDatum(d, name, nullable, options)(_.toBoolean) case dt: DecimalType => (d: String) => nullSafeDatum(d, name, nullable, options) { datum => Decimal(decimalParser(datum), dt.precision, dt.scale) } case _: TimestampType => (d: String) => nullSafeDatum(d, name, nullable, options) { datum => try { timestampFormatter.parse(datum) } catch { case NonFatal(e) => // If fails to parse, then tries the way used in 2.0 and 1.x for backwards // compatibility. val str = DateTimeUtils.cleanLegacyTimestampStr(UTF8String.fromString(datum)) DateTimeUtils.stringToTimestamp(str, options.zoneId).getOrElse(throw e) } } case _: DateType => (d: String) => nullSafeDatum(d, name, nullable, options) { datum => try { dateFormatter.parse(datum) } catch { case NonFatal(e) => // If fails to parse, then tries the way used in 2.0 and 1.x for backwards // compatibility. val str = DateTimeUtils.cleanLegacyTimestampStr(UTF8String.fromString(datum)) DateTimeUtils.stringToDate(str, options.zoneId).getOrElse(throw e) } } case _: StringType => (d: String) => nullSafeDatum(d, name, nullable, options)(UTF8String.fromString) case CalendarIntervalType => (d: String) => nullSafeDatum(d, name, nullable, options) { datum => IntervalUtils.safeStringToInterval(UTF8String.fromString(datum)) } case udt: UserDefinedType[_] => makeConverter(name, udt.sqlType, nullable) // We don't actually hit this exception though, we keep it for understandability case _ => throw new RuntimeException(s"Unsupported type: ${dataType.typeName}") } private def nullSafeDatum( datum: String, name: String, nullable: Boolean, options: CSVOptions)(converter: ValueConverter): Any = { if (datum == options.nullValue || datum == null) { if (!nullable) { throw new RuntimeException(s"null value found but field $name is not nullable.") } null } else { converter.apply(datum) } } /** * Parses a single CSV string and turns it into either one resulting row or no row (if the * the record is malformed). */ val parse: String => Option[InternalRow] = { // This is intentionally a val to create a function once and reuse. if (options.columnPruning && requiredSchema.isEmpty) { // If `columnPruning` enabled and partition attributes scanned only, // `schema` gets empty. (_: String) => Some(InternalRow.empty) } else { // parse if the columnPruning is disabled or requiredSchema is nonEmpty (input: String) => convert(tokenizer.parseLine(input)) } } private val getToken = if (options.columnPruning) { (tokens: Array[String], index: Int) => tokens(index) } else { (tokens: Array[String], index: Int) => tokens(tokenIndexArr(index)) } private def convert(tokens: Array[String]): Option[InternalRow] = { if (tokens == null) { throw BadRecordException( () => getCurrentInput, () => None, new RuntimeException("Malformed CSV record")) } var badRecordException: Option[Throwable] = if (tokens.length != parsedSchema.length) { // If the number of tokens doesn't match the schema, we should treat it as a malformed record. // However, we still have chance to parse some of the tokens. It continues to parses the // tokens normally and sets null when `ArrayIndexOutOfBoundsException` occurs for missing // tokens. Some(new RuntimeException("Malformed CSV record")) } else None // When the length of the returned tokens is identical to the length of the parsed schema, // we just need to: // 1. Convert the tokens that correspond to the required schema. // 2. Apply the pushdown filters to `requiredRow`. var i = 0 val row = requiredRow.get var skipRow = false while (i < requiredSchema.length) { try { if (skipRow) { row.setNullAt(i) } else { row(i) = valueConverters(i).apply(getToken(tokens, i)) if (csvFilters.skipRow(row, i)) { skipRow = true } } } catch { case e: SparkUpgradeException => throw e case NonFatal(e) => badRecordException = badRecordException.orElse(Some(e)) row.setNullAt(i) } i += 1 } if (skipRow) { noRows } else { if (badRecordException.isDefined) { throw BadRecordException( () => getCurrentInput, () => requiredRow.headOption, badRecordException.get) } else { requiredRow } } } } private[sql] object UnivocityParser { /** * Parses a stream that contains CSV strings and turns it into an iterator of tokens. */ def tokenizeStream( inputStream: InputStream, shouldDropHeader: Boolean, tokenizer: CsvParser, encoding: String): Iterator[Array[String]] = { val handleHeader: () => Unit = () => if (shouldDropHeader) tokenizer.parseNext convertStream(inputStream, tokenizer, handleHeader, encoding)(tokens => tokens) } /** * Parses a stream that contains CSV strings and turns it into an iterator of rows. */ def parseStream( inputStream: InputStream, parser: UnivocityParser, headerChecker: CSVHeaderChecker, schema: StructType): Iterator[InternalRow] = { val tokenizer = parser.tokenizer val safeParser = new FailureSafeParser[Array[String]]( input => parser.convert(input), parser.options.parseMode, schema, parser.options.columnNameOfCorruptRecord) val handleHeader: () => Unit = () => headerChecker.checkHeaderColumnNames(tokenizer) convertStream(inputStream, tokenizer, handleHeader, parser.options.charset) { tokens => safeParser.parse(tokens) }.flatten } private def convertStream[T]( inputStream: InputStream, tokenizer: CsvParser, handleHeader: () => Unit, encoding: String)( convert: Array[String] => T) = new Iterator[T] { tokenizer.beginParsing(inputStream, encoding) // We can handle header here since here the stream is open. handleHeader() private var nextRecord = tokenizer.parseNext() override def hasNext: Boolean = nextRecord != null override def next(): T = { if (!hasNext) { throw new NoSuchElementException("End of stream") } val curRecord = convert(nextRecord) nextRecord = tokenizer.parseNext() curRecord } } /** * Parses an iterator that contains CSV strings and turns it into an iterator of rows. */ def parseIterator( lines: Iterator[String], parser: UnivocityParser, headerChecker: CSVHeaderChecker, schema: StructType): Iterator[InternalRow] = { headerChecker.checkHeaderColumnNames(lines, parser.tokenizer) val options = parser.options val filteredLines: Iterator[String] = CSVExprUtils.filterCommentAndEmpty(lines, options) val safeParser = new FailureSafeParser[String]( input => parser.parse(input), parser.options.parseMode, schema, parser.options.columnNameOfCorruptRecord) filteredLines.flatMap(safeParser.parse) } }
spark-test/spark
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/csv/UnivocityParser.scala
Scala
apache-2.0
14,217
package rescala.extra.lattices.delta.crdt.reactive import kofre.decompose.interfaces.GMapInterface import kofre.decompose.interfaces.GMapInterface.{GMapCompanion, State} import kofre.decompose.{Delta, UIJDLattice} /** [[ReactiveCRDT Reacitve]] implementation of [[rescala.extra.lattices.delta.interfaces.GMapInterface GMapInterface]] * * Instead of the class constructor, you should use the apply method of the companion object to create new instances. * * @tparam K Type of the keys of this map * @tparam V State type of the nested CRDTs */ class GMap[K, V: UIJDLattice]( val state: State[K, V], val replicaID: String, val deltaBuffer: List[Delta[State[K, V]]] ) extends GMapInterface[K, V, GMap[K, V]] with ReactiveCRDT[State[K, V], GMap[K, V]] { override protected def copy(state: State[K, V], deltaBuffer: List[Delta[State[K, V]]]): GMap[K, V] = new GMap(state, replicaID, deltaBuffer) } object GMap extends GMapCompanion { /** Creates a new GMap instance * * @param replicaID Unique id of the replica that this instance is located on * @tparam K Type of the keys of this map * @tparam V State type of the nested CRDTs */ def apply[K, V: UIJDLattice](replicaID: String): GMap[K, V] = new GMap(UIJDLattice[State[K, V]].bottom, replicaID, List()) }
guidosalva/REScala
Code/Extensions/Replication/src/main/scala/rescala/extra/lattices/delta/crdt/reactive/GMap.scala
Scala
apache-2.0
1,314
package org.http4s import cats.effect.Async package object servlet { protected[servlet] type BodyWriter[F[_]] = Response[F] => F[Unit] protected[servlet] def NullBodyWriter[F[_]](implicit F: Async[F]): BodyWriter[F] = _ => F.unit protected[servlet] val DefaultChunkSize = 4096 }
ChristopherDavenport/http4s
servlet/src/main/scala/org/http4s/servlet/package.scala
Scala
apache-2.0
293
/* * Copyright (c) 2014 Contributor. All rights reserved. */ package dotty.tools.dotc.classpath import dotty.tools.io.ClassPath.RootPackage /** * Common methods related to package names represented as String */ object PackageNameUtils { /** * @param fullClassName full class name with package * @return (package, simple class name) */ inline def separatePkgAndClassNames(fullClassName: String): (String, String) = { val lastDotIndex = fullClassName.lastIndexOf('.') if (lastDotIndex == -1) (RootPackage, fullClassName) else (fullClassName.substring(0, lastDotIndex).nn, fullClassName.substring(lastDotIndex + 1).nn) } def packagePrefix(inPackage: String): String = if (inPackage == RootPackage) "" else inPackage + "." /** * `true` if `packageDottedName` is a package directly nested in `inPackage`, for example: * - `packageContains("scala", "scala.collection")` * - `packageContains("", "scala")` */ def packageContains(inPackage: String, packageDottedName: String) = { if (packageDottedName.contains(".")) packageDottedName.startsWith(inPackage) && packageDottedName.lastIndexOf('.') == inPackage.length else inPackage == "" } }
dotty-staging/dotty
compiler/src/dotty/tools/dotc/classpath/PackageNameUtils.scala
Scala
apache-2.0
1,218
package com.github.chaabaj.openid.oauth trait OpenIDConnectStandardClaims { def sub: String def name: Option[String] def givenName: Option[String] def familyName: Option[String] def middleName: Option[String] def nickName: Option[String] def preferredUserName: Option[String] def profile: Option[String] def picture: Option[String] def website: Option[String] def email: Option[String] def emailVerified: Option[Boolean] def gender: Option[String] def birthDate: Option[String] def zoneinfo: Option[String] def locale: Option[String] def phoneNumber: Option[String] def phoneNumberVerified: Option[Boolean] def address: Option[Any]// TODO see RFC4627 def updatedAt: Option[String] }
chaabaj/openid-scala
src/main/scala/com/github/chaabaj/openid/oauth/OpenIDConnectStandardClaims.scala
Scala
mit
724
package com.twitter.zipkin.storage.anormdb /* * Copyright 2013 Twitter Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ import org.specs._ import anorm._ import anorm.SqlParser._ class AnormDBSpec extends Specification { "AnormDB" should { "have the correct schema" in { implicit val con = new DB(new DBConfig("sqlite-memory", new DBParams(dbName = "zipkinTest"))).install() val expectedTables = List("zipkin_annotations", "zipkin_binary_annotations", "zipkin_spans") // The right tables are present val tables: List[String] = SQL( "SELECT name FROM sqlite_master WHERE type='table'" ).as(str("name") *) tables must containAll(expectedTables) val expectedCols = List( ("span_id", "BIGINT", 1), ("parent_id", "BIGINT", 0), ("trace_id", "BIGINT", 1), ("span_name", "VARCHAR(255)", 1), ("debug", "SMALLINT", 1), ("duration", "BIGINT", 0), ("created_ts", "BIGINT", 0) ) // The right columns are present val cols_spans: List[(Int, String, String, Int, Option[String], Int)] = SQL("PRAGMA table_info(zipkin_spans)").as(( int("cid") ~ str("name") ~ str("type") ~ int("notnull") ~ get[Option[String]]("dflt_value") ~ int("pk") map flatten) *) val better_cols = cols_spans.map { col => (col._2, col._3, col._4) } better_cols must containAll(expectedCols) con.close() } "insert and get rows" in { implicit val con = new DB(new DBConfig("sqlite-memory", new DBParams(dbName = "zipkinTest"))).install() // Insert val numRowsInserted: Int = SQL( "INSERT INTO zipkin_spans VALUES (2, 1, 1, 'mySpan', 1, 1000, 0)" ).executeUpdate() numRowsInserted mustEqual 1 // Get val result: List[(Long, Option[Long], Long, String, Int, Option[Long], Long)] = SQL("SELECT * FROM zipkin_spans").as(( long("span_id") ~ get[Option[Long]]("parent_id") ~ long("trace_id") ~ str("span_name") ~ int("debug") ~ get[Option[Long]]("duration") ~ long("created_ts") map flatten) *) result mustEqual List((2L, Some(1L), 1L, "mySpan", 1, Some(1000L), 0L)) con.close() } } }
AnSavvides/zipkin
zipkin-anormdb/src/test/scala/com/twitter/zipkin/storage/anormdb/AnormDBSpec.scala
Scala
apache-2.0
2,764
package au.com.dius.pact.consumer.dispatch import java.nio.charset.Charset import java.util import java.util.concurrent.CompletableFuture import au.com.dius.pact.model.{OptionalBody, Request, Response} import org.apache.commons.lang3.StringUtils import org.asynchttpclient.{DefaultAsyncHttpClient, RequestBuilder} object HttpClient { def run(request: Request): CompletableFuture[Response] = { val req = new RequestBuilder(request.getMethod) .setUrl(request.getPath) .setQueryParams(request.getQuery) request.getHeaders.forEach((name, value) => req.addHeader(name, value)) if (request.getBody.isPresent) { req.setBody(request.getBody.getValue) } val asyncHttpClient = new DefaultAsyncHttpClient asyncHttpClient.executeRequest(req).toCompletableFuture.thenApply(res => { val headers = new util.HashMap[String, String]() res.getHeaders.names().forEach(name => headers.put(name, res.getHeader(name))) val contentType = if (StringUtils.isEmpty(res.getContentType)) org.apache.http.entity.ContentType.APPLICATION_JSON else org.apache.http.entity.ContentType.parse(res.getContentType) val charset = if (contentType.getCharset == null) Charset.forName("UTF-8") else contentType.getCharset val body = if (res.hasResponseBody) { OptionalBody.body(res.getResponseBody(charset)) } else { OptionalBody.empty() } new Response(res.getStatusCode, headers, body) }) } }
algra/pact-jvm
pact-jvm-consumer-specs2/src/main/scala/au/com/dius/pact/consumer/dispatch/HttpClient.scala
Scala
apache-2.0
1,494
package org.rebeam.boxes.core.demo //import org.rebeam.boxes.core.{BoxNow, ShelfDefault} // //object BoxDemo { // // def main(args: Array[String]): Unit = { // implicit val s = ShelfDefault() // // val a = BoxNow(1) // val b = BoxNow(0) // b.now << {implicit txn => a() * 2} // // println(b.now()) // a.now() = 2 // println(b.now()) // // } //}
trepidacious/boxes-core
src/main/scala/org/rebeam/boxes/core/demo/BoxDemo.scala
Scala
gpl-2.0
368
package semighini.tdc.servico import akka.actor.ActorRef import akka.util.Timeout import semighini.tdc.JsonFormatter import semighini.tdc.atores.MensagensUsuario.{GetUser, DelUser, SetUser} import semighini.tdc.modelo.Usuario import scala.concurrent.ExecutionContext import scala.concurrent.duration._ import akka.pattern.ask import spray.routing.Directives import spray.http._ import MediaTypes._ import scala.util.{Failure, Success} import spray.json._ import DefaultJsonProtocol._ import spray.httpx.SprayJsonSupport._ /** * Created by dirceu on 8/5/14. */ class ServicoUsuario(atorUsuario:ActorRef)(implicit executionContext: ExecutionContext) extends Directives with DefaultJsonProtocol with JsonFormatter { // Request Timeout implicit val timeout = Timeout(10 seconds) // Message Json Formatters implicit val usuarioFormat = jsonFormat2(Usuario) implicit val postFormat = jsonFormat1(SetUser) implicit val getFormat = jsonFormat1(GetUser) implicit val deleteFormat = jsonFormat1(DelUser) /** * Defined Routes: * * <ul> * <li>POST usuario/v1/sessao </li> * <li>GET usuario/v1/sessao/<JavaUUID> </li> * <li>DELETE usuario/v1/sessao/<JavaUUID> </li> * </ul> */ val rota = pathPrefix("usuario" / "v1") { path("sessao") { respondWithMediaType(`application/json`) { post { handleWith { p: SetUser => { (atorUsuario ? p).mapTo[String].map(_.parseJson.prettyPrint) } } } } } ~ path("sessao" / JavaUUID) { uuid => get { respondWithMediaType(`application/json`) { onComplete((atorUsuario? GetUser(uuid)).mapTo[Option[Usuario]]) { case Success(value) => complete(value.map(_.toJson.prettyPrint)) case Failure(t) => failWith(t) } } } ~ delete { complete { atorUsuario ! DelUser(uuid) StatusCodes.NoContent } } } } }
dirceusemighini/tdc2014
src/main/scala/semighini/tdc/servico/ServicoUsuario.scala
Scala
apache-2.0
2,272
/* * Copyright 2014 JHC Systems Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sqlest.sql import sqlest.ast._ trait PostgresStatementBuilder extends base.StatementBuilder object PostgresStatementBuilder extends PostgresStatementBuilder
DavidGregory084/sqlest
sqlest/src/main/scala/sqlest/sql/PostgresStatementBuilder.scala
Scala
apache-2.0
772
package org.bitcoins.protocol import org.bitcoinj.core.{VersionedChecksummedBytes, Base58, Utils} import org.bitcoins.config.{RegTest, TestNet3, MainNet} import org.bitcoins.util.{Factory, BitcoinSUtil} import scala.util.{Failure, Success, Try} case class AddressInfo(bitcoinAddress: BitcoinAddress, n_tx: Long, total_received: Long, total_sent: Long, final_balance: Long) sealed abstract class Address( val value : String) sealed case class BitcoinAddress(override val value: String) extends Address(value ) { require(BitcoinAddress.validate(value), "Bitcoin address was invalid " + value) } sealed case class AssetAddress(override val value : String) extends Address(value) { require(AssetAddress.validate(value), "The provided asset was was invalid: " + value) } object BitcoinAddress { def validate(bitcoinAddress: String): Boolean = { val illegalChars = List('O', 'I', 'l', '0') bitcoinAddress.length >= 26 && bitcoinAddress.length <= 35 && (p2pkh(bitcoinAddress) || p2shAddress(bitcoinAddress)) && bitcoinAddress.filter(c => illegalChars.contains(c)).size == 0 } /** * Converts a bitcoin address to an asset address * * @param address * @return */ def convertToAssetAddress(address : BitcoinAddress) : AssetAddress = { val underlying : String = address.value val base58decodeChecked : Array[Byte] = Base58.decodeChecked(underlying) require ( base58decodeChecked.size == 21 ) AssetAddress(new VersionedChecksummedBytes(0x13, base58decodeChecked){}.toString()) } /** * Checks if a address is a valid p2sh address * * @param address * @return */ def p2shAddress(address : String) : Boolean = { try { val base58decodeChecked : Array[Byte] = Base58.decodeChecked(address) val firstByte = base58decodeChecked(0) ((firstByte == MainNet.p2shNetworkByte || firstByte == TestNet3.p2shNetworkByte || RegTest.p2shNetworkByte == firstByte) && base58decodeChecked.size == 21) } catch { case _ : Throwable => false } } /** * Checks if a address is a valid p2sh address * * @param address * @return */ def p2shAddress(address : BitcoinAddress) : Boolean = p2shAddress(address.value) /** * Checks if an address is a valid p2pkh address * * @param address * @return */ def p2pkh(address : String) : Boolean = { try { val base58decodeChecked : Array[Byte] = Base58.decodeChecked(address) val firstByte = base58decodeChecked(0) ((firstByte == MainNet.p2pkhNetworkByte || firstByte == TestNet3.p2pkhNetworkByte || firstByte == RegTest.p2pkhNetworkByte) && base58decodeChecked.size == 21) } catch { case _ : Throwable => false } } /** * Checks if an address is a valid p2pkh address * * @param address * @return */ def p2pkh(address : BitcoinAddress) : Boolean = p2pkh(address.value) } object AssetAddress { def validate(assetAddress : String) : Boolean = { //asset addresses must have the one byte namespace equivalent to 19 //which ends up being 'a' in the ascii character set val base58DecodeChecked : Try[Array[Byte]] = Try(Base58.decodeChecked(assetAddress)) base58DecodeChecked match { case Success(bytes) => if (bytes == null) false else bytes.size == 22 && bytes(0) == 0x13 case Failure(_) => false } } /** * Converts an asset address into a bitcoin address * * @param assetAddress * @return */ def convertToBitcoinAddress(assetAddress : AssetAddress) = { val underlying : String = assetAddress.value val base58decodeChecked : Array[Byte] = Base58.decodeChecked(underlying) require(base58decodeChecked.size == 22) val slice = base58decodeChecked.slice(2, base58decodeChecked.length) BitcoinAddress(new VersionedChecksummedBytes(base58decodeChecked(1), slice){}.toString()) } } object Address extends Factory[Address] { /** * Factory method for creating addresses * Takes in a string to check if it is an address * if it is it creates the address * if not it throws a runtime exception * * @param str * @return */ def factory(str : String) : Address = { if (AssetAddress.validate(str)) AssetAddress(str) else if (BitcoinAddress.validate(str)) BitcoinAddress(str) else throw new RuntimeException("The address that you passed in is invalid") } def fromBytes(bytes : Seq[Byte]) : Address = factory(BitcoinSUtil.encodeBase58(bytes)) override def fromHex(hex : String) : Address = throw new RuntimeException("We cannot create a bitcoin address from hex - bitcoin addresses are base 58 encoded") def apply(bytes : Seq[Byte]) : Address = fromBytes(bytes) def apply(str : String) : Address = factory(str) }
Christewart/scalacoin
src/main/scala/org/bitcoins/protocol/Address.scala
Scala
mit
4,824
// timber -- Copyright 2012-2021 -- Justin Patterson // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.scalawag.timber.backend.receiver /** Contains functionality for turning log entries into text. */ package object formatter
scalawag/timber
timber-backend/src/main/scala/org/scalawag/timber/backend/receiver/formatter/package.scala
Scala
apache-2.0
745
// Project: scalajs-rxjs // Module: rxjs/Subscription.ts // Description: Façade trait for RxJS5 Subscriptions // Copyright (c) 2016. Distributed under the MIT License (see included LICENSE file). package rxjs.core import rxjs.core.Subscription.TeardownLogic import scala.scalajs.js @js.native trait AnonymousSubscription extends js.Object { def unsubscribe(): Unit = js.native } @js.native trait Subscription extends AnonymousSubscription { def closed: Boolean = js.native def add(teardown: TeardownLogic): Subscription = js.native def remove(subscription: Subscription): Unit = js.native } object Subscription { type TeardownLogic = js.|[AnonymousSubscription,js.Function] }
jokade/scalajs-rxjs
src/main/scala/rxjs/core/Subscription.scala
Scala
mit
702
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.mllib.stat.correlation import breeze.linalg.{DenseMatrix => BDM} import org.apache.spark.internal.Logging import org.apache.spark.mllib.linalg.{Matrices, Matrix, Vector} import org.apache.spark.mllib.linalg.distributed.RowMatrix import org.apache.spark.rdd.RDD /** * Compute Pearson correlation for two RDDs of the type RDD[Double] or the correlation matrix * for an RDD of the type RDD[Vector]. * * Definition of Pearson correlation can be found at * http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient */ private[stat] object PearsonCorrelation extends Correlation with Logging { /** * Compute the Pearson correlation for two datasets. NaN if either vector has 0 variance. */ override def computeCorrelation(x: RDD[Double], y: RDD[Double]): Double = { computeCorrelationWithMatrixImpl(x, y) } /** * Compute the Pearson correlation matrix S, for the input matrix, where S(i, j) is the * correlation between column i and j. 0 covariance results in a correlation value of Double.NaN. */ override def computeCorrelationMatrix(X: RDD[Vector]): Matrix = { val rowMatrix = new RowMatrix(X) val cov = rowMatrix.computeCovariance() computeCorrelationMatrixFromCovariance(cov) } /** * Compute the Pearson correlation matrix from the covariance matrix. * 0 variance results in a correlation value of Double.NaN. */ def computeCorrelationMatrixFromCovariance(covarianceMatrix: Matrix): Matrix = { val cov = covarianceMatrix.asBreeze.asInstanceOf[BDM[Double]] val n = cov.cols // Compute the standard deviation on the diagonals first var i = 0 while (i < n) { // TODO remove once covariance numerical issue resolved. cov(i, i) = if (closeToZero(cov(i, i))) 0.0 else math.sqrt(cov(i, i)) i +=1 } // Loop through columns since cov is column major var j = 0 var sigma = 0.0 var containNaN = false while (j < n) { sigma = cov(j, j) i = 0 while (i < j) { val corr = if (sigma == 0.0 || cov(i, i) == 0.0) { containNaN = true Double.NaN } else { cov(i, j) / (sigma * cov(i, i)) } cov(i, j) = corr cov(j, i) = corr i += 1 } j += 1 } // put 1.0 on the diagonals i = 0 while (i < n) { cov(i, i) = 1.0 i +=1 } if (containNaN) { logWarning("Pearson correlation matrix contains NaN values.") } Matrices.fromBreeze(cov) } private def closeToZero(value: Double, threshold: Double = 1e-12): Boolean = { math.abs(value) <= threshold } }
bravo-zhang/spark
mllib/src/main/scala/org/apache/spark/mllib/stat/correlation/PearsonCorrelation.scala
Scala
apache-2.0
3,464
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package services import config.ApplicationConfig import connectors.{EnrolmentStubConnector, TaxEnrolmentsConnector} import javax.inject.Inject import models.enrolment.{AmlsEnrolmentKey, TaxEnrolment} import play.api.Logging import uk.gov.hmrc.http.{HeaderCarrier, HttpResponse} import scala.concurrent.{ExecutionContext, Future} class AuthEnrolmentsService @Inject()(val enrolmentStore: TaxEnrolmentsConnector, val config: ApplicationConfig, val stubConnector: EnrolmentStubConnector) extends Logging { private val amlsKey = "HMRC-MLR-ORG" private val amlsNumberKey = "MLRRefNumber" private val prefix = "AuthEnrolmentsService" def amlsRegistrationNumber(amlsRegistrationNumber: Option[String], groupIdentifier: Option[String]) (implicit headerCarrier: HeaderCarrier, ec: ExecutionContext): Future[Option[String]] = { // $COVERAGE-OFF$ logger.debug(s"[$prefix][amlsRegistrationNumber] - Begin...)") logger.debug(s"[$prefix][amlsRegistrationNumber] - config.enrolmentStubsEnabled: ${config.enrolmentStubsEnabled})") // $COVERAGE-ON$ val stubbedEnrolments = if (config.enrolmentStubsEnabled) { stubConnector.enrolments(groupIdentifier.getOrElse(throw new Exception("Group ID is unavailable"))) } else { // $COVERAGE-OFF$ logger.debug(s"[$prefix][amlsRegistrationNumber] - Returning empty sequence...)") // $COVERAGE-ON$ Future.successful(Seq.empty) } amlsRegistrationNumber match { case regNo@Some(_) => Future.successful(regNo) case None => stubbedEnrolments map { enrolmentsList => // $COVERAGE-OFF$ logger.debug(s"[$prefix][amlsRegistrationNumber] - enrolmentsList: $enrolmentsList)") // $COVERAGE-ON$ for { amlsEnrolment <- enrolmentsList.find(enrolment => enrolment.key == amlsKey) amlsIdentifier <- amlsEnrolment.identifiers.find(identifier => identifier.key == amlsNumberKey) } yield { // $COVERAGE-OFF$ logger.debug(s"[$prefix][amlsRegistrationNumber] - amlsEnrolment: $amlsEnrolment)") logger.debug(s"[$prefix][amlsRegistrationNumber] : ${amlsIdentifier.value}") // $COVERAGE-ON$ amlsIdentifier.value } } } } def enrol(amlsRegistrationNumber: String, postcode: String, groupId: Option[String], credId: String) (implicit hc: HeaderCarrier, ec: ExecutionContext): Future[HttpResponse] = { enrolmentStore.enrol(AmlsEnrolmentKey(amlsRegistrationNumber), TaxEnrolment(credId, postcode), groupId) } def deEnrol(amlsRegistrationNumber: String, groupId: Option[String]) (implicit hc: HeaderCarrier, ec: ExecutionContext): Future[Boolean] = { for { _ <- enrolmentStore.removeKnownFacts(amlsRegistrationNumber) _ <- enrolmentStore.deEnrol(amlsRegistrationNumber, groupId) } yield true } }
hmrc/amls-frontend
app/services/AuthEnrolmentsService.scala
Scala
apache-2.0
3,601
/* * RotateFlipMatrix.scala * (FScape) * * Copyright (c) 2001-2022 Hanns Holger Rutz. All rights reserved. * * This software is published under the GNU Affero General Public License v3+ * * * For further information, please contact Hanns Holger Rutz at * [email protected] */ package de.sciss.fscape package stream import akka.stream.{Attributes, FanInShape4} import de.sciss.fscape.graph.RotateFlipMatrix._ import de.sciss.fscape.stream.impl.Handlers.{InDMain, InIAux, OutDMain} import de.sciss.fscape.stream.impl.logic.WindowedInAOutA import de.sciss.fscape.stream.impl.{Handlers, NodeImpl, StageImpl} import scala.annotation.switch import math.max import de.sciss.numbers.Implicits._ object RotateFlipMatrix { def apply(in: OutD, rows: OutI, columns: OutI, mode: OutI)(implicit b: Builder): OutD = { val stage0 = new Stage(b.layer) val stage = b.add(stage0) b.connect(in , stage.in0) b.connect(rows , stage.in1) b.connect(columns, stage.in2) b.connect(mode , stage.in3) stage.out } private final val name = "RotateFlipMatrix" private type Shp = FanInShape4[BufD, BufI, BufI, BufI, BufD] private final class Stage(layer: Layer)(implicit a: Allocator) extends StageImpl[Shp](name) { stage => val shape: Shape = new FanInShape4( in0 = InD (s"${stage.name}.in" ), in1 = InI (s"${stage.name}.rows" ), in2 = InI (s"${stage.name}.columns"), in3 = InI (s"${stage.name}.mode" ), out = OutD(s"${stage.name}.out" ) ) def createLogic(attr: Attributes): NodeImpl[Shape] = new Logic(shape, layer) } private final val Transpose = 16 // XXX TODO -- abstract over data type (BufD vs BufI)? private final class Logic(shape: Shp, layer: Layer)(implicit a: Allocator) extends Handlers(name, layer, shape) with WindowedInAOutA[Double, BufD] { protected val hIn : InDMain = InDMain (this, shape.in0) protected val hOut : OutDMain = OutDMain(this, shape.out) private[this] val hRows : InIAux = InIAux (this, shape.in1)(max(1, _)) private[this] val hCols : InIAux = InIAux (this, shape.in2)(max(1, _)) private[this] val hMode : InIAux = InIAux (this, shape.in3)(_.clip(0, 11)) private[this] var inBuf : Array[Double] = _ private[this] var outBuf : Array[Double] = _ private[this] var rows : Int = _ private[this] var columns: Int = _ private[this] var mode : Int = _ private[this] var needsDoubleBuf: Boolean = _ private[this] var winSize: Int = _ protected def tpe: StreamType[Double, BufD] = StreamType.double protected def tryObtainWinParams(): Boolean = { val ok = hRows.hasNext && hCols.hasNext && hMode.hasNext if (ok) { val oldSize = winSize val oldMode = mode rows = hRows.next() columns = hCols.next() val isSquare = rows == columns var _mode = hMode.next() // logically remove cw + ccw here if ((_mode & 12) == 12) _mode &= ~12 // reduce number of steps if (isSquare) { if (_mode == (FlipX | Rot90CCW) || _mode == (FlipY | Rot90CW)) _mode = Transpose else if (_mode == (FlipY | Rot90CCW) || _mode == (FlipX | Rot90CW)) _mode = Transpose | Rot180 } mode = _mode needsDoubleBuf = !isSquare && (mode & 12) != 0 winSize = rows * columns if (winSize != oldSize) { inBuf = new Array[Double](winSize) if (needsDoubleBuf) { outBuf = new Array[Double](winSize) } else{ outBuf = inBuf } } else if (mode != oldMode) { if (needsDoubleBuf) { if (outBuf eq inBuf) outBuf = new Array[Double](winSize) } else { outBuf = inBuf } } } ok } protected def winBufSize: Int = 0 override protected def readWinSize : Long = winSize override protected def writeWinSize : Long = winSize override protected def stopped(): Unit = { super.stopped() inBuf = null outBuf = null } override protected def readIntoWindow(n: Int): Unit = { val offI = readOff.toInt hIn.nextN(inBuf, offI, n) } /** Writes out a number of frames. The default implementation copies from the window buffer. */ override protected def writeFromWindow(n: Int): Unit = { val offI = writeOff.toInt hOut.nextN(outBuf, offI, n) } // in-place private def flipX(): Unit = { val a = inBuf val _cols = columns var off = 0 val stop = winSize while (off < stop) { var i = off off += _cols var j = off - 1 while (i < j) { val tmp = a(i) a(i) = a(j) a(j) = tmp i += 1 j -= 1 } } } // in-place private def flipY(): Unit = { val a = inBuf val _cols = columns var i = 0 var j = winSize - _cols while (i < j) { val iNext = i + _cols val jNext = j - _cols while (i < iNext) { val tmp = a(i) a(i) = a(j) a(j) = tmp i += 1 j += 1 } j = jNext } } // in-place private def rot180(): Unit = Util.reverse(inBuf, 0, winSize) // in-place private def transpose(): Unit = { val a = inBuf val n = columns val jStep = n + 1 var m = n var i = 0 var j = 0 val stop = winSize while (i < stop) { i = j val iNext = i + m val jNext = j + jStep while (i < iNext) { val tmp = a(i) a(i) = a(j) a(j) = tmp i += 1 j += n } m -= 1 j = jNext } } // in-place private def sqrRot90CW(): Unit = { transpose() flipX() } // in-place private def sqrRot90CCW(): Unit = { transpose() flipY() } private def rot90CW(): Unit = { val a = inBuf val b = outBuf val _cols = columns val _rows = rows var i = 0 var j = _cols * (_rows - 1) val stop = winSize while (i < stop) { val iNext = i + _rows val jNext = j + 1 while (i < iNext) { b(i) = a(j) i += 1 j -= _cols } j = jNext } } private def rot90CCW(): Unit = { val a = inBuf val b = outBuf val _cols = columns val _rows = rows var i = 0 var j = _rows * (_cols - 1) val stop = winSize while (i < stop) { val iNext = i + _cols val jNext = j + 1 while (i < iNext) { b(j) = a(i) i += 1 j -= _rows } j = jNext } } protected def processWindow(): Unit = { val _mode = mode (_mode & 3: @switch) match { case Through => case FlipX => flipX() case FlipY => flipY() case Rot180 => rot180() } (_mode >> 2: @switch) match { case 0 => case 1 => if (needsDoubleBuf) rot90CW() else sqrRot90CW() case 2 => if (needsDoubleBuf) rot90CCW() else sqrRot90CCW() case 4 => transpose() } } } }
Sciss/FScape-next
core/shared/src/main/scala/de/sciss/fscape/stream/RotateFlipMatrix.scala
Scala
agpl-3.0
7,450
// Copyright 2017 Foursquare Labs Inc. All Rights Reserved. package io.fsq.spindle.common.thrift.serde import org.apache.thrift.{TBase, TByteArrayOutputStream, TFieldIdEnum} import org.apache.thrift.protocol.TCompactProtocol import org.apache.thrift.transport.TIOStreamTransport /** * Custom serializer that reuses the internal byte array instead of defensively copying. * NOTE: This means that you *must* use/copy the array before calling. * * As with the standard TSerializer, this is not threadsafe. */ class ThriftReusingSerializer[T <: TBase[_ <: TBase[_, _], _ <: TFieldIdEnum]] { private[this] val protocolFactory = new TCompactProtocol.Factory() private[this] val baos = new TByteArrayOutputStream(512) private[this] val transport = new TIOStreamTransport(baos) private[this] val prot = protocolFactory.getProtocol(transport) /** * Serialize the record out. Remember, the array is reused so you may not retain a reference between calls. */ def serialize(t: T): (Array[Byte], Int) = { baos.reset() t.write(prot) (baos.get, baos.len) } }
foursquare/fsqio
src/jvm/io/fsq/spindle/common/thrift/serde/ThriftReusingSerializer.scala
Scala
apache-2.0
1,092
object Test extends App { test.Test.test } package test { object Test { def test = { Macros.foo } } }
scala/scala
test/files/run/macro-enclosures/Test_2.scala
Scala
apache-2.0
123
package fpinscala.localeffects import fpinscala.monads._ object Mutable { def quicksort(xs: List[Int]): List[Int] = if (xs.isEmpty) xs else { val arr = xs.toArray def swap(x: Int, y: Int) = { val tmp = arr(x) arr(x) = arr(y) arr(y) = tmp } def partition(l: Int, r: Int, pivot: Int) = { val pivotVal = arr(pivot) swap(pivot, r) var j = l for (i <- l until r) if (arr(i) < pivotVal) { swap(i, j) j += 1 } swap(j, r) j } def qs(l: Int, r: Int): Unit = if (l < r) { val pi = partition(l, r, l + (r - l) / 2) qs(l, pi - 1) qs(pi + 1, r) } qs(0, arr.length - 1) arr.toList } } sealed trait ST[S,A] { self => protected def run(s: S): (A,S) def map[B](f: A => B): ST[S,B] = new ST[S,B] { def run(s: S) = { val (a, s1) = self.run(s) (f(a), s1) } } def flatMap[B](f: A => ST[S,B]): ST[S,B] = new ST[S,B] { def run(s: S) = { val (a, s1) = self.run(s) f(a).run(s1) } } } object ST { def apply[S,A](a: => A) = { lazy val memo = a new ST[S,A] { def run(s: S) = (memo, s) } } def runST[A](st: RunnableST[A]): A = st[Null].run(null)._1 } sealed trait STRef[S,A] { protected var cell: A def read: ST[S,A] = ST(cell) def write(a: => A): ST[S,Unit] = new ST[S,Unit] { def run(s: S) = { cell = a ((), s) } } } object STRef { def apply[S,A](a: A): ST[S, STRef[S,A]] = ST(new STRef[S,A] { var cell = a }) } trait RunnableST[A] { def apply[S]: ST[S,A] } // Scala requires an implicit Manifest for constructing arrays. sealed abstract class STArray[S,A](implicit manifest: Manifest[A]) { protected def value: Array[A] def size: ST[S,Int] = ST(value.size) // Write a value at the give index of the array def write(i: Int, a: A): ST[S,Unit] = new ST[S,Unit] { def run(s: S) = { value(i) = a ((), s) } } // Read the value at the given index of the array def read(i: Int): ST[S,A] = ST(value(i)) // Turn the array into an immutable list def freeze: ST[S,List[A]] = ST(value.toList) def fill(xs: Map[Int,A]): ST[S,Unit] = ??? def swap(i: Int, j: Int): ST[S,Unit] = for { x <- read(i) y <- read(j) _ <- write(i, y) _ <- write(j, x) } yield () } object STArray { // Construct an array of the given size filled with the value v def apply[S,A:Manifest](sz: Int, v: A): ST[S, STArray[S,A]] = ST(new STArray[S,A] { lazy val value = Array.fill(sz)(v) }) def fromList[S,A:Manifest](xs: List[A]): ST[S, STArray[S,A]] = ST(new STArray[S,A] { lazy val value = xs.toArray }) } object Immutable { def noop[S] = ST[S,Unit](()) def partition[S](a: STArray[S,Int], l: Int, r: Int, pivot: Int): ST[S,Int] = ??? def qs[S](a: STArray[S,Int], l: Int, r: Int): ST[S, Unit] = ??? def quicksort(xs: List[Int]): List[Int] = if (xs.isEmpty) xs else ST.runST(new RunnableST[List[Int]] { def apply[S] = for { arr <- STArray.fromList(xs) size <- arr.size _ <- qs(arr, 0, size - 1) sorted <- arr.freeze } yield sorted }) } import scala.collection.mutable.HashMap sealed trait STMap[S,K,V] { protected def table: HashMap[K,V] def size: ST[S,Int] = ??? // Get the value under a key def apply(k: K): ST[S,V] = ??? // Get the value under a key, or None if the key does not exist def get(k: K): ST[S, Option[V]] = ??? // Add a value under a key def +=(kv: (K, V)): ST[S,Unit] = ??? // Remove a key def -=(k: K): ST[S,Unit] = ??? } object STMap { def empty[S,K,V]: ST[S, STMap[S,K,V]] = ??? def fromMap[S,K,V](m: Map[K,V]): ST[S, STMap[S,K,V]] = ??? }
fpinscala-muc/fpinscala-mhofsche
exercises/src/main/scala/fpinscala/localeffects/LocalEffects.scala
Scala
mit
3,752
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kafka.admin import kafka.admin.TopicCommand.{PartitionDescription, TopicCommandOptions} import kafka.common.AdminCommandFailedException import kafka.utils.Exit import org.apache.kafka.clients.admin.PartitionReassignment import org.apache.kafka.common.Node import org.apache.kafka.common.TopicPartitionInfo import org.junit.jupiter.api.Assertions._ import org.junit.jupiter.api.Test import scala.jdk.CollectionConverters._ class TopicCommandTest { private[this] val brokerList = "localhost:9092" private[this] val topicName = "topicName" @Test def testIsNotUnderReplicatedWhenAdding(): Unit = { val replicaIds = List(1, 2) val replicas = replicaIds.map { id => new Node(id, "localhost", 9090 + id) } val partitionDescription = PartitionDescription( "test-topic", new TopicPartitionInfo( 0, new Node(1, "localhost", 9091), replicas.asJava, List(new Node(1, "localhost", 9091)).asJava ), None, markedForDeletion = false, Some( new PartitionReassignment( replicaIds.map(id => id: java.lang.Integer).asJava, List(2: java.lang.Integer).asJava, List.empty.asJava ) ) ) assertFalse(partitionDescription.isUnderReplicated) } @Test def testAlterWithUnspecifiedPartitionCount(): Unit = { assertCheckArgsExitCode(1, new TopicCommandOptions( Array("--bootstrap-server", brokerList ,"--alter", "--topic", topicName))) } @Test def testConfigOptWithBootstrapServers(): Unit = { assertCheckArgsExitCode(1, new TopicCommandOptions(Array("--bootstrap-server", brokerList ,"--alter", "--topic", topicName, "--partitions", "3", "--config", "cleanup.policy=compact"))) assertCheckArgsExitCode(1, new TopicCommandOptions(Array("--bootstrap-server", brokerList ,"--alter", "--topic", topicName, "--partitions", "3", "--delete-config", "cleanup.policy"))) val opts = new TopicCommandOptions(Array("--bootstrap-server", brokerList ,"--create", "--topic", topicName, "--partitions", "3", "--replication-factor", "3", "--config", "cleanup.policy=compact")) opts.checkArgs() assertTrue(opts.hasCreateOption) assertEquals(brokerList, opts.bootstrapServer.get) assertEquals("cleanup.policy=compact", opts.topicConfig.get.get(0)) } @Test def testCreateWithAssignmentAndPartitionCount(): Unit = { assertCheckArgsExitCode(1, new TopicCommandOptions( Array("--bootstrap-server", brokerList, "--create", "--replica-assignment", "3:0,5:1", "--partitions", "2", "--topic", "testTopic"))) } @Test def testCreateWithAssignmentAndReplicationFactor(): Unit = { assertCheckArgsExitCode(1, new TopicCommandOptions( Array("--bootstrap-server", brokerList, "--create", "--replica-assignment", "3:0,5:1", "--replication-factor", "2", "--topic", "testTopic"))) } @Test def testParseAssignmentDuplicateEntries(): Unit = { assertThrows(classOf[AdminCommandFailedException], () => TopicCommand.parseReplicaAssignment("5:5")) } @Test def testParseAssignmentPartitionsOfDifferentSize(): Unit = { assertThrows(classOf[AdminOperationException], () => TopicCommand.parseReplicaAssignment("5:4:3,2:1")) } @Test def testParseAssignment(): Unit = { val actualAssignment = TopicCommand.parseReplicaAssignment("5:4,3:2,1:0") val expectedAssignment = Map(0 -> List(5, 4), 1 -> List(3, 2), 2 -> List(1, 0)) assertEquals(expectedAssignment, actualAssignment) } private[this] def assertCheckArgsExitCode(expected: Int, options: TopicCommandOptions): Unit = { Exit.setExitProcedure { (exitCode: Int, _: Option[String]) => assertEquals(expected, exitCode) throw new RuntimeException } try assertThrows(classOf[RuntimeException], () => options.checkArgs()) finally Exit.resetExitProcedure() } }
Chasego/kafka
core/src/test/scala/unit/kafka/admin/TopicCommandTest.scala
Scala
apache-2.0
4,781
/* * This file is part of eCobertura. * * Copyright (c) 2009, 2010 Joachim Hofer * All rights reserved. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package ecobertura.ui.editors import java.util.logging.Logger import org.eclipse.ui.texteditor.ITextEditor import org.eclipse.jdt.core.ITypeRoot import org.eclipse.jdt.ui._ import ecobertura.core.data._ object LineCoverageFinder { val logger = Logger.getLogger("ecobertura.ui.editors") def forSession(session: CoverageSession) = new LineCoverageFinder(session) } class LineCoverageFinder(session: CoverageSession) { import LineCoverageFinder.logger def findInEditor(editor: ITextEditor): List[LineCoverage] = { JavaUI.getEditorInputTypeRoot(editor.getEditorInput) match { case typeRoot: ITypeRoot => findForTypeRoot(typeRoot) case _ => Nil } } private def findForTypeRoot(typeRoot: ITypeRoot) = { val sourceFileName = typeRoot.getElementName val packageName = typeRoot.getParent.getElementName def findInPackage(packageCov: PackageCoverage) = { packageCov.sourceFileLines.get(sourceFileName) match { case Some(lines) => { logger.fine("found lines: " + lines.mkString(", ")) lines } case None => Nil } } session.packageMap.get(packageName) match { case Some(packageCov) => findInPackage(packageCov) case None => Nil } } }
jmhofer/eCobertura
ecobertura.ui/src/main/scala/ecobertura/ui/editors/LineCoverageFinder.scala
Scala
epl-1.0
1,542
package org.http4s.dsl.impl import org.http4s.{AuthedRequest, Request} trait Auth { object as { def unapply[F[_], A](ar: AuthedRequest[F, A]): Option[(Request[F], A)] = Some(ar.req -> ar.context) } }
ChristopherDavenport/http4s
dsl/src/main/scala/org/http4s/dsl/impl/Auth.scala
Scala
apache-2.0
216
package com.tritondigital.counters import com.typesafe.config.ConfigFactory import scala.util.Random object Benchmark extends App with CustomMatchers { val Loops = 100000 // val TagCardinality = 100 val TagCardinality = 2 val config = ConfigFactory .load() usingActorSystem(config) { system => val metricsSystem = new MetricsSystemFactory(system, Array.empty[MetricsProvider], null, Array.empty[Tag], true, false, true) val metrics = metricsSystem.metrics // Warm up benchmarkedLogic(metrics) Thread.sleep(100) val start = System.nanoTime() // readLine("Ready to start the benchmark. Press [ENTER] to proceed.") for(cycle <- 0 to 4) { println("Starting cycle") for (i <- 0 to Loops) { benchmarkedLogic(metrics) } println("Cycle done!") Thread.sleep(15 * 1000) } val timeTaken = System.nanoTime() - start println(s"Took ${timeTaken / 1000000L} ms for $Loops calls (${timeTaken / Loops} ns / call)") readLine("Press [ENTER] to quit.") } def benchmarkedLogic(metrics: Metrics) { metrics.updateHistogram("benchmark.histo." + Random.nextInt(2), 12L, Tag("tag1", Random.nextInt(TagCardinality).toString), Tag("tag2", Random.nextInt(TagCardinality).toString)) } }
tritondigital/tritondigital-counters
src/test/scala/com/tritondigital/counters/Benchmark.scala
Scala
apache-2.0
1,273
/* * Copyright 2014 Treode, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.treode.cluster import scala.util.{Failure, Success, Try} import com.treode.async.Async import com.treode.pickle.Pickler import Async.guard class RequestDescriptor [Q, A] private ( val id: PortId, val preq: Pickler [Q], val prsp: Pickler [A] ) { type Port = EphemeralPort [Option [A]] private val _preq = { import ClusterPicklers._ tuple (portId, preq) } private val _prsp = { import ClusterPicklers._ option (prsp) } private [cluster] def listen (m: PortRegistry) (f: (Q, Peer) => Async [A]): Unit = m.listen (_preq, id) { case ((port, req), from) => guard (f (req, from)) run { case Success (rsp) => from.send (_prsp, port, Some (rsp)) case Failure (_: IgnoreRequestException) => () case Failure (t) => from.send (_prsp, port, None) throw t }} private [cluster] def open (m: PortRegistry) (f: (Try [A], Peer) => Any): Port = m.open (_prsp) { case (Some (v), from) => f (Success (v), from) case (None, from) => f (Failure (new RemoteException), from) } def listen (f: (Q, Peer) => Async [A]) (implicit c: Cluster): Unit = c.listen (this) (f) def open (f: (Try [A], Peer) => Any) (implicit c: Cluster): Port = c.open (this) (f) def apply (req: Q) = RequestSender [Q, A] (id, _preq, req) override def toString = s"RequestDescriptor($id)" } object RequestDescriptor { def apply [Q, A] (id: PortId, preq: Pickler [Q], pans: Pickler [A]): RequestDescriptor [Q, A] = new RequestDescriptor (id, preq, pans) }
Treode/store
cluster/src/com/treode/cluster/RequestDescriptor.scala
Scala
apache-2.0
2,190
package frameless package functions import frameless.functions.aggregate._ import org.scalacheck.Prop import org.scalacheck.Prop._ class AggregateFunctionsTests extends TypedDatasetSuite { def approximatelyEqual[A](a: A, b: A)(implicit numeric: Numeric[A]): Prop = { val da = numeric.toDouble(a) val db = numeric.toDouble(b) val epsilon = 1E-6 // Spark has a weird behaviour concerning expressions that should return Inf // Most of the time they return NaN instead, for instance stddev of Seq(-7.827553978923477E227, -5.009124275715786E153) if((da.isNaN || da.isInfinity) && (db.isNaN || db.isInfinity)) proved else if ( (da - db).abs < epsilon || (da - db).abs < da.abs / 100) proved else falsified :| s"Expected $a but got $b, which is more than 1% off and greater than epsilon = $epsilon." } def sparkSchema[A: TypedEncoder, U](f: TypedColumn[X1[A], A] => TypedColumn[X1[A], U]): Prop = { val df = TypedDataset.create[X1[A]](Nil) val col = f(df.col('a)) import col.uencoder val sumDf = df.select(col) TypedExpressionEncoder.targetStructType(sumDf.encoder) ?= sumDf.dataset.schema } test("sum") { case class Sum4Tests[A, B](sum: Seq[A] => B) def prop[A: TypedEncoder, Out: TypedEncoder : Numeric](xs: List[A])( implicit summable: CatalystSummable[A, Out], summer: Sum4Tests[A, Out] ): Prop = { val dataset = TypedDataset.create(xs.map(X1(_))) val A = dataset.col[A]('a) val datasetSum: List[Out] = dataset.select(sum(A)).collect().run().toList datasetSum match { case x :: Nil => approximatelyEqual(summer.sum(xs), x) case other => falsified } } // Replicate Spark's behaviour : Ints and Shorts are cast to Long // https://github.com/apache/spark/blob/7eb2ca8/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Sum.scala#L37 implicit def summerDecimal = Sum4Tests[BigDecimal, BigDecimal](_.sum) implicit def summerDouble = Sum4Tests[Double, Double](_.sum) implicit def summerLong = Sum4Tests[Long, Long](_.sum) implicit def summerInt = Sum4Tests[Int, Long](_.map(_.toLong).sum) implicit def summerShort = Sum4Tests[Short, Long](_.map(_.toLong).sum) check(forAll(prop[BigDecimal, BigDecimal] _)) check(forAll(prop[Long, Long] _)) check(forAll(prop[Double, Double] _)) check(forAll(prop[Int, Long] _)) check(forAll(prop[Short, Long] _)) check(sparkSchema[BigDecimal, BigDecimal](sum)) check(sparkSchema[Long, Long](sum)) check(sparkSchema[Int, Long](sum)) check(sparkSchema[Double, Double](sum)) check(sparkSchema[Short, Long](sum)) } test("avg") { case class Averager4Tests[A, B](avg: Seq[A] => B) def prop[A: TypedEncoder, Out: TypedEncoder : Numeric](xs: List[A])( implicit averageable: CatalystAverageable[A, Out], averager: Averager4Tests[A, Out] ): Prop = { val dataset = TypedDataset.create(xs.map(X1(_))) val A = dataset.col[A]('a) val Vector(datasetAvg): Vector[Option[Out]] = dataset.select(avg(A)).collect().run().toVector xs match { case Nil => datasetAvg ?= None case _ :: _ => datasetAvg match { case Some(x) => approximatelyEqual(averager.avg(xs), x) case other => falsified } } } // Replicate Spark's behaviour : If the datatype isn't BigDecimal cast type to Double // https://github.com/apache/spark/blob/7eb2ca8/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/aggregate/Average.scala#L50 implicit def averageDecimal = Averager4Tests[BigDecimal, BigDecimal](as => as.sum/as.size) implicit def averageDouble = Averager4Tests[Double, Double](as => as.sum/as.size) implicit def averageLong = Averager4Tests[Long, Double](as => as.map(_.toDouble).sum/as.size) implicit def averageInt = Averager4Tests[Int, Double](as => as.map(_.toDouble).sum/as.size) implicit def averageShort = Averager4Tests[Short, Double](as => as.map(_.toDouble).sum/as.size) check(forAll(prop[BigDecimal, BigDecimal] _)) check(forAll(prop[Double, Double] _)) check(forAll(prop[Long, Double] _)) check(forAll(prop[Int, Double] _)) check(forAll(prop[Short, Double] _)) } test("stddev") { def prop[A: TypedEncoder : CatalystVariance : Numeric](xs: List[A]): Prop = { val dataset = TypedDataset.create(xs.map(X1(_))) val A = dataset.col[A]('a) val Vector(datasetStd) = dataset.select(stddev(A)).collect().run().toVector val std = sc.parallelize(xs.map(implicitly[Numeric[A]].toDouble)).sampleStdev() xs match { case Nil => datasetStd ?= None case _ :: Nil => datasetStd match { case Some(x) => if (x.isNaN) proved else falsified case _ => falsified } case _ => datasetStd match { case Some(x) => approximatelyEqual(std, x) case _ => falsified } } } check(forAll(prop[Short] _)) check(forAll(prop[Int] _)) check(forAll(prop[Long] _)) check(forAll(prop[BigDecimal] _)) check(forAll(prop[Double] _)) } test("count") { def prop[A: TypedEncoder](xs: List[A]): Prop = { val dataset = TypedDataset.create(xs) val Vector(datasetCount) = dataset.select(count()).collect().run().toVector datasetCount ?= xs.size.toLong } check(forAll(prop[Int] _)) check(forAll(prop[Byte] _)) } test("count('a)") { def prop[A: TypedEncoder](xs: List[A]): Prop = { val dataset = TypedDataset.create(xs.map(X1(_))) val A = dataset.col[A]('a) val datasetCount = dataset.select(count(A)).collect().run() datasetCount ?= List(xs.size.toLong) } check(forAll(prop[Int] _)) check(forAll(prop[Byte] _)) } test("max") { def prop[A: TypedEncoder: CatalystOrdered](xs: List[A])(implicit o: Ordering[A]): Prop = { val dataset = TypedDataset.create(xs.map(X1(_))) val A = dataset.col[A]('a) val datasetMax = dataset.select(max(A)).collect().run().toList datasetMax ?= List(xs.reduceOption(o.max)) } check(forAll(prop[Long] _)) check(forAll(prop[Double] _)) check(forAll(prop[Int] _)) check(forAll(prop[Short] _)) check(forAll(prop[Byte] _)) check(forAll(prop[String] _)) } test("min") { def prop[A: TypedEncoder: CatalystOrdered](xs: List[A])(implicit o: Ordering[A]): Prop = { val dataset = TypedDataset.create(xs.map(X1(_))) val A = dataset.col[A]('a) val datasetMin = dataset.select(min(A)).collect().run().toList datasetMin ?= List(xs.reduceOption(o.min)) } check(forAll(prop[Long] _)) check(forAll(prop[Double] _)) check(forAll(prop[Int] _)) check(forAll(prop[Short] _)) check(forAll(prop[Byte] _)) check(forAll(prop[String] _)) } test("first") { def prop[A: TypedEncoder](xs: List[A]): Prop = { val dataset = TypedDataset.create(xs.map(X1(_))) val A = dataset.col[A]('a) val datasetFirst = dataset.select(first(A)).collect().run().toList datasetFirst ?= List(xs.headOption) } check(forAll(prop[BigDecimal] _)) check(forAll(prop[Long] _)) check(forAll(prop[Double] _)) check(forAll(prop[Int] _)) check(forAll(prop[Short] _)) check(forAll(prop[Byte] _)) check(forAll(prop[String] _)) } test("last") { def prop[A: TypedEncoder](xs: List[A]): Prop = { val dataset = TypedDataset.create(xs.map(X1(_))) val A = dataset.col[A]('a) val datasetLast = dataset.select(last(A)).collect().run().toList datasetLast ?= List(xs.lastOption) } check(forAll(prop[BigDecimal] _)) check(forAll(prop[Long] _)) check(forAll(prop[Double] _)) check(forAll(prop[Int] _)) check(forAll(prop[Short] _)) check(forAll(prop[Byte] _)) check(forAll(prop[String] _)) } }
OlivierBlanvillain/frameless
dataset/src/test/scala/frameless/functions/AggregateFunctionsTests.scala
Scala
apache-2.0
7,950
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.functions.aggfunctions import java.math.BigDecimal import java.lang.{Iterable => JIterable, Long => JLong} import java.sql.{Date, Time, Timestamp} import org.apache.flink.api.common.typeinfo.{BasicTypeInfo, TypeInformation, Types} import org.apache.flink.table.api.dataview.MapView import org.apache.flink.table.functions.aggfunctions.Ordering._ import org.apache.flink.table.functions.AggregateFunction /** The initial accumulator for Max with retraction aggregate function */ class MaxWithRetractAccumulator[T] { var max: T = _ var distinctCount: JLong = _ var map: MapView[T, JLong] = _ } /** * Base class for built-in Max with retraction aggregate function * * @tparam T the type for the aggregation result */ abstract class MaxWithRetractAggFunction[T](implicit ord: Ordering[T]) extends AggregateFunction[T, MaxWithRetractAccumulator[T]] { override def createAccumulator(): MaxWithRetractAccumulator[T] = { val acc = new MaxWithRetractAccumulator[T] acc.max = getInitValue //max acc.distinctCount = 0L acc.map = new MapView(getValueTypeInfo, Types.LONG) .asInstanceOf[MapView[T, JLong]] //store the count for each value acc } def accumulate(acc: MaxWithRetractAccumulator[T], value: Any): Unit = { if (value != null) { val v = value.asInstanceOf[T] if (acc.distinctCount == 0 || (ord.compare(acc.max, v) < 0)) { acc.max = v } var count = acc.map.get(v) if (count == null) { acc.map.put(v, 1L) acc.distinctCount += 1 } else { count += 1L acc.map.put(v, count) } } } def retract(acc: MaxWithRetractAccumulator[T], value: Any): Unit = { if (value != null) { val v = value.asInstanceOf[T] val count = acc.map.get(v) if (count == null || count == 1) { //remove the key v from the map if the number of appearance of the value v is 0 if (count != null) { acc.map.remove(v) } //if the total count is 0, we could just simply set the f0(max) to the initial value acc.distinctCount -= 1 if (acc.distinctCount == 0) { acc.max = getInitValue return } //if v is the current max value, we have to iterate the map to find the 2nd biggest // value to replace v as the max value if (v == acc.max) { val iterator = acc.map.keys.iterator() var hasMax = false while (iterator.hasNext) { val key = iterator.next() if (!hasMax || ord.compare(acc.max, key) < 0) { acc.max = key hasMax = true } } if (!hasMax) { acc.distinctCount = 0L } } } else { acc.map.put(v, count - 1) } } } override def getValue(acc: MaxWithRetractAccumulator[T]): T = { if (acc.distinctCount != 0) { acc.max } else { null.asInstanceOf[T] } } def merge(acc: MaxWithRetractAccumulator[T], its: JIterable[MaxWithRetractAccumulator[T]]): Unit = { val iter = its.iterator() while (iter.hasNext) { val a = iter.next() if (a.distinctCount != 0) { // set max element if (ord.compare(acc.max, a.max) < 0) { acc.max = a.max } // merge the count for each key val iterator = a.map.entries.iterator() while (iterator.hasNext) { val entry = iterator.next() val key = entry.getKey val value = entry.getValue val count = acc.map.get(key) if (count != null) { acc.map.put(key, count + value) } else { acc.map.put(key, value) acc.distinctCount += 1 } } } } } def resetAccumulator(acc: MaxWithRetractAccumulator[T]): Unit = { acc.max = getInitValue acc.distinctCount = 0L acc.map.clear() } def getInitValue: T def getValueTypeInfo: TypeInformation[_] } /** * Built-in Byte Max with retraction aggregate function */ class ByteMaxWithRetractAggFunction extends MaxWithRetractAggFunction[Byte] { override def getInitValue: Byte = 0.toByte override def getValueTypeInfo = BasicTypeInfo.BYTE_TYPE_INFO } /** * Built-in Short Max with retraction aggregate function */ class ShortMaxWithRetractAggFunction extends MaxWithRetractAggFunction[Short] { override def getInitValue: Short = 0.toShort override def getValueTypeInfo = BasicTypeInfo.SHORT_TYPE_INFO } /** * Built-in Int Max with retraction aggregate function */ class IntMaxWithRetractAggFunction extends MaxWithRetractAggFunction[Int] { override def getInitValue: Int = 0 override def getValueTypeInfo = BasicTypeInfo.INT_TYPE_INFO } /** * Built-in Long Max with retraction aggregate function */ class LongMaxWithRetractAggFunction extends MaxWithRetractAggFunction[Long] { override def getInitValue: Long = 0L override def getValueTypeInfo = BasicTypeInfo.LONG_TYPE_INFO } /** * Built-in Float Max with retraction aggregate function */ class FloatMaxWithRetractAggFunction extends MaxWithRetractAggFunction[Float] { override def getInitValue: Float = 0.0f override def getValueTypeInfo = BasicTypeInfo.FLOAT_TYPE_INFO } /** * Built-in Double Max with retraction aggregate function */ class DoubleMaxWithRetractAggFunction extends MaxWithRetractAggFunction[Double] { override def getInitValue: Double = 0.0d override def getValueTypeInfo = BasicTypeInfo.DOUBLE_TYPE_INFO } /** * Built-in Boolean Max with retraction aggregate function */ class BooleanMaxWithRetractAggFunction extends MaxWithRetractAggFunction[Boolean] { override def getInitValue: Boolean = false override def getValueTypeInfo = BasicTypeInfo.BOOLEAN_TYPE_INFO } /** * Built-in Big Decimal Max with retraction aggregate function */ class DecimalMaxWithRetractAggFunction extends MaxWithRetractAggFunction[BigDecimal] { override def getInitValue: BigDecimal = BigDecimal.ZERO override def getValueTypeInfo = BasicTypeInfo.BIG_DEC_TYPE_INFO } /** * Built-in String Max with retraction aggregate function */ class StringMaxWithRetractAggFunction extends MaxWithRetractAggFunction[String] { override def getInitValue: String = "" override def getValueTypeInfo = BasicTypeInfo.STRING_TYPE_INFO } /** * Built-in Timestamp Max with retraction aggregate function */ class TimestampMaxWithRetractAggFunction extends MaxWithRetractAggFunction[Timestamp] { override def getInitValue: Timestamp = new Timestamp(0) override def getValueTypeInfo = Types.SQL_TIMESTAMP } /** * Built-in Date Max with retraction aggregate function */ class DateMaxWithRetractAggFunction extends MaxWithRetractAggFunction[Date] { override def getInitValue: Date = new Date(0) override def getValueTypeInfo = Types.SQL_DATE } /** * Built-in Time Max with retraction aggregate function */ class TimeMaxWithRetractAggFunction extends MaxWithRetractAggFunction[Time] { override def getInitValue: Time = new Time(0) override def getValueTypeInfo = Types.SQL_TIME }
hequn8128/flink
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/functions/aggfunctions/MaxAggFunctionWithRetract.scala
Scala
apache-2.0
7,947
package slick.util import java.util /** A simplified copy of `java.util.concurrent.ArrayBlockingQueue` with additional logic for * temporarily rejecting elements based on the current size. All features of the original * ArrayBlockingQueue have been ported, except the mutation methods of the iterator. See * `java.util.concurrent.ArrayBlockingQueue` for documentation. */ private[util] final class InternalArrayQueue[E >: Null <: AnyRef](capacity: Int) { private[this] val items = new Array[AnyRef](capacity) private[this] var takeIndex, putIndex = 0 private[util] var count = 0 private[this] def checkNotNull(v: AnyRef): Unit = if (v == null) throw new NullPointerException private[this] def inc(i: Int): Int = if(i+1 == items.length) 0 else i+1 private[this] def itemAt(i: Int): E = items(i).asInstanceOf[E] private[util] def extract: E = { val items = this.items val x: E = items(takeIndex).asInstanceOf[E] items(takeIndex) = null takeIndex = inc(takeIndex) count -= 1 x } private[util] def insert(x: E): Boolean = { if (count == items.length) { false } else { items(putIndex) = x putIndex = inc(putIndex) count += 1 true } } private[this] def removeAt(_i: Int): Unit = { var i = _i val items = this.items if (i == takeIndex) { items(takeIndex) = null takeIndex = inc(takeIndex) } else { var cond = true while (cond) { val nexti: Int = inc(i) if (nexti != putIndex) { items(i) = items(nexti) i = nexti } else { items(i) = null putIndex = i cond = false } } } count -= 1 } private[util] def contains(o: AnyRef): Boolean = { if (o == null) return false val items = this.items var i = takeIndex var k = count while (k > 0) { if (o == items(i)) return true i = inc(i) k -= 1 } false } private[util] def remove(o: AnyRef): Boolean = if (o eq null) false else { val items = this.items var i: Int = takeIndex var k: Int = count while (k > 0) { if (o == items(i)) { removeAt(i) return true } i = inc(i) k -= 1 } false } def peek: E = if(count == 0) null else itemAt(takeIndex) private[util] def clear(): Unit = { val items = this.items var i = takeIndex var k = count while (k > 0) { items(i) = null i = inc(i) k -= 1 } count = 0 putIndex = 0 takeIndex = 0 } private[util] def drainTo(c: util.Collection[_ >: E]): Int = { checkNotNull(c) val items = this.items var i = takeIndex var n = 0 val max = count while (n < max) { c.add(items(i).asInstanceOf[E]) items(i) = null i = inc(i) n += 1 } if (n > 0) { count = 0 putIndex = 0 takeIndex = 0 } n } private[util] def drainTo(c: util.Collection[_ >: E], maxElements: Int): Int = { checkNotNull(c) if (maxElements <= 0) return 0 val items = this.items var i: Int = takeIndex var n: Int = 0 val max: Int = if (maxElements < count) maxElements else count while (n < max) { c.add(items(i).asInstanceOf[E]) items(i) = null i = inc(i) n += 1 } if (n > 0) { count -= n takeIndex = i } n } private[util] def iterator: util.Iterator[E] = new util.Iterator[E] { private var remaining: Int = _ private var nextIndex: Int = _ private var nextItem: E = _ private var lastItem: E = _ private var lastRet: Int = -1 remaining = count if(remaining > 0) { nextIndex = takeIndex nextItem = itemAt(nextIndex) } def hasNext: Boolean = remaining > 0 def next: E = { if (remaining <= 0) throw new NoSuchElementException lastRet = nextIndex var x: E = itemAt(nextIndex) if (x == null) { x = nextItem lastItem = null } else lastItem = x while ({ remaining -= 1; remaining > 0 } && { nextIndex = inc(nextIndex); nextItem = itemAt(nextIndex); nextItem == null }) () x } override def remove(): Unit = throw new UnsupportedOperationException } }
nafg/slick
slick/src/main/scala/slick/util/InternalArrayQueue.scala
Scala
bsd-2-clause
4,294
/** Copyright 2015 TappingStone, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prediction.e2.engine import org.apache.spark.SparkContext._ import org.apache.spark.mllib.linalg.distributed.CoordinateMatrix import org.apache.spark.mllib.linalg.{SparseVector, Vectors} import org.apache.spark.rdd.RDD /** * Class for training a Markov Chain model */ object MarkovChain { /** * Train a Markov Chain model * * @param matrix Tally of all state transitions * @param topN Use the top-N tally for each state */ def train(matrix: CoordinateMatrix, topN: Int): MarkovChainModel = { val noOfStates = matrix.numCols().toInt val transitionVectors = matrix.entries .keyBy(_.i.toInt) .groupByKey() .mapValues { rowEntries => val total = rowEntries.map(_.value).sum val sortedTopN = rowEntries.toSeq .sortBy(_.value)(Ordering.Double.reverse) .take(topN) .map(me => (me.j.toInt, me.value / total)) .sortBy(_._1) new SparseVector( noOfStates, sortedTopN.map(_._1).toArray, sortedTopN.map(_._2).toArray) } new MarkovChainModel( transitionVectors, topN) } } /** * Markov Chain model * * @param transitionVectors transition vectors * @param n top N used to construct the model */ case class MarkovChainModel( transitionVectors: RDD[(Int, SparseVector)], n: Int) { /** * Calculate the probabilities of the next state * * @param currentState probabilities of the current state */ def predict(currentState: Seq[Double]): Seq[Double] = { // multiply the input with transition matrix row by row val nextStateVectors = transitionVectors.map { case (rowIndex, vector) => val values = vector.indices.map { index => vector(index) * currentState(rowIndex) } Vectors.sparse(currentState.size, vector.indices, values) }.collect() // sum up to get the total probabilities (0 until currentState.size).map { index => nextStateVectors.map { vector => vector(index) }.sum } } }
ch33hau/PredictionIO
e2/src/main/scala/io/prediction/e2/engine/MarkovChain.scala
Scala
apache-2.0
2,640
package com.scalableminds.webknossos.tracingstore.tracings.volume import com.scalableminds.util.geometry.{BoundingBox, Vec3Int} import com.scalableminds.util.tools.Fox import com.scalableminds.webknossos.datastore.dataformats.{BucketProvider, MappingProvider} import com.scalableminds.webknossos.datastore.models.datasource.LayerViewConfiguration.LayerViewConfiguration import com.scalableminds.webknossos.datastore.models.datasource._ import com.scalableminds.webknossos.datastore.models.requests.DataReadInstruction import com.scalableminds.webknossos.datastore.storage.DataCubeCache import net.liftweb.common.{Empty, Failure, Full} import scala.concurrent.{ExecutionContext, Future} class FallbackBucketProvider(primary: DataLayer, fallback: DataLayer) extends BucketProvider { override def load(readInstruction: DataReadInstruction, cache: DataCubeCache)( implicit ec: ExecutionContext): Fox[Array[Byte]] = { val primaryReadInstruction = readInstruction.copy(dataLayer = primary) primary.bucketProvider.load(primaryReadInstruction, cache).futureBox.flatMap { case Full(data) => Fox.successful(data) case Empty => val fallbackReadInstruction = readInstruction.copy(dataLayer = fallback) fallback.bucketProvider.load(fallbackReadInstruction, cache) case f: Failure => Future.successful(f) } } } class FallbackLayerAdapter(primary: SegmentationLayer, fallback: SegmentationLayer) extends SegmentationLayer { val name: String = s"${primary.name}/${fallback.name}" lazy val boundingBox: BoundingBox = primary.boundingBox val resolutions: List[Vec3Int] = primary.resolutions.union(fallback.resolutions) val elementClass: ElementClass.Value = primary.elementClass val dataFormat: DataFormat.Value = DataFormat.tracing def lengthOfUnderlyingCubes(resolution: Vec3Int): Int = fallback.lengthOfUnderlyingCubes(resolution) val largestSegmentId: Long = math.max(primary.largestSegmentId, fallback.largestSegmentId) val mappings: Option[Set[String]] = primary.mappings lazy val bucketProvider: BucketProvider = new FallbackBucketProvider(primary, fallback) override lazy val mappingProvider: MappingProvider = fallback.mappingProvider val defaultViewConfiguration: Option[LayerViewConfiguration] = primary.defaultViewConfiguration val adminViewConfiguration: Option[LayerViewConfiguration] = primary.adminViewConfiguration }
scalableminds/webknossos
webknossos-tracingstore/app/com/scalableminds/webknossos/tracingstore/tracings/volume/FallbackLayerAdapter.scala
Scala
agpl-3.0
2,429
package com.eevolution.context.dictionary.infrastructure.repository import java.util.UUID import com.eevolution.context.dictionary.domain._ import com.eevolution.context.dictionary.domain.model.ModelValidator import com.eevolution.context.dictionary.infrastructure.db.DbContext._ import com.eevolution.utils.PaginatedSequence import com.lightbend.lagom.scaladsl.persistence.jdbc.JdbcSession import scala.concurrent.{ExecutionContext, Future} /** * Copyright (C) 2003-2017, e-Evolution Consultants S.A. , http://www.e-evolution.com * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * Email: [email protected], http://www.e-evolution.com , http://github.com/EmerisScala * Created by [email protected] , www.e-evolution.com on 07/11/17. */ /** * Model Validator Repository * @param session * @param executionContext */ class ModelValidatorRepository (session: JdbcSession)(implicit executionContext: ExecutionContext) extends api.repository.ModelValidatorRepository[ModelValidator , Int] with ModelValidatorMapping { def getById(id: Int): Future[ModelValidator] = { Future(run(queryModelValidator.filter(_.modelValidatorId == lift(id))).headOption.get) } def getByUUID(uuid: UUID): Future[ModelValidator] = { Future(run(queryModelValidator.filter(_.uuid == lift(uuid.toString))).headOption.get) } def getByModelValidatorId(id : Int) : Future[List[ModelValidator]] = { Future(run(queryModelValidator)) } def getAll() : Future[List[ModelValidator]] = { Future(run(queryModelValidator)) } def getAllByPage(page: Int, pageSize: Int): Future[PaginatedSequence[ModelValidator]] = { val offset = page * pageSize val limit = (page + 1) * pageSize for { count <- countModelValidator() elements <- if (offset > count) Future.successful(Nil) else selectModelValidator(offset, limit) } yield { PaginatedSequence(elements, page, pageSize, count) } } private def countModelValidator() = { Future(run(queryModelValidator.size).toInt) } private def selectModelValidator(offset: Int, limit: Int): Future[Seq[ModelValidator]] = { Future(run(queryModelValidator).drop(offset).take(limit).toSeq) } }
adempiere/ADReactiveSystem
dictionary-impl/src/main/scala/com/eevolution/context/dictionary/infrastructure/repository/ModelValidatorRepository.scala
Scala
gpl-3.0
2,838
/*********************************************************************** * Copyright (c) 2013-2018 Commonwealth Computer Research, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at * http://www.opensource.org/licenses/apache2.0.php. ***********************************************************************/ package org.locationtech.geomesa.kudu.spark import java.io.{ByteArrayInputStream, ByteArrayOutputStream, DataInputStream, DataOutputStream} import org.apache.hadoop.mapreduce.Job import org.geotools.data.Query import org.junit.runner.RunWith import org.locationtech.geomesa.kudu.spark.GeoMesaKuduInputFormat.GeoMesaKuduInputSplit import org.specs2.mutable.Specification import org.specs2.runner.JUnitRunner @RunWith(classOf[JUnitRunner]) class GeoMesaKuduInputFormatTest extends Specification { import scala.collection.JavaConverters._ skipAll // integration val params = Map( "kudu.master" -> "localhost", "kudu.catalog" -> "geomesa", "geomesa.security.auths" -> "admin" ) "GeoMesaKuduInputFormat" should { "create writable splits" in { val job = Job.getInstance() GeoMesaKuduInputFormat.configure(job.getConfiguration, params, new Query("testpoints")) val input = new GeoMesaKuduInputFormat() input.setConf(job.getConfiguration) val splits = input.getSplits(job).asScala splits must not(beEmpty) foreach(splits) { split => val out = new ByteArrayOutputStream() split.asInstanceOf[GeoMesaKuduInputSplit].write(new DataOutputStream(out)) out.flush() val in = new ByteArrayInputStream(out.toByteArray) val recovered = new GeoMesaKuduInputSplit() recovered.readFields(new DataInputStream(in)) recovered mustEqual split } } } }
ddseapy/geomesa
geomesa-kudu/geomesa-kudu-spark/src/test/scala/org/locationtech/geomesa/kudu/spark/GeoMesaKuduInputFormatTest.scala
Scala
apache-2.0
1,957
package bitcoin import java.time.Instant import bitcoin.JsonProtocol._ import org.scalatest.concurrent.ScalaFutures import org.scalatest.{FlatSpec, Matchers} import streams.AkkaStreamsTest import spray.json._ class JsonProtocolSpec extends FlatSpec with AkkaStreamsTest with Matchers with ScalaFutures { "format" should "serialize OHLCV" in { val trade = Trade(Instant.now(), 100, 200) val ohlcv = OHLCV(trade) val json = ohlcv.toJson println(s"json:\\n$json") } }
linearregression/akka-streams-http-intro
src/test/scala/bitcoin/JsonProtocolSpec.scala
Scala
apache-2.0
494
/* NSC -- new Scala compiler * Copyright 2005-2012 LAMP/EPFL * @author Martin Odersky */ package dotty.tools.dotc package backend.jvm import dotty.tools.backend.jvm.GenBCodePipeline import dotty.tools.dotc.ast.Trees.Select import dotty.tools.dotc.ast.tpd._ import dotty.tools.dotc.core.Names.TermName import dotty.tools.dotc.core.StdNames import dotty.tools.dotc.core.StdNames._ import dotty.tools.dotc.core.Types.{JavaArrayType, ErrorType, Type} import scala.collection.{ mutable, immutable } import core.Contexts.Context import core.Symbols.{Symbol, NoSymbol} /** Scala primitive operations are represented as methods in `Any` and * `AnyVal` subclasses. Here we demultiplex them by providing a mapping * from their symbols to integers. Different methods exist for * different value types, but with the same meaning (like plus, minus, * etc.). They will all be mapped to the same int. * * Note: The three equal methods have the following semantics: * - `"=="` checks for `null`, and if non-null, calls * `java.lang.Object.equals` * `(class: Any; modifier: final)`. Primitive: `EQ` * - `"eq"` usual reference comparison * `(class: AnyRef; modifier: final)`. Primitive: `ID` * - `"equals"` user-defined equality (Java semantics) * `(class: Object; modifier: none)`. Primitive: `EQUALS` * * Inspired from the `scalac` compiler. */ class DottyPrimitives(ctx: Context) { import scala.tools.nsc.backend.ScalaPrimitives._ private lazy val primitives: immutable.Map[Symbol, Int] = init /** Return the code for the given symbol. */ def getPrimitive(sym: Symbol): Int = { primitives(sym) } /** * Return the primitive code of the given operation. If the * operation is an array get/set, we inspect the type of the receiver * to demux the operation. * * @param fun The method symbol * @param tpe The type of the receiver object. It is used only for array * operations */ def getPrimitive(app: Apply, tpe: Type)(implicit ctx: Context): Int = { val fun = app.fun.symbol val defn = ctx.definitions val code = app.fun match { case Select(_, nme.primitive.arrayLength) => LENGTH case Select(_, nme.primitive.arrayUpdate) => UPDATE case Select(_, nme.primitive.arrayApply) => APPLY case _ => getPrimitive(fun) } def elementType: Type = tpe.widenDealias match { case defn.ArrayType(el) => el case JavaArrayType(el) => el case _ => ctx.error(s"expected Array $tpe") ErrorType } code match { case APPLY => elementType.classSymbol match { case defn.BooleanClass => ZARRAY_GET case defn.ByteClass => BARRAY_GET case defn.ShortClass => SARRAY_GET case defn.CharClass => CARRAY_GET case defn.IntClass => IARRAY_GET case defn.LongClass => LARRAY_GET case defn.FloatClass => FARRAY_GET case defn.DoubleClass => DARRAY_GET case _ => OARRAY_GET } case UPDATE => elementType.classSymbol match { case defn.BooleanClass => ZARRAY_SET case defn.ByteClass => BARRAY_SET case defn.ShortClass => SARRAY_SET case defn.CharClass => CARRAY_SET case defn.IntClass => IARRAY_SET case defn.LongClass => LARRAY_SET case defn.FloatClass => FARRAY_SET case defn.DoubleClass => DARRAY_SET case _ => OARRAY_SET } case LENGTH => elementType.classSymbol match { case defn.BooleanClass => ZARRAY_LENGTH case defn.ByteClass => BARRAY_LENGTH case defn.ShortClass => SARRAY_LENGTH case defn.CharClass => CARRAY_LENGTH case defn.IntClass => IARRAY_LENGTH case defn.LongClass => LARRAY_LENGTH case defn.FloatClass => FARRAY_LENGTH case defn.DoubleClass => DARRAY_LENGTH case _ => OARRAY_LENGTH } case _ => code } } /** Initialize the primitive map */ private def init: immutable.Map[Symbol, Int] = { implicit val ctx = this.ctx import core.Symbols.defn val primitives = new mutable.HashMap[Symbol, Int]() /** Add a primitive operation to the map */ def addPrimitive(s: Symbol, code: Int): Unit = { assert(!(primitives contains s), "Duplicate primitive " + s) primitives(s) = code } def addPrimitives(cls: Symbol, method: TermName, code: Int)(implicit ctx: Context): Unit = { val alts = cls.info.member(method).alternatives.map(_.symbol) if (alts.isEmpty) ctx.error(s"Unknown primitive method $cls.$method") else alts foreach (s => addPrimitive(s, s.info.paramTypess match { case List(tp :: _) if code == ADD && tp =:= ctx.definitions.StringType => CONCAT case _ => code } ) ) } // scala.Any addPrimitive(defn.Any_==, EQ) addPrimitive(defn.Any_!=, NE) addPrimitive(defn.Any_isInstanceOf, IS) addPrimitive(defn.Any_asInstanceOf, AS) addPrimitive(defn.Any_##, HASH) // java.lang.Object addPrimitive(defn.Object_eq, ID) addPrimitive(defn.Object_ne, NI) /* addPrimitive(defn.Any_==, EQ) addPrimitive(defn.Any_!=, NE)*/ addPrimitive(defn.Object_synchronized, SYNCHRONIZED) /*addPrimitive(defn.Any_isInstanceOf, IS) addPrimitive(defn.Any_asInstanceOf, AS)*/ // java.lang.String addPrimitive(defn.String_+, CONCAT) import core.StdNames.nme // scala.Array lazy val ArrayClass = defn.ArrayClass addPrimitives(ArrayClass, nme.length, LENGTH) addPrimitives(ArrayClass, nme.apply, APPLY) addPrimitives(ArrayClass, nme.update, UPDATE) // scala.Boolean lazy val BooleanClass = defn.BooleanClass addPrimitives(BooleanClass, nme.EQ, EQ) addPrimitives(BooleanClass, nme.NE, NE) addPrimitives(BooleanClass, nme.UNARY_!, ZNOT) addPrimitives(BooleanClass, nme.ZOR, ZOR) addPrimitives(BooleanClass, nme.ZAND, ZAND) addPrimitives(BooleanClass, nme.OR, OR) addPrimitives(BooleanClass, nme.AND, AND) addPrimitives(BooleanClass, nme.XOR, XOR) // scala.Byte lazy val ByteClass = defn.ByteClass addPrimitives(ByteClass, nme.EQ, EQ) addPrimitives(ByteClass, nme.NE, NE) addPrimitives(ByteClass, nme.ADD, ADD) addPrimitives(ByteClass, nme.SUB, SUB) addPrimitives(ByteClass, nme.MUL, MUL) addPrimitives(ByteClass, nme.DIV, DIV) addPrimitives(ByteClass, nme.MOD, MOD) addPrimitives(ByteClass, nme.LT, LT) addPrimitives(ByteClass, nme.LE, LE) addPrimitives(ByteClass, nme.GT, GT) addPrimitives(ByteClass, nme.GE, GE) addPrimitives(ByteClass, nme.XOR, XOR) addPrimitives(ByteClass, nme.OR, OR) addPrimitives(ByteClass, nme.AND, AND) addPrimitives(ByteClass, nme.LSL, LSL) addPrimitives(ByteClass, nme.LSR, LSR) addPrimitives(ByteClass, nme.ASR, ASR) // conversions addPrimitives(ByteClass, nme.toByte, B2B) addPrimitives(ByteClass, nme.toShort, B2S) addPrimitives(ByteClass, nme.toChar, B2C) addPrimitives(ByteClass, nme.toInt, B2I) addPrimitives(ByteClass, nme.toLong, B2L) // unary methods addPrimitives(ByteClass, nme.UNARY_+, POS) addPrimitives(ByteClass, nme.UNARY_-, NEG) addPrimitives(ByteClass, nme.UNARY_~, NOT) addPrimitives(ByteClass, nme.toFloat, B2F) addPrimitives(ByteClass, nme.toDouble, B2D) // scala.Short lazy val ShortClass = defn.ShortClass addPrimitives(ShortClass, nme.EQ, EQ) addPrimitives(ShortClass, nme.NE, NE) addPrimitives(ShortClass, nme.ADD, ADD) addPrimitives(ShortClass, nme.SUB, SUB) addPrimitives(ShortClass, nme.MUL, MUL) addPrimitives(ShortClass, nme.DIV, DIV) addPrimitives(ShortClass, nme.MOD, MOD) addPrimitives(ShortClass, nme.LT, LT) addPrimitives(ShortClass, nme.LE, LE) addPrimitives(ShortClass, nme.GT, GT) addPrimitives(ShortClass, nme.GE, GE) addPrimitives(ShortClass, nme.XOR, XOR) addPrimitives(ShortClass, nme.OR, OR) addPrimitives(ShortClass, nme.AND, AND) addPrimitives(ShortClass, nme.LSL, LSL) addPrimitives(ShortClass, nme.LSR, LSR) addPrimitives(ShortClass, nme.ASR, ASR) // conversions addPrimitives(ShortClass, nme.toByte, S2B) addPrimitives(ShortClass, nme.toShort, S2S) addPrimitives(ShortClass, nme.toChar, S2C) addPrimitives(ShortClass, nme.toInt, S2I) addPrimitives(ShortClass, nme.toLong, S2L) // unary methods addPrimitives(ShortClass, nme.UNARY_+, POS) addPrimitives(ShortClass, nme.UNARY_-, NEG) addPrimitives(ShortClass, nme.UNARY_~, NOT) addPrimitives(ShortClass, nme.toFloat, S2F) addPrimitives(ShortClass, nme.toDouble, S2D) // scala.Char lazy val CharClass = defn.CharClass addPrimitives(CharClass, nme.EQ, EQ) addPrimitives(CharClass, nme.NE, NE) addPrimitives(CharClass, nme.ADD, ADD) addPrimitives(CharClass, nme.SUB, SUB) addPrimitives(CharClass, nme.MUL, MUL) addPrimitives(CharClass, nme.DIV, DIV) addPrimitives(CharClass, nme.MOD, MOD) addPrimitives(CharClass, nme.LT, LT) addPrimitives(CharClass, nme.LE, LE) addPrimitives(CharClass, nme.GT, GT) addPrimitives(CharClass, nme.GE, GE) addPrimitives(CharClass, nme.XOR, XOR) addPrimitives(CharClass, nme.OR, OR) addPrimitives(CharClass, nme.AND, AND) addPrimitives(CharClass, nme.LSL, LSL) addPrimitives(CharClass, nme.LSR, LSR) addPrimitives(CharClass, nme.ASR, ASR) // conversions addPrimitives(CharClass, nme.toByte, C2B) addPrimitives(CharClass, nme.toShort, C2S) addPrimitives(CharClass, nme.toChar, C2C) addPrimitives(CharClass, nme.toInt, C2I) addPrimitives(CharClass, nme.toLong, C2L) // unary methods addPrimitives(CharClass, nme.UNARY_+, POS) addPrimitives(CharClass, nme.UNARY_-, NEG) addPrimitives(CharClass, nme.UNARY_~, NOT) addPrimitives(CharClass, nme.toFloat, C2F) addPrimitives(CharClass, nme.toDouble, C2D) // scala.Int lazy val IntClass = defn.IntClass addPrimitives(IntClass, nme.EQ, EQ) addPrimitives(IntClass, nme.NE, NE) addPrimitives(IntClass, nme.ADD, ADD) addPrimitives(IntClass, nme.SUB, SUB) addPrimitives(IntClass, nme.MUL, MUL) addPrimitives(IntClass, nme.DIV, DIV) addPrimitives(IntClass, nme.MOD, MOD) addPrimitives(IntClass, nme.LT, LT) addPrimitives(IntClass, nme.LE, LE) addPrimitives(IntClass, nme.GT, GT) addPrimitives(IntClass, nme.GE, GE) addPrimitives(IntClass, nme.XOR, XOR) addPrimitives(IntClass, nme.OR, OR) addPrimitives(IntClass, nme.AND, AND) addPrimitives(IntClass, nme.LSL, LSL) addPrimitives(IntClass, nme.LSR, LSR) addPrimitives(IntClass, nme.ASR, ASR) // conversions addPrimitives(IntClass, nme.toByte, I2B) addPrimitives(IntClass, nme.toShort, I2S) addPrimitives(IntClass, nme.toChar, I2C) addPrimitives(IntClass, nme.toInt, I2I) addPrimitives(IntClass, nme.toLong, I2L) // unary methods addPrimitives(IntClass, nme.UNARY_+, POS) addPrimitives(IntClass, nme.UNARY_-, NEG) addPrimitives(IntClass, nme.UNARY_~, NOT) addPrimitives(IntClass, nme.toFloat, I2F) addPrimitives(IntClass, nme.toDouble, I2D) // scala.Long lazy val LongClass = defn.LongClass addPrimitives(LongClass, nme.EQ, EQ) addPrimitives(LongClass, nme.NE, NE) addPrimitives(LongClass, nme.ADD, ADD) addPrimitives(LongClass, nme.SUB, SUB) addPrimitives(LongClass, nme.MUL, MUL) addPrimitives(LongClass, nme.DIV, DIV) addPrimitives(LongClass, nme.MOD, MOD) addPrimitives(LongClass, nme.LT, LT) addPrimitives(LongClass, nme.LE, LE) addPrimitives(LongClass, nme.GT, GT) addPrimitives(LongClass, nme.GE, GE) addPrimitives(LongClass, nme.XOR, XOR) addPrimitives(LongClass, nme.OR, OR) addPrimitives(LongClass, nme.AND, AND) addPrimitives(LongClass, nme.LSL, LSL) addPrimitives(LongClass, nme.LSR, LSR) addPrimitives(LongClass, nme.ASR, ASR) // conversions addPrimitives(LongClass, nme.toByte, L2B) addPrimitives(LongClass, nme.toShort, L2S) addPrimitives(LongClass, nme.toChar, L2C) addPrimitives(LongClass, nme.toInt, L2I) addPrimitives(LongClass, nme.toLong, L2L) // unary methods addPrimitives(LongClass, nme.UNARY_+, POS) addPrimitives(LongClass, nme.UNARY_-, NEG) addPrimitives(LongClass, nme.UNARY_~, NOT) addPrimitives(LongClass, nme.toFloat, L2F) addPrimitives(LongClass, nme.toDouble, L2D) // scala.Float lazy val FloatClass = defn.FloatClass addPrimitives(FloatClass, nme.EQ, EQ) addPrimitives(FloatClass, nme.NE, NE) addPrimitives(FloatClass, nme.ADD, ADD) addPrimitives(FloatClass, nme.SUB, SUB) addPrimitives(FloatClass, nme.MUL, MUL) addPrimitives(FloatClass, nme.DIV, DIV) addPrimitives(FloatClass, nme.MOD, MOD) addPrimitives(FloatClass, nme.LT, LT) addPrimitives(FloatClass, nme.LE, LE) addPrimitives(FloatClass, nme.GT, GT) addPrimitives(FloatClass, nme.GE, GE) // conversions addPrimitives(FloatClass, nme.toByte, F2B) addPrimitives(FloatClass, nme.toShort, F2S) addPrimitives(FloatClass, nme.toChar, F2C) addPrimitives(FloatClass, nme.toInt, F2I) addPrimitives(FloatClass, nme.toLong, F2L) addPrimitives(FloatClass, nme.toFloat, F2F) addPrimitives(FloatClass, nme.toDouble, F2D) // unary methods addPrimitives(FloatClass, nme.UNARY_+, POS) addPrimitives(FloatClass, nme.UNARY_-, NEG) // scala.Double lazy val DoubleClass = defn.DoubleClass addPrimitives(DoubleClass, nme.EQ, EQ) addPrimitives(DoubleClass, nme.NE, NE) addPrimitives(DoubleClass, nme.ADD, ADD) addPrimitives(DoubleClass, nme.SUB, SUB) addPrimitives(DoubleClass, nme.MUL, MUL) addPrimitives(DoubleClass, nme.DIV, DIV) addPrimitives(DoubleClass, nme.MOD, MOD) addPrimitives(DoubleClass, nme.LT, LT) addPrimitives(DoubleClass, nme.LE, LE) addPrimitives(DoubleClass, nme.GT, GT) addPrimitives(DoubleClass, nme.GE, GE) // conversions addPrimitives(DoubleClass, nme.toByte, D2B) addPrimitives(DoubleClass, nme.toShort, D2S) addPrimitives(DoubleClass, nme.toChar, D2C) addPrimitives(DoubleClass, nme.toInt, D2I) addPrimitives(DoubleClass, nme.toLong, D2L) addPrimitives(DoubleClass, nme.toFloat, D2F) addPrimitives(DoubleClass, nme.toDouble, D2D) // unary methods addPrimitives(DoubleClass, nme.UNARY_+, POS) addPrimitives(DoubleClass, nme.UNARY_-, NEG) primitives.toMap } def isPrimitive(fun: Tree): Boolean = { (primitives contains fun.symbol(ctx)) || (fun.symbol(ctx) == NoSymbol // the only trees that do not have a symbol assigned are array.{update,select,length,clone}} && (fun match { case Select(_, StdNames.nme.clone_) => false // but array.clone is NOT a primitive op. case _ => true })) } }
AlexSikia/dotty
src/dotty/tools/backend/jvm/scalaPrimitives.scala
Scala
bsd-3-clause
15,369
package com.yetu.play.authenticator.utils import com.mohiva.play.silhouette.impl.authenticators.SessionAuthenticator import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll} import org.scalatest.concurrent.{AsyncAssertions, ScalaFutures} import org.scalatestplus.play.{OneAppPerSuite, PlaySpec} import play.api.libs.json.{JsNull, JsValue} import play.api.mvc.{AnyContentAsEmpty, Result} import play.api.test.Helpers._ import play.api.test.{FakeApplication, FakeHeaders, FakeRequest} // used for the withAuthenticator and fake login information as specified in the FakeGlobal import com.mohiva.play.silhouette.api.Logger import com.mohiva.play.silhouette.test.FakeRequestWithAuthenticator import scala.concurrent.Future class BaseSpec extends PlaySpec with ScalaFutures with AsyncAssertions with OneAppPerSuite with Logger with TestData with BeforeAndAfterAll with BeforeAndAfter { def log(s: String) = logger.debug(s) def getRequestAuthenticated(url: String, headers: FakeHeaders = FakeHeaders()): Future[Result] = { route(FakeRequest(GET, url, headers, AnyContentAsEmpty).withAuthenticator[SessionAuthenticator](FakeGlobal.identity.loginInfo)(FakeGlobal.env) ) match { case Some(response) => log(s"content $url: ${contentAsString(response)}") log(s"status $url: ${status(response)}") redirectLocation(response).map { location => log(s"redirectLocation of $url: $location") } response case None => throw new Exception(s"The url '$url' is not valid.") } } def postRequestAuthenticated(url: String, parameters: JsValue = JsNull, fakeHeaders: FakeHeaders = FakeHeaders()): Future[Result] = { route(FakeRequest(POST, url, fakeHeaders, parameters) .withAuthenticator[SessionAuthenticator](FakeGlobal.identity.loginInfo)(FakeGlobal.env)) match { case Some(response) => log(s"response: ${contentAsString(response)}") log(s"response status: ${status(response)}") log(s"response location: ${header("Location", response)}") log(s"response headers: ${headers(response)}") response case None => throw new Exception(s"The url '$url' is not valid.") } } //for all tests, use the FakeGlobal with Authentication mocked out. implicit override lazy val app: FakeApplication = FakeApplication(withGlobal = Some(new FakeGlobal)) }
yetu/yetu-play-authenticator
test/com/yetu/play/authenticator/utils/BaseSpec.scala
Scala
apache-2.0
2,383
package com.esri import com.esri.hex.HexGrid import com.esri.webmercator._ import com.vividsolutions.jts.geom.{GeometryFactory, PrecisionModel} import com.vividsolutions.jts.io.WKTReader import org.apache.spark.sql.SparkSession import org.apache.spark.sql.catalyst.ScalaReflection import org.apache.spark.sql.catalyst.util.ParseModes import org.apache.spark.sql.types.StructType object HexApp extends App { val spark = SparkSession .builder() .appName("Hex App") .master("local[*]") .config("spark.ui.enabled", "false") .getOrCreate() import spark.implicits._ try { val conf = spark.sparkContext.getConf val schema = ScalaReflection.schemaFor[Broadcast].dataType.asInstanceOf[StructType] val size = conf.getInt("spark.app.size.meters", 200) spark .read .format("csv") .option("delimiter", conf.get("spark.app.input.delimiter", "\\t")) .option("header", conf.getBoolean("spark.app.input.header", true)) .option("mode", ParseModes.DROP_MALFORMED_MODE) .option("timestampFormat", conf.get("spark.app.input.timestampFormat", "yyyy-MM-dd HH:mm:ss")) .schema(schema) .load(conf.get("spark.app.input.path", "alluxio://localhost:19998/Broadcast.csv")) .as[Broadcast] .mapPartitions(iter => { val reader = new WKTReader(new GeometryFactory(new PrecisionModel(1000000.0))) iter.map(line => { val geom = reader.read(line.wkt) val coord = geom.getCoordinate BroadcastRow(line, coord.x, coord.y) }) }) .createTempView("BROADCASTS") spark.sqlContext.udf.register("toX", (d: Double) => { d toMercatorX }) spark.sqlContext.udf.register("toY", (d: Double) => { d toMercatorY }) val hexGrid = HexGrid(size, -20000000.0, -20000000.0) spark.sqlContext.udf.register("hex", (x: Double, y: Double) => { hexGrid.convertXYToRowCol(x, y).toLong }) spark.sql("select hex,count(hex) as pop from" + "(select hex(toX(lon),toY(lat)) as hex from BROADCASTS where status=0)" + "group by hex") .repartition(conf.getInt("spark.app.output.repartition", 8)) .write .format("csv") .save(conf.get("com.esri.output.path", s"alluxio://localhost:19998/hex$size")) } finally { spark.stop() } }
mraad/arcgis-alluxio
src/main/scala/com/esri/HexApp.scala
Scala
apache-2.0
2,325
package com.webtrends.harness.utils import scala.concurrent.{ExecutionContext, Future, Promise} import scala.util.Try object FutureExtensions { implicit class FutureExtensions[T](f: Future[T]) { // Allows you to map over futures and handle both Success and Failure scenarios in a partial function. // // For example: // val f: Future[_] = .... // f.mapAll { // case Success(...) => ... // case Failure(t) => ... // } def mapAll[Target](m: Try[T] => Target)(implicit ec: ExecutionContext): Future[Target] = { val p = Promise[Target]() f.onComplete { r => try { p success m(r) } catch { case ex: Exception => p failure(ex) }}(ec) p.future } // Allows you to flatMap over futures and handle both Success and Failure scenarios in a partial function. // // For example: // val f: Future[_] = .... // f.flatMapAll { // case Success(...) => ... // case Failure(t) => ... // } def flatMapAll[Target](m: Try[T] => Future[Target])(implicit ec: ExecutionContext): Future[Target] = { val p = Promise[Target]() f.onComplete { r => try { m(r).onComplete { z => p complete z }(ec) }catch { case ex: Exception => p failure(ex) } }(ec) p.future } } }
Webtrends/wookiee
wookiee-core/src/main/scala/com/webtrends/harness/utils/FutureExtensions.scala
Scala
apache-2.0
1,414
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark import java.lang.Long import org.apache.spark.deploy.SparkHadoopUtil import org.apache.spark.executor.InputMetrics import org.apache.spark.sql.execution.vectorized.ColumnarBatch import org.apache.carbondata.common.logging.LogServiceFactory import org.apache.carbondata.core.util.TaskMetricsMap import org.apache.carbondata.hadoop.CarbonMultiBlockSplit import org.apache.carbondata.spark.InitInputMetrics /** * It gives statistics of number of bytes and record read */ class CarbonInputMetrics extends InitInputMetrics{ @transient val LOGGER = LogServiceFactory.getLogService(this.getClass.getName) var inputMetrics: InputMetrics = _ // bytes read before compute by other map rdds in lineage var existingBytesRead: Long = _ var carbonMultiBlockSplit: CarbonMultiBlockSplit = _ def initBytesReadCallback(context: TaskContext, carbonMultiBlockSplit: CarbonMultiBlockSplit) { inputMetrics = context.taskMetrics().inputMetrics existingBytesRead = inputMetrics.bytesRead this.carbonMultiBlockSplit = carbonMultiBlockSplit; } def incrementRecordRead(recordRead: Long) { val value : scala.Long = recordRead inputMetrics.incRecordsRead(value) if (inputMetrics.recordsRead % SparkHadoopUtil.UPDATE_INPUT_METRICS_INTERVAL_RECORDS == 0) { updateBytesRead() } } def updateBytesRead(): Unit = { inputMetrics .setBytesRead(existingBytesRead + TaskMetricsMap.getInstance().getReadBytesSum(Thread.currentThread().getId)) } def updateAndClose() { // if metrics supported file system ex: hdfs if (!TaskMetricsMap.getInstance().isCallbackEmpty(Thread.currentThread().getId)) { updateBytesRead() // after update clear parent thread entry from map. TaskMetricsMap.getInstance().removeEntry(Thread.currentThread().getId) } else if (carbonMultiBlockSplit.isInstanceOf[CarbonMultiBlockSplit]) { // If we can't get the bytes read from the FS stats, fall back to the split size, // which may be inaccurate. try { inputMetrics.incBytesRead(carbonMultiBlockSplit.getLength) } catch { case e: java.io.IOException => LOGGER.warn("Unable to get input size to set InputMetrics for task:" + e.getMessage) } } } override def updateByValue(value: Object): Unit = { } }
jatin9896/incubator-carbondata
integration/spark2/src/main/scala/org/apache/spark/CarbonInputMetrics.scala
Scala
apache-2.0
3,169
package akka.persistence.hazelcast.journal import akka.persistence.CapabilityFlag import akka.persistence.journal.JournalSpec import com.typesafe.config.ConfigFactory class HazelcastJournalSpec extends JournalSpec(ConfigFactory.load()) { override protected def supportsRejectingNonSerializableObjects: CapabilityFlag = true }
dlisin/akka-persistence-hazelcast
src/test/scala/akka/persistence/hazelcast/journal/HazelcastJournalSpec.scala
Scala
apache-2.0
330
package spire package algebra trait EuclideanRing[@sp(Byte, Short, Int, Long, Float, Double) A] extends Any with CRing[A] { def quot(a: A, b: A): A def mod(a: A, b: A): A def quotmod(a: A, b: A): (A, A) = (quot(a, b), mod(a, b)) def gcd(a: A, b: A): A def lcm(a: A, b: A): A = times(quot(a, gcd(a, b)), b) @tailrec protected[this] final def euclid(a: A, b: A)(implicit eq: Eq[A]): A = if (eq.eqv(b, zero)) a else euclid(b, mod(a, b)) } object EuclideanRing { @inline final def apply[A](implicit e: EuclideanRing[A]): EuclideanRing[A] = e }
rklaehn/spire
core/shared/src/main/scala/spire/algebra/EuclideanRing.scala
Scala
mit
562
/* * La Trobe University - Distributed Deep Learning System * Copyright 2016 Matthias Langer ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package edu.latrobe.io.showoff import edu.latrobe._ import edu.latrobe.io._ import java.io.BufferedInputStream import org.apache.http.client.methods._ import org.apache.http.entity._ import org.json4s.JsonAST._ import org.json4s.StreamInput import org.json4s.jackson.JsonMethods import scala.collection._ final class Notebook(val id: Long) { // Clear the current notebook. def clear() : Unit = { frames.clear() val req = new HttpDelete( s"http://$LTU_IO_SHOWOFF_HOST_ADDRESS:$LTU_IO_SHOWOFF_HOST_PORT/api/notebook/$id/frames" ) try { // HTTP Client >= 4.3 => using(HttpClient.default.execute(req))(rsp => { val rsp = HttpClient.default.execute(req) if (logger.isInfoEnabled) { logger.info(s"Showoff[$id]: Clear => ${rsp.getStatusLine}") } } catch { case e: Exception => logger.error(s"Showoff[$id] Clear => $e") } finally { req.abort() } } // TODO: Overload right interfaces and use set. private val frames : mutable.Map[String, Frame] = mutable.Map.empty def getOrCreateFrame(handle: String) : Frame = synchronized { frames.getOrElseUpdate(handle, { // Create json request. val json = { val tmp = JObject( Json.field( "frame", Json.field("notebookId", id), Json.field("type", "text"), Json.field("title", s"New Frame - $handle"), Json.field( "content", Json.field("body", "No data present!") ) ) ) JsonMethods.compact(tmp) } logger.trace(json) // Post it. val req = new HttpPost( s"http://$LTU_IO_SHOWOFF_HOST_ADDRESS:$LTU_IO_SHOWOFF_HOST_PORT/api/frame" ) req.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)) // Retrieve ID. try { // HTTP Client >= 4.3 => using(HttpClient.default.execute(req))(rsp => { val rsp = HttpClient.default.execute(req) if (logger.isInfoEnabled) { logger.info(s"Showoff[]: Created frame => ${rsp.getStatusLine}") } val json = using( new BufferedInputStream(rsp.getEntity.getContent) )(stream => JsonMethods.parse(StreamInput(stream))) // Get frame ID. val fields = json.asInstanceOf[JObject].obj.toMap val id = Json.toLong(fields("id")) if (logger.isInfoEnabled) { logger.info(s"Showoff[]: Frame ID = $id") } Frame(this, id) } catch { case e: Exception => logger.error(s"Showoff | Error = $e") Frame(this, -1L) } finally { req.abort() } }) } } object Notebook { final private val notebooks : mutable.Map[Int, Notebook] = mutable.Map.empty final def get(agentNo: Int) : Notebook = notebooks.getOrElseUpdate(agentNo, { // Create json request. val json = { val tmp = JObject( Json.field( "notebook", Json.field("title", s"${Host.name} #$agentNo") ) ) JsonMethods.compact(tmp) } logger.trace(json) // Post it. val req = new HttpPost( s"http://$LTU_IO_SHOWOFF_HOST_ADDRESS:$LTU_IO_SHOWOFF_HOST_PORT/api/notebook" ) req.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)) // Get notebook ID. val id = try { // HTTP Client >= 4.3 => using(HttpClient.default.execute(req))(rsp => { val rsp = HttpClient.default.execute(req) if (logger.isInfoEnabled) { logger.info(s"Showoff[] Create Notebook => ${rsp.getStatusLine}") } val json = using( new BufferedInputStream(rsp.getEntity.getContent) )(stream => JsonMethods.parse(StreamInput(stream))) val fields = json.asInstanceOf[JObject].obj.toMap Json.toLong(fields("id")) } catch { case e: Exception => logger.error(s"Showoff[] Create Notebook => $e") -1L } finally { req.abort() } // Create the notebook. if (logger.isInfoEnabled) { logger.info(s"Showoff[] Notebook ID is $id") } new Notebook(id) }) }
bashimao/ltudl
base/src/main/scala/edu/latrobe/io/showoff/Notebook.scala
Scala
apache-2.0
4,866
package com.codesimples.jpa import javax.sql.DataSource import com.typesafe.config.Config import org.springframework.jdbc.datasource.DriverManagerDataSource object DataSourceBuilder { def buildDataSourceWith(config:Config): DataSource = { val dataSourceOrigin: DriverManagerDataSource = new DriverManagerDataSource(); dataSourceOrigin.setDriverClassName( config.getString("driver") ); dataSourceOrigin.setUrl( config.getString("url") ); dataSourceOrigin.setUsername( config.getString("username") ); dataSourceOrigin.setPassword( config.getString("password") ); dataSourceOrigin } }
agnaldo4j/estudos_arquitetura_limpa_scala
planner-jpa/src/main/scala/com/codesimples/jpa/DataSourceBuilder.scala
Scala
mit
613
/* * (c) Copyright 2016 Hewlett Packard Enterprise Development LP * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package toolkit.neuralnetwork.function import libcog._ import toolkit.neuralnetwork.DifferentiableField import toolkit.neuralnetwork.DifferentiableField.GradientPort /** A convolutional transformation that applies a filter bank to a signal in the space domain. * * @author Matthew Pickett and Dick Carter * @param input The signal node * @param weights The filter bank input, typically a TrainableState field * @param stride The factor by which the output with be downsampled after the BorderValid convolution */ class SpatialConvolution private[SpatialConvolution] (input: DifferentiableField, weights: DifferentiableField, border: BorderPolicy, stride: Int) extends DifferentiableField { val supportedBorders = Seq(BorderValid, BorderZero) require(supportedBorders.contains(border), s"border policy $border not supported, must be one of: ${supportedBorders.mkString(", ")}.") require(weights.batchSize == 1, s"weights must have a batch size of 1, got ${weights.batchSize}") private val x1 = (input.forward, input.batchSize) private val x2 = (weights.forward, weights.batchSize) override val batchSize: Int = input.batchSize override val forward: Field = _forward(x1, x2)._1 override val inputs: Map[Symbol, GradientPort] = Map( 'input -> GradientPort(input, dx1 => jacobian1(dx1, x1, x2), grad => jacobianAdjoint1(grad, x1, x2)), 'weights -> GradientPort(weights, dx2 => jacobian2(dx2, x1, x2), grad => jacobianAdjoint2(grad, x1, x2))) private def _forward(x1: (Field, Int), x2: (Field, Int)): (Field, Int) = { val (in1, batchSize) = x1 val (filter, filterBatchSize) = x2 assert(filterBatchSize == 1, "convolutional filter bank must have a batch size of 1") assert(filter.fieldShape.dimensions == 2, "convolutional filter bank must contain 2D filters") assert(filter.fieldShape(0) == filter.fieldShape(1), "convolutional filter bank must contain square filters") assert(filter.fieldShape(0) % 2 == 1, "convolutional filter bank must contain odd-sized filters") val inputLen = in1.tensorShape(0) assert(inputLen % batchSize == 0, s"internal test error: expecting input vector depth $inputLen to be a multiple of the batchsize $batchSize") val numInputs = inputLen / batchSize val result = blockReduceSum(projectFrame(in1, filter, border, DownsampleOutputConvolution(stride), batchSize), numInputs) (result, batchSize) } private def jacobian1(dx1: Field, x1: (Field, Int), x2: (Field, Int)): Field = { val (in1, batchSize) = x1 _forward((dx1, batchSize), x2)._1 } private def jacobianAdjoint1(grad: Field, x1: (Field, Int), x2: (Field, Int)): Field = { val (in1, batchSize) = x1 val (filter, filterBatchSize) = x2 val inputLen = in1.tensorShape(0) val gradLen = grad.tensorShape(0) assert(inputLen % batchSize == 0, s"internal test error: expecting input vector depth $inputLen to be a multiple of the batchsize $batchSize") assert(gradLen % batchSize == 0, s"internal test error: expecting gradient vector depth $gradLen to be a multiple of the batchsize $batchSize") val numInputs = inputLen / batchSize val numFilters = filter.tensorShape(0) / numInputs val retField = border match { case BorderValid => blockReduceSum(backProjectFrame(grad, filter, BorderFull, UpsampleInputConvolution(stride), batchSize), numFilters) case BorderZero => blockReduceSum(backProjectFrame(grad, filter, BorderZero, UpsampleInputConvolution(stride), batchSize), numFilters) case x => throw new RuntimeException(s"Unexpected border policy $x.") } retField } private def jacobian2(dx2: Field, x1: (Field, Int), x2: (Field, Int)): Field = _forward(x1, (dx2, x2._2))._1 private def jacobianAdjoint2(grad: Field, x1: (Field, Int), x2: (Field, Int)): Field = { val (in1, batchSize) = x1 val (filter, filterBatchSize) = x2 val (filterRows, filterColumns) = { require(filter.dimensions == 2, "Expecting 2D filter") require(filter.rows % 2 == 1 && filter.columns % 2 == 1, s"Expecting odd filter sizes, found ${filter.fieldShape}.") (filter.rows, filter.columns) } val inputLen = in1.tensorShape(0) val gradLen = grad.tensorShape(0) assert(inputLen % batchSize == 0, s"internal test error: expecting input vector depth $inputLen to be a multiple of the batchsize $batchSize") assert(gradLen % batchSize == 0, s"internal test error: expecting gradient vector depth $gradLen to be a multiple of the batchsize $batchSize") // Apply a 0-valued halo region around a field, as needed for BorderZero border policy. def addZeroHalo(f: Field, rowHalo: Int, columnHalo: Int) = { val expandedShape = Shape(f.rows + 2 * rowHalo, f.columns + 2 * columnHalo) f.expand(BorderZero, expandedShape).shiftCyclic(rowHalo, columnHalo) } val dX2 = border match { case BorderValid => crossCorrelateFilterAdjoint(in1, grad, BorderValid, UpsampleInputConvolution(stride), batchSize) case BorderZero => val paddedIn = addZeroHalo(in1, filterRows/2, filterColumns/2) crossCorrelateFilterAdjoint(paddedIn, grad, BorderValid, UpsampleInputConvolution(stride), batchSize) case x => throw new RuntimeException(s"Unexpected border policy $x.") } val dX2Len = dX2.tensorShape(0) assert(dX2Len % batchSize == 0, s"internal test error: expecting filter adjoint vector depth $dX2Len to be a multiple of the batchsize $batchSize") if (batchSize == 1) dX2 else blockReduceSum(dX2, batchSize) } // If you add/remove constructor parameters, you should alter the toString() implementation. */ /** A string description of the instance in the "case class" style. */ override def toString = this.getClass.getName + (input, weights, border, stride) } /** Factory object- eliminates clutter of 'new' operator. */ object SpatialConvolution { /** A convolutional transformation that applies a filter bank to a signal in the space domain. * * @param input The signal node * @param weights The filter bank input, typically a TrainableState field * @param stride The factor by which the output with be downsampled after the BorderValid convolution */ def apply(input: DifferentiableField, weights: DifferentiableField, border: BorderPolicy = BorderValid, stride: Int = 1) = new SpatialConvolution(input, weights, border, stride) }
hpe-cct/cct-nn
src/main/scala/toolkit/neuralnetwork/function/SpatialConvolution.scala
Scala
apache-2.0
7,184
/** * Copyright (c) 2013 Mark S. Kolich * http://mark.koli.ch * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package com.kolich.spray.protocols import java.lang.StringBuilder import org.apache.commons.lang3.StringEscapeUtils.escapeHtml4 import spray.http._ import spray.httpx._ import spray.httpx.marshalling.Marshaller import spray.json._ sealed trait HtmlSafeCompactJsonPrinter extends CompactPrinter { override def print(x: JsValue, sb: StringBuilder) { x match { case JsString(x) => printString(escapeHtml4(x), sb) case _ => super.print(x, sb) } } } object HtmlSafeCompactJsonPrinter extends HtmlSafeCompactJsonPrinter trait HtmlSafeSprayJsonSupport extends SprayJsonSupport { override implicit def sprayJsonMarshaller[T](implicit writer: RootJsonWriter[T], printer: JsonPrinter = PrettyPrinter) = Marshaller.delegate[T, String](ContentType.`application/json`) { value => lazy val printer = HtmlSafeCompactJsonPrinter val json = writer.write(value) printer(json) } }
markkolich/spray-servlet-webapp
src/main/scala/com/kolich/spray/protocols/HtmlSafeSprayJsonSupport.scala
Scala
mit
2,076
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kafka.server import java.util import java.util.{Optional, Properties} import kafka.log.LogConfig import kafka.utils.TestUtils import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord} import org.apache.kafka.common.TopicPartition import org.apache.kafka.common.protocol.Errors import org.apache.kafka.common.requests.{FetchRequest, FetchResponse} import org.apache.kafka.common.serialization.StringSerializer import org.junit.jupiter.api.Assertions._ import org.junit.jupiter.api.{AfterEach, BeforeEach, Test} class FetchRequestDownConversionConfigTest extends BaseRequestTest { private var producer: KafkaProducer[String, String] = null override def brokerCount: Int = 1 @BeforeEach override def setUp(): Unit = { super.setUp() initProducer() } @AfterEach override def tearDown(): Unit = { if (producer != null) producer.close() super.tearDown() } override protected def brokerPropertyOverrides(properties: Properties): Unit = { super.brokerPropertyOverrides(properties) properties.put(KafkaConfig.LogMessageDownConversionEnableProp, "false") } private def initProducer(): Unit = { producer = TestUtils.createProducer(TestUtils.getBrokerListStrFromServers(servers), keySerializer = new StringSerializer, valueSerializer = new StringSerializer) } private def createTopics(numTopics: Int, numPartitions: Int, configs: Map[String, String] = Map.empty, topicSuffixStart: Int = 0): Map[TopicPartition, Int] = { val topics = (0 until numTopics).map(t => s"topic${t + topicSuffixStart}") val topicConfig = new Properties topicConfig.setProperty(LogConfig.MinInSyncReplicasProp, 1.toString) configs.foreach { case (k, v) => topicConfig.setProperty(k, v) } topics.flatMap { topic => val partitionToLeader = createTopic(topic, numPartitions = numPartitions, replicationFactor = 1, topicConfig = topicConfig) partitionToLeader.map { case (partition, leader) => new TopicPartition(topic, partition) -> leader } }.toMap } private def createPartitionMap(maxPartitionBytes: Int, topicPartitions: Seq[TopicPartition], offsetMap: Map[TopicPartition, Long] = Map.empty): util.LinkedHashMap[TopicPartition, FetchRequest.PartitionData] = { val partitionMap = new util.LinkedHashMap[TopicPartition, FetchRequest.PartitionData] topicPartitions.foreach { tp => partitionMap.put(tp, new FetchRequest.PartitionData(offsetMap.getOrElse(tp, 0), 0L, maxPartitionBytes, Optional.empty())) } partitionMap } private def sendFetchRequest(leaderId: Int, request: FetchRequest): FetchResponse = { connectAndReceive[FetchResponse](request, destination = brokerSocketServer(leaderId)) } /** * Tests that fetch request that require down-conversion returns with an error response when down-conversion is disabled on broker. */ @Test def testV1FetchWithDownConversionDisabled(): Unit = { val topicMap = createTopics(numTopics = 5, numPartitions = 1) val topicPartitions = topicMap.keySet.toSeq topicPartitions.foreach(tp => producer.send(new ProducerRecord(tp.topic, "key", "value")).get()) val fetchRequest = FetchRequest.Builder.forConsumer(Int.MaxValue, 0, createPartitionMap(1024, topicPartitions)).build(1) val fetchResponse = sendFetchRequest(topicMap.head._2, fetchRequest) topicPartitions.foreach(tp => assertEquals(Errors.UNSUPPORTED_VERSION, Errors.forCode(fetchResponse.responseData.get(tp).errorCode))) } /** * Tests that "message.downconversion.enable" has no effect when down-conversion is not required. */ @Test def testLatestFetchWithDownConversionDisabled(): Unit = { val topicMap = createTopics(numTopics = 5, numPartitions = 1) val topicPartitions = topicMap.keySet.toSeq topicPartitions.foreach(tp => producer.send(new ProducerRecord(tp.topic, "key", "value")).get()) val fetchRequest = FetchRequest.Builder.forConsumer(Int.MaxValue, 0, createPartitionMap(1024, topicPartitions)).build() val fetchResponse = sendFetchRequest(topicMap.head._2, fetchRequest) topicPartitions.foreach(tp => assertEquals(Errors.NONE, Errors.forCode(fetchResponse.responseData.get(tp).errorCode))) } /** * Tests that "message.downconversion.enable" can be set at topic level, and its configuration is obeyed for client * fetch requests. */ @Test def testV1FetchWithTopicLevelOverrides(): Unit = { // create topics with default down-conversion configuration (i.e. conversion disabled) val conversionDisabledTopicsMap = createTopics(numTopics = 5, numPartitions = 1, topicSuffixStart = 0) val conversionDisabledTopicPartitions = conversionDisabledTopicsMap.keySet.toSeq // create topics with down-conversion configuration enabled val topicConfig = Map(LogConfig.MessageDownConversionEnableProp -> "true") val conversionEnabledTopicsMap = createTopics(numTopics = 5, numPartitions = 1, topicConfig, topicSuffixStart = 5) val conversionEnabledTopicPartitions = conversionEnabledTopicsMap.keySet.toSeq val allTopics = conversionDisabledTopicPartitions ++ conversionEnabledTopicPartitions val leaderId = conversionDisabledTopicsMap.head._2 allTopics.foreach(tp => producer.send(new ProducerRecord(tp.topic, "key", "value")).get()) val fetchRequest = FetchRequest.Builder.forConsumer(Int.MaxValue, 0, createPartitionMap(1024, allTopics)).build(1) val fetchResponse = sendFetchRequest(leaderId, fetchRequest) conversionDisabledTopicPartitions.foreach(tp => assertEquals(Errors.UNSUPPORTED_VERSION.code, fetchResponse.responseData.get(tp).errorCode)) conversionEnabledTopicPartitions.foreach(tp => assertEquals(Errors.NONE.code, fetchResponse.responseData.get(tp).errorCode)) } /** * Tests that "message.downconversion.enable" has no effect on fetch requests from replicas. */ @Test def testV1FetchFromReplica(): Unit = { // create topics with default down-conversion configuration (i.e. conversion disabled) val conversionDisabledTopicsMap = createTopics(numTopics = 5, numPartitions = 1, topicSuffixStart = 0) val conversionDisabledTopicPartitions = conversionDisabledTopicsMap.keySet.toSeq // create topics with down-conversion configuration enabled val topicConfig = Map(LogConfig.MessageDownConversionEnableProp -> "true") val conversionEnabledTopicsMap = createTopics(numTopics = 5, numPartitions = 1, topicConfig, topicSuffixStart = 5) val conversionEnabledTopicPartitions = conversionEnabledTopicsMap.keySet.toSeq val allTopicPartitions = conversionDisabledTopicPartitions ++ conversionEnabledTopicPartitions val leaderId = conversionDisabledTopicsMap.head._2 allTopicPartitions.foreach(tp => producer.send(new ProducerRecord(tp.topic, "key", "value")).get()) val fetchRequest = FetchRequest.Builder.forReplica(1, 1, Int.MaxValue, 0, createPartitionMap(1024, allTopicPartitions)).build() val fetchResponse = sendFetchRequest(leaderId, fetchRequest) allTopicPartitions.foreach(tp => assertEquals(Errors.NONE.code, fetchResponse.responseData.get(tp).errorCode)) } }
Chasego/kafka
core/src/test/scala/unit/kafka/server/FetchRequestDownConversionConfigTest.scala
Scala
apache-2.0
8,019
package org.ninjatasks.spi import java.util.UUID /** * A work object is a container for multiple job objects. * The logic and data included in this object are: * 1. A JobCreator object, which is responsible for the lazy initialization of * processable job objects. * 2. A combine function, which reduces the results of the underlying job objects * as they are processed, into a single result. * 3. The initial result of the computation. The final result is calculated as a reduction of the combine function * over the stream of incoming results, with the initial result field as its initial value. * 4. User-supplied priority. * 5. A data object, which is usually a relatively large object that is required * for the processing of the job objects. It is preferable that implementations of * this trait will include all non-job-specific data in the work object, since the * work object is sent to worker actors only once per *work*, while if you include * lots un-needed data in job objects, that data will occur a higher latency in * transferring the job objects themselves from the work manager to the workers, * and vice versa. * * The final result of this work is computed by applying the combine function * to the stream of incoming job results, with initialResult being the initial value * of the reduction * * Since the combine and creator functions will be called by actors inside the ninja-tasks framework, * they must absolutely be non-blocking, otherwise possibly resulting in severe scalability issues * for this system. * This requirement is especially critical for the combine function which may be called many times, * depending on the number of underlying job objects a work will have. If a blocking call (say network, DB-related) * must be made, then make sure to either make it before or after submitting the work for processing. The same applies * for the creator function, however that will only be called once per work submission, so it has less potential * to become a bottleneck. * * @tparam JobT The type of results produced by processing the underlying jobs. * @tparam DataT The type of work-related data which is supplied to the job objects. * @tparam ResT The type of the final result obtained by the computation of this work. */ trait Work[JobT, DataT, ResT] extends WorkOps[JobT, ResT] { self => private[ninjatasks] type baseJobType private[ninjatasks] type baseResType private[ninjatasks] val id: UUID = UUID.randomUUID() private[ninjatasks] val updater: ResultUpdater[baseJobType, JobT, baseResType, ResT] private[ninjatasks] def update(res: baseJobType) = updater.update(res) private[ninjatasks] def result: ResT = updater.result /** * The priority assigned to this work. * A higher value means higher priority -- that is, works with the higher priority will be processed prior to works * with a lower priority, regardless of insertion time. Job objects of works with the same priority value will be sent * to processing in order of insertion to the internal job queue. */ val priority: Int /** * Underlying data which will be used by jobs for their computation. * This object should mostly consist of data that is not related to a certain job's computation, * since it is sent to all processing actors, regardless of which job they are executing. * On the other hand, it any data that is relevant to all jobs should be contained in this object * and not in other job objects, in order to minimize serialization costs, to not incur * that cost for every job that is sent. * * It should be noted that this object will most likely be shared between multiple job objects, * so it is essential that either it is thread-safe, or that all jobs access it in a synchronized fashion. */ val data: Option[DataT] /** * Job objects factory, for lazy creation of jobs when required and when * processing has become possible. */ val creator: JobCreator[baseJobType, DataT] /** * Returns a new work object with the given combiner, which is invoked on the results of the * work's job results after the result is mapped by f. * @param f mapping function * @param combiner new combiner * @tparam U type of the new intermediate results * @return A new work object which maps the results of job objects by the mapping function. */ def mapJobs[U](f: JobT => U)(combiner: (ResT, U) => ResT): Work[U, DataT, ResT] = { val mappedUpdater = updater.mapJobs(f)(combiner) NinjaWork(this, mappedUpdater, creator) } /** * Map the result of this work object to another * @param f mapping function * @tparam U target result type * @return A new work instance with its result mapped by the given function */ def map[U](f: ResT => U): Work[JobT, DataT, U] = { val mappedUpdater = updater.map(f) NinjaWork(this, mappedUpdater, creator) } /** * Add a filter to the work object's job results, ignoring results that do not pass the filter. * @param p predicate to filter by * @return A new RichWork object which ignores job results according to the input filter. */ def filter(p: JobT => Boolean): Work[JobT, DataT, ResT] = { val filteredUpdater = updater.filter(p) NinjaWork(this, filteredUpdater, creator) } /** * Applies a function to each incoming job result, ignoring the function's result * (i.e. it is only needed for side effects). * @param f function to be invoked on each job result * @tparam U function result type (is ignored) * @return a new work object which will apply the input function to each job result on reduction */ def foreach[U](f: JobT => U): Work[JobT, DataT, ResT] = { val foreachUpdater = updater.foreach(f) NinjaWork(this, foreachUpdater, creator) } def fold[U](f: (U, JobT) => U)(acc: U): Work[JobT, DataT, U] = { val foldUpdater = updater.fold(f)(acc) NinjaWork(this, foldUpdater, creator) } } private[ninjatasks] object NinjaWork { def apply[J, JF, D, R, RF](work: Work[_, D, _], updater: ResultUpdater[J, JF, R, RF], creator: JobCreator[J, D]) = { new NinjaWork(work.priority, work.data, updater, creator) } def apply[J, D, R](priority: Int, data: Option[D], creator: JobCreator[J, D], combine: (R, J) => R, initialResult: R) = { new NinjaWork(priority, data, ResultUpdater(combine, initialResult), creator) } } private[ninjatasks] class NinjaWork[J, JF, D, R, RF](override val priority: Int, override val data: Option[D], override val updater: ResultUpdater[J, JF, R, RF], override val creator: JobCreator[J, D]) extends Work[JF, D, RF] { private[ninjatasks] type baseJobType = J private[ninjatasks] type baseResType = R }
giladber/ninja-tasks
src/main/scala/org/ninjatasks/spi/Work.scala
Scala
apache-2.0
6,705
package com.sksamuel.elastic4s.searches.queries.funcscorer import com.sksamuel.elastic4s.script.ScriptDefinition import org.elasticsearch.index.query.functionscore.{ScoreFunctionBuilders, ScriptScoreFunctionBuilder} import com.sksamuel.exts.OptionImplicits._ case class ScriptScoreDefinition(script: ScriptDefinition, weight: Option[Double] = None) extends ScoreFunctionDefinition { override type B = ScriptScoreFunctionBuilder def builder = { val builder = ScoreFunctionBuilders.scriptFunction(script.toJavaAPI) weight.map(_.toFloat).foreach(builder.setWeight) builder } def weight(weight: Double): ScriptScoreDefinition = copy(weight = weight.some) }
ulric260/elastic4s
elastic4s-core/src/main/scala/com/sksamuel/elastic4s/searches/queries/funcscorer/ScriptScoreDefinition.scala
Scala
apache-2.0
711
/* * */ package see.nodes import java.lang.reflect.Constructor import see.EvalError import see.Scope import see.values._ private[see] class ReflectP(methName: String, args: Node) extends Proto { override def precedence = PREC.Deref override def finish(n: Node) = Some(new MethReflector(n, methName, args)) } private[see] class ReflectFieldP(fieldName: String) extends Proto { override def precedence = PREC.Deref override def finish(n: Node) = Some(new FieldReflector(n, fieldName)) } private[see] class MethReflector( ref: Node, val methName: String, val args: Node) extends Atom(ref) { override def evalIn(s: Scope) = { if (!see.See.reflectionEnabled) throw new EvalError("Java Reflection is disabled.") val obj = opd.evalIn(s).coerce val cargs = args.evalIn(s).coerce match { case v: Vector => v.values.toArray case x => Array(x) } obj match { case AnyVal(any) => deref(any, cargs) case _ => derefClass(obj.toStr, cargs) } } override def simplifyIn(s: Scope) = try { val ref = opd.simplifyIn(s) val sargs = args.simplifyIn(s) new MethReflector(ref, methName, sargs) } catch { case _: Exception => this } override def isDefinedIn(s: Scope): Boolean = opd.isDefinedIn(s) && args.isDefinedIn(s) override def toString = "(" + opd + ":>" + methName + "[" + args + "])" private def deref(obj: AnyRef, cargs: Array[Val]) = callMethod(obj.getClass, obj, cargs) private def derefClass(clsName: String, cargs: Array[Val]) = { val cls = try { Class.forName(clsName) } catch { case _: Exception => throw new EvalError("Unknown classname: '" + clsName + "'.") } if (methName == "new") create(cls, cargs) else callMethod(cls, null, cargs) // static call } private def callMethod(cls: Class[_], inst: AnyRef, cargs: Array[Val]): Val = { val mths = for { m <- cls.getMethods pt = m.getParameterTypes if (m.getName == methName) && (pt.length == cargs.length) } yield m if (mths.isEmpty) throw new EvalError(s"Class '${cls.getName}' has no method $methName with ${cargs.length} arguments") val meth = if (mths.size > 1) Native.select(mths, cargs) else mths.head val jargs = Native.convertArgs(meth.getParameterTypes, cargs) try { val result = meth.invoke(inst, jargs: _*) if (result != null) Val(result) else if (meth.getReturnType == java.lang.Void.TYPE) VoidVal else NullVal } catch { case x: Exception => throw new EvalError(s"Invocation of '${cls.getName}.$methName' failed: ${x.getMessage}") } } private def create(cls: Class[_], cargs: Array[Val]): Val = { val ctors = for { c <- cls.getConstructors pt = c.getParameterTypes if pt.length == cargs.length } yield c if (ctors.isEmpty) throw new EvalError(s"Class '${cls.getName}' has no constructor with ${cargs.length} arguments") val ctor = if (ctors.size > 1) select(ctors, cargs) else ctors.head val jargs = Native.convertArgs(ctor.getParameterTypes, cargs) try { Val(ctor.newInstance(jargs: _*).asInstanceOf[AnyRef]) } catch { case x: Exception => throw new EvalError(s"Construction of '${cls.getName}' failed: ${x.getMessage}") } } private def select(ctors: Array[Constructor[_]], args: Array[Val]) = { val n = Native.bestMatch(ctors.map(_.getParameterTypes), args) if (n >= 0) ctors(n) else throw new EvalError(args.mkString( "No constructor matches argument list (", ", ", ").") ) } } /** Reflector Node, performs native java call using reflection */ private[see] class FieldReflector( ref: Node, val fieldName: String) extends Atom(ref) with LvNode { override def evalIn(s: Scope) = { if (!see.See.reflectionEnabled) throw new EvalError("Java Reflection is disabled.") val obj = opd.evalIn(s).coerce obj match { case AnyVal(any) => getField(any.getClass, any) case _ => getField(ofClass(obj.toStr), null) } } override def setIn(s: Scope, value: Val) { if (!see.See.reflectionEnabled) throw new EvalError("Java Reflection is disabled.") val obj = opd.evalIn(s).coerce obj match { case AnyVal(any) => setField(any.getClass, any, value) case _ => setField(ofClass(obj.toStr), null, value) } } override def simplifyIn(s: Scope) = try { val ref = opd.simplifyIn(s) new FieldReflector(ref, fieldName) } catch { case _: Exception => this } override def isDefinedIn(s: Scope): Boolean = opd.isDefinedIn(s) override def toString = s"($opd:>$fieldName)" private def ofClass(clsName: String) = try { Class.forName(clsName) } catch { case _: Exception => throw new EvalError(s"Unknown classname: '$clsName'.") } private def jfield(cls: Class[_]) = try { cls.getDeclaredField(fieldName) } catch { case _: Exception => throw new EvalError(s"Class '${cls.getName}' has no field '$fieldName'." ) } private def getField(cls: Class[_], inst: AnyRef): Val = { val field = jfield(cls) try { Val(field.get(inst)) } catch { case x: Exception => throw new EvalError(s"Cannot access '${cls.getName}.$fieldName': ${x.getMessage}") } } private def setField(cls: Class[_], inst: AnyRef, value: Val) { val field = jfield(cls) try { val jobj = value.convertTo(field.getType) field.set(inst, jobj) } catch { case x: Exception => throw new EvalError(s"Cannot change '${cls.getName}.$fieldName': ${x.getMessage}") } } }
acruise/see
src/main/scala/see/nodes/Reflect.scala
Scala
bsd-3-clause
5,887
package mesosphere.marathon.core.appinfo.impl import mesosphere.marathon.MarathonSchedulerService import mesosphere.marathon.Protos.MarathonTask import mesosphere.marathon.core.appinfo.{ AppInfo, EnrichedTask, TaskCounts, TaskStatsByVersion } import mesosphere.marathon.core.base.Clock import mesosphere.marathon.health.{ Health, HealthCheckManager } import mesosphere.marathon.state._ import mesosphere.marathon.tasks.TaskTracker import mesosphere.marathon.upgrade.DeploymentPlan import org.slf4j.LoggerFactory import scala.collection.immutable.Seq import scala.concurrent.Future import scala.util.control.NonFatal class AppInfoBaseData( clock: Clock, taskTracker: TaskTracker, healthCheckManager: HealthCheckManager, marathonSchedulerService: MarathonSchedulerService, taskFailureRepository: TaskFailureRepository) { import AppInfoBaseData.log import scala.concurrent.ExecutionContext.Implicits.global lazy val runningDeploymentsByAppFuture: Future[Map[PathId, Seq[Identifiable]]] = { log.debug("Retrieving running deployments") val allRunningDeploymentsFuture: Future[Seq[DeploymentPlan]] = for { stepInfos <- marathonSchedulerService.listRunningDeployments() } yield stepInfos.map(_.plan) allRunningDeploymentsFuture.map { allDeployments => val byApp = Map.empty[PathId, Vector[DeploymentPlan]].withDefaultValue(Vector.empty) val deploymentsByAppId = allDeployments.foldLeft(byApp) { (result, deploymentPlan) => deploymentPlan.affectedApplicationIds.foldLeft(result) { (result, appId) => val newEl = appId -> (result(appId) :+ deploymentPlan) result + newEl } } deploymentsByAppId .mapValues(_.map(deploymentPlan => Identifiable(deploymentPlan.id))) .withDefaultValue(Seq.empty) } } def appInfoFuture(app: AppDefinition, embed: Set[AppInfo.Embed]): Future[AppInfo] = { val appData = new AppData(app) embed.foldLeft(Future.successful(AppInfo(app))) { (infoFuture, embed) => infoFuture.flatMap { info => embed match { case AppInfo.Embed.Counts => appData.taskCountsFuture.map(counts => info.copy(maybeCounts = Some(counts))) case AppInfo.Embed.Deployments => runningDeploymentsByAppFuture.map(deployments => info.copy(maybeDeployments = Some(deployments(app.id)))) case AppInfo.Embed.LastTaskFailure => appData.maybeLastTaskFailureFuture.map { maybeLastTaskFailure => info.copy(maybeLastTaskFailure = maybeLastTaskFailure) } case AppInfo.Embed.Tasks => appData.enrichedTasksFuture.map(tasks => info.copy(maybeTasks = Some(tasks))) case AppInfo.Embed.TaskStats => appData.taskStatsFuture.map(taskStats => info.copy(maybeTaskStats = Some(taskStats))) } } } } /** * Contains app-sepcific data that we need to retrieved. * * All data is lazy such that only data that is actually needed for the requested embedded information * gets retrieved. */ private[this] class AppData(app: AppDefinition) { lazy val now: Timestamp = clock.now() lazy val tasks: Iterable[MarathonTask] = { log.debug(s"retrieving running tasks for app [${app.id}]") taskTracker.getTasks(app.id) } lazy val tasksFuture: Future[Iterable[MarathonTask]] = Future.successful(tasks) lazy val healthCountsFuture: Future[Map[String, Seq[Health]]] = { log.debug(s"retrieving health counts for app [${app.id}]") healthCheckManager.statuses(app.id) }.recover { case NonFatal(e) => throw new RuntimeException(s"while retrieving health counts for app [${app.id}]", e) } lazy val tasksForStats: Future[Iterable[TaskForStatistics]] = { for { tasks <- tasksFuture healthCounts <- healthCountsFuture } yield TaskForStatistics.forTasks(now, tasks, healthCounts) }.recover { case NonFatal(e) => throw new RuntimeException(s"while calculating tasksForStats for app [${app.id}]", e) } lazy val taskCountsFuture: Future[TaskCounts] = { log.debug(s"calculating task counts for app [${app.id}]") for { tasks <- tasksForStats } yield TaskCounts(tasks) }.recover { case NonFatal(e) => throw new RuntimeException(s"while calculating task counts for app [${app.id}]", e) } lazy val taskStatsFuture: Future[TaskStatsByVersion] = { log.debug(s"calculating task stats for app [${app.id}]") for { tasks <- tasksForStats } yield TaskStatsByVersion(app.versionInfo, tasks) } lazy val enrichedTasksFuture: Future[Seq[EnrichedTask]] = { def statusesToEnrichedTasks( tasksById: Map[String, MarathonTask], statuses: Map[String, collection.Seq[Health]]): Seq[EnrichedTask] = { for { (taskId, healthResults) <- statuses.to[Seq] task <- tasksById.get(taskId) } yield EnrichedTask(app.id, task, healthResults) } log.debug(s"assembling rich tasks for app [${app.id}]") val tasksById: Map[String, MarathonTask] = tasks.map(task => task.getId -> task).toMap healthCheckManager.statuses(app.id).map(statuses => statusesToEnrichedTasks(tasksById, statuses)) }.recover { case NonFatal(e) => throw new RuntimeException(s"while assembling rich tasks for app [${app.id}]", e) } lazy val maybeLastTaskFailureFuture: Future[Option[TaskFailure]] = { log.debug(s"retrieving last task failure for app [${app.id}]") taskFailureRepository.current(app.id) }.recover { case NonFatal(e) => throw new RuntimeException(s"while retrieving last task failure for app [${app.id}]", e) } } } object AppInfoBaseData { private val log = LoggerFactory.getLogger(getClass) }
Yhgenomics/marathon
src/main/scala/mesosphere/marathon/core/appinfo/impl/AppInfoBaseData.scala
Scala
apache-2.0
5,850
package com.duffmanstudios.memory import org.scalatest.{Matchers, FlatSpec} /** * Contains unit tests for the functionality in Card * * @author Iain Duff */ class CardTest extends ProjectTest { "Two cards with matching IDs" must "be identified as having matching IDs" in { val cardOne = new Card(1) val cardTwo = new Card(1) cardOne.Id should equal (cardTwo.Id) } "Two cards with non-matching IDs" must "be identified as having non-matching IDs" in { cardOne.Id should not equal cardTwo.Id } "equals" must "return true if both reference the same object" in { val cardOne = new Card(1) val cardTwo = cardOne assert(cardOne.equals(cardTwo)) } "equals" must "return false if object to compare to is NOT a Card" in { val cardOne = new Card(1) val notACard = new String("") assertResult(false)(cardOne.equals(notACard)) } "equals" must "return true if cards have the SAME ID" in { val cardOne = new Card(1) val cardTwo = new Card(1) assert(cardOne.equals(cardTwo)) } "equals" must "return false if cards have DIFFERENT IDs" in { assertResult(false)(cardOne.equals(cardTwo)) } }
iainduff91/memory-backend
src/test/java/com/duffmanstudios/memory/CardTest.scala
Scala
gpl-2.0
1,169
package com.mycompany.scalcium.langmodel import java.io.File import org.apache.commons.math3.random.MersenneTwister import org.deeplearning4j.datasets.iterator.CSVDataSetIterator import org.deeplearning4j.distributions.Distributions import org.deeplearning4j.eval.Evaluation import org.deeplearning4j.models.classifiers.dbn.DBN import org.deeplearning4j.nn.WeightInit import org.deeplearning4j.nn.conf.NeuralNetConfiguration import org.nd4j.linalg.api.activation.Activations import org.nd4j.linalg.lossfunctions.LossFunctions class DL4jNNEval { val NumTrainingInstances = 3823 val evaluation = new Evaluation() def evaluate(trainfile: File, decay: Float, hiddenLayerSize: Int, numIters: Int, learningRate: Float, momentum: Float, miniBatchSize: Int): (Double, Double) = { // set up the DBN val rng = new MersenneTwister(123) val conf = new NeuralNetConfiguration.Builder() .learningRate(learningRate) .momentum(momentum) .iterations(numIters) .regularization(decay > 0.0F) .regularizationCoefficient(decay) .lossFunction(LossFunctions.LossFunction.RECONSTRUCTION_CROSSENTROPY) .rng(rng) .dist(Distributions.uniform(rng)) .activationFunction(Activations.tanh()) .weightInit(WeightInit.DISTRIBUTION) .nIn(64) // 8*8 pixels per handwritten digit .nOut(10) // softmax 0-9 .build() val dbn = new DBN.Builder() .configure(conf) .hiddenLayerSizes(Array[Int](hiddenLayerSize)) .forceEpochs() .build() dbn.getOutputLayer().conf().setActivationFunction(Activations.softMaxRows()) dbn.getOutputLayer().conf().setLossFunction(LossFunctions.LossFunction.MCXENT) // read input data val it = new CSVDataSetIterator( miniBatchSize * 2, NumTrainingInstances, trainfile, 64) val dataset = it.next(miniBatchSize * 2) dataset.normalizeZeroMeanZeroUnitVariance() val split = dataset.splitTestAndTrain(miniBatchSize) val trainset = split.getTrain() val testset = split.getTest() dbn.fit(trainset) evaluation.eval(dbn.output(trainset.getFeatureMatrix()), trainset.getLabels()) val trainf1 = evaluation.f1() evaluation.eval(dbn.output(testset.getFeatureMatrix()), testset.getLabels()) val testf1 = evaluation.f1() (trainf1, testf1) } }
sujitpal/scalcium
src/main/scala/com/mycompany/scalcium/langmodel/DL4jNNEval.scala
Scala
apache-2.0
2,317
/* sbt -- Simple Build Tool * Copyright 2011 Mark Harrah */ package sbt import Keys._ import complete.{DefaultParsers, Parser} import DefaultParsers._ import Project.{ScopedKey, Setting} import Scope.GlobalScope object Cross { final val Switch = "++" final val Cross = "+" def switchParser(state: State): Parser[(String, String)] = { val knownVersions = crossVersions(state) lazy val switchArgs = token(NotSpace.examples(knownVersions : _*)) ~ (token(Space ~> matched(state.combinedParser)) ?? "") lazy val nextSpaced = spacedFirst(Switch) token(Switch ~ OptSpace) flatMap { _ => switchArgs & nextSpaced } } def spacedFirst(name: String) = opOrIDSpaced(name) ~ any.+ lazy val switchVersion = Command.arb(requireSession(switchParser)) { case (state, (version, command)) => val x = Project.extract(state) import x._ println("Setting version to " + version) val add = (scalaVersion in GlobalScope :== version) :: (scalaHome in GlobalScope :== None) :: Nil val cleared = session.mergeSettings.filterNot( crossExclude ) val newStructure = Load.reapply(add ++ cleared, structure) Project.setProject(session, newStructure, command :: state) } def crossExclude(s: Setting[_]): Boolean = s.key match { case ScopedKey( Scope(_, Global, Global, _), scalaHome.key | scalaVersion.key) => true case _ => false } def crossParser(state: State): Parser[String] = token(Cross <~ OptSpace) flatMap { _ => token(matched( state.combinedParser & spacedFirst(Cross) )) } lazy val crossBuild = Command.arb(requireSession(crossParser)) { (state, command) => val x = Project.extract(state) import x._ val versions = crossVersions(state) val current = scalaVersion in currentRef get structure.data map(Switch + " " + _) toList; if(versions.isEmpty) command :: state else versions.map(Switch + " " + _ + " " + command) ::: current ::: state } def crossVersions(state: State): Seq[String] = { val x = Project.extract(state) import x._ crossScalaVersions in currentRef get structure.data getOrElse Nil } def requireSession[T](p: State => Parser[T]): State => Parser[T] = s => if(s get sessionSettings isEmpty) failure("No project loaded") else p(s) }
kuochaoyi/xsbt
main/Cross.scala
Scala
bsd-3-clause
2,207
package org.bitcoins.core.script import org.bitcoins.core.script.arithmetic.OP_1ADD import org.bitcoins.core.script.bitwise.OP_EQUAL import org.bitcoins.core.script.constant._ import org.bitcoins.core.script.control.OP_IF import org.bitcoins.core.script.crypto.OP_RIPEMD160 import org.bitcoins.core.script.locktime.OP_CHECKLOCKTIMEVERIFY import org.bitcoins.core.script.splice.OP_SUBSTR import org.bitcoins.core.script.stack.OP_TOALTSTACK import org.bitcoins.core.util.BytesUtil import org.bitcoins.testkitcore.util.BitcoinSUnitTest /** Created by chris on 1/9/16. */ class ScriptOperationFactoryTest extends BitcoinSUnitTest { "ScriptOperationFactory" must "match operations with their byte representation" in { ScriptOperation(0x00.toByte) must be(OP_0) ScriptOperation(0x51.toByte) must be(OP_1) ScriptOperation(0x63.toByte) must be(OP_IF) ScriptOperation(0x6b.toByte) must be(OP_TOALTSTACK) ScriptOperation(135.toByte) must be(OP_EQUAL) ScriptOperation(139.toByte) must be(OP_1ADD) ScriptOperation(166.toByte) must be(OP_RIPEMD160) ScriptOperation(177.toByte) must be(OP_CHECKLOCKTIMEVERIFY) } it must "find OP_4 from it's byte representation" in { val byteRepresentation = BytesUtil.decodeHex("54").head ScriptOperation(byteRepresentation) must be(OP_4) } it must "find a byte to push onto stack from its byte representation" in { val result = ScriptOperation(2.toByte) result must be(BytesToPushOntoStack(2)) } it must "find a script number from its hex representation" in { val result = ScriptOperation("02") result.isDefined must be(true) result.get must be(BytesToPushOntoStack(2)) } it must "find undefined op codes" in { val result = ScriptOperation("ba") result.isDefined must be(true) } it must "find a splice operation from it's hex representation" in { val spliceOperation = ScriptOperation("7F") spliceOperation.isDefined must be(true) spliceOperation.get must be(OP_SUBSTR) } it must "find OP_1NEGATE from its hex representation" in { OP_1NEGATE.opCode must be(79) OP_1NEGATE.toByte must be(79) val negateOperation = ScriptOperation("4f") negateOperation.isDefined must be(true) negateOperation.get must be(OP_1NEGATE) } }
bitcoin-s/bitcoin-s
core-test/src/test/scala/org/bitcoins/core/script/ScriptOperationFactoryTest.scala
Scala
mit
2,286
/* * Wire * Copyright (C) 2016 Wire Swiss GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.waz.service.assets2 import java.io.InputStream import java.net.URI import com.waz.model.Mime import scala.util.Try trait UriHelper { def openInputStream(uri: URI): Try[InputStream] def extractMime(uri: URI): Try[Mime] def extractSize(uri: URI): Try[Long] def extractFileName(uri: URI): Try[String] }
wireapp/wire-android-sync-engine
zmessaging/src/main/scala/com/waz/service/assets2/UriHelper.scala
Scala
gpl-3.0
1,024
package com.socrata.soql.typechecker import com.socrata.soql.environment.TypeName import com.socrata.soql.collection.OrderedSet import com.socrata.soql.typed.CoreExpr import scala.util.parsing.input.Position trait TypeInfo[Type] { def booleanLiteralExpr(b: Boolean, pos: Position): Seq[CoreExpr[Nothing, Type]] def stringLiteralExpr(s: String, pos: Position): Seq[CoreExpr[Nothing, Type]] def numberLiteralExpr(n: BigDecimal, pos: Position): Seq[CoreExpr[Nothing, Type]] def nullLiteralExpr(pos: Position): Seq[CoreExpr[Nothing, Type]] def typeFor(name: TypeName): Option[Type] def typeNameFor(typ: Type): TypeName def isOrdered(typ: Type): Boolean def isBoolean(typ: Type): Boolean def isGroupable(typ: Type): Boolean /** The set of all types a function can be declared to accept. That is, * every real type except null. It should be ordered by most-preferred * to least-preferred for null-disambiguation purposes. */ def typeParameterUniverse: OrderedSet[Type] }
socrata-platform/soql-reference
soql-analyzer/src/main/scala/com/socrata/soql/typechecker/TypeInfo.scala
Scala
apache-2.0
1,004
package lila.slack import play.api.libs.json._ import play.api.libs.ws.WS import play.api.Play.current import lila.common.PimpedJson._ private final class SlackClient(url: String, defaultChannel: String) { def apply(msg: SlackMessage): Funit = url.nonEmpty ?? WS.url(url) .post(Json.obj( "username" -> msg.username, "text" -> msg.text, "icon_emoji" -> s":${msg.icon}:", "channel" -> (msg.channel != defaultChannel).option(s"#${msg.channel}") ).noNull).flatMap { case res if res.status == 200 => funit case res => fufail(s"[slack] $url $msg ${res.status} ${res.body}") } }
clarkerubber/lila
modules/slack/src/main/SlackClient.scala
Scala
agpl-3.0
669
import org.scalatest._ import scala.collection.mutable.Stack import scala.collection.mutable import org.scalatest.events._ import scala.util.Random import scala.reflect.NameTransformer class UnitedStates extends Suite { import UnitedStates.allStates import UnitedStates.nestedSuiteCount override def nestedSuites: List[Suite] = allStates.take(nestedSuiteCount).toList override def run(testName: Option[String], reporter: Reporter, stopper: Stopper, filter: Filter, configMap: Map[String, Any], distributor: Option[Distributor], tracker: Tracker) { if (nestedSuiteCount < allStates.length) nestedSuiteCount += 1 super.run(testName, reporter, stopper, filter, configMap, distributor, tracker) } } trait StateSuite extends Suite { import StateSuite.allTestNames import StateSuite.testCounts import StateSuite.testStatuses private def anInitialDuration = Random.nextInt(20) private val simpleName = getClass.getSimpleName.replaceAll("\\\\$", "") override def testNames: Set[String] = allTestNames.take(testCounts(simpleName)).toSet override def testTags: Map[String, Set[String]] = Map() override def run(testName: Option[String], reporter: Reporter, stopper: Stopper, filter: Filter, configMap: Map[String, Any], distributor: Option[Distributor], tracker: Tracker) { val testCount = testCounts(simpleName) if (testCount < allTestNames.length) { testCounts(simpleName) += 1 // The new test is at testCount; Decide if it is pending, and if so, how many times it will stay pending // whether or not it will be pending should be a 50/50 choice val nameOfNewTest = allTestNames(testCount) val isPending = Random.nextInt(2) == 0 testStatuses(simpleName)(nameOfNewTest) = if (isPending) Pending(anInitialDuration, Random.nextInt(30)) // Maximum of 30 times pending before going to some other status else Succeeded(anInitialDuration) } val alterSucceededTests = Random.nextInt(3) == 0 if (alterSucceededTests) { val nameOfTestToAlter = allTestNames(Random.nextInt(testCounts(simpleName)) ) testStatuses(simpleName)(nameOfTestToAlter) match { case Succeeded(duration) => val isIgnored = Random.nextInt(2) == 0 val isCanceled = !isIgnored && (Random.nextInt(2) == 0) // If not ignored or canceled, then make it failed val remaining = Random.nextInt(if (isIgnored) 20 else 15) testStatuses(simpleName)(nameOfTestToAlter) = if (isIgnored) Ignored(duration, remaining) else if (isCanceled) Canceled(duration, remaining) else Failed(duration, remaining) case _ => } } val shouldSlowATest = Random.nextInt(50) == 0 if (shouldSlowATest) { val nameOfTestToSlow = allTestNames(Random.nextInt(testCounts(simpleName))) val slowFactor = Random.nextInt(25) val slowerStatus = testStatuses(simpleName)(nameOfTestToSlow) match { case Succeeded(d) => Succeeded(d * slowFactor) case Pending(d, r) => Pending(d * slowFactor, r) case Canceled(d, r) => Canceled(d * slowFactor, r) case Ignored(d, r) => Ignored(d * slowFactor, r) case Failed(d, r) => Failed(d * slowFactor, r) } testStatuses(simpleName)(nameOfTestToSlow) = slowerStatus } super.run(testName, reporter, stopper, filter, configMap, distributor, tracker) } // Decode suite name enclosed using backtick (`) def getDecodedName(name:String): Option[String] = { val decoded = NameTransformer.decode(name) if(decoded == name) None else Some(decoded) } private def reportTestStarting(theSuite: Suite, report: Reporter, tracker: Tracker, testName: String, testText: String, decodedTestName: Option[String], rerunnable: Option[Rerunner], location: Option[Location]) { report(TestStarting(tracker.nextOrdinal(), theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), getDecodedName(theSuite.suiteName), testName, testText, decodedTestName, Some(MotionToSuppress), location, rerunnable)) } private def reportTestFailed(theSuite: Suite, report: Reporter, throwable: Throwable, testName: String, testText: String, decodedTestName: Option[String], rerunnable: Option[Rerunner], tracker: Tracker, duration: Long, level: Int, includeIcon: Boolean, location: Option[Location]) { val message = getMessageForException(throwable) val formatter = getIndentedText(testText, level, includeIcon) report(TestFailed(tracker.nextOrdinal(), message, theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), getDecodedName(theSuite.suiteName), testName, testText, decodedTestName, Some(throwable), Some(duration), Some(formatter), location, rerunnable)) } private def reportTestCanceled(theSuite: Suite, report: Reporter, throwable: Throwable, testName: String, testText: String, rerunnable: Option[Rerunner], tracker: Tracker, duration: Long, level: Int, includeIcon: Boolean, location: Option[Location]) { val message = getMessageForException(throwable) val formatter = getIndentedText(testText, level, includeIcon) report(TestCanceled(tracker.nextOrdinal(), message, theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), getDecodedName(theSuite.suiteName), testName, testText, getDecodedName(testName), Some(throwable), Some(duration), Some(formatter), location, rerunnable)) } private def reportTestSucceeded(theSuite: Suite, report: Reporter, tracker: Tracker, testName: String, testText: String, decodedTestName: Option[String], duration: Long, formatter: Formatter, rerunnable: Option[Rerunner], location: Option[Location]) { report(TestSucceeded(tracker.nextOrdinal(), theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), getDecodedName(theSuite.suiteName), testName, testText, decodedTestName, Some(duration), Some(formatter), location, rerunnable)) } private def reportTestPending(theSuite: Suite, report: Reporter, tracker: Tracker, testName: String, testText: String, decodedTestName: Option[String], duration: Long, formatter: Formatter, location: Option[Location]) { report(TestPending(tracker.nextOrdinal(), theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), getDecodedName(theSuite.suiteName), testName, testText, decodedTestName, Some(duration), Some(formatter), location)) } private def getMessageForException(e: Throwable): String = if (e.getMessage != null) e.getMessage else e.getClass.getName + " was thrown" private def getIndentedText(testText: String, level: Int, includeIcon: Boolean) = { val formattedText = if (includeIcon) { val testSucceededIcon = "-" (" " * (if (level == 0) 0 else (level - 1))) + testSucceededIcon + " " + testText } else { (" " * level) + testText } IndentedText(formattedText, testText, level) } def indentation(level: Int) = " " * level private def reportTestIgnored(report: Reporter, tracker: Tracker, testName: String, testText: String, decodeTestName: Option[String], level: Int) { val testSucceededIcon = "-" val formattedText = indentation(level - 1) + (testSucceededIcon + " " + testText) report(TestIgnored(tracker.nextOrdinal(), suiteName, suiteId, Some(getClass.getName), getDecodedName(suiteName), testName, testText, decodeTestName, Some(IndentedText(formattedText, testText, level)), Some(ToDoLocation))) } private def handleFailedTest(throwable: Throwable, testName: String, decodedTestName: Option[String], report: Reporter, tracker: Tracker, duration: Long, location: Option[Location]) { val message = getMessageForException(throwable) val formatter = getIndentedText(testName, 1, true) report(TestFailed(tracker.nextOrdinal(), message, suiteName, suiteId, getDecodedName(suiteName), Some(getClass.getName), testName, testName, decodedTestName, Some(throwable), Some(duration), Some(formatter), location, None)) } override def runTest(testName: String, reporter: Reporter, stopper: Stopper, configMap: Map[String, Any], tracker: Tracker) { if (!testStatuses(simpleName)(testName).isInstanceOf[Ignored]) reportTestStarting(this, reporter, tracker, testName, testName, getDecodedName(testName), None, None) val formatter = getIndentedText(testName, 1, true) testStatuses(simpleName)(testName) match { case Pending(duration, remaining) => if (remaining > 1) testStatuses(simpleName)(testName) = Pending(duration, remaining - 1) else testStatuses(simpleName)(testName) = Succeeded(duration) reportTestPending(this, reporter, tracker, testName, testName, getDecodedName(testName), duration, formatter, None) case Ignored(duration, remaining) => if (remaining > 1) testStatuses(simpleName)(testName) = Ignored(duration, remaining - 1) else testStatuses(simpleName)(testName) = Succeeded(duration) reportTestIgnored(reporter, tracker, testName, testName, getDecodedName(testName), 1) case Canceled(duration, remaining) => if (remaining > 1) testStatuses(simpleName)(testName) = Canceled(duration, remaining - 1) else testStatuses(simpleName)(testName) = Succeeded(duration) val e = intercept[TestCanceledException] { cancel("Because of rain") } val message = getMessageForException(e) val formatter = getIndentedText(testName, 1, true) reporter(TestCanceled(tracker.nextOrdinal(), message, suiteName, suiteId, getDecodedName(suiteName), Some(getClass.getName), testName, testName, getDecodedName(testName), Some(e), Some(duration), Some(formatter), Some(ToDoLocation), None)) case Failed(duration, remaining) => if (remaining > 1) testStatuses(simpleName)(testName) = Failed(duration, remaining - 1) else testStatuses(simpleName)(testName) = Succeeded(duration) val e = intercept[TestFailedException] { fail("1 + 1 did not equal 3, even for very large values of 1") } handleFailedTest(e, testName, getDecodedName(testName), reporter, tracker, duration, None) case Succeeded(duration) => reportTestSucceeded(this, reporter, tracker, testName, testName, getDecodedName(testName), duration, formatter, None, None) } } } sealed abstract class Status { val duration: Int } case class Pending(duration: Int, remaining: Int) extends Status case class Succeeded(duration: Int) extends Status case class Canceled(duration: Int, remaining: Int) extends Status case class Ignored(duration: Int, remaining: Int) extends Status case class Failed(duration: Int, remaining: Int) extends Status object StateSuite { val testCounts = mutable.Map( "Alabama" -> 0, "Alaska" -> 0, "Arizona" -> 0, "Arkansas" -> 0, "California" -> 0, "Colorado" -> 0, "Connecticut" -> 0, "Delaware" -> 0, "Florida" -> 0, "Georgia" -> 0, "Hawaii" -> 0, "Idaho" -> 0, "Illinois" -> 0, "Indiana" -> 0, "Iowa" -> 0, "Kansas" -> 0, "Kentucky" -> 0, "Louisiana" -> 0, "Maine" -> 0, "Maryland" -> 0, "Massachusetts" -> 0, "Michigan" -> 0, "Minnesota" -> 0, "Mississippi" -> 0, "Missouri" -> 0, "Montana" -> 0, "Nebraska" -> 0, "Nevada" -> 0, "NewHampshire" -> 0, "NewJersey" -> 0, "NewMexico" -> 0, "NewYork" -> 0, "NorthCarolina" -> 0, "NorthDakota" -> 0, "Ohio" -> 0, "Oklahoma" -> 0, "Oregon" -> 0, "Pennsylvania" -> 0, "RhodeIsland" -> 0, "SouthCarolina" -> 0, "SouthDakota" -> 0, "Tennessee" -> 0, "Texas" -> 0, "Utah" -> 0, "Vermont" -> 0, "Virginia" -> 0, "Washington" -> 0, "WestVirginia" -> 0, "Wisconsin" -> 0, "Wyoming" -> 0 ) val testStatuses = mutable.Map( "Alabama" -> mutable.Map.empty[String, Status], "Alaska" -> mutable.Map.empty[String, Status], "Arizona" -> mutable.Map.empty[String, Status], "Arkansas" -> mutable.Map.empty[String, Status], "California" -> mutable.Map.empty[String, Status], "Colorado" -> mutable.Map.empty[String, Status], "Connecticut" -> mutable.Map.empty[String, Status], "Delaware" -> mutable.Map.empty[String, Status], "Florida" -> mutable.Map.empty[String, Status], "Georgia" -> mutable.Map.empty[String, Status], "Hawaii" -> mutable.Map.empty[String, Status], "Idaho" -> mutable.Map.empty[String, Status], "Illinois" -> mutable.Map.empty[String, Status], "Indiana" -> mutable.Map.empty[String, Status], "Iowa" -> mutable.Map.empty[String, Status], "Kansas" -> mutable.Map.empty[String, Status], "Kentucky" -> mutable.Map.empty[String, Status], "Louisiana" -> mutable.Map.empty[String, Status], "Maine" -> mutable.Map.empty[String, Status], "Maryland" -> mutable.Map.empty[String, Status], "Massachusetts" -> mutable.Map.empty[String, Status], "Michigan" -> mutable.Map.empty[String, Status], "Minnesota" -> mutable.Map.empty[String, Status], "Mississippi" -> mutable.Map.empty[String, Status], "Missouri" -> mutable.Map.empty[String, Status], "Montana" -> mutable.Map.empty[String, Status], "Nebraska" -> mutable.Map.empty[String, Status], "Nevada" -> mutable.Map.empty[String, Status], "NewHampshire" -> mutable.Map.empty[String, Status], "NewJersey" -> mutable.Map.empty[String, Status], "NewMexico" -> mutable.Map.empty[String, Status], "NewYork" -> mutable.Map.empty[String, Status], "NorthCarolina" -> mutable.Map.empty[String, Status], "NorthDakota" -> mutable.Map.empty[String, Status], "Ohio" -> mutable.Map.empty[String, Status], "Oklahoma" -> mutable.Map.empty[String, Status], "Oregon" -> mutable.Map.empty[String, Status], "Pennsylvania" -> mutable.Map.empty[String, Status], "RhodeIsland" -> mutable.Map.empty[String, Status], "SouthCarolina" -> mutable.Map.empty[String, Status], "SouthDakota" -> mutable.Map.empty[String, Status], "Tennessee" -> mutable.Map.empty[String, Status], "Texas" -> mutable.Map.empty[String, Status], "Utah" -> mutable.Map.empty[String, Status], "Vermont" -> mutable.Map.empty[String, Status], "Virginia" -> mutable.Map.empty[String, Status], "Washington" -> mutable.Map.empty[String, Status], "WestVirginia" -> mutable.Map.empty[String, Status], "Wisconsin" -> mutable.Map.empty[String, Status], "Wyoming" -> mutable.Map.empty[String, Status] ) val allTestNames = Vector( "When in the Course of human events", "it becomes necessary for one people to dissolve the political bands which have connected them with another", "and to assume among the powers of the earth", "the separate and equal station to which the Laws of Nature and of Nature's God entitle them", "a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation", "We hold these truths to be self-evident", "that all men are created equal", "that they are endowed by their Creator with certain unalienable Rights", "that among these are Life, Liberty and the pursuit of Happiness.", "That to secure these rights", "Governments are instituted among Men", "deriving their just powers from the consent of the governed", "That whenever any Form of Government becomes destructive of these ends", "it is the Right of the People to alter or to abolish it", "and to institute new Government", "laying its foundation on such principles and organizing its powers in such form", "as to them shall seem most likely to effect their Safety and Happiness.", "Prudence, indeed, will dictate that Governments long established should not be changed for light and transient causes", "and accordingly all experience hath shewn", "that mankind are more disposed to suffer", "while evils are sufferable", "than to right themselves by abolishing the forms to which they are accustomed", "But when a long train of abuses and usurpations", "pursuing invariably the same Object evinces a design to reduce them under absolute Despotism", "it is their right", "it is their duty", "to throw off such Government", "and to provide new Guards for their future security", "Such has been the patient sufferance of these Colonies", "and such is now the necessity which constrains them to alter their former Systems of Government", "The history of the present King of Great Britain is a history of repeated injuries and usurpations", "all having in direct object the establishment of an absolute Tyranny over these States", "To prove this, let Facts be submitted to a candid world.", "He has refused his Assent to Laws, the most wholesome and necessary for the public good", "He has forbidden his Governors to pass Laws of immediate and pressing importance", "unless suspended in their operation till his Assent should be obtained", "and when so suspended, he has utterly neglected to attend to them", "He has refused to pass other Laws for the accommodation of large districts of people", "unless those people would relinquish the right of Representation in the Legislature", "a right inestimable to them and formidable to tyrants only ", "He has called together legislative bodies at places unusual, uncomfortable, and distant from the depository of their public Records", "for the sole purpose of fatiguing them into compliance with his measures ", "He has dissolved Representative Houses repeatedly", "for opposing with manly firmness his invasions on the rights of the people.", "He has refused for a long time, after such dissolutions, to cause others to be elected", "whereby the Legislative powers, incapable of Annihilation, have returned to the People at large for their exercise", "the State remaining in the mean time exposed to all the dangers of invasion from without, and convulsions within.", "He has endeavoured to prevent the population of these States", "for that purpose obstructing the Laws for Naturalization of Foreigners", "refusing to pass others to encourage their migrations hither", "and raising the conditions of new Appropriations of Lands", "He has obstructed the Administration of Justice", "by refusing his Assent to Laws for establishing Judiciary powers.", "He has made Judges dependent on his Will alone", "for the tenure of their offices", "and the amount and payment of their salaries.", "He has erected a multitude of New Offices", "and sent hither swarms of Officers to harrass our people, and eat out their substance.", "He has kept among us, in times of peace, Standing Armies without the Consent of our legislatures", "He has affected to render the Military independent of and superior to the Civil power.", "He has combined with others to subject us to a jurisdiction foreign to our constitution, and unacknowledged by our laws", "giving his Assent to their Acts of pretended Legislation:", "For Quartering large bodies of armed troops among us", "For protecting them, by a mock Trial, from punishment for any Murders which they should commit on the Inhabitants of these States", "For cutting off our Trade with all parts of the world", "For imposing Taxes on us without our Consent:", "For depriving us in many cases, of the benefits of Trial by Jury", "For transporting us beyond Seas to be tried for pretended offences", "For abolishing the free System of English Laws in a neighbouring Province", "establishing therein an Arbitrary government", "and enlarging its Boundaries so as to render it at once an example and fit instrument for introducing the same absolute rule into these Colonies", "For taking away our Charters, abolishing our most valuable Laws, and altering fundamentally the Forms of our Governments", "For suspending our own Legislatures, and declaring themselves invested with power to legislate for us in all cases whatsoever", "He has abdicated Government here, by declaring us out of his Protection and waging War against us", "He has plundered our seas, ravaged our Coasts, burnt our towns, and destroyed the lives of our people", "He is at this time transporting large Armies of foreign Mercenaries to compleat the works of death, desolation and tyranny", "already begun with circumstances of Cruelty & perfidy scarcely paralleled in the most barbarous ages", "and totally unworthy the Head of a civilized nation.", "He has constrained our fellow Citizens taken Captive on the high Seas to bear Arms against their Country", "to become the executioners of their friends and Brethren", "or to fall themselves by their Hands", "He has excited domestic insurrections amongst us", "and has endeavoured to bring on the inhabitants of our frontiers", "the merciless Indian Savages, whose known rule of warfare", "is an undistinguished destruction of all ages, sexes and conditions.", "In every stage of these Oppressions We have Petitioned for Redress in the most humble terms", "Our repeated Petitions have been answered only by repeated injury", "A Prince whose character is thus marked by every act which may define a Tyrant", "is unfit to be the ruler of a free people.", "Nor have We been wanting in attentions to our Brittish brethren", "We have warned them from time to time of attempts by their legislature to extend an unwarrantable jurisdiction over us", "We have reminded them of the circumstances of our emigration and settlement here", "We have appealed to their native justice and magnanimity", "and we have conjured them by the ties of our common kindred to disavow these usurpations", "which, would inevitably interrupt our connections and correspondence", "They too have been deaf to the voice of justice and of consanguinity", "We must, therefore, acquiesce in the necessity, which denounces our Separation", "and hold them, as we hold the rest of mankind, Enemies in War, in Peace Friends", "We, therefore, the Representatives of the united States of America", "in General Congress, Assembled, appealing to the Supreme Judge of the world for the rectitude of our intentions", "do, in the Name, and by Authority of the good People of these Colonies", "solemnly publish and declare, That these United Colonies are", "and of Right ought to be Free and Independent States", "that they are Absolved from all Allegiance to the British Crown", "and that all political connection between them and the State of Great Britain", "is and ought to be totally dissolved", "and that as Free and Independent States", "they have full Power to levy War", "conclude Peace", "contract Alliances", "establish Commerce", "and to do all other Acts and Things which Independent States may of right do", "And for the support of this Declaration", "with a firm reliance on the protection of divine Providence", "we mutually pledge to each other our Lives", "our Fortunes and our sacred Honor" ) } object UnitedStates { private var nestedSuiteCount = 0 val allStates = Vector( Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware, Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, NewHampshire, NewJersey, NewMexico, NewYork, NorthCarolina, NorthDakota, Ohio, Oklahoma, Oregon, Pennsylvania, RhodeIsland, SouthCarolina, SouthDakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, WestVirginia, Wisconsin, Wyoming ) } object Alabama extends StateSuite object Alaska extends StateSuite object Arizona extends StateSuite object Arkansas extends StateSuite object California extends StateSuite object Colorado extends StateSuite object Connecticut extends StateSuite object Delaware extends StateSuite object Florida extends StateSuite object Georgia extends StateSuite object Hawaii extends StateSuite object Idaho extends StateSuite object Illinois extends StateSuite object Indiana extends StateSuite object Iowa extends StateSuite object Kansas extends StateSuite object Kentucky extends StateSuite object Louisiana extends StateSuite object Maine extends StateSuite object Maryland extends StateSuite object Massachusetts extends StateSuite object Michigan extends StateSuite object Minnesota extends StateSuite object Mississippi extends StateSuite object Missouri extends StateSuite object Montana extends StateSuite object Nebraska extends StateSuite object Nevada extends StateSuite object NewHampshire extends StateSuite object NewJersey extends StateSuite object NewMexico extends StateSuite object NewYork extends StateSuite object NorthCarolina extends StateSuite object NorthDakota extends StateSuite object Ohio extends StateSuite object Oklahoma extends StateSuite object Oregon extends StateSuite object Pennsylvania extends StateSuite object RhodeIsland extends StateSuite object SouthCarolina extends StateSuite object SouthDakota extends StateSuite object Tennessee extends StateSuite object Texas extends StateSuite object Utah extends StateSuite object Vermont extends StateSuite object Virginia extends StateSuite object Washington extends StateSuite object WestVirginia extends StateSuite object Wisconsin extends StateSuite object Wyoming extends StateSuite
epishkin/scalatest-google-code
src/us/US.scala
Scala
apache-2.0
26,490