Archives 2005 - 2019    Search

Brexit, Pax Americana & urholkningen av Europa

published Jun 24, 2016 12:08   by admin ( last modified Jun 24, 2016 12:08 )

Det här (Brexit) var inte roligt. USA:s makt minskar i världen, och EU har vuxit fram för att axla ett ansvar efter Pax Americana. Men utan Storbritannien består EU bland annat av veliga västmakter (Tyskland), ett Frankrike som nu också kan tänkas gå ur och som har nog med sina egna problem, och ett antal för detta östländer där flera också går åt det nationalistiska hållet.

En bra grej med demokrati är att det är en lärande organisation, att man lär sig av de beslut man gör, korrigerar och fortsätter. Besluten och konsekvenserna blir ett slags institutionellt minne. Men ibland undrar man om det finns tid att lära; svängningarna går så fort.

Brexit, Trump, Erdogan, Polens nya regering, Fidesz, Front National i Frankrike och sverigedemokraterna ser jag som symtom på samma sak:  Elitens misslyckande att förankra sig i folklagren. Jag tror den ekonomiska politiken med QE och annat har ställt till det mycket på en kognitiv nivå: Det har uppstått en desorientering ( se http://kvartal.se/artiklar/den-nya-pessimismen ) . Och när desorienteringen sätter in så försvinner förtroendet för eliten.

Jag vet inte om det är bara jag som fast jag inte levde då ändå på något sätt har den omedelbara tiden efter 2:a världskriget i minne. Jag är inte alls säker på att man kommer att kunna bygga upp något nytt ur spillrorna av EU. De demokratiska instinkterna är inte så starka över kontinenten utan har ofta påbjudits av USA. Sveriges totala oförmåga att försvara sig, inkompetens vad gäller polis mm visar på en institutionell urholkning.  I USA har partierna föga makt över de nya politikerna: Trump, Cruz, Sanders: http://www.theatlantic.com/magazine/archive/2016/07/how-american-politics-went-insane/485570/

Klaus Mann råkade på en svensk intellektuell efter kriget och deras konversation säger en del om tillståndet då: /index_html/archive/2005/10/20/illa-stllt-bland-intellektuella-i-europa-redan-1949
Glad midsommar! :D


A new generation of hashing algorithms

published Jun 23, 2016 03:52   by admin ( last modified Jun 23, 2016 03:52 )

A competition was held and Argon2 was selected as winner:

Password Hashing Competition

It seems one of the traits they were looking at was resistance to ASIC optimization.

Honorable mentions of Catena, Lyra2, Makwa and Yescrypt.


Some languages that compile to javascript

published Jun 22, 2016 10:07   by admin ( last modified Jun 22, 2016 10:07 )

Most of these untested by me.

Scala.js Scala.js

Clojurescript clojure/clojurescript: Clojure to JS compiler

Numbers

    ClojureScript currently only supports integer and floating point literals that map to JavaScript primitives
        Ratio, BigDecimal, and BigInteger literals are currently not supported
        Equality on numbers works like JavaScript, not Clojure: (= 0.0 0) => true

Kotlin JavaScript Interop | Kotlin Blog

Nim Nim Backend Integration

Features or modules that the JavaScript platform does not support are not available. This includes:

    manual memory management (alloc, etc.)
    casting and other unsafe operations (cast operator, zeroMem, etc.)
    file management
    most modules of the Standard library
    proper 64 bit integer arithmetic
    unsigned integer arithmetic

Dart


 

 


Error control flow in javascript promise chains (bluebird)

published Jun 18, 2016 01:00   by admin ( last modified Jun 18, 2016 01:01 )

You can catch an error, but what does that mean for the control flow?

Consider this test script:

const P = require('bluebird')
function bad(){
return sdfffsf // this will throw an error
}
P.resolve(8).then(x=>x).then(bad).catch(e=>console.log('We got an error' + e)).then(x=>console.log('We got here' + x))

That script will print "We got here". The chain was not terminated early due to the error, because we put an error handler in between the function that threw the error and the function that printed to the console.

However, this will not print "We got here" because the error handler is after the print statement.

const P = require('bluebird')
function bad(){
return sdfffsf
}
P.resolve(8).then(x=>x).then(bad).then(x=>console.log('We got here' + x)).catch(e=>console.log('We got an error' + e))

 

So in a nutshell, .catch allows you to skip from the point of error and resume execution in the pipeline at an arbitrary point down the line. Remember to rethrow the error unless you want the rest of the pipeline after the catch handler to get executed.


Making find ignore directories or other stuff with -prune

published Jun 16, 2016 11:05   by admin ( last modified Jul 12, 2016 12:04 )

(Warning: correct syntax with faulty explanations follow)

This was a real head scratcher for me. There is a -prune flag you can add to the find command on e.g. the Linux command line. It prunes stuff. So my first thought was that it takes an argument after itself for what needs to be pruned. It does not.

Instead it takes arguments before itself and uses them for what to prune out of the find results. But wait, it gets weirder: -prune returns true, which means that the stuff in front of -prune will still be there. What you need is to put an -o flag after prune. Now what is that? The total amount of documentation in the find man page about -o on my Ubuntu 16.04 is this:

       The POSIX standard specifies parentheses `(', `)', negation `!' and the `and' and `or' operators ( -a, -o).

So -o is the or operator. And -prune returns true. I don't know what programming languages you are used to, but in the ones I am used to, if the left hand side returns true with the or operator, the right hand side is not evaluated at all. If you want the right hand side to be evaluated too, you would stick an and operator in between.

So anyway, here is the way to do it

find [stuff you do not want to find] -prune -o [stuff you want to find] -print

You also need the -print flag at the end, because reasons. I guess the implicit -print you usually get in find, gets lost somewhere. Without an explicit -print, it prints. Everything.

Incidentally, if you change the -o to an -a, nothing gets printed.

Actually I think I just got it, one should think like this:

find [path] - "I'm gonna find anythyng in my path. Anything"

[stuff you do not want to find] - find all this stuff, yeah  this is what matched

-prune - "Return true! Because reasons"

-o - Ignore that shit, just terminate it, let's instead talk about this:

[stuff you want to find] - The stuff I really want. It magically got here because -prune did not return true for it. Or whatever.

-print - Hi, I'm print. I crowd out implicit prints, maybe. And I bind tight to the right hand side, so never heard of the left hand stuff.

So the or operator gets false for the files and dirs not matched by -prune, so it tries the right hand side. But wait, if this is the way it works, maybe -prune is kind of redundant. Yup, on my machine these give the same results back:

$ find -path "*/node_modules/*" -prune -o -name "*.js" -print
$ find -path "*/node_modules/*" -o -name "*.js" -print

Go figure. Maybe they are not always equivalent.
 

 


New features of Javascript/ECMAScript I am starting to use

published Jun 11, 2016 12:50   by admin ( last modified Jun 11, 2016 09:02 )

Well, they may not in all cases be new to the world but here goes:

 

for ... of

Coming from python this is a no-brainer. Proper iteration over an array without getting properties

Object.keys() - JavaScript | MDN

Again, coming from python it is nice to go through the keys of an object (dictionary-style)

Arrow functions

Saves on keystrokes, and makes code more concise

Templates

It took a while to get used to the grave accents, but the fact that you can have multi line strings and have placeholders make this one interesting. Again, similar to python.

Maps

And instead of relying on Object.keys(), why not use a proper map/dictionary?

And here are things I will start to use I think:

Learning ES6: Enhanced object literals | Ben Ilegbod

From that page:

function getCar(make, model, value) {
	return {
		// with property value shorthand
		// syntax, you can omit the property
		// value if key matches variable
		// name
		make,  // same as make: make
		model, // same as model: model
		value, // same as value: value

		// computed values now work with
		// object literals
		['make' + make]: true,

		// Method definition shorthand syntax
		// omits `function` keyword & colon
		depreciate() {
			this.value -= 2500;
		}
	};
}

Ok, it turned out I needed all of those object literal improvements today, so it is now in usage by me. I needed an update to run on the nedb datbase and set a property which name is not known until runtime, so the weird [] construct was used (is Javascript turning into Perl? Using all letters?).  Before that I solved that conundrum by constructing JSON with string concatenation and then parse the result which was awkward. The shorthand for key-values worked fine in module.exports, and shorter formats of functions worked fine too.

Things I am not sure how I would benefit from using in my current style:

Symbol - JavaScript | MDN - Invisible properties, kind of.

Typed Arrays in ECMAScript 6 - Good if you work with binary data, e.g. interfacing with libraries in other languages.

Weak Maps - A way to associate data to objects which data go away (gets garbage collected) with the object.

Things I may stay away from:

Does HTML comment <!-- act as a single-line comment in JavaScript, and why? - Stack Overflow

Actually this is not new, more of a placeholder in ECMAScript documenting current browser behaviour.

Things that disappeared

Array comprehensions - were introduced and then removed(!)

 

 


javascript-object-templates: Pre-define what goes into a JSON-like object

published Jun 05, 2016 10:28   by admin ( last modified Jun 05, 2016 10:28 )

You can pre-define what goes into a JSON-like object with this:

javascript-object-templates


tryThisforAWhile: Try something for a while in a javascript promise chain

published Jun 03, 2016 10:20   by admin ( last modified Jun 03, 2016 10:26 )

Uses the promise-retry library. The idea is to have a function that retries something a couple of times, and checks if it succeeds. Failure is defined as the function you're trying is either throwing an exception, which is already handled by promise-retry, or, which is the new thing, failure can also be returning a value that a test function deems false. tryThisforAWhile takes the same parameters as promise-retry, with the addition of a "test" property in the config object, that references the test function. Changes to the code are likely. For example the test functions may in the future return true or false instead of throwing. And the test function should probably be curried so that it can be configured with testing criteria in the pipeline.

Example usage (warning, this is alpha code):

const _ = require('lodash')

const P = require('bluebird')

const repeat = require('promise-retry')

P.resolve('foo')
.then(tryThisforAWhile({retries:3, test:neverAcceptFn}, unreliableNetworkCall))
.then(continueWithSomethingElse)

function acceptFn(item) {
    console.log('Accept function triggered')
    return item
}
function neverAcceptFn(item) {
    console.log('Never accept function triggered')
    // Throw some kind of Error. This is a custom one.
    throw new utils.ApplicationError('Validation error', "I will reject anything")
}

function tryThisforAWhile(config, fn) {
    // accepts a config object according to the specifications of
    // https://www.npmjs.com/package/promise-retry
    // with the addition of a test property that should be assigned
    // a test function which should throw an exception if the test fails,
    // otherwise return the item

    return _.curry(_tryThisforAWhile)(config, fn)

    function _tryThisforAWhile(config, fn, item) {
        return repeat(config, function(retry, number) {
            return fn(item).then(config.test).catch(retry)
        })
    }
}

Understanding Alan Kay's concepts

published Jun 03, 2016 09:40   by admin ( last modified Jun 03, 2016 09:50 )

...would probably be very enlightening. I think some time I will go through this post: Ask HN: Relationship between OO and functional programming? | Hacker News

 

And see if I can make heads or tails of the concepts.

 My guess some of this reasoning underlies current systems such as clojure and datomic. Some bullet points of quotes from the text:

  •  "world-line" ideas
  • Gelernter's Linda "coordination language" as an approach to do loose coupling via description matching in a general publish and describe manner
  • McCarthy's Temporal Logic: "Real Functions in Time"
  • But John [McCarthy] fixed it by adding an extra parameter to all "facts" that represented the "time frame" when a fact was true. This created a simple temporal logic, with a visualization of "collections of facts" as stacked "layers" of world-lines.
  • Christopher Strachey -- a great fan of Lisp and McCarthy -- who realized that many kinds of programming could be unified and also be made safer by always using "old" values (from the previous frame) to make new values, which are installed in a the new frame.
  • the programming language Lucid, by Ashcroft and Wadge, which extended many of Strachey's ideas ...
  • In this model -- again partly from McCarthy, Strachey, Simula, etc., -- "time doesn't exist between stable states": the "clock" only advances when each new state is completed. The CPU itself doesn't act as a clock as far as programs are concerned.
  • This gives rise to a very simple way to do deterministic relationships that has an intrinsic and clean model of time.
  • For a variety of reasons -- none of them very good -- this way of being safe lost out in the 60s in favor of allowing race conditions in imperative programming and then trying to protect against them using terrible semaphores, etc which can lead to lock ups.
  •  This got deeper if one was aware of how Lisp 1.5 had been implemented with the possibility of late bound parameter evaluation -- FEXPRs rather than EXPRs -- the unevaluated expressions could be passed as parameters and evaled later. This allowed the ungainly "special forms" (like the conditional) to be dispensed with, they could be written as a kind of vanilla lazy function.
  • By using the temporal modeling mentioned above, one could loosen the "gears" of "eval-apply" and get functional relationships between temporal layers via safe messaging.
     

Javascript destructuring for named parameters

published May 28, 2016 02:12   by admin ( last modified May 28, 2016 02:12 )

Here is one way, adapted from 11. Parameter handling :

function selectEntries({ start, end, step }) {
    console.log(end)
}

can be called like this:

selectEntries({end:7})
>> 7

In node 5.7.0 use the flag:

--harmony_destructuring

"node.js equivalent of python's if __name__ == '__main__' "

published May 25, 2016 03:15   by admin ( last modified May 25, 2016 03:16 )

node.js equivalent of python's if __name__ == '__main__' - Stack Overflow

 

if (!module.parent) {
  // this is the main module
} else {
  // we were require()d from somewhere else
}

 


RPC built into child_process.fork in Node.js for remote calling objects

published May 18, 2016 03:30   by admin ( last modified May 18, 2016 03:35 )

This module, called "remote.js" can be required into a module (let's call it "child_module") and then if  child_module has been forked from Node.js, the mother process can send commands to any object in child_module, that has been exposed by module.exports.

Here is some example code in child_module, where we want to be able to execute "foo.bar(params)" remotely from the mother process:

const remote = require('./remote')
remote.install(module)

const foo = require('foo') // some module
foo.bar(params) // some function call, just an example

module.exports = {foo: foo} // make sure it is visible for remote

 

Here is the code for remote.js that child_module requires:

// This module allows the calling module's exported objects'
// functions/methods to be called over RPC, from the module that forked it
// useful for testing
module.exports = {
    install: install
}

const P = require('bluebird')

function install(callingModule) {
    process.on('message', function(payload) {
            var result = callingModule.exports[payload.objectName][payload.functionName](payload.parameters)
            if (payload.isFunctionCall) { // return stuff if true, otherwise not
                P.resolve(result).done(  // TODO use standard promise
                    function(res) {
                        process.send({
                            itemName: payload.objectName,
                            functionName: payload.functionName,
                            result: res
                        })
                    }) // end done
            } // endif
        } // end process.on function
    ) // end process.on
}

It works with promises by wrapping teh return value of the function call in one (which will do nothing if it is already a promise) and the resolve it.

Calling a function from the mother module would be something like this:

var childp = child_process.fork(`${__dirname}/child_module.js`
childp.send({
            objectName: 'foo',
            functionName: 'bar',
            parameters: params,
            isFunctionCall: true
        })

And to catch a return value something like this:

childp.on('message', function(payload){
 console.log("Payload from client is: " + payload)

}

Efficient network protocols for RPC

published May 17, 2016 07:36   by admin ( last modified May 17, 2016 07:36 )

YAML examples

published May 13, 2016 06:27   by admin ( last modified May 13, 2016 06:27 )

How to include a multi line string in YAML

published May 10, 2016 11:39   by admin ( last modified May 10, 2016 11:39 )

Put just a pipe character on the first line:

foo: |

Then add the string, indented on the following lines:

foo: |
    bar
    baz
    bletch
    flum

 



Nollräntor och QE kan bli liberalernas största blunder

published May 09, 2016 05:30   by admin ( last modified May 10, 2016 11:42 )

Att liberaler tillåtit negativa räntor, nollräntor och penningtryckning kan vara ett  misstag av historiska proportioner och hotar nu liberalismen över hela världen.

Alla dessa åtgärder förstör kapitalismen och desorienterar väljare. Den förstör också kapitalismens och marknadernas goda namn, eftersom åtgärderna utges vara i samklang med dem.

Men: Utan korrekt prisinformation, desorientering. Just någon slags desorientering kan ligga bakom mycket av de förskjutningar mot extremer som vi ser i väljarkårerna både i USA och i Europa, vilket Peter Santesson tagit upp: Den nya pessimismen — Kvartal. Folk reagerar negativt på desorientering, även om mätarna pekar uppåt.

Vi borde aldrig låtit dessa åtgärder passera. Även i de länder där vi inte är i regeringsställning borde vi protesterat högt och ljutt. Det finns inget liberalt i dessa reformer; de förstör informationsflödet mellan långivare och presumtiva låntagare och de flyttar stora värden från de som arbetat ihop dem till de som råkar befinna sig på en speciell plats i systemet. Åtgärderna förstör för fattiga länder genom att skicka penningflöden in och ur dem med stor godtycklighet . Åtgärderna förstör i väst och framför allt i USA genom att invagga oss i en falsk säkerhet att bara för att vi sitter på de finansiella institutionerna just nu och har en slags hävarm, så kommer det alltid att vara så.

Summa summarum kommer vi nog att se en kraftig vänstervridning, ackompanjerat av populistiska högerrörelser bland länder och samhällsskikt som upplever sig vara på tillbakagång.


Mopidy - an mpd server

published May 09, 2016 04:01   by admin ( last modified May 09, 2016 04:01 )

It seems to have some extra tricks up its sleeve compared to e.g. mpd.

 

Vanilla Mopidy only plays music from your local disk and radio streams. Through extensions, Mopidy can play music from cloud services like Spotify, SoundCloud, and Google Play Music.


Read more: Link - Mopidy


Pipelines as programming method

published May 09, 2016 01:28   by admin ( last modified May 09, 2016 01:28 )

Structuring your code in the shape of pipelines seems to alleviate a a lot of problems. I am using promise chains in javascript in this way as we speak. Or I speak. Or write, rather.

 

With these thoughts in mind, I look back at all my failures at reusable code and notice something else: It looks nothing at all like: source → algorithm → sink. In fact, it looks like a bunch of nested loops. The source data enters at the top, and gets swirled around and around in ever smaller and tighter loops, and leaves via the sink in the center of that maelstrom.


Read more: Link - Component Programming in D | Dr Dobb's


WhatsApp krypterar all trafik, tror man

published Apr 09, 2016 02:33   by admin ( last modified Apr 09, 2016 02:33 )

Eff.org har en ranking av vilka meddelande-applikationer som har bäst säkerhet. För att få full pott så måste det vara open source. WhatsApp har nu 6 av 7 poäng, med väldigt genomtänkt end-to-end kryptering enligt EFF, men inte open source så det går ju inte att kolla https://www.eff.org/deeplinks/2016/04/whatsapp-rolls-out-end-end-encryption-its-1bn-users

En annan fråga är ju om det är bra eller dåligt med kryptering. Hur som helst, full pott går till:

https://www.eff.org/secure-messaging-scorecard