Skip to content

Instantly share code, notes, and snippets.

Avatar

agolovenko

  • SCRM
  • Barcelona
View GitHub Profile
@agolovenko
agolovenko / TimeoutFuture.scala
Last active Apr 15, 2022
Future with timeout execution in a non-blocking style via akka scheduler
View TimeoutFuture.scala
import akka.actor.Scheduler
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{ExecutionContext, Future, Promise}
object TimeoutFuture {
private class CancellableExecution[T](body: => T) extends Function[Unit, T] {
private val runningThread = new AtomicReference[Thread](null)
private val isCancelled = new AtomicBoolean(false)
@agolovenko
agolovenko / DelayedFuture.scala
Last active Apr 6, 2022
Future with delayed execution in a non-blocking style via akka scheduler
View DelayedFuture.scala
import akka.actor.Scheduler
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{ExecutionContext, Future, Promise}
object DelayedFuture {
def apply[T](scheduler: Scheduler, delay: FiniteDuration)(body: => T)(implicit ec: ExecutionContext): Future[T] = {
val delayPromise = Promise[Unit]()
scheduler.scheduleOnce(delay)(delayPromise.success(()))
@agolovenko
agolovenko / Ema.scala
Created Oct 16, 2021
Scala implementation for Exponential Moving Average indicator
View Ema.scala
object Ema {
def apply(period: Int)(data: Vector[Double]): Vector[Double] = {
if (period < 1) throw new IllegalArgumentException(s"Period ($period) is smaller than 1")
if (period > data.size) throw new IllegalArgumentException(s"Period ($period) is bigger than data size (${data.size})")
val factor = 2d / (period + 1)
data.iterator
.drop(1)
.scanLeft(data.head) { (prevEma, value) => value * factor + (1d - factor) * prevEma }
@agolovenko
agolovenko / InformationSize.scala
Created Jun 15, 2021
InformationSize: scala implementation for human-readable file sizes
View InformationSize.scala
final case class InformationSize(size: Double, unit: InformationUnit) extends Ordered[InformationSize] {
import InformationSize.{safeAdd, safeDivide, safeMultiply}
import InformationUnit._
if (size < 0d) throw new IllegalArgumentException(s"Unsupported negative size: $size")
def toBits: Double = to(Bit)
def toKiloBits: Double = to(KiloBit)
def toMegaBits: Double = to(MegaBit)
def toBytes: Double = to(Byte)