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
|
---|---|---|---|---|---|
/*
* Copyright 2010 Data Fueled
*
* 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.datafueled.trace.util
import com.datafueled.trace.core.datamodel.Span
class Timer(val parentSpan: Option[Span], val startTime: Long) {
def stop : Span = {
if (parentSpan.isDefined) {
return Span.make(parentSpan.get.id, startTime, System.nanoTime())
} else {
return Span.make(startTime, System.nanoTime())
}
}
}
object Timer {
def start = new Timer(None, System.nanoTime())
}
| waywardmonkeys/trace | trace-local/src/main/scala/com/datafueled/trace/local/util/Timer.scala | Scala | apache-2.0 | 1,016 |
package com.github.hgiddens.ausms
package telstra
import io.circe.Json
import io.circe.syntax._
import org.specs2.matcher.{ Matcher, MatcherMacros }
import org.specs2.mutable.Specification
object MessageStatusResponseSpec extends Specification with MatcherMacros {
def body(status: String) =
Json.obj(
"to" -> "0400000000".asJson,
"receivedTimestamp" -> "2015-02-05T14:10:14+11:00".asJson,
"sentTimestamp" -> "2015-02-05T14:10:12+11:00".asJson,
"status" -> status.asJson
)
def beResponseWithStatus(status: DeliveryStatus): Matcher[MessageStatusResponse] =
matchA[MessageStatusResponse].status(status)
"Decoding JSON" should {
"decode PEND status" in {
body("PEND").as[MessageStatusResponse].toEither must beRight(beResponseWithStatus(DeliveryStatus.Pending))
}
"decode SENT status" in {
body("SENT").as[MessageStatusResponse].toEither must beRight(beResponseWithStatus(DeliveryStatus.Sent))
}
"decode DELIVRD status" in {
body("DELIVRD").as[MessageStatusResponse].toEither must beRight(beResponseWithStatus(DeliveryStatus.Delivered))
}
"decode READ status" in {
body("READ").as[MessageStatusResponse].toEither must beRight(beResponseWithStatus(DeliveryStatus.Read))
}
}
}
| hgiddens/au-sms | telstra-client/src/test/scala/com/github/hgiddens/ausms/telstra/ResourcesSpec.scala | Scala | mit | 1,279 |
package org.elasticmq.rest.sqs.model
import org.elasticmq.rest.sqs.model.RedrivePolicy.{BackwardCompatibleRedrivePolicy, RedrivePolicy}
import spray.json.{
DefaultJsonProtocol,
JsNumber,
JsObject,
JsString,
JsValue,
JsonFormat,
JsonReader,
JsonWriter,
deserializationError
}
object RedrivePolicyJson extends DefaultJsonProtocol {
/** Regexp extracting region, account and queueName from AWS resource id for example it will match
* arn:aws:sqs:us-west-2:123456:queue and extract us-west-2, 123456 and queue in groups
*/
private val Arn = "(?:.+:(.+)?:(.+)?:)?(.+)".r
implicit val backwardCompatibleFormat: JsonFormat[BackwardCompatibleRedrivePolicy] = lift(
new JsonReader[BackwardCompatibleRedrivePolicy] {
override def read(json: JsValue): BackwardCompatibleRedrivePolicy = {
json.asJsObject
.getFields("deadLetterTargetArn", "maxReceiveCount") match {
case Seq(JsString(Arn(region, accountId, queueName)), JsString(maxReceiveCount)) =>
GenericRedrivePolicy(queueName, Option(region), Option(accountId), maxReceiveCount.toInt)
case Seq(JsString(Arn(region, accountId, queueName)), JsNumber(maxReceiveCount)) =>
GenericRedrivePolicy(queueName, Option(region), Option(accountId), maxReceiveCount.toInt)
case _ =>
deserializationError(
"Expected fields: 'deadLetterTargetArn' (JSON string) and 'maxReceiveCount' (JSON number)"
)
}
}
}
)
implicit val format: JsonFormat[RedrivePolicy] = lift(new JsonWriter[RedrivePolicy] {
override def write(obj: RedrivePolicy): JsValue = {
JsObject(
"deadLetterTargetArn" -> JsString(s"arn:aws:sqs:${obj.region}:${obj.accountId}:${obj.queueName}"),
"maxReceiveCount" -> JsNumber(obj.maxReceiveCount)
)
}
})
}
| adamw/elasticmq | rest/rest-sqs/src/main/scala/org/elasticmq/rest/sqs/model/RedrivePolicyJson.scala | Scala | apache-2.0 | 1,859 |
/*
* Copyright 2015
*
* 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 influxdbreporter.core.metrics.push
import influxdbreporter.core.Tag
import influxdbreporter.core.metrics.Metric.CodahaleMeter
import scala.annotation.varargs
class Meter extends TagRelatedPushingMetric[CodahaleMeter] {
override protected def createMetric(): CodahaleMeter = new CodahaleMeter()
@varargs def mark(tags: Tag*): Unit = mark(1L, tags: _*)
@varargs def mark(n: Long,tags: Tag*): Unit = increaseMetric(tags.toList, _.mark(n))
}
| TouK/influxdb-reporter | core/src/main/scala/influxdbreporter/core/metrics/push/Meter.scala | Scala | apache-2.0 | 1,041 |
/*
* The MIT License (MIT)
*
* Copyright (C) 2012 47 Degrees, LLC http://47deg.com [email protected]
*
* 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.
*/
package com.fortysevendeg.mvessel.util
import java.text.SimpleDateFormat
import java.util.Date
import com.fortysevendeg.mvessel.logging.LogWrapper
import scala.util.{Failure, Success, Try}
trait DateUtils {
val log: LogWrapper
private[this] val dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S")
def parseDate(date: String): Option[java.util.Date] =
Try(dateFormat.parse(date)) match {
case Success(d) => Some(d)
case Failure(e) =>
log.e("Can't parse date", Some(e))
None
}
def formatDate(date: Date): Option[String] =
Try(dateFormat.format(date)) match {
case Success(d) => Some(d)
case Failure(e) =>
log.e("Can't format date", Some(e))
None
}
} | 47deg/mvessel | core/src/main/scala/com/fortysevendeg/mvessel/util/DateUtils.scala | Scala | mit | 1,440 |
/*
* Copyright (C) 2012 Pavel Fatin <http://pavelfatin.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/>.
*/
package com.pavelfatin.fs
package internal
package toyfs
private class MockRecordStorage(maxNameLength: Int, content: Record*) extends RecordStorage {
private val buffer = content.toBuffer
def nameLength = maxNameLength
def get(index: Int) = buffer(index)
def set(index: Int, record: Record) {
if (index == buffer.size)
buffer += record
else
buffer(index) = record
}
def truncate(size: Int) {
if (size < buffer.size)
buffer.remove(size, buffer.size - size)
}
def records: Seq[Record] = buffer.toList
override def toString = s"${getClass.getSimpleName}(${buffer.mkString(", ")})"
} | pavelfatin/toyfs | src/test/scala/com/pavelfatin/fs/internal/toyfs/MockRecordStorage.scala | Scala | gpl-3.0 | 1,350 |
/*
* 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.execution
import org.apache.spark.{MapOutputStatistics, SparkFunSuite}
import org.apache.spark.sql.execution.adaptive.ShufflePartitionsUtil
class ShufflePartitionsUtilSuite extends SparkFunSuite {
private def checkEstimation(
bytesByPartitionIdArray: Array[Array[Long]],
expectedPartitionStartIndices: Seq[CoalescedPartitionSpec],
targetSize: Long,
minNumPartitions: Int = 1): Unit = {
val mapOutputStatistics = bytesByPartitionIdArray.zipWithIndex.map {
case (bytesByPartitionId, index) =>
new MapOutputStatistics(index, bytesByPartitionId)
}
val estimatedPartitionStartIndices = ShufflePartitionsUtil.coalescePartitions(
mapOutputStatistics,
targetSize,
minNumPartitions)
assert(estimatedPartitionStartIndices === expectedPartitionStartIndices)
}
test("1 shuffle") {
val targetSize = 100
{
// Some bytes per partition are 0 and total size is less than the target size.
// 1 coalesced partition is expected.
val bytesByPartitionId = Array[Long](10, 0, 20, 0, 0)
val expectedPartitionSpecs = Seq(CoalescedPartitionSpec(0, 5))
checkEstimation(Array(bytesByPartitionId), expectedPartitionSpecs, targetSize)
}
{
// 2 coalesced partitions are expected.
val bytesByPartitionId = Array[Long](10, 0, 90, 20, 0)
val expectedPartitionSpecs = Seq(CoalescedPartitionSpec(0, 3), CoalescedPartitionSpec(3, 5))
checkEstimation(Array(bytesByPartitionId), expectedPartitionSpecs, targetSize)
}
{
// There are a few large shuffle partitions.
val bytesByPartitionId = Array[Long](110, 10, 100, 110, 0)
val expectedPartitionSpecs = Seq(
CoalescedPartitionSpec(0, 1),
CoalescedPartitionSpec(1, 2),
CoalescedPartitionSpec(2, 3),
CoalescedPartitionSpec(3, 4))
checkEstimation(Array(bytesByPartitionId), expectedPartitionSpecs, targetSize)
}
{
// All shuffle partitions are larger than the targeted size.
val bytesByPartitionId = Array[Long](100, 110, 100, 110, 110)
val expectedPartitionSpecs = Seq(
CoalescedPartitionSpec(0, 1),
CoalescedPartitionSpec(1, 2),
CoalescedPartitionSpec(2, 3),
CoalescedPartitionSpec(3, 4),
CoalescedPartitionSpec(4, 5))
checkEstimation(Array(bytesByPartitionId), expectedPartitionSpecs, targetSize)
}
{
// The last shuffle partition is in a single coalesced partition.
val bytesByPartitionId = Array[Long](30, 30, 0, 40, 110)
val expectedPartitionSpecs = Seq(CoalescedPartitionSpec(0, 4), CoalescedPartitionSpec(4, 5))
checkEstimation(Array(bytesByPartitionId), expectedPartitionSpecs, targetSize)
}
}
test("2 shuffles") {
val targetSize = 100
{
// If there are multiple values of the number of shuffle partitions,
// we should see an assertion error.
val bytesByPartitionId1 = Array[Long](0, 0, 0, 0, 0)
val bytesByPartitionId2 = Array[Long](0, 0, 0, 0, 0, 0)
intercept[AssertionError] {
checkEstimation(Array(bytesByPartitionId1, bytesByPartitionId2), Seq.empty, targetSize)
}
}
{
// Some bytes per partition are 0.
// 1 coalesced partition is expected.
val bytesByPartitionId1 = Array[Long](0, 10, 0, 20, 0)
val bytesByPartitionId2 = Array[Long](30, 0, 20, 0, 20)
val expectedPartitionSpecs = Seq(CoalescedPartitionSpec(0, 5))
checkEstimation(
Array(bytesByPartitionId1, bytesByPartitionId2),
expectedPartitionSpecs,
targetSize)
}
{
// 2 coalesced partition are expected.
val bytesByPartitionId1 = Array[Long](0, 10, 0, 20, 0)
val bytesByPartitionId2 = Array[Long](30, 0, 70, 0, 30)
val expectedPartitionSpecs = Seq(
CoalescedPartitionSpec(0, 2),
CoalescedPartitionSpec(2, 4),
CoalescedPartitionSpec(4, 5))
checkEstimation(
Array(bytesByPartitionId1, bytesByPartitionId2),
expectedPartitionSpecs,
targetSize)
}
{
// 4 coalesced partition are expected.
val bytesByPartitionId1 = Array[Long](0, 99, 0, 20, 0)
val bytesByPartitionId2 = Array[Long](30, 0, 70, 0, 30)
val expectedPartitionSpecs = Seq(
CoalescedPartitionSpec(0, 1),
CoalescedPartitionSpec(1, 2),
CoalescedPartitionSpec(2, 4),
CoalescedPartitionSpec(4, 5))
checkEstimation(
Array(bytesByPartitionId1, bytesByPartitionId2),
expectedPartitionSpecs,
targetSize)
}
{
// 2 coalesced partition are needed.
val bytesByPartitionId1 = Array[Long](0, 100, 0, 30, 0)
val bytesByPartitionId2 = Array[Long](30, 0, 70, 0, 30)
val expectedPartitionSpecs = Seq(
CoalescedPartitionSpec(0, 1),
CoalescedPartitionSpec(1, 2),
CoalescedPartitionSpec(2, 4),
CoalescedPartitionSpec(4, 5))
checkEstimation(
Array(bytesByPartitionId1, bytesByPartitionId2),
expectedPartitionSpecs,
targetSize)
}
{
// There are a few large shuffle partitions.
val bytesByPartitionId1 = Array[Long](0, 100, 40, 30, 0)
val bytesByPartitionId2 = Array[Long](30, 0, 60, 0, 110)
val expectedPartitionSpecs = Seq(
CoalescedPartitionSpec(0, 1),
CoalescedPartitionSpec(1, 2),
CoalescedPartitionSpec(2, 3),
CoalescedPartitionSpec(3, 4),
CoalescedPartitionSpec(4, 5))
checkEstimation(
Array(bytesByPartitionId1, bytesByPartitionId2),
expectedPartitionSpecs,
targetSize)
}
{
// All pairs of shuffle partitions are larger than the targeted size.
val bytesByPartitionId1 = Array[Long](100, 100, 40, 30, 0)
val bytesByPartitionId2 = Array[Long](30, 0, 60, 70, 110)
val expectedPartitionSpecs = Seq(
CoalescedPartitionSpec(0, 1),
CoalescedPartitionSpec(1, 2),
CoalescedPartitionSpec(2, 3),
CoalescedPartitionSpec(3, 4),
CoalescedPartitionSpec(4, 5))
checkEstimation(
Array(bytesByPartitionId1, bytesByPartitionId2),
expectedPartitionSpecs,
targetSize)
}
}
test("enforce minimal number of coalesced partitions") {
val targetSize = 100
val minNumPartitions = 2
{
// The minimal number of coalesced partitions is not enforced because
// the size of data is 0.
val bytesByPartitionId1 = Array[Long](0, 0, 0, 0, 0)
val bytesByPartitionId2 = Array[Long](0, 0, 0, 0, 0)
checkEstimation(
Array(bytesByPartitionId1, bytesByPartitionId2),
Seq.empty, targetSize, minNumPartitions)
}
{
// The minimal number of coalesced partitions is not enforced because
// there are too many 0-size partitions.
val bytesByPartitionId1 = Array[Long](200, 0, 0)
val bytesByPartitionId2 = Array[Long](100, 0, 0)
val expectedPartitionSpecs = Seq(CoalescedPartitionSpec(0, 1))
checkEstimation(
Array(bytesByPartitionId1, bytesByPartitionId2),
expectedPartitionSpecs,
targetSize, minNumPartitions)
}
{
// The minimal number of coalesced partitions is enforced.
val bytesByPartitionId1 = Array[Long](10, 5, 5, 0, 20)
val bytesByPartitionId2 = Array[Long](5, 10, 0, 10, 5)
val expectedPartitionSpecs = Seq(CoalescedPartitionSpec(0, 3), CoalescedPartitionSpec(3, 5))
checkEstimation(
Array(bytesByPartitionId1, bytesByPartitionId2),
expectedPartitionSpecs,
targetSize, minNumPartitions)
}
{
// The number of coalesced partitions is determined by the algorithm.
val bytesByPartitionId1 = Array[Long](10, 50, 20, 80, 20)
val bytesByPartitionId2 = Array[Long](40, 10, 0, 10, 30)
val expectedPartitionSpecs = Seq(
CoalescedPartitionSpec(0, 1),
CoalescedPartitionSpec(1, 3),
CoalescedPartitionSpec(3, 4),
CoalescedPartitionSpec(4, 5))
checkEstimation(
Array(bytesByPartitionId1, bytesByPartitionId2),
expectedPartitionSpecs,
targetSize, minNumPartitions)
}
}
test("do not create partition spec for 0-size partitions") {
val targetSize = 100
val minNumPartitions = 2
{
// 1 shuffle: All bytes per partition are 0, no partition spec created.
val bytesByPartitionId = Array[Long](0, 0, 0, 0, 0)
checkEstimation(Array(bytesByPartitionId), Seq.empty, targetSize)
}
{
// 2 shuffles: All bytes per partition are 0, no partition spec created.
val bytesByPartitionId1 = Array[Long](0, 0, 0, 0, 0)
val bytesByPartitionId2 = Array[Long](0, 0, 0, 0, 0)
checkEstimation(Array(bytesByPartitionId1, bytesByPartitionId2), Seq.empty, targetSize)
}
{
// No partition spec created for the 0-size partitions.
val bytesByPartitionId1 = Array[Long](200, 0, 0, 0, 0)
val bytesByPartitionId2 = Array[Long](100, 0, 300, 0, 0)
val expectedPartitionSpecs = Seq(
CoalescedPartitionSpec(0, 1),
CoalescedPartitionSpec(2, 3))
checkEstimation(
Array(bytesByPartitionId1, bytesByPartitionId2),
expectedPartitionSpecs,
targetSize, minNumPartitions)
}
}
test("splitSizeListByTargetSize") {
val targetSize = 100
// merge the small partitions at the beginning/end
val sizeList1 = Seq[Long](15, 90, 15, 15, 15, 90, 15)
assert(ShufflePartitionsUtil.splitSizeListByTargetSize(sizeList1, targetSize).toSeq ==
Seq(0, 2, 5))
// merge the small partitions in the middle
val sizeList2 = Seq[Long](30, 15, 90, 10, 90, 15, 30)
assert(ShufflePartitionsUtil.splitSizeListByTargetSize(sizeList2, targetSize).toSeq ==
Seq(0, 2, 4, 5))
// merge small partitions if the partition itself is smaller than
// targetSize * SMALL_PARTITION_FACTOR
val sizeList3 = Seq[Long](15, 1000, 15, 1000)
assert(ShufflePartitionsUtil.splitSizeListByTargetSize(sizeList3, targetSize).toSeq ==
Seq(0, 3))
// merge small partitions if the combined size is smaller than
// targetSize * MERGED_PARTITION_FACTOR
val sizeList4 = Seq[Long](35, 75, 90, 20, 35, 25, 35)
assert(ShufflePartitionsUtil.splitSizeListByTargetSize(sizeList4, targetSize).toSeq ==
Seq(0, 2, 3))
}
}
| ConeyLiu/spark | sql/core/src/test/scala/org/apache/spark/sql/execution/ShufflePartitionsUtilSuite.scala | Scala | apache-2.0 | 11,185 |
/***********************************************************************
* Copyright (c) 2013-2017 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.fs.tools.compact
import java.io.File
import com.beust.jcommander.{Parameter, ParameterException, Parameters}
import com.typesafe.scalalogging.LazyLogging
import org.apache.hadoop.fs.Path
import org.locationtech.geomesa.fs.FileSystemDataStore
import org.locationtech.geomesa.fs.tools.ingest.TempDirParam
import org.locationtech.geomesa.fs.tools.{FsDataStoreCommand, FsParams, PartitionParam}
import org.locationtech.geomesa.tools.ingest.AbstractIngest
import org.locationtech.geomesa.tools.ingest.AbstractIngest.PrintProgress
import org.locationtech.geomesa.tools.{Command, RequiredTypeNameParam}
import org.locationtech.geomesa.utils.classpath.ClassPathUtils
import org.locationtech.geomesa.utils.text.TextTools
import scala.collection.JavaConversions._
class CompactCommand extends FsDataStoreCommand with LazyLogging {
override val name: String = "compact"
override val params = new CompactParams
override def execute(): Unit = {
if (!Seq(RunModes.Distributed, RunModes.Local).contains(params.runMode)) {
throw new ParameterException(s"Invalid run mode '${params.runMode}'")
}
withDataStore(compact)
}
val libjarsFile: String = "org/locationtech/geomesa/fs/tools/ingest-libjars.list"
def libjarsPaths: Iterator[() => Seq[File]] = Iterator(
() => ClassPathUtils.getJarsFromEnvironment("GEOMESA_FS_HOME"),
() => ClassPathUtils.getJarsFromClasspath(classOf[FileSystemDataStore])
)
def compact(ds: FileSystemDataStore): Unit = {
Command.user.info(s"Beginning Compaction Process...updating metadata")
ds.storage.updateMetadata(params.featureName)
Command.user.info(s"Metadata update complete")
val m = ds.storage.getMetadata(params.featureName)
val allPartitions = m.getPartitions
val toCompact: Seq[String] = if (params.partitions.nonEmpty) {
params.partitions.filterNot(allPartitions.contains).headOption.foreach { p =>
throw new ParameterException(s"Partition $p cannot be found in metadata")
}
params.partitions
} else {
allPartitions
}
Command.user.info(s"Compacting ${toCompact.size} partitions")
params.runMode match {
case RunModes.Local =>
toCompact.foreach { p =>
logger.info(s"Compacting ${params.featureName}:$p")
ds.storage.compact(params.featureName, p)
logger.info(s"Completed compaction of ${params.featureName}:$p")
}
case RunModes.Distributed =>
val tempDir = Option(params.tempDir).map(t => new Path(t))
val job = new ParquetCompactionJob(ds.getSchema(params.featureName), ds.root, tempDir)
val statusCallback = new PrintProgress(System.err, TextTools.buildString(' ', 60), '\\u003d', '\\u003e', '\\u003e')
val start = System.currentTimeMillis()
val (success, failed) = job.run(connection, params.featureName, toCompact, libjarsFile, libjarsPaths, statusCallback)
Command.user.info(s"Distributed compaction complete in ${TextTools.getTime(start)}")
Command.user.info(AbstractIngest.getStatInfo(success, failed))
}
Command.user.info(s"Compaction completed")
}
}
@Parameters(commandDescription = "Compact partitions")
class CompactParams extends FsParams with RequiredTypeNameParam with TempDirParam with PartitionParam {
@Parameter(names = Array("--mode"), description = "Run mode for compaction ('local' or 'distributed' via mapreduce)", required = false)
var runMode: String = "distributed"
}
object RunModes {
val Distributed = "distributed"
val Local = "local"
} | ronq/geomesa | geomesa-fs/geomesa-fs-tools/src/main/scala/org/locationtech/geomesa/fs/tools/compact/CompactCommand.scala | Scala | apache-2.0 | 4,039 |
/*
* Copyright (c) 2014-2021 by The Monix Project Developers.
* See the project homepage at: https://monix.io
*
* 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 monix.reactive.observers
import monix.execution.Ack.{Continue, Stop}
import monix.execution.exceptions.DummyException
import monix.reactive.{BaseTestSuite, Observer}
object ContramapObserverSuite extends BaseTestSuite {
test("Observer.contramap equivalence with plain Observer") { implicit s =>
check1 { xs: List[Int] =>
var sum = 0
val plainObserver: Observer[Int] = new Observer[Int] {
def onError(ex: Throwable): Unit = ()
def onComplete(): Unit = sum += 100
def onNext(elem: Int) = {
sum += elem
Continue
}
}
val contramapObserver: Observer[Long] =
plainObserver.contramap(_.toInt)
val plainAck = plainObserver.onNextAll(xs)
val contraAck = contramapObserver.onNextAll(xs.map(_.toLong))
s.tick()
plainAck.syncTryFlatten(s) == Continue &&
contraAck.syncTryFlatten(s) == Continue &&
sum == xs.sum * 2
}
}
test("Observer.contramap protects against user code") { implicit s =>
val dummy = DummyException("dummy")
val out: Observer[Long] = (Observer.empty[Int]: Observer[Int])
.contramap(_ => throw dummy)
s.tick()
assertEquals(out.onNext(1), Stop)
}
test("Observer.contramap works") { implicit s =>
var isDone = 0
val intObserver: Observer[Int] = new Observer[Int] {
def onError(ex: Throwable): Unit = isDone += 1
def onComplete(): Unit = isDone += 1
def onNext(elem: Int) = Continue
}
val doubleObserver: Observer[Double] = intObserver.contramap(_.toInt)
assertEquals(doubleObserver.onNext(1.0), Continue)
doubleObserver.onComplete()
assertEquals(isDone, 1)
doubleObserver.onError(DummyException("dummy"))
assertEquals(isDone, 1)
assertEquals(doubleObserver.onNext(2.0), Stop)
}
}
| monifu/monix | monix-reactive/shared/src/test/scala/monix/reactive/observers/ContramapObserverSuite.scala | Scala | apache-2.0 | 2,495 |
package com.bostontechnologies.quickfixs.messages
import scala.collection.JavaConversions._
import quickfix.field._
import quickfix.Message
import com.bostontechnologies.quickfixs.components.{RoutingGroup, Entry}
import com.bostontechnologies.quickfixs.fields.RichGroup
import quickfix.fix50.MarketDataSnapshotFullRefresh
class RichMarketDataSnapshotFullRefresh private(self: Message) extends RichMessage(self) with InstrumentFields[Message] {
require(RichMessage.isA(self, RichMarketDataSnapshotFullRefresh.msgType))
def hasRequestId: Boolean = self.isSetField(MDReqID.FIELD)
def requestId: String = self.getString(MDReqID.FIELD)
def requestId_=(id: String) {
self.setString(MDReqID.FIELD, id)
}
def entryCount: Int = self.getInt(NoMDEntries.FIELD)
def entries: List[Entry] = self.getGroups(NoMDEntries.FIELD).map( Entry(_) ).toList
def routingGroups: List[RoutingGroup] = self.getGroups(NoRoutingIDs.FIELD).map( RoutingGroup(_)).toList
def +=(group: RichGroup) {
self.addGroup(group.toFields)
}
def ++=(groups: Iterable[RichGroup]) {
groups.foreach( this += _)
}
}
object RichMarketDataSnapshotFullRefresh extends RichMessageExtractor[RichMarketDataSnapshotFullRefresh, MarketDataSnapshotFullRefresh] {
val msgType = MsgType.MARKET_DATA_SNAPSHOT_FULL_REFRESH
def apply(message: quickfix.fix50.MarketDataSnapshotFullRefresh): RichMarketDataSnapshotFullRefresh =
new RichMarketDataSnapshotFullRefresh(message)
def new50Message: RichMarketDataSnapshotFullRefresh = this(new quickfix.fix50.MarketDataSnapshotFullRefresh)
def apply(message: quickfix.fix44.MarketDataSnapshotFullRefresh): RichMarketDataSnapshotFullRefresh =
new RichMarketDataSnapshotFullRefresh(message)
def new44Message: RichMarketDataSnapshotFullRefresh = this(new quickfix.fix44.MarketDataSnapshotFullRefresh)
def newMessage: RichMarketDataSnapshotFullRefresh = new RichMarketDataSnapshotFullRefresh(
RichMessage.newMessage(msgType).self)
}
| Forexware/quickfixs | src/main/scala/com/bostontechnologies/quickfixs/messages/RichMarketDataSnapshotFullRefresh.scala | Scala | apache-2.0 | 1,964 |
package org.nkvoll.javabin.service.internal
import org.elasticsearch.client.Client
import org.elasticsearch.client.transport.TransportClient
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.common.transport.InetSocketTransportAddress
import org.elasticsearch.node.{ NodeBuilder, Node }
import org.elasticsearch.rest.RestController
trait ElasticsearchClientCreation extends ElasticsearchReflections {
def createElasticsearchClient(mode: String, elasticsearchSettings: Settings): (Option[Node], Client, RestController) = {
if (mode == "transport")
createTransportElasticsearchClient(elasticsearchSettings)
else
createNodeElasticsearchClient(elasticsearchSettings)
}
def createNodeElasticsearchClient(elasticsearchSettings: Settings): (Option[Node], Client, RestController) = {
val node = NodeBuilder.nodeBuilder().settings(elasticsearchSettings).build()
// get the client for the node
val client = node.client()
// reflect the rest controller from the node, so we can send it internal http requests
val restController = getRestController(node)
(Some(node), client, restController)
}
def createTransportElasticsearchClient(elasticsearchSettings: Settings): (Option[Node], Client, RestController) = {
// create the transport client
val client = new TransportClient(elasticsearchSettings)
elasticsearchSettings.getAsArray("transport.initial_hosts", Array.empty[String]) foreach { hostPort =>
hostPort.split(':') match {
case Array(host, port) =>
client.addTransportAddress(new InetSocketTransportAddress(host, Integer.parseInt(port)))
}
}
// reflect the rest controller from the node, so we can send it internal http requests
val restController = getRestController(client)
(None, client, restController)
}
}
| nkvoll/javabin-rest-on-akka | src/main/scala/org/nkvoll/javabin/service/internal/ElasticsearchClientCreation.scala | Scala | mit | 1,853 |
/*
* Copyright (C) 2005, The Beangle Software.
*
* 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.beangle.db.transport.schema
import java.sql.Connection
import javax.sql.DataSource
import org.beangle.commons.io.IOs
import org.beangle.commons.logging.Logging
import org.beangle.data.jdbc.engine.Engine
import org.beangle.data.jdbc.meta.{MetadataLoader, Schema, Sequence, Table}
import org.beangle.data.jdbc.query.{JdbcExecutor, ResultSetIterator}
import org.beangle.db.transport.DataWrapper
class SchemaWrapper(val dataSource: DataSource, val engine: Engine, val schema: Schema)
extends DataWrapper with Logging {
val executor = new JdbcExecutor(dataSource)
def loadMetas(loadTableExtra: Boolean, loadSequence: Boolean): Unit = {
var conn: Connection = null
try {
conn = dataSource.getConnection
val loader = new MetadataLoader(conn.getMetaData, engine)
loader.loadTables(schema, loadTableExtra)
if (loadSequence) loader.loadSequences(schema)
} finally {
IOs.close(conn)
}
}
override def has(table: Table): Boolean = {
schema.getTable(table.name.value).isDefined
}
override def drop(table: Table): Boolean = {
try {
schema.getTable(table.name.value) foreach { t =>
schema.tables.remove(t.name)
executor.update(engine.dropTable(t.qualifiedName))
}
true
} catch {
case e: Exception =>
logger.error(s"Drop table ${table.name} failed", e)
false
}
}
override def create(table: Table): Boolean = {
if (schema.getTable(table.name.value).isEmpty) {
try {
executor.update(engine.createTable(table))
} catch {
case e: Exception =>
logger.error(s"Cannot create table ${table.name}", e)
return false
}
}
true
}
def drop(sequence: Sequence): Boolean = {
val exists = schema.sequences.contains(sequence)
if (exists) {
schema.sequences.remove(sequence)
try {
val dropSql = engine.dropSequence(sequence)
if (null != dropSql) executor.update(dropSql)
} catch {
case e: Exception =>
logger.error(s"Drop sequence ${sequence.name} failed", e)
return false
}
}
true
}
def create(sequence: Sequence): Boolean = {
try {
val createSql = engine.createSequence(sequence)
if (null != createSql) executor.update(createSql)
true
} catch {
case e: Exception =>
logger.error(s"cannot create sequence ${sequence.name}", e)
false
}
}
def count(table: Table): Int = {
executor.queryForInt("select count(*) from " + table.qualifiedName + " tb").get
}
def get(table: Table): ResultSetIterator = {
executor.iterate(engine.query(table))
}
def save(table: Table, datas: collection.Seq[Array[_]]): Int = {
val types = for (column <- table.columns) yield column.sqlType.code
val insertSql = engine.insert(table)
executor.batch(insertSql, datas, types.toSeq).length
}
def close(): Unit = {}
}
| beangle/db | transport/src/main/scala/org/beangle/db/transport/schema/SchemaWrapper.scala | Scala | gpl-3.0 | 3,680 |
/*
* 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.plan.nodes.dataset
import org.apache.calcite.plan.{RelOptCluster, RelOptCost, RelOptPlanner, RelTraitSet}
import org.apache.calcite.rel.`type`.RelDataType
import org.apache.calcite.rel.core.AggregateCall
import org.apache.calcite.rel.metadata.RelMetadataQuery
import org.apache.calcite.rel.{RelNode, RelWriter, SingleRel}
import org.apache.flink.api.common.operators.Order
import org.apache.flink.api.java.DataSet
import org.apache.flink.api.java.typeutils.{ResultTypeQueryable, RowTypeInfo}
import org.apache.flink.table.api.BatchTableEnvironment
import org.apache.flink.table.calcite.FlinkRelBuilder.NamedWindowProperty
import org.apache.flink.table.calcite.FlinkTypeFactory
import org.apache.flink.table.codegen.AggregationCodeGenerator
import org.apache.flink.table.expressions.ExpressionUtils._
import org.apache.flink.table.plan.logical._
import org.apache.flink.table.plan.nodes.CommonAggregate
import org.apache.flink.table.runtime.aggregate.AggregateUtil.{CalcitePair, _}
import org.apache.flink.table.typeutils.TypeCheckUtils.{isLong, isTimePoint}
import org.apache.flink.types.Row
/**
* Flink RelNode which matches along with a LogicalWindowAggregate.
*/
class DataSetWindowAggregate(
window: LogicalWindow,
namedProperties: Seq[NamedWindowProperty],
cluster: RelOptCluster,
traitSet: RelTraitSet,
inputNode: RelNode,
namedAggregates: Seq[CalcitePair[AggregateCall, String]],
rowRelDataType: RelDataType,
inputType: RelDataType,
grouping: Array[Int])
extends SingleRel(cluster, traitSet, inputNode) with CommonAggregate with DataSetRel {
override def deriveRowType() = rowRelDataType
override def copy(traitSet: RelTraitSet, inputs: java.util.List[RelNode]): RelNode = {
new DataSetWindowAggregate(
window,
namedProperties,
cluster,
traitSet,
inputs.get(0),
namedAggregates,
getRowType,
inputType,
grouping)
}
override def toString: String = {
s"Aggregate(${
if (!grouping.isEmpty) {
s"groupBy: (${groupingToString(inputType, grouping)}), "
} else {
""
}
}window: ($window), " +
s"select: (${
aggregationToString(
inputType,
grouping,
getRowType,
namedAggregates,
namedProperties)
}))"
}
override def explainTerms(pw: RelWriter): RelWriter = {
super.explainTerms(pw)
.itemIf("groupBy", groupingToString(inputType, grouping), !grouping.isEmpty)
.item("window", window)
.item(
"select", aggregationToString(
inputType,
grouping,
getRowType,
namedAggregates,
namedProperties))
}
override def computeSelfCost(planner: RelOptPlanner, metadata: RelMetadataQuery): RelOptCost = {
val child = this.getInput
val rowCnt = metadata.getRowCount(child)
val rowSize = this.estimateRowSize(child.getRowType)
val aggCnt = this.namedAggregates.size
planner.getCostFactory.makeCost(rowCnt, rowCnt * aggCnt, rowCnt * rowSize)
}
override def translateToPlan(tableEnv: BatchTableEnvironment): DataSet[Row] = {
val inputDS = getInput.asInstanceOf[DataSetRel].translateToPlan(tableEnv)
val generator = new AggregationCodeGenerator(
tableEnv.getConfig,
false,
inputDS.getType)
// whether identifiers are matched case-sensitively
val caseSensitive = tableEnv.getFrameworkConfig.getParserConfig.caseSensitive()
window match {
case TumblingGroupWindow(_, timeField, size)
if isTimePoint(timeField.resultType) || isLong(timeField.resultType) =>
createEventTimeTumblingWindowDataSet(
generator,
inputDS,
isTimeIntervalLiteral(size),
caseSensitive)
case SessionGroupWindow(_, timeField, gap)
if isTimePoint(timeField.resultType) || isLong(timeField.resultType) =>
createEventTimeSessionWindowDataSet(generator, inputDS, caseSensitive)
case SlidingGroupWindow(_, timeField, size, slide)
if isTimePoint(timeField.resultType) || isLong(timeField.resultType) =>
createEventTimeSlidingWindowDataSet(
generator,
inputDS,
isTimeIntervalLiteral(size),
asLong(size),
asLong(slide),
caseSensitive)
case _ =>
throw new UnsupportedOperationException(
s"Window $window is not supported in a batch environment.")
}
}
private def createEventTimeTumblingWindowDataSet(
generator: AggregationCodeGenerator,
inputDS: DataSet[Row],
isTimeWindow: Boolean,
isParserCaseSensitive: Boolean): DataSet[Row] = {
val input = inputNode.asInstanceOf[DataSetRel]
val mapFunction = createDataSetWindowPrepareMapFunction(
generator,
window,
namedAggregates,
grouping,
input.getRowType,
inputDS.getType.asInstanceOf[RowTypeInfo].getFieldTypes,
isParserCaseSensitive)
val groupReduceFunction = createDataSetWindowAggregationGroupReduceFunction(
generator,
window,
namedAggregates,
input.getRowType,
inputDS.getType.asInstanceOf[RowTypeInfo].getFieldTypes,
getRowType,
grouping,
namedProperties)
val mappedInput = inputDS
.map(mapFunction)
.name(prepareOperatorName)
val rowTypeInfo = FlinkTypeFactory.toInternalRowTypeInfo(getRowType)
val mapReturnType = mapFunction.asInstanceOf[ResultTypeQueryable[Row]].getProducedType
if (isTimeWindow) {
// grouped time window aggregation
// group by grouping keys and rowtime field (the last field in the row)
val groupingKeys = grouping.indices ++ Seq(mapReturnType.getArity - 1)
mappedInput.asInstanceOf[DataSet[Row]]
.groupBy(groupingKeys: _*)
.reduceGroup(groupReduceFunction)
.returns(rowTypeInfo)
.name(aggregateOperatorName)
} else {
// count window
val groupingKeys = grouping.indices.toArray
if (groupingKeys.length > 0) {
// grouped aggregation
mappedInput.asInstanceOf[DataSet[Row]]
.groupBy(groupingKeys: _*)
// sort on time field, it's the last element in the row
.sortGroup(mapReturnType.getArity - 1, Order.ASCENDING)
.reduceGroup(groupReduceFunction)
.returns(rowTypeInfo)
.name(aggregateOperatorName)
} else {
// TODO: count tumbling all window on event-time should sort all the data set
// on event time before applying the windowing logic.
throw new UnsupportedOperationException(
"Count tumbling non-grouping windows on event-time are currently not supported.")
}
}
}
private[this] def createEventTimeSessionWindowDataSet(
generator: AggregationCodeGenerator,
inputDS: DataSet[Row],
isParserCaseSensitive: Boolean): DataSet[Row] = {
val input = inputNode.asInstanceOf[DataSetRel]
val groupingKeys = grouping.indices.toArray
val rowTypeInfo = FlinkTypeFactory.toInternalRowTypeInfo(getRowType)
// create mapFunction for initializing the aggregations
val mapFunction = createDataSetWindowPrepareMapFunction(
generator,
window,
namedAggregates,
grouping,
input.getRowType,
inputDS.getType.asInstanceOf[RowTypeInfo].getFieldTypes,
isParserCaseSensitive)
val mappedInput = inputDS.map(mapFunction).name(prepareOperatorName)
val mapReturnType = mapFunction.asInstanceOf[ResultTypeQueryable[Row]].getProducedType
// the position of the rowtime field in the intermediate result for map output
val rowTimeFieldPos = mapReturnType.getArity - 1
// do incremental aggregation
if (doAllSupportPartialMerge(
namedAggregates.map(_.getKey),
inputType,
grouping.length)) {
// gets the window-start and window-end position in the intermediate result.
val windowStartPos = rowTimeFieldPos
val windowEndPos = windowStartPos + 1
// grouping window
if (groupingKeys.length > 0) {
// create groupCombineFunction for combine the aggregations
val combineGroupFunction = createDataSetWindowAggregationCombineFunction(
generator,
window,
namedAggregates,
input.getRowType,
inputDS.getType.asInstanceOf[RowTypeInfo].getFieldTypes,
grouping)
// create groupReduceFunction for calculating the aggregations
val groupReduceFunction = createDataSetWindowAggregationGroupReduceFunction(
generator,
window,
namedAggregates,
input.getRowType,
inputDS.getType.asInstanceOf[RowTypeInfo].getFieldTypes,
rowRelDataType,
grouping,
namedProperties,
isInputCombined = true)
mappedInput
.groupBy(groupingKeys: _*)
.sortGroup(rowTimeFieldPos, Order.ASCENDING)
.combineGroup(combineGroupFunction)
.groupBy(groupingKeys: _*)
.sortGroup(windowStartPos, Order.ASCENDING)
.sortGroup(windowEndPos, Order.ASCENDING)
.reduceGroup(groupReduceFunction)
.returns(rowTypeInfo)
.name(aggregateOperatorName)
} else {
// non-grouping window
val mapPartitionFunction = createDataSetWindowAggregationMapPartitionFunction(
generator,
window,
namedAggregates,
input.getRowType,
inputDS.getType.asInstanceOf[RowTypeInfo].getFieldTypes,
grouping)
// create groupReduceFunction for calculating the aggregations
val groupReduceFunction = createDataSetWindowAggregationGroupReduceFunction(
generator,
window,
namedAggregates,
input.getRowType,
inputDS.getType.asInstanceOf[RowTypeInfo].getFieldTypes,
rowRelDataType,
grouping,
namedProperties,
isInputCombined = true)
mappedInput.sortPartition(rowTimeFieldPos, Order.ASCENDING)
.mapPartition(mapPartitionFunction)
.sortPartition(windowStartPos, Order.ASCENDING).setParallelism(1)
.sortPartition(windowEndPos, Order.ASCENDING).setParallelism(1)
.reduceGroup(groupReduceFunction)
.returns(rowTypeInfo)
.name(aggregateOperatorName)
.asInstanceOf[DataSet[Row]]
}
// do non-incremental aggregation
} else {
// grouping window
if (groupingKeys.length > 0) {
// create groupReduceFunction for calculating the aggregations
val groupReduceFunction = createDataSetWindowAggregationGroupReduceFunction(
generator,
window,
namedAggregates,
input.getRowType,
inputDS.getType.asInstanceOf[RowTypeInfo].getFieldTypes,
rowRelDataType,
grouping,
namedProperties)
mappedInput.groupBy(groupingKeys: _*)
.sortGroup(rowTimeFieldPos, Order.ASCENDING)
.reduceGroup(groupReduceFunction)
.returns(rowTypeInfo)
.name(aggregateOperatorName)
} else {
// non-grouping window
val groupReduceFunction = createDataSetWindowAggregationGroupReduceFunction(
generator,
window,
namedAggregates,
input.getRowType,
inputDS.getType.asInstanceOf[RowTypeInfo].getFieldTypes,
rowRelDataType,
grouping,
namedProperties)
mappedInput.sortPartition(rowTimeFieldPos, Order.ASCENDING).setParallelism(1)
.reduceGroup(groupReduceFunction)
.returns(rowTypeInfo)
.name(aggregateOperatorName)
.asInstanceOf[DataSet[Row]]
}
}
}
private def createEventTimeSlidingWindowDataSet(
generator: AggregationCodeGenerator,
inputDS: DataSet[Row],
isTimeWindow: Boolean,
size: Long,
slide: Long,
isParserCaseSensitive: Boolean)
: DataSet[Row] = {
val input = inputNode.asInstanceOf[DataSetRel]
// create MapFunction for initializing the aggregations
// it aligns the rowtime for pre-tumbling in case of a time-window for partial aggregates
val mapFunction = createDataSetWindowPrepareMapFunction(
generator,
window,
namedAggregates,
grouping,
input.getRowType,
inputDS.getType.asInstanceOf[RowTypeInfo].getFieldTypes,
isParserCaseSensitive)
val mappedDataSet = inputDS
.map(mapFunction)
.name(prepareOperatorName)
val mapReturnType = mappedDataSet.getType
val rowTypeInfo = FlinkTypeFactory.toInternalRowTypeInfo(getRowType)
val groupingKeys = grouping.indices.toArray
// do partial aggregation if possible
val isPartial = doAllSupportPartialMerge(
namedAggregates.map(_.getKey),
inputType,
grouping.length)
// only pre-tumble if it is worth it
val isLittleTumblingSize = determineLargestTumblingSize(size, slide) <= 1
val preparedDataSet = if (isTimeWindow) {
// time window
if (isPartial && !isLittleTumblingSize) {
// partial aggregates
val groupingKeysAndAlignedRowtime = groupingKeys :+ mapReturnType.getArity - 1
// create GroupReduceFunction
// for pre-tumbling and replicating/omitting the content for each pane
val prepareReduceFunction = createDataSetSlideWindowPrepareGroupReduceFunction(
generator,
window,
namedAggregates,
grouping,
input.getRowType,
inputDS.getType.asInstanceOf[RowTypeInfo].getFieldTypes,
isParserCaseSensitive)
mappedDataSet.asInstanceOf[DataSet[Row]]
.groupBy(groupingKeysAndAlignedRowtime: _*)
.reduceGroup(prepareReduceFunction) // pre-tumbles and replicates/omits
.name(prepareOperatorName)
} else {
// non-partial aggregates
// create FlatMapFunction
// for replicating/omitting the content for each pane
val prepareFlatMapFunction = createDataSetSlideWindowPrepareFlatMapFunction(
window,
namedAggregates,
grouping,
mapReturnType,
isParserCaseSensitive)
mappedDataSet
.flatMap(prepareFlatMapFunction) // replicates/omits
}
} else {
// count window
throw new UnsupportedOperationException(
"Count sliding group windows on event-time are currently not supported.")
}
val prepareReduceReturnType = preparedDataSet.getType
// create GroupReduceFunction for final aggregation and conversion to output row
val aggregateReduceFunction = createDataSetWindowAggregationGroupReduceFunction(
generator,
window,
namedAggregates,
input.getRowType,
inputDS.getType.asInstanceOf[RowTypeInfo].getFieldTypes,
rowRelDataType,
grouping,
namedProperties,
isInputCombined = false)
// gets the window-start position in the intermediate result.
val windowStartPos = prepareReduceReturnType.getArity - 1
val groupingKeysAndWindowStart = groupingKeys :+ windowStartPos
preparedDataSet
.groupBy(groupingKeysAndWindowStart: _*)
.reduceGroup(aggregateReduceFunction)
.returns(rowTypeInfo)
.name(aggregateOperatorName)
}
private def prepareOperatorName: String = {
val aggString = aggregationToString(
inputType,
grouping,
getRowType,
namedAggregates,
namedProperties)
s"prepare select: ($aggString)"
}
private def aggregateOperatorName: String = {
val aggString = aggregationToString(
inputType,
grouping,
getRowType,
namedAggregates,
namedProperties)
if (grouping.length > 0) {
s"groupBy: (${groupingToString(inputType, grouping)}), " +
s"window: ($window), select: ($aggString)"
} else {
s"window: ($window), select: ($aggString)"
}
}
}
| zohar-mizrahi/flink | flink-libraries/flink-table/src/main/scala/org/apache/flink/table/plan/nodes/dataset/DataSetWindowAggregate.scala | Scala | apache-2.0 | 16,824 |
package turkey.tasks
import upickle.default._
trait Service[Request <: { type Response }] {
def processRequest(request: Request): request.Response
}
object Service {
case class UnitRequest() { final type Response = Unit }
case object UnitRequest {
implicit val responseRW = new ResponseRW[UnitRequest] {
override def getReader(request: UnitRequest) = implicitly[Reader[Unit]]
override def getWriter(request: UnitRequest) = implicitly[Writer[Unit]]
}
}
val unitServer = new Service[UnitRequest] {
override def processRequest(request: UnitRequest) = ()
}
}
| julianmichael/turkey | turkey/shared/src/main/scala/turkey/tasks/Service.scala | Scala | mit | 594 |
/*
* 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.execution
import scala.language.implicitConversions
import scala.util.control.NonFatal
import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.{DataFrame, Row, SparkSession, SQLContext}
import org.apache.spark.sql.catalyst.analysis.UnresolvedAttribute
import org.apache.spark.sql.catalyst.plans.logical.LocalRelation
import org.apache.spark.sql.test.SQLTestUtils
/**
* Base class for writing tests for individual physical operators. For an example of how this
* class's test helper methods can be used, see [[SortSuite]].
*/
private[sql] abstract class SparkPlanTest extends SparkFunSuite {
protected def spark: SparkSession
/**
* Runs the plan and makes sure the answer matches the expected result.
* @param input the input data to be used.
* @param planFunction a function which accepts the input SparkPlan and uses it to instantiate
* the physical operator that's being tested.
* @param expectedAnswer the expected result in a [[Seq]] of [[Row]]s.
* @param sortAnswers if true, the answers will be sorted by their toString representations prior
* to being compared.
*/
protected def checkAnswer(
input: DataFrame,
planFunction: SparkPlan => SparkPlan,
expectedAnswer: Seq[Row],
sortAnswers: Boolean = true): Unit = {
doCheckAnswer(
input :: Nil,
(plans: Seq[SparkPlan]) => planFunction(plans.head),
expectedAnswer,
sortAnswers)
}
/**
* Runs the plan and makes sure the answer matches the expected result.
* @param left the left input data to be used.
* @param right the right input data to be used.
* @param planFunction a function which accepts the input SparkPlan and uses it to instantiate
* the physical operator that's being tested.
* @param expectedAnswer the expected result in a [[Seq]] of [[Row]]s.
* @param sortAnswers if true, the answers will be sorted by their toString representations prior
* to being compared.
*/
protected def checkAnswer2(
left: DataFrame,
right: DataFrame,
planFunction: (SparkPlan, SparkPlan) => SparkPlan,
expectedAnswer: Seq[Row],
sortAnswers: Boolean = true): Unit = {
doCheckAnswer(
left :: right :: Nil,
(plans: Seq[SparkPlan]) => planFunction(plans(0), plans(1)),
expectedAnswer,
sortAnswers)
}
/**
* Runs the plan and makes sure the answer matches the expected result.
* @param input the input data to be used.
* @param planFunction a function which accepts a sequence of input SparkPlans and uses them to
* instantiate the physical operator that's being tested.
* @param expectedAnswer the expected result in a [[Seq]] of [[Row]]s.
* @param sortAnswers if true, the answers will be sorted by their toString representations prior
* to being compared.
*/
protected def doCheckAnswer(
input: Seq[DataFrame],
planFunction: Seq[SparkPlan] => SparkPlan,
expectedAnswer: Seq[Row],
sortAnswers: Boolean = true): Unit = {
SparkPlanTest
.checkAnswer(input, planFunction, expectedAnswer, sortAnswers, spark.sqlContext) match {
case Some(errorMessage) => fail(errorMessage)
case None =>
}
}
/**
* Runs the plan and makes sure the answer matches the result produced by a reference plan.
* @param input the input data to be used.
* @param planFunction a function which accepts the input SparkPlan and uses it to instantiate
* the physical operator that's being tested.
* @param expectedPlanFunction a function which accepts the input SparkPlan and uses it to
* instantiate a reference implementation of the physical operator
* that's being tested. The result of executing this plan will be
* treated as the source-of-truth for the test.
* @param sortAnswers if true, the answers will be sorted by their toString representations prior
* to being compared.
*/
protected def checkThatPlansAgree(
input: DataFrame,
planFunction: SparkPlan => SparkPlan,
expectedPlanFunction: SparkPlan => SparkPlan,
sortAnswers: Boolean = true): Unit = {
SparkPlanTest.checkAnswer(
input, planFunction, expectedPlanFunction, sortAnswers, spark.sqlContext) match {
case Some(errorMessage) => fail(errorMessage)
case None =>
}
}
}
/**
* Helper methods for writing tests of individual physical operators.
*/
object SparkPlanTest {
/**
* Runs the plan and makes sure the answer matches the result produced by a reference plan.
* @param input the input data to be used.
* @param planFunction a function which accepts the input SparkPlan and uses it to instantiate
* the physical operator that's being tested.
* @param expectedPlanFunction a function which accepts the input SparkPlan and uses it to
* instantiate a reference implementation of the physical operator
* that's being tested. The result of executing this plan will be
* treated as the source-of-truth for the test.
*/
def checkAnswer(
input: DataFrame,
planFunction: SparkPlan => SparkPlan,
expectedPlanFunction: SparkPlan => SparkPlan,
sortAnswers: Boolean,
spark: SQLContext): Option[String] = {
val outputPlan = planFunction(input.queryExecution.sparkPlan)
val expectedOutputPlan = expectedPlanFunction(input.queryExecution.sparkPlan)
val expectedAnswer: Seq[Row] = try {
executePlan(expectedOutputPlan, spark)
} catch {
case NonFatal(e) =>
val errorMessage =
s"""
| Exception thrown while executing Spark plan to calculate expected answer:
| $expectedOutputPlan
| == Exception ==
| $e
| ${org.apache.spark.sql.catalyst.util.stackTraceToString(e)}
""".stripMargin
return Some(errorMessage)
}
val actualAnswer: Seq[Row] = try {
executePlan(outputPlan, spark)
} catch {
case NonFatal(e) =>
val errorMessage =
s"""
| Exception thrown while executing Spark plan:
| $outputPlan
| == Exception ==
| $e
| ${org.apache.spark.sql.catalyst.util.stackTraceToString(e)}
""".stripMargin
return Some(errorMessage)
}
SQLTestUtils.compareAnswers(actualAnswer, expectedAnswer, sortAnswers).map { errorMessage =>
s"""
| Results do not match.
| Actual result Spark plan:
| $outputPlan
| Expected result Spark plan:
| $expectedOutputPlan
| $errorMessage
""".stripMargin
}
}
/**
* Runs the plan and makes sure the answer matches the expected result.
* @param input the input data to be used.
* @param planFunction a function which accepts the input SparkPlan and uses it to instantiate
* the physical operator that's being tested.
* @param expectedAnswer the expected result in a [[Seq]] of [[Row]]s.
* @param sortAnswers if true, the answers will be sorted by their toString representations prior
* to being compared.
*/
def checkAnswer(
input: Seq[DataFrame],
planFunction: Seq[SparkPlan] => SparkPlan,
expectedAnswer: Seq[Row],
sortAnswers: Boolean,
spark: SQLContext): Option[String] = {
val outputPlan = planFunction(input.map(_.queryExecution.sparkPlan))
val sparkAnswer: Seq[Row] = try {
executePlan(outputPlan, spark)
} catch {
case NonFatal(e) =>
val errorMessage =
s"""
| Exception thrown while executing Spark plan:
| $outputPlan
| == Exception ==
| $e
| ${org.apache.spark.sql.catalyst.util.stackTraceToString(e)}
""".stripMargin
return Some(errorMessage)
}
SQLTestUtils.compareAnswers(sparkAnswer, expectedAnswer, sortAnswers).map { errorMessage =>
s"""
| Results do not match for Spark plan:
| $outputPlan
| $errorMessage
""".stripMargin
}
}
/**
* Runs the plan
* @param outputPlan SparkPlan to be executed
* @param spark SqlContext used for execution of the plan
*/
def executePlan(outputPlan: SparkPlan, spark: SQLContext): Seq[Row] = {
val execution = new QueryExecution(spark.sparkSession, LocalRelation(Nil)) {
override lazy val sparkPlan: SparkPlan = outputPlan transform {
case plan: SparkPlan =>
val inputMap = plan.children.flatMap(_.output).map(a => (a.name, a)).toMap
plan transformExpressions {
case UnresolvedAttribute(Seq(u)) =>
inputMap.getOrElse(u,
sys.error(s"Invalid Test: Cannot resolve $u given input $inputMap"))
}
}
}
execution.executedPlan.executeCollectPublic().toSeq
}
}
| dbtsai/spark | sql/core/src/test/scala/org/apache/spark/sql/execution/SparkPlanTest.scala | Scala | apache-2.0 | 10,014 |
/*
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
package org.apache.spark.api.csharp
import org.apache.spark.util.Utils
import java.io.{DataOutputStream, ByteArrayOutputStream, DataInputStream, ByteArrayInputStream}
import java.net.Socket
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.{ChannelHandlerContext, SimpleChannelInboundHandler}
// TODO - work with SparkR devs to make this configurable and reuse RBackendHandler
import org.apache.spark.api.csharp.SerDe._
import scala.collection.mutable.HashMap
/**
* Handler for CSharpBackend.
* This implementation is identical to RBackendHandler and that can be reused
* in SparkCLR if SerDe is made pluggable
*/
// Since SparkCLR is a package to Spark and not a part of spark-core, it mirrors the implementation
// of selected parts from RBackend with SparkCLR customizations
class CSharpBackendHandler(server: CSharpBackend) extends SimpleChannelInboundHandler[Array[Byte]] {
override def channelRead0(ctx: ChannelHandlerContext, msg: Array[Byte]): Unit = {
val bis = new ByteArrayInputStream(msg)
val dis = new DataInputStream(bis)
val bos = new ByteArrayOutputStream()
val dos = new DataOutputStream(bos)
// First bit is isStatic
val isStatic = readBoolean(dis)
val objId = readString(dis)
val methodName = readString(dis)
val numArgs = readInt(dis)
if (objId == "SparkCLRHandler") {
methodName match {
case "stopBackend" =>
writeInt(dos, 0)
writeType(dos, "void")
server.close()
case "rm" =>
try {
val t = readObjectType(dis)
assert(t == 'c')
val objToRemove = readString(dis)
JVMObjectTracker.remove(objToRemove)
writeInt(dos, 0)
writeObject(dos, null)
} catch {
case e: Exception =>
logError(s"Removing $objId failed", e)
writeInt(dos, -1)
}
case "connectCallback" =>
val t = readObjectType(dis)
assert(t == 'i')
val port = readInt(dis)
// scalastyle:off println
println("[CSharpBackendHandler] Connecting to a callback server at port " + port)
CSharpBackend.callbackPort = port
writeInt(dos, 0)
writeType(dos, "void")
case "closeCallback" =>
// Send close to CSharp callback server.
println("[CSharpBackendHandler] Requesting to close all call back sockets.")
// scalastyle:on
var socket: Socket = null
do {
socket = CSharpBackend.callbackSockets.poll()
if (socket != null) {
val dataOutputStream = new DataOutputStream(socket.getOutputStream)
SerDe.writeString(dataOutputStream, "close")
try {
socket.close()
socket = null
}
}
} while (socket != null)
CSharpBackend.callbackSocketShutdown = true
writeInt(dos, 0)
writeType(dos, "void")
case _ => dos.writeInt(-1)
}
} else {
handleMethodCall(isStatic, objId, methodName, numArgs, dis, dos)
}
val reply = bos.toByteArray
ctx.write(reply)
}
override def channelReadComplete(ctx: ChannelHandlerContext): Unit = {
ctx.flush()
}
override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable): Unit = {
// Close the connection when an exception is raised.
// scalastyle:off println
println("Exception caught: " + cause.getMessage)
// scalastyle:on
cause.printStackTrace()
ctx.close()
}
def handleMethodCall(
isStatic: Boolean,
objId: String,
methodName: String,
numArgs: Int,
dis: DataInputStream,
dos: DataOutputStream): Unit = {
var obj: Object = null
var args: Array[java.lang.Object] = null
var methods: Array[java.lang.reflect.Method] = null
try {
val cls = if (isStatic) {
Utils.classForName(objId)
} else {
JVMObjectTracker.get(objId) match {
case None => throw new IllegalArgumentException("Object not found " + objId)
case Some(o) =>
obj = o
o.getClass
}
}
args = readArgs(numArgs, dis)
methods = cls.getMethods
val selectedMethods = methods.filter(m => m.getName == methodName)
if (selectedMethods.length > 0) {
methods = selectedMethods.filter { x =>
matchMethod(numArgs, args, x.getParameterTypes)
}
if (methods.isEmpty) {
logWarning(s"cannot find matching method ${cls}.$methodName. "
+ s"Candidates are:")
selectedMethods.foreach { method =>
logWarning(s"$methodName(${method.getParameterTypes.mkString(",")})")
}
throw new Exception(s"No matched method found for $cls.$methodName")
}
val ret = methods.head.invoke(obj, args : _*)
// Write status bit
writeInt(dos, 0)
writeObject(dos, ret.asInstanceOf[AnyRef])
} else if (methodName == "<init>") {
// methodName should be "<init>" for constructor
val ctor = cls.getConstructors.filter { x =>
matchMethod(numArgs, args, x.getParameterTypes)
}.head
val obj = ctor.newInstance(args : _*)
writeInt(dos, 0)
writeObject(dos, obj.asInstanceOf[AnyRef])
} else {
throw new IllegalArgumentException("invalid method " + methodName + " for object " + objId)
}
} catch {
case e: Exception =>
// TODO - logError does not work now..fix //logError(s"$methodName on $objId failed", e)
val jvmObj = JVMObjectTracker.get(objId)
val jvmObjName = jvmObj match
{
case Some(jObj) => jObj.getClass.getName
case None => "NullObject"
}
// scalastyle:off println
println(s"[CSharpBackendHandler] $methodName on object of type $jvmObjName failed")
println(e.getMessage)
println(e.printStackTrace())
if (methods != null) {
println("methods:")
methods.foreach(println(_))
}
if (args != null) {
println("args:")
args.foreach(arg => {
if (arg != null) {
println("argType: " + arg.getClass.getCanonicalName + ", argValue: " + arg)
} else {
println("arg: NULL")
}
})
}
// scalastyle:on println
writeInt(dos, -1)
writeString(dos, Utils.exceptionString(e.getCause))
}
}
// Read a number of arguments from the data input stream
def readArgs(numArgs: Int, dis: DataInputStream): Array[java.lang.Object] = {
(0 until numArgs).map { arg =>
readObject(dis)
}.toArray
}
// Checks if the arguments passed in args matches the parameter types.
// NOTE: Currently we do exact match. We may add type conversions later.
def matchMethod(
numArgs: Int,
args: Array[java.lang.Object],
parameterTypes: Array[Class[_]]): Boolean = {
if (parameterTypes.length != numArgs) {
return false
}
for (i <- 0 to numArgs - 1) {
val parameterType = parameterTypes(i)
var parameterWrapperType = parameterType
// Convert native parameters to Object types as args is Array[Object] here
if (parameterType.isPrimitive) {
parameterWrapperType = parameterType match {
case java.lang.Integer.TYPE => classOf[java.lang.Integer]
case java.lang.Long.TYPE => classOf[java.lang.Long]
case java.lang.Double.TYPE => classOf[java.lang.Double]
case java.lang.Boolean.TYPE => classOf[java.lang.Boolean]
case _ => parameterType
}
}
if (!parameterWrapperType.isInstance(args(i))) {
// non primitive types
if (!parameterType.isPrimitive && args(i) != null) {
return false
}
// primitive types
if (parameterType.isPrimitive && !parameterWrapperType.isInstance(args(i))) {
return false
}
}
}
true
}
// scalastyle:off println
def logError(id: String) {
println(id)
}
def logWarning(id: String) {
println(id)
}
// scalastyle:on println
def logError(id: String, e: Exception): Unit = {
}
}
/**
* Tracks JVM objects returned to C# which is useful for invoking calls from C# to JVM objects
*/
private object JVMObjectTracker {
// Muliple threads may access objMap and increase objCounter. Because get method return Option,
// it is convenient to use a Scala map instead of java.util.concurrent.ConcurrentHashMap.
private[this] val objMap = new HashMap[String, Object]
private[this] var objCounter: Int = 1
def getObject(id: String): Object = {
synchronized {
objMap(id)
}
}
def get(id: String): Option[Object] = {
synchronized {
objMap.get(id)
}
}
def put(obj: Object): String = {
synchronized {
val objId = objCounter.toString
objCounter = objCounter + 1
objMap.put(objId, obj)
objId
}
}
def remove(id: String): Option[Object] = {
synchronized {
objMap.remove(id)
}
}
}
| cyruszhang/SparkCLR | scala/src/main/org/apache/spark/api/csharp/CSharpBackendHandler.scala | Scala | mit | 9,534 |
/*
* 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.internal.{GaussianNoise => BigDLGaussianNoise}
import com.intel.analytics.bigdl.dllib.tensor.TensorNumericMath.TensorNumeric
import com.intel.analytics.bigdl.dllib.utils.Shape
import com.intel.analytics.bigdl.dllib.keras.Net
import scala.reflect.ClassTag
/**
* Apply additive zero-centered Gaussian noise.
* This is useful to mitigate overfitting (you could see it as a form of random data augmentation).
* Gaussian Noise is a natural choice as corruption process for real valued inputs.
* As it is a regularization layer, it is only active at training time.
*
* When you use this layer as the first layer of a model, you need to provide the argument
* inputShape (a Single Shape, does not include the batch dimension).
*
* @param sigma Double, standard deviation of the noise distribution.
* @param inputShape A Single Shape, does not include the batch dimension.
* @tparam T Numeric type of parameter(e.g. weight, bias). Only support float/double now.
*/
class GaussianNoise[T: ClassTag](
override val sigma: Double,
override val inputShape: Shape = null)(implicit ev: TensorNumeric[T])
extends BigDLGaussianNoise[T](
sigma, inputShape) with Net {
}
object GaussianNoise {
def apply[@specialized(Float, Double) T: ClassTag](
sigma: Double,
inputShape: Shape = null)(implicit ev: TensorNumeric[T]): GaussianNoise[T] = {
new GaussianNoise[T](sigma, inputShape)
}
}
| intel-analytics/BigDL | scala/dllib/src/main/scala/com/intel/analytics/bigdl/dllib/keras/layers/GaussianNoise.scala | Scala | apache-2.0 | 2,109 |
package com.bobwilsonsgarage.frontend.rest.routes
import akka.cluster.sharding.ClusterSharding
import akka.pattern.ask
import akka.util.Timeout
import com.bobwilsonsgarage.frontend.resources.BobWilsonsGarageServiceRestProtocol
import com.bobwilsonsgarage.frontend.rest.{HostAndPath, RestApiServiceActor}
import com.bobwilsonsgarage.frontend.server.ServerFrontendProtocol.{DependentServices, RequestDependentServices}
import com.bobwilsonsgarage.frontend.util.{UrlEstablisher, UuidUtil}
import common.protocol.BobWilsonsGarageProtocol.{BobWilsonsGarageServiceRequest, BobWilsonsGarageServiceResult, GetBobWilsonsGarageServiceResult}
import common.protocol.FulfillmentProcessProtocol.InitiateFulfillmentProcess
import common.protocol.ShardingProtocol.EntryEnvelope
import common.shardingfunctions.FulfillmentProcessShardingFunctions
import common.util.Logging
import spray.http.HttpHeaders.RawHeader
import spray.http.StatusCodes
import spray.routing.{HttpService, RequestContext}
import scala.concurrent.duration._
import scala.util.{Failure, Success}
/**
* BobWilsonsGarage Order rest routes.
*
* @author dbolene
*/
trait OrdersRoutes extends HttpService with Logging {
this: RestApiServiceActor =>
def hostAndPath(req: RequestContext): String = {
HostAndPath.hostAndPath(req)
}
val fulfillmentProcessRegion = ClusterSharding(context.system).startProxy(
typeName = "FulfillmentProcess",
role = None,
extractEntityId = FulfillmentProcessShardingFunctions.idExtractor,
extractShardId = FulfillmentProcessShardingFunctions.shardResolver)
import com.bobwilsonsgarage.frontend.resources.BobWilsonsGarageServiceRestProtocol._
import context.dispatcher
import spray.httpx.SprayJsonSupport._
implicit val timeout = Timeout(130 seconds)
lazy val ordersRoute = {
post {
entity(as[BobWilsonsGarageServiceRequestPost]) {
bobWilsonsGarageServicePostRequest => {
ctx =>
(dependenciesResolver ? RequestDependentServices).mapTo[DependentServices] onComplete {
case Failure(e) =>
ctx.complete(e)
case Success(dependentServicesResponse) =>
val fulfillmentProcessId = UuidUtil.generateNewUuid()
fulfillmentProcessRegion ! EntryEnvelope(fulfillmentProcessId, InitiateFulfillmentProcess(
id = fulfillmentProcessId,
request = BobWilsonsGarageServiceRequest(car = bobWilsonsGarageServicePostRequest.car),
carRepairServiceEndpoint = dependentServicesResponse.carRepairServiceEndpoint,
detailingServiceEndpoint = dependentServicesResponse.detailingServiceEndpoint
))
val fulfillmentProcessUrl = UrlEstablisher.orderUrl(fulfillmentProcessId, hostAndPath(ctx))
info(s"returned fulfillmentProcessUrl: $fulfillmentProcessUrl")
ctx.complete(StatusCodes.Accepted, RawHeader("Location", fulfillmentProcessUrl) :: Nil, "")
}
}
}
}
}
lazy val ordersIdRoute = {
orderId: String =>
get {
ctx =>
(fulfillmentProcessRegion ? EntryEnvelope(orderId, GetBobWilsonsGarageServiceResult)).mapTo[BobWilsonsGarageServiceResult] onComplete {
case Failure(e) =>
ctx.complete(e)
case Success(bobWilsonsGarageServiceResult) =>
val result = BobWilsonsGarageServiceRestProtocol.mapFromBobWilsonsGarageServiceResult(bobWilsonsGarageServiceResult)
ctx.complete(result)
}
}
}
}
| dbolene/BobWilsonsGarage | frontEnd/src/main/scala/com/bobwilsonsgarage/frontend/rest/routes/OrdersRoutes.scala | Scala | apache-2.0 | 3,576 |
package cromwell.database.slick
import cats.instances.future._
import cats.syntax.functor._
import cromwell.database.sql.SubWorkflowStoreSqlDatabase
import cromwell.database.sql.tables.SubWorkflowStoreEntry
import scala.concurrent.{ExecutionContext, Future}
import scala.language.postfixOps
trait SubWorkflowStoreSlickDatabase extends SubWorkflowStoreSqlDatabase {
this: EngineSlickDatabase =>
import dataAccess.driver.api._
def addSubWorkflowStoreEntry(rootWorkflowExecutionUuid: String,
parentWorkflowExecutionUuid: String,
callFullyQualifiedName: String,
jobIndex: Int,
jobAttempt: Int,
subWorkflowExecutionUuid: String)(implicit ec: ExecutionContext): Future[Unit] = {
val action = for {
workflowStoreEntry <- dataAccess.workflowStoreEntriesForWorkflowExecutionUuid(rootWorkflowExecutionUuid).result.headOption
_ <- workflowStoreEntry match {
case Some(rootWorkflow) =>
dataAccess.subWorkflowStoreEntryIdsAutoInc +=
SubWorkflowStoreEntry(
rootWorkflow.workflowStoreEntryId,
parentWorkflowExecutionUuid,
callFullyQualifiedName,
jobIndex,
jobAttempt,
subWorkflowExecutionUuid
)
case None => DBIO.failed(new IllegalArgumentException(s"Could not find root workflow with UUID $rootWorkflowExecutionUuid"))
}
} yield ()
runTransaction(action) void
}
override def querySubWorkflowStore(parentWorkflowExecutionUuid: String, callFqn: String, jobIndex: Int, jobAttempt: Int)
(implicit ec: ExecutionContext): Future[Option[SubWorkflowStoreEntry]] = {
val action = for {
subWorkflowStoreEntryOption <- dataAccess.subWorkflowStoreEntriesForJobKey(
(parentWorkflowExecutionUuid, callFqn, jobIndex, jobAttempt)
).result.headOption
} yield subWorkflowStoreEntryOption
runTransaction(action)
}
override def removeSubWorkflowStoreEntries(rootWorkflowExecutionUuid: String)
(implicit ec: ExecutionContext): Future[Int] = {
val action = for {
workflowStoreEntry <- dataAccess.workflowStoreEntriesForWorkflowExecutionUuid(rootWorkflowExecutionUuid).result.headOption
deleted <- workflowStoreEntry match {
case Some(rootWorkflow) =>
dataAccess.subWorkflowStoreEntriesForRootWorkflowId(rootWorkflow.workflowStoreEntryId.get).delete
case None =>
DBIO.successful(0)
}
} yield deleted
runTransaction(action)
}
}
| ohsu-comp-bio/cromwell | database/sql/src/main/scala/cromwell/database/slick/SubWorkflowStoreSlickDatabase.scala | Scala | bsd-3-clause | 2,722 |
package ch3
import List._
object Exercise3 {
def setHead[T](l: List[T], newValue: T) = l match {
case Nil => Nil
case Cons(x, Nil) => Cons(newValue, Nil)
case Cons(x, xs) => Cons(newValue, xs)
}
}
import Exercise3._
/*
from repl you can test typing:
:load src/main/scala/fpinscala/ch3/List.scala
:load src/main/scala/fpinscala/ch3/Exercise3.scala
setHead(Nil, 5)
setHead(List(), 5)
setHead(List(1), 5)
setHead(List(1,2,3,4,5), 5)
*/
| rucka/fpinscala | src/main/scala/fpinscala/ch3/Exercise3.scala | Scala | gpl-2.0 | 465 |
/*
* 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 ai.h2o.sparkling.ml.params
import ai.h2o.sparkling.H2OFrame
trait HasUnsupportedOffsetCol {
def getOffsetCol(): String = null
def setOffsetCol(value: String): this.type = {
val className = this.getClass.getName
throw new UnsupportedOperationException(s"The parameter 'offsetCol' is not yet supported on $className.")
}
private[sparkling] def getUnsupportedOffsetColParam(trainingFrame: H2OFrame): Map[String, Any] = Map.empty
}
| h2oai/sparkling-water | ml/src/main/scala/ai/h2o/sparkling/ml/params/HasUnsupportedOffsetCol.scala | Scala | apache-2.0 | 1,259 |
package com.simple.simplespec.matchers
import scala.collection.TraversableLike
import org.hamcrest.{Description, BaseMatcher}
class SizedTraversableMatcher[A <: TraversableLike[_, _]](expectedSize: Int) extends BaseMatcher[A] {
def describeTo(description: Description) {
description.appendText("a collection with a size of ").appendValue(expectedSize)
}
def matches(item: AnyRef) = item match {
case coll: TraversableLike[_, _] => coll.hasDefiniteSize && coll.size == expectedSize
case _ => false
}
}
| SimpleFinance/simplespec | src/main/scala/com/simple/simplespec/matchers/SizedTraversableMatcher.scala | Scala | mit | 524 |
/*
* Copyright 2014–2018 SlamData 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 quasar.frontend.logicalplan
import slamdata.Predef._
import quasar._, RenderTree.ops._
import quasar.common.{JoinType, SortDir}
import quasar.contrib.pathy.{FPath, refineTypeAbs}
import quasar.contrib.shapeless._
import quasar.fp._
import quasar.fp.binder._
import quasar.time.TemporalPart
import scala.Symbol
import scala.Predef.$conforms
import matryoshka._
import matryoshka.implicits._
import scalaz._, Scalaz._
import shapeless.{Nat, Sized}
import pathy.Path.posixCodec
sealed abstract class LogicalPlan[A] extends Product with Serializable {
// TODO this should be removed, but usage of `==` is so pervasive in
// external dependencies (and scalac) that removal may never be possible
override def equals(that: scala.Any): Boolean = that match {
case lp: LogicalPlan[A] => LogicalPlan.equal(Equal.equalA[A]).equal(this, lp)
case _ => false
}
}
final case class Read[A](path: FPath) extends LogicalPlan[A]
final case class Constant[A](data: Data) extends LogicalPlan[A]
final case class Invoke[N <: Nat, A](func: GenericFunc[N], values: Func.Input[A, N])
extends LogicalPlan[A]
// TODO we create a custom `unapply` to bypass a scalac pattern matching bug
// https://issues.scala-lang.org/browse/SI-5900
object InvokeUnapply {
def unapply[N <: Nat, A](in: Invoke[N, A])
: Some[(GenericFunc[N], Func.Input[A, N])] =
Some((in.func, in.values))
}
final case class JoinSideName[A](name: Symbol) extends LogicalPlan[A]
final case class JoinCondition[A](leftName: Symbol, rightName: Symbol, value: A)
final case class Join[A](left: A, right: A, tpe: JoinType, condition: JoinCondition[A])
extends LogicalPlan[A]
final case class Free[A](name: Symbol) extends LogicalPlan[A]
final case class Let[A](let: Symbol, form: A, in: A) extends LogicalPlan[A]
final case class Sort[A](src: A, order: NonEmptyList[(A, SortDir)])
extends LogicalPlan[A]
final case class TemporalTrunc[A](part: TemporalPart, src: A) extends LogicalPlan[A]
// NB: This should only be inserted by the type checker. In future, this
// should only exist in BlackShield – the checker will annotate nodes
// where runtime checks are necessary, then they will be added during
// compilation to BlackShield.
final case class Typecheck[A](expr: A, typ: Type, cont: A, fallback: A)
extends LogicalPlan[A]
object LogicalPlan {
import quasar.std.StdLib._
implicit val traverse: Traverse[LogicalPlan] =
new Traverse[LogicalPlan] {
def traverseImpl[G[_], A, B](
fa: LogicalPlan[A])(
f: A => G[B])(
implicit G: Applicative[G]):
G[LogicalPlan[B]] =
fa match {
case Read(coll) => G.point(Read(coll))
case Constant(data) => G.point(Constant(data))
case Invoke(func, values) => values.traverse(f).map(Invoke(func, _))
case JoinSideName(v) => G.point(JoinSideName(v))
case Join(l, r, tpe, JoinCondition(lName, rName, cond)) =>
(f(l) ⊛ f(r) ⊛ f(cond))((v1, v2, v3) => Join(v1, v2, tpe, JoinCondition(lName, rName, v3)))
case Free(v) => G.point(Free(v))
case Let(ident, form, in) => (f(form) ⊛ f(in))(Let(ident, _, _))
case Sort(src, ords) =>
(f(src) ⊛ ords.traverse { case (a, d) => f(a) strengthR d })(Sort(_, _))
case TemporalTrunc(part, src) => f(src) ∘ (TemporalTrunc(part, _))
case Typecheck(expr, typ, cont, fallback) =>
(f(expr) ⊛ f(cont) ⊛ f(fallback))(Typecheck(_, typ, _, _))
}
override def map[A, B](v: LogicalPlan[A])(f: A => B): LogicalPlan[B] =
v match {
case Read(coll) => Read(coll)
case Constant(data) => Constant(data)
case Invoke(func, values) => Invoke(func, values.map(f))
case JoinSideName(v) => JoinSideName(v)
case Join(l, r, tpe, JoinCondition(lName, rName, cond)) =>
Join(f(l), f(r), tpe, JoinCondition(lName, rName, f(cond)))
case Free(v) => Free(v)
case Let(ident, form, in) => Let(ident, f(form), f(in))
case Sort(src, ords) => Sort(f(src), ords map (f.first))
case TemporalTrunc(part, src) => TemporalTrunc(part, f(src))
case Typecheck(expr, typ, cont, fallback) =>
Typecheck(f(expr), typ, f(cont), f(fallback))
}
override def foldMap[A, B](fa: LogicalPlan[A])(f: A => B)(implicit B: Monoid[B]): B =
fa match {
case Read(_) => B.zero
case Constant(_) => B.zero
case Invoke(_, values) => values.foldMap(f)
case JoinSideName(_) => B.zero
case Join(l, r, _, JoinCondition(_, _, v)) =>
f(l) ⊹ f(r) ⊹ f(v)
case Free(_) => B.zero
case Let(_, form, in) => f(form) ⊹ f(in)
case Sort(src, ords) => f(src) ⊹ ords.foldMap { case (a, _) => f(a) }
case TemporalTrunc(_, src) => f(src)
case Typecheck(expr, _, cont, fallback) =>
f(expr) ⊹ f(cont) ⊹ f(fallback)
}
override def foldRight[A, B](fa: LogicalPlan[A], z: => B)(f: (A, => B) => B): B =
fa match {
case Read(_) => z
case Constant(_) => z
case Invoke(_, values) => values.foldRight(z)(f)
case JoinSideName(_) => z
case Join(l, r, _, JoinCondition(_, _, v)) =>
f(l, f(r, f(v, z)))
case Free(_) => z
case Let(ident, form, in) => f(form, f(in, z))
case Sort(src, ords) => f(src, ords.foldRight(z) { case ((a, _), b) => f(a, b) })
case TemporalTrunc(_, src) => f(src, z)
case Typecheck(expr, _, cont, fallback) =>
f(expr, f(cont, f(fallback, z)))
}
}
implicit val show: Delay[Show, LogicalPlan] =
new Delay[Show, LogicalPlan] {
def apply[A](sa: Show[A]): Show[LogicalPlan[A]] = {
implicit val showA: Show[A] = sa
Show.show {
case Read(v) =>
Cord("Read(") ++ v.show ++ Cord(")")
case Constant(v) =>
Cord("Constant(") ++ v.show ++ Cord(")")
case Invoke(func, values) =>
// TODO remove trailing comma
func.show ++ Cord("(") ++
values.foldLeft(Cord("")){ case (acc, v) => acc ++ sa.show(v) ++ Cord(", ") } ++ Cord(")")
case JoinSideName(n) =>
Cord("JoinSideName(") ++ Cord(n.toString) ++ Cord(")")
case Join(l, r, tpe, JoinCondition(lName, rName, v)) =>
Cord("Join(") ++
l.show ++ Cord(", ") ++
r.show ++ Cord(", ") ++
tpe.show ++ Cord(", ") ++
Cord(lName.toString) ++ Cord(", ") ++
Cord(rName.toString) ++ Cord(", ") ++
v.show ++ Cord(")")
case Free(n) =>
Cord("Free(") ++ Cord(n.toString) ++ Cord(")")
case Let(n, f, b) =>
Cord("Let(") ++ Cord(n.toString) ++ Cord(",") ++
sa.show(f) ++ Cord(",") ++ sa.show(b) ++ Cord(")")
case Sort(src, ords) =>
Cord("Sort(") ++ sa.show(src) ++ Cord(", ") ++ ords.show ++ Cord(")")
case TemporalTrunc(part, src) =>
Cord("TemporalTrunc(") ++ part.show ++ Cord(",") ++ sa.show(src) ++ Cord(")")
case Typecheck(e, t, c, f) =>
Cord("Typecheck(") ++ sa.show(e) ++ Cord(",") ++ t.show ++ Cord(",") ++
sa.show(c) ++ Cord(",") ++ sa.show(f) ++ Cord(")")
}
}
}
implicit val renderTree: Delay[RenderTree, LogicalPlan] =
new Delay[RenderTree, LogicalPlan] {
def apply[A](ra: RenderTree[A]): RenderTree[LogicalPlan[A]] =
new RenderTree[LogicalPlan[A]] {
val nodeType = "LogicalPlan" :: Nil
def render(v: LogicalPlan[A]) = v match {
// NB: a couple of special cases for readability
case Constant(Data.Str(str)) => Terminal("Str" :: "Constant" :: nodeType, Some(str.shows))
case InvokeUnapply(func @ structural.MapProject, Sized(expr, name)) =>
(ra.render(expr), ra.render(name)) match {
case (exprR @ RenderedTree(_, Some(_), Nil), RenderedTree(_, Some(n), Nil)) =>
Terminal("MapProject" :: nodeType, Some(exprR.shows + "{" + n + "}"))
case (x, n) => NonTerminal("Invoke" :: nodeType, Some(func.shows), x :: n :: Nil)
}
case Read(file) => Terminal("Read" :: nodeType, Some(posixCodec.printPath(file)))
case Constant(data) => Terminal("Constant" :: nodeType, Some(data.shows))
case InvokeUnapply(func, args) => NonTerminal("Invoke" :: nodeType, Some(func.shows), args.unsized.map(ra.render))
case JoinSideName(name) => Terminal("JoinSideName" :: nodeType, Some(name.toString))
case Join(l, r, t, JoinCondition(lName, rName, c)) =>
NonTerminal("Join" :: nodeType, None, List(
ra.render(l),
ra.render(r),
RenderTree[JoinType].render(t),
Terminal("LeftSide" :: nodeType, Some(lName.toString)),
Terminal("RightSide" :: nodeType, Some(rName.toString)),
ra.render(c)))
case Free(name) => Terminal("Free" :: nodeType, Some(name.toString))
case Let(ident, form, body) => NonTerminal("Let" :: nodeType, Some(ident.toString), List(ra.render(form), ra.render(body)))
case Sort(src, ords) =>
NonTerminal("Sort" :: nodeType, None,
(ra.render(src) :: ords.list.flatMap {
case (a, d) => IList(ra.render(a), d.render)
}).toList)
case TemporalTrunc(part, src) =>
NonTerminal("TemporalTrunc" :: nodeType, Some(part.shows), List(ra.render(src)))
case Typecheck(expr, typ, cont, fallback) =>
NonTerminal("Typecheck" :: nodeType, Some(typ.shows),
List(ra.render(expr), ra.render(cont), ra.render(fallback)))
}
}
}
@SuppressWarnings(Array("org.wartremover.warts.Equals"))
implicit val equal: Delay[Equal, LogicalPlan] =
new Delay[Equal, LogicalPlan] {
def apply[A](fa: Equal[A]) = {
implicit val eqA: Equal[A] = fa
Equal.equal {
case (Read(n1), Read(n2)) => refineTypeAbs(n1) ≟ refineTypeAbs(n2)
case (Constant(d1), Constant(d2)) => d1 ≟ d2
case (InvokeUnapply(f1, v1), InvokeUnapply(f2, v2)) => f1 == f2 && v1.unsized ≟ v2.unsized // TODO impl `scalaz.Equal` for `GenericFunc`
case (JoinSideName(n1), JoinSideName(n2)) => n1 ≟ n2
case (Join(l1, r1, t1, JoinCondition(lName1, rName1, c1)), Join(l2, r2, t2, JoinCondition(lName2, rName2, c2))) =>
l1 ≟ l2 && r1 ≟ r2 && t1 ≟ t2 && lName1 ≟ lName2 && rName1 ≟ rName2 && c1 ≟ c2
case (Free(n1), Free(n2)) => n1 ≟ n2
case (Let(ident1, form1, in1), Let(ident2, form2, in2)) =>
ident1 ≟ ident2 && form1 ≟ form2 && in1 ≟ in2
case (Sort(s1, o1), Sort(s2, o2)) => s1 ≟ s2 && o1 ≟ o2
case (TemporalTrunc(part1, src1), TemporalTrunc(part2, src2)) =>
part1 ≟ part2 && src1 ≟ src2
case (Typecheck(expr1, typ1, cont1, fb1), Typecheck(expr2, typ2, cont2, fb2)) =>
expr1 ≟ expr2 && typ1 ≟ typ2 && cont1 ≟ cont2 && fb1 ≟ fb2
case _ => false
}
}
}
implicit val unzip: Unzip[LogicalPlan] = new Unzip[LogicalPlan] {
def unzip[A, B](f: LogicalPlan[(A, B)]) = (f.map(_._1), f.map(_._2))
}
implicit val binder: Binder[LogicalPlan] = new Binder[LogicalPlan] {
type G[A] = Map[Symbol, A]
val G = Traverse[G]
def initial[A] = Map[Symbol, A]()
def bindings[T, A]
(t: LogicalPlan[T], b: G[A])
(f: LogicalPlan[T] => A)
(implicit T: Recursive.Aux[T, LogicalPlan])
: G[A] =
t match {
case Let(ident, form, _) => b + (ident -> f(form.project))
case _ => b
}
def subst[T, A]
(t: LogicalPlan[T], b: G[A])
(implicit T: Recursive.Aux[T, LogicalPlan])
: Option[A] =
t match {
case Free(symbol) => b.get(symbol)
case _ => None
}
}
}
| jedesah/Quasar | frontend/src/main/scala/quasar/frontend/logicalplan/LogicalPlan.scala | Scala | apache-2.0 | 13,159 |
/*
* Copyright (c) 2014-2018 by The Monix Project Developers.
* See the project homepage at: https://monix.io
*
* 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 monix.reactive.observers.buffers
import monix.execution.Ack
import monix.execution.Ack.{Continue, Stop}
import monix.execution.atomic.PaddingStrategy.{LeftRight128, LeftRight256}
import monix.execution.atomic.{Atomic, AtomicAny, AtomicInt}
import monix.execution.internal.math
import scala.util.control.NonFatal
import monix.reactive.OverflowStrategy._
import monix.reactive.observers.buffers.AbstractEvictingBufferedSubscriber._
import monix.reactive.observers.{BufferedSubscriber, Subscriber}
import scala.collection.immutable.Queue
import scala.concurrent.Future
import scala.util.{Failure, Success}
/** A [[BufferedSubscriber]] implementation for the
* [[monix.reactive.OverflowStrategy.DropOld DropOld]]
* and for the
* [[monix.reactive.OverflowStrategy.ClearBuffer ClearBuffer]]
* overflow strategies.
*/
private[observers] final class EvictingBufferedSubscriber[-A] private
(out: Subscriber[A], strategy: Evicted[Nothing], onOverflow: Long => Option[A])
extends AbstractEvictingBufferedSubscriber(out, strategy, onOverflow) {
@volatile protected var p50, p51, p52, p53, p54, p55, p56, p57 = 5
@volatile protected var q50, q51, q52, q53, q54, q55, q56, q57 = 5
}
private[observers] object EvictingBufferedSubscriber {
/** Returns an instance of a [[EvictingBufferedSubscriber]]
* for the [[monix.reactive.OverflowStrategy.DropOld DropOld]]
* overflow strategy.
*/
def dropOld[A](underlying: Subscriber[A], bufferSize: Int): EvictingBufferedSubscriber[A] = {
require(bufferSize > 1, "bufferSize must be a strictly positive number, bigger than 1")
val maxCapacity = math.nextPowerOf2(bufferSize)
new EvictingBufferedSubscriber[A](underlying, DropOld(maxCapacity), null)
}
/** Returns an instance of a [[EvictingBufferedSubscriber]]
* for the [[monix.reactive.OverflowStrategy.DropOld DropOld]]
* overflow strategy, with signaling of the number of events that
* were dropped.
*/
def dropOldAndSignal[A](underlying: Subscriber[A],
bufferSize: Int, onOverflow: Long => Option[A]): EvictingBufferedSubscriber[A] = {
require(bufferSize > 1, "bufferSize must be a strictly positive number, bigger than 1")
val maxCapacity = math.nextPowerOf2(bufferSize)
new EvictingBufferedSubscriber[A](underlying, DropOld(maxCapacity), onOverflow)
}
/** Returns an instance of a [[EvictingBufferedSubscriber]] for the
* [[monix.reactive.OverflowStrategy.ClearBuffer ClearBuffer]]
* overflow strategy.
*/
def clearBuffer[A](underlying: Subscriber[A], bufferSize: Int): EvictingBufferedSubscriber[A] = {
require(bufferSize > 1,
"bufferSize must be a strictly positive number, bigger than 1")
require(bufferSize > 1, "bufferSize must be a strictly positive number, bigger than 1")
val maxCapacity = math.nextPowerOf2(bufferSize)
new EvictingBufferedSubscriber[A](underlying, ClearBuffer(maxCapacity), null)
}
/** Returns an instance of a [[EvictingBufferedSubscriber]]
* for the [[monix.reactive.OverflowStrategy.ClearBuffer ClearBuffer]]
* overflow strategy, with signaling of the number of events that
* were dropped.
*/
def clearBufferAndSignal[A](underlying: Subscriber[A],
bufferSize: Int, onOverflow: Long => Option[A]): EvictingBufferedSubscriber[A] = {
require(bufferSize > 1, "bufferSize must be a strictly positive number, bigger than 1")
val maxCapacity = math.nextPowerOf2(bufferSize)
new EvictingBufferedSubscriber[A](underlying, ClearBuffer(maxCapacity), onOverflow)
}
}
private[observers] abstract class AbstractEvictingBufferedSubscriber[-A]
(out: Subscriber[A], strategy: Evicted[Nothing], onOverflow: Long => Option[A])
extends CommonBufferMembers with BufferedSubscriber[A] with Subscriber.Sync[A] {
require(strategy.bufferSize > 0, "bufferSize must be a strictly positive number")
implicit val scheduler = out.scheduler
private[this] val em = out.scheduler.executionModel
private[this] val droppedCount: AtomicInt =
if (onOverflow != null) AtomicInt.withPadding(0, LeftRight128)
else null
private[this] val itemsToPush =
Atomic.withPadding(0, LeftRight256)
private[this] val queue =
new ConcurrentBuffer[A](strategy)
def onNext(elem: A): Ack = {
if (upstreamIsComplete || downstreamIsComplete) Stop else {
if (elem == null) {
onError(new NullPointerException("Null not supported in onNext"))
Stop
}
else {
val dropped = queue.offer(elem)
if (dropped > 0 && onOverflow != null)
droppedCount.increment(dropped)
val increment = 1 - dropped
pushToConsumer(increment)
Continue
}
}
}
def onError(ex: Throwable): Unit = {
if (!upstreamIsComplete && !downstreamIsComplete) {
errorThrown = ex
upstreamIsComplete = true
pushToConsumer(1)
}
}
def onComplete(): Unit = {
if (!upstreamIsComplete && !downstreamIsComplete) {
upstreamIsComplete = true
pushToConsumer(1)
}
}
private[this] def pushToConsumer(increment: Int): Unit = {
val currentNr = {
if (increment != 0)
itemsToPush.getAndIncrement(increment)
else
itemsToPush.get
}
// If a run-loop isn't started, then go, go, go!
if (currentNr == 0) {
// Starting the run-loop, as at this point we can be sure
// that no other loop is active
scheduler.execute(consumerLoop)
}
}
private[this] val consumerLoop = new Runnable {
def run(): Unit = {
// This lastIterationAck is also being set by the consumer-loop,
// but it's important for the write to happen before `itemsToPush`,
// to ensure its visibility
fastLoop(Queue.empty, lastIterationAck, 0, 0)
}
private def signalNext(next: A): Future[Ack] =
try {
val ack = out.onNext(next)
// Tries flattening the Future[Ack] to a
// synchronous value
if (ack == Continue || ack == Stop)
ack
else ack.value match {
case Some(Success(success)) =>
success
case Some(Failure(ex)) =>
signalError(ex)
Stop
case None =>
ack
}
} catch {
case ex if NonFatal(ex) =>
signalError(ex)
Stop
}
private def signalComplete(): Unit =
try out.onComplete() catch {
case ex if NonFatal(ex) =>
scheduler.reportFailure(ex)
}
private def signalError(ex: Throwable): Unit =
try out.onError(ex) catch {
case err if NonFatal(err) =>
scheduler.reportFailure(err)
}
private def goAsync(prevQueue: Queue[A], next: A, ack: Future[Ack], processed: Int, toProcess: Int): Unit =
ack.onComplete {
case Success(Continue) =>
val nextAck = signalNext(next)
val isSync = ack == Continue || ack == Stop
val nextFrame = if (isSync) em.nextFrameIndex(0) else 0
fastLoop(prevQueue, nextAck, processed + toProcess, nextFrame)
case Success(Stop) =>
// ending loop
downstreamIsComplete = true
case Failure(ex) =>
// ending loop
downstreamIsComplete = true
signalError(ex)
}
private def fastLoop(prevQueue: Queue[A], prevAck: Future[Ack], lastProcessed: Int, startIndex: Int): Unit = {
var ack = if (prevAck == null) Continue else prevAck
var isFirstIteration = ack == Continue
var processed = lastProcessed
var nextIndex = startIndex
var currentQueue = prevQueue
while (!downstreamIsComplete) {
var streamErrors = true
try {
// Local cache
if (currentQueue.isEmpty) currentQueue = queue.drain()
// The `processed` count is only for counting things processed
// from the queue, but not overflow messages, as these are
// not pushed to the queue - so we keep track of what to add
var toProcess = 0
val next: A = {
// Do we have an overflow message to send?
val overflowMessage =
if (onOverflow == null || droppedCount.get == 0)
null.asInstanceOf[A]
else
onOverflow(droppedCount.getAndSet(0)) match {
case Some(value) => value
case None => null.asInstanceOf[A]
}
if (overflowMessage != null) overflowMessage else {
if (currentQueue.isEmpty)
null.asInstanceOf[A]
else {
val (ref,q) = currentQueue.dequeue
currentQueue = q
toProcess = 1
ref
}
}
}
// Threshold after which we are no longer allowed to
// stream errors downstream if they happen
streamErrors = false
if (next != null) {
if (nextIndex > 0 || isFirstIteration) {
isFirstIteration = false
ack match {
case Continue =>
ack = signalNext(next)
if (ack == Stop) {
// ending loop
downstreamIsComplete = true
return
} else {
val isSync = ack == Continue
nextIndex = if (isSync) em.nextFrameIndex(nextIndex) else 0
processed += toProcess
}
case Stop =>
// ending loop
downstreamIsComplete = true
return
case _ =>
goAsync(currentQueue, next, ack, processed, toProcess)
return
}
}
else {
goAsync(currentQueue, next, ack, processed, toProcess)
return
}
}
else if (upstreamIsComplete) {
// Race-condition check, but if upstreamIsComplete=true is
// visible, then the queue should be fully published because
// there's a clear happens-before relationship between
// queue.offer() and upstreamIsComplete=true
currentQueue = queue.drain()
if (currentQueue.isEmpty && (onOverflow == null || droppedCount.get == 0)) {
// ending loop
downstreamIsComplete = true
if (errorThrown ne null) signalError(errorThrown)
else signalComplete()
return
}
}
else {
// Given we are writing in `itemsToPush` before this
// assignment, it means that writes will not get reordered,
// so when we observe that itemsToPush is zero on the
// producer side, we will also have the latest lastIterationAck
lastIterationAck = ack
val remaining = itemsToPush.decrementAndGet(processed)
processed = 0
// if the queue is non-empty (i.e. concurrent modifications
// just happened) then continue loop, otherwise stop
if (remaining <= 0) return
}
} catch {
case ex if NonFatal(ex) =>
if (streamErrors) {
// ending loop
downstreamIsComplete = true
signalError(ex)
} else {
scheduler.reportFailure(ex)
}
}
}
}
}
}
private[observers] object AbstractEvictingBufferedSubscriber {
private final class ConcurrentBuffer[A](strategy: Evicted[Nothing]) {
private[this] val bufferRef: AtomicAny[Buffer[A]] =
AtomicAny.withPadding(emptyBuffer, LeftRight256)
def drain(): Queue[A] = {
val current = bufferRef.getAndSet(emptyBuffer)
current.queue
}
def offer(a: A): Int = {
val current = bufferRef.get
val length = current.length
val queue = current.queue
if (length < strategy.bufferSize) {
val update = Buffer(length+1, queue.enqueue(a))
if (!bufferRef.compareAndSet(current, update))
offer(a)
else
0
} else {
strategy match {
case DropOld(_) | DropOldAndSignal(_, _) =>
val (_, q) = queue.dequeue
val update = Buffer(length, q.enqueue(a))
if (!bufferRef.compareAndSet(current, update))
offer(a)
else
1
case ClearBuffer(_) | ClearBufferAndSignal(_, _) =>
val update = Buffer(1, Queue(a))
if (!bufferRef.compareAndSet(current, update))
offer(a)
else
length
case DropNew(_) | DropNewAndSignal(_, _) =>
// The buffer for DropNew is specialized, so
// we should never get this case
1
}
}
}
}
private final case class Buffer[+A](
length: Int,
queue: Queue[A])
private val emptyBuffer =
Buffer(0, Queue.empty)
}
| Wogan/monix | monix-reactive/jvm/src/main/scala/monix/reactive/observers/buffers/EvictingBufferedSubscriber.scala | Scala | apache-2.0 | 13,730 |
package composing_methods
/**
* Created by lingx on 2015/10/27.
*/
class IntroduceExplainingVariable {
}
| zj-lingxin/refactoring | src/main/scala/composing_methods/IntroduceExplainingVariable.scala | Scala | mit | 109 |
/* Title: Tools/jEdit/src/active.scala
Author: Makarius
Active areas within the document.
*/
package isabelle.jedit
import isabelle._
import org.gjt.sp.jedit.View
object Active
{
def action(view: View, text: String, elem: XML.Elem)
{
GUI_Thread.require {}
Document_View(view.getTextArea) match {
case Some(doc_view) =>
doc_view.rich_text_area.robust_body() {
val text_area = doc_view.text_area
val model = doc_view.model
val buffer = model.buffer
val snapshot = model.snapshot()
if (!snapshot.is_outdated) {
// FIXME avoid hard-wired stuff
elem match {
case XML.Elem(Markup(Markup.BROWSER, _), body) =>
Future.fork {
val graph_file = Isabelle_System.tmp_file("graph")
File.write(graph_file, XML.content(body))
Isabelle_System.bash_env(null,
Map("GRAPH_FILE" -> Isabelle_System.posix_path(graph_file)),
"\\"$ISABELLE_TOOL\\" browser -c \\"$GRAPH_FILE\\" &")
}
case XML.Elem(Markup(Markup.GRAPHVIEW, _), body) =>
Future.fork {
val graph =
Exn.capture {
isabelle.graphview.Model.decode_graph(body)
.transitive_reduction_acyclic
}
GUI_Thread.later { Graphview_Dockable(view, snapshot, graph) }
}
case XML.Elem(Markup(Markup.SIMP_TRACE_PANEL, props), _) =>
val link =
props match {
case Position.Id(id) => PIDE.editor.hyperlink_command_id(snapshot, id)
case _ => None
}
GUI_Thread.later {
link.foreach(_.follow(view))
view.getDockableWindowManager.showDockableWindow("isabelle-simplifier-trace")
}
case XML.Elem(Markup(Markup.SENDBACK, props), _) =>
if (buffer.isEditable) {
props match {
case Position.Id(id) =>
Isabelle.edit_command(snapshot, buffer,
props.exists(_ == Markup.PADDING_COMMAND), id, text)
case _ =>
if (props.exists(_ == Markup.PADDING_LINE))
Isabelle.insert_line_padding(text_area, text)
else text_area.setSelectedText(text)
}
text_area.requestFocus
}
case Protocol.Dialog(id, serial, result) =>
model.session.dialog_result(id, serial, result)
case _ =>
}
}
}
case None =>
}
}
}
| MerelyAPseudonym/isabelle | src/Tools/jEdit/src/active.scala | Scala | bsd-3-clause | 2,838 |
import java.io.File
import scala.io.Source
object Main extends App {
implicit class RichFile(val from: File) extends AnyVal {
def read = Source.fromFile(from.getPath).mkString
}
val contents = new File("RichFile2.scala").read
println(contents)
}
| yeahnoob/scala-impatient-2e-code | src/ch21/sec02/RichFile2.scala | Scala | gpl-3.0 | 260 |
/*
* Beangle, Agile Development Scaffold and Toolkits.
*
* Copyright © 2005, The Beangle Software.
*
* 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.beangle.sas.tomcat
import java.io.File
import org.beangle.sas.model.{Container, Engine, Farm, Host, Server}
import org.junit.runner.RunWith
import org.scalatest.funspec.AnyFunSpec
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class TomcatMakerTest extends AnyFunSpec with Matchers {
describe("Resolver") {
it("make catalina engine") {
val sasHome = "/tmp/sas"
val engine = new Engine("tomcat85", "tomcat", "8.5.15")
val farm = new Farm("farm", engine)
val server = new Server(farm, "server1")
val container = new Container
container.farms += farm
engine.jspSupport = true
val file = new File("/tmp/apache-tomcat-8.5.15.zip")
if (file.exists()) {
TomcatMaker.doMakeEngine("/tmp/sas", engine, file)
TomcatMaker.doMakeBase(sasHome, container, server,Set(Host.Localhost.ip))
}
}
}
}
| beangle/tomcat | shell/src/test/scala/org/beangle/sas/tomcat/TomcatMakerTest.scala | Scala | gpl-3.0 | 1,733 |
package object postoffice {
type Weight = Double
}
| blstream/akka-viz | demo/src/main/scala/postoffice/package.scala | Scala | mit | 53 |
/*
Copyright 2012 Georgia Tech Research Institute
Author: [email protected]
This file is part of org.gtri.util.iteratee library.
org.gtri.util.iteratee library 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.
org.gtri.util.iteratee library 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 org.gtri.util.iteratee library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gtri.util.iteratee.impl.test
import org.gtri.util.iteratee.api.{StatusCode, ImmutableBuffer, Iteratee}
import org.gtri.util.iteratee.impl.iteratees._
import org.gtri.util.iteratee.impl.ImmutableBufferConversions._
/**
* Created with IntelliJ IDEA.
* User: Lance
* Date: 11/28/12
* Time: 8:35 PM
* To change this template use File | Settings | File Templates.
*/
class TestIntIteratee extends Iteratee[java.lang.Integer, java.lang.Integer] {
class Cont(loopState : java.lang.Integer) extends MultiItemCont[java.lang.Integer, java.lang.Integer] {
def apply(items: ImmutableBuffer[java.lang.Integer]) = {
println("debug=" + items + " loopState=" + loopState)
Result(new Cont(items.fold(loopState) { _ + _ }))
}
def endOfInput() = Success(loopState)
}
def initialState() = new Cont(0)
}
| gtri-iead/org.gtri.util.iteratee | impl/src/main/scala/org/gtri/util/iteratee/impl/test/TestIntIteratee.scala | Scala | gpl-3.0 | 1,741 |
package Chapter14
object PatternMatchingAndCaseClasses {
// topics:
// a better switch
// guards
// variables in patterns
// type patterns
// matching arrays, lists, tuples
// extractors
// patterns in variable declarations
// patterns in for-expressions
// case classes
// the copy method and named parameters
// infix notations in case clauses
// matching nested structures
// are case classes evil?
// sealed classes
// simulating enumerations
// the option type
// partial functions
// pattern matching applications: 'switch' statement, type inquiry, destructuring;
// case classes are optimized for pattern matching, compiler produce some methods;
// 'match' expression is a better 'switch', no fal-through;
// MatchError if no matches, use 'case _' to avoid it;
// guard: arbitrary condition in a pattern;
// can match on type;
// can bing parts to variables;
// in a 'for-expression' nonmatches are silently skipped;
// the common sup. in hierarchy should be sealed;
// a better switch
def aBetterSwitch = {
import java.awt.Color
// C-style switch
var sign: Int = ???
val ch: Char = ???
ch match {
case '+' => sign = 1
case '-' => sign = -1
case _ => sign = 0 // default, w/o default MatchError may be thrown
}
// does not suffer from the 'fall-through' problem
// 'match' is an expression (have a value)
sign = ch match {
case '+' => 1
case '-' => -1
case _ => 0
}
// use '|' to separate multiple alternatives
ch match {
case '0' | 'o' | 'O' => ???
}
// match with any types
val color: Color = ???
color match {
case Color.RED => ???
}
}
// guards
def guards = {
// match all digits? add a guard: any boolean condition
val ch: Char = ???
ch match {
case _ if Character.isDigit(ch) => ???
case '+' => ???
case _ => ??? // default
}
// always matched top-to-bottom
}
// variables in patterns
def variablesInPatterns = {
// case keyword is followed by variable name: match expression is assigned to that variable
val str: String = ???
val i: Int = ???
str(i) match {
case ch => Character.digit(ch, 10) // ch holds str(i) char
}
// '_' is a special case of this feature
// use the variable in a guard
str(i) match {
case ch if Character.isDigit(ch) => ???
}
// n.b. variable pattern can conflict with constants !!!
// case ch ... // ch holds str(i) char
// vs
// case ZERO ... // str(i) is ZERO char
import scala.math.Pi
0.5 * i match {
case Pi => ??? // 0.5 * i equals Pi?
case x => ??? // set x to 0.5 * i
}
// constants starts with UPPERCASE letter,
// variable must start with a LOWERCASE letter
// or, if you need to check equality with lowerCaseConst: use back-ticks (symbol notation)
import java.io.File.pathSeparator
str match {
case `pathSeparator` => ???
}
}
// type patterns
def typePatterns = {
//match on the type, preferred form (vs isInstanceOf)
val obj: Any = ???
obj match {
case x: Int => x
case s: String => Integer.parseInt(s)
case _: BigInt => Int.MaxValue
// case Double => ??? // matching against a type you must supply a variable name
}
// matches occur at runtime: generic types are erased
// e.g. you can't match for a specific Map type
obj match {
// case m: Map[String, Int] => ??? // don't: can't match for a specific Map type
case mm: Map[_, _] => ??? // OK for generic map
// but, arrays type are not erased (jvm feature)
case a: Array[Int] => ??? // OK
}
}
// matching arrays, lists, tuples
def matchingArraysListsTuples = {
// extractors in pattern matching: match against content
val arr: Array[Int] = ???
arr match {
case Array(0) => "one 0"
case Array(x, y) => s"two: $x, $y" // binds x, y
case Array(0, _*) => "starts with 0"
// bind a variable to tail of array
case Array(x, rest @ _*) => s"starts with $x and rest is: ${rest.mkString}"
}
// lists can be matched in the same way
// or, better, with '::' operator
val lst: List[Int] = ???
lst match {
case 0 :: Nil => ???
case x :: y :: Nil => ???
case 0 :: tail => ???
}
// tuples notation for tuples
val pair: (Int, Int) = (???, ???)
pair match {
case (0, _) => ???
case (y, 0) => ???
case _ => "neither is 0"
}
// n.b. variables are bound to parts of the expression
// called 'destructuring'
// n.b. you can't use named variables with alternatives
pair match {
case (_, 0) | (0, _) => ??? // OK
// case (x, 0) | (0, x) => ??? // error
}
}
// extractors
def extractors = {
// destructuring done using extractors: unapply, unapplySeq
val arr: Array[Int] = ???
arr match {
case Array(0) => "one 0"
case Array(x, y) => s"two: $x, $y"
case Array(0, _*) => "starts with 0"
case Array(x, rest @ _*) => s"starts with $x and rest is: ${rest.mkString}"
}
// Array companion object is an extractor: Array.unapplySeq(arr)
// regular expressions provide another good use of extractors
// match groups with pattern
val re = "([0-9]+) ([a-z]+)".r
"99 bottles" match {
case re(num, item) => ??? // num=99, item=bottles
}
// re.unapplySeq("99 bottles") // extractor is a Regex instance
}
// patterns in variable declarations
def patternsInVariableDeclarations = {
val (x, y) = (1, 2)
// useful for functions that return a pair
val (q, r) = BigInt(10) /% 3
// works for any patters with variable names
val arr: Array[Int] = ???
val Array(first, second, rest @ _*) = arr
// it works like this:
// val p(x1, ..., xn) = e
// is the same as
// val $result = e match { case p(x1, ...) => (x1, ...)
// val x1 = $result._1; ...
// this definition holds even w/o free variables
val 2 = x
// x match { case 2 => () }
// effectively: if (2 != x) throw new MatchError
}
// patterns in for-expressions
def patternsInForExpressions = {
import scala.collection.JavaConverters.propertiesAsScalaMapConverter
// for each iteration, the variables are bound
// traverse a map
for ((k, v) <- System.getProperties.asScala) println(s"$k -> $v")
// in a 'for' expression match failures are silently ignored
for ((k, "") <- System.getProperties.asScala) println(s"no value for $k")
// skip all non-empty
// or, you can use a guard
for ((k, v) <- System.getProperties.asScala if v == "") println(s"no value for $k")
}
// case classes
def caseClasses = {
// special kind of classes, optimized for pattern matching:
// constructor parameters become a 'val'
// methods generated: toString, equals, hashCode, copy
// companion object constructed with 'apply', 'unapply'
sealed abstract class Amount // sealed: hinted compiler about exhaustiveness match partial function
case class Dollar(value: Double) extends Amount
case class Currency(value: Double, unit: String) extends Amount
// use case objects for singletons
case object Nothing extends Amount
val amt: Amount = ???
amt match {
case Dollar(v) => ???
case Currency(_, u) => ???
case Nothing => ??? // no parenthesis for object
}
}
// the copy method and named parameters
def theCopyMethodAndNamedParameters = {
// 'copy' makes a new object with the same values, allowing to redefine only selected values
sealed abstract class Amount
case class Dollar(value: Double) extends Amount
case class Currency(value: Double, unit: String) extends Amount
case object Nothing extends Amount
val amt = Currency(29.95, "EUR")
val price = amt.copy(unit = "CHF") // use named parameters to modify properties
}
// infix notations in case clauses
def infixNotationsInCaseClauses = {
// if 'unapply' yields a pair, you can use infix notation in pattern
// usable for DSL construction
sealed abstract class Amount
case class Dollar(value: Double) extends Amount
case class Currency(value: Double, unit: String) extends Amount
case object Nothing extends Amount
val amt: Amount = ???
amt match {
case amount Currency "EUR" => ??? // same as: case Currency(amount, "EUR")
}
// the feature is meant for matching sequences: case class ::(head, tail) extends List
val lst: List[Int] = ???
lst match { case h :: t => ??? } // same as: case ::(h, t) // calls ::.unapply(lst)
// later you will encounter case class ~ // for parser combinators
// res match { case p ~ q => ??? } // same as: case ~(p, q)
// easier to read when more than one
// res match { case p ~ q ~ r => ??? } // vs: case ~(~(p, q), r)
// colon ':' on the end means right-to-left associativity
// case a :: b :: c // means case ::(a, ::(b, c))
// example : unapply return a pair
case object +: {
def unapply[T](arg: List[T]) = if (arg.isEmpty) None else Some( (arg.head, arg.tail) )
}
1 +: 7 +: Nil match {
case a +: b +: rest => ???
}
}
// matching nested structures
def matchingNestedStructures = {
// with case classes it's easy: match nested structures
// example: bundle of items
sealed abstract class Item
case class Article(descr: String, price: Double) extends Item
case class Bundle(descr: String, discount: Double, items: Item*) extends Item
val itm: Item = ???
itm match {
case Bundle(_, _, Article(descr, _), _*) => ??? // binds descr to the description of the first article
case Bundle(_, _, art @ Article(_, _), rest @ _*) => ??? // binds first article and the rest of the bundle
}
// app: compute price
def price(itm: Item): Double = itm match {
case Article(_, p) => p
case Bundle(_, disc, items @ _*) => items.map(price).sum - disc
}
}
// are case classes evil?
def areCaseClassesEvil = {
// compute price example: not good from OO poin of view.
// 'price' should be a method of the sup. and be redefined in bundle
// if you don't have to add another operations to class hierarchy, it's true.
// see 'expression problem'
// if you add classes and have a fixed set of operators: use polymorphism
// if you add operators and have a fixed set of classes: use pattern matching
// case classes and pattern matching is good for fixed set of classes: sealed sup
// example: List
// abstract class List
// case object Nil extends List
// case class ::(head, tail) extends List
// case classes are quite convenient:
// more concise code
// easier to read
// toString, equals, hashCode, copy for free
// some people call them 'value classes', which is wrong: value class creates no objects on instantiation
// n.b. if, god forbid, you have 'var' in case class, derive hashCode from immutable fields only;
// don't extend case class from case class: toString, equals, hashCode, copy will not be generated,
// only leaves of a tree should be case classes
}
// sealed classes
def sealedClasses = {
// compiler could check that you exhausted all alternatives in match expression
// to make it possible, declare sup as 'sealed'
sealed trait Amount
case class Dollar(value: Double) extends Amount
case class Currency(value: Double, unit: String) extends Amount
// all subclasses of a sealed must be defined in the same file
}
// simulating enumerations
def simulatingEnumerations = {
// you may prefer Enumeration class
// example
sealed trait TrafficLightColor
case object Red extends TrafficLightColor
case object Yellow extends TrafficLightColor
case object Green extends TrafficLightColor
val color: TrafficLightColor = ???
color match {
case Red => ???
case _ => ???
}
}
// the option type
def theOptionType = {
// monadic Option type with
// case class None
// case class Some
// don't use "" or null, use Option
// e.g. with maps
val score = Map("A" -> 3).get("B")
score match {
case Some(sc) => ???
case None => ???
}
// or with map.getOrElse
// option may be considered as a collection
for (sc <- score) println(s"$sc") // print only if have some value
// can use map, filter, flatMap, foreach, ...
score.map(_ + 1)
score.filter(_ > 5)
score.foreach(println)
}
// partial functions
def partialFunctions = {
// a set of case clauses enclosed in braces: partial function
// may not be defined on all inputs
// class PartialFunction[A, B]
// two methods: apply, isDefinedAt
val f: PartialFunction[Char, Int] = { case '+' => 1; case '-' => -1 }
f('-') == f.apply('-')
f.isDefinedAt(' ') // false
f('0') // MatchError
// method 'collect' of the traversable accept a partial function
"1 - 3 + 4" collect { case '+' => 1; case '-' => -1 }
// an exhaustive set of cases define a Function1, not a PartialFunction
"1 - 3 + 4" map { case '+' => 1; case '-' => -1; case _ => 0 }
// Seq is a partial function idx => T
// Map is a partial function k => v
// you can pass a map to 'collect'
" " collect Map(' ' -> 42)
// 'lift' method
// turns a PartialFunction[T, R] into Function1[T, Option[R]]
val g = f.lift
g('0') == None
g('+') == Some(1)
// example: use map in Regex.replaceSomeIn
import scala.util.matching.Regex
val msg = "At {1}, there was {2} on {3}"
val map = Map("{1}" -> "planet 7", "{2}" -> "12:30 pm", "{3}" -> "a disturbance of the force")
val pattern = """\\{([0-9]+)\\}""".r // {number}
// def mf(map: Map[String, String])(rm: Regex.Match): Option[String] = map.lift(rm.matched)
// val res = pattern.replaceSomeIn(msg, mf(map))
val res = pattern.replaceSomeIn(msg, m => map.lift(m.matched))
}
}
object PatternMatchingAndCaseClasses_Exercises {
// 1. Your Java Development Kit distribution has the source code for much of the JDK in the src.zip file.
// Unzip and search for case labels (regular expression case [^:]+:).
// Then look for comments starting with // and containing [Ff]alls? thr
// to catch comments such as // Falls through
// or // just fall thru
// Assuming the JDK programmers follow the Java code convention, which requires such a comment,
// what percentage of cases falls through?
def ex1(startFrom: String = "/tmp") = {
import scala.util.matching.Regex
// case class CaseLabels(count: Int = 0) extends AnyVal
// case class FallsThrough(count: Int = 0) extends AnyVal
// value class may not be a local class
case class CaseLabels(count: Int = 0)
case class FallsThrough(count: Int = 0)
case class Counts(labels: CaseLabels = CaseLabels(), falls: FallsThrough = FallsThrough()) {
def add(other: Counts): Counts = Counts(
CaseLabels(other.labels.count + labels.count),
FallsThrough(other.falls.count + falls.count)
)
}
def exist(re: Regex, line: String): Boolean = (re findFirstIn line).fold(false)(_ => true)
def lineProcessing(labels: Regex, falls: Regex, line: String): Counts = Counts(
CaseLabels( if (exist(labels, line)) 1 else 0 ),
FallsThrough( if (exist(falls, line)) 1 else 0 )
)
def textProcessing(lines: Iterator[String]): Counts = {
val caseLabelsRe = """case [^:]+:""".r
val fallsThroughRe = """ //.*[Ff]alls? thr""".r
val cntlist = for {
line <- lines
} yield lineProcessing(caseLabelsRe, fallsThroughRe, line)
(Counts() /: cntlist)(_ add _)
}
def fileLines(path: String): Iterator[String] = {
scala.io.Source.fromFile(path).getLines
}
def files(root: String = "/tmp"): Iterable[String] = {
import java.nio.{file => jnf}
import java.io.{File, IOException}
import rx.lang.scala.Observable
import scala.language.implicitConversions
def listFiles(dir: jnf.Path) = Observable[jnf.Path](subscriber => {
val visitor = new jnf.SimpleFileVisitor[jnf.Path] {
override def visitFile(file: jnf.Path, attrs: jnf.attribute.BasicFileAttributes) = {
if (subscriber.isUnsubscribed) jnf.FileVisitResult.TERMINATE
else {
subscriber.onNext(file)
jnf.FileVisitResult.CONTINUE
}
}
override def visitFileFailed(file: jnf.Path, exc: IOException) = {
println(s"visitFileFailed: $exc")
//subscriber.onError(exc) // exactly once
jnf.FileVisitResult.CONTINUE
}
override def postVisitDirectory(dir: jnf.Path, exc: IOException) = {
if (exc != null) println(s"postVisitDirectory: $exc")
jnf.FileVisitResult.CONTINUE
}
}
jnf.Files.walkFileTree(dir, visitor)
subscriber.onCompleted()
}) // .onErrorResumeNext(_ => Observable.empty)
val startDir = new File(root).toPath
val files = listFiles(startDir)
val srcfiles = files.filter(p => p.toString.endsWith(".java"))
files.length.subscribe(c => println(s"total files check: $c"))
srcfiles.length.subscribe(c => println(s"java files check: $c"))
// debug
srcfiles.subscribe(p => println(p))
// result: escape async world // not really good decision
srcfiles.map(p => p.toAbsolutePath.toString).toBlocking.toIterable
}
// TODO: all pipeline should be reactive (try Akka Streams)
// add unit tests for text processing stages
// do grep and count
val res = files(startFrom)
.map(path => fileLines(path))
.map(lines => textProcessing(lines))
.fold(Counts())(_ add _)
// scala> f"'$res16%8.3f'" // float width.precision example
// res26: String = ' 101.000'
println(f"counts: $res; falls thru ${100d * res.falls.count / (1 + res.labels.count)}%4.2f%%")
// java files check: 7711
// counts: Counts(CaseLabels(10099),FallsThrough(102)); falls thru 1.01
}
// 2. Using pattern matching, write a function 'swap' that receives a pair of integers and returns the
// pair with the components swapped.
def ex2 = {
def swap(pair: (Int, Int)) = pair match { case (a, b) => (b, a) }
// test
assert((1, 2) == swap((2, 1)))
}
// 3. Using pattern matching, write a function 'swap' that swaps the first two elements of an array
// provided its length is at least two.
def ex3 = {
import scala.reflect.ClassTag
def swap[T: ClassTag](arr: Array[T]): Array[T] = arr match {
case Array(a, b) => Array(b, a)
// immutable, slow
// case Array(a, b, rest @ _*) => Array(b, a) ++ rest
// mutable, fast
case Array(a, b, _*) => arr(0) = b; arr(1) = a; arr
}
// test
assert( List(1,2,3) == swap(Array(2,1,3)).toList )
}
// 4. Add a case class 'Multiple' that is a subclass of the 'Item' class.
// For example,
// Multiple(10, Article("Blackwell Toaster", 29.95))
// describes ten toasters. Of course, you should be able to handle any items,
// such as bundles or multiples, in the second argument.
// Extend the price function to handle this new case.
def ex4 = {
sealed abstract class Item
case class Article(descr: String, price: Double) extends Item
case class Bundle(descr: String, discount: Double, items: Item*) extends Item
case class Multiple(quantity: Int, item: Item) extends Item
def price(itm: Item): Double = itm match {
case Article(_, p) => p
case Bundle(_, disc, items @ _*) => items.map(price).sum - disc
case Multiple(q, item) => q * price(item)
}
// test
assert(price(Multiple(10, Article("Blackwell Toaster", 29.95))) == 299.5)
}
// 5. One can use lists to model trees that store values only in the leaves.
// For example, the list ((3 8) 2 (5)) describes the tree
// •
// / | \\
// • 2 •
// /\\ |
// 3 8 5
// However, some of the list elements are numbers and others are lists.
// In Scala, you cannot have heterogeneous lists, so you have to use a List[Any].
// Write a leafSum function to compute the sum of all elements in the leaves,
// using pattern matching to differentiate between numbers and lists.
def ex5 = {
def leafSum(lst: List[Any]): Int = lst match {
case Nil => 0
case h :: t => h match {
case a: Int => leafSum(t) + a
case b: List[Any] => leafSum(b) + leafSum(t)
case _ => leafSum(t)
}
}
def leafSum2(lst: List[_]): Int = lst.map( {
case a: Int => a
case b: List[_] => leafSum2(b)
case _ => 0
} ).sum
def leafSum3(lst: Seq[_]): Int = lst match {
case Seq(x: Int, rest @ _*) => x + leafSum3(rest)
case Seq(xs: Seq[_], rest @ _*) => leafSum3(xs) + leafSum3(rest)
case _ => 0
}
// test
val lst = List( List(3, 8), 2, List(5) )
val res = leafSum(lst); println(s"result: $res")
assert(res == 18 && res == leafSum2(lst) && res == leafSum3(lst))
assert(leafSum(List(42)) + leafSum2(List(42)) + leafSum3(List(42)) == 126)
}
// 6. A better way of modeling such trees is with case classes.
// Let’s start with binary trees.
// sealed abstract class BinaryTree
// case class Leaf(value: Int) extends BinaryTree
// case class Node(left: BinaryTree, right: BinaryTree) extends BinaryTree
// Write a function to compute the sum of all elements in the leaves.
def ex6 = {
sealed abstract class BinaryTree
case class Leaf(value: Int) extends BinaryTree
case class Node(left: BinaryTree, right: BinaryTree) extends BinaryTree
def leafSum(tree: BinaryTree): Int = tree match {
case Leaf(x) => x
case Node(a, b) => leafSum(a) + leafSum(b)
}
// test
val tree = Node(Leaf(1), Node(Node(Leaf(2), Leaf(3)), Node(Leaf(4), Leaf(5))))
val res = leafSum(tree)
assert(res == 15)
}
// 7. Extend the tree in the preceding exercise so that
// each node can have an arbitrary number of children, and reimplement the leafSum function.
// The tree in Exercise 5 should be expressible as
// Node(Node(Leaf(3), Leaf(8)), Leaf(2), Node(Leaf(5)))
def ex7 = {
sealed abstract class BinaryTree
case class Leaf(value: Int) extends BinaryTree
case class Node(children: BinaryTree*) extends BinaryTree
def leafSum(tree: BinaryTree): Int = tree match {
case Leaf(x) => x
case Node(xs @ _*) => xs.map(leafSum).sum
}
// test
val tree = Node( Node(Leaf(3), Leaf(8)), Leaf(2), Node(Leaf(5)) )
val res = leafSum(tree)
assert(res == 18)
}
// 8. Extend the tree in the preceding exercise so that each nonleaf node stores an operator in
// addition to the child nodes.
// Then write a function 'eval' that computes the value.
// For example, the tree
// +
// / | \\
// * 2 -
// /\\ |
// 3 8 5
// has value (3 × 8) + 2 + (–5) = 21
// Pay attention to the unary minus
def ex8 = {
sealed abstract class BinaryTree
case class Leaf(value: Int) extends BinaryTree
case class Node(op: Char, children: BinaryTree*) extends BinaryTree
def eval(tree: BinaryTree): Int = tree match {
case Leaf(x) => x
case Node('+', xs @ _*) => xs.map(eval).sum
case Node('*', xs @ _*) => xs.map(eval).product
case Node('-', one) => -eval(one)
case Node('-', xs @ _*) => xs.map(eval).reduceLeft(_ - _)
case Node(op, _) => throw new IllegalArgumentException(s"unknown operation: $op")
}
// test
val tree = Node('+',
Node('*', Leaf(3), Leaf(8)),
Leaf(2),
Node('-', Leaf(5)),
Node('-', Leaf(1), Leaf(9)))
// (3 × 8) + 2 + (0 – 5) + (1 - 9) = 13
val res = eval(tree)
println(s"eval: $res")
assert(res == 13)
}
// 9. Write a function that computes the sum of the non-None values in a List[Option[Int]]
// Don’t use a match statement.
def ex9 = {
def sum(lst: List[Option[Int]]): Int = (for (Some(x) <- lst) yield x).sum
//test
val lst = Seq(
Some(1), None, Some(3), None, Some(-4)
)
assert(sum(lst.toList) == 0)
}
// 10. Write a function that composes two functions of type
// Double => Option[Double]
// yielding another function of the same type.
// The composition should yield None if either function does.
// For example,
// def f(x: Double) = if (x != 1) Some(1 / (x - 1)) else None
// def g(x: Double) = if (x >= 0) Some(sqrt(x)) else None
// val h = compose(g, f) // h(x) should be g(f(x))
// Then h(2) is Some(1), and h(1) and h(0) are None.
def ex10 = {
import scala.math.sqrt
def compose(
g: Double => Option[Double],
f: Double => Option[Double]
)(x: Double): Option[Double] = {
// f(x).flatMap(g)
for (y <- f(x); z <- g(y)) yield z
}
def f(x: Double): Option[Double] = if (x != 1) Some(1 / (x - 1)) else None
def g(x: Double): Option[Double] = if (x >= 0) Some(sqrt(x)) else None
val h: Double => Option[Double] = compose(g, f) // h(x) should be g(f(x))
// test
assert(h(2).contains(1))
assert(h(1).isEmpty && h(0).isEmpty)
}
}
| vasnake/scala-for-the-impatient | src/main/scala/Chapter14/PatternMatchingAndCaseClasses.scala | Scala | gpl-3.0 | 28,251 |
package io.swagger.client.api
import io.swagger.client.model.OutputFile
import io.swagger.client.model.Error
import io.swagger.client.ApiInvoker
import io.swagger.client.ApiException
import com.sun.jersey.multipart.FormDataMultiPart
import com.sun.jersey.multipart.file.FileDataBodyPart
import javax.ws.rs.core.MediaType
import java.io.File
import java.util.Date
import scala.collection.mutable.HashMap
class OutputApi(val defBasePath: String = "http://api2.online-convert.com/",
defApiInvoker: ApiInvoker = ApiInvoker) {
var basePath = defBasePath
var apiInvoker = defApiInvoker
def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value
/**
* Get list of converted.
*
* @param conversionId
* @param inputId
* @param xOcToken Token for authentication for the current job
* @param xOcApiKey Api key for the user to filter.
* @param jobId ID of job that needs to be fetched
* @return List[OutputFile]
*/
def jobsJobIdOutputGet (conversionId: String, inputId: String, xOcToken: String, xOcApiKey: String, jobId: String) : Option[List[OutputFile]] = {
// create path and map variables
val path = "/jobs/{job_id}/output".replaceAll("\\\\{format\\\\}","json").replaceAll("\\\\{" + "job_id" + "\\\\}",apiInvoker.escape(jobId))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
if(String.valueOf(conversionId) != "null") queryParams += "conversion_id" -> conversionId.toString
if(String.valueOf(inputId) != "null") queryParams += "input_id" -> inputId.toString
headerParams += "X-Oc-Token" -> xOcToken
headerParams += "X-Oc-Api-Key" -> xOcApiKey
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "array", classOf[OutputFile]).asInstanceOf[List[OutputFile]])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Get information about an output file source.
*
* @param xOcToken Token for authentication for the current job
* @param xOcApiKey Api key for the user to filter.
* @param jobId ID of job that needs to be fetched
* @param fileId Id of the file to download
* @return List[OutputFile]
*/
def jobsJobIdOutputFileIdGet (xOcToken: String, xOcApiKey: String, jobId: String, fileId: String) : Option[List[OutputFile]] = {
// create path and map variables
val path = "/jobs/{job_id}/output/{file_id}".replaceAll("\\\\{format\\\\}","json").replaceAll("\\\\{" + "job_id" + "\\\\}",apiInvoker.escape(jobId))
.replaceAll("\\\\{" + "file_id" + "\\\\}",apiInvoker.escape(fileId))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
headerParams += "X-Oc-Token" -> xOcToken
headerParams += "X-Oc-Api-Key" -> xOcApiKey
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "array", classOf[OutputFile]).asInstanceOf[List[OutputFile]])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
/**
* Deletes a file from the output.
*
* @param xOcToken Token for authentication for the current job
* @param xOcApiKey Api key for the user to filter.
* @param jobId ID of job that needs to be fetched
* @param fileId Id of the file to download
* @return List[OutputFile]
*/
def jobsJobIdOutputFileIdDelete (xOcToken: String, xOcApiKey: String, jobId: String, fileId: String) : Option[List[OutputFile]] = {
// create path and map variables
val path = "/jobs/{job_id}/output/{file_id}".replaceAll("\\\\{format\\\\}","json").replaceAll("\\\\{" + "job_id" + "\\\\}",apiInvoker.escape(jobId))
.replaceAll("\\\\{" + "file_id" + "\\\\}",apiInvoker.escape(fileId))
val contentTypes = List("application/json")
val contentType = contentTypes(0)
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
val formParams = new HashMap[String, String]
headerParams += "X-Oc-Token" -> xOcToken
headerParams += "X-Oc-Api-Key" -> xOcApiKey
var postBody: AnyRef = null
if(contentType.startsWith("multipart/form-data")) {
val mp = new FormDataMultiPart()
postBody = mp
}
else {
}
try {
apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "array", classOf[OutputFile]).asInstanceOf[List[OutputFile]])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
}
| onlineconvert/onlineconvert-api-sdk-scala | src/main/scala/io/swagger/client/api/OutputApi.scala | Scala | apache-2.0 | 5,928 |
class Child1 extends Overriders {
override def foo(i: Int) = i + 1
foo(42)
} | ilinum/intellij-scala | testdata/changeSignature/fromJava/Overriders.scala | Scala | apache-2.0 | 81 |
package com.amarjanica.discourse.util
trait Imports {
/*Common imports*/
type JsonIgnoreProperties = com.fasterxml.jackson.annotation.JsonIgnoreProperties
type JsonProperty = com.fasterxml.jackson.annotation.JsonProperty
}
| amarjanica/discourse-scala-client | src/main/scala/com/amarjanica/discourse/util/Imports.scala | Scala | mit | 230 |
/*
* Licensed to STRATIO (C) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. The STRATIO (C) 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 com.stratio.crossdata.driver.querybuilder
/**
* Select query builder.
*/
class Select extends Query {
/**
* The selected columns.
*/
var selection : Option[Selection] = None
/**
* The target table in the from clause.
*/
var from : Option[String] = None
/**
* The join clause.
*/
var join : Option[Join] = None
/**
* The where clause.
*/
var where : Option[Where] = None
/**
* The window clause.
*/
var window : Option[String] = None
/**
* The group by clause.
*/
var groupBy : Option[String] = None
/**
* The order by clause.
*/
var orderBy : Option[String] = None
/**
* The limit clause.
*/
var limit : Option[Long] = None
/**
* Class constructor.
* @param columnName The name of the column to be selected.
*/
def this(columnName : String){
this()
selection = Option(new Selection(List(columnName)))
}
/**
* Class constructor.
* @param columnNames A sequence of string column names.
*/
def this(columnNames : Seq[String]){
this()
selection = Option(new Selection(columnNames.toList))
}
/**
* Class constructor.
* @param selectedColumns The Selection with the required columns.
*/
def this(selectedColumns : Selection){
this()
selection = Option(selectedColumns)
}
/**
* Add a from clause to the current query.
* @param tableName The target table name.
* @return The current Select object.
*/
def from(tableName : String) : Select = {
from = Option(tableName)
this
}
/**
* Add a join clause to the current query.
* @param tableName The target table to perform the join.
* @return A default Join.
*/
def join(tableName : String) : Join = {
innerJoin(tableName)
}
/**
* Add an inner join clause to the current query.
* @param tableName The target table to perform the join.
* @return An inner Join
*/
def innerJoin(tableName: String) : Join = {
join = Option(new Join(tableName, "INNER", this))
join.get
}
/**
* Add a window clause to the current query.
* @param window The window.
* @return The current Select object.
*/
def withWindow(window: String) : Select = {
this.window = Option(window)
this
}
/**
* Add a where clause to the current query.
* @param clause The where clause.
* @return A Where object.
*/
def where(clause : String) : Where = {
where = Option(new Where(clause, this))
where.get
}
/**
* Add a group by clause to the current query.
* @param clause The group by clause.
* @return The current Select object.
*/
def groupBy(clause : String) : Select = {
groupBy = Option(clause)
this
}
/**
* Add an order by clause to the current query.
* @param clause The order by clause.
* @return The current Select object.
*/
def orderBy(clause : String) : Select = {
orderBy = Option(clause)
this
}
/**
* Add a limit clause to the current query.
* @param queryLimit The limit.
* @return The current Select object.
*/
def limit(queryLimit : Long) : Select = {
limit = Option(queryLimit)
this
}
override def toString() : String = {
val sb : StringBuilder = new StringBuilder("SELECT ");
if(selection.nonEmpty){
sb.append(selection.get.asString)
}
if(from.nonEmpty){
sb.append(" FROM ").append(from.get)
}
if(window.nonEmpty){
sb.append(" WITH WINDOW ").append(window.get)
}
if(join.nonEmpty){
sb.append(join.get.asString)
}
if(where.nonEmpty){
sb.append(" WHERE ").append(where.get.asString)
}
if(orderBy.nonEmpty){
sb.append(" ORDER BY ").append(orderBy.get)
}
if(groupBy.nonEmpty){
sb.append(" GROUP BY ").append(groupBy.get)
}
if(limit.nonEmpty){
sb.append(" LIMIT ").append(limit.get)
}
sb append ";"
sb mkString
}
}
| ccaballe/crossdata | crossdata-driver/src/main/scala/com/stratio/crossdata/driver/querybuilder/Select.scala | Scala | apache-2.0 | 4,733 |
package org.jetbrains.plugins.scala.codeInspection.methodSignature
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.testFramework.EditorTestUtil
import com.intellij.testFramework.fixtures.CodeInsightTestFixture
import org.jetbrains.plugins.scala.codeInspection.{ScalaInspectionBundle, ScalaQuickFixTestBase}
class ApparentResultTypeRefinementInspectionTest extends ScalaQuickFixTestBase {
import CodeInsightTestFixture.{CARET_MARKER => CARET}
protected override val classOfInspection: Class[_ <: LocalInspectionTool] =
classOf[ApparentResultTypeRefinementInspection]
protected override val description: String =
ScalaInspectionBundle.message("method.signature.result.type.refinement")
private val hint = ScalaInspectionBundle.message("insert.missing.assignment")
def test(): Unit = {
checkTextHasError(
text =
s"""
|trait T {
| def test(): ${START}T {}$END
|}
""".stripMargin
)
testQuickFix(
text =
s"""
|trait T {
| def test(): T$CARET {}
|}
""".stripMargin,
expected =
s"""
|trait T {
| def test(): T = {}
|}
""".stripMargin,
hint
)
}
def test_ok(): Unit = {
checkTextHasNoErrors(
text =
s"""
|trait T {
| def test(): T = {}
|}
""".stripMargin
)
}
} | JetBrains/intellij-scala | scala/scala-impl/test/org/jetbrains/plugins/scala/codeInspection/methodSignature/ApparentResultTypeRefinementInspectionTest.scala | Scala | apache-2.0 | 1,469 |
package org.jetbrains.plugins.scala
package lang
package completeStatement
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.actionSystem.IdeActions.ACTION_EDITOR_COMPLETE_STATEMENT
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.psi.statistics.StatisticsManager
import com.intellij.psi.statistics.impl.StatisticsManagerImpl
import com.intellij.testFramework.EditorTestUtil
import org.jetbrains.plugins.scala.base.ScalaLightCodeInsightFixtureTestAdapter
/**
* User: Dmitry.Naydanov
* Date: 27.07.15.
*/
abstract class ScalaCompleteStatementTestBase extends ScalaLightCodeInsightFixtureTestAdapter {
import ScalaLightCodeInsightFixtureTestAdapter._
protected val fileType: LanguageFileType = ScalaFileType.INSTANCE
protected override def setUp(): Unit = {
super.setUp()
StatisticsManager.getInstance match {
case impl: StatisticsManagerImpl => impl.enableStatistics(getTestRootDisposable)
}
//We should change this setting in order to be sure EnterProcessor works without 'swap-settings-hack'
//it was in org.jetbrains.plugins.scala.editor.smartEnter.ScalaSmartEnterProcessor#moveCaretInsideBracesIfAny
getCommonSettings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = true
}
override def tearDown(): Unit = {
getCommonSettings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = false
super.tearDown()
}
def doCompletionTest(fileText: String, resultText: String): Unit = {
val fixture = getFixture
fixture.configureByText(fileType, normalize(fileText))
fixture.performEditorAction(ACTION_EDITOR_COMPLETE_STATEMENT)
fixture.checkResult(normalize(resultText), /*stripTrailingSpaces = */ true)
}
}
class JavaCompleteStatementTest extends ScalaCompleteStatementTestBase {
import EditorTestUtil.{CARET_TAG => CARET}
override protected val fileType: LanguageFileType = JavaFileType.INSTANCE
def testFormatJava(): Unit = doCompletionTest(
fileText =
s"""
|class B {
| int d=7+7+7+77;$CARET
|}
""".stripMargin,
resultText =
s"""
|class B {
| int d = 7 + 7 + 7 + 77;$CARET
|}
""".stripMargin
)
def testIfConditionJava(): Unit = doCompletionTest( //WHAT THE _?!
fileText =
s"""
|class B {
| public static void main(String[] args) {
| if $CARET
| }
|}
""".stripMargin,
resultText =
s"""
|class B {
| public static void main(String[] args) {
| if ($CARET) {
| }
| }
|}
""".stripMargin
)
def testIfCondition2Java(): Unit = doCompletionTest(
fileText =
s"""
|class B {
| public static void main(String[] args) {
| if ()$CARET
| }
|}
""".stripMargin,
resultText =
s"""
|class B {
| public static void main(String[] args) {
| if ($CARET) {
| }
| }
|}
""".stripMargin
)
}
| JetBrains/intellij-scala | scala/scala-impl/test/org/jetbrains/plugins/scala/lang/completeStatement/ScalaCompleteStatementTestBase.scala | Scala | apache-2.0 | 3,104 |
package vexatos.cheatycomputers
import li.cil.oc.Constants.{BlockName, ItemName}
import li.cil.oc.api
import li.cil.oc.api.detail.ItemInfo
import li.cil.oc.common.InventorySlots.InventorySlot
import li.cil.oc.common.tileentity.traits.Rotatable
import li.cil.oc.common.{InventorySlots, Slot, Tier}
import li.cil.oc.util.{BlockPosition, InventoryUtils}
import net.minecraft.entity.Entity
import net.minecraft.item.ItemStack
import net.minecraft.nbt.{NBTTagCompound, NBTTagList, NBTTagString}
import net.minecraftforge.common.util.ForgeDirection
/**
* @author Vexatos
*/
object ScalaProxy {
//private implicit def toItemStack(s: String): Option[ItemStack] = Option(api.Items.get(s)).map(_.createItemStack(1))
private implicit def toItemStack(s: String): (Int => Option[String]) = index => Option(s)
private implicit def to2(s: String): Option[String] = Option(s)
//private implicit def toSimpleFunction(s: String): (Int => Option[ItemStack]) = index => s
def createRecipes() = {
addPackageRecipe(createPackage(Tier.One, {
case Slot.CPU => ItemName.CPUTier1
case Slot.HDD => ItemName.HDDTier1
case Slot.EEPROM => ItemName.LuaBios
case Slot.Memory => ItemName.RAMTier2
case Slot.Card => {
case 0 => ItemName.GraphicsCardTier1
case 1 => ItemName.RedstoneCardTier1
case 2 => ItemName.NetworkCard
case _ => ""
}
case _ => ""
}
), "stone")
addPackageRecipe(createPackage(Tier.Two, {
case Slot.CPU => ItemName.APUTier1
case Slot.HDD => ItemName.HDDTier2
case Slot.EEPROM => ItemName.LuaBios
case Slot.Memory => ItemName.RAMTier4
case Slot.Card => {
case 0 => ItemName.RedstoneCardTier2
case 1 => ItemName.NetworkCard
case _ => ""
}
case _ => ""
}
), "ingotIron")
addPackageRecipe(createPackage(Tier.Three, {
case Slot.CPU => ItemName.CPUTier3
case Slot.HDD => ItemName.HDDTier3
case Slot.EEPROM => ItemName.LuaBios
case Slot.Memory => ItemName.RAMTier6
case Slot.Floppy => ItemName.OpenOS
case Slot.Card => {
case 0 => ItemName.GraphicsCardTier3
case 1 => ItemName.RedstoneCardTier2
case 2 => ItemName.NetworkCard
case _ => ""
}
case _ => ""
}
), "ingotGold")
}
def addPackageRecipe(result: ItemStack, other: AnyRef) = {
CheatyComputers.addPackageRecipe(result, other)
}
def countSlots(s: Array[InventorySlot], slot: String): Int = s.count(otherslot => otherslot.slot.equals(slot))
def getCase(tier: Int): ItemInfo = api.Items.get(BlockName.Case(tier))
def setFacing(rotatable: Rotatable, entity: Entity) = {
rotatable.setFromEntityPitchAndYaw(entity)
if (!rotatable.validFacings.contains(rotatable.pitch)) {
rotatable.pitch = rotatable.validFacings.headOption.getOrElse(ForgeDirection.NORTH)
}
rotatable.invertRotation()
}
def insertIntoInventoryAt(stack: ItemStack, pos: BlockPosition) = InventoryUtils.insertIntoInventoryAt(stack, pos)
//def registerRecipes() = recipes.foreach(GameRegistry.addRecipe(_))
def createPackage(tier: Int, f: (String => (Int => Option[String]))): ItemStack = {
val stack = new ItemStack(CheatyComputers.item, 1, 0)
val tag = new NBTTagCompound
tag.setInteger("t", tier)
val slots = InventorySlots.computer(tier)
slots.groupBy(_.slot).keys.foreach {
slot => f(slot) match {
case g if g != null =>
val list = new NBTTagList()
for (index <- 0 until countSlots(slots, slot)) {
g(index) match {
case Some(content) =>
//list.appendTag(content.writeToNBT(new NBTTagCompound))
list.appendTag(new NBTTagString(content))
case _ => // NO-OP
}
}
tag.setTag(slot, list)
case _ => // NO-OP
}
}
stack.setTagCompound(tag)
stack
}
}
| Vexatos/CheatyComputers | src/main/scala/vexatos/cheatycomputers/ScalaProxy.scala | Scala | mit | 3,957 |
/*
* Copyright 2015 Sanford Ryza, Uri Laserson, Sean Owen and Joshua Wills
*
* See LICENSE file for further information.
*/
package com.cloudera.datascience.risk
import java.io.File
import java.text.SimpleDateFormat
import scala.collection.mutable.ArrayBuffer
import scala.io.Source
import breeze.plot._
import com.github.nscala_time.time.Imports._
import org.apache.commons.math3.distribution.ChiSquaredDistribution
import org.apache.commons.math3.distribution.MultivariateNormalDistribution
import org.apache.commons.math3.random.MersenneTwister
import org.apache.commons.math3.stat.correlation.Covariance
import org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.SparkContext._
import org.apache.spark.rdd.RDD
object RunRisk {
def main(args: Array[String]): Unit = {
val sc = new SparkContext(new SparkConf().setAppName("VaR"))
val (stocksReturns, factorsReturns) = readStocksAndFactors("./")
plotDistribution(factorsReturns(2))
plotDistribution(factorsReturns(3))
val numTrials = 10000000
val parallelism = 1000
val baseSeed = 1001L
val trials = computeTrialReturns(stocksReturns, factorsReturns, sc, baseSeed, numTrials,
parallelism)
trials.cache()
val valueAtRisk = fivePercentVaR(trials)
val conditionalValueAtRisk = fivePercentCVaR(trials)
println("VaR 5%: " + valueAtRisk)
println("CVaR 5%: " + conditionalValueAtRisk)
val varConfidenceInterval = bootstrappedConfidenceInterval(trials, fivePercentVaR, 100, .05)
val cvarConfidenceInterval = bootstrappedConfidenceInterval(trials, fivePercentCVaR, 100, .05)
println("VaR confidence interval: " + varConfidenceInterval)
println("CVaR confidence interval: " + cvarConfidenceInterval)
println("Kupiec test p-value: " + kupiecTestPValue(stocksReturns, valueAtRisk, 0.05))
plotDistribution(trials)
}
def computeTrialReturns(
stocksReturns: Seq[Array[Double]],
factorsReturns: Seq[Array[Double]],
sc: SparkContext,
baseSeed: Long,
numTrials: Int,
parallelism: Int): RDD[Double] = {
val factorMat = factorMatrix(factorsReturns)
val factorCov = new Covariance(factorMat).getCovarianceMatrix().getData()
val factorMeans = factorsReturns.map(factor => factor.sum / factor.size).toArray
val factorFeatures = factorMat.map(featurize)
val factorWeights = computeFactorWeights(stocksReturns, factorFeatures)
val bInstruments = sc.broadcast(factorWeights)
// Generate different seeds so that our simulations don't all end up with the same results
val seeds = (baseSeed until baseSeed + parallelism)
val seedRdd = sc.parallelize(seeds, parallelism)
// Main computation: run simulations and compute aggregate return for each
seedRdd.flatMap(
trialReturns(_, numTrials / parallelism, bInstruments.value, factorMeans, factorCov))
}
def computeFactorWeights(
stocksReturns: Seq[Array[Double]],
factorFeatures: Array[Array[Double]]): Array[Array[Double]] = {
val models = stocksReturns.map(linearModel(_, factorFeatures))
val factorWeights = Array.ofDim[Double](stocksReturns.length, factorFeatures.head.length+1)
for (s <- 0 until stocksReturns.length) {
factorWeights(s) = models(s).estimateRegressionParameters()
}
factorWeights
}
def featurize(factorReturns: Array[Double]): Array[Double] = {
val squaredReturns = factorReturns.map(x => math.signum(x) * x * x)
val squareRootedReturns = factorReturns.map(x => math.signum(x) * math.sqrt(math.abs(x)))
squaredReturns ++ squareRootedReturns ++ factorReturns
}
def readStocksAndFactors(prefix: String): (Seq[Array[Double]], Seq[Array[Double]]) = {
val start = new DateTime(2009, 10, 23, 0, 0)
val end = new DateTime(2014, 10, 23, 0, 0)
val rawStocks = readHistories(new File(prefix + "data/stocks/")).filter(_.size >= 260*5+10)
val stocks = rawStocks.map(trimToRegion(_, start, end)).map(fillInHistory(_, start, end))
val factorsPrefix = prefix + "data/factors/"
val factors1 = Array("crudeoil.tsv", "us30yeartreasurybonds.tsv").
map(x => new File(factorsPrefix + x)).
map(readInvestingDotComHistory)
val factors2 = Array("^GSPC.csv", "^IXIC.csv").
map(x => new File(factorsPrefix + x)).
map(readYahooHistory)
val factors = (factors1 ++ factors2).
map(trimToRegion(_, start, end)).
map(fillInHistory(_, start, end))
val stockReturns = stocks.map(twoWeekReturns)
val factorReturns = factors.map(twoWeekReturns)
(stockReturns, factorReturns)
}
def trialReturns(
seed: Long,
numTrials: Int,
instruments: Seq[Array[Double]],
factorMeans: Array[Double],
factorCovariances: Array[Array[Double]]): Seq[Double] = {
val rand = new MersenneTwister(seed)
val multivariateNormal = new MultivariateNormalDistribution(rand, factorMeans,
factorCovariances)
val trialReturns = new Array[Double](numTrials)
for (i <- 0 until numTrials) {
val trialFactorReturns = multivariateNormal.sample()
val trialFeatures = RunRisk.featurize(trialFactorReturns)
trialReturns(i) = trialReturn(trialFeatures, instruments)
}
trialReturns
}
/**
* Calculate the full return of the portfolio under particular trial conditions.
*/
def trialReturn(trial: Array[Double], instruments: Seq[Array[Double]]): Double = {
var totalReturn = 0.0
for (instrument <- instruments) {
totalReturn += instrumentTrialReturn(instrument, trial)
}
totalReturn / instruments.size
}
/**
* Calculate the return of a particular instrument under particular trial conditions.
*/
def instrumentTrialReturn(instrument: Array[Double], trial: Array[Double]): Double = {
var instrumentTrialReturn = instrument(0)
var i = 0
while (i < trial.length) {
instrumentTrialReturn += trial(i) * instrument(i+1)
i += 1
}
instrumentTrialReturn
}
def twoWeekReturns(history: Array[(DateTime, Double)]): Array[Double] = {
history.sliding(10).map { window =>
val next = window.last._2
val prev = window.head._2
(next - prev) / prev
}.toArray
}
def linearModel(instrument: Array[Double], factorMatrix: Array[Array[Double]])
: OLSMultipleLinearRegression = {
val regression = new OLSMultipleLinearRegression()
regression.newSampleData(instrument, factorMatrix)
regression
}
def factorMatrix(histories: Seq[Array[Double]]): Array[Array[Double]] = {
val mat = new Array[Array[Double]](histories.head.length)
for (i <- 0 until histories.head.length) {
mat(i) = histories.map(_(i)).toArray
}
mat
}
def readHistories(dir: File): Seq[Array[(DateTime, Double)]] = {
val files = dir.listFiles()
files.flatMap(file => {
try {
Some(readYahooHistory(file))
} catch {
case e: Exception => None
}
})
}
def trimToRegion(history: Array[(DateTime, Double)], start: DateTime, end: DateTime)
: Array[(DateTime, Double)] = {
var trimmed = history.dropWhile(_._1 < start).takeWhile(_._1 <= end)
if (trimmed.head._1 != start) {
trimmed = Array((start, trimmed.head._2)) ++ trimmed
}
if (trimmed.last._1 != end) {
trimmed = trimmed ++ Array((end, trimmed.last._2))
}
trimmed
}
/**
* Given a timeseries of values of an instruments, returns a timeseries between the given
* start and end dates with all missing weekdays imputed. Values are imputed as the value on the
* most recent previous given day.
*/
def fillInHistory(history: Array[(DateTime, Double)], start: DateTime, end: DateTime)
: Array[(DateTime, Double)] = {
var cur = history
val filled = new ArrayBuffer[(DateTime, Double)]()
var curDate = start
while (curDate < end) {
if (cur.tail.nonEmpty && cur.tail.head._1 == curDate) {
cur = cur.tail
}
filled += ((curDate, cur.head._2))
curDate += 1.days
// Skip weekends
if (curDate.dayOfWeek().get > 5) curDate += 2.days
}
filled.toArray
}
def readInvestingDotComHistory(file: File): Array[(DateTime, Double)] = {
val format = new SimpleDateFormat("MMM d, yyyy")
val lines = Source.fromFile(file).getLines().toSeq
lines.map(line => {
val cols = line.split('\\t')
val date = new DateTime(format.parse(cols(0)))
val value = cols(1).toDouble
(date, value)
}).reverse.toArray
}
/**
* Reads a history in the Yahoo format
*/
def readYahooHistory(file: File): Array[(DateTime, Double)] = {
val format = new SimpleDateFormat("yyyy-MM-dd")
val lines = Source.fromFile(file).getLines().toSeq
lines.tail.map(line => {
val cols = line.split(',')
val date = new DateTime(format.parse(cols(0)))
val value = cols(1).toDouble
(date, value)
}).reverse.toArray
}
def plotDistribution(samples: Array[Double]): Figure = {
val min = samples.min
val max = samples.max
// Using toList before toArray avoids a Scala bug
val domain = Range.Double(min, max, (max - min) / 100).toList.toArray
val densities = KernelDensity.estimate(samples, domain)
val f = Figure()
val p = f.subplot(0)
p += plot(domain, densities)
p.xlabel = "Two Week Return ($)"
p.ylabel = "Density"
f
}
def plotDistribution(samples: RDD[Double]): Figure = {
val stats = samples.stats()
val min = stats.min
val max = stats.max
// Using toList before toArray avoids a Scala bug
val domain = Range.Double(min, max, (max - min) / 100).toList.toArray
val densities = KernelDensity.estimate(samples, domain)
val f = Figure()
val p = f.subplot(0)
p += plot(domain, densities)
p.xlabel = "Two Week Return ($)"
p.ylabel = "Density"
f
}
def fivePercentVaR(trials: RDD[Double]): Double = {
val topLosses = trials.takeOrdered(math.max(trials.count().toInt / 20, 1))
topLosses.last
}
def fivePercentCVaR(trials: RDD[Double]): Double = {
val topLosses = trials.takeOrdered(math.max(trials.count().toInt / 20, 1))
topLosses.sum / topLosses.length
}
def bootstrappedConfidenceInterval(
trials: RDD[Double],
computeStatistic: RDD[Double] => Double,
numResamples: Int,
pValue: Double): (Double, Double) = {
val stats = (0 until numResamples).map { i =>
val resample = trials.sample(true, 1.0)
computeStatistic(resample)
}.sorted
val lowerIndex = (numResamples * pValue / 2 - 1).toInt
val upperIndex = math.ceil(numResamples * (1 - pValue / 2)).toInt
(stats(lowerIndex), stats(upperIndex))
}
def countFailures(stocksReturns: Seq[Array[Double]], valueAtRisk: Double): Int = {
var failures = 0
for (i <- 0 until stocksReturns(0).size) {
val loss = stocksReturns.map(_(i)).sum
if (loss < valueAtRisk) {
failures += 1
}
}
failures
}
def kupiecTestStatistic(total: Int, failures: Int, confidenceLevel: Double): Double = {
val failureRatio = failures.toDouble / total
val logNumer = (total - failures) * math.log1p(-confidenceLevel) +
failures * math.log(confidenceLevel)
val logDenom = (total - failures) * math.log1p(-failureRatio) +
failures * math.log(failureRatio)
-2 * (logNumer - logDenom)
}
def kupiecTestPValue(
stocksReturns: Seq[Array[Double]],
valueAtRisk: Double,
confidenceLevel: Double): Double = {
val failures = countFailures(stocksReturns, valueAtRisk)
val total = stocksReturns(0).size
val testStatistic = kupiecTestStatistic(total, failures, confidenceLevel)
1 - new ChiSquaredDistribution(1.0).cumulativeProbability(testStatistic)
}
}
| accavdar/aas | ch09-risk/src/main/scala/com/cloudera/datascience/risk/RunRisk.scala | Scala | apache-2.0 | 11,829 |
package colang.ast.raw
import colang.Strategy.Result
import colang.Strategy.Result.{Malformed, NoMatch, Success}
import colang.ast.raw.ParserImpl.{Absent, Invalid, Present, SingleTokenStrategy}
import colang.issues.Terms
import colang.tokens.{Comma, Identifier, LeftParen, RightParen}
import colang.{SourceCode, TokenStream}
/**
* Represents a function parameter.
* @param type_ parameter type
* @param name parameter name
*/
case class FunctionParameter(type_ : Type, name: Identifier) extends Node {
def source: SourceCode = type_.source + name.source
}
object FunctionParameter {
val strategy = new ParserImpl.Strategy[FunctionParameter] {
def apply(stream: TokenStream): Result[TokenStream, FunctionParameter] = {
ParserImpl.parseGroup()
.definingElement(Type.strategy)
.element(SingleTokenStrategy(classOf[Identifier]), Terms.Name of Terms.Parameter)
.parse(stream)
.as[Type, Identifier] match {
case (Present(type_), Present(name), issues, streamAfterParam) =>
Success(FunctionParameter(type_, name), issues, streamAfterParam)
case (Present(_) | Invalid(), Invalid() | Absent(), issues, streamAfterParam) =>
Malformed(issues, streamAfterParam)
case _ => NoMatch()
}
}
}
}
/**
* Represents a function parameter list.
* @param leftParen opening parentheses
* @param params function parameters
* @param rightParen closing parentheses
*/
case class ParameterList(leftParen: LeftParen, params: Seq[FunctionParameter], rightParen: RightParen) extends Node {
def source: SourceCode = leftParen.source + rightParen.source
}
object ParameterList {
val strategy = new ParserImpl.Strategy[ParameterList] {
def apply(stream: TokenStream): Result[TokenStream, ParameterList] = {
ParserImpl.parseEnclosedSequence(
stream = stream,
sequenceDescription = Terms.List of Terms.Parameters,
elementStrategy = FunctionParameter.strategy,
elementDescription = Terms.Definition of Terms.Parameter,
openingElement = classOf[LeftParen],
closingElement = classOf[RightParen],
closingElementDescription = Terms.ClosingParen,
mandatorySeparator = Some(classOf[Comma]),
separatorDescription = Some(Terms.Comma)
) match {
case Some((leftParen, params, rightParenOption, issues, streamAfterParams)) =>
val rightParen = rightParenOption match {
case Some(rp) => rp
case None =>
val previousSource = if (params.nonEmpty) params.last.source else leftParen.source
RightParen(previousSource.after)
}
Success(ParameterList(leftParen, params, rightParen), issues, streamAfterParams)
case _ => NoMatch()
}
}
}
}
| merkispavel/colang | src/main/scala/colang/ast/raw/ParameterList.scala | Scala | mit | 2,810 |
package shorty
import org.easymock.EasyMock._
import org.easymock.EasyMock
import javax.servlet.http._
class TestMethodParser extends BaseTest {
describe("MethodParser") {
it ("should be properly parse") {
testParsing("POST",POST)
testParsing("GET",GET)
testParsing("PUT",PUT)
testParsing("DELETE",DELETE)
}
it ("should be case insensitive") {
val request = createMock(classOf[HttpServletRequest])
val parser = new AnyRef with MethodParser
EasyMock.expect(request.getMethod()).andReturn("POST")
EasyMock.expect(request.getHeader(parser.METHOD_HEADER)).andReturn(null)
EasyMock.expect(request.getParameter(parser.METHOD_PARAM)).andReturn(null)
replay(request)
val method = parser.determineMethod(request)
method should equal (POST)
}
it ("should be favor the header over the method") {
val request = createMock(classOf[HttpServletRequest])
val parser = new AnyRef with MethodParser
EasyMock.expect(request.getMethod()).andReturn("POST")
EasyMock.expect(request.getHeader(parser.METHOD_HEADER)).andReturn("delete")
EasyMock.expect(request.getHeader(parser.METHOD_HEADER)).andReturn("delete")
EasyMock.expect(request.getParameter(parser.METHOD_PARAM)).andReturn(null)
replay(request)
val method = parser.determineMethod(request)
method should equal (DELETE)
}
it ("should be favor the param over the method") {
val request = createMock(classOf[HttpServletRequest])
val parser = new AnyRef with MethodParser
EasyMock.expect(request.getMethod()).andReturn("POST")
EasyMock.expect(request.getHeader(parser.METHOD_HEADER)).andReturn(null)
EasyMock.expect(request.getParameter(parser.METHOD_PARAM)).andReturn("put")
EasyMock.expect(request.getParameter(parser.METHOD_PARAM)).andReturn("put")
replay(request)
val method = parser.determineMethod(request)
method should equal (PUT)
}
it ("should be favor the param over both") {
val request = createMock(classOf[HttpServletRequest])
val parser = new AnyRef with MethodParser
EasyMock.expect(request.getMethod()).andReturn("POST")
EasyMock.expect(request.getHeader(parser.METHOD_HEADER)).andReturn("delete")
EasyMock.expect(request.getHeader(parser.METHOD_HEADER)).andReturn("delete")
EasyMock.expect(request.getParameter(parser.METHOD_PARAM)).andReturn("put")
EasyMock.expect(request.getParameter(parser.METHOD_PARAM)).andReturn("put")
replay(request)
val method = parser.determineMethod(request)
method should equal (PUT)
}
}
private def testParsing(methodString:String,methodObject:HTTPMethod) = {
val request = createMock(classOf[HttpServletRequest])
val parser = new AnyRef with MethodParser
EasyMock.expect(request.getMethod()).andReturn(methodString)
EasyMock.expect(request.getHeader(parser.METHOD_HEADER)).andReturn(null)
EasyMock.expect(request.getParameter(parser.METHOD_PARAM)).andReturn(null)
replay(request)
val method = parser.determineMethod(request)
method should equal (methodObject)
}
}
| davetron5000/shorty | src/test/scala/shorty/TestMethodParser.scala | Scala | mit | 3,184 |
/*
* 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
import breeze.linalg._
/**
* This class contains low overhead wrappers around native BLAS functions.
*/
private[latrobe] object _BLAS {
final val blas = com.github.fommil.netlib.BLAS.getInstance()
// ---------------------------------------------------------------------------
// asum: sum(abs(x))
// ---------------------------------------------------------------------------
@inline
final def asum(x: Array[Float])
: Float = blas.sasum(
x.length,
x, 0, 1
)
@inline
final def asum(n: Int,
x: Array[Float], xOff: Int, xInc: Int)
: Float = {
require(xInc > 0)
blas.sasum(
n,
x, xOff, xInc
)
}
@inline
final def asum(x: Array[Double])
: Double = blas.dasum(
x.length,
x, 0, 1
)
@inline
final def asum(n: Int,
x: Array[Double], xOff: Int, xInc: Int)
: Double = {
require(xInc > 0)
blas.dasum(
n,
x, xOff, xInc
)
}
// ---------------------------------------------------------------------------
// axpy: y = a * x + y
// ---------------------------------------------------------------------------
@inline
final def axpy(a: Float,
x: Array[Float],
y: Array[Float])
: Unit = {
require(x.length == y.length)
blas.saxpy(
x.length,
a,
x, 0, 1,
y, 0, 1
)
}
@inline
final def axpy(n: Int,
a: Float,
x: Array[Float], xOff: Int, xInc: Int,
y: Array[Float], yOff: Int, yInc: Int)
: Unit = {
require(xInc > 0 && yInc > 0)
blas.saxpy(
n,
a,
x, xOff, xInc,
y, yOff, yInc
)
}
@inline
final def axpy(a: Double,
x: Array[Double],
y: Array[Double])
: Unit = {
require(x.length == y.length)
blas.daxpy(
x.length,
a,
x, 0, 1,
y, 0, 1
)
}
@inline
final def axpy(n: Int,
a: Double,
x: Array[Double], xOff: Int, xInc: Int,
y: Array[Double], yOff: Int, yInc: Int)
: Unit = {
require(xInc > 0 && yInc > 0)
blas.daxpy(
n,
a,
x, xOff, xInc,
y, yOff, yInc
)
}
// ---------------------------------------------------------------------------
// copy: y = x
// ---------------------------------------------------------------------------
@inline
final def copy(x: Array[Float],
y: Array[Float])
: Unit = {
require(x.length == y.length)
blas.scopy(
x.length,
x, 0, 1,
y, 0, 1
)
}
@inline
final def copy(n: Int,
x: Array[Float], xOff: Int, xInc: Int,
y: Array[Float], yOff: Int, yInc: Int)
: Unit = {
require(xInc > 0 && yInc > 0)
blas.scopy(
n,
x, xOff, xInc,
y, yOff, yInc
)
}
@inline
final def copy(x: Array[Double],
y: Array[Double])
: Unit = {
require(x.length == y.length)
blas.dcopy(
x.length,
x, 0, 1,
y, 0, 1
)
}
@inline
final def copy(n: Int,
x: Array[Double], xOff: Int, xInc: Int,
y: Array[Double], yOff: Int, yInc: Int)
: Unit = {
require(xInc > 0 && yInc > 0)
blas.dcopy(
n,
x, xOff, xInc,
y, yOff, yInc
)
}
// ---------------------------------------------------------------------------
// dot: x' * y
// ---------------------------------------------------------------------------
@inline
final def dot(x: Array[Float],
y: Array[Float])
: Float = {
require(x.length == y.length)
blas.sdot(
x.length,
x, 0, 1,
y, 0, 1
)
}
@inline
final def dot(n: Int,
x: Array[Float], xOff: Int, xInc: Int,
y: Array[Float], yOff: Int, yInc: Int)
: Float = {
require(xInc > 0 && yInc > 0)
blas.sdot(
n,
x, xOff, xInc,
y, yOff, yInc
)
}
@inline
final def dot(x: Array[Double],
y: Array[Double])
: Double = {
require(x.length == y.length)
blas.ddot(
x.length,
x, 0, 1,
y, 0, 1
)
}
@inline
final def dot(n: Int,
x: Array[Double], xOff: Int, xInc: Int,
y: Array[Double], yOff: Int, yInc: Int)
: Double = {
require(xInc > 0 && yInc > 0)
blas.ddot(
n,
x, xOff, xInc,
y, yOff, yInc
)
}
// ---------------------------------------------------------------------------
// gbmv: z = alpha * x * y + beta * z
// gbmv: z = alpha * x' * y + beta * z
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// gemm: C = alpha * op(A) * op(B) + beta * C
// ---------------------------------------------------------------------------
@inline
final def gemm(alpha: Float,
a: Array[Float], aOff: Int, aStride: Int, aRows: Int, aCols: Int, aTrans: Boolean,
b: Array[Float], bOff: Int, bStride: Int, bRows: Int, bCols: Int, bTrans: Boolean,
beta: Float,
c: Array[Float], cOff: Int, cStride: Int, cRows: Int, cCols: Int)
: Unit = {
require(
aStride > 0 &&
bStride > 0 &&
cStride > 0 &&
aRows == cRows &&
aCols == bRows &&
bCols == cCols
)
blas.sgemm(
if (aTrans) "T" else "N",
if (bTrans) "T" else "N",
aRows,
bCols,
aCols,
alpha,
a, aOff, aStride,
b, bOff, bStride,
beta,
c, cOff, cStride
)
}
@inline
final def gemm(alpha: Double,
a: Array[Double], aOff: Int, aStride: Int, aRows: Int, aCols: Int, aTrans: Boolean,
b: Array[Double], bOff: Int, bStride: Int, bRows: Int, bCols: Int, bTrans: Boolean,
beta: Double,
c: Array[Double], cOff: Int, cStride: Int, cRows: Int, cCols: Int)
: Unit = {
require(
aStride > 0 &&
bStride > 0 &&
cStride > 0 &&
aRows == cRows &&
aCols == bRows &&
bCols == cCols
)
blas.dgemm(
if (aTrans) "T" else "N",
if (bTrans) "T" else "N",
aRows,
bCols,
aCols,
alpha,
a, aOff, aStride,
b, bOff, bStride,
beta,
c, cOff, cStride
)
}
@inline
final def gemm(alpha: Real,
a: DenseMatrix[Real],
b: DenseMatrix[Real])
: DenseMatrix[Float] = {
val c = DenseMatrix.zeros[Real](a.rows, b.cols)
gemm(
alpha,
a,
b,
Real.zero,
c
)
c
}
@inline
final def gemm(alpha: Real,
a: DenseMatrix[Real],
b: DenseMatrix[Real],
beta: Real,
c: DenseMatrix[Real])
: Unit = gemm(
alpha,
a, a.offset, a.rows, a.cols,
b, b.offset, b.rows, b.cols,
beta,
c, c.offset, c.rows, c.cols
)
@inline
final def gemm(alpha: Real,
a: DenseMatrix[Real], aOff: Int, aRows: Int, aCols: Int,
b: DenseMatrix[Real], bOff: Int, bRows: Int, bCols: Int,
beta: Real,
c: DenseMatrix[Real], cOff: Int, cRows: Int, cCols: Int)
: Unit = {
require(!c.isTranspose)
gemm(
alpha,
a.data, aOff, a.majorStride, aRows, aCols, a.isTranspose,
b.data, bOff, b.majorStride, bRows, bCols, b.isTranspose,
beta,
c.data, cOff, c.majorStride, cRows, cCols
)
}
// ---------------------------------------------------------------------------
// gemv: z = alpha * x * y + beta * z
// gemv: z = alpha * x' * y + beta * z
// ---------------------------------------------------------------------------
@inline
final def gemv(alpha: Float,
a: Array[Float], aOff: Int, aStride: Int, aRows: Int, aCols: Int, aTrans: Boolean,
x: Array[Float], xOff: Int, xInc: Int, xRows: Int,
beta: Float,
y: Array[Float], yOff: Int, yInc: Int, yRows: Int)
: Unit = {
require(
aStride > 0 &&
xInc > 0 &&
yInc > 0 &&
aCols == xRows &&
aCols == yRows
)
blas.sgemv(
if (aTrans) "T" else "N",
aRows,
aCols,
alpha,
a, aOff, aStride,
x, xOff, xInc,
beta,
y, yOff, yInc
)
}
@inline
final def gemv(alpha: Double,
a: Array[Double], aOff: Int, aStride: Int, aRows: Int, aCols: Int, aTrans: Boolean,
x: Array[Double], xOff: Int, xInc: Int, xRows: Int,
beta: Double,
y: Array[Double], yOff: Int, yInc: Int, yRows: Int)
: Unit = {
require(
aStride > 0 &&
xInc > 0 &&
yInc > 0 &&
aCols == xRows &&
aCols == yRows
)
blas.dgemv(
if (aTrans) "T" else "N",
aRows,
aCols,
alpha,
a, aOff, aStride,
x, xOff, xInc,
beta,
y, yOff, yInc
)
}
/*
@inline
final def gemv(alpha: Real,
a: DenseMatrix[Real],
x: DenseVector[Real])
: DenseVector[Real] = {
val y = DenseVector.zeros[Real](x.length)
gemv(alpha, a, x, Real.zero, y)
y
}
@inline
final def gemv(alpha: Real,
a: DenseMatrix[Real],
x: DenseVector[Real],
beta: Real,
y: DenseVector[Real])
: Unit = gemv(
alpha,
a, a.offset, a.rows, a.cols,
x, x.offset, x.length,
beta,
y, y.offset, y.length
)
@inline
final def gemv(alpha: Real,
a: DenseMatrix[Real], aOff: Int, aRows: Int, aCols: Int,
x: DenseVector[Real], xOff: Int, xRows: Int,
beta: Real,
y: DenseVector[Real], yOff: Int, yRows: Int)
: Unit = gemv(
alpha,
a.data, aOff, a.majorStride, aRows, aCols, a.isTranspose,
x.data, xOff, x.stride, xRows,
beta,
y.data, yOff, y.stride, yRows
)
*/
// ---------------------------------------------------------------------------
// ger: z = alpha * x * y' + z
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// iamax: index_where(abs(x) = max(abs(x)))
// ---------------------------------------------------------------------------
@inline
final def iamax(x: Array[Float])
: Int = blas.isamax(
x.length,
x, 0, 1
)
@inline
final def iamax(n: Int,
x: Array[Float], xOff: Int, xInc: Int)
: Int = {
require(xInc > 0)
blas.isamax(
n,
x, xOff, xInc
)
}
@inline
final def iamax(x: Array[Double])
: Int = blas.idamax(
x.length,
x, 0, 1
)
@inline
final def iamax(n: Int,
x: Array[Double], xOff: Int, xInc: Int)
: Int = {
require(xInc > 0)
blas.idamax(
n,
x, xOff, xInc
)
}
// ---------------------------------------------------------------------------
// nrm2: sqrt(x' * x)
// ---------------------------------------------------------------------------
@inline
final def nrm2(x: Array[Float])
: Float = {
blas.snrm2(
x.length,
x, 0, 1
)
}
@inline
final def nrm2(n: Int,
x: Array[Float], xOff: Int, xInc: Int)
: Float = {
require(xInc > 0)
blas.snrm2(
n,
x, xOff, xInc
)
}
@inline
final def nrm2(x: Array[Double])
: Double = {
blas.dnrm2(
x.length,
x, 0, 1
)
}
@inline
final def nrm2(n: Int,
x: Array[Double], xOff: Int, xInc: Int)
: Double = {
require(xInc > 0)
blas.dnrm2(
n,
x, xOff, xInc
)
}
// ---------------------------------------------------------------------------
// rot:
// rotg:
// rotm:
// rotmg:
// dsbmv: z = alpha * x * y + beta * y
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// scal: a * x
// ---------------------------------------------------------------------------
@inline
final def scal(a: Float, x: Array[Float])
: Unit = blas.sscal(
x.length,
a,
x, 0, 1
)
@inline
final def scal(n: Int,
a: Float,
x: Array[Float], xOff: Int, xInc: Int)
: Unit = {
require(xInc > 0)
blas.sscal(
n,
a,
x, xOff, xInc
)
}
@inline
final def scal(a: Double, x: Array[Double])
: Unit = blas.dscal(
x.length,
a,
x, 0, 1
)
@inline
final def scal(n: Int,
a: Double,
x: Array[Double], xOff: Int, xInc: Int)
: Unit = {
require(xInc > 0)
blas.dscal(
n,
a,
x, xOff, xInc
)
}
// ---------------------------------------------------------------------------
// spmv: z = alpha * X * y + beta * z
// spr: Y = alpha * x * x' + Y
// spr2: Z = alpha * x * y' + alpha * y * x' + Z
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// swap: tmp = x; x = y; y = tmp
// ---------------------------------------------------------------------------
@inline
final def swap(x: Array[Float],
y: Array[Float])
: Unit = {
require(x.length == y.length)
blas.sswap(
x.length,
x, 0, 1,
y, 0, 1
)
}
@inline
final def swap(n: Int,
x: Array[Float], xOff: Int, xInc: Int,
y: Array[Float], yOff: Int, yInc: Int)
: Unit = {
require(xInc > 0 && yInc > 0)
blas.sswap(
n,
x, xOff, xInc,
y, yOff, yInc
)
}
@inline
final def swap(x: Array[Double],
y: Array[Double])
: Unit = {
require(x.length == y.length)
blas.dswap(
x.length,
x, 0, 1,
y, 0, 1
)
}
@inline
final def swap(n: Int,
x: Array[Double], xOff: Int, xInc: Int,
y: Array[Double], yOff: Int, yInc: Int)
: Unit = {
require(xInc > 0 && yInc > 0)
blas.dswap(
n,
x, xOff, xInc,
y, yOff, yInc
)
}
// ---------------------------------------------------------------------------
// symm: Z = alpha * X * Y + beta * Z
// symm: Z = alpha * Y * X + beta * Z
// symv: z = alpha * X * y + beta * z
// syr: Y = alpha * x * x' + Y
// syr2: Z = alpha * x * y' + alpha * y * x' + Z
// syr2k: Z = alpha * X * Y' + alpha * Y * X' + beta * Z
// syrk: Y = alpha * X * X' + beta * Y
// tbmv: x = A * x
// tbmv: x = A' * x
// tbsv: A * x = b
// tbsv: A' * x = b
// tpmv: x = A * x
// tpmv: x = A' * x
// tpsv: A * x = b
// tpsv: A' * x = b
// trmm: B = alpha * op(A) * B
// trmm: B = alpha * B * op(A)
// trmv: x = A * x
// trmv: x = A' * x
// trsm: op(A) * X = alpha * B
// trsm: X * op(A) = alpha * B
// trsv: A * x = b
// trsv: A' * x = b
// ---------------------------------------------------------------------------
}
| bashimao/ltudl | base/src/main/scala/edu/latrobe/_BLAS.scala | Scala | apache-2.0 | 16,186 |
package components.plane.applications
import components.plane.elements.Point
object Reflection {
def reflectX(point: Point)(x: Int): Point = point.copy(x = 2 * x - point.x)
def reflectX(points: Iterable[Point])(x: Int): Iterable[Point] =
for (point <- points) yield reflectX(point)(x)
} | arie-benichou/blockplus | src/main/scala/components/plane/applications/Reflection.scala | Scala | gpl-3.0 | 299 |
/*
* Copyright 2017 Datamountaineer.
*
* 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.datamountaineer.streamreactor.connect.bloomberg
import org.apache.kafka.connect.data.{Schema, SchemaBuilder}
import scala.collection.JavaConverters._
/**
* Utility class to allow generating the connect schema for the BloombergData.
*
* @param namespace Avro namespace
*/
private[bloomberg] class ConnectSchema(namespace: String) {
/**
* Creates an avro schema for the given input. Only a handful of types are supported given the return types from BloombergFieldValueFn
*
* @param name field name
* @param value The value for which it will create a avro schema
* @return A avro Schema instance
*/
def createSchema(name: String, value: Any): Schema = {
value match {
case _: Boolean => Schema.BOOLEAN_SCHEMA
case _: Int => Schema.INT32_SCHEMA
case _: Long => Schema.INT64_SCHEMA
case _: Double => Schema.FLOAT64_SCHEMA
case _: Char => Schema.STRING_SCHEMA
case _: String => Schema.STRING_SCHEMA
case _: Float => Schema.FLOAT32_SCHEMA
case list: java.util.List[_] =>
val firstItemSchema = if (list.isEmpty) Schema.OPTIONAL_STRING_SCHEMA else createSchema(name, list.get(0))
SchemaBuilder.array(firstItemSchema).build()
case map: java.util.LinkedHashMap[String @unchecked, _] =>
val recordBuilder = SchemaBuilder.struct()
recordBuilder.name(name)
map.entrySet().asScala.foreach(kvp =>
recordBuilder.field(kvp.getKey, createSchema(kvp.getKey, kvp.getValue)))
recordBuilder.build()
case v => sys.error(s"${v.getClass} is not handled.")
}
}
}
object ConnectSchema {
val namespace = "com.datamountaineer.streamreactor.connect.bloomberg"
val connectSchema = new ConnectSchema(namespace)
implicit class BloombergDataToConnectSchema(val data: BloombergData) {
def getConnectSchema : Schema = {
connectSchema.createSchema("BloombergData", data.data)
}
}
}
| CodeSmell/stream-reactor | kafka-connect-bloomberg/src/main/scala/com/datamountaineer/streamreactor/connect/bloomberg/ConnectSchema.scala | Scala | apache-2.0 | 2,547 |
package de.choffmeister.auth.common
import de.choffmeister.auth.common.util.Base64StringConverter._
import de.choffmeister.auth.common.util._
class PasswordHasher(defaultName: String, defaultConfig: List[String], algorithms: Seq[PasswordHashAlgorithm]) {
def hash(password: String, additionalConfig: List[String] = Nil): String = {
hashByAlgoName(defaultName, defaultConfig ++ additionalConfig, password) match {
case Right(hash) =>
val fields = List(defaultName) ++ defaultConfig ++ additionalConfig ++ List(bytesToBase64(hash))
fields.mkString(":")
case Left(c) =>
hash(password, additionalConfig ++ c)
}
}
def validate(stored: String, password: String): Boolean = {
val splitted = stored.split(":", -1).toList
val name = splitted.head
val config = splitted.tail.init
val hash = base64ToBytes(splitted.last)
SequenceUtils.compareConstantTime(hashByAlgoName(name, config, password).right.get, hash)
}
private def hashByAlgoName(name: String, config: List[String], password: String): Either[List[String], Array[Byte]] = {
algorithms.find(_.name == name).get.hash(config, password)
}
}
| choffmeister/auth-utils | auth-common/src/main/scala/de/choffmeister/auth/common/PasswordHasher.scala | Scala | mit | 1,169 |
/***********************************************************************
* Copyright (c) 2013-2022 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.process.analytic
import com.typesafe.scalalogging.LazyLogging
import org.geotools.data.Query
import org.geotools.data.collection.ListFeatureCollection
import org.geotools.data.simple.{SimpleFeatureCollection, SimpleFeatureSource}
import org.geotools.process.factory.{DescribeParameter, DescribeProcess, DescribeResult}
import org.locationtech.geomesa.features.ScalaSimpleFeature
import org.locationtech.geomesa.index.geotools.GeoMesaFeatureCollection
import org.locationtech.geomesa.index.iterators.StatsScan
import org.locationtech.geomesa.index.process.GeoMesaProcessVisitor
import org.locationtech.geomesa.index.stats.HasGeoMesaStats
import org.locationtech.geomesa.process.{FeatureResult, GeoMesaProcess}
import org.locationtech.geomesa.process.analytic.MinMaxProcess.MinMaxVisitor
import org.locationtech.geomesa.utils.collection.SelfClosingIterator
import org.locationtech.geomesa.utils.geotools.GeometryUtils
import org.locationtech.geomesa.utils.stats.Stat
import org.opengis.feature.Feature
import org.opengis.feature.simple.SimpleFeature
@DescribeProcess(
title = "Min/Max Process",
description = "Gets attribute bounds for a data set"
)
class MinMaxProcess extends GeoMesaProcess with LazyLogging {
@DescribeResult(description = "Output feature collection")
def execute(
@DescribeParameter(
name = "features",
description = "The feature set on which to query")
features: SimpleFeatureCollection,
@DescribeParameter(
name = "attribute",
description = "The attribute to gather bounds for")
attribute: String,
@DescribeParameter(
name = "cached",
description = "Return cached values, if available",
min = 0, max = 1)
cached: java.lang.Boolean = null
): SimpleFeatureCollection = {
require(attribute != null, "Attribute is a required field")
logger.debug(s"Attempting min/max process on type ${features.getClass.getName}")
val visitor = new MinMaxVisitor(features, attribute, Option(cached).forall(_.booleanValue()))
GeoMesaFeatureCollection.visit(features, visitor)
visitor.getResult.results
}
}
object MinMaxProcess {
class MinMaxVisitor(features: SimpleFeatureCollection, attribute: String, cached: Boolean)
extends GeoMesaProcessVisitor with LazyLogging {
private lazy val stat: Stat = Stat(features.getSchema, Stat.MinMax(attribute))
private var resultCalc: FeatureResult = _
// non-optimized visit
override def visit(feature: Feature): Unit = stat.observe(feature.asInstanceOf[SimpleFeature])
override def getResult: FeatureResult = {
if (resultCalc != null) {
resultCalc
} else {
createResult(stat.toJson)
}
}
override def execute(source: SimpleFeatureSource, query: Query): Unit = {
logger.debug(s"Running Geomesa min/max process on source type ${source.getClass.getName}")
source.getDataStore match {
case ds: HasGeoMesaStats =>
resultCalc = ds.stats.getMinMax[Any](source.getSchema, attribute, query.getFilter, !cached) match {
case None => createResult("{}")
case Some(mm) => createResult(mm.toJson)
}
case ds =>
logger.warn(s"Running unoptimized min/max query on ${ds.getClass.getName}")
SelfClosingIterator(features.features).foreach(visit)
}
}
}
private def createResult(stat: String): FeatureResult = {
val sf = new ScalaSimpleFeature(StatsScan.StatsSft, "", Array(stat, GeometryUtils.zeroPoint))
FeatureResult(new ListFeatureCollection(StatsScan.StatsSft, Array[SimpleFeature](sf)))
}
}
| locationtech/geomesa | geomesa-process/geomesa-process-vector/src/main/scala/org/locationtech/geomesa/process/analytic/MinMaxProcess.scala | Scala | apache-2.0 | 4,295 |
package com.wavesplatform.it.sync.grpc
import com.google.protobuf.ByteString
import com.wavesplatform.common.utils.EitherExt2
import com.wavesplatform.it.api.SyncGrpcApi._
import com.wavesplatform.it.sync._
import com.wavesplatform.protobuf.transaction.MassTransferTransactionData.Transfer
import com.wavesplatform.protobuf.transaction.{PBTransactions, Recipient}
import com.wavesplatform.transaction.transfer.MassTransferTransaction.MaxTransferCount
import com.wavesplatform.transaction.transfer.TransferTransaction.MaxAttachmentSize
import io.grpc.Status.Code
class MassTransferTransactionGrpcSuite extends GrpcBaseTransactionSuite {
test("asset mass transfer changes asset balances and sender's.waves balance is decreased by fee.") {
for (v <- massTransferTxSupportedVersions) {
val firstBalance = sender.wavesBalance(firstAddress)
val secondBalance = sender.wavesBalance(secondAddress)
val attachment = ByteString.copyFrom("mass transfer description".getBytes("UTF-8"))
val transfers = List(Transfer(Some(Recipient().withPublicKeyHash(secondAddress)), transferAmount))
val assetId = PBTransactions.vanilla(
sender.broadcastIssue(firstAcc, "name", issueAmount, 8, reissuable = false, issueFee, waitForTx = true)
).explicitGet().id().toString
sender.waitForTransaction(assetId)
val massTransferTransactionFee = calcMassTransferFee(transfers.size)
sender.broadcastMassTransfer(firstAcc, Some(assetId), transfers, attachment, massTransferTransactionFee, waitForTx = true)
val firstBalanceAfter = sender.wavesBalance(firstAddress)
val secondBalanceAfter = sender.wavesBalance(secondAddress)
firstBalanceAfter.regular shouldBe firstBalance.regular - issueFee - massTransferTransactionFee
firstBalanceAfter.effective shouldBe firstBalance.effective - issueFee - massTransferTransactionFee
sender.assetsBalance(firstAddress, Seq(assetId)).getOrElse(assetId, 0L) shouldBe issueAmount - transferAmount
secondBalanceAfter.regular shouldBe secondBalance.regular
secondBalanceAfter.effective shouldBe secondBalance.effective
sender.assetsBalance(secondAddress, Seq(assetId)).getOrElse(assetId, 0L) shouldBe transferAmount
}
}
test("waves mass transfer changes waves balances") {
val firstBalance = sender.wavesBalance(firstAddress)
val secondBalance = sender.wavesBalance(secondAddress)
val thirdBalance = sender.wavesBalance(thirdAddress)
val transfers = List(Transfer(Some(Recipient().withPublicKeyHash(secondAddress)), transferAmount), Transfer(Some(Recipient().withPublicKeyHash(thirdAddress)), 2 * transferAmount))
val massTransferTransactionFee = calcMassTransferFee(transfers.size)
sender.broadcastMassTransfer(firstAcc, transfers = transfers, fee = massTransferTransactionFee, waitForTx = true)
val firstBalanceAfter = sender.wavesBalance(firstAddress)
val secondBalanceAfter = sender.wavesBalance(secondAddress)
val thirdBalanceAfter = sender.wavesBalance(thirdAddress)
firstBalanceAfter.regular shouldBe firstBalance.regular - massTransferTransactionFee - 3 * transferAmount
firstBalanceAfter.effective shouldBe firstBalance.effective - massTransferTransactionFee - 3 * transferAmount
secondBalanceAfter.regular shouldBe secondBalance.regular + transferAmount
secondBalanceAfter.effective shouldBe secondBalance.effective + transferAmount
thirdBalanceAfter.regular shouldBe thirdBalance.regular + 2 * transferAmount
thirdBalanceAfter.effective shouldBe thirdBalance.effective + 2 * transferAmount
}
test("can not make mass transfer without having enough waves") {
val firstBalance = sender.wavesBalance(firstAddress)
val secondBalance = sender.wavesBalance(secondAddress)
val transfers = List(Transfer(Some(Recipient().withPublicKeyHash(secondAddress)), firstBalance.regular / 2), Transfer(Some(Recipient().withPublicKeyHash(thirdAddress)), firstBalance.regular / 2))
assertGrpcError(
sender.broadcastMassTransfer(firstAcc, transfers = transfers, fee = calcMassTransferFee(transfers.size)),
"Attempt to transfer unavailable funds",
Code.INVALID_ARGUMENT
)
nodes.foreach(n => n.waitForHeight(n.height + 1))
sender.wavesBalance(firstAddress) shouldBe firstBalance
sender.wavesBalance(secondAddress) shouldBe secondBalance
}
test("cannot make mass transfer when fee less then minimal ") {
val firstBalance = sender.wavesBalance(firstAddress)
val secondBalance = sender.wavesBalance(secondAddress)
val transfers = List(Transfer(Some(Recipient().withPublicKeyHash(secondAddress)), transferAmount))
val massTransferTransactionFee = calcMassTransferFee(transfers.size)
assertGrpcError(
sender.broadcastMassTransfer(firstAcc, transfers = transfers, fee = massTransferTransactionFee - 1),
s"does not exceed minimal value of $massTransferTransactionFee WAVES",
Code.INVALID_ARGUMENT
)
nodes.foreach(n => n.waitForHeight(n.height + 1))
sender.wavesBalance(firstAddress) shouldBe firstBalance
sender.wavesBalance(secondAddress) shouldBe secondBalance
}
test("cannot make mass transfer without having enough of effective balance") {
val firstBalance = sender.wavesBalance(firstAddress)
val secondBalance = sender.wavesBalance(secondAddress)
val transfers = List(Transfer(Some(Recipient().withPublicKeyHash(secondAddress)), firstBalance.regular - 2 * minFee))
val massTransferTransactionFee = calcMassTransferFee(transfers.size)
sender.broadcastLease(firstAcc, Recipient().withPublicKeyHash(secondAddress), leasingAmount, minFee, waitForTx = true)
assertGrpcError(
sender.broadcastMassTransfer(firstAcc, transfers = transfers, fee = massTransferTransactionFee),
"Attempt to transfer unavailable funds",
Code.INVALID_ARGUMENT
)
nodes.foreach(n => n.waitForHeight(n.height + 1))
sender.wavesBalance(firstAddress).regular shouldBe firstBalance.regular - minFee
sender.wavesBalance(firstAddress).effective shouldBe firstBalance.effective - minFee - leasingAmount
sender.wavesBalance(secondAddress).regular shouldBe secondBalance.regular
sender.wavesBalance(secondAddress).effective shouldBe secondBalance.effective + leasingAmount
}
test("cannot broadcast invalid mass transfer tx") {
val firstBalance = sender.wavesBalance(firstAddress)
val secondBalance = sender.wavesBalance(secondAddress)
val defaultTransfer = List(Transfer(Some(Recipient().withPublicKeyHash(secondAddress)), transferAmount))
val negativeTransfer = List(Transfer(Some(Recipient().withPublicKeyHash(secondAddress)), -1))
assertGrpcError(
sender.broadcastMassTransfer(firstAcc, transfers = negativeTransfer, fee = calcMassTransferFee(negativeTransfer.size)),
"One of the transfers has negative amount",
Code.INVALID_ARGUMENT
)
val tooManyTransfers = List.fill(MaxTransferCount + 1)(Transfer(Some(Recipient().withPublicKeyHash(secondAddress)), 1))
assertGrpcError(
sender.broadcastMassTransfer(firstAcc, transfers = tooManyTransfers, fee = calcMassTransferFee(MaxTransferCount + 1)),
s"Number of transfers ${MaxTransferCount + 1} is greater than 100",
Code.INVALID_ARGUMENT
)
val tooBigAttachment = ByteString.copyFrom(("a" * (MaxAttachmentSize + 1)).getBytes("UTF-8"))
assertGrpcError(
sender.broadcastMassTransfer(firstAcc, transfers = defaultTransfer, attachment = tooBigAttachment, fee = calcMassTransferFee(1)),
"Too big sequence requested",
Code.INVALID_ARGUMENT
)
sender.wavesBalance(firstAddress) shouldBe firstBalance
sender.wavesBalance(secondAddress) shouldBe secondBalance
}
test("huge transactions are allowed") {
val firstBalance = sender.wavesBalance(firstAddress)
val fee = calcMassTransferFee(MaxTransferCount)
val amount = (firstBalance.available - fee) / MaxTransferCount
val maxAttachment = ByteString.copyFrom(("a" * MaxAttachmentSize).getBytes("UTF-8"))
val transfers = List.fill(MaxTransferCount)(Transfer(Some(Recipient().withPublicKeyHash(firstAddress)), amount))
sender.broadcastMassTransfer(firstAcc, transfers = transfers, fee = fee, attachment = maxAttachment, waitForTx = true)
sender.wavesBalance(firstAddress).regular shouldBe firstBalance.regular - fee
sender.wavesBalance(firstAddress).effective shouldBe firstBalance.effective - fee
}
test("able to mass transfer to alias") {
val firstBalance = sender.wavesBalance(firstAddress)
val secondBalance = sender.wavesBalance(secondAddress)
val alias = "masstest_alias"
sender.broadcastCreateAlias(secondAcc, alias, minFee, waitForTx = true)
val transfers = List(Transfer(Some(Recipient().withPublicKeyHash(firstAddress)), transferAmount), Transfer(Some(Recipient().withAlias(alias)), transferAmount))
val massTransferTransactionFee = calcMassTransferFee(transfers.size)
sender.broadcastMassTransfer(firstAcc, transfers = transfers, fee = massTransferTransactionFee, waitForTx = true)
sender.wavesBalance(firstAddress).regular shouldBe firstBalance.regular - massTransferTransactionFee - transferAmount
sender.wavesBalance(firstAddress).effective shouldBe firstBalance.effective - massTransferTransactionFee - transferAmount
sender.wavesBalance(secondAddress).regular shouldBe secondBalance.regular + transferAmount - minFee
sender.wavesBalance(secondAddress).effective shouldBe secondBalance.effective + transferAmount - minFee
}
}
| wavesplatform/Waves | node-it/src/test/scala/com/wavesplatform/it/sync/grpc/MassTransferTransactionGrpcSuite.scala | Scala | mit | 9,586 |
/*
* Copyright (C) 2012 Romain Reuillon
*
* 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 org.openmole.tool.cache
import squants._
object TimeCache {
def apply[T](f: () ⇒ (T, Time)) = new TimeCache[T](f)
}
class TimeCache[T](f: () ⇒ (T, Time)) {
var cache: Option[T] = None
var cacheExpiration = Long.MinValue
def apply() = synchronized {
if (System.currentTimeMillis > cacheExpiration) cache = None
cache match {
case None ⇒
val (v, t) = f()
cache = Some(v)
cacheExpiration = System.currentTimeMillis + t.millis
v
case Some(c) ⇒ c
}
}
}
| openmole/openmole | openmole/third-parties/org.openmole.tool.cache/src/main/scala/org/openmole/tool/cache/TimeCache.scala | Scala | agpl-3.0 | 1,231 |
/*
*************************************************************************************
* Copyright 2013 Normation SAS
*************************************************************************************
*
* 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.
*
* In accordance with the terms of section 7 (7. Additional Terms.) of
* the GNU Affero GPL v3, the copyright holders add the following
* Additional permissions:
* Notwithstanding to the terms of section 5 (5. Conveying Modified Source
* Versions) and 6 (6. Conveying Non-Source Forms.) of the GNU Affero GPL v3
* licence, when you create a Related Module, this Related Module is
* not considered as a part of the work and may be distributed under the
* license agreement of your choice.
* A "Related Module" means a set of sources files including their
* documentation that, without modification of the Source Code, enables
* supplementary functions or services in addition to those offered by
* the Software.
*
* 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/agpl.html>.
*
*************************************************************************************
*/
package com.normation.rudder.web.rest.parameter
import com.normation.eventlog.EventActor
import com.normation.eventlog.ModificationId
import com.normation.rudder.batch.AsyncDeploymentAgent
import com.normation.rudder.domain.parameters._
import com.normation.rudder.domain.workflows.ChangeRequestId
import com.normation.rudder.repository.RoParameterRepository
import com.normation.rudder.repository.WoParameterRepository
import com.normation.rudder.services.workflows.ChangeRequestService
import com.normation.rudder.services.workflows.WorkflowService
import com.normation.rudder.web.rest.RestUtils
import com.normation.rudder.web.rest.RestUtils.getActor
import com.normation.rudder.web.rest.RestUtils.toJsonError
import com.normation.rudder.web.rest.RestUtils.toJsonResponse
import com.normation.rudder.web.rest.RestExtractorService
import com.normation.utils.StringUuidGenerator
import net.liftweb.common.Box
import net.liftweb.common.Box.box2Option
import net.liftweb.common.EmptyBox
import net.liftweb.common.Full
import net.liftweb.http.Req
import net.liftweb.json.JArray
import net.liftweb.json.JValue
import net.liftweb.json.JsonDSL._
import net.liftweb.common.Loggable
import com.normation.rudder.web.rest.RestDataSerializer
case class ParameterApiService2 (
readParameter : RoParameterRepository
, writeParameter : WoParameterRepository
, uuidGen : StringUuidGenerator
, changeRequestService : ChangeRequestService
, workflowService : WorkflowService
, restExtractor : RestExtractorService
, workflowEnabled : () => Box[Boolean]
, restDataSerializer : RestDataSerializer
) extends Loggable {
import restDataSerializer.{ serializeParameter => serialize}
private[this] def createChangeRequestAndAnswer (
id : String
, diff : ChangeRequestGlobalParameterDiff
, parameter : GlobalParameter
, initialState : Option[GlobalParameter]
, actor : EventActor
, req : Req
, act : String
) (implicit action : String, prettify : Boolean) = {
logger.info(restExtractor.extractReason(req.params))
( for {
reason <- restExtractor.extractReason(req.params)
crName <- restExtractor.extractChangeRequestName(req.params).map(_.getOrElse(s"${act} Parameter ${parameter.name} from API"))
crDescription = restExtractor.extractChangeRequestDescription(req.params)
cr <- changeRequestService.createChangeRequestFromGlobalParameter(
crName
, crDescription
, parameter
, initialState
, diff
, actor
, reason
)
wfStarted <- workflowService.startWorkflow(cr.id, actor, None)
} yield {
cr.id
}
) match {
case Full(crId) =>
workflowEnabled() match {
case Full(enabled) =>
val optCrId = if (enabled) Some(crId) else None
val jsonParameter = List(serialize(parameter,optCrId))
toJsonResponse(Some(id), ("parameters" -> JArray(jsonParameter)))
case eb : EmptyBox =>
val fail = eb ?~ (s"Could not check workflow property" )
val msg = s"Change request creation failed, cause is: ${fail.msg}."
toJsonError(Some(id), msg)
}
case eb:EmptyBox =>
val fail = eb ?~ (s"Could not save changes on Parameter ${id}" )
val msg = s"${act} failed, cause is: ${fail.msg}."
toJsonError(Some(id), msg)
}
}
def listParameters(req : Req) = {
implicit val action = "listParameters"
implicit val prettify = restExtractor.extractPrettify(req.params)
readParameter.getAllGlobalParameters match {
case Full(parameters) =>
toJsonResponse(None, ( "parameters" -> JArray(parameters.map(serialize(_,None)).toList)))
case eb: EmptyBox =>
val message = (eb ?~ ("Could not fetch Parameters")).msg
toJsonError(None, message)
}
}
def createParameter(restParameter: Box[RestParameter], parameterName : ParameterName, req:Req) = {
implicit val action = "createParameter"
implicit val prettify = restExtractor.extractPrettify(req.params)
val modId = ModificationId(uuidGen.newUuid)
val actor = RestUtils.getActor(req)
restParameter match {
case Full(restParameter) =>
val parameter = restParameter.updateParameter(GlobalParameter(parameterName,"","",false))
val diff = AddGlobalParameterDiff(parameter)
createChangeRequestAndAnswer(
parameterName.value
, diff
, parameter
, None
, actor
, req
, "Create"
)
case eb : EmptyBox =>
val fail = eb ?~ (s"Could extract values from request" )
val message = s"Could not create Parameter ${parameterName.value} cause is: ${fail.msg}."
toJsonError(Some(parameterName.value), message)
}
}
def parameterDetails(id:String, req:Req) = {
implicit val action = "parameterDetails"
implicit val prettify = restExtractor.extractPrettify(req.params)
readParameter.getGlobalParameter(ParameterName(id)) match {
case Full(parameter) =>
val jsonParameter = List(serialize(parameter,None))
toJsonResponse(Some(id),("parameters" -> JArray(jsonParameter)))
case eb:EmptyBox =>
val fail = eb ?~!(s"Could not find Parameter ${id}" )
val message= s"Could not get Parameter ${id} details cause is: ${fail.msg}."
toJsonError(Some(id), message)
}
}
def deleteParameter(id:String, req:Req) = {
implicit val action = "deleteParameter"
implicit val prettify = restExtractor.extractPrettify(req.params)
val modId = ModificationId(uuidGen.newUuid)
val actor = RestUtils.getActor(req)
val parameterId = ParameterName(id)
readParameter.getGlobalParameter(parameterId) match {
case Full(parameter) =>
val deleteParameterDiff = DeleteGlobalParameterDiff(parameter)
createChangeRequestAndAnswer(id, deleteParameterDiff, parameter, Some(parameter), actor, req, "Delete")
case eb:EmptyBox =>
val fail = eb ?~ (s"Could not find Parameter ${parameterId.value}" )
val message = s"Could not delete Parameter ${parameterId.value} cause is: ${fail.msg}."
toJsonError(Some(parameterId.value), message)
}
}
def updateParameter(id: String, req: Req, restValues : Box[RestParameter]) = {
implicit val action = "updateParameter"
implicit val prettify = restExtractor.extractPrettify(req.params)
val modId = ModificationId(uuidGen.newUuid)
val actor = getActor(req)
val parameterId = ParameterName(id)
logger.info(req)
readParameter.getGlobalParameter(parameterId) match {
case Full(parameter) =>
restValues match {
case Full(restParameter) =>
val updatedParameter = restParameter.updateParameter(parameter)
val diff = ModifyToGlobalParameterDiff(updatedParameter)
createChangeRequestAndAnswer(id, diff, updatedParameter, Some(parameter), actor, req, "Update")
case eb : EmptyBox =>
val fail = eb ?~ (s"Could extract values from request" )
val message = s"Could not modify Parameter ${parameterId.value} cause is: ${fail.msg}."
toJsonError(Some(parameterId.value), message)
}
case eb:EmptyBox =>
val fail = eb ?~ (s"Could not find Parameter ${parameterId.value}" )
val message = s"Could not modify Parameter ${parameterId.value} cause is: ${fail.msg}."
toJsonError(Some(parameterId.value), message)
}
}
} | Kegeruneku/rudder | rudder-web/src/main/scala/com/normation/rudder/web/rest/parameters/ParameterApiService2.scala | Scala | agpl-3.0 | 9,431 |
/*
* This file is part of KatLib, licensed under the MIT License (MIT).
*
* Copyright (c) 2016 Katrix
*
* 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 io.github.katrix.katlib.command
import java.util.{Locale, Optional}
import scala.util.Try
import org.spongepowered.api.command.spec.{CommandExecutor, CommandSpec}
import org.spongepowered.api.command.{CommandException, CommandSource}
import org.spongepowered.api.text.Text
import org.spongepowered.api.text.format.TextColors._
import io.github.katrix.katlib.KatPlugin
import io.github.katrix.katlib.helper.Implicits._
import io.github.katrix.katlib.i18n.{KLResource, Localized}
abstract class CommandBase(val parent: Option[CommandBase])(implicit plugin: KatPlugin) extends CommandExecutor {
def commandSpec: CommandSpec
def aliases: Seq[String]
def children: Seq[CommandBase] = Nil
def description(src: CommandSource): Option[Text] = commandSpec.getShortDescription(src).toOption
def extendedDescription(src: CommandSource): Option[Text] =
Try {
CommandBase.extendedDescriptionField.flatMap {
_.get(commandSpec) match {
case opt: Optional[Text @unchecked] =>
opt.orElse(null) match {
case t: Text => Option(t)
case _ => None
}
case t: Text => Option(t)
case _ => None
}
}
}.toOption.flatten
def usage(src: CommandSource): Text = commandSpec.getUsage(src)
def help(src: CommandSource): Text = {
val builder = Text.builder
val desc = description(src)
desc.foreach(builder.append(_, Text.NEW_LINE))
builder.append(usage(src))
extendedDescription(src).foreach(builder.append(Text.NEW_LINE, _))
builder.build
}
def registerHelp(): Unit = {
plugin.pluginCmd.cmdHelp.registerCommandHelp(this)
children.foreach(_.registerHelp())
}
protected def registerSubcommands(builder: CommandSpec.Builder): Unit =
children.foreach(command => builder.child(command.commandSpec, command.aliases: _*))
def nonPlayerErrorLocalized(implicit locale: Locale): CommandException =
new CommandException(t"$RED${KLResource.get("command.error.nonPlayer")}")
def playerNotFoundErrorLocalized(implicit locale: Locale): CommandException =
new CommandException(t"$RED${KLResource.get("command.error.playerNotFound")}")
def invalidParameterErrorLocalized(implicit locale: Locale): CommandException =
new CommandException(t"$RED${KLResource.get("command.error.invalidParameter")}")
@Deprecated
def nonPlayerError: CommandException = CommandBase.nonPlayerError
@Deprecated
def playerNotFoundError: CommandException = CommandBase.playerNotFoundError
@Deprecated
def notFoundError(notFound: String, lookFor: String): CommandException = CommandBase.notFoundError(notFound, lookFor)
@Deprecated
def invalidParameterError: CommandException = CommandBase.invalidParameterError
}
object CommandBase {
private val extendedDescriptionField = Option(classOf[CommandSpec].getField("extendedDescription"))
def nonPlayerErrorLocalized(implicit locale: Locale): CommandException =
new CommandException(t"$RED${KLResource.get("command.error.nonPlayer")}")
def playerNotFoundErrorLocalized(implicit locale: Locale): CommandException =
new CommandException(t"$RED${KLResource.get("command.error.playerNotFound")}")
def invalidParameterErrorLocalized(implicit locale: Locale): CommandException =
new CommandException(t"$RED${KLResource.get("command.error.invalidParameter")}")
@Deprecated
def nonPlayerError: CommandException = nonPlayerErrorLocalized(Localized.Default)
@Deprecated
def playerNotFoundError: CommandException = playerNotFoundErrorLocalized(Localized.Default)
@Deprecated
def notFoundError(notFound: String, lookFor: String): CommandException =
new CommandException(t"$RED$notFound $lookFor was not found")
@Deprecated
def invalidParameterError: CommandException = invalidParameterErrorLocalized(Localized.Default)
implicit class RichCommandSpecBuilder(val builder: CommandSpec.Builder) extends AnyVal {
def children(commandBase: CommandBase): CommandSpec.Builder = {
commandBase.registerSubcommands(builder)
builder
}
}
}
| Katrix-/KatLib | katLib/shared/src/main/scala/io/github/katrix/katlib/command/CommandBase.scala | Scala | mit | 5,270 |
// Let's rewrite functionally!
object Main extends App {
import Color._
import IO._
case class Person(name: String, age: Int, color: Color)
// why do we need: .right.toOption and .flatten?
val people : Seq[Person] = (1 to 3).toList.map { _ => readPerson.right.toOption }.flatten
printPerson((people.maxBy(_.age)))
def readPerson : Either[String,Person] = {
print("enter a name: ")
val name = getLine
print("enter an age: ")
for {
age <- toAge(getLine).right
_ <- Right(print("enter a color: ")).right
color <- toColor(getLine).right
} yield Person(name, age, color)
}
def toAge(s: String) : Either[String,Int] = {
try {
val i = Integer.parseInt(s)
Right(i)
} catch {
case e: Exception => Left("invalid age")
}
}
def toColor(s : String) : Either[String, Color] = {
if( s == "red" ) {
Right(Red)
} else if (s == "green" ){
Right(Green)
} else if( s == "blue") {
Right(Blue)
} else {
Left("invalid color")
}
}
def printPerson(p: Person) = {
println(p.name + " is " + p.age + " years old; " + p.name + "'s favorite color is " + p.color)
}
}
object IO {
val scan = new java.util.Scanner( System.in )
def getLine = scan.nextLine
}
object Color extends Enumeration {
type Color = Value
val Red, Blue, Green = Value
}
| leeavital/scala-examples | seven.scala | Scala | cc0-1.0 | 1,379 |
package org.apache.spark.api.ruby
import scala.collection.JavaConverters._
import scala.reflect.{ClassTag, classTag}
import org.apache.spark.api.java.JavaRDD
import org.apache.spark.api.ruby.marshal._
/* =================================================================================================
* object RubySerializer
* =================================================================================================
*/
object RubySerializer { }
| ondra-m/ruby-spark | ext/spark/src/main/scala/RubySerializer.scala | Scala | mit | 462 |
package mesosphere.marathon.storage.migration
import akka.Done
import akka.stream.scaladsl.Source
import com.codahale.metrics.MetricRegistry
import mesosphere.AkkaUnitTest
import mesosphere.marathon.Protos.StorageVersion
import mesosphere.marathon.core.storage.store.PersistenceStore
import mesosphere.marathon.metrics.Metrics
import mesosphere.marathon.storage.LegacyStorageConfig
import mesosphere.marathon.storage.migration.StorageVersions._
import mesosphere.marathon.storage.repository.legacy.store.{ InMemoryEntity, PersistentEntity, PersistentStore, PersistentStoreManagement }
import mesosphere.marathon.storage.repository.{ AppRepository, DeploymentRepository, EventSubscribersRepository, FrameworkIdRepository, GroupRepository, TaskFailureRepository, TaskRepository }
import mesosphere.marathon.test.Mockito
import org.scalatest.GivenWhenThen
import scala.concurrent.Future
class MigrationTest extends AkkaUnitTest with Mockito with GivenWhenThen {
implicit private def metrics = new Metrics(new MetricRegistry)
def migration(
legacyConfig: Option[LegacyStorageConfig] = None,
persistenceStore: Option[PersistenceStore[_, _, _]] = None,
appRepository: AppRepository = mock[AppRepository],
groupRepository: GroupRepository = mock[GroupRepository],
deploymentRepository: DeploymentRepository = mock[DeploymentRepository],
taskRepository: TaskRepository = mock[TaskRepository],
taskFailureRepository: TaskFailureRepository = mock[TaskFailureRepository],
frameworkIdRepository: FrameworkIdRepository = mock[FrameworkIdRepository],
eventSubscribersRepository: EventSubscribersRepository = mock[EventSubscribersRepository]): Migration = {
new Migration(legacyConfig, persistenceStore, appRepository, groupRepository, deploymentRepository,
taskRepository, taskFailureRepository, frameworkIdRepository, eventSubscribersRepository)
}
val currentVersion = if (StorageVersions.current < StorageVersions(1, 3, 0)) {
StorageVersions(1, 3, 0)
} else {
StorageVersions.current
}
"Migration" should {
"be filterable by version" in {
val migrate = migration()
val all = migrate.migrations.filter(_._1 > StorageVersions(0, 0, 0)).sortBy(_._1)
all should have size migrate.migrations.size.toLong
val none = migrate.migrations.filter(_._1 > StorageVersions(Int.MaxValue, 0, 0, StorageVersion.StorageFormat.PERSISTENCE_STORE))
none should be('empty)
val some = migrate.migrations.filter(_._1 < StorageVersions(0, 10, 0))
some should have size 1
}
"migrate on an empty database will set the storage version" in {
val mockedStore = mock[PersistenceStore[_, _, _]]
val migrate = migration(persistenceStore = Option(mockedStore))
mockedStore.storageVersion() returns Future.successful(None)
mockedStore.setStorageVersion(any) returns Future.successful(Done)
migrate.migrate()
verify(mockedStore).storageVersion()
verify(mockedStore).setStorageVersion(StorageVersions.current)
noMoreInteractions(mockedStore)
}
"migrate on an empty legacy database will set the storage version" in {
val legacyConfig = mock[LegacyStorageConfig]
val mockedPersistentStore = mock[PersistentStore]
mockedPersistentStore.load(Migration.StorageVersionName) returns Future.successful(None)
mockedPersistentStore.create(eq(Migration.StorageVersionName), eq(StorageVersions.current.toByteArray)) returns
Future.successful(mock[PersistentEntity])
legacyConfig.store returns mockedPersistentStore
val migrate = migration(legacyConfig = Some(legacyConfig), persistenceStore = None)
migrate.migrate()
verify(mockedPersistentStore, times(2)).load(Migration.StorageVersionName)
verify(mockedPersistentStore).create(Migration.StorageVersionName, StorageVersions.current.toByteArray)
noMoreInteractions(mockedPersistentStore)
}
"migrate on a database with the same version will do nothing" in {
val mockedStore = mock[PersistenceStore[_, _, _]]
val migrate = migration(persistenceStore = Option(mockedStore))
val currentPersistenceVersion =
StorageVersions.current.toBuilder.setFormat(StorageVersion.StorageFormat.PERSISTENCE_STORE).build()
mockedStore.storageVersion() returns Future.successful(Some(currentPersistenceVersion))
migrate.migrate()
verify(mockedStore).storageVersion()
noMoreInteractions(mockedStore)
}
"migrate on a legacy database with the same version will do nothing" in {
val legacyConfig = mock[LegacyStorageConfig]
val mockedPersistentStore = mock[PersistentStore]
val currentVersionEntity = InMemoryEntity(Migration.StorageVersionName, 0, StorageVersions(1, 4, 0).toByteArray)
mockedPersistentStore.load(Migration.StorageVersionName) returns Future.successful(Some(currentVersionEntity))
legacyConfig.store returns mockedPersistentStore
val migrate = migration(legacyConfig = Some(legacyConfig), persistenceStore = None)
migrate.migrate()
verify(mockedPersistentStore).load(Migration.StorageVersionName)
noMoreInteractions(mockedPersistentStore)
}
"migrate throws an error for early unsupported versions" in {
val mockedStore = mock[PersistenceStore[_, _, _]]
val migrate = migration(persistenceStore = Option(mockedStore))
val minVersion = migrate.minSupportedStorageVersion
Given("An unsupported storage version")
val unsupportedVersion = StorageVersions(0, 2, 0)
mockedStore.storageVersion() returns Future.successful(Some(unsupportedVersion))
When("migrate is called for that version")
val ex = intercept[RuntimeException] {
migrate.migrate()
}
Then("Migration exits with a readable error message")
ex.getMessage should equal (s"Migration from versions < ${minVersion.str} are not supported. Your version: ${unsupportedVersion.str}")
}
"migrate throws an error for versions > current" in {
val mockedStore = mock[PersistenceStore[_, _, _]]
val migrate = migration(persistenceStore = Option(mockedStore))
val minVersion = migrate.minSupportedStorageVersion
Given("An unsupported storage version")
val unsupportedVersion = StorageVersions(Int.MaxValue, Int.MaxValue, Int.MaxValue, StorageVersion.StorageFormat.PERSISTENCE_STORE)
mockedStore.storageVersion() returns Future.successful(Some(unsupportedVersion))
When("migrate is called for that version")
val ex = intercept[RuntimeException] {
migrate.migrate()
}
Then("Migration exits with a readable error message")
ex.getMessage should equal (s"Migration from ${unsupportedVersion.str} is not supported as it is newer than ${StorageVersions.current.str}.")
}
"migrate throws an error if using legacy store with a PersistenceStore version" in {
val legacyConfig = mock[LegacyStorageConfig]
val mockedPersistentStore = mock[PersistentStore]
legacyConfig.store returns mockedPersistentStore
Given("An unsupported storage version")
val unsupportedVersion = StorageVersions.current.toBuilder.setFormat(StorageVersion.StorageFormat.PERSISTENCE_STORE).build()
val entity = InMemoryEntity(Migration.StorageVersionName, 0, unsupportedVersion.toByteArray)
mockedPersistentStore.load(Migration.StorageVersionName) returns Future.successful(Some(entity))
val migrate = migration(Some(legacyConfig), None)
When("migrate is called for that version")
val ex = intercept[RuntimeException] {
migrate.migrate()
}
Then("Migration exits with a readable error message")
ex.getMessage should equal ("Migration from this storage format back to the legacy storage format" +
" is not supported.")
}
"initializes and closes the persistent store when performing a legacy migration" in {
val legacyConfig = mock[LegacyStorageConfig]
trait Store extends PersistentStore with PersistentStoreManagement
val mockedPersistentStore = mock[Store]
val currentVersionEntity = InMemoryEntity(Migration.StorageVersionName, 0, StorageVersions(1, 4, 0).toByteArray)
mockedPersistentStore.initialize() returns Future.successful(())
mockedPersistentStore.close() returns Future.successful(Done)
mockedPersistentStore.load(Migration.StorageVersionName) returns Future.successful(Some(currentVersionEntity))
legacyConfig.store returns mockedPersistentStore
val migrate = migration(legacyConfig = Some(legacyConfig))
migrate.migrate()
verify(mockedPersistentStore).initialize()
verify(mockedPersistentStore).close()
verify(mockedPersistentStore).load(Migration.StorageVersionName)
noMoreInteractions(mockedPersistentStore)
}
"migrations are executed sequentially" in {
val mockedStore = mock[PersistenceStore[_, _, _]]
mockedStore.storageVersion() returns Future.successful(Some(StorageVersions(0, 8, 0)))
mockedStore.versions(any)(any) returns Source.empty
mockedStore.ids()(any) returns Source.empty
mockedStore.get(any)(any, any) returns Future.successful(None)
mockedStore.get(any, any)(any, any) returns Future.successful(None)
mockedStore.store(any, any)(any, any) returns Future.successful(Done)
mockedStore.store(any, any, any)(any, any) returns Future.successful(Done)
mockedStore.setStorageVersion(any) returns Future.successful(Done)
val migrate = migration(persistenceStore = Some(mockedStore))
val result = migrate.migrate()
result should be ('nonEmpty)
result should be(migrate.migrations.drop(1).map(_._1))
}
}
}
| timcharper/marathon | src/test/scala/mesosphere/marathon/storage/migration/MigrationTest.scala | Scala | apache-2.0 | 9,766 |
/*
* 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.profile
import es.tid.cosmos.api.profile.dao.ProfileDataStore
/** Utilities for setting up users on integration tests. */
object CosmosProfileTestHelpers {
/** Generates a registration object given a handle.
* The rest of the fields are generated by plugin in the handle into dummy
* domains or keys.
*
* @param handle Handle for the registration
* @return A complete registration object
*/
def registrationFor(handle: String): Registration = {
val email = s"[email protected]"
Registration(
handle = handle,
publicKey = s"ssh-rsa AAAAAA $email",
email = email
)
}
/** Generates a user id based on a keyword.
*
* @param keyword To fill in the auth id
* @return A user id on the default realm
*/
def userIdFor(keyword: String): UserId = UserId(s"id-$keyword")
/** Registers a new user by generating dummy data based on the handle.
* See registrationFor and userIdFor methods for more details.
*
* @param handle Handle to base the dummy info generation on
* @param store Where to create the user in
* @return The newly created profile
*
* @see [[es.tid.cosmos.api.profile.CosmosProfileTestHelpers$#registrationFor]]
* @see [[es.tid.cosmos.api.profile.CosmosProfileTestHelpers$#userIdFor]]
*/
def registerUser(handle: String)(implicit store: ProfileDataStore): CosmosProfile =
store.withTransaction { implicit c =>
registerUser(store, handle)
}
/** Overload of `registerUser` that uses a given transaction/connection.
*
* As this is intended for testing isolated from a ServiceManager implementation the user
* is created directly as an enabled one.
*
* Note that `dao` and `c` should be in different argument groups to satisfy type checking.
*
* @param store Where to create the user in
* @param handle Handle to base the dummy info generation on
* @param c Connection/transaction to do the changes on
* @return The newly created profile
*/
def registerUser(store: ProfileDataStore, handle: String)
(implicit c: store.Conn): CosmosProfile = store.profile.register(
userId = userIdFor(handle),
reg = registrationFor(handle),
state = UserState.Enabled
)
/** Lookup a user profile by their handle.
*
* @param handle The user's handle
* @param store The store to use
* @return The profile iff found
*/
def lookup(handle: String)(implicit store: ProfileDataStore): Option[CosmosProfile] =
store.withTransaction{ implicit c =>
lookup(store, handle)
}
/** Overload of `lookup` that uses a given transaction/connection
*
* @param store The store to use
* @param handle The user's handle
* @param c Connection/transaction to do the changes on
* @return The profile iff found
*/
def lookup(store: ProfileDataStore, handle: String)
(implicit c: store.Conn): Option[CosmosProfile] =
store.profile.lookupByUserId(userIdFor(handle))
}
| telefonicaid/fiware-cosmos-platform | cosmos-api/test/es/tid/cosmos/api/profile/CosmosProfileTestHelpers.scala | Scala | apache-2.0 | 3,758 |
// scalastyle:off line.size.limit
/*
* Ported by Alistair Johnson from
* https://github.com/gwtproject/gwt/blob/master/user/test/com/google/gwt/emultest/java/math/BigIntegerOperateBitsTest.java
*/
// scalastyle:on line.size.limit
package org.scalajs.testsuite.javalib.math
import java.math.BigInteger
import org.junit.Test
import org.junit.Assert._
import org.scalajs.testsuite.utils.AssertThrows._
class BigIntegerOperateBitsTest {
@Test def testBitCountNeg(): Unit = {
val aNumber = new BigInteger("-12378634756382937873487638746283767238657872368748726875")
assertEquals(87, aNumber.bitCount())
}
@Test def testBitCountPos(): Unit = {
val aNumber = new BigInteger("12378634756343564757582937873487638746283767238657872368748726875")
assertEquals(107, aNumber.bitCount())
}
@Test def testBitCountZero(): Unit = {
val aNumber = new BigInteger("0")
assertEquals(0, aNumber.bitCount())
}
@Test def testBitLengthNegative1(): Unit = {
val aBytes = Array[Byte](12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91)
val aSign = -1
val aNumber = new BigInteger(aSign, aBytes)
assertEquals(108, aNumber.bitLength())
}
@Test def testBitLengthNegative2(): Unit = {
val aBytes = Array[Byte](-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val aNumber = new BigInteger(aSign, aBytes)
assertEquals(96, aNumber.bitLength())
}
@Test def testBitLengthNegative3(): Unit = {
val aBytes = Array[Byte](1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
val aSign = -1
val aNumber = new BigInteger(aSign, aBytes)
assertEquals(80, aNumber.bitLength())
}
@Test def testBitLengthPositive1(): Unit = {
val aBytes = Array[Byte](12, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26, 3, 91)
val aSign = 1
val aNumber = new BigInteger(aSign, aBytes)
assertEquals(108, aNumber.bitLength())
}
@Test def testBitLengthPositive2(): Unit = {
val aBytes = Array[Byte](-128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val aNumber = new BigInteger(aSign, aBytes)
assertEquals(96, aNumber.bitLength())
}
@Test def testBitLengthPositive3(): Unit = {
val aBytes = Array[Byte](1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
val aSign = 1
val aNumber = new BigInteger(aSign, aBytes)
assertEquals(81, aNumber.bitLength())
}
@Test def testBitLengthZero(): Unit = {
val aNumber = new BigInteger("0")
assertEquals(0, aNumber.bitLength())
}
@Test def testClearBitException(): Unit = {
val aBytes = Array[Byte](-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = -7
val aNumber = new BigInteger(aSign, aBytes)
expectThrows(classOf[ArithmeticException], aNumber.clearBit(number))
}
@Test def testClearBitNegativeInside1(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 15
val rBytes = Array[Byte](-2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, 92, -26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.clearBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testClearBitNegativeInside2(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 44
val rBytes = Array[Byte](-2, 127, -57, -101, 1, 75, -90, -62, -92, -4, 14, -36, -26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.clearBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testClearBitNegativeInside3(): Unit = {
val as = "-18446744073709551615"
val number = 2
val aNumber = new BigInteger(as)
val result = aNumber.clearBit(number)
assertEquals(result.toString, as)
}
@Test def testClearBitNegativeInside4(): Unit = {
val as = "-4294967295"
val res = "-4294967296"
val number = 0
val aNumber = new BigInteger(as)
val result = aNumber.clearBit(number)
assertEquals(result.toString, res)
}
@Test def testClearBitNegativeInside5(): Unit = {
val as = "-18446744073709551615"
val res = "-18446744073709551616"
val number = 0
val aNumber = new BigInteger(as)
val result = aNumber.clearBit(number)
assertEquals(result.toString, res)
}
@Test def testClearBitNegativeOutside1(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 150
val rBytes = Array[Byte](-65, -1, -1, -1, -1, -1, -2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.clearBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testClearBitNegativeOutside2(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 165
val rBytes = Array[Byte](-33, -1, -1, -1, -1, -1, -1, -1, -2, 127, -57,
-101, 1, 75, -90, -46, -92, -4, 14, -36, -26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.clearBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testClearBitPositiveInside1(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 20
val rBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -31, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.clearBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testClearBitPositiveInside2(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 17
val rBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.clearBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testClearBitPositiveInside3(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 45
val rBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 13, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.clearBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testClearBitPositiveInside4(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 50
val rBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.clearBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testClearBitPositiveInside5(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 63
val rBytes = Array[Byte](1, -128, 56, 100, -2, 52, 89, 45, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.clearBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testClearBitPositiveOutside1(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 150
val rBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.clearBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testClearBitPositiveOutside2(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 191
val rBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.clearBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testClearBitTopNegative(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -15, 35, 26)
val aSign = -1
val number = 63
val rBytes = Array[Byte](-1, 127, -2, 127, -57, -101, 14, -36, -26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.clearBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testClearBitZero(): Unit = {
val aBytes = Array[Byte](0)
val aSign = 0
val number = 0
val rBytes = Array[Byte](0)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.clearBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(0, result.signum())
}
@Test def testClearBitZeroOutside1(): Unit = {
val aBytes = Array[Byte](0)
val aSign = 0
val number = 95
val rBytes = Array[Byte](0)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.clearBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(0, result.signum())
}
@Test def testFlipBitException(): Unit = {
val aBytes = Array[Byte](-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = -7
val aNumber = new BigInteger(aSign, aBytes)
expectThrows(classOf[ArithmeticException], aNumber.flipBit(number))
}
@Test def testFlipBitLeftmostNegative(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -15, 35, 26)
val aSign = -1
val number = 48
val rBytes = Array[Byte](-1, 127, -57, -101, 14, -36, -26, 49)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.flipBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testFlipBitLeftmostPositive(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -15, 35, 26)
val aSign = 1
val number = 48
val rBytes = Array[Byte](0, -128, 56, 100, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.flipBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testFlipBitNegativeInside1(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 15
val rBytes = Array[Byte](-2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, 92, -26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.flipBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testFlipBitNegativeInside2(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 45
val rBytes = Array[Byte](-2, 127, -57, -101, 1, 75, -90, -14, -92, -4, 14, -36, -26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.flipBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testFlipBitNegativeInside3(): Unit = {
val as = "-18446744073709551615"
val res = "-18446744073709551611"
val number = 2
val aNumber = new BigInteger(as)
val result = aNumber.flipBit(number)
assertEquals(result.toString, res)
}
@Test def testFlipBitNegativeInside4(): Unit = {
val as = "-4294967295"
val res = "-4294967296"
val number = 0
val aNumber = new BigInteger(as)
val result = aNumber.flipBit(number)
assertEquals(result.toString, res)
}
@Test def testFlipBitNegativeInside5(): Unit = {
val as = "-18446744073709551615"
val res = "-18446744073709551616"
val number = 0
val aNumber = new BigInteger(as)
val result = aNumber.flipBit(number)
assertEquals(result.toString, res)
}
@Test def testFlipBitNegativeOutside1(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 150
val rBytes = Array[Byte](-65, -1, -1, -1, -1, -1, -2, 127, -57, -101, 1,
75, -90, -46, -92, -4, 14, -36, -26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.flipBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testFlipBitNegativeOutside2(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 191
val rBytes = Array[Byte](-1, 127, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.flipBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testFlipBitPositiveInside1(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 15
val rBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, -93, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.flipBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testFlipBitPositiveInside2(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 45
val rBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 13, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.flipBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testFlipBitPositiveOutside1(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 150
val rBytes = Array[Byte](64, 0, 0, 0, 0, 0, 1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.flipBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testFlipBitPositiveOutside2(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 191
val rBytes = Array[Byte](0, -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, -128,
56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.flipBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testFlipBitZero(): Unit = {
val aBytes = Array[Byte](0)
val aSign = 0
val number = 0
val rBytes = Array[Byte](1)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.flipBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testFlipBitZeroOutside1(): Unit = {
val aBytes = Array[Byte](0)
val aSign = 0
val number = 62
val rBytes = Array[Byte](64, 0, 0, 0, 0, 0, 0, 0)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.flipBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testFlipBitZeroOutside2(): Unit = {
val aBytes = Array[Byte](0)
val aSign = 0
val number = 63
val rBytes = Array[Byte](0, -128, 0, 0, 0, 0, 0, 0, 0)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.flipBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testSetBitBug1331(): Unit = {
val result = BigInteger.valueOf(0L).setBit(191)
assertEquals("3138550867693340381917894711603833208051177722232017256448", result.toString)
assertEquals(1, result.signum())
}
@Test def testSetBitException(): Unit = {
val aBytes = Array[Byte](-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = -7
var aNumber = new BigInteger(aSign, aBytes)
expectThrows(classOf[ArithmeticException], aNumber.setBit(number))
}
@Test def testSetBitLeftmostNegative(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -15, 35, 26)
val aSign = -1
val number = 48
val rBytes = Array[Byte](-1, 127, -57, -101, 14, -36, -26, 49)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.setBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testSetBitNegativeInside1(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 15
val rBytes = Array[Byte](-2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.setBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testSetBitNegativeInside2(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 44
val rBytes = Array[Byte](-2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.setBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testSetBitNegativeInside3(): Unit = {
val as = "-18446744073709551615"
val res = "-18446744073709551611"
val number = 2
val aNumber = new BigInteger(as)
val result = aNumber.setBit(number)
assertEquals(result.toString, res)
}
@Test def testSetBitNegativeInside4(): Unit = {
val as = "-4294967295"
val number = 0
val aNumber = new BigInteger(as)
val result = aNumber.setBit(number)
assertEquals(as, result.toString)
}
@Test def testSetBitNegativeInside5(): Unit = {
val as = "-18446744073709551615"
val number = 0
val aNumber = new BigInteger(as)
val result = aNumber.setBit(number)
assertEquals(as, result.toString)
}
@Test def testSetBitNegativeOutside1(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 150
val rBytes = Array[Byte](-2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.setBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testSetBitNegativeOutside2(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 191
val rBytes = Array[Byte](-2, 127, -57, -101, 1, 75, -90, -46, -92, -4, 14, -36, -26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.setBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testSetBitPositiveInside1(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 20
val rBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.setBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testSetBitPositiveInside2(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 17
val rBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -13, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.setBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testSetBitPositiveInside3(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 45
val rBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.setBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testSetBitPositiveInside4(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 50
val rBytes = Array[Byte](1, -128, 56, 100, -2, -76, 93, 45, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.setBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testSetBitPositiveOutside1(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 150
val rBytes = Array[Byte](64, 0, 0, 0, 0, 0, 1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.setBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testSetBitPositiveOutside2(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 223
val rBytes = Array[Byte](0, -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.setBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testSetBitTopPositive(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -15, 35, 26)
val aSign = 1
val number = 63
val rBytes = Array[Byte](0, -128, 1, -128, 56, 100, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.setBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testSetBitZero(): Unit = {
val aBytes = Array[Byte](0)
val aSign = 0
val number = 0
val rBytes = Array[Byte](1)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.setBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testSetBitZeroOutside1(): Unit = {
val aBytes = Array[Byte](0)
val aSign = 0
val number = 95
val rBytes = Array[Byte](0, -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.setBit(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testShiftLeft1(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 0
val rBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.shiftLeft(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testShiftLeft2(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = -27
val rBytes = Array[Byte](48, 7, 12, -97, -42, -117, 37, -85, 96)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.shiftLeft(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testShiftLeft3(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 27
val rBytes = Array[Byte](12, 1, -61, 39, -11, -94, -55, 106, -40, 31, -119, 24, -48, 0, 0, 0)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.shiftLeft(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testShiftLeft4(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 45
val rBytes = Array[Byte](48, 7, 12, -97, -42, -117, 37, -85, 96, 126, 36, 99, 64, 0, 0, 0, 0, 0)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.shiftLeft(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testShiftLeft5(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 45
val rBytes = Array[Byte](-49, -8, -13, 96, 41, 116, -38, 84, -97, -127,
-37, -100, -64, 0, 0, 0, 0, 0)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.shiftLeft(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testShiftRight1(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 0
val rBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.shiftRight(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testShiftRight2(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = -27
val rBytes = Array[Byte](12, 1, -61, 39, -11, -94, -55, 106, -40, 31, -119, 24, -48, 0, 0, 0)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.shiftRight(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testShiftRight3(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 27
val rBytes = Array[Byte](48, 7, 12, -97, -42, -117, 37, -85, 96)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.shiftRight(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testShiftRight4(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 45
val rBytes = Array[Byte](12, 1, -61, 39, -11, -94, -55)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.shiftRight(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(1, result.signum())
}
@Test def testShiftRight5(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 300
val rBytes = Array[Byte](0)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.shiftRight(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(0, result.signum())
}
@Test def testShiftRightNegNonZeroes(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 0, 0, 0, 0, 0, 0, 0, 0)
val aSign = -1
val number = 68
val rBytes = Array[Byte](-25, -4, 121, -80, 20, -70, 109, 42)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.shiftRight(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testShiftRightNegNonZeroesMul32(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 1, 0, 0, 0, 0, 0, 0, 0)
val aSign = -1
val number = 64
val rBytes = Array[Byte](-2, 127, -57, -101, 1, 75, -90, -46, -92)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.shiftRight(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testShiftRightNegZeroes(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 0, 0, 0, 0, 0, 0, 0, 0, 0)
val aSign = -1
val number = 68
val rBytes = Array[Byte](-25, -4, 121, -80, 20, -70, 109, 48)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.shiftRight(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testShiftRightNegZeroesMul32(): Unit = {
val aBytes = Array[Byte](1, -128, 56, 100, -2, -76, 89, 45, 91, 0, 0, 0, 0, 0, 0, 0, 0)
val aSign = -1
val number = 64
val rBytes = Array[Byte](-2, 127, -57, -101, 1, 75, -90, -46, -91)
val aNumber = new BigInteger(aSign, aBytes)
val result = aNumber.shiftRight(number)
var resBytes = Array.ofDim[Byte](rBytes.length)
resBytes = result.toByteArray()
for (i <- 0 until resBytes.length) {
assertEquals(rBytes(i), resBytes(i))
}
assertEquals(-1, result.signum())
}
@Test def testTestBitException(): Unit = {
val aBytes = Array[Byte](-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = -7
val aNumber = new BigInteger(aSign, aBytes)
expectThrows(classOf[ArithmeticException], aNumber.testBit(number))
}
@Test def testTestBitNegative1(): Unit = {
val aBytes = Array[Byte](-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 7
val aNumber = new BigInteger(aSign, aBytes)
assertTrue(aNumber.testBit(number))
}
@Test def testTestBitNegative2(): Unit = {
val aBytes = Array[Byte](-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 45
val aNumber = new BigInteger(aSign, aBytes)
assertTrue(!aNumber.testBit(number))
}
@Test def testTestBitNegative3(): Unit = {
val aBytes = Array[Byte](-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = -1
val number = 300
val aNumber = new BigInteger(aSign, aBytes)
assertTrue(aNumber.testBit(number))
}
@Test def testTestBitPositive1(): Unit = {
val aBytes = Array[Byte](-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 7
val aNumber = new BigInteger(aSign, aBytes)
assertTrue(!aNumber.testBit(number))
}
@Test def testTestBitPositive2(): Unit = {
val aBytes = Array[Byte](-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 45
val aNumber = new BigInteger(aSign, aBytes)
assertTrue(aNumber.testBit(number))
}
@Test def testTestBitPositive3(): Unit = {
val aBytes = Array[Byte](-1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26)
val aSign = 1
val number = 300
val aNumber = new BigInteger(aSign, aBytes)
assertTrue(!aNumber.testBit(number))
}
}
| lrytz/scala-js | test-suite/shared/src/test/scala/org/scalajs/testsuite/javalib/math/BigIntegerOperateBitsTest.scala | Scala | bsd-3-clause | 38,218 |
/*
* Copyright 2014-2015 Websudos Ltd, Sphonic Ltd. All Rights Reserved.
*
* 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.websudos.phantom.connectors
/**
* Entry point for defining a keySpace based
* on a single contact point (Cassandra node).
*
* Using a single contact point only is usually
* only recommended for testing purposes.
*/
object ContactPoint {
/**
* Cassandra's default ports.
*/
object DefaultPorts {
val live = 9042
val embedded = 9142
}
/**
* A keyspace builder based on a single
* contact point running on the default
* port on localhost.
*/
lazy val local = apply(DefaultPorts.live)
/**
* A keyspace builder based on a single
* contact point running on the default
* port of embedded Cassandra.
*/
lazy val embedded = apply(DefaultPorts.embedded)
/**
* A keyspace builder based on a single
* contact point running on the specified
* port on localhost.
*/
def apply(port: Int): KeySpaceBuilder = apply("localhost", port)
/**
* A keyspace builder based on a single
* contact point running on the specified
* host and port.
*/
def apply(host: String, port: Int): KeySpaceBuilder =
new KeySpaceBuilder(_.addContactPoint(host).withPort(port))
}
/**
* Entry point for defining a keySpace based
* on multiple contact points (Cassandra nodes).
*
* Even though the Cassandra driver technically only
* needs a single contact point and will then fetch
* the metadata for all other Cassandra nodes, it is
* recommended to specify more than just one contact
* point in case one node is down the moment the driver
* initializes.
*
* Since the driver finds additional nodes on its own,
* the initial list of contact points only needs to be
* updated when you remove one of the specified contact
* points, not when merely adding new nodes to the cluster.
*/
object ContactPoints {
/**
* A keyspace builder based on the specified
* contact points, all running on the default port.
*/
def apply(hosts: Seq[String]): KeySpaceBuilder =
new KeySpaceBuilder(_.addContactPoints(hosts:_*))
/**
* A keyspace builder based on the specified
* contact points, all running on the specified port.
*/
def apply(hosts: Seq[String], port: Int): KeySpaceBuilder =
new KeySpaceBuilder(_.addContactPoints(hosts:_*).withPort(port))
}
| nkijak/phantom | phantom-connectors/src/main/scala/com/websudos/phantom/connectors/ContactPoint.scala | Scala | bsd-2-clause | 2,899 |
package com.arcusys.learn.models
/**
* Created by Iliya Tryapitsin on 13.03.14.
*/
@deprecated
case class BadgeResponse(recipient: String,
issued_on: String,
badge: BadgeModel)
@deprecated
case class BadgeModel(name: String,
image: String,
description: String,
criteria: String,
issuer: IssuerModel,
version: String = "1.0.0")
@deprecated
case class IssuerModel(origin: String,
name: String,
org: String,
contact: String = "[email protected]")
| ViLPy/Valamis | learn-portlet/src/main/scala/com/arcusys/learn/models/BadgeResponse.scala | Scala | lgpl-3.0 | 467 |
package reactivemongo.api.collections
import scala.concurrent.duration.FiniteDuration
import reactivemongo.api.{
ChangeStreams,
Cursor,
CursorProducer,
CursorOptions,
ReadConcern,
SerializationPack
}
trait ChangeStreamOps[P <: SerializationPack] { collection: GenericCollection[P] =>
import collection.AggregationFramework.ChangeStream
/**
* '''EXPERIMENTAL:''' Prepares a builder for watching the [[https://docs.mongodb.com/manual/changeStreams change stream]] of this collection.
*
* '''Note:''' The target mongo instance MUST be a replica-set
* (even in the case of a single node deployement).
*
* {{{
* import reactivemongo.api.Cursor
* import reactivemongo.api.bson.BSONDocument
* import reactivemongo.api.bson.collection.BSONCollection
*
* def events(coll: BSONCollection): Cursor[BSONDocument] =
* coll.watch[BSONDocument]().cursor
* }}}
*
* @since MongoDB 3.6
* @param offset the change stream offset
* @param pipeline The sequence of aggregation stages to apply on events in the stream (see MongoDB documentation for a list of valid stages for a change stream).
* @param maxAwaitTimeMS The maximum amount of time in milliseconds the server waits for new data changes before returning an empty batch. In practice, this parameter controls the duration of the long-polling behavior of the cursor.
* @param fullDocumentStrategy if set to UpdateLookup, every update change event will be joined with the ''current'' version of the relevant document.
* @param reader the reader of the resulting change events
* @tparam T the type into which Change Events are deserialized
*/
final def watch[T](
offset: Option[ChangeStream.Offset] = None,
pipeline: List[PipelineOperator] = Nil,
maxTime: Option[FiniteDuration] = None,
fullDocumentStrategy: Option[ChangeStreams.FullDocumentStrategy] = None)(implicit reader: pack.Reader[T]): WatchBuilder[T] = {
new WatchBuilder[T] {
protected val context: AggregatorContext[T] = aggregatorContext[T](
pipeline = (new ChangeStream(offset, fullDocumentStrategy)) +: pipeline,
readConcern = ReadConcern.Majority,
cursorOptions = CursorOptions.empty.tailable,
maxTime = maxTime)
}
}
/**
* A builder for the `watch` collection helper,
* which allows to consume the collection's ChangeStream.
*/
sealed trait WatchBuilder[T] {
protected val context: AggregatorContext[T]
/**
* Creates a cursor for the changeStream of this collection,
* as configured by the builder.
*
* The resulting cursor implicitly has a `tailable` and `awaitData`
* behavior, and requires some special handling:
*
* 1. The cursor will never be exhausted, unless the change stream is invalidated (see
* [[https://docs.mongodb.com/manual/reference/change-events/#invalidate-event]]).
* Therefore, you need to ensure that either:
* - you consume a bounded number of events from the stream (such as when using `collect`, `foldWhile`, etc.)
* - you close the cursor explicitly when you no longer need it (the cursor provider needs to support such a
* functionality)
* - you only start a finite number of unbounded cursors which follow the lifecycle of your whole application (for
* example they will be shut down along with the driver when the app goes down).
* In particular, using `fold` with the default unbounded `maxSize` will yield a Future which will never resolve.
*
* 2. The cursor may yield no results within any given finite time bounds, if there are no changes in the
* underlying collection. Therefore, the Futures resulting from the cursor operations may never resolve.
* Unless you are in a fully reactive scenario, you may want to add some timeout behavior to the resulting Future.
* In that case, remember to explicitly close the cursor when the timeout triggers, so that you don't leak the
* cursor (the cursor provider needs to support such a functionality).
*
* 3. New change streams return no data when the cursor is initially established (only subsequent GetMore commands
* will actually return the subsequent events). Therefore, such a cursor `head` will always be empty. Only folding
* the cursor (directly or through a higher-level cursor provider) will provide the next change event.
*
* 4. Resumed change streams (via id or operation time) will return the next event when the cursor is initially
* established, if there is is some next event. Therefore, `head` is guaranteed to eventually return the next
* change event beyond the resume point, when such an event appears.
*/
def cursor[AC[U] <: Cursor.WithOps[U]](implicit cp: CursorProducer.Aux[T, AC]): AC[T] = context.prepared[AC].cursor
}
}
| ReactiveMongo/ReactiveMongo | driver/src/main/scala/api/collections/ChangeStreamOps.scala | Scala | apache-2.0 | 4,858 |
/**
* Licensed to the Minutemen Group under one or more contributor license
* agreements. See the COPYRIGHT file distributed with this work for
* additional information regarding copyright ownership.
*
* 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 silhouette.provider.social.state
import io.circe.Json
import org.specs2.concurrent.ExecutionEnv
import org.specs2.matcher.JsonMatchers
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.Scope
import silhouette.crypto.Signer
import silhouette.http._
import silhouette.provider.ProviderException
import silhouette.provider.social.state.DefaultStateHandler._
import silhouette.provider.social.state.StateItem.ItemStructure
import silhouette.specs2.WaitPatience
import scala.concurrent.Future
import scala.util.{ Failure, Success }
/**
* Test case for the [[DefaultStateHandler]] class.
*
* @param ev The execution environment.
*/
class DefaultStateHandlerSpec(implicit ev: ExecutionEnv)
extends Specification
with Mockito
with JsonMatchers
with WaitPatience {
"The `withHandler` method" should {
"return a new state handler with the given item handler added" in new Context {
val newHandler = mock[StateItemHandler].smart
stateHandler.handlers.size must be equalTo 2
stateHandler.withHandler(newHandler).handlers.size must be equalTo 3
}
}
"The `state` method" should {
"return the social state" in new Context {
Default.itemHandler.item returns Future.successful(Default.item)
Publishable.itemHandler.item returns Future.successful(Publishable.item)
stateHandler.state must beEqualTo(state).awaitWithPatience
}
}
"The `serialize` method" should {
"return None if no handler is registered" in new Context {
override val stateHandler = new DefaultStateHandler(Set(), signer)
stateHandler.serialize(state) must beNone
}
"return None if the items are empty" in new Context {
stateHandler.serialize(State(Set())) must beNone
}
"return some serialized social state" in new Context {
Default.itemHandler.canHandle(Publishable.item) returns None
Default.itemHandler.canHandle(Default.item) returns Some(Default.item)
Default.itemHandler.serialize(Default.item) returns Default.structure
Publishable.itemHandler.canHandle(Default.item) returns None
Publishable.itemHandler.canHandle(Publishable.item) returns Some(Publishable.item)
Publishable.itemHandler.serialize(Publishable.item) returns Publishable.structure
stateHandler.serialize(state) must beSome(s"${Publishable.structure.asString}.${Default.structure.asString}")
}
}
"The `unserialize` method" should {
"omit state validation if no handler is registered" in new Context {
override val stateHandler = new DefaultStateHandler(Set(), signer)
stateHandler.unserialize("") must beEqualTo(State(Set())).awaitWithPatience
there was no(signer).extract(any[String]())
}
"throw an Exception for an empty string" in new Context {
stateHandler.unserialize("") must throwA[RuntimeException].like {
case e =>
e.getMessage must startWith("Wrong state format")
}.awaitWithPatience
}
"throw an ProviderException if the serialized item structure cannot be extracted" in new Context {
val serialized = s"some-wired-content"
stateHandler.unserialize(serialized) must throwA[ProviderException].like {
case e =>
e.getMessage must startWith(ItemExtractionError.format(serialized))
}.awaitWithPatience
}
"throw an ProviderException if none of the item handlers can handle the given state" in new Context {
val serialized = s"${Default.structure.asString}"
Default.itemHandler.canHandle(any[ItemStructure]())(any()) returns false
Publishable.itemHandler.canHandle(any[ItemStructure]())(any()) returns false
stateHandler.unserialize(serialized) must throwA[ProviderException].like {
case e =>
e.getMessage must startWith(MissingItemHandlerError.format(Default.structure))
}.awaitWithPatience
}
"return the unserialized social state" in new Context {
val serialized = s"${Default.structure.asString}.${Publishable.structure.asString}"
Default.itemHandler.canHandle(Publishable.structure) returns false
Default.itemHandler.canHandle(Default.structure) returns true
Default.itemHandler.unserialize(Default.structure) returns Future.successful(Default.item)
Publishable.itemHandler.canHandle(Default.structure) returns false
Publishable.itemHandler.canHandle(Publishable.structure) returns true
Publishable.itemHandler.unserialize(Publishable.structure) returns Future.successful(Publishable.item)
stateHandler.unserialize(serialized) must beEqualTo(State(Set(Default.item, Publishable.item))).awaitWithPatience
}
}
"The `publish` method" should {
"should publish the state with the publishable handler that is responsible for the item" in new Context {
val publishedResult = Fake.response.withHeaders(Header("X-PUBLISHED", "true"))
Publishable.itemHandler.publish(Publishable.item, publishedResult) returns publishedResult
Publishable.itemHandler.canHandle(Default.item) returns None
Publishable.itemHandler.canHandle(Publishable.item) returns Some(Publishable.item)
stateHandler.publish(publishedResult, state) must be equalTo publishedResult
}
"should not publish the state if no publishable handler is responsible" in new Context {
val response = Fake.response
Publishable.itemHandler.canHandle(Default.item) returns None
Publishable.itemHandler.canHandle(Publishable.item) returns None
stateHandler.publish(response, state) must be equalTo response
}
}
/**
* The context.
*/
trait Context extends Scope {
/**
* A default handler implementation.
*/
case class DefaultItem() extends StateItem
trait DefaultItemHandler extends StateItemHandler {
type Item = DefaultItem
}
object Default {
val itemHandler = mock[DefaultItemHandler].smart
val item = DefaultItem()
val structure = ItemStructure("default", Json.obj())
}
/**
* A publishable handler implementation.
*/
case class PublishableItem() extends StateItem
trait PublishableItemHandler extends StateItemHandler with PublishableStateItemHandler {
type Item = PublishableItem
}
object Publishable {
val itemHandler = mock[PublishableItemHandler].smart
val item = PublishableItem()
val structure = ItemStructure("publishable", Json.obj())
}
/**
* The request pipeline.
*/
implicit val requestPipeline: RequestPipeline[SilhouetteRequest] = Fake.request
/**
* The signer implementation.
*
* The signer returns the same value as passed to the methods. This is enough for testing.
*/
val signer = {
val c = mock[Signer].smart
c.sign(anyString) answers { p: Any => p.asInstanceOf[String] }
c.extract(anyString) answers { p: Any =>
p.asInstanceOf[String] match {
case "" => Failure(new RuntimeException("Wrong state format"))
case s => Success(s)
}
}
c
}
/**
* The state.
*/
val state = State(Set(Publishable.item, Default.item))
/**
* The state handler to test.
*/
val stateHandler = new DefaultStateHandler(Set(Publishable.itemHandler, Default.itemHandler), signer)
}
}
| mohiva/silhouette | modules/provider-social/src/test/scala/silhouette/provider/social/state/DefaultStateHandlerSpec.scala | Scala | apache-2.0 | 8,143 |
package play.core.j
import play.api.mvc._
import play.templates._
/** Defines a magic helper for Play templates in a Java context. */
object PlayMagicForJava {
import scala.collection.JavaConverters._
import scala.language.implicitConversions
/** Transforms a Play Java `Option` to a proper Scala `Option`. */
implicit def javaOptionToScala[T](x: play.libs.F.Option[T]): Option[T] = x match {
case x: play.libs.F.Some[_] => Some(x.get)
case x: play.libs.F.None[_] => None
}
implicit def implicitJavaLang: play.api.i18n.Lang = {
try {
play.mvc.Http.Context.Implicit.lang.asInstanceOf[play.api.i18n.Lang]
} catch {
case _: Throwable => play.api.i18n.Lang.defaultLang
}
}
/**
* Implicit conversion of a Play Java form `Field` to a proper Scala form `Field`.
*/
implicit def javaFieldtoScalaField(jField: play.data.Form.Field): play.api.data.Field = {
new play.api.data.Field(
null,
jField.name,
jField.constraints.asScala.map { jT =>
jT._1 -> jT._2.asScala
},
Option(jField.format).map(f => f._1 -> f._2.asScala),
jField.errors.asScala.map { jE =>
play.api.data.FormError(
jE.key,
jE.message,
jE.arguments.asScala)
},
Option(jField.value)) {
override def apply(key: String) = {
javaFieldtoScalaField(jField.sub(key))
}
override lazy val indexes = jField.indexes.asScala.toSeq.map(_.toInt)
}
}
implicit def requestHeader: play.api.mvc.RequestHeader = {
play.mvc.Http.Context.Implicit.ctx._requestHeader
}
}
| michaelahlers/team-awesome-wedding | vendor/play-2.2.1/framework/src/play-java/src/main/scala/play/core/TemplateMagicForJava.scala | Scala | mit | 1,609 |
package reductions
import org.scalameter._
import common._
object ParallelCountChangeRunner {
@volatile var seqResult = 0
@volatile var parResult = 0
val standardConfig = config(
Key.exec.minWarmupRuns -> 20,
Key.exec.maxWarmupRuns -> 40,
Key.exec.benchRuns -> 80,
Key.verbose -> true
) withWarmer(new Warmer.Default)
def main(args: Array[String]): Unit = {
val amount = 250
val coins = List(1, 2, 5, 10, 20, 50)
val seqtime = standardConfig measure {
seqResult = ParallelCountChange.countChange(amount, coins)
}
println(s"sequential result = $seqResult")
println(s"sequential count time: $seqtime ms")
def measureParallelCountChange(threshold: ParallelCountChange.Threshold): Unit = {
val fjtime = standardConfig measure {
parResult = ParallelCountChange.parCountChange(amount, coins, threshold)
}
println(s"parallel result = $parResult")
println(s"parallel count time: $fjtime ms")
println(s"speedup: ${seqtime / fjtime}")
}
measureParallelCountChange(ParallelCountChange.moneyThreshold(amount))
measureParallelCountChange(ParallelCountChange.totalCoinsThreshold(coins.length))
measureParallelCountChange(ParallelCountChange.combinedThreshold(amount, coins))
}
}
object ParallelCountChange {
/** Returns the number of ways change can be made from the specified list of
* coins for the specified amount of money.
*/
def countChange(money: Int, coins: List[Int]): Int = {
if (money == 0) 1
else if (money < 0) 0
else {
coins match {
case Nil => 0
case head::tail => countChange(money, tail) + countChange(money - head, coins)
}
}
}
type Threshold = (Int, List[Int]) => Boolean
/** In parallel, counts the number of ways change can be made from the
* specified list of coins for the specified amount of money.
*/
def parCountChange(money: Int, coins: List[Int], threshold: Threshold): Int = {
if (money == 0) 1
else if (money < 0) 0
else {
coins match {
case Nil => 0
case head::tail => {
if (threshold(money, coins)) {
countChange(money, coins)
} else {
val (a, b) = parallel(parCountChange(money, tail, threshold), parCountChange(money - head, coins, threshold))
a + b
}
}
}
}
}
/** Threshold heuristic based on the starting money. */
def moneyThreshold(startingMoney: Int): Threshold =
(money: Int, _) => money <= startingMoney * 2 / 3
/** Threshold heuristic based on the total number of initial coins. */
def totalCoinsThreshold(totalCoins: Int): Threshold =
(_, coins: List[Int]) => coins.length <= totalCoins * 2 / 3
/** Threshold heuristic based on the starting money and the initial list of coins. */
def combinedThreshold(startingMoney: Int, allCoins: List[Int]): Threshold = {
(money: Int, coins: List[Int]) => money * coins.length <= startingMoney * allCoins.length / 2
}
}
| syhan/coursera | parprog1/reductions/src/main/scala/reductions/ParallelCountChange.scala | Scala | gpl-3.0 | 3,034 |
object O
{
def d(t: Top) = t match {
case s: Sub => true
case _ => false
}
def main(args: Array[String]): Unit = {
val c = new AnyRef with C
c.bob().toString + c.bob2().toString
}
}
| som-snytt/dotty | tests/pos/t1107b/O.scala | Scala | apache-2.0 | 208 |
package depress_bender
// Read inputs from System.in, Write outputs to use print.
// Your class name has to be Solution
import math._
import scala.util._
import scala.collection.mutable.{HashMap => Map, HashSet => Set, MutableList => List, Stack}
object Solution {
class Position(val x: Int, val y: Int) {
def ==(p: Position) : Boolean = ==((p.x, p.y))
def ==(p: (Int, Int)): Boolean = x == p._1 && y == p._2
def !=(p: Position) : Boolean = !(==(p))
def !=(p: (Int, Int)): Boolean = !(==(p))
def get(c: Char): Position = c match {
case 'N' => new Position(x, y - 1)
case 'S' => new Position(x, y + 1)
case 'W' => new Position(x - 1, y)
case _ => new Position(x + 1, y)
}
}
class State(var direction: Char, var obstacles: Int, var inverseur: Boolean = false, var biere: Boolean = false) {
def copy: State = new State(direction, obstacles, inverseur, biere)
def ==(s: State): Boolean = direction == s.direction && obstacles == s.obstacles && inverseur == s.inverseur && biere == s.biere
}
class Jeu(val pos: Position, var tpe: Char, var state: Option[State] = None) {
def stateChanged(s: State): Boolean = state match {
case Some(st) => !(st == s)
case None => true
}
}
def main(args: Array[String]) {
//Récupération des données
val dim = readLine.split(" ").map(_.toInt)
val map = new Array[Array[Jeu]](dim(0))
val nPos = new Position(-1, -1)
var (begin, end, t1, t2) = (nPos, nPos, nPos, nPos)
var nbObstacles = 0
for (y <- 0 until dim(0)) {
val s = readLine.toCharArray
map(y) = new Array[Jeu](dim(1))
for (x <- 0 until dim(1)) {
val p = new Position(x, y)
s(x) match {
case '@' => begin = p
case '$' => end = p
case 'T' => if (t1 == nPos) t1 = p else t2 = p
case 'X' => nbObstacles += 1
case _ => {}
}
map(y)(x) = new Jeu(p, s(x))
}
}
// Calcul du parcours
val parcours = new List[String]
var p = begin
val s = new State('S', nbObstacles)
while (p != end) {
val jC = map(p.y)(p.x)
jC.tpe match {
case 'T' => p = if (p == t1) t2 else t1
case 'N' => s.direction = 'N'
case 'S' => s.direction = 'S'
case 'W' => s.direction = 'W'
case 'E' => s.direction = 'E'
case 'B' => s.biere = !s.biere
case 'I' => s.inverseur = !s.inverseur
case _ => {}
}
var pNext = p.get(s.direction)
if (s.biere && map(pNext.y)(pNext.x).tpe == 'X') {
map(pNext.y)(pNext.x).tpe = ' '
s.obstacles -= 1
}
if (map(pNext.y)(pNext.x).tpe == '#' || map(pNext.y)(pNext.x).tpe == 'X') {
s.direction = if (s.inverseur) 'W' else 'S'
pNext = p.get(s.direction)
while (map(pNext.y)(pNext.x).tpe == '#' || map(pNext.y)(pNext.x).tpe == 'X') {
if (s.biere && map(pNext.y)(pNext.x).tpe == 'X') {
map(pNext.y)(pNext.x).tpe = ' '
} else {
pNext = p.get(changeDirection(s))
}
}
}
if (!jC.stateChanged(s)) {
println("LOOP")
return
}
jC.state = Some(s.copy)
p = pNext
parcours += nameDirection(s)
}
// Impression chemin
parcours.foreach((e) => println(e))
}
def changeDirection(s: State): Char = {
val d = s.direction match {
case 'S' => if (s.inverseur) 'W' else 'E'
case 'E' => if (s.inverseur) 'S' else 'N'
case 'N' => if (s.inverseur) 'E' else 'W'
case _ => if (s.inverseur) 'N' else 'S'
}
s.direction = d
d
}
def nameDirection(s: State): String = {
s.direction match {
case 'S' => "SOUTH"
case 'N' => "NORTH"
case 'E' => "EAST"
case _ => "WEST"
}
}
}
| bvaudour/codingame | level2/Bender_a_depressed_robot.scala | Scala | gpl-2.0 | 3,847 |
package com.scalaAsm.x86
package Instructions
package General
// Description: Conditional Move - below or equal/not above (CF=1 AND ZF=1)
// Category: general/datamov
trait CMOVNA extends InstructionDefinition {
val mnemonic = "CMOVNA"
}
object CMOVNA extends TwoOperands[CMOVNA] with CMOVNAImpl
trait CMOVNAImpl extends CMOVNA {
implicit object _0 extends TwoOp[r16, rm16] {
val opcode: TwoOpcodes = (0x0F, 0x46) /r
val format = RegRmFormat
}
implicit object _1 extends TwoOp[r32, rm32] {
val opcode: TwoOpcodes = (0x0F, 0x46) /r
val format = RegRmFormat
}
implicit object _2 extends TwoOp[r64, rm64] {
val opcode: TwoOpcodes = (0x0F, 0x46) /r
override def prefix = REX.W(true)
val format = RegRmFormat
}
}
| bdwashbu/scala-x86-inst | src/main/scala/com/scalaAsm/x86/Instructions/General/CMOVNA.scala | Scala | apache-2.0 | 756 |
package skiis2
import java.util.concurrent.Executors
import org.scalatest.WordSpec
import org.scalatest.matchers.ShouldMatchers
import scala.collection._
import java.util.concurrent.atomic.AtomicInteger
@org.junit.runner.RunWith(classOf[org.scalatest.junit.JUnitRunner])
class ParMapSuite extends WordSpec with ShouldMatchers {
import Skiis._
val r = new scala.util.Random
"Skiis" should {
val tortureLevel = Option(System.getenv("TORTURE")) map (_.toInt) getOrElse 1
for (i <- 1 to tortureLevel) {
val context = Skiis.newContext("ParMapSuite",
parallelism = r.nextInt(8) + 8,
queue = r.nextInt(100) + 1,
batch = r.nextInt(10) + 1
)
("parMap %d" format i) in {
val acc1 = new AtomicInteger()
val acc2 = new AtomicInteger()
val acc3 = new AtomicInteger()
val acc4 = new AtomicInteger()
val skiis1 = Skiis(1 to 1000 grouped 25) flatMap { batch =>
acc1.incrementAndGet()
Thread.sleep(r.nextInt(50))
val b = batch map { x => (x, x + 1) }
Skiis(b)
}
val skiis = skiis1.parMap { case (x1, x2) =>
acc2.incrementAndGet()
Thread.sleep(r.nextInt(50))
(x1, x2, x1)
}(context)
skiis foreach { case (x1, x2, x3) =>
x2 should be === (x1 + 1)
x3 should be === (x1)
acc3.incrementAndGet()
acc4.addAndGet(x1)
}
acc1.get should be === 40
acc2.get should be === 1000
acc3.get should be === 1000
acc4.get should be === (1 to 1000).sum
}
("parFlatMap %d" format i) in {
val skiis = Skiis(1 to 1000).parFlatMap { i =>
Thread.sleep(r.nextInt(50))
val len = i % 100
Skiis(1 to len)
}(context)
skiis.force().sum should be === 1666500
}
}
}
}
| teddyknox/skiis | src/test/scala/skiis2/ParMapSuite.scala | Scala | apache-2.0 | 1,890 |
package wow.common.database
import java.sql.ResultSet
import scalikejdbc._
trait EnumerationValueToSqlSyntax[A] {
def apply(value: A): SQLSyntax
}
/**
* Makes an enumeration bindable to database
*/
trait DatabaseSerializableEnumeration {
this: Enumeration =>
/**
* The name of the type in the database server
*/
def typeName: String = SQLSyntaxSupportFactory.camelToSnake(getClass.getSimpleName).trim
/**
* Type binder for enum value
*/
implicit val typeBinder = new TypeBinder[Value] {
override def apply(rs: ResultSet, columnIndex: Int): Value = DatabaseSerializableEnumeration.this
.withName(rs.getString(columnIndex))
override def apply(rs: ResultSet, columnLabel: String): Value = DatabaseSerializableEnumeration.this
.withName(rs.getString(columnLabel))
}
/**
* Provides a cast from value to SqlSyntax
*/
implicit val valueToSqlSyntax = new EnumerationValueToSqlSyntax[Value] {
override def apply(value: Value): scalikejdbc.SQLSyntax = {
sqls"CAST(${value.toString} AS "
.append(SQLSyntax.createUnsafely(typeName))
.append(sqls")")
}
}
}
| SKNZ/SpinaciCore | wow/core/src/main/scala/wow/common/database/DatabaseSerializableEnumeration.scala | Scala | mit | 1,150 |
/*
Copyright 2010 the original author or 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 net.gumbix.hl7dsl.DSL
import org.hl7.rim.{RimObjectFactory, Role, RoleLink, Entity}
import net.gumbix.hl7dsl.helper.ImplicitDef._
import org.hl7.types._
import java.util.ArrayList
import scala.collection.JavaConversions._
import java.util.List
import net.gumbix.hl7dsl.helper.{Address, RimRelationshipOne, RimRelationshipMany}
/**
* Wrapper Class for RIM Class "Role"
* @author Ahmet Gül ([email protected])
*/
class RoleDSL(val role: Role) extends RimDSL(role) {
/**
* @param cloneName Required to navigate through the object graph.
*/
def this() = {
this (RimObjectFactory.getInstance.createRimObject("Role").asInstanceOf[Role])
}
/**
* @return CS
*/
def classCode: CS = role.getClassCode
def classCode_=(v: CS) {
role.setClassCode(v)
}
/**
* @return SET[II]
*/
def id: SET[II] = role.getId
def id_=(id: SET[II]) {
role.setId(id)
}
/**
* @return CE
*/
def code: CE = role.getCode
def code_=(v: CE) {
role.setCode(v)
}
/**
* @return BL
*/
def negationInd: BL = role.getNegationInd
def negationInd_=(v: BL) {
role.setNegationInd(v)
}
/**
* @return BAG[EN]
*/
def name: BAG[EN] = role.getName
def name_=(v: BAG[EN]) {
role.setName(v)
}
/**
* @return BAG[AD]
*/
def addr: Address = {
def addressChanged(a: Address) {
role.setAddr(a.toRSBag)
}
val a = new Address(role.getAddr, addressChanged)
a
}
def addr_=(a: Address) {
// TODO Somehow remember that here was an assignment:
role.setAddr(a.toRSBag)
}
/**
* @return BAG[TEL]
*/
def telecom: BAG[TEL] = role.getTelecom
def telecom_=(v: BAG[TEL]) {
role.setTelecom(v)
}
/**
* @return CS
*/
def statusCode: CS = role.getStatusCode
def statusCode_=(v: CS) {
role.setStatusCode(v)
}
/**
* @return IVL[TS]
*/
def effectiveTime: IVL[TS] = role.getEffectiveTime
def effectiveTime_=(v: IVL[TS]) {
role.setEffectiveTime(v)
}
/**
* @return ED
*/
def certificateText: ED = role.getCertificateText
def certificateText_=(v: ED) {
role.setCertificateText(v)
}
/**
* @return SET[CE]
*/
def confidentialityCode: SET[CE] = role.getConfidentialityCode
def confidentialityCode_=(v: SET[CE]) {
role.setConfidentialityCode(v)
}
/**
* @return LIST[INT]
*/
def positionNumber: LIST[INT] = role.getPositionNumber
def positionNumber_=(v: LIST[INT]) {
role.setPositionNumber(v)
}
val player = {
new RimRelationshipOne[Entity, EntityDSL](
{e => role.setPlayer(e)},
role.getPlayer,
{e => new EntityDSL(e)})
}
val scoper = {
new RimRelationshipOne[Entity, EntityDSL](
{s => role.setScoper(s)},
role.getScoper,
s => new EntityDSL(s)) // TODO
}
// TODO change to new pattern:
/**
* @return RoleLinkDSL
*/
def inboundLink(i: Int) = new RoleLinkDSL(role.getInboundLink.get(i))
/**
* @return List[RoleLinkDSL]
*/
def inboundLink: List[RoleLinkDSL] = {
val list: List[RoleLinkDSL] = new ArrayList[RoleLinkDSL]
(role.getInboundLink).toList.map(a => list.add(new RoleLinkDSL(a)))
list
}
def inboundLink_=(p: RoleLink) {
role.addInboundLink(p)
}
/**
* @return RoleLinkDSL
*/
def outboundLink(i: Int) = new RoleLinkDSL(role.getOutboundLink.get(i))
/**
* @return List[RoleLinkDSL]
*/
def outboundLink: List[RoleLinkDSL] = {
val list: List[RoleLinkDSL] = new ArrayList[RoleLinkDSL]
(role.getOutboundLink).toList.map(a => list.add(new RoleLinkDSL(a)))
list
}
def outboundLink_=(p: RoleLink) {
role.addOutboundLink(p)
}
} | markusgumbel/dshl7 | core/src/main/scala/net/gumbix/hl7dsl/DSL/RoleDSL.scala | Scala | apache-2.0 | 4,280 |
package org.sisioh.aws4s.eb.model
import com.amazonaws.services.elasticbeanstalk.model.{ ListAvailableSolutionStacksResult, SolutionStackDescription }
import org.sisioh.aws4s.PimpedType
import scala.collection.JavaConverters._
object ListAvailableSolutionStacksResultFactory {
def create(): ListAvailableSolutionStacksResult =
new ListAvailableSolutionStacksResult()
}
class RichListAvailableSolutionStacksResult(val underlying: ListAvailableSolutionStacksResult)
extends AnyVal
with PimpedType[ListAvailableSolutionStacksResult] {
def solutionStacks: Seq[String] =
underlying.getSolutionStacks.asScala.toVector
def solutionStacks_=(value: Seq[String]): Unit =
underlying.setSolutionStacks(value.asJava)
def withSolutionStacks_=(value: Seq[String]): ListAvailableSolutionStacksResult =
underlying.withSolutionStacks(value.asJava)
// ----
def solutionStackDetails: Seq[SolutionStackDescription] =
underlying.getSolutionStackDetails.asScala.toVector
def solutionStackDetails_=(value: Seq[SolutionStackDescription]): Unit =
underlying.setSolutionStackDetails(value.asJava)
def withSolutionStackDetails_=(value: Seq[SolutionStackDescription]): ListAvailableSolutionStacksResult =
underlying.withSolutionStackDetails(value.asJava)
}
| sisioh/aws4s | aws4s-eb/src/main/scala/org/sisioh/aws4s/eb/model/RichListAvailableSolutionStacksResult.scala | Scala | mit | 1,294 |
package com.softwaremill.codebrag.domain
import org.bson.types.ObjectId
/**
* Class contains Codebrag's instance global settings, i.e. uniqueId
*/
case class InstanceSettings(uniqueId: String) {
def uniqueIdAsObjectId = new ObjectId(uniqueId)
}
| softwaremill/codebrag | codebrag-domain/src/main/scala/com/softwaremill/codebrag/domain/InstanceSettings.scala | Scala | agpl-3.0 | 251 |
/*
* 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.analysis
import org.apache.spark.sql.AnalysisException
import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.dsl.plans._
import org.apache.spark.sql.catalyst.expressions.{CreateArray, Expression, GetStructField, InSubquery, LateralSubquery, ListQuery, OuterReference, ScalarSubquery}
import org.apache.spark.sql.catalyst.expressions.aggregate.Count
import org.apache.spark.sql.catalyst.plans.{Inner, JoinType}
import org.apache.spark.sql.catalyst.plans.logical._
/**
* Unit tests for [[ResolveSubquery]].
*/
class ResolveSubquerySuite extends AnalysisTest {
val a = 'a.int
val b = 'b.int
val c = 'c.int
val x = 'x.struct(a)
val y = 'y.struct(a)
val t0 = OneRowRelation()
val t1 = LocalRelation(a, b)
val t2 = LocalRelation(b, c)
val t3 = LocalRelation(c)
val t4 = LocalRelation(x, y)
private def lateralJoin(
left: LogicalPlan,
right: LogicalPlan,
joinType: JoinType = Inner,
condition: Option[Expression] = None): LateralJoin =
LateralJoin(left, LateralSubquery(right), joinType, condition)
test("SPARK-17251 Improve `OuterReference` to be `NamedExpression`") {
val expr = Filter(
InSubquery(Seq(a), ListQuery(Project(Seq(UnresolvedAttribute("a")), t2))), t1)
val m = intercept[AnalysisException] {
SimpleAnalyzer.checkAnalysis(SimpleAnalyzer.ResolveSubquery(expr))
}.getMessage
assert(m.contains(
"Expressions referencing the outer query are not supported outside of WHERE/HAVING clauses"))
}
test("SPARK-29145 Support subquery in join condition") {
val expr = Join(t1,
t2,
Inner,
Some(InSubquery(Seq(a), ListQuery(Project(Seq(UnresolvedAttribute("c")), t3)))),
JoinHint.NONE)
assertAnalysisSuccess(expr)
}
test("deduplicate lateral subquery") {
val plan = lateralJoin(t1, t0.select('a))
// The subquery's output OuterReference(a#0) conflicts with the left child output
// attribute a#0. So an alias should be added to deduplicate the subquery's outputs.
val expected = LateralJoin(
t1,
LateralSubquery(Project(Seq(OuterReference(a).as(a.name)), t0), Seq(a)),
Inner,
None)
checkAnalysis(plan, expected)
}
test("lateral join with ambiguous join conditions") {
val plan = lateralJoin(t1, t0.select('b), condition = Some('b === 1))
assertAnalysisError(plan, "Reference 'b' is ambiguous, could be: b, b." :: Nil)
}
test("prefer resolving lateral subquery attributes from the inner query") {
val plan = lateralJoin(t1, t2.select('a, 'b, 'c))
val expected = LateralJoin(
t1,
LateralSubquery(Project(Seq(OuterReference(a).as(a.name), b, c), t2), Seq(a)),
Inner, None)
checkAnalysis(plan, expected)
}
test("qualified column names in lateral subquery") {
val t1b = b.withQualifier(Seq("t1"))
val t2b = b.withQualifier(Seq("t2"))
checkAnalysis(
lateralJoin(t1.as("t1"), t0.select($"t1.b")),
LateralJoin(
t1,
LateralSubquery(Project(Seq(OuterReference(t1b).as(b.name)), t0), Seq(t1b)),
Inner, None)
)
checkAnalysis(
lateralJoin(t1.as("t1"), t2.as("t2").select($"t1.b", $"t2.b")),
LateralJoin(
t1,
LateralSubquery(Project(Seq(OuterReference(t1b).as(b.name), t2b), t2.as("t2")), Seq(t1b)),
Inner, None)
)
}
test("resolve nested lateral subqueries") {
// SELECT * FROM t1, LATERAL (SELECT * FROM (SELECT a, b, c FROM t2), LATERAL (SELECT b, c))
checkAnalysis(
lateralJoin(t1, lateralJoin(t2.select('a, 'b, 'c), t0.select('b, 'c))),
LateralJoin(
t1,
LateralSubquery(
LateralJoin(
Project(Seq(OuterReference(a).as(a.name), b, c), t2),
LateralSubquery(
Project(Seq(OuterReference(b).as(b.name), OuterReference(c).as(c.name)), t0),
Seq(b, c)),
Inner, None),
Seq(a)),
Inner, None)
)
// SELECT * FROM t1, LATERAL (SELECT * FROM t2, LATERAL (SELECT a, b, c))
// TODO: support accessing columns from outer outer query.
assertAnalysisError(
lateralJoin(t1, lateralJoin(t2, t0.select('a, 'b, 'c))),
Seq("cannot resolve 'a' given input columns: []"))
}
test("lateral subquery with unresolvable attributes") {
// SELECT * FROM t1, LATERAL (SELECT a, c)
assertAnalysisError(
lateralJoin(t1, t0.select('a, 'c)),
Seq("cannot resolve 'c' given input columns: []")
)
// SELECT * FROM t1, LATERAL (SELECT a, b, c, d FROM t2)
assertAnalysisError(
lateralJoin(t1, t2.select('a, 'b, 'c, 'd)),
Seq("cannot resolve 'd' given input columns: [b, c]")
)
// SELECT * FROM t1, LATERAL (SELECT * FROM t2, LATERAL (SELECT t1.a))
assertAnalysisError(
lateralJoin(t1, lateralJoin(t2, t0.select($"t1.a"))),
Seq("cannot resolve 't1.a' given input columns: []")
)
// SELECT * FROM t1, LATERAL (SELECT * FROM t2, LATERAL (SELECT a, b))
assertAnalysisError(
lateralJoin(t1, lateralJoin(t2, t0.select('a, 'b))),
Seq("cannot resolve 'a' given input columns: []")
)
}
test("lateral subquery with struct type") {
val xa = GetStructField(OuterReference(x), 0, Some("a")).as(a.name)
val ya = GetStructField(OuterReference(y), 0, Some("a")).as(a.name)
checkAnalysis(
lateralJoin(t4, t0.select($"x.a", $"y.a")),
LateralJoin(t4, LateralSubquery(Project(Seq(xa, ya), t0), Seq(x, y)), Inner, None)
)
// Analyzer will try to resolve struct first before subquery alias.
assertAnalysisError(
lateralJoin(t1.as("x"), t4.select($"x.a", $"x.b")),
Seq("No such struct field b in a")
)
}
test("lateral join with unsupported expressions") {
val plan = lateralJoin(t1, t0.select(('a + 'b).as("c")),
condition = Some(sum('a) === sum('c)))
assertAnalysisError(plan, Seq("Invalid expressions: [sum(a), sum(c)]"))
}
test("SPARK-35618: lateral join with star expansion") {
val outerA = OuterReference(a.withQualifier(Seq("t1"))).as(a.name)
val outerB = OuterReference(b.withQualifier(Seq("t1"))).as(b.name)
// SELECT * FROM t1, LATERAL (SELECT *)
checkAnalysis(
lateralJoin(t1.as("t1"), t0.select(star())),
LateralJoin(t1, LateralSubquery(Project(Nil, t0)), Inner, None)
)
// SELECT * FROM t1, LATERAL (SELECT t1.*)
checkAnalysis(
lateralJoin(t1.as("t1"), t0.select(star("t1"))),
LateralJoin(t1, LateralSubquery(Project(Seq(outerA, outerB), t0), Seq(a, b)), Inner, None)
)
// SELECT * FROM t1, LATERAL (SELECT * FROM t2)
checkAnalysis(
lateralJoin(t1.as("t1"), t2.select(star())),
LateralJoin(t1, LateralSubquery(Project(Seq(b, c), t2)), Inner, None)
)
// SELECT * FROM t1, LATERAL (SELECT t1.*, t2.* FROM t2)
checkAnalysis(
lateralJoin(t1.as("t1"), t2.as("t2").select(star("t1"), star("t2"))),
LateralJoin(t1,
LateralSubquery(Project(Seq(outerA, outerB, b, c), t2.as("t2")), Seq(a, b)), Inner, None)
)
// SELECT * FROM t1, LATERAL (SELECT t2.*)
assertAnalysisError(
lateralJoin(t1.as("t1"), t0.select(star("t2"))),
Seq("cannot resolve 't2.*' given input columns ''")
)
// Check case sensitivities.
// SELECT * FROM t1, LATERAL (SELECT T1.*)
val plan = lateralJoin(t1.as("t1"), t0.select(star("T1")))
assertAnalysisError(plan, "cannot resolve 'T1.*' given input columns ''" :: Nil)
assertAnalysisSuccess(plan, caseSensitive = false)
}
test("SPARK-35618: lateral join with star expansion in functions") {
val outerA = OuterReference(a.withQualifier(Seq("t1")))
val outerB = OuterReference(b.withQualifier(Seq("t1")))
val array = CreateArray(Seq(star("t1")))
val newArray = CreateArray(Seq(outerA, outerB))
checkAnalysis(
lateralJoin(t1.as("t1"), t0.select(array)),
LateralJoin(t1,
LateralSubquery(t0.select(newArray.as(newArray.sql)), Seq(a, b)), Inner, None)
)
assertAnalysisError(
lateralJoin(t1.as("t1"), t0.select(Count(star("t1")))),
Seq("Invalid usage of '*' in expression 'count'")
)
}
test("SPARK-35618: lateral join with struct type star expansion") {
// SELECT * FROM t4, LATERAL (SELECT x.*)
checkAnalysis(
lateralJoin(t4, t0.select(star("x"))),
LateralJoin(t4, LateralSubquery(
Project(Seq(GetStructField(OuterReference(x), 0).as(a.name)), t0), Seq(x)),
Inner, None)
)
}
test("SPARK-36028: resolve scalar subqueries with outer references in Project") {
// SELECT (SELECT a) FROM t1
checkAnalysis(
Project(ScalarSubquery(t0.select('a)).as("sub") :: Nil, t1),
Project(ScalarSubquery(Project(OuterReference(a) :: Nil, t0), Seq(a)).as("sub") :: Nil, t1)
)
// SELECT (SELECT a + b + c AS r FROM t2) FROM t1
checkAnalysis(
Project(ScalarSubquery(
t2.select(('a + 'b + 'c).as("r"))).as("sub") :: Nil, t1),
Project(ScalarSubquery(
Project((OuterReference(a) + b + c).as("r") :: Nil, t2), Seq(a)).as("sub") :: Nil, t1)
)
// SELECT (SELECT array(t1.*) AS arr) FROM t1
checkAnalysis(
Project(ScalarSubquery(t0.select(
CreateArray(Seq(star("t1"))).as("arr"))
).as("sub") :: Nil, t1.as("t1")),
Project(ScalarSubquery(Project(
CreateArray(Seq(OuterReference(a), OuterReference(b))).as("arr") :: Nil, t0
), Seq(a, b)).as("sub") :: Nil, t1)
)
}
}
| hvanhovell/spark | sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/ResolveSubquerySuite.scala | Scala | apache-2.0 | 10,311 |
package provingground.scalahott
import provingground._, HoTT._
/**
* Wrapper for universe with refined scala type for objects (i.e., types) in it.
* Refined scala types typically recursively built from (dependent) function types and types of already refined types.
*/
case class ScalaUniv[U <: Term with Subs[U]](univ: Typ[Typ[U]])
object ScalaUniv {
/**
* given a universe with objects of scala type Typ[U], gives one with scala type Typ[Typ[U]]
*/
case class HigherUniv[U <: Typ[Term] with Subs[U]](univ: Typ[U])
extends Typ[Typ[U]] {
type Obj = Typ[U]
lazy val typ = HigherUniv[Typ[U]](this)
def variable(name: AnySym) = univ
def newobj =
throw new IllegalArgumentException(
s"trying to use the constant $this as a variable (or a component of one)")
def subs(x: Term, y: Term) = this
}
/**
* Universe whose elements are FuncTyps
*/
case class FuncTypUniv[W <: Term with Subs[W], U <: Term with Subs[U]](
domuniv: Typ[Typ[W]],
codomuniv: Typ[Typ[U]])
extends Typ[FuncTyp[W, U]] {
type Obj = FuncTyp[W, U]
lazy val typ = HigherUniv(this)
def variable(name: AnySym) = {
val dom = domuniv.symbObj(DomSym(name))
val codom = codomuniv.symbObj(CodomSym(name))
FuncTyp(dom, codom)
}
def newobj = FuncTypUniv(domuniv.newobj, codomuniv.newobj)
def subs(x: Term, y: Term) = this
}
/**
* Universe with objects Pi-Types
*/
@deprecated("Use PiDefn", "14/12/2016")
case class PiTypUniv[W <: Term with Subs[W], U <: Term with Subs[U]](
domuniv: Typ[Typ[W]],
codomuniv: Typ[Typ[U]])
extends Typ[PiTyp[W, U]] {
type Obj = PiTyp[W, U]
lazy val typ = HigherUniv(this)
def variable(name: AnySym) = {
val dom = domuniv.symbObj(DomSym(name))
// val codom = codomuniv.symbObj(CodomSym(name))
val typFmly = FuncTyp(dom, codomuniv).symbObj(name)
PiTyp(typFmly)
}
def newobj =
throw new IllegalArgumentException(
s"trying to use the constant $this as a variable (or a component of one)")
def subs(x: Term, y: Term) = this
}
/**
* Symbolic types, which the compiler knows are types.
*
*/
case class FineSymbTyp[U <: Term with Subs[U]](name: AnySym,
symobj: AnySym => U)
extends Typ[U]
with Symbolic {
lazy val typ = FineUniv(symobj)
def newobj = FineSymbTyp(new InnerSym[Typ[U]](this), symobj)
type Obj = U
def variable(name: AnySym) = symobj(name)
def elem = this
def subs(x: Term, y: Term) = (x, y) match {
case (u: Typ[_], v: Typ[_]) if (u == this) => v.asInstanceOf[Typ[U]]
case _ => {
def symbobj(name: AnySym) = FineSymbTyp(name, symobj)
symSubs(symbobj)(x, y)(name)
}
}
}
case class FineUniv[U <: Term with Subs[U]](symobj: AnySym => U)
extends Typ[Typ[U]]
with BaseUniv {
type Obj = Typ[U]
lazy val typ = HigherUniv(this)
def variable(name: AnySym) = FineSymbTyp(name, symobj)
def newobj =
throw new IllegalArgumentException(
s"trying to use the constant $this as a variable (or a component of one)")
def subs(x: Term, y: Term) = this
}
// import ScalaUniv._
/**
* scala universe with no refinement.
*/
implicit val baseUniv: ScalaUniv[Term] = ScalaUniv(Type)
/**
* implicitly returns from a scala universe of Typ[U] one of Typ[Typ[U]]
*/
implicit def higherUniv[U <: Term with Subs[U]](
implicit sc: ScalaUniv[U]): ScalaUniv[Typ[U]] = {
ScalaUniv(HigherUniv(sc.univ))
}
def newobj =
throw new IllegalArgumentException(
s"trying to use the constant $this as a variable (or a component of one)")
/**
* implicitly build universe with elements FuncTyps from universes for domain and codomain.
*/
implicit def funcUniv[W <: Term with Subs[W], U <: Term with Subs[U]](
implicit domsc: ScalaUniv[W],
codomsc: ScalaUniv[U]): ScalaUniv[Func[W, U]] = {
ScalaUniv(FuncTypUniv(domsc.univ, codomsc.univ): Typ[FuncTyp[W, U]])
}
/**
* builds scala universe for pi-types given ones for domain and codomain types.
*/
@deprecated("Use PiDefn", "14/12/2016")
implicit def piUniv[W <: Term with Subs[W], U <: Term with Subs[U]](
implicit domsc: ScalaUniv[W],
codomsc: ScalaUniv[U]): ScalaUniv[FuncLike[W, U]] = {
ScalaUniv(PiTypUniv(domsc.univ, codomsc.univ): Typ[PiTyp[W, U]])
}
/**
* returns dependent function inferring type fiber.
*/
def depFunc[W <: Term with Subs[W], U <: Term with Subs[U]](
dom: Typ[W],
func: W => U)(implicit su: ScalaUniv[U]): FuncLike[W, U] = {
val fibers = typFamily(dom, (w: W) => func(w).typ.asInstanceOf[Typ[U]])
new DepFuncDefn(func, dom, fibers)
}
/**
* convenience for Pi-type
*/
// implicit class RichTypFamily[W <: Term with Subs[W], U <: Term with Subs[U]](
// fibre: Func[W, Typ[U]])(
// implicit
// su: ScalaUniv[U]) {
// // val dom = func.dom
//
// def pi = PiTyp(fibre)
// }
/**
* Companion to dependent functions
*
*/
object DepFunc {
def apply[W <: Term with Subs[W], U <: Term with Subs[U]](
func: Term => U,
dom: Typ[W])(implicit su: ScalaUniv[U]) = {
def section(arg: Term) = func(arg).typ.asInstanceOf[Typ[U]]
val fibers: TypFamily[W, U] = typFamily[W, U](dom, section)
new DepFuncDefn(func, dom, fibers)
}
}
/**
* create type family, implicitly using a scala-universe object to build the codomain.
*/
def typFamily[W <: Term with Subs[W], U <: Term with Subs[U]](
dom: Typ[W],
f: W => Typ[U])(implicit su: ScalaUniv[U]) = {
val codom = su.univ
new FuncDefn[W, Typ[U]](f, dom, codom)
}
}
| siddhartha-gadgil/ProvingGround | core/src/main/scala/provingground/scalahott/ScalaUniverses.scala | Scala | mit | 5,849 |
package fpinscala.monoids
import fpinscala.monoids.Monoid._
import org.scalatest._
class FoldableIndexedSeqTest
extends FlatSpec
with Matchers {
"The Foldable[IndexedSeq]" should "implement foldRight method" in {
val listOfIntegers = IndexedSeq(1, 2, 3)
val sumOfList = IndexedSeqFoldable.foldRight(listOfIntegers)(0)(_ + _)
sumOfList should be(6)
}
it should "implement foldLeft method" in {
val listOfIntegers = IndexedSeq(1, 2, 3)
val sumOfList = IndexedSeqFoldable.foldLeft(listOfIntegers)(0)(_ + _)
sumOfList should be(6)
}
it should "implement foldMap method" in {
val myList = IndexedSeq(1.0,2.0,3.0)
val myContatenatedDoubleList = IndexedSeqFoldable.foldMap(myList)(elem => elem.toString)(stringMonoid)
myContatenatedDoubleList should be("1.02.03.0")
}
}
| ardlema/fpinscala | exercises/src/test/scala/fpinscala/monoids/FoldableIndexedSeqTest.scala | Scala | mit | 820 |
package sp.kalle.testing
import sp.domain._
import Logic._
object TestingAPI extends sp.domain.testing.TestingDerived {
sealed trait API
case class X1(a: String, b: Int = 3, c: Boolean = false) extends API
case class X2(a: String, b: Int = 3, c: Boolean = false) extends API
case class X3(a: String, b: Int = 3, c: Boolean = false) extends API
case class X4(a: String, b: Int = 3, c: Boolean = false) extends API
case class X5(a: String, b: Int = 3, c: Boolean = false) extends API
case object X6 extends API
case class X7(a: String, b: Int = 3, c: Boolean = false) extends API
case class X8(a: String, b: Int = 3, c: Boolean = false) extends API
case class X9(a: String, b: Int = 3, c: Boolean = false) extends API
case class X10(a: String, b: Int = 3, c: Boolean = false) extends API
case class X11(a: String, b: Int = 3, c: Boolean = false) extends API
case class X12(a: String, b: Int = 3, c: Boolean = false) extends API
case class X13(a: String, b: Int = 3, c: Boolean = false) extends API
case class X14(a: String, b: Int = 3, c: Boolean = false) extends API
case class X15(a: String, b: Int = 3, c: Boolean = false) extends API
case class X16(a: String, b: Int = 3, c: Boolean = false) extends API
case class X17(a: String, b: Int = 3, c: Boolean = false) extends API
case class X18(a: String, b: Int = 3, c: Boolean = false) extends API
case class Y1(a: String, b: Int = 3, c: Boolean = false) extends API
case class Y2(a: String, b: Int = 3, c: Boolean = false) extends API
case class Y3(a: String, b: Int = 3, c: Boolean = false) extends API
case class Y4(a: String, b: Int = 3, c: Boolean = false) extends API
case class Y5(a: String, b: Int = 3, c: Boolean = false) extends API
case class Y6(a: String, b: Int = 3, c: Boolean = false) extends API
case class Y7(a: String, b: Int = 3, c: Boolean = false) extends API
case class Y8(a: String, b: Int = 3, c: Boolean = false) extends API
case class Y9(a: String, b: Int = 3, c: Boolean = false) extends API
case class Y10(a: String, b: Int = 3, c: Boolean = false) extends API
//val k = deriveFormatISA[API]
import play.api.libs.json._
object SUB {
implicit val fX2: JSFormat[X2] = derive.format[X2]
implicit val fX3: JSFormat[X3] = derive.format[X3]
implicit val fX4: JSFormat[X4] = derive.format[X4]
implicit val fX5: JSFormat[X5] = derive.format[X5]
implicit val fX1: JSFormat[X1] = derive.format[X1]
implicit val fX6: JSFormat[X6.type] = deriveCaseObject[X6.type]
implicit val fX7: JSFormat[X7] = derive.format[X7]
implicit val fX8: JSFormat[X8] = derive.format[X8]
implicit val fX9: JSFormat[X9] = derive.format[X9]
implicit val fX10: JSFormat[X10] = derive.format[X10]
implicit val fX11: JSFormat[X11] = derive.format[X11]
implicit val fX12: JSFormat[X12] = derive.format[X12]
implicit val fX13: JSFormat[X13] = derive.format[X13]
implicit val fX14: JSFormat[X14] = derive.format[X14]
implicit val fX15: JSFormat[X15] = derive.format[X15]
implicit val fX16: JSFormat[X16] = derive.format[X16]
implicit val fX17: JSFormat[X17] = derive.format[X17]
implicit val fX18: JSFormat[X18] = derive.format[X18]
implicit val fY1: JSFormat[Y1] = derive.format[Y1]
implicit val fY2: JSFormat[Y2] = derive.format[Y2]
implicit val fY3: JSFormat[Y3] = derive.format[Y3]
implicit val fY4: JSFormat[Y4] = derive.format[Y4]
implicit val fY5: JSFormat[Y5] = derive.format[Y5]
implicit val fY6: JSFormat[Y6] = derive.format[Y6]
implicit val fY7: JSFormat[Y7] = derive.format[Y7]
implicit val fY8: JSFormat[Y8] = derive.format[Y8]
implicit val fY9: JSFormat[Y9] = derive.format[Y9]
implicit val fY10: JSFormat[Y10] = derive.format[Y10]
}
object API {
import SUB._
implicit val kk = derive.format[TestingAPI.API]
}
}
| sequenceplanner/sp-domain | src/test/scala/sp/domain/testing/TestingAPI.scala | Scala | mit | 4,142 |
package controllers
import org.specs2.mutable.Specification
//import play.api.test.Helpers.{GET, OK, contentType, running, status}
import play.api.test.Helpers._
import play.api.test.{FakeApplication, FakeRequest}
/**
* You can mock out a whole application including requests, plugins etc.
* For more information, consult the wiki.
*/
class ApplicationIT extends Specification {
"Application" should {
"send 404 on a bad request" in {
running(FakeApplication()) {
route(FakeRequest(GET, "/boum")) must beNone
}
}
"render the index page" in {
running(FakeApplication()) {
val home = route(FakeRequest(GET, "/")).get
status(home) must equalTo(OK)
contentType(home) must beSome.which(_ == "text/html")
}
}
}
} | amsterdam-scala/play-reactive-mongo-coffee-angular | test/controllers/ApplicationIT.scala | Scala | apache-2.0 | 794 |
/**
* Copyright (C) 2011 JTalks.org Team
* This library 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 library 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.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
import java.nio.file.Path
import io.gatling.commons.util.PathHelper._
object IDEPathHelper {
val gatlingConfUrl: Path = getClass.getClassLoader.getResource("gatling.conf").toURI
val projectRootDir = gatlingConfUrl.ancestor(3)
val mavenSourcesDirectory = projectRootDir / "src" / "test" / "scala"
val mavenResourcesDirectory = projectRootDir / "src" / "test" / "resources"
val mavenTargetDirectory = projectRootDir / "target"
val mavenBinariesDirectory = mavenTargetDirectory / "test-classes"
val dataDirectory = mavenResourcesDirectory / "data"
val bodiesDirectory = mavenResourcesDirectory / "bodies"
val recorderOutputDirectory = mavenSourcesDirectory
val resultsDirectory = mavenTargetDirectory / "gatling"
val recorderConfigFile = mavenResourcesDirectory / "recorder.conf"
}
| Noctrunal/jcommune | jcommune-performance-tests/src/test/scala/IDEPathHelper.scala | Scala | lgpl-2.1 | 1,579 |
/*
* Copyright 2013 http4s.org
*
* 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.
*/
/*
* Copyright 2013 http4s.org
*
* 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.http4s
package headers
import cats.data.NonEmptyList
import cats.parse.Parser
import org.http4s.Header
import org.http4s.internal.parsing.Rfc7235
import org.typelevel.ci._
object `Proxy-Authenticate` {
def apply(head: Challenge, tail: Challenge*): `Proxy-Authenticate` =
apply(NonEmptyList(head, tail.toList))
private[http4s] val parser: Parser[`Proxy-Authenticate`] =
Rfc7235.challenges.map(`Proxy-Authenticate`.apply)
def parse(s: String): ParseResult[`Proxy-Authenticate`] =
ParseResult.fromParser(parser, "Invalid Proxy-Authenticate header")(s)
implicit val headerInstance: Header[`Proxy-Authenticate`, Header.Recurring] =
Header.createRendered(
ci"Proxy-Authenticate",
_.values,
parse,
)
implicit val headerSemigroupInstance: cats.Semigroup[`Proxy-Authenticate`] =
(a, b) => `Proxy-Authenticate`(a.values.concatNel(b.values))
}
/** {{{
* The "Proxy-Authenticate" header field consists of at least one
* challenge that indicates the authentication scheme(s) and parameters
* applicable to the proxy for this effective request URI...
* }}}
* From [[https://datatracker.ietf.org/doc/html/rfc7235#section-4.3 RFC-7235]]
*/
final case class `Proxy-Authenticate`(values: NonEmptyList[Challenge])
| http4s/http4s | core/shared/src/main/scala/org/http4s/headers/Proxy-Authenticate.scala | Scala | apache-2.0 | 2,475 |
/*
* Copyright 2013 Stephane Godbillon (@sgodbillon)
*
* 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 reactivemongo.bson.buffer
import reactivemongo.bson._
import scala.util.{ Failure, Success, Try }
trait BufferHandler {
def serialize(bson: BSONValue, buffer: WritableBuffer): WritableBuffer
def deserialize(buffer: ReadableBuffer): Try[(String, BSONValue)]
def write(buffer: WritableBuffer, document: BSONDocument) = {
serialize(document, buffer)
}
def write(buffer: WritableBuffer, arr: BSONArray) = {
serialize(arr, buffer)
}
def readDocument(buffer: ReadableBuffer): Try[BSONDocument]
def writeDocument(document: BSONDocument, buffer: WritableBuffer): WritableBuffer
def stream(buffer: ReadableBuffer): Stream[(String, BSONValue)] = {
val elem = deserialize(buffer)
if (elem.isSuccess)
elem.get #:: stream(buffer)
else Stream.empty
}
}
object DefaultBufferHandler extends BufferHandler {
sealed trait BufferWriter[B <: BSONValue] {
def write(value: B, buffer: WritableBuffer): WritableBuffer
}
sealed trait BufferReader[B <: BSONValue] {
def read(buffer: ReadableBuffer): B
}
sealed trait BufferRW[B <: BSONValue] extends BufferWriter[B] with BufferReader[B]
val handlersByCode: Map[Byte, BufferRW[_ <: BSONValue]] = Map(
0x01.toByte -> BSONDoubleBufferHandler,
0x02.toByte -> BSONStringBufferHandler,
0x03.toByte -> BSONDocumentBufferHandler,
0x04.toByte -> BSONArrayBufferHandler, // array
0x05.toByte -> BSONBinaryBufferHandler, // binary TODO
0x06.toByte -> BSONUndefinedBufferHandler, // undefined,
0x07.toByte -> BSONObjectIDBufferHandler, // objectid,
0x08.toByte -> BSONBooleanBufferHandler, // boolean
0x09.toByte -> BSONDateTimeBufferHandler, // datetime
0x0A.toByte -> BSONNullBufferHandler, // null
0x0B.toByte -> BSONRegexBufferHandler, // regex
0x0C.toByte -> BSONDBPointerBufferHandler, // dbpointer
0x0D.toByte -> BSONJavaScriptBufferHandler, // JS
0x0E.toByte -> BSONSymbolBufferHandler, // symbol
0x0F.toByte -> BSONJavaScriptWSBufferHandler, // JS with scope
0x10.toByte -> BSONIntegerBufferHandler,
0x11.toByte -> BSONTimestampBufferHandler, // timestamp,
0x12.toByte -> BSONLongBufferHandler, // long,
0xFF.toByte -> BSONMinKeyBufferHandler, // min
0x7F.toByte -> BSONMaxKeyBufferHandler) // max
object BSONDoubleBufferHandler extends BufferRW[BSONDouble] {
def write(value: BSONDouble, buffer: WritableBuffer): WritableBuffer = buffer.writeDouble(value.value)
def read(buffer: ReadableBuffer): BSONDouble = BSONDouble(buffer.readDouble)
}
object BSONStringBufferHandler extends BufferRW[BSONString] {
def write(value: BSONString, buffer: WritableBuffer): WritableBuffer = buffer.writeString(value.value)
def read(buffer: ReadableBuffer): BSONString = BSONString(buffer.readString)
}
object BSONDocumentBufferHandler extends BufferRW[BSONDocument] {
def write(doc: BSONDocument, buffer: WritableBuffer) = {
val now = buffer.index
buffer.writeInt(0)
doc.elements.foreach { e =>
buffer.writeByte(e._2.code.toByte)
buffer.writeCString(e._1)
serialize(e._2, buffer)
}
buffer.setInt(now, (buffer.index - now + 1))
buffer.writeByte(0)
buffer
}
def read(b: ReadableBuffer) = {
val startIndex = b.index
val length = b.readInt
val buffer = b.slice(length - 4)
b.discard(length - 4)
def makeStream(): Stream[Try[(String, BSONValue)]] = {
if (buffer.readable > 1) { // last is 0
val code = buffer.readByte
val name = buffer.readCString
val elem = Try(name -> DefaultBufferHandler.handlersByCode.get(code).map(_.read(buffer)).get)
elem #:: makeStream
} else Stream.empty
}
val stream = makeStream
stream.force // TODO remove
new BSONDocument(stream)
}
}
object BSONArrayBufferHandler extends BufferRW[BSONArray] {
def write(array: BSONArray, buffer: WritableBuffer) = {
val now = buffer.index
buffer.writeInt(0)
array.values.zipWithIndex.foreach { e =>
buffer.writeByte(e._1.code.toByte)
buffer.writeCString(e._2.toString)
serialize(e._1, buffer)
}
buffer.setInt(now, (buffer.index - now + 1))
buffer.writeByte(0)
buffer
}
def read(b: ReadableBuffer) = {
val startIndex = b.index
val length = b.readInt
val buffer = b.slice(length - 4)
b.discard(length - 4)
def makeStream(): Stream[Try[BSONValue]] = {
if (buffer.readable > 1) { // last is 0
val code = buffer.readByte
val name = buffer.readCString
val elem = Try(DefaultBufferHandler.handlersByCode.get(code).map(_.read(buffer)).get)
elem #:: makeStream
} else Stream.empty
}
val stream = makeStream
stream.force // TODO remove
new BSONArray(stream)
}
}
object BSONBinaryBufferHandler extends BufferRW[BSONBinary] {
def write(binary: BSONBinary, buffer: WritableBuffer) = {
buffer.writeInt(binary.value.readable)
buffer.writeByte(binary.subtype.value.toByte)
val bin = binary.value.slice(binary.value.readable)
buffer.writeBytes(bin.readArray(bin.readable)) // TODO
buffer
}
def read(buffer: ReadableBuffer) = {
val length = buffer.readInt
val subtype = Subtype.apply(buffer.readByte)
val bin = buffer.slice(length)
buffer.discard(length)
BSONBinary(bin, subtype)
}
}
object BSONUndefinedBufferHandler extends BufferRW[BSONUndefined.type] {
def write(undefined: BSONUndefined.type, buffer: WritableBuffer) = buffer
def read(buffer: ReadableBuffer) = BSONUndefined
}
object BSONObjectIDBufferHandler extends BufferRW[BSONObjectID] {
def write(objectId: BSONObjectID, buffer: WritableBuffer) = buffer writeBytes objectId.valueAsArray
def read(buffer: ReadableBuffer) = BSONObjectID(buffer.readArray(12))
}
object BSONBooleanBufferHandler extends BufferRW[BSONBoolean] {
def write(boolean: BSONBoolean, buffer: WritableBuffer) = buffer writeByte (if (boolean.value) 1 else 0)
def read(buffer: ReadableBuffer) = BSONBoolean(buffer.readByte == 0x01)
}
object BSONDateTimeBufferHandler extends BufferRW[BSONDateTime] {
def write(dateTime: BSONDateTime, buffer: WritableBuffer) = buffer writeLong dateTime.value
def read(buffer: ReadableBuffer) = BSONDateTime(buffer.readLong)
}
object BSONNullBufferHandler extends BufferRW[BSONNull.type] {
def write(`null`: BSONNull.type, buffer: WritableBuffer) = buffer
def read(buffer: ReadableBuffer) = BSONNull
}
object BSONRegexBufferHandler extends BufferRW[BSONRegex] {
def write(regex: BSONRegex, buffer: WritableBuffer) = { buffer writeCString regex.value; buffer writeCString regex.flags }
def read(buffer: ReadableBuffer) = BSONRegex(buffer.readCString, buffer.readCString)
}
object BSONDBPointerBufferHandler extends BufferRW[BSONDBPointer] {
def write(pointer: BSONDBPointer, buffer: WritableBuffer) = { buffer writeCString pointer.value; buffer writeBytes pointer.id }
def read(buffer: ReadableBuffer) = BSONDBPointer(buffer.readCString, buffer.readArray(12))
}
object BSONJavaScriptBufferHandler extends BufferRW[BSONJavaScript] {
def write(js: BSONJavaScript, buffer: WritableBuffer) = buffer writeString js.value
def read(buffer: ReadableBuffer) = BSONJavaScript(buffer.readString)
}
object BSONSymbolBufferHandler extends BufferRW[BSONSymbol] {
def write(symbol: BSONSymbol, buffer: WritableBuffer) = buffer writeString symbol.value
def read(buffer: ReadableBuffer) = BSONSymbol(buffer.readString)
}
object BSONJavaScriptWSBufferHandler extends BufferRW[BSONJavaScriptWS] {
def write(jsws: BSONJavaScriptWS, buffer: WritableBuffer) = buffer writeString jsws.value
def read(buffer: ReadableBuffer) = BSONJavaScriptWS(buffer.readString)
}
object BSONIntegerBufferHandler extends BufferRW[BSONInteger] {
def write(value: BSONInteger, buffer: WritableBuffer) = buffer writeInt value.value
def read(buffer: ReadableBuffer): BSONInteger = BSONInteger(buffer.readInt)
}
object BSONTimestampBufferHandler extends BufferRW[BSONTimestamp] {
def write(ts: BSONTimestamp, buffer: WritableBuffer) = buffer writeLong ts.value
def read(buffer: ReadableBuffer) = BSONTimestamp(buffer.readLong)
}
object BSONLongBufferHandler extends BufferRW[BSONLong] {
def write(long: BSONLong, buffer: WritableBuffer) = buffer writeLong long.value
def read(buffer: ReadableBuffer) = BSONLong(buffer.readLong)
}
object BSONMinKeyBufferHandler extends BufferRW[BSONMinKey.type] {
def write(b: BSONMinKey.type, buffer: WritableBuffer) = buffer
def read(buffer: ReadableBuffer) = BSONMinKey
}
object BSONMaxKeyBufferHandler extends BufferRW[BSONMaxKey.type] {
def write(b: BSONMaxKey.type, buffer: WritableBuffer) = buffer
def read(buffer: ReadableBuffer) = BSONMaxKey
}
def serialize(bson: BSONValue, buffer: WritableBuffer): WritableBuffer = {
handlersByCode.get(bson.code).get.asInstanceOf[BufferRW[BSONValue]].write(bson, buffer)
}
def deserialize(buffer: ReadableBuffer): Try[(String, BSONValue)] = Try {
if (buffer.readable > 0) {
val code = buffer.readByte
buffer.readString -> handlersByCode.get(code).map(_.read(buffer)).get
} else throw new NoSuchElementException("buffer can not be read, end of buffer reached")
}
def readDocument(buffer: ReadableBuffer): Try[BSONDocument] = Try {
BSONDocumentBufferHandler.read(buffer)
}
def writeDocument(document: BSONDocument, buffer: WritableBuffer): WritableBuffer =
serialize(document, buffer)
}
sealed trait BSONIterator extends Iterator[BSONElement] {
val buffer: ReadableBuffer
val startIndex = buffer.index
val documentSize = buffer.readInt
def next: BSONElement = {
val code = buffer.readByte
buffer.readString -> DefaultBufferHandler.handlersByCode.get(code).map(_.read(buffer)).get
}
def hasNext = buffer.index - startIndex + 1 < documentSize
def mapped: Map[String, BSONElement] = {
for (el <- this) yield (el._1, el)
}.toMap
}
object BSONIterator {
private[bson] def pretty(i: Int, it: Iterator[Try[BSONElement]]): String = {
val prefix = (0 to i).map { i => " " }.mkString("")
(for (tryElem <- it) yield {
tryElem match {
case Success(elem) => elem._2 match {
case doc: BSONDocument => prefix + elem._1 + ": {\n" + pretty(i + 1, doc.stream.iterator) + "\n" + prefix + "}"
case array: BSONArray => prefix + elem._1 + ": [\n" + pretty(i + 1, array.iterator) + "\n" + prefix + "]"
case _ => prefix + elem._1 + ": " + elem._2.toString
}
case Failure(e) => prefix + s"ERROR[${e.getMessage()}]"
}
}).mkString(",\n")
}
/** Makes a pretty String representation of the given iterator of BSON elements. */
def pretty(it: Iterator[Try[BSONElement]]): String = "{\n" + pretty(0, it) + "\n}"
}
| reactific/ReactiveMongo | bson/src/main/scala/bufferhandlers.scala | Scala | apache-2.0 | 11,648 |
/*
* 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.utils
import java.lang.Character.UnicodeBlock._
import java.text.{CollationKey, Collator}
import java.util
import java.util.{Comparator, Locale}
import android.annotation.TargetApi
import android.content.res.Configuration
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.{JELLY_BEAN_MR2, LOLLIPOP}
import com.github.ghik.silencer.silent
import com.waz.log.BasicLogging.LogTag
import com.waz.log.BasicLogging.LogTag.DerivedLogTag
import com.waz.log.LogSE._
import com.waz.service.ZMessaging
import com.waz.utils
import scala.annotation.tailrec
import scala.util.Try
object Locales extends DerivedLogTag {
def currentLocale =
(for {
context <- Option(ZMessaging.context)
resources <- Option(context.getResources)
config <- Option(resources.getConfiguration)
locale <- localeOptFromConfig(config)
} yield locale) getOrElse Locale.getDefault
lazy val bcp47 = if (SDK_INT >= LOLLIPOP) AndroidLanguageTags.create else FallbackLanguageTags.create
@silent def localeOptFromConfig(config: Configuration): Option[Locale] = Option(config.locale)
// the underlying native collator shows no signs of being thread-safe & locale might change – that's why this is a def instead of a val
def currentLocaleOrdering: Ordering[String] = new Ordering[String] {
private[this] val collator = Collator.getInstance(currentLocale)
final def compare(a: String, b: String): Int = collator.compare(a, b)
}
def sortWithCurrentLocale[A](as: IndexedSeq[A], f: A => String): Vector[A] = { // much faster than as.sortBy(f)(currentLocaleOrdering)
val collator = Collator.getInstance(currentLocale)
val indexed = Array.tabulate(as.size)(n => (n, collator.getCollationKey(f(as(n)))))
util.Arrays.sort(indexed, CollationKeyComparator)
Vector.tabulate(indexed.size)(n => as(indexed(n)._1))
}
def preloadTransliterator(): Transliteration = transliteration
lazy val transliteration = Transliteration.chooseImplementation()
def transliteration(id: String) = Transliteration.chooseImplementation(id)
def indexing(locale: Locale = currentLocale): Indexing = Try(Class.forName("libcore.icu.AlphabeticIndex")).flatMap(
_ => Try(LibcoreIndexing.create(locale))).getOrElse(FallbackIndexing.instance)
}
object CollationKeyComparator extends Comparator[(Int, CollationKey)] {
override def compare(lhs: (Int, CollationKey), rhs: (Int, CollationKey)): Int = lhs._2 compareTo rhs._2
}
trait LanguageTags {
def languageTagOf(l: Locale): String
def localeFor(languageTag: String): Option[Locale]
}
@TargetApi(LOLLIPOP)
object AndroidLanguageTags {
def create(implicit logTag: LogTag): LanguageTags = new LanguageTags {
debug(l"using built-in Android language tag support")(logTag)
def languageTagOf(l: Locale): String = l.toLanguageTag
def localeFor(t: String): Option[Locale] = Try(Locale.forLanguageTag(t)).toOption
}
}
object FallbackLanguageTags {
def create(implicit logTag: LogTag): LanguageTags = new LanguageTags {
debug(l"using fallback language tag support")(logTag)
def languageTagOf(l: Locale): String = {
val language = if (l.getLanguage.nonEmpty) l.getLanguage else "und"
val country = l.getCountry
if (country.isEmpty) language else s"$language-$country"
}
val LanguageTag = s"([a-zA-Z]{2,8})(?:-[a-zA-Z]{4})?(?:-([a-zA-Z]{2}|[0-9]{3}))?".r
def localeFor(t: String): Option[Locale] = t match {
case LanguageTag(language, region) =>
Some(
if (region ne null) new Locale(language, region)
else new Locale(language))
case _ =>
None
}
}
}
trait Transliteration {
def transliterate(s: String): String
}
object Transliteration extends DerivedLogTag {
private val id = "Any-Latin; Latin-ASCII; Lower; [^\\\\ 0-9a-z] Remove"
def chooseImplementation(id: String = id): Transliteration = {
verbose(l"chooseImplementation: ${showString(id)}")
if (!utils.isTest && Try(Class.forName("libcore.icu.Transliterator")).isSuccess) LibcoreTransliteration.create(id)
else ICU4JTransliteration.create(id)
}
}
@TargetApi(JELLY_BEAN_MR2)
object LibcoreTransliteration {
def create(id: String)(implicit logTag: LogTag): Transliteration = new Transliteration {
debug(l"using libcore transliteration")(logTag)
private val delegate = new libcore.icu.Transliterator(id)
def transliterate(s: String): String = delegate.transliterate(s)
}
}
object ICU4JTransliteration {
def create(id: String)(implicit logTag: LogTag): Transliteration = new Transliteration {
debug(l"using ICU4J transliteration")(logTag)
private val delegate = com.ibm.icu.text.Transliterator.getInstance(id)
def transliterate(s: String): String = delegate.transliterate(s)
}
}
trait Indexing {
def labelFor(s: String): String
}
@TargetApi(JELLY_BEAN_MR2)
object LibcoreIndexing {
def create(locale: Locale)(implicit logTag: LogTag): Indexing = new Indexing {
private val delegate = new libcore.icu.AlphabeticIndex(locale).getImmutableIndex
verbose(l"using libcore indexing for locale $locale; buckets: ${delegate.getBucketCount}")
override def labelFor(s: String): String = {
val index = delegate.getBucketIndex(s)
if (index == -1) "#"
else {
val label = delegate.getBucketLabel(index)
if (label.isEmpty) "#" else label
}
}
}
}
object FallbackIndexing extends DerivedLogTag {
lazy val instance: Indexing = new Indexing {
val blocks = Set(
BASIC_LATIN,
LATIN_1_SUPPLEMENT,
LATIN_EXTENDED_A,
LATIN_EXTENDED_B,
LATIN_EXTENDED_ADDITIONAL,
IPA_EXTENSIONS,
SPACING_MODIFIER_LETTERS,
PHONETIC_EXTENSIONS,
SUPERSCRIPTS_AND_SUBSCRIPTS,
NUMBER_FORMS,
ALPHABETIC_PRESENTATION_FORMS,
HALFWIDTH_AND_FULLWIDTH_FORMS)
def isProbablyLatin(c: Int): Boolean = {
val block = Character.UnicodeBlock.of(c)
if (block eq null) false else blocks(block)
}
verbose(l"creating fallback indexing")
@tailrec override def labelFor(s: String): String = {
if (s.isEmpty) "#"
else {
val c = s.codePointAt(0)
if (Character.isDigit(c)) "#"
else if (c >= 'A' && c <= 'Z') String.valueOf(c.toChar)
else if (c >= 'a' && c <= 'z') String.valueOf((c - 32).toChar)
else if (isProbablyLatin(c)) labelFor(Locales.transliteration.transliterate(s.substring(0, Character.charCount(c))))
else "#"
}
}
}
}
| wireapp/wire-android-sync-engine | zmessaging/src/main/scala/com/waz/utils/Locales.scala | Scala | gpl-3.0 | 7,233 |
/**
* Copyright (C) 2010-2012 LShift 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 net.lshift.diffa.kernel.util.cache
import org.junit.Assert._
import org.junit.runner.RunWith
import org.junit.experimental.theories.{DataPoint, Theories, Theory}
@RunWith(classOf[Theories])
class CacheProviderTest {
@Theory
def shouldProvideReadThroughCaching(provider:CacheProvider) {
val cache = provider.getCachedMap[String,String]("some-cache")
reset(cache)
val underlying = new UnderlyingDataSource("some-value")
val unCachedResponse = cache.readThrough("some_key", underlying.getData)
assertEquals("some-value", unCachedResponse)
val cachedResponse = cache.readThrough("some_key", underlying.getData)
assertEquals("some-value", cachedResponse)
assertEquals(1, underlying.invocations)
}
@Theory
def shouldSupportRetreivalBasedOnValuePredicate(provider:CacheProvider) {
val cache = provider.getCachedMap[String,NonProductionCacheValue]("my-cache")
reset(cache)
val fooValue = NonProductionCacheValue("foo", 1)
val barValue = NonProductionCacheValue("bar", 2)
cache.put("foo", fooValue)
cache.put("bar", barValue)
assertEquals(2, cache.size())
assertEquals(fooValue, cache.get("foo"))
assertEquals(barValue, cache.get("bar"))
cache.valueSubset("firstAttribute", "foo").foreach(x => cache.evict(x.firstAttribute))
assertEquals(1, cache.size())
assertNull(cache.get("foo"))
assertEquals(barValue, cache.get("bar"))
}
@Theory
def shouldSupportRemovalBasedOnKeyQuery(provider:CacheProvider) {
val cache = provider.getCachedMap[NonProductionCacheKey,String]("another-cache")
reset(cache)
val fooKey = NonProductionCacheKey("foo", 1)
val barKey = NonProductionCacheKey("bar", 2)
cache.put(fooKey, "first-value")
cache.put(barKey, "second-value")
assertEquals(2, cache.size())
assertEquals("first-value", cache.get(fooKey))
assertEquals("second-value", cache.get(barKey))
cache.keySubset(NonProductionKeyPredicate("foo")).evictAll
assertEquals(1, cache.size())
assertNull(cache.get(fooKey))
assertEquals("second-value", cache.get(barKey))
}
@Theory
def shouldSupportRemovalBasedOnExplicitKey(provider:CacheProvider) {
val cache = provider.getCachedMap[NonProductionCacheKey,String]("new-cache")
reset(cache)
val key = new NonProductionCacheKey("baz", 888)
cache.put(key, "baz-value")
assertEquals(1, cache.size())
assertEquals("baz-value", cache.get(key))
cache.evict(key)
assertEquals(0, cache.size())
assertNull(cache.get(key))
}
private def reset(cache:CachedMap[_,_]) = {
cache.evictAll
assertEquals(0, cache.size)
}
}
object CacheProviderTest {
@DataPoint def hazelcast = new HazelcastCacheProvider
}
class UnderlyingDataSource(responseValue:String) {
var invocations = 0
def getData() = {
invocations += 1
responseValue
}
}
| 0x6e6562/diffa | kernel/src/test/scala/net/lshift/diffa/kernel/util/cache/CacheProviderTest.scala | Scala | apache-2.0 | 3,499 |
package generator.graphql.helpers
trait TestHelpers {
def rightOrErrors[T](value: Either[_, T]): T = {
value match {
case Right(r) => r
case Left(errors) => sys.error(s"Expected valid value but got: ${errors}")
}
}
}
| mbryzek/apidoc-generator | graphql-generator/src/test/scala/generator/graphql/helpers/TestHelpers.scala | Scala | mit | 242 |
package com.twitter.finatra.http.tests.integration.pools.test
import com.twitter.finagle.http.Status._
import com.twitter.finatra.http.tests.integration.pools.main.{PooledController, PooledServer}
import com.twitter.finatra.http.EmbeddedHttpServer
import com.twitter.inject.server.FeatureTest
class PooledServerIntegrationTest extends FeatureTest {
override val server = new EmbeddedHttpServer(new PooledServer)
"PooledServer should return right away" in {
for (i <- 1 to 100) {
server.httpGet("/hi?id=" + i, andExpect = Ok)
}
//When manually testing, uncomment the next line to wait for forked future logging
//Thread.sleep(10000)
PooledController.pool1.executor.shutdownNow()
PooledController.pool2.executor.shutdownNow()
}
}
| syamantm/finatra | http/src/test/scala/com/twitter/finatra/http/tests/integration/pools/test/PooledServerIntegrationTest.scala | Scala | apache-2.0 | 770 |
import Common._
import org.specs2.mutable._
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.commands.bson.BSONUpdateCommand._
import reactivemongo.api.commands.bson.BSONUpdateCommandImplicits._
import reactivemongo.bson._
import scala.concurrent._
class UpdateSpec extends Specification {
sequential
val collection: BSONCollection = db("UpdateSpec")
case class Person(firstName: String,
lastName: String,
age: Int)
implicit object PersonReader extends BSONDocumentReader[Person] {
def read(doc: BSONDocument): Person =
Person(
doc.getAs[String]("firstName").getOrElse(""),
doc.getAs[String]("lastName").getOrElse(""),
doc.getAs[Int]("age").getOrElse(0))
}
implicit object PersonWriter extends BSONDocumentWriter[Person] {
def write(person: Person): BSONDocument =
BSONDocument(
"firstName" -> person.firstName,
"lastName" -> person.lastName,
"age" -> person.age
)
}
"Update" should {
"upsert a doc" in {
val jack = Person("Jack", "London", 27)
val result = Await.result(
collection.runCommand(Update(UpdateElement(
q = jack,
u = BSONDocument("$set" -> BSONDocument("age" -> 33)),
upsert = true))),
timeout
)
result.upserted must have size (1)
val upserted = Await.result(
collection.find(BSONDocument("_id" -> result.upserted(0)._id.asInstanceOf[Option[BSONObjectID]])).one[Person],
timeout
)
upserted must beSome
upserted.get.firstName mustEqual "Jack"
upserted.get.lastName mustEqual "London"
upserted.get.age mustEqual 33
}
"update a doc" in {
val jack = Person("Jack", "London", 33)
val result = Await.result(
collection.runCommand(Update(UpdateElement(
q = jack,
u = BSONDocument("$set" -> BSONDocument("age" -> 66))))),
timeout
)
result.nModified mustEqual 1
val updated = Await.result(
collection.find(BSONDocument("age" -> 66)).one[Person],
timeout
)
updated must beSome
updated.get.firstName mustEqual "Jack"
updated.get.lastName mustEqual "London"
}
}
}
| reactific/ReactiveMongo | driver/src/test/scala/commands/UpdateSpec.scala | Scala | apache-2.0 | 2,289 |
package com.karasiq.torrentstream.shared
import boopickle.Pickler
import boopickle.Default._
@SerialVersionUID(0L)
final case class TorrentInfo(announceList: Seq[Seq[String]], comment: String,
createdBy: String, files: Seq[(String, Long)],
infoHash: String, name: String, size: Long)
object TorrentInfo {
implicit val pickler: Pickler[TorrentInfo] = generatePickler[TorrentInfo]
}
| Karasiq/torrentstream | shared/src/main/scala/com/karasiq/torrentstream/shared/TorrentInfo.scala | Scala | apache-2.0 | 444 |
/*
* Copyright 2012-2013 Stephane Godbillon (@sgodbillon) and Zenexity
*
* 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 reactivemongo.utils
import scala.concurrent._
import scala.concurrent.duration._
object `package` {
/** Concats two array - fast way */
def concat[T](a1: Array[T], a2: Array[T])(implicit m: Manifest[T]): Array[T] = {
var i, j = 0
val result = new Array[T](a1.length + a2.length)
while (i < a1.length) {
result(i) = a1(i)
i = i + 1
}
while (j < a2.length) {
result(i + j) = a2(j)
j = j + 1
}
result
}
/** Makes an option of the value matching the condition. */
def option[T](cond: => Boolean, value: => T): Option[T] = (if (cond) Some(value) else None)
}
case class LazyLogger(logger: org.apache.logging.log4j.Logger) {
def trace(s: => String) { if (logger.isTraceEnabled) logger.trace(s) }
def trace(s: => String, e: => Throwable) { if (logger.isTraceEnabled) logger.trace(s, e) }
def debug(s: => String) { if (logger.isDebugEnabled) logger.debug(s) }
def debug(s: => String, e: => Throwable) { if (logger.isDebugEnabled) logger.debug(s, e) }
def info(s: => String) { if (logger.isInfoEnabled) logger.info(s) }
def info(s: => String, e: => Throwable) { if (logger.isInfoEnabled) logger.info(s, e) }
def warn(s: => String) { if (logger.isWarnEnabled) logger.warn(s) }
def warn(s: => String, e: => Throwable) { if (logger.isWarnEnabled) logger.warn(s, e) }
def error(s: => String) { if (logger.isErrorEnabled) logger.error(s) }
def error(s: => String, e: => Throwable) { if (logger.isErrorEnabled) logger.error(s, e) }
}
object LazyLogger {
def apply(logger: String): LazyLogger = LazyLogger(org.apache.logging.log4j.LogManager.getLogger(logger))
}
case class EitherMappableFuture[A](future: Future[A]) {
def mapEither[E <: Throwable, B](f: A => Either[E, B])(implicit ec: ExecutionContext) = {
future.flatMap(
f(_) match {
case Left(e) => Future.failed(e)
case Right(b) => Future.successful(b)
})
}
}
object EitherMappableFuture {
implicit def futureToEitherMappable[A](future: Future[A]): EitherMappableFuture[A] = EitherMappableFuture(future)
}
object ExtendedFutures {
import akka.actor.{ ActorSystem, Scheduler }
// better way to this?
def DelayedFuture(millis: Long, system: ActorSystem): Future[Unit] = {
implicit val ec = system.dispatcher
val promise = Promise[Unit]()
system.scheduler.scheduleOnce(Duration.apply(millis, "millis"))(promise.success(()))
promise.future
}
} | bfil/ReactiveMongo | driver/src/main/scala/utils.scala | Scala | apache-2.0 | 3,073 |
package im.tox.toktok.app.util
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import im.tox.toktok.TypedLayout
abstract class ActivityAdapter[VH >: Null](layout: TypedLayout[_]) extends AppCompatActivity {
private var holder: VH = null
protected def onCreateViewHolder(): VH
protected def onCreate(holder: VH): Unit
protected final override def onCreate(savedInstanceState: Bundle): Unit = {
super.onCreate(savedInstanceState)
setContentView(layout.id)
holder = onCreateViewHolder()
onCreate(holder)
}
}
| vassad/toktok | src/main/scala/im/tox/toktok/app/util/ActivityAdapter.scala | Scala | agpl-3.0 | 563 |
package org.jetbrains.plugins.scala
package lang
package psi
package api
package base
package patterns
import com.intellij.psi._
import com.intellij.psi.util.PsiModificationTracker
import org.jetbrains.plugins.scala.extensions._
import org.jetbrains.plugins.scala.lang.psi.api.base.types.ScTypeVariableTypeElement
import org.jetbrains.plugins.scala.lang.psi.api.expr._
import org.jetbrains.plugins.scala.lang.psi.api.expr.xml.ScXmlPattern
import org.jetbrains.plugins.scala.lang.psi.api.statements.params.{ScClassParameter, ScParameter, ScTypeParam}
import org.jetbrains.plugins.scala.lang.psi.api.statements.{ScFunction, ScValue, ScVariable}
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.{ScClass, ScTemplateDefinition}
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiManager
import org.jetbrains.plugins.scala.lang.psi.impl.base.ScStableCodeReferenceElementImpl
import org.jetbrains.plugins.scala.lang.psi.types
import org.jetbrains.plugins.scala.lang.psi.types._
import org.jetbrains.plugins.scala.lang.psi.types.result.{Failure, Success, TypeResult, TypingContext}
import org.jetbrains.plugins.scala.lang.resolve._
import org.jetbrains.plugins.scala.lang.resolve.processor.{CompletionProcessor, ExpandedExtractorResolveProcessor}
import org.jetbrains.plugins.scala.macroAnnotations.CachedInsidePsiElement
import org.jetbrains.plugins.scala.project.ScalaLanguageLevel.Scala_2_11
import org.jetbrains.plugins.scala.project._
import scala.annotation.tailrec
import scala.collection.immutable.Set
import scala.collection.mutable.ArrayBuffer
/**
* @author Alexander Podkhalyuzin
*/
trait ScPattern extends ScalaPsiElement {
def isIrrefutableFor(t: Option[ScType]): Boolean = false
def getType(ctx: TypingContext): TypeResult[ScType] = Failure("Cannot type pattern", Some(this))
def bindings: Seq[ScBindingPattern] = {
val b = new ArrayBuffer[ScBindingPattern]
def inner(p: ScPattern) {
p match {
case binding: ScBindingPattern => b += binding
case _ =>
}
for (sub <- p.subpatterns) {
inner(sub)
}
}
inner(this)
b
}
def typeVariables: Seq[ScTypeVariableTypeElement] = {
val b = new ArrayBuffer[ScTypeVariableTypeElement]
def inner(p: ScPattern) {
p match {
case ScTypedPattern(te) =>
te.accept(new ScalaRecursiveElementVisitor {
override def visitTypeVariableTypeElement(tvar: ScTypeVariableTypeElement): Unit = {
b += tvar
}
})
case _ =>
}
for (sub <- p.subpatterns) {
inner(sub)
}
}
inner(this)
b
}
override def accept(visitor: ScalaElementVisitor) {
visitor.visitPattern(this)
}
def subpatterns: Seq[ScPattern] = this match {
case _: ScReferencePattern => Seq.empty
case _ => findChildrenByClassScala[ScPattern](classOf[ScPattern])
}
private def resolveReferenceToExtractor(ref: ScStableCodeReferenceElement, i: Int, expected: Option[ScType],
patternsNumber: Int): Option[ScType] = {
val bind: Option[ScalaResolveResult] = ref.bind() match {
case Some(ScalaResolveResult(_: ScBindingPattern | _: ScParameter, _)) =>
val resolve = ref match {
case refImpl: ScStableCodeReferenceElementImpl =>
refImpl.doResolve(refImpl, new ExpandedExtractorResolveProcessor(ref, ref.refName, ref.getKinds(incomplete = false), ref.getContext match {
case inf: ScInfixPattern => inf.expectedType
case constr: ScConstructorPattern => constr.expectedType
case _ => None
}))
}
if (resolve.length != 1) None
else {
resolve(0) match {
case s: ScalaResolveResult => Some(s)
case _ => None
}
}
case m => m
}
def calculateSubstitutor(_tp: ScType, funType: ScType, substitutor: ScSubstitutor): ScSubstitutor = {
val tp = _tp match {
case ex: ScExistentialType => ex.skolem
case _ => _tp
}
def rightWay: ScSubstitutor = {
val t = Conformance.conformsInner(tp, substitutor.subst(funType), Set.empty, new ScUndefinedSubstitutor)
if (t._1) {
val undefSubst = t._2
undefSubst.getSubstitutor match {
case Some(newSubst) => newSubst.followed(substitutor)
case _ => substitutor
}
} else substitutor
}
//todo: looks quite hacky to try another direction first, do you know better? see SCL-6543
val t = Conformance.conformsInner(substitutor.subst(funType), tp, Set.empty, new ScUndefinedSubstitutor)
if (t._1) {
val undefSubst = t._2
undefSubst.getSubstitutor match {
case Some(newSubst) => newSubst.followed(substitutor)
case _ => rightWay
}
} else rightWay
}
bind match {
case Some(ScalaResolveResult(fun: ScFunction, substitutor: ScSubstitutor)) if fun.name == "unapply" &&
fun.parameters.length == 1 =>
val subst = if (fun.typeParameters.isEmpty) substitutor else {
var undefSubst = fun.typeParameters.foldLeft(ScSubstitutor.empty)((s, p) =>
s.bindT((p.name, ScalaPsiUtil.getPsiElementId(p)), ScUndefinedType(new ScTypeParameterType(p,
substitutor))))
val clazz = ScalaPsiUtil.getContextOfType(this, true, classOf[ScTemplateDefinition])
clazz match {
case clazz: ScTemplateDefinition =>
undefSubst = undefSubst.followed(new ScSubstitutor(ScThisType(clazz)))
case _ =>
}
val funType = undefSubst.subst(fun.parameters.head.getType(TypingContext.empty) match {
case Success(tp, _) => tp
case _ => return None
})
expected match {
case Some(tp) => calculateSubstitutor(tp, funType, substitutor)
case _ => substitutor
}
}
fun.returnType match {
case Success(rt, _) =>
def updateRes(tp: ScType): ScType = {
val parameters: Seq[ScTypeParam] = fun.typeParameters
tp.recursiveVarianceUpdate {
case (tp: ScTypeParameterType, variance) if parameters.contains(tp.param) =>
(true, if (variance == -1) substitutor.subst(tp.lower.v)
else substitutor.subst(tp.upper.v))
case (typez, _) => (false, typez)
}
}
if (subst.subst(rt).equiv(lang.psi.types.Boolean)) return None
val args = ScPattern.extractorParameters(subst.subst(rt), this, ScPattern.isOneArgCaseClassMethod(fun))
if (i < args.length) return Some(updateRes(subst.subst(args(i)).unpackedType))
else return None
case _ =>
}
None
case Some(ScalaResolveResult(fun: ScFunction, substitutor: ScSubstitutor)) if fun.name == "unapplySeq" &&
fun.parameters.length == 1 =>
val subst = if (fun.typeParameters.isEmpty) substitutor else {
val undefSubst = substitutor followed fun.typeParameters.foldLeft(ScSubstitutor.empty)((s, p) =>
s.bindT((p.name, ScalaPsiUtil.getPsiElementId(p)), ScUndefinedType(new ScTypeParameterType(p,
substitutor))))
val funType = undefSubst.subst(fun.parameters.head.getType(TypingContext.empty) match {
case Success(tp, _) => tp
case _ => return None
})
expected match {
case Some(tp) => calculateSubstitutor(tp, funType, substitutor)
case _ => substitutor
}
}
fun.returnType match {
case Success(rt, _) =>
val args = ScPattern.extractorParameters(subst.subst(rt), this, ScPattern.isOneArgCaseClassMethod(fun))
if (args.isEmpty) return None
if (i < args.length - 1) return Some(subst.subst(args(i)))
val lastArg = args.last
(Seq(lastArg) ++ BaseTypes.get(lastArg)).find({
case ScParameterizedType(des, seqArgs) if seqArgs.length == 1 && (ScType.extractClass(des) match {
case Some(clazz) if clazz.qualifiedName == "scala.collection.Seq" => true
case _ => false
}) => true
case _ => false
}) match {
case Some(seq@ScParameterizedType(des, seqArgs)) =>
this match {
case n: ScNamingPattern if n.getLastChild.isInstanceOf[ScSeqWildcard] => return Some(subst.subst(seq))
case _ => return Some(subst.subst(seqArgs.head))
}
case _ => return None
}
case _ =>
}
None
case _ => None
}
}
@CachedInsidePsiElement(this, PsiModificationTracker.MODIFICATION_COUNT)
def expectedType: Option[ScType] = getContext match {
case list : ScPatternList => list.getContext match {
case _var : ScVariable => Some(_var.getType(TypingContext.empty) match {
case Success(tp, _) => tp
case _ => return None
})
case _val : ScValue => Some(_val.getType(TypingContext.empty) match {
case Success(tp, _) => tp
case _ => return None
})
}
case argList : ScPatternArgumentList =>
argList.getContext match {
case constr : ScConstructorPattern =>
resolveReferenceToExtractor(constr.ref, constr.args.patterns.indexWhere(_ == this), constr.expectedType, argList.patterns.length)
case _ => None
}
case composite: ScCompositePattern => composite.expectedType
case infix: ScInfixPattern =>
val i = if (infix.leftPattern == this) 0 else {
if (this.isInstanceOf[ScTuplePattern]) return None
1
}
resolveReferenceToExtractor(infix.refernece, i, infix.expectedType, 2)
case par: ScParenthesisedPattern => par.expectedType
case patternList : ScPatterns => patternList.getContext match {
case tuple : ScTuplePattern =>
tuple.getContext match {
case infix: ScInfixPattern =>
if (infix.leftPattern != tuple) {
//so it's right pattern
val i = tuple.patternList match {
case Some(patterns: ScPatterns) => patterns.patterns.indexWhere(_ == this)
case _ => return None
}
return resolveReferenceToExtractor(infix.refernece, i + 1, infix.expectedType, tuple.patternList.get.patterns.length + 1)
}
case _ =>
}
tuple.expectedType.flatMap {
case ScTupleType(comps) =>
for ((t, p) <- comps.iterator.zip(patternList.patterns.iterator)) {
if (p == this) return Some(t)
}
None
case et0 if et0 == types.AnyRef || et0 == types.Any => Some(types.Any)
case _ => None
}
case _: ScXmlPattern =>
val nodeClass: PsiClass = ScalaPsiManager.instance(getProject).getCachedClass(getResolveScope, "scala.xml.Node").orNull
if (nodeClass == null) return None
this match {
case n: ScNamingPattern if n.getLastChild.isInstanceOf[ScSeqWildcard] =>
val seqClass: PsiClass =
ScalaPsiManager.instance(getProject).getCachedClass(getResolveScope, "scala.collection.Seq").orNull
if (seqClass == null) return None
Some(ScParameterizedType(ScDesignatorType(seqClass), Seq(ScDesignatorType(nodeClass))))
case _ => Some(ScDesignatorType(nodeClass))
}
case _ => None
}
case clause: ScCaseClause => clause.getContext/*clauses*/.getContext match {
case matchStat : ScMatchStmt => matchStat.expr match {
case Some(e) => Some(e.getType(TypingContext.empty).getOrAny)
case _ => None
}
case b: ScBlockExpr if b.getContext.isInstanceOf[ScCatchBlock] =>
val thr = ScalaPsiManager.instance(getProject).getCachedClass(getResolveScope, "java.lang.Throwable")
thr.map(ScType.designator(_))
case b : ScBlockExpr =>
b.expectedType(fromUnderscore = false) match {
case Some(et) =>
et.removeAbstracts match {
case ScFunctionType(_, Seq()) => Some(types.Unit)
case ScFunctionType(_, Seq(p0)) => Some(p0)
case ScFunctionType(_, params) =>
val tt = ScTupleType(params)(getProject, getResolveScope)
Some(tt)
case ScPartialFunctionType(_, param) => Some(param)
case _ => None
}
case None => None
}
case _ => None
}
case named: ScNamingPattern => named.expectedType
case gen: ScGenerator =>
val analog = getAnalog
if (analog != this) analog.expectedType
else None
case enum: ScEnumerator =>
if (enum.rvalue == null) return None
Some(enum.rvalue.getType(TypingContext.empty) match {
case Success(tp, _) => tp
case _ => return None
})
case _ => None
}
def getAnalog: ScPattern = {
getContext match {
case gen: ScGenerator =>
val f: ScForStatement = gen.getContext.getContext match {
case fr: ScForStatement => fr
case _ => return this
}
f.getDesugarizedExpr match {
case Some(expr) =>
if (analog != null) return analog
case _ =>
}
this
case _ => this
}
}
var desugarizedPatternIndex = -1
var analog: ScPattern = null
}
object ScPattern {
def isOneArgCaseClassMethod(fun: ScFunction): Boolean = {
fun.syntheticCaseClass match {
case Some(c: ScClass) => c.constructor.exists(_.effectiveFirstParameterSection.length == 1)
case _ => false
}
}
private def findMember(name: String, tp: ScType, place: PsiElement): Option[ScType] = {
val cp = new CompletionProcessor(StdKinds.methodRef, place, forName = Some(name))
cp.processType(tp, place)
cp.candidatesS.flatMap {
case ScalaResolveResult(fun: ScFunction, subst) if fun.parameters.isEmpty && fun.name == name =>
Seq(subst.subst(fun.returnType.getOrAny))
case ScalaResolveResult(b: ScBindingPattern, subst) if b.name == name =>
Seq(subst.subst(b.getType(TypingContext.empty).getOrAny))
case ScalaResolveResult(param: ScClassParameter, subst) if param.name == name =>
Seq(subst.subst(param.getType(TypingContext.empty).getOrAny))
case _ => Seq.empty
}.headOption
}
private def extractPossibleProductParts(receiverType: ScType, place: PsiElement, isOneArgCaseClass: Boolean): Seq[ScType] = {
val res: ArrayBuffer[ScType] = new ArrayBuffer[ScType]()
@tailrec
def collect(i: Int) {
findMember(s"_$i", receiverType, place) match {
case Some(tp) if !isOneArgCaseClass =>
res += tp
collect(i + 1)
case _ =>
if (i == 1) res += receiverType
}
}
collect(1)
res.toSeq
}
def extractProductParts(tp: ScType, place: PsiElement): Seq[ScType] = {
extractPossibleProductParts(tp, place, isOneArgCaseClass = false)
}
def extractorParameters(returnType: ScType, place: PsiElement, isOneArgCaseClass: Boolean): Seq[ScType] = {
def collectFor2_11: Seq[ScType] = {
findMember("isEmpty", returnType, place) match {
case Some(tp) if types.Boolean.equiv(tp) =>
case _ => return Seq.empty
}
val receiverType = findMember("get", returnType, place).getOrElse(return Seq.empty)
extractPossibleProductParts(receiverType, place, isOneArgCaseClass)
}
val level = place.languageLevel
if (level >= Scala_2_11) collectFor2_11
else {
returnType match {
case ScParameterizedType(des, args) =>
ScType.extractClass(des) match {
case Some(clazz) if clazz.qualifiedName == "scala.Option" ||
clazz.qualifiedName == "scala.Some" =>
if (args.length == 1) {
def checkProduct(tp: ScType): Seq[ScType] = {
val productChance = collectFor2_11
if (productChance.length <= 1) Seq(tp)
else {
val productFqn = "scala.Product" + productChance.length
(for {
productClass <- ScalaPsiManager.instance(place.getProject).getCachedClass(place.getResolveScope, productFqn)
clazz <- ScType.extractClass(tp, Some(place.getProject))
} yield clazz == productClass || clazz.isInheritor(productClass, true)).
filter(identity).fold(Seq(tp))(_ => productChance)
}
}
args.head match {
case tp if isOneArgCaseClass => Seq(tp)
case ScTupleType(comps) => comps
case tp => checkProduct(tp)
}
} else Seq.empty
case _ => Seq.empty
}
case _ => Seq.empty
}
}
}
} | LPTK/intellij-scala | src/org/jetbrains/plugins/scala/lang/psi/api/base/patterns/ScPattern.scala | Scala | apache-2.0 | 17,213 |
package backend
import akka.actor._
import com.typesafe.config.ConfigFactory
import backend.factorial._
import scala.collection.JavaConversions._
/**
* Booting a cluster backend node with all actors
*/
object Backend extends App {
// Simple cli parsing
val port = args match {
case Array() => "0"
case Array(port) => port
case args => throw new IllegalArgumentException(s"only ports. Args [ $args ] are invalid")
}
// System initialization
val properties = Map(
"akka.remote.netty.tcp.port" -> port
)
val system = ActorSystem("application", (ConfigFactory parseMap properties)
.withFallback(ConfigFactory.load())
)
// Deploy actors and services
FactorialBackend startOn system
}
| enpassant/estore | backend/src/main/scala/backend/Backend.scala | Scala | gpl-3.0 | 740 |
package controllers.circs.your_details
import app.ReportChange
import controllers.circs.report_changes.GOtherChangeInfo
import controllers.mappings.Mappings
import models.domain._
import models.view.CachedChangeOfCircs
import org.specs2.mutable._
import play.api.test.Helpers._
import play.api.test.FakeRequest
import utils.{LightFakeApplication, WithApplication}
import utils.pageobjects.circumstances.report_changes.GOtherChangeInfoPage
import utils.pageobjects.circumstances.start_of_process.GCircsYourDetailsPage
class GYourDetailsFormSpec extends Specification {
val firstName = "John"
val surname = "Smith"
val nino = "AB123456C"
val dateOfBirthDay = 5
val dateOfBirthMonth = 12
val dateOfBirthYear = 1990
val theirFirstName = "Jane"
val theirSurname = "Jones"
val theirRelationshipToYou = "Wife"
val byTelephone = "01254897675"
val wantsEmailContactCircs = "no"
val nextPageUrl = GOtherChangeInfoPage.url
section("unit", models.domain.CircumstancesReportChanges.id)
"Change of circumstances - About You Form" should {
"map data into case class" in new WithApplication {
GYourDetails.form.bind(
Map(
"firstName" -> firstName,
"surname" -> surname,
"nationalInsuranceNumber.nino" -> nino,
"dateOfBirth.day" -> dateOfBirthDay.toString,
"dateOfBirth.month" -> dateOfBirthMonth.toString,
"dateOfBirth.year" -> dateOfBirthYear.toString,
"theirFirstName" -> theirFirstName,
"theirSurname" -> theirSurname,
"theirRelationshipToYou" -> theirRelationshipToYou,
"furtherInfoContact" -> byTelephone,
"wantsEmailContactCircs" -> wantsEmailContactCircs
)
).fold(
formWithErrors => {
println(s"errors $formWithErrors.errors")
"This mapping should not happen." must equalTo("Error")
},
f => {
f.firstName must equalTo("John")
f.surname must equalTo("Smith")
}
)
}
"map data into case class no contact info" in new WithApplication {
GYourDetails.form.bind(
Map(
"firstName" -> firstName,
"surname" -> surname,
"nationalInsuranceNumber.nino" -> nino,
"dateOfBirth.day" -> dateOfBirthDay.toString,
"dateOfBirth.month" -> dateOfBirthMonth.toString,
"dateOfBirth.year" -> dateOfBirthYear.toString,
"theirFirstName" -> theirFirstName,
"theirSurname" -> theirSurname,
"theirRelationshipToYou" -> theirRelationshipToYou,
"wantsEmailContactCircs" -> wantsEmailContactCircs
)
).fold(
formWithErrors => "This mapping should not happen." must equalTo("Error"),
f => {
f.firstName must equalTo("John")
f.surname must equalTo("Smith")
}
)
}
"reject too many characters in text fields" in new WithApplication {
GYourDetails.form.bind(
Map(
"firstName" -> "a really long first name greater than max",
"surname" -> "a really long surname greater than max",
"nationalInsuranceNumber.nino" -> nino,
"dateOfBirth.day" -> dateOfBirthDay.toString,
"dateOfBirth.month" -> dateOfBirthMonth.toString,
"dateOfBirth.year" -> dateOfBirthYear.toString,
"theirFirstName" -> "HARACTERS,CHARACTE,HARACTERS,CHARACTE,HARACTERS,CHARACTE,HARACTERS,CHARACTE",
"theirSurname" -> "HARACTERS,CHARACTE,HARACTERS,CHARACTE,HARACTERS,CHARACTE,HARACTERS,CHARACTE",
"theirRelationshipToYou" -> "HARACTERS,CHARACTE,HARACTERS,CHARACTE",
"furtherInfoContact" -> byTelephone,
"wantsEmailContactCircs" -> wantsEmailContactCircs
)).fold(
formWithErrors => {
println(formWithErrors)
formWithErrors.errors.length must equalTo(5)
formWithErrors.errors(0).message must equalTo(Mappings.maxLengthError)
formWithErrors.errors(1).message must equalTo(Mappings.maxLengthError)
formWithErrors.errors(2).message must equalTo(Mappings.maxLengthError)
formWithErrors.errors(3).message must equalTo(Mappings.maxLengthError)
formWithErrors.errors(4).message must equalTo(Mappings.maxLengthError)
},
f => "This mapping should not happen." must equalTo("Valid"))
}
"reject characters in contact number field" in new WithApplication {
GYourDetails.form.bind(
Map(
"firstName" -> firstName,
"surname" -> surname,
"nationalInsuranceNumber.nino" -> nino,
"dateOfBirth.day" -> dateOfBirthDay.toString,
"dateOfBirth.month" -> dateOfBirthMonth.toString,
"dateOfBirth.year" -> dateOfBirthYear.toString,
"theirFirstName" -> theirFirstName,
"theirSurname" -> theirSurname,
"theirRelationshipToYou" -> theirRelationshipToYou,
"furtherInfoContact" -> "dhjahskdk",
"wantsEmailContactCircs" -> wantsEmailContactCircs
)).fold(
formWithErrors => {
formWithErrors.errors.length must equalTo(1)
formWithErrors.errors(0).message must equalTo(Mappings.errorInvalid)
},
f => "This mapping should not happen." must equalTo("Valid"))
}
"reject too many digits in contact number field" in new WithApplication {
GYourDetails.form.bind(
Map(
"firstName" -> firstName,
"surname" -> surname,
"nationalInsuranceNumber.nino" -> nino,
"dateOfBirth.day" -> dateOfBirthDay.toString,
"dateOfBirth.month" -> dateOfBirthMonth.toString,
"dateOfBirth.year" -> dateOfBirthYear.toString,
"theirFirstName" -> theirFirstName,
"theirSurname" -> theirSurname,
"theirRelationshipToYou" -> theirRelationshipToYou,
"furtherInfoContact" -> "012345678901234567890",
"wantsEmailContactCircs" -> wantsEmailContactCircs
)).fold(
formWithErrors => {
formWithErrors.errors.length must equalTo(1)
formWithErrors.errors(0).message must equalTo(Mappings.errorInvalid)
},
f => "This mapping should not happen." must equalTo("Valid"))
}
"reject too few digits in contact number field" in new WithApplication {
GYourDetails.form.bind(
Map(
"firstName" -> firstName,
"surname" -> surname,
"nationalInsuranceNumber.nino" -> nino,
"dateOfBirth.day" -> dateOfBirthDay.toString,
"dateOfBirth.month" -> dateOfBirthMonth.toString,
"dateOfBirth.year" -> dateOfBirthYear.toString,
"theirFirstName" -> theirFirstName,
"theirSurname" -> theirSurname,
"theirRelationshipToYou" -> theirRelationshipToYou,
"furtherInfoContact" -> "012345",
"wantsEmailContactCircs" -> wantsEmailContactCircs
)).fold(
formWithErrors => {
formWithErrors.errors.length must equalTo(1)
formWithErrors.errors(0).message must equalTo(Mappings.errorInvalid)
},
f => "This mapping should not happen." must equalTo("Valid"))
}
"reject special characters in text fields pre drs schema" in new WithApplication(app = LightFakeApplication(additionalConfiguration = Map("surname-drs-regex" -> "false"))) {
GYourDetails.form.bind(
Map(
"firstName" -> "John >",
"surname" -> "Smith $",
"nationalInsuranceNumber.nino" -> nino,
"dateOfBirth.day" -> dateOfBirthDay.toString,
"dateOfBirth.month" -> dateOfBirthMonth.toString,
"dateOfBirth.year" -> dateOfBirthYear.toString,
"theirFirstName" -> "Jane >",
"theirSurname" -> "Evans $",
"theirRelationshipToYou" -> "Wife >",
"furtherInfoContact" -> byTelephone,
"wantsEmailContactCircs" -> wantsEmailContactCircs
)).fold(
formWithErrors => {
println("FORMWITHERRORS:" + formWithErrors)
formWithErrors.errors.length must equalTo(5)
formWithErrors.errors(0).message must equalTo(Mappings.errorRestrictedCharacters)
formWithErrors.errors(1).message must equalTo(Mappings.errorRestrictedCharacters)
formWithErrors.errors(2).message must equalTo(Mappings.errorRestrictedCharacters)
formWithErrors.errors(3).message must equalTo(Mappings.errorRestrictedCharacters)
formWithErrors.errors(4).message must equalTo(Mappings.errorRestrictedCharacters)
},
f => "This mapping should not happen." must equalTo("Valid"))
}
"reject special characters in text fields" in new WithApplication(app = LightFakeApplication(additionalConfiguration = Map("surname-drs-regex" -> "true"))) {
GYourDetails.form.bind(
Map(
"firstName" -> "John >",
"surname" -> "Smith $",
"nationalInsuranceNumber.nino" -> nino,
"dateOfBirth.day" -> dateOfBirthDay.toString,
"dateOfBirth.month" -> dateOfBirthMonth.toString,
"dateOfBirth.year" -> dateOfBirthYear.toString,
"theirFirstName" -> "Jane >",
"theirSurname" -> "Evans $",
"theirRelationshipToYou" -> "Wife >",
"furtherInfoContact" -> byTelephone,
"wantsEmailContactCircs" -> wantsEmailContactCircs
)).fold(
formWithErrors => {
formWithErrors.errors.length must equalTo(5)
// firstName
formWithErrors.errors(0).message must equalTo(Mappings.errorNameRestrictedCharacters)
// surname
formWithErrors.errors(1).message must equalTo(Mappings.errorNameRestrictedCharacters)
// theirFirstname
formWithErrors.errors(2).message must equalTo(Mappings.errorNameRestrictedCharacters)
// theirSurname
formWithErrors.errors(3).message must equalTo(Mappings.errorNameRestrictedCharacters)
// Relationship
formWithErrors.errors(4).message must equalTo(Mappings.errorRestrictedCharacters)
},
f => "This mapping should not happen." must equalTo("Valid"))
}
"have 8 mandatory fields (plus invalid Nino)" in new WithApplication {
GYourDetails.form.bind(
Map("fullName" -> "")).fold(
formWithErrors => {
formWithErrors.errors.length must equalTo(8)
formWithErrors.errors(0).message must equalTo(Mappings.errorRequired)
formWithErrors.errors(1).message must equalTo(Mappings.errorRequired)
formWithErrors.errors(3).message must equalTo(Mappings.errorRequired)
formWithErrors.errors(4).message must equalTo(Mappings.errorRequired)
formWithErrors.errors(5).message must equalTo(Mappings.errorRequired)
formWithErrors.errors(6).message must equalTo(Mappings.errorRequired)
formWithErrors.errors(7).message must equalTo(Mappings.errorRequired)
},
f => "This mapping should not happen." must equalTo("Valid"))
}
"reject invalid national insurance number" in new WithApplication {
GYourDetails.form.bind(
Map(
"firstName" -> firstName,
"surname" -> surname,
"nationalInsuranceNumber.nino" -> "INVALID",
"dateOfBirth.day" -> dateOfBirthDay.toString,
"dateOfBirth.month" -> dateOfBirthMonth.toString,
"dateOfBirth.year" -> dateOfBirthYear.toString,
"theirFirstName" -> theirFirstName,
"theirSurname" -> theirSurname,
"theirRelationshipToYou" -> theirRelationshipToYou,
"furtherInfoContact" -> byTelephone,
"wantsEmailContactCircs" -> wantsEmailContactCircs
)).fold(
formWithErrors => {
formWithErrors.errors.length must equalTo(1)
formWithErrors.errors.head.message must equalTo("error.nationalInsuranceNumber")
},
f => "This mapping should not happen." must equalTo("Valid"))
}
"reject invalid date" in new WithApplication {
GYourDetails.form.bind(
Map(
"firstName" -> firstName,
"surname" -> surname,
"nationalInsuranceNumber.nino" -> nino.toString,
"dateOfBirth.day" -> dateOfBirthDay.toString,
"dateOfBirth.month" -> dateOfBirthMonth.toString,
"dateOfBirth.year" -> "12345",
"theirFirstName" -> theirFirstName,
"theirSurname" -> theirSurname,
"theirRelationshipToYou" -> theirRelationshipToYou,
"furtherInfoContact" -> byTelephone,
"wantsEmailContactCircs" -> wantsEmailContactCircs
)).fold(
formWithErrors => {
formWithErrors.errors.length must equalTo(1)
formWithErrors.errors.head.message must equalTo(Mappings.errorInvalid)
},
f => "This mapping should not happen." must equalTo("Valid"))
}
val startDateDay = 1
val startDateMonth = 12
val startDateYear = 2012
val selfEmployed = "self-employed"
val selfEmployedTypeOfWork = "IT Consultant"
"allow maximum spaces in and around nino totalling 19 chars" in new WithApplication {
GYourDetails.form.bind(
Map(
"firstName" -> firstName,
"surname" -> surname,
"nationalInsuranceNumber.nino" -> " N R 0 1 0 2 0 3 A ",
"dateOfBirth.day" -> dateOfBirthDay.toString,
"dateOfBirth.month" -> dateOfBirthMonth.toString,
"dateOfBirth.year" -> dateOfBirthYear.toString,
"theirFirstName" -> theirFirstName,
"theirSurname" -> theirSurname,
"theirRelationshipToYou" -> theirRelationshipToYou,
"furtherInfoContact" -> byTelephone,
"wantsEmailContactCircs" -> wantsEmailContactCircs
)).fold(
formWithErrors => {
formWithErrors.errors.length must equalTo(0)
},
f => {
f.nationalInsuranceNumber.nino.getOrElse("").length mustEqual 19
f.nationalInsuranceNumber.nino mustEqual Some(" N R 0 1 0 2 0 3 A ")
f.nationalInsuranceNumber.stringify mustEqual "NR010203A"
})
}
"enforce usual validation on nino" in new WithApplication {
GYourDetails.form.bind(
Map(
"firstName" -> firstName,
"surname" -> surname,
"nationalInsuranceNumber.nino" -> " N R X 1 0 2 0 3 A ",
"dateOfBirth.day" -> dateOfBirthDay.toString,
"dateOfBirth.month" -> dateOfBirthMonth.toString,
"dateOfBirth.year" -> dateOfBirthYear.toString,
"theirFirstName" -> theirFirstName,
"theirSurname" -> theirSurname,
"theirRelationshipToYou" -> theirRelationshipToYou,
"furtherInfoContact" -> byTelephone,
"wantsEmailContactCircs" -> wantsEmailContactCircs
)).fold(
formWithErrors => {
formWithErrors.errors.length must equalTo(1)
},
f => {
"This mapping should not happen." must equalTo("Valid")
})
}
def g2FakeRequest(claimKey: String) = {
FakeRequest().withSession(CachedChangeOfCircs.key -> claimKey).withFormUrlEncodedBody(
"firstName" -> firstName,
"surname" -> surname,
"nationalInsuranceNumber.nino" -> nino,
"dateOfBirth.day" -> dateOfBirthDay.toString,
"dateOfBirth.month" -> dateOfBirthMonth.toString,
"dateOfBirth.year" -> dateOfBirthYear.toString,
"theirFirstName" -> theirFirstName,
"theirSurname" -> theirSurname,
"theirRelationshipToYou" -> theirRelationshipToYou,
"furtherInfoContact" -> byTelephone,
"wantsEmailContactCircs" -> wantsEmailContactCircs
)
}
"Controller flow " should {
"redirect to the next page after a valid additional info submission" in new WithApplication with MockForm {
val claim = Claim(claimKey)
cache.set("default" + claimKey, claim.update(ReportChangeReason(false, ReportChange.AdditionalInfo.name)))
val result = GYourDetails.submit(g2FakeRequest(claimKey))
redirectLocation(result) must beSome(nextPageUrl)
}
}
}
section("unit", models.domain.CircumstancesReportChanges.id)
}
| Department-for-Work-and-Pensions/ClaimCapture | c3/test/controllers/circs/your_details/GYourDetailsFormSpec.scala | Scala | mit | 16,189 |
/*
* RichCPD.scala
* Conditional probability distributions with rich cases.
*
* Created By: Avi Pfeffer ([email protected])
* Creation Date: Apr 25, 2011
*
* Copyright 2013 Avrom J. Pfeffer and Charles River Analytics, Inc.
* See http://www.cra.com or email [email protected] for information.
*
* See http://www.github.com/p2t2/figaro for a copy of the software license.
*/
package com.cra.figaro.library.compound
import com.cra.figaro.language._
/**
* A conditional probability distributions with rich cases with one parent.
*/
class RichCPD1[T1, U](
name: Name[U],
arg1: Element[T1],
clauses: Seq[(CPDCase[T1], Element[U])],
collection: ElementCollection) extends CachingChain[T1, U](
name,
arg1,
(t1: T1) => RichCPD.getMatch(clauses, t1),
collection)
/**
* A conditional probability distributions with rich cases with two parents.
*/
class RichCPD2[T1, T2, U](
name: Name[U],
arg1: Element[T1],
arg2: Element[T2],
clauses: Seq[((CPDCase[T1], CPDCase[T2]), Element[U])],
collection: ElementCollection) extends CachingChain[(T1, T2), U](
name,
^^(arg1, arg2),
(p: (T1, T2)) => RichCPD.getMatch(clauses, p._1, p._2),
collection)
/**
* A conditional probability distributions with rich cases with three parents.
*/
class RichCPD3[T1, T2, T3, U](
name: Name[U],
arg1: Element[T1],
arg2: Element[T2],
arg3: Element[T3],
clauses: Seq[((CPDCase[T1], CPDCase[T2], CPDCase[T3]), Element[U])],
collection: ElementCollection) extends CachingChain[(T1, T2, T3), U](
name,
^^(arg1, arg2, arg3),
(p: (T1, T2, T3)) => RichCPD.getMatch(clauses, p._1, p._2, p._3),
collection)
/**
* A conditional probability distributions with rich cases with four parents.
*/
class RichCPD4[T1, T2, T3, T4, U](
name: Name[U],
arg1: Element[T1],
arg2: Element[T2],
arg3: Element[T3],
arg4: Element[T4],
clauses: Seq[((CPDCase[T1], CPDCase[T2], CPDCase[T3], CPDCase[T4]), Element[U])],
collection: ElementCollection) extends CachingChain[(T1, T2, T3, T4), U](
name,
^^(arg1, arg2, arg3, arg4),
(p: (T1, T2, T3, T4)) => RichCPD.getMatch(clauses, p._1, p._2, p._3, p._4),
collection)
/**
* A conditional probability distributions with rich cases with five parents.
*/
class RichCPD5[T1, T2, T3, T4, T5, U](
name: Name[U],
arg1: Element[T1],
arg2: Element[T2],
arg3: Element[T3],
arg4: Element[T4],
arg5: Element[T5],
clauses: Seq[((CPDCase[T1], CPDCase[T2], CPDCase[T3], CPDCase[T4], CPDCase[T5]), Element[U])],
collection: ElementCollection) extends CachingChain[(T1, T2, T3, T4, T5), U](
name,
^^(arg1, arg2, arg3, arg4, arg5),
(p: (T1, T2, T3, T4, T5)) => RichCPD.getMatch(clauses, p._1, p._2, p._3, p._4, p._5),
collection)
object RichCPD {
/**
* Create a conditional probability distributions with rich cases with one parent.
* @param clauses A sequence of (condition, Element) pairs, where the condition specifies a CPDCase of the parent
*/
def apply[T1, U](arg1: Element[T1], clauses: (CPDCase[T1], Element[U])*)(implicit name: Name[U], collection: ElementCollection) =
new RichCPD1(name, arg1, clauses, collection)
/**
* Create a conditional probability distributions with rich cases with two parents.
* @param clauses A sequence of (condition, Element) pairs, where the condition specifies a CPDCase of each of the parents
*/
def apply[T1, T2, U](arg1: Element[T1], arg2: Element[T2],
clauses: ((CPDCase[T1], CPDCase[T2]), Element[U])*)(implicit name: Name[U], collection: ElementCollection) =
new RichCPD2(name, arg1, arg2, clauses, collection)
/**
* Create a conditional probability distributions with rich cases with three parents.
* @param clauses A sequence of (condition, Element) pairs, where the condition specifies a CPDCase of each of the parents
*/
def apply[T1, T2, T3, U](arg1: Element[T1], arg2: Element[T2], arg3: Element[T3],
clauses: ((CPDCase[T1], CPDCase[T2], CPDCase[T3]), Element[U])*)(implicit name: Name[U], collection: ElementCollection) =
new RichCPD3(name, arg1, arg2, arg3, clauses, collection)
/**
* Create a conditional probability distributions with rich cases with four parents.
* @param clauses A sequence of (condition, Element) pairs, where the condition specifies a CPDCase of each of the parents
*/
def apply[T1, T2, T3, T4, U](arg1: Element[T1], arg2: Element[T2], arg3: Element[T3], arg4: Element[T4],
clauses: ((CPDCase[T1], CPDCase[T2], CPDCase[T3], CPDCase[T4]), Element[U])*)(implicit name: Name[U], collection: ElementCollection) =
new RichCPD4(name, arg1, arg2, arg3, arg4, clauses, collection)
/**
* Create a conditional probability distributions with rich cases with five parents.
* @param clauses A sequence of (condition, Element) pairs, where the condition specifies a CPDCase of each of the parents
*/
def apply[T1, T2, T3, T4, T5, U](arg1: Element[T1], arg2: Element[T2], arg3: Element[T3], arg4: Element[T4],
arg5: Element[T5],
clauses: ((CPDCase[T1], CPDCase[T2], CPDCase[T3], CPDCase[T4], CPDCase[T5]), Element[U])*)(implicit name: Name[U], collection: ElementCollection) =
new RichCPD5(name, arg1, arg2, arg3, arg4, arg5, clauses, collection)
private[compound] def getMatch[T1, U](clauses: Seq[(CPDCase[T1], Element[U])], t1: T1): Element[U] =
clauses.find(_._1 contains t1) match {
case Some(clause) => clause._2
case None =>
throw new MatchError(t1)
}
private[compound] def getMatch[T1, T2, U](clauses: Seq[((CPDCase[T1], CPDCase[T2]), Element[U])],
t1: T1, t2: T2): Element[U] =
clauses.find(clause => (clause._1._1 contains t1) && (clause._1._2 contains t2)) match {
case Some(clause) => clause._2
case None => throw new MatchError((t1, t2))
}
private[compound] def getMatch[T1, T2, T3, U](clauses: Seq[((CPDCase[T1], CPDCase[T2], CPDCase[T3]), Element[U])],
t1: T1, t2: T2, t3: T3): Element[U] =
clauses.find(clause => (clause._1._1 contains t1) &&
(clause._1._2 contains t2) && (clause._1._3 contains t3)) match {
case Some(clause) => clause._2
case None => throw new MatchError((t1, t2, t3))
}
private[compound] def getMatch[T1, T2, T3, T4, U](
clauses: Seq[((CPDCase[T1], CPDCase[T2], CPDCase[T3], CPDCase[T4]), Element[U])],
t1: T1, t2: T2, t3: T3, t4: T4): Element[U] =
clauses.find(clause => (clause._1._1 contains t1) &&
(clause._1._2 contains t2) && (clause._1._3 contains t3) &&
(clause._1._4 contains t4)) match {
case Some(clause) => clause._2
case None => throw new MatchError((t1, t2, t3, t4))
}
private[compound] def getMatch[T1, T2, T3, T4, T5, U](
clauses: Seq[((CPDCase[T1], CPDCase[T2], CPDCase[T3], CPDCase[T4], CPDCase[T5]), Element[U])],
t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): Element[U] =
clauses.find(clause => (clause._1._1 contains t1) &&
(clause._1._2 contains t2) && (clause._1._3 contains t3) &&
(clause._1._4 contains t4) && (clause._1._5 contains t5)) match {
case Some(clause) => clause._2
case None => throw new MatchError((t1, t2, t3, t4, t5))
}
}
| jyuhuan/figaro | Figaro/src/main/scala/com/cra/figaro/library/compound/RichCPD.scala | Scala | bsd-3-clause | 7,139 |
/*
* Copyright 2010 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.
*/
package com.twitter.bijection.clojure
import com.twitter.bijection.BaseProperties
import org.scalatest.propspec.AnyPropSpec
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks
class ClojureBijectionLaws extends AnyPropSpec with ScalaCheckPropertyChecks with BaseProperties {
// TODO: Fill in tests.
}
| twitter/bijection | bijection-clojure/src/test/scala/com/twitter/bijection/clojure/ClojureBijectionLaws.scala | Scala | apache-2.0 | 911 |
/**
* Copyright 2015 Thomson Reuters
*
* 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 filters
import javax.inject._
import akka.stream.Materializer
import cmwell.ws.util.TypeHelpers
import play.api.libs.typedmap.TypedKey
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future}
/**
* Proj: server
* User: gilad
* Date: 10/24/17
* Time: 8:04 AM
*/
class GeneralAttributesFilter @Inject()(implicit val mat: Materializer, ec: ExecutionContext)
extends Filter
with TypeHelpers {
override def apply(f: RequestHeader => Future[Result])(rh: RequestHeader) = {
f(
rh.addAttr(Attrs.RequestReceivedTimestamp, System.currentTimeMillis())
.addAttr(Attrs.UserIP, rh.headers.get("X-Forwarded-For").getOrElse(rh.remoteAddress)) // TODO: might be good to add ip to logs when user misbehaves
)
}
}
object Attrs {
val RequestReceivedTimestamp: TypedKey[Long] = TypedKey.apply[Long]("RequestReceivedTimestamp")
val UserIP: TypedKey[String] = TypedKey.apply[String]("UserIP")
}
| hochgi/CM-Well | server/cmwell-ws/app/filters/GeneralAttributesFilter.scala | Scala | apache-2.0 | 1,565 |
package spire
package algebra
/**
* A trait for linearly ordered additive commutative monoid. The following laws holds:
*
* (1) if `a <= b` then `a + c <= b + c` (linear order),
* (2) `signum(x) = -1` if `x < 0`, `signum(x) = 1` if `x > 0`, `signum(x) = 0` otherwise,
*
* Negative elements only appear when `scalar` is a additive abelian group, and then
* (3) `abs(x) = -x` if `x < 0`, or `x` otherwise,
*
* Laws (1) and (2) lead to the triange inequality:
*
* (4) `abs(a + b) <= abs(a) + abs(b)`
*
* Signed should never be extended in implementations, rather the AdditiveCMonoid and AdditiveAbGroup subtraits.
* We cannot use self-types to express the constraint `self: AdditiveCMonoid =>` (interaction with specialization?).
*/
trait Signed[@sp(Byte, Short, Int, Long, Float, Double) A] extends Any with Order[A] {
/** Returns Zero if `a` is 0, Positive if `a` is positive, and Negative is `a` is negative. */
def sign(a: A): Sign = Sign(signum(a))
/** Returns 0 if `a` is 0, 1 if `a` is positive, and -1 is `a` is negative. */
def signum(a: A): Int
/** An idempotent function that ensures an object has a non-negative sign. */
def abs(a: A): A
def isSignZero(a: A): Boolean = signum(a) == 0
def isSignPositive(a: A): Boolean = signum(a) > 0
def isSignNegative(a: A): Boolean = signum(a) < 0
def isSignNonZero(a: A): Boolean = signum(a) != 0
def isSignNonPositive(a: A): Boolean = signum(a) <= 0
def isSignNonNegative(a: A): Boolean = signum(a) >= 0
}
trait SignedAdditiveCMonoid[@sp(Byte, Short, Int, Long, Float, Double) A] extends Any with Signed[A] with AdditiveCMonoid[A] {
/** Returns 0 if `a` is 0, 1 if `a` is positive, and -1 is `a` is negative. */
def signum(a: A): Int = {
val c = compare(a, zero)
if (c < 0) -1
else if (c > 0) 1
else 0
}
}
trait SignedAdditiveAbGroup[@sp(Byte, Short, Int, Long, Float, Double) A] extends Any with SignedAdditiveCMonoid[A] with AdditiveAbGroup[A] {
def abs(a: A): A = if (compare(a, zero) < 0) negate(a) else a
}
object Signed {
def apply[A](implicit s: Signed[A]): Signed[A] = s
}
| adampingel/spire | core/src/main/scala/spire/algebra/Signed.scala | Scala | mit | 2,102 |
/*
* 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.ignite.visor.commands
import org.apache.ignite.visor.visor
import org.scalatest._
import visor._
/**
* Test for visor's argument list parsing.
*/
class VisorArgListSpec extends FlatSpec with ShouldMatchers {
behavior of "A visor argument list"
it should "properly parse 'null' arguments" in {
val v = parseArgs(null)
assert(v.isEmpty)
}
it should "properly parse non-empty arguments" in {
val v = parseArgs("-a=b c d -minus -d=")
assert(v.size == 5)
assert(v(0)._1 == "a")
assert(v(0)._2 == "b")
assert(v(1)._1 == null)
assert(v(1)._2 == "c")
assert(v(2)._1 == null)
assert(v(2)._2 == "d")
assert(v(3)._1 == "minus")
assert(v(3)._2 == null)
assert(v(4)._1 == "d")
assert(v(4)._2 == "")
}
it should "properly parse quoted arguments" in {
val v = parseArgs("-a='b 'c' d' -minus -d=")
assert(v.size == 3)
assert(v(0)._1 == "a")
assert(v(0)._2 == "b 'c' d")
assert(v(1)._1 == "minus")
assert(v(1)._2 == null)
assert(v(2)._1 == "d")
assert(v(2)._2 == "")
}
}
| gridgain/apache-ignite | modules/visor-console/src/test/scala/org/apache/ignite/visor/commands/VisorArgListSpec.scala | Scala | apache-2.0 | 2,000 |
def map[B](f: A => B): Gen[B] =
Gen(sample.map(f), exhaustive.map(_.map(f)))
def map2[B,C](g: Gen[B])(f: (A,B) => C): Gen[C] =
Gen(sample.map2(g.sample)(f),
map2Stream(exhaustive,g.exhaustive)(map2Option(_,_)(f))) | galarragas/FpInScala | answerkey/testing/7.answer.scala | Scala | mit | 227 |
/*
* Copyright 2013 - 2020 Outworkers 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 com.outworkers.phantom.builder.serializers.datatypes
import com.outworkers.phantom.builder.QueryBuilder
import com.outworkers.phantom.builder.primitives.Primitive
import com.outworkers.phantom.builder.query.SerializationTest
import com.outworkers.phantom.builder.syntax.CQLSyntax
import org.scalatest.{FlatSpec, Matchers}
class DataTypeSerializationTest extends FlatSpec with Matchers with SerializationTest {
it should "add a static column modifier on a simple collection" in {
val stringP = Primitive[String]
db.staticCollectionTable.staticList.cassandraType shouldEqual s"list<${stringP.dataType}> static"
}
it should "freeze a collection type without a frozen inner type" in {
val qb = QueryBuilder.Collections.collectionType(
colType = CQLSyntax.Collections.list,
cassandraType = CQLSyntax.Types.BigInt,
shouldFreeze = true,
freezeInner = false,
static = false
).queryString
qb shouldEqual "frozen<list<bigint>>"
}
it should "freeze a collection type with a frozen inner type" in {
val tpe = QueryBuilder.Collections.tupleType(
CQLSyntax.Types.BigInt,
CQLSyntax.Types.Text
).queryString
val qb = QueryBuilder.Collections.collectionType(
colType = CQLSyntax.Collections.list,
cassandraType = tpe,
shouldFreeze = true,
freezeInner = true,
static = false
).queryString
qb shouldEqual "frozen<list<frozen<tuple<bigint, text>>>>"
}
it should "generate a frozen collection if its used as a partition key " in {
val stringP = Primitive[String]
val cType = db.primaryCollectionsTable.listIndex.cassandraType
cType shouldEqual s"frozen<list<${stringP.dataType}>>"
}
it should "generate a frozen collection if its used as a primary key " in {
val stringP = Primitive[String]
val cType = db.primaryCollectionsTable.setCol.cassandraType
cType shouldEqual s"frozen<set<${stringP.dataType}>>"
}
it should "generate a frozen collection type for a tuple inside a list" in {
val innerP = Primitive[(Int, String)]
val cType = db.tupleCollectionsTable.tuples.cassandraType
cType shouldEqual s"list<frozen<${innerP.dataType}>>"
}
it should "generate a frozen collection type for a tuple inside a set" in {
val innerP = Primitive[(Int, String)]
val cType = db.tupleCollectionsTable.uniqueTuples.cassandraType
cType shouldEqual s"set<frozen<${innerP.dataType}>>"
}
it should "generate a frozen collection type for map with a collection key and value type" in {
val stringP = Primitive[String]
val cType = db.nestedCollectionTable.doubleProps.cassandraType
cType shouldEqual s"map<frozen<set<${stringP.dataType}>>, frozen<list<${stringP.dataType}>>>"
}
it should "generate a frozen collection type for a nested list" in {
val stringP = Primitive[String]
val cType = db.nestedCollectionTable.nestedList.cassandraType
cType shouldEqual s"list<frozen<list<${stringP.dataType}>>>"
}
it should "generate a frozen collection type for a nested list set" in {
val stringP = Primitive[String]
val cType = db.nestedCollectionTable.nestedListSet.cassandraType
cType shouldEqual s"list<frozen<set<${stringP.dataType}>>>"
}
it should "generate a frozen collection type for map with a collection value type" in {
val stringP = Primitive[String]
val cType = db.nestedCollectionTable.props.cassandraType
cType shouldEqual s"map<text, frozen<list<${stringP.dataType}>>>"
}
it should "freeze nested collections properly" in {
val stringP = Primitive[String]
val inner = Primitive[List[String]]
val listP = Primitive[List[List[String]]]
inner.frozen shouldEqual true
listP.cassandraType shouldEqual s"frozen<list<frozen<list<${stringP.dataType}>>>>"
}
it should "freeze a partition key wrapped tuple derived type" in {
val primitive = Primitive[PasswordInfo]
primitive.cassandraType shouldEqual s"frozen<tuple<text, text, text>>"
}
}
| outworkers/phantom | phantom-dsl/src/test/scala/com/outworkers/phantom/builder/serializers/datatypes/DataTypeSerializationTest.scala | Scala | apache-2.0 | 4,634 |
/*
* Copyright 2018 Analytics Zoo 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.zoo.pipeline.api.keras.layers
import com.intel.analytics.bigdl.nn.abstractnn.AbstractModule
import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.utils.Shape
import com.intel.analytics.zoo.pipeline.api.keras.models.Sequential
import com.intel.analytics.zoo.pipeline.api.keras.serializer.ModuleSerializationTest
class Cropping3DSpec extends KerasBaseSpec {
"Cropping3D channel_first" should "be the same as Keras" in {
val kerasCode =
"""
|input_tensor = Input(shape=[4, 12, 16, 20])
|input = np.random.random([2, 4, 12, 16, 20])
|output_tensor = Cropping3D(((2, 0), (1, 2), (3, 1)),
| dim_ordering="th")(input_tensor)
|model = Model(input=input_tensor, output=output_tensor)
""".stripMargin
val seq = Sequential[Float]()
val layer = Cropping3D[Float](((2, 0), (1, 2), (3, 1)), inputShape = Shape(4, 12, 16, 20))
seq.add(layer)
checkOutputAndGrad(seq.asInstanceOf[AbstractModule[Tensor[Float], Tensor[Float], Float]],
kerasCode)
}
"Cropping3D channel_last" should "be the same as Keras" in {
val kerasCode =
"""
|input_tensor = Input(shape=[32, 32, 32, 2])
|input = np.random.random([2, 32, 32, 32, 2])
|output_tensor = Cropping3D(((1, 1), (2, 2), (0, 3)),
| dim_ordering="tf")(input_tensor)
|model = Model(input=input_tensor, output=output_tensor)
""".stripMargin
val seq = Sequential[Float]()
val layer = Cropping3D[Float](((1, 1), (2, 2), (0, 3)), dimOrdering = "tf",
inputShape = Shape(32, 32, 32, 2))
seq.add(layer)
checkOutputAndGrad(seq.asInstanceOf[AbstractModule[Tensor[Float], Tensor[Float], Float]],
kerasCode)
}
}
class Cropping3DSerialTest extends ModuleSerializationTest {
override def test(): Unit = {
val layer = Cropping3D[Float](inputShape = Shape(4, 12, 16, 20))
layer.build(Shape(2, 4, 12, 16, 20))
val input = Tensor[Float](2, 4, 12, 16, 20).rand()
runSerializationTest(layer, input)
}
}
| intel-analytics/analytics-zoo | zoo/src/test/scala/com/intel/analytics/zoo/pipeline/api/keras/layers/Cropping3DSpec.scala | Scala | apache-2.0 | 2,719 |
/*
* 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.openwhisk.core.controller.actions
import java.time.{Clock, Instant}
import java.util.concurrent.atomic.AtomicReference
import akka.actor.ActorSystem
import spray.json._
import spray.json.DefaultJsonProtocol._
import org.apache.openwhisk.common.{Logging, TransactionId, UserEvents}
import org.apache.openwhisk.core.connector.{EventMessage, MessagingProvider}
import org.apache.openwhisk.core.containerpool.Interval
import org.apache.openwhisk.core.controller.WhiskServices
import org.apache.openwhisk.core.database.{ActivationStore, NoDocumentException, UserContext}
import org.apache.openwhisk.core.entity._
import org.apache.openwhisk.core.entity.size.SizeInt
import org.apache.openwhisk.core.entity.types._
import org.apache.openwhisk.http.Messages._
import org.apache.openwhisk.spi.SpiLoader
import org.apache.openwhisk.utils.ExecutionContextFactory.FutureExtensions
import spray.json._
import scala.collection._
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
import scala.language.postfixOps
import scala.util.{Failure, Success}
protected[actions] trait SequenceActions {
/** The core collections require backend services to be injected in this trait. */
services: WhiskServices =>
/** An actor system for timed based futures. */
protected implicit val actorSystem: ActorSystem
/** An execution context for futures. */
protected implicit val executionContext: ExecutionContext
protected implicit val logging: Logging
/** Database service to CRUD actions. */
protected val entityStore: EntityStore
/** Database service to get activations. */
protected val activationStore: ActivationStore
/** Instace of the controller. This is needed to write user-metrics. */
protected val activeAckTopicIndex: ControllerInstanceId
/** Message producer. This is needed to write user-metrics. */
private val messagingProvider = SpiLoader.get[MessagingProvider]
private val producer = messagingProvider.getProducer(services.whiskConfig)
/** A method that knows how to invoke a single primitive action. */
protected[actions] def invokeAction(
user: Identity,
action: WhiskActionMetaData,
payload: Option[JsObject],
waitForResponse: Option[FiniteDuration],
cause: Option[ActivationId])(implicit transid: TransactionId): Future[Either[ActivationId, WhiskActivation]]
/**
* Executes a sequence by invoking in a blocking fashion each of its components.
*
* @param user the user invoking the action
* @param action the sequence action to be invoked
* @param components the actions in the sequence
* @param payload the dynamic arguments for the activation
* @param waitForOutermostResponse some duration iff this is a blocking invoke
* @param cause the id of the activation that caused this sequence (defined only for inner sequences and None for topmost sequences)
* @param topmost true iff this is the topmost sequence invoked directly through the api (not indirectly through a sequence)
* @param atomicActionsCount the dynamic atomic action count observed so far since the start of invocation of the topmost sequence(0 if topmost)
* @param transid a transaction id for logging
* @return a future of type (ActivationId, Some(WhiskActivation), atomicActionsCount) if blocking; else (ActivationId, None, 0)
*/
protected[actions] def invokeSequence(
user: Identity,
action: WhiskActionMetaData,
components: Vector[FullyQualifiedEntityName],
payload: Option[JsObject],
waitForOutermostResponse: Option[FiniteDuration],
cause: Option[ActivationId],
topmost: Boolean,
atomicActionsCount: Int)(implicit transid: TransactionId): Future[(Either[ActivationId, WhiskActivation], Int)] = {
require(action.exec.kind == Exec.SEQUENCE, "this method requires an action sequence")
// create new activation id that corresponds to the sequence
val seqActivationId = activationIdFactory.make()
logging.info(this, s"invoking sequence $action topmost $topmost activationid '$seqActivationId'")
val start = Instant.now(Clock.systemUTC())
val futureSeqResult: Future[(Either[ActivationId, WhiskActivation], Int)] = {
// even though the result of completeSequenceActivation is Right[WhiskActivation],
// use a more general type for futureSeqResult in case a blocking invoke takes
// longer than expected and we must return Left[ActivationId] instead
completeSequenceActivation(
seqActivationId,
// the cause for the component activations is the current sequence
invokeSequenceComponents(
user,
action,
seqActivationId,
payload,
components,
cause = Some(seqActivationId),
atomicActionsCount),
user,
action,
topmost,
waitForOutermostResponse.isDefined,
start,
cause)
}
if (topmost) { // need to deal with blocking and closing connection
waitForOutermostResponse
.map { timeout =>
logging.debug(this, s"invoke sequence blocking topmost!")
futureSeqResult.withAlternativeAfterTimeout(
timeout,
Future.successful(Left(seqActivationId), atomicActionsCount))
}
.getOrElse {
// non-blocking sequence execution, return activation id
Future.successful(Left(seqActivationId), 0)
}
} else {
// not topmost, no need to worry about terminating incoming request
// and this is a blocking activation therefore by definition
// Note: the future for the sequence result recovers from all throwable failures
futureSeqResult
}
}
/**
* Creates an activation for the sequence and writes it back to the datastore.
*/
private def completeSequenceActivation(seqActivationId: ActivationId,
futureSeqResult: Future[SequenceAccounting],
user: Identity,
action: WhiskActionMetaData,
topmost: Boolean,
blockingSequence: Boolean,
start: Instant,
cause: Option[ActivationId])(
implicit transid: TransactionId): Future[(Right[ActivationId, WhiskActivation], Int)] = {
val context = UserContext(user)
// not topmost, no need to worry about terminating incoming request
// Note: the future for the sequence result recovers from all throwable failures
futureSeqResult
.map { accounting =>
// sequence terminated, the result of the sequence is the result of the last completed activation
val end = Instant.now(Clock.systemUTC())
val seqActivation =
makeSequenceActivation(user, action, seqActivationId, accounting, topmost, cause, start, end)
(Right(seqActivation), accounting.atomicActionCnt)
}
.andThen {
case Success((Right(seqActivation), _)) =>
if (UserEvents.enabled) {
EventMessage.from(seqActivation, s"controller${activeAckTopicIndex.asString}", user.namespace.uuid) match {
case Success(msg) => UserEvents.send(producer, msg)
case Failure(t) => logging.warn(this, s"activation event was not sent: $t")
}
}
activationStore.storeAfterCheck(seqActivation, blockingSequence, None, context)(
transid,
notifier = None,
logging)
// This should never happen; in this case, there is no activation record created or stored:
// should there be?
case Failure(t) => logging.error(this, s"sequence activation failed: ${t.getMessage}")
}
}
/**
* Creates an activation for a sequence.
*/
private def makeSequenceActivation(user: Identity,
action: WhiskActionMetaData,
activationId: ActivationId,
accounting: SequenceAccounting,
topmost: Boolean,
cause: Option[ActivationId],
start: Instant,
end: Instant)(implicit transid: TransactionId): WhiskActivation = {
// compute max memory
val sequenceLimits = accounting.maxMemory map { maxMemoryAcrossActionsInSequence =>
Parameters(
WhiskActivation.limitsAnnotation,
ActionLimits(action.limits.timeout, MemoryLimit(maxMemoryAcrossActionsInSequence MB), action.limits.logs).toJson)
}
// set causedBy if not topmost sequence
val causedBy = if (!topmost) {
Some(Parameters(WhiskActivation.causedByAnnotation, JsString(Exec.SEQUENCE)))
} else None
// set waitTime for sequence action
val waitTime = {
Parameters(WhiskActivation.waitTimeAnnotation, Interval(transid.meta.start, start).duration.toMillis.toJson)
}
// set binding if an invoked action is in a package binding
val binding = action.binding map { path =>
Parameters(WhiskActivation.bindingAnnotation, JsString(path.asString))
}
// create the whisk activation
WhiskActivation(
namespace = user.namespace.name.toPath,
name = action.name,
user.subject,
activationId = activationId,
start = start,
end = end,
cause = if (topmost) None else cause, // propagate the cause for inner sequences, but undefined for topmost
response = accounting.previousResponse.getAndSet(null), // getAndSet(null) drops reference to the activation result
logs = accounting.finalLogs,
version = action.version,
publish = false,
annotations = Parameters(WhiskActivation.topmostAnnotation, JsBoolean(topmost)) ++
Parameters(WhiskActivation.pathAnnotation, JsString(action.fullyQualifiedName(false).asString)) ++
Parameters(WhiskActivation.kindAnnotation, JsString(Exec.SEQUENCE)) ++
causedBy ++ waitTime ++ binding ++
sequenceLimits,
duration = Some(accounting.duration))
}
/**
* Invokes the components of a sequence in a blocking fashion.
* Returns a vector of successful futures containing the results of the invocation of all components in the sequence.
* Unexpected behavior is modeled through an Either with activation(right) or activation response in case of error (left).
*
* Keeps track of the dynamic atomic action count.
* @param user the user invoking the sequence
* @param seqAction the sequence invoked
* @param seqActivationId the id of the sequence
* @param inputPayload the payload passed to the first component in the sequence
* @param components the components in the sequence
* @param cause the activation id of the sequence that lead to invoking this sequence or None if this sequence is topmost
* @param atomicActionCnt the dynamic atomic action count observed so far since the start of the execution of the topmost sequence
* @return a future which resolves with the accounting for a sequence, including the last result, duration, and activation ids
*/
private def invokeSequenceComponents(
user: Identity,
seqAction: WhiskActionMetaData,
seqActivationId: ActivationId,
inputPayload: Option[JsObject],
components: Vector[FullyQualifiedEntityName],
cause: Option[ActivationId],
atomicActionCnt: Int)(implicit transid: TransactionId): Future[SequenceAccounting] = {
// For each action in the sequence, fetch any of its associated parameters (including package or binding).
// We do this for all of the actions in the sequence even though it may be short circuited. This is to
// hide the latency of the fetches from the datastore and the parameter merging that has to occur. It
// may be desirable in the future to selectively speculate over a smaller number of components rather than
// the entire sequence.
//
// This action/parameter resolution is done in futures; the execution starts as soon as the first component
// is resolved.
val resolvedFutureActions = resolveDefaultNamespace(components, user) map { c =>
WhiskActionMetaData.resolveActionAndMergeParameters(entityStore, c)
}
// this holds the initial value of the accounting structure, including the input boxed as an ActivationResponse
val initialAccounting = Future.successful {
SequenceAccounting(atomicActionCnt, ActivationResponse.payloadPlaceholder(inputPayload))
}
// execute the actions in sequential blocking fashion
resolvedFutureActions
.foldLeft(initialAccounting) { (accountingFuture, futureAction) =>
accountingFuture.flatMap { accounting =>
if (accounting.atomicActionCnt < actionSequenceLimit) {
invokeNextAction(user, futureAction, accounting, cause, transid)
.flatMap { accounting =>
if (!accounting.shortcircuit) {
Future.successful(accounting)
} else {
// this is to short circuit the fold
Future.failed(FailedSequenceActivation(accounting)) // terminates the fold
}
}
.recoverWith {
case _: NoDocumentException =>
val updatedAccount =
accounting.fail(ActivationResponse.applicationError(sequenceComponentNotFound), None)
Future.failed(FailedSequenceActivation(updatedAccount)) // terminates the fold
}
} else {
val updatedAccount = accounting.fail(ActivationResponse.applicationError(sequenceIsTooLong), None)
Future.failed(FailedSequenceActivation(updatedAccount)) // terminates the fold
}
}
}
.recoverWith {
// turn the failed accounting back to success; this is the only possible failure
// since all throwables are recovered with a failed accounting instance and this is
// in turned boxed to FailedSequenceActivation
case FailedSequenceActivation(accounting) => Future.successful(accounting)
}
}
/**
* Invokes one component from a sequence action. Unless an unexpected whisk failure happens, the future returned is always successful.
* The return is a tuple of
* 1. either an activation (right) or an activation response (left) in case the activation could not be retrieved
* 2. the dynamic count of atomic actions observed so far since the start of the topmost sequence on behalf which this action is executing
*
* The method distinguishes between invoking a sequence or an atomic action.
* @param user the user executing the sequence
* @param futureAction the future which fetches the action to be invoked from the db
* @param accounting the state of the sequence activation, contains the dynamic activation count, logs and payload for the next action
* @param cause the activation id of the first sequence containing this activations
* @return a future which resolves with updated accounting for a sequence, including the last result, duration, and activation ids
*/
private def invokeNextAction(user: Identity,
futureAction: Future[WhiskActionMetaData],
accounting: SequenceAccounting,
cause: Option[ActivationId],
parentTid: TransactionId): Future[SequenceAccounting] = {
futureAction.flatMap { action =>
implicit val transid: TransactionId = TransactionId.childOf(parentTid)
// the previous response becomes input for the next action in the sequence;
// the accounting no longer needs to hold a reference to it once the action is
// invoked, so previousResponse.getAndSet(null) drops the reference at this point
// which prevents dragging the previous response for the lifetime of the next activation
val inputPayload = accounting.previousResponse.getAndSet(null).result.map(_.asJsObject)
// invoke the action by calling the right method depending on whether it's an atomic action or a sequence
val futureWhiskActivationTuple = action.toExecutableWhiskAction match {
case None =>
val SequenceExecMetaData(components) = action.exec
logging.debug(this, s"sequence invoking an enclosed sequence $action")
// call invokeSequence to invoke the inner sequence; this is a blocking activation by definition
invokeSequence(
user,
action,
components,
inputPayload,
None,
cause,
topmost = false,
accounting.atomicActionCnt)
case Some(executable) =>
// this is an invoke for an atomic action
logging.debug(this, s"sequence invoking an enclosed atomic action $action")
val timeout = action.limits.timeout.duration + 1.minute
invokeAction(user, action, inputPayload, waitForResponse = Some(timeout), cause) map {
case res => (res, accounting.atomicActionCnt + 1)
}
}
futureWhiskActivationTuple
.map {
case (Right(activation), atomicActionCountSoFar) =>
accounting.maybe(activation, atomicActionCountSoFar, actionSequenceLimit)
case (Left(activationId), atomicActionCountSoFar) =>
// the result could not be retrieved in time either from active ack or from db
logging.error(this, s"component activation timedout for $activationId")
val activationResponse = ActivationResponse.whiskError(sequenceRetrieveActivationTimeout(activationId))
accounting.fail(activationResponse, Some(activationId))
}
.recover {
// check any failure here and generate an activation response to encapsulate
// the failure mode; consider this failure a whisk error
case t: Throwable =>
logging.error(this, s"component activation failed: $t")
accounting.fail(ActivationResponse.whiskError(sequenceActivationFailure), None)
}
}
}
/** Replaces default namespaces in a vector of components from a sequence with appropriate namespace. */
private def resolveDefaultNamespace(components: Vector[FullyQualifiedEntityName],
user: Identity): Vector[FullyQualifiedEntityName] = {
// resolve any namespaces that may appears as "_" (the default namespace)
components.map(c => FullyQualifiedEntityName(c.path.resolveNamespace(user.namespace), c.name))
}
/** Max atomic action count allowed for sequences */
private lazy val actionSequenceLimit = whiskConfig.actionSequenceLimit.toInt
}
/**
* Cumulative accounting of what happened during the execution of a sequence.
*
* @param atomicActionCnt the current count of non-sequence (c.f. atomic) actions already invoked
* @param previousResponse a reference to the previous activation result which will be nulled out
* when no longer needed (see previousResponse.getAndSet(null) below)
* @param logs a mutable buffer that is appended with new activation ids as the sequence unfolds
* @param duration the "user" time so far executing the sequence (sum of durations for
* all actions invoked so far which is different from the total time spent executing the sequence)
* @param maxMemory the maximum memory annotation observed so far for the
* components (needed to annotate the sequence with GB-s)
* @param shortcircuit when true, stops the execution of the next component in the sequence
*/
protected[actions] case class SequenceAccounting(atomicActionCnt: Int,
previousResponse: AtomicReference[ActivationResponse],
logs: mutable.Buffer[ActivationId],
duration: Long = 0,
maxMemory: Option[Int] = None,
shortcircuit: Boolean = false) {
/** @return the ActivationLogs data structure for this sequence invocation */
def finalLogs = ActivationLogs(logs.map(id => id.asString).toVector)
/** The previous activation was successful. */
private def success(activation: WhiskActivation, newCnt: Int, shortcircuit: Boolean = false) = {
previousResponse.set(null)
SequenceAccounting(
prev = this,
newCnt = newCnt,
shortcircuit = shortcircuit,
incrDuration = activation.duration,
newResponse = activation.response,
newActivationId = activation.activationId,
newMemoryLimit = activation.annotations.get("limits") map { limitsAnnotation => // we have a limits annotation
limitsAnnotation.asJsObject.getFields("memory") match {
case Seq(JsNumber(memory)) =>
Some(memory.toInt) // we have a numerical "memory" field in the "limits" annotation
}
} getOrElse { None })
}
/** The previous activation failed (this is used when there is no activation record or an internal error. */
def fail(failureResponse: ActivationResponse, activationId: Option[ActivationId]) = {
require(!failureResponse.isSuccess)
logs.appendAll(activationId)
copy(previousResponse = new AtomicReference(failureResponse), shortcircuit = true)
}
/** Determines whether the previous activation succeeded or failed. */
def maybe(activation: WhiskActivation, newCnt: Int, maxSequenceCnt: Int) = {
// check conditions on payload that may lead to interrupting the execution of the sequence
// short-circuit the execution of the sequence iff the payload contains an error field
// and is the result of an action return, not the initial payload
val outputPayload = activation.response.result.map(_.asJsObject)
val payloadContent = outputPayload getOrElse JsObject.empty
val errorField = payloadContent.fields.get(ActivationResponse.ERROR_FIELD)
val withinSeqLimit = newCnt <= maxSequenceCnt
if (withinSeqLimit && errorField.isEmpty) {
// all good with this action invocation
success(activation, newCnt)
} else {
val nextActivation = if (!withinSeqLimit) {
// no error in the activation but the dynamic count of actions exceeds the threshold
// this is here as defensive code; the activation should not occur if its takes the
// count above its limit
val newResponse = ActivationResponse.applicationError(sequenceIsTooLong)
activation.copy(response = newResponse)
} else {
assert(errorField.isDefined)
activation
}
// there is an error field in the activation response. here, we treat this like success,
// in the sense of tallying up the accounting fields, but terminate the sequence early
success(nextActivation, newCnt, shortcircuit = true)
}
}
}
/**
* Three constructors for SequenceAccounting:
* - one for successful invocation of an action in the sequence,
* - one for failed invocation, and
* - one to initialize things
*/
protected[actions] object SequenceAccounting {
def maxMemory(prevMemoryLimit: Option[Int], newMemoryLimit: Option[Int]): Option[Int] = {
(prevMemoryLimit ++ newMemoryLimit).reduceOption(Math.max)
}
// constructor for successful invocations, or error'ing ones (where shortcircuit = true)
def apply(prev: SequenceAccounting,
newCnt: Int,
incrDuration: Option[Long],
newResponse: ActivationResponse,
newActivationId: ActivationId,
newMemoryLimit: Option[Int],
shortcircuit: Boolean): SequenceAccounting = {
// compute the new max memory
val newMaxMemory = maxMemory(prev.maxMemory, newMemoryLimit)
// append log entry
prev.logs += newActivationId
SequenceAccounting(
atomicActionCnt = newCnt,
previousResponse = new AtomicReference(newResponse),
logs = prev.logs,
duration = incrDuration map { prev.duration + _ } getOrElse { prev.duration },
maxMemory = newMaxMemory,
shortcircuit = shortcircuit)
}
// constructor for initial payload
def apply(atomicActionCnt: Int, initialPayload: ActivationResponse): SequenceAccounting = {
SequenceAccounting(atomicActionCnt, new AtomicReference(initialPayload), mutable.Buffer.empty)
}
}
protected[actions] case class FailedSequenceActivation(accounting: SequenceAccounting) extends Throwable
| style95/openwhisk | core/controller/src/main/scala/org/apache/openwhisk/core/controller/actions/SequenceActions.scala | Scala | apache-2.0 | 25,512 |
// ImportNameChange.scala
import util.{ Random => Bob,
Properties => Jill }
val r = new Bob
val p = Jill
| P7h/ScalaPlayground | Atomic Scala/atomic-scala-examples/examples/11_ImportsAndPackages-1stEdition/ImportNameChange.scala | Scala | apache-2.0 | 108 |
package mesosphere.marathon.upgrade
import mesosphere.marathon.core.task.Task
import mesosphere.marathon.core.task.state.MarathonTaskStatus
import mesosphere.marathon.state.Timestamp
case class ScalingProposition(tasksToKill: Option[Seq[Task]], tasksToStart: Option[Int])
object ScalingProposition {
def propose(
runningTasks: Iterable[Task],
toKill: Option[Iterable[Task]],
meetConstraints: ((Iterable[Task], Int) => Iterable[Task]),
scaleTo: Int): ScalingProposition = {
// TODO: tasks in state KILLING shouldn't be killed and should decrease the amount to kill
val runningTaskMap = Task.tasksById(runningTasks)
val toKillMap = Task.tasksById(toKill.getOrElse(Set.empty))
val (sentencedAndRunningMap, notSentencedAndRunningMap) = runningTaskMap partition {
case (k, v) =>
toKillMap.contains(k)
}
// overall number of tasks that need to be killed
val killCount = math.max(runningTasks.size - scaleTo, sentencedAndRunningMap.size)
// tasks that should be killed to meet constraints – pass notSentenced & consider the sentenced 'already killed'
val killToMeetConstraints = meetConstraints(
notSentencedAndRunningMap.values,
killCount - sentencedAndRunningMap.size
)
// rest are tasks that are not sentenced and need not be killed to meet constraints
val rest = notSentencedAndRunningMap -- killToMeetConstraints.map(_.taskId)
// TODO: this should evaluate a task's health as well
// If we need to kill tasks, the order should be LOST - UNREACHABLE - UNHEALTHY - STAGING - (EVERYTHING ELSE)
def sortByStatusAndDate(a: Task, b: Task): Boolean = {
import SortHelper._
val weightA = weight(a.status.taskStatus)
val weightB = weight(b.status.taskStatus)
if (weightA < weightB) true
else if (weightB < weightA) false
else startedAt(a) > startedAt(b)
}
val ordered =
sentencedAndRunningMap.values.toSeq ++
killToMeetConstraints.toSeq ++
rest.values.toSeq.sortWith(sortByStatusAndDate)
val candidatesToKill = ordered.take(killCount)
val numberOfTasksToStart = scaleTo - runningTasks.size + killCount
val tasksToKill = if (candidatesToKill.nonEmpty) Some(candidatesToKill) else None
val tasksToStart = if (numberOfTasksToStart > 0) Some(numberOfTasksToStart) else None
ScalingProposition(tasksToKill, tasksToStart)
}
}
private[this] object SortHelper {
/** tasks with lower weight should be killed first */
val weight: Map[MarathonTaskStatus, Int] = Map[MarathonTaskStatus, Int](
MarathonTaskStatus.Unreachable -> 1,
MarathonTaskStatus.Staging -> 2,
MarathonTaskStatus.Starting -> 3,
MarathonTaskStatus.Running -> 4).withDefaultValue(5)
def startedAt(task: Task): Timestamp = {
task.launched.flatMap(_.status.startedAt).getOrElse(Timestamp.zero)
}
}
| timcharper/marathon | src/main/scala/mesosphere/marathon/upgrade/ScalingProposition.scala | Scala | apache-2.0 | 2,876 |
package cz.cvut.fit.palicand.knapsack
import java.io.File
import java.lang.System
import com.typesafe.scalalogging.{LazyLogging, Logger}
import cz.cvut.fit.palicand.knapsack.algorithms.evolution.KnapsackGeneticAlgorithm
import scala.util.Random
/**
* Created by palicka on 15/12/15.
*/
object KnapsackEvA extends LazyLogging {
def main(args: Array[String]) {
if (args.length != 3) {
System.exit(1)
}
Random.setSeed(System.currentTimeMillis())
val inputData = args(0)
val solution = args(1)
val config = args(0)
val instances = getFileNames(new File(inputData).listFiles.filter(_.isFile).map(_.getName),
new File(solution).listFiles.filter(_.isFile).map(_.getName)).map {
case (instanceFile, solutionFile) =>
val parsed = InputParser.parseInput(scala.io.Source.fromFile(inputData + "/" + instanceFile).getLines.toSeq,
scala.io.Source.fromFile(solution + "/" + solutionFile).getLines.toSeq)
parsed.head.size -> parsed
}(collection.breakOut): scala.collection.SortedMap[Int, Seq[KnapsackInstance]]
instances.map { case (size, instanceCollection) =>
logger.info(s"Instance size: ${size}")
val solutions = instanceCollection.toList.map { (instance) =>
logger.info(s"Start: ${instance.id}")
val start = System.nanoTime()
val algorithm = new KnapsackGeneticAlgorithm(instance, 100 * instance.size, 10 * instance.size, 3, 0.01, 2)
val solution = algorithm.solve()
val runTime = System.nanoTime() - start
logger.info(s"Total: ${instance.id} ${instance.controlValue} ${solution.prices} $runTime")
solution
}
size -> solutions
}
}
def getFileNames(instanceFiles: Seq[String], solutionFiles: Seq[String]): Iterable[(String, String)] = {
val sortedInstance = instanceFiles.sortWith(compareFileNames)
val sortedSol = solutionFiles.sortWith(compareFileNames)
sortedInstance.zip(sortedSol)
}
def compareFileNames(left: String, right: String): Boolean = {
val filePattern = """.*?([0-9]+).*?""".r
val leftSize = left match {
case filePattern(size) => size.toInt
}
val rightSize = right match {
case filePattern(size) => size.toInt
}
leftSize < rightSize
}
}
| palicand/mi_paa_genetic_algorithm | src/main/scala/cz/cvut/fit/palicand/knapsack/KnapsackEvA.scala | Scala | mit | 2,275 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.