Skip to content

Instantly share code, notes, and snippets.

@latant
latant / permutations.kt
Created November 7, 2020 17:55
efficient permutations in Kotlin
import org.pcollections.PSet
fun <T> PSet<T>.permutations(): Sequence<Sequence<T>> = when {
size < 2 -> sequenceOf(asSequence())
else -> asSequence().flatMap { x -> minus(x).permutations().asSequence().map { sequenceOf(x) + it } }
}
@latant
latant / await_shutdown.kt
Created October 23, 2020 10:50
A coroutine function that suspends until a shutdown is requested
import kotlin.concurrent.thread
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
suspend fun awaitShutdown() {
suspendCoroutine<Unit> { c ->
Runtime.getRuntime().addShutdownHook(thread(start = false) {
c.resume(Unit)
})
}
@latant
latant / nodes_and_relationships_of pattern.cypher
Last active October 8, 2020 17:33
Loading distinct nodes and relationships with patterns in Neo4J 4.0
call {
match p=()--()--() return
reduce(ns = [], n in collect(nodes(p)) | ns + n) as ns,
reduce(rs = [], r in collect(relationships(p)) | rs + r) as rs
}
call { with ns unwind ns as n return collect(distinct n) as nodes }
call { with rs unwind rs as r return collect(distinct r) as relationships }
return {nodes: nodes, relationships: relationships}
@latant
latant / PrettyString.py
Created August 14, 2020 14:54
Pretty string printer for nested, circular data structures.
class PrettyStringCreation:
def pstr_list(self, l: list, opts: dict):
plist = []
for e in l:
plist.append(self.pstr(e, opts))
return '[' + ', '.join(plist) + ']'
def pstr_dict(self, d: dict, opts: dict):
sl = []
for k in d.keys():
@latant
latant / async.clj
Created July 25, 2020 00:33
An abstraction over reactive behavior
(defmulti then-fn
(fn [deferred _] (class deferred)))
(defmethod then-fn CompletableFuture [^CompletableFuture future func]
(.thenAccept future
(reify Consumer
(accept [_ result] (func result)))))
(defmacro async [arg & block]
(if (vector? arg)
@latant
latant / nio_server_coroutine.kt
Last active April 22, 2020 10:24
A demo of creating a Java NIO one threaded, non-blocking server coroutine API.
interface NioSocketServer {
fun stop()
suspend fun SelectableChannel.awaitSelection(ops: Int): SelectionKey
}
fun nioSocketServer(port: Int, acceptor: suspend NioSocketServer.(SocketChannel) -> Unit) {
var isStopped = false
val serverChannel = ServerSocketChannel.open().apply {
configureBlocking(false)
bind(InetSocketAddress(port))
@latant
latant / PList.kt
Created March 26, 2020 15:54
Simple persistent (single-linked) list implemented with Kotlin
package core
open class PList<T>(val value: T, val next: PList<T>?) : Iterable<T> {
override fun iterator() = object : Iterator<T> {
var PList: PList<T>? = this@PList
override fun hasNext() = PList != null
override fun next() = PList!!.value.also { PList = PList!!.next }
}
@latant
latant / dynamic_extension_property.kt
Created March 22, 2020 13:02
Creating extension property with backing field in Kotlin JS.
//In Kotlin, we can't create 'var' extension property that requires backing field. (https://kotlinlang.org/docs/reference/extensions.html#extension-properties)
//However, in Kotlin JS, we can can 'create' backing fields, due to the JS Object's dynamic nature.
var HTMLElement.myProp: String
get() = this.asDynamic().myProp
set(value) { this.asDynamic().myProp = value }
//We can also create custom property delegate to remove boilerplate:
class DynamicProperty<T> {
operator fun getValue(thisRef: Any, prop: KProperty<*>) = thisRef.asDynamic()[prop.name]
@latant
latant / rmi-example.kt
Created March 9, 2020 22:59
An example using Java RMI with Kotlin
import java.io.Serializable
import java.rmi.Remote
import java.rmi.RemoteException
import java.rmi.registry.LocateRegistry
import java.rmi.server.UnicastRemoteObject
class Person(val name: String, val age: Int): Serializable
interface HelloService : Remote {
@Throws(RemoteException::class)
@latant
latant / facebook_your_messages_html_fix.kt
Last active March 10, 2020 14:50
'Download your facebook information' generates html to view your messages, but the href attributes contain wrong directory names.It can be solved quickly by 'lowerCase-ing' the href attributes that start with 'messages' path segment.
import org.jsoup.Jsoup
import java.io.File
fun main(args: Array<String>) {
val (srcFile, targetFile) = args
val doc = Jsoup.parse(File(srcFile).readText())
doc.select("[href]").toList().forEach {
val pathSegments = it.attr("href").split("/").toMutableList()
if (pathSegments[0] == "messages") {
pathSegments[2] = pathSegments[2].toLowerCase()