Skip to content

Instantly share code, notes, and snippets.

View Slakah's full-sized avatar

James Collier Slakah

View GitHub Profile
@Slakah
Slakah / splitWhen.scala
Created December 20, 2023 10:23
Scala splitWhen for lists
def splitWhen[A](list: List[A], f: A => Boolean): List[List[A]] = {
list.reverse.foldLeft((List.empty[List[A]], true)) {
case ((Nil, _), e) if f(e) => (Nil, true)
case ((Nil, _), e) => (List(List(e)), false)
case ((head :: tail, _), e) if f(e) => (head :: tail, true)
case ((head :: tail, false), e) => ((e :: head) :: tail, false)
case ((head :: tail, true), e) => (List(e) :: head :: tail, false)
}._1
}
@Slakah
Slakah / Sliding.scala
Created December 30, 2020 00:03
.slidingN, Scala .sliding method, but for tuples. Only relies on foldable, could do up to .sliding22
import $ivy.`org.typelevel::cats-core:2.3.0`
import cats.data.NonEmptyList
import cats.Foldable
import cats.implicits._
def sliding2[F[_] : Foldable, A](l: F[A]): Option[NonEmptyList[(A, A)]] = {
l.foldLeft[(List[(A, A)], Option[A])]((Nil, None)) {
case ((acc, Some(x1)), x2) =>
((x1, x2) :: acc, Some(x2))
case ((Nil, None), x) =>
import $ivy.`org.typelevel::cats-core:2.3.0`
def find2Addends(numbers: List[Long], sum: Long): Option[(Long, Long)] = {
numbers.collectFirstSome { x =>
val y = sum - x
if (numbers.contains(y)) Some((x, y))
else None
}
}
@Slakah
Slakah / LuceneEscape.scala
Last active September 22, 2020 17:26
Scala implementation of lucene escaping, useful when querying elasticsearch
// https://github.com/apache/lucene-solr/blob/master/lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/QueryParserBase.java#L973
def luceneEscape(s: String): String = {
// use string builder, as it's probably more efficient
val sb = new StringBuilder
s.foreach {
case char @ ('\\' | '+' | '-' | '!' | '(' | ')' | ':' | '^' | '[' | ']' | '\"' | '{' | '}' | '~' | '*' | '?' | '|' | '&' | '/') =>
sb.append('\\').append(char)
case other => sb.append(other)
}
sb.result()
@Slakah
Slakah / kms-decrypt.sh
Created September 8, 2020 17:08
Scripts to encrypt and decrypt a file
#!/bin/bash
set -euo pipefail
echoerr() { echo "$@" 1>&2; }
if [[ $# -ne 1 ]]; then
echoerr "Usage: $0 file"
exit 1
fi
@Slakah
Slakah / build.sbt
Last active August 26, 2020 11:10
Publish vendor Jar to maven from sbt
// publish to your maven repo using `sbt "myProject/publish"`
// note maven appears to only really support a single jar per library, so create multiple sub-modules
// name of the jar in modules/my-project/lib/<name>.jar
val jarName = "my-vendor-jar"
lazy val myJar = (project in file("modules/my-jar"))
.settings(
name := "my-jar",
/**
* Evaluate simple math expressions, supports add/times.
* Operator precedence is observed.
* e.g. in the expression 5+3*2, 3*2 would be evaluated first, leading to the final result of 11.
*/
def eval(expr: String): Int = {
var i = 0
var result = 0
var num = 0
while (i < expr.size) {
@Slakah
Slakah / num2word.sc
Created July 3, 2020 16:04
Scala ammonite script to turn a number into a a human readable(ish) representation, try ./num2word.sc 10002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
#!/usr/bin/env amm
@main
def main(n: BigInt): Unit =
println(num2wordList(n, List.empty).mkString(" "))
// https://en.wikipedia.org/wiki/Names_of_large_numbers
private val prefix2factor = List(
"Centillion" -> 303,
"Googol" -> 100,
@Slakah
Slakah / RequestIdMiddleware.scala
Last active June 10, 2020 12:09
Http4s X-Request-Id middleware
import java.util.UUID
import org.http4s.{Header, Http, Request, Response}
import cats.data.Kleisli
import cats.effect.Sync
import cats.implicits._
import org.http4s.syntax.string._
/**
* Propagate a `X-Request-Id` header to the response, generate a UUID
@Slakah
Slakah / IOCaseApp.scala
Created May 1, 2020 08:57
cats-effect support for case-app
package com.gubbns
import caseapp.core.Error
import caseapp.core.help.{Help, WithHelp}
import caseapp.core.parser.Parser
import caseapp.core.RemainingArgs
import cats.effect.{ExitCode, IO, IOApp}
/** IO version of CaseApp. */
abstract class IOCaseApp[T](implicit val parser: Parser[T], val messages: Help[T]) extends IOApp {