Skip to content

Instantly share code, notes, and snippets.

@valtih1978
valtih1978 / parprog - week1.sc
Last active July 27, 2017 10:59
scala solutions
// task and parallel definition can be found at https://www.coursera.org/learn/parprog1/discussions/weeks/1/threads/2gsI2DHVEeaKAhJC1hWxEQ/replies/-avxXTIBEeabvwrOSKMg4w/comments/O5yTH3K6EeeM7BK4-ybiDA
/** Computes the blurred RGBA value of a single pixel of the input image. */
def boxBlurKernel(src: Img, x: Int, y: Int, radius: Int): RGBA = {
val xMin = clamp(x-radius, 0, src.width-1)
val xMax = clamp(x+radius, 0, src.width-1)
val yMin = clamp(y-radius, 0, src.height-1)
val yMax = clamp(y+radius, 0, src.height-1)
var (i,j,n) = (xMin, yMin, 0.0)
var r,g,b,a = 0.0
@valtih1978
valtih1978 / lib.html
Last active September 2, 2018 13:06
javascript-based parser
<script id="library" title="it must be a part of starndard javascript">
const log = console.log ; const assert = console.assert
update = (o, mutator) => {mutator(o); return o}
trace = (value, format) => {format = format || (data => data) ; log(format(value)); return value};
tracejs = (msg, data) => trace(data, data => [msg, data.json()])
Object.prototype.trace = function(format) {trace(this, format)}
function range (len, begin) {begin = begin || 0
@valtih1978
valtih1978 / header.js
Last active November 14, 2016 19:06
javascript unils
const log = console.log ; const assert = console.assert
//Object.prototype.trace = function(format) {format = format || (data => data); log(format(this)); return this} // prints something wrong
const trace = (data, format) => {format = format || (data => data); log(format(data)); return data}
const tracejs = (ms, data) => trace(data, data => [ms, data.json()])
function range (len, begin) {begin = begin || 0
return Array.apply(null, Array(len)).map((_, i) => {return begin+i;})}
//Array.prototype.fill = function(filler) {return this.map(_ => filler)} // startard func
Array.prototype.equals = function(that) {return this.every((my, i) => my == that[i] )} ; [1,2].equals([1,2])
Array.prototype.sum = function() {return this.reduce((acc, el) => acc + el,0)}
import java.lang.reflect.{Method, InvocationHandler, Proxy}
import scala.language.reflectiveCalls, scala.language.postfixOps
import scala.collection.mutable, java.io._, Util._
// I called this version "reduced" because proxies are not GC-ed when not referenced by user
// This makes a code a bit simpler and, probably, even faster if proxies are small indeed.
// The experiment
// timeit "scala -J-Xmx33m ProxyDemo + 16 100 > nul"
// however suggests that this implementation is slow as 144 sec vs 129 sec for managed proxies.
@valtih1978
valtih1978 / Test.sc
Last active September 1, 2017 07:07
vhdl parser based on scala parser combinators
import Vhdl._
// TODO: CharLiteral -> Char, StringLiteral -> String to save memory
object AllTests extends App {
def recover[T](okMsg: String/*, shouldRecover: T => Boolean = _ => true*/): ParseResult[T] => ParseResult[_] = pr => pr match {
case f @ Failure(msg, rem) => Success(okMsg, rem) //if (shouldRecover(msg)) Success(okMsg, rem) else f
case e @ Error(msg, rem) => println("Recovering error " + msg); Success(okMsg, rem) //if (shouldRecover(msg)) Success(okMsg, rem) else f
case s @ Success(msg, rem) => Failure(s"we had to fail because $okMsg but succeeded with " + msg, rem); case a => a
}
@valtih1978
valtih1978 / Expressions.sc
Last active November 4, 2015 20:29
Symbolic expressions
trait E {
def e(dict: Map[Const, Int]): Int
def +(another: E): E = (this, another) match {
case (zero, _) => another // Bug! Bug! this unintentionally redefines zero
case (_, zero) => this
case _ => Plus(this, another)
}
def *(another: E): E = {
def par(e: E) = e match {case e @ Plus(a,b) => Par(e); case e => e}
Mult(par(this), par(another))
@valtih1978
valtih1978 / 1. asexual_oversimplication.scala
Last active August 29, 2015 14:25
4% degradation with every generation
// This talk https://www.youtube.com/watch?v=MGfr_col5PI claims that if 4% of healty people degenerate with every
// and if 50% recover from defective genetics then we reach 8% failed genetics. Here is the simulation that confirms this.
def sim1(healthy: Double, generation: Int = 1): Unit = if (generation < 100) {
val degenerates = 1 - healthy; println((degenerates * 100) + "% down" )
sim1(healthy * 0.96 + degenerates * 0.5, generation + 1)
} //> sim1: (healthy: Double, generation: Int)Unit
sim1(1) //> 0.0% down
//| 4.0000000000000036% down
@valtih1978
valtih1978 / 1.generators.sc
Last active August 29, 2015 14:22
Scala reactive programming FRP
object generator {
// Coursera Reactive programming
trait Generator[T] { self =>
def generate: T
def map[K](f: T => K) = new Generator[K] {
// {val sample = generate ; println("map creates a generator [" + sample.getClass().getSimpleName + "]") }
def generate: K = f(self.generate)
}
@valtih1978
valtih1978 / Scala+gcc.sc
Last active August 29, 2015 14:17
Remove executable fails after gcc > execute > kill > remove executable
File deletion does not have immediate effect at least process image file, at least when
process was killed ungracefully prematurely. I have to retry the delete in my app.
Also, EVEN IF FILE DELETED, IT IS REPORTED EXISTING and complire cannot reporduce the
file. I have to retry the compilation also.
object prog_gen extends App {
import scala.sys.process._, scala.concurrent._, ExecutionContext.Implicits.global, Paths.get
implicit def toPath(filename: String) = get(filename)
@valtih1978
valtih1978 / 1.sequence_generator.py
Last active September 17, 2017 08:42
Sequence Generator - generates some C (or Java?) programs
# There were multiple goals: to implement AI for my game, to inject bugs ino VHDL and prove that sexual demorphims
# where boys have much higher mutation rate ' Сперматозоидов у мужчины за всю его жизнь вырабатывается гораздо больше, чем яйцеклеток у женщины. Это значит, что предшественники мужских половых клеток делятся гораздо интенсивнее и, следовательно, у них больше риск возникновения мутаций.'
#, is advantageous.
# Inspired by http://eli.thegreenplace.net/2010/01/28/generating-random-sentences-from-a-context-free-grammar
from collections import defaultdict
import random
def weighted_choice(weights):
rnd = random.random() * sum(weights)