Skip to content. | Skip to navigation

Personal tools
Log in
Sections
You are here: Home

jorgenmodin.net - Blog

Brexit, Pax Americana & urholkningen av Europa

Posted by admin |

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å: http://jorgenmodin.net/index_html/archive/2005/10/20/illa-stllt-bland-intellektuella-i-europa-redan-1949
Glad midsommar! :D

Jun 24, 2016 12:08

A new generation of hashing algorithms

Posted by admin |

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.

Jun 23, 2016 03:52

Some languages that compile to javascript

Posted by admin |

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


 

 

Jun 22, 2016 10:07

Error control flow in javascript promise chains (bluebird)

Posted by admin |

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.

Jun 18, 2016 01:00

Making find ignore directories or other stuff with -prune

Posted by admin |

(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 -name "*.js"  -o -name "*.mocha" -print
$ find -name "*.js"  -prune -o -name "*.mocha" -print

Go figure. Maybe they are not always equivalent.
 

 

Jun 16, 2016 11:05

New features of Javascript/ECMAScript I am starting to use

Posted by admin |

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

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 multiline 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?

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

Things that disappeared

Array comprehensions - were introduced and then removed(!)

 

 

Jun 11, 2016 12:50

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

Posted by admin |

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

javascript-object-templates

Jun 05, 2016 10:28

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

Posted by admin |

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 your 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)
        })
    }
}
Jun 03, 2016 10:20

Understanding Alan Kay's concepts

Posted by admin |

...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.
     
Jun 03, 2016 09:40

Javascript destructuring for named parameters

Posted by admin |

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
May 28, 2016 02:12
Ads