I have been a professional in the IT business for a lot of years, less if you consider just software development, more if you count that my favorite activity since I was a kid was to mess with a computer or another. I think I know how to develop software, especially since I've kind of built my career on trying new places and new methods for doing that. And now people come to me and ask me: "Can I learn too? Can you teach me?". And the immediate answer is yes and no (heh! Learnt from the best politicians that line) Well, yes because I believe anyone who actually wants to learn can and no because I am a lousy teacher. But wait a minute... can't I become one?

You may think that it is easy to remember how it was when I was a code virgin, when I was writing Basic programs in a notebook in the hope that some day my father will buy me a computer, but it's not. My brain has picked up so many things that now they are applied automatically. I may not know what I know, but I know a lot and I am using it at all times. A few weeks ago I started thinking about these things and one of the first ideas that came to me was FizzBuzz! A program that allegedly people who can't program simple can't... err... program. Well, I thought, how would I write this best? How about worst? I even asked my wife and she gave me an idea that had never occurred to me, like not using the modulo function to determine divisibility.

And it dawned on me. To know if your code is good you need to know exactly what that code has to do. In other words, you can't program without having an idea on how to use or test it afterwards. You have to think about all the other people that would be stumbling unto your masterwork: other developers, for example, hired after you left the company, need to understand what they are looking at. You need to provide up to date and clear documentation to your users, as well. You need to handle all kinds of weird situations that your software might be subjected to. To sum it up: as a good developer you need to be a bit of all the people on the chain - users, testers, documenters, managers, marketers, colleagues - and to see the future as well. After all, you're an expert.

Of course, sketches like the one above are nothing but caricatures of people from the viewpoint of other people who don't understand them. After all, good managers need to be a little of everything as well. If you think about it, to be good at anything means you have to understand a little of everybody you work with and do your part well - exactly the opposite of specialization, the solution touted as solving every problem in the modern world. Anyway, enough philosophy. We were talking programming here.

What I mean to say is that for every bit of our craft, we developers are doing good things for other people. We code so that the computer does the job well, but we are telling it to do things that users need, we write concisely yet clear so that other developers can work from where we leave off, we write unit tests to make sure what we do is what we mean and ease the work of people who need to manually check that, we comment the code so that anyone can understand at a glance what a method does and maybe even automate the creation of documents explaining what the software does. And we draw lines in a form of a kitten so that marketers and managers sell the software - and we hate it, but we do it anyway.

So I ask, do we need to learn to write programs all over again? Because, to be frank, coders today write in TDD style because they think it's cutting edge, not that they are doing it for someone; they work in agile teams not because they know everybody will get a better understanding of what they are doing and prevent catastrophic crashes caused by lack of vision, but because they feel it takes managers off their backs and they can do their jobs; they don't write comments for the documentation team, but because they fear their small attention span might make them forget what the hell they were doing; they don't write several smaller methods instead of a large one because they believe in helping others read their code, but because some new gimmick tells them they have too much cyclomatic complexity. And so on and so on.

What if we would learn (and teach) that writing software is nothing but an abstraction layer thrown over helping all kinds of people in need and that even the least rockstar ninja superhero developer is still a hero if they do their job right? What if being a good cog in the machine is not such a bad thing?

While writing this I went all over the place, I know, and I didn't even touch what started me thinking about it: politics and laws. I was thinking that if we define the purpose of a law when we write it and package them together, anyone who can demonstrate that the effect is not the desired one can remove the law. How grand would that be? To know that something is applied upon you because no one could demonstrate that it is bad or wrong or ineffective.

We do that in software all the time, open software, for example, but also the internal processes in a programming shop designed to catch flaws early and to ensure people wrote things how they should have. Sometimes I feel so far removed from "the real world" because what I am doing seems to make more sense and in fact be more real than the crap I see all around me or on the media. What if we could apply this everywhere? Where people would take responsibility individually, not in social crowds? Where things would be working well not because a lot of people agree, but because no one can demonstrate they are working bad? What if the world is a big machine and we need to code for it?

Maybe learning to code is learning to live! Who wouldn't want to teach that?

During one revamp of the blog I realized that I didn't have images for some of my posts. I had counted pretty much on the Blogger system that provides a post.thumbnailUrl post metadata that I can use in the display of the post, but the url is not always there. Of course if you have a nice image in the post somewhere prominently displayed, the thumbnail URL will be populated, but what if you have a video? Surprisingly, Blogger has a pretty shitty video to thumbnail mechanism that prompted me to build my own.

So the requirements would be: get me the image representing a video embedded in my page, using Javascript only.

Well, first of all, videos can be actual video tags, but most of the time they are iframe elements coming from a reliable global provider like YouTube, Dailymotion, Vimeo, etc, and all the information available is the URL of the display frame. Here is the way to get the thumbnail for these scenarios:

YouTube


Given the iframe src value:

// find youtube.com/embed/[videohash] or youtube.com/embed/video/[videohash]
var m = /youtube\.com\/embed(?:\/video)?\/([^\/\?]+)/.exec(src);
if (m) {
// the thumbnail url is https://img.youtube.com/vi/[videohash]/0.jpg
imgSrc = 'https://img.youtube.com/vi/' + m[1] + '/0.jpg';
}

If you have embeds in the old object format, it is best to replace them with the iframe one. If you can't change the content, it remains your job to create the code to give you the thumbnail image.

Dailymotion


Given the iframe src value:

//find dailymotion.com/embed/video/[videohash]
var m=/dailymotion\.com\/embed\/video\/([^\/\?]+)/.exec(src);
if (m) {
// the thumbnail url is at the same URL with `thumbnail` replacing `embed`
imgSrc=src.replace('embed','thumbnail');
}

Vimeo


Vimeo doesn't have a one URL thumbnail format that I am aware of, but they have a Javascript accessible API.

// find vimeo.com/video/[videohash]
m=/vimeo\.com\/video\/([^\/\?]+)/.exec(src);
if (m) {
// set the value to the videohash initially
imgSrc=m[1];
$.ajax({
//call the API video/[videohash].json
url:'https://vimeo.com/api/v2/video/'+m[1]+'.json',
method:'GET',
success: function(data) {
if (data&&data.length) {
// and with the data replace the initial value with the thumbnail_medium value
replaceUrl(data[0].thumbnail_medium,m[1]);
}
}
});
}

In this example, the replaceUrl function would look for img elements to which the videohash value is attached and replace the url with the correct one, asynchronously.

TED


I am proud to announce that I was the one pestering them to make their API available over Javascript.

// find ted.com/talks/[video title].html
m=/ted\.com\/talks\/(.*)\.html/.exec(src);
if (m) {
// associate the video title with the image element
imgSrc=m[1];
$.ajax({
// call the oembed.json?url=frame_url
url:'https://www.ted.com/services/v1/oembed.json?url='+encodeURIComponent(src),
method:'GET',
success: function(data) {
// set the value of the image element asynchronously
replaceUrl(removeSchemeForHttpsEnabledSites(data.thumbnail_url),m[1]);
}
});
return false;
}

video tags


Of course there is no API to get the image from an arbitrary video URL, but the standard for the video tag specifies a poster attribute that can describe the static image associated with a video.

// if the element is a video with a poster value
if ($(this).is('video[poster]')) {
// use it
imgSrc=$(this).attr('poster');
}

and has 0 comments
The book was nothing if not captivating, its pace much better than for the Magicians trilogy, but as in those books, it was really really difficult to empathize with any of the characters.

The story in Codex is about this investment banker who is having the first vacation in years, actually a small transition time between switching from his US job to a London based one. This makes him feel disconnected and somehow gets tangled in a project to arrange the library of a very wealthy family. The problem with this character is that he doesn't seem to chose anything. Things just happen to him, kind of like with Quentin in the Magicians, and he goes with them, only to get disappointed or surprised at the end. His friends, the people he randomly meets, even his adversaries appear at the exact time when the story requires them, making the book feel like a string of unlikely happenstances a rather aimless character just stumbles through.

There are some interesting parallels in the book, analogies between the beginning of romantic literature and the emergence of computer game fantasy, and probably the literary and historical details in the book hide some deeper meaning as well, but it's Lev Grossman's infuriatingly detached, almost dreamlike perspective that made me not care about it at all. Strangely, all the literary research going on in the book and the altered mood made me think of House of Leaves, only that was orders of magnitude weirder and better written.

As for the ending, I think I can safely say now that it's typical Grossman: the main character becomes aware of the delusions he was living under, both relating to his goals and the people around him. The veil gets lifted and the world goes back to the usual confusing pointless drag that it is for most of us. The author doesn't seem to care about the need of the reader for a happy ending, and I would normally applaud that, yet to use a depressingly realistic ending to a story that felt torn out of a night's dream seems a bit pointless to me.

Bottom line: I actually enjoyed it better than The Magicians, perhaps because it was shorter, better paced and I could relate to the main character a bit more. However, it is not something I would recommend to people. It felt too much like describing a man during a heatstroke, always dazed and confused, spinning wildly out of control of the things happening around him, a hapless victim of his immature feelings and a situation he is out of his depth in.

I came upon a StackOverflow question today that sounded plain silly to me. In it someone was complaining that parsing a command line like "x\" -y returns a single argument, not two. And that is ridiculous, since the operating system doesn't do that.

Just to prove myself right (because I love being right) I created a batch file that displays all command line parameters:
@ECHO OFF 
SET counter=1
:loop
IF "%1"=="" EXIT
ECHO %counter% %1
SET /A counter=counter+1
SHIFT
GOTO loop

I ran the batch file with the command line supplied in the SO question: -p -z "E:\temp.zip" -v "f:\" -r -o -s –c and the result was
1 -p
2 -z
3 "E:\temp.zip"
4 -v
5 "f:\"
6 -r
7 -o
8 -s
9 –c
See? I was right! The command line is properly parsed. But just to be sure, I created a .NET console application:
static void Main(string[] args)
{
for (var i=0; i<args.Length; i++)
{
Console.WriteLine(i + " " + args[i]);
}
}
and the result was... different!
0  -p
1 -z
2 E:\temp.zip
3 -v
4 f:" -r -o -s -c
Never would I have imagined that .NET console applications would do different things from system applications, especially since they are both made by Microsoft.

Investigating the problem, I found a page that explained the rules of parsing command line arguments. It was for C++, but it applied perfectly. Apparently the caret (^) is treated just as any other character (not like by the operating system that treats it as an escape character) and a quote preceded by a backslash is considered an ordinary character as well (not like the operating system that ignores it).

So, how do I get the command line the same way the operating system does? First of all I need the raw unprocessed command line. I get that using Environment.CommandLine. Then I need to split it. Of course, I can make my own code, but I want to use the same stuff as the operating system - in this case Windows, we are not discussing .NET Core or Mono here - so I will be "Pinvoking" the Windows CommandLineToArgvW function.

And, of course, it didn't work. What I did here was basically recreating the Environment.GetCommandLineArgs method, which returns the exact same result as the args array!

Now that I had already gone through the rabbit hole, I got to this very informative link about it: How Command Line Parameters Are Parsed. In it, you may find the very aptly named chapter Everyone Parses Differently which shows that there are even differences between how C and VB programs parse the command line.

Bottom line: while you may be able to get the command line from the Environment class, there is no "standard" for parsing command line arguments, instead each compiler and operating system version implements their own. Consequently, I suggest that the only way to be consistent in how you parse command line arguments is to parse them yourself.

I had this crazy idea that I could make each word on my page come alive. The word "robot" would walk around the page, "explosion" would explode, "rotate" would rotate, color words would appear in the color they represent, no matter how weird named like OliveDrab , Chocolate , Crimson , DeepPink , DodgerBlue and so on, "radioactive" would pulse green, "Siderite" would appear in all its rocking glory and so on. And so I did!

The library is on GitHub and I urge you to come and bring your own ideas. Every effect that you see there is an addon that can be included or not in your setup.



Also see directly on GitHub pages.








Almost a month ago I got started being active on StackOverflow, a web site dedicated to answering computer related questions. It quickly got addictive, but the things that I found out there are many and subtle and I am happy with the experience.

The first thing you learn when you get into it is that you need to be fast. And I mean fast! Not your average typing-and-reading-and-going-back-to-fix-typos speed, but full on radioactive zombie attack typing. And without typos! If you don't, by the time you post your contribution the question would have been answered already. And that, in itself, is not bad, but when you have worked for minutes trying to get code working, looking good, being properly commented, taking care of all test cases, being effective, being efficient and you go there and you find someone else did the same thing, you feel cheated. And I know that my work is valid, too, and maybe even better than the answers already provided (otherwise I feel dumb), but to post it means I just reiterate what has been said before. In the spirit of good sportsmanship, I can only upvote the answer I feel is the best and eventually comment on what I think is missing. Now I realize that whenever I do post the answer first there are a lot of people feeling the same way I just described. Sorry about that, guys and gals!

The second thing you learn immediately after is that you need to not make mistakes. If you do, there will be people pointing them out to you immediately, and you get to fix them, which is not bad in itself, however, when you write something carelessly and you get told off or, worse, downvoted, you feel stupid. I am not the smartest guy in the world, but feeling stupid I don't like. True, sometimes I kind of cheat and post the answer as fast as possible and I edit it in the time I know the question poster will come check it out but before poor schmucks like me wanted to give their own answers. Hey, those are the rules! I feel bad about it, but what can you do?

Sometimes you see things that are not quite right. While you were busy explaining to the guy what he was doing wrong, somebody comes and posts the solution in code and gets the points for the good answer. Technically, he answered the question; educationally, not so much. And there are lot of people out there that ask the most silly of questions and only want quick cut-and-pastable answers. I pity them, but it's their job, somewhere in a remote software development sweat shop where they don't really want to work, but where the money is in their country. Luckily, for each question there are enough answers to get one thinking in the right direction, if that is what they meant to do.

The things you get afterwards become more and more subtle, yet more powerful as well. For example it is short term rewarding to give the answer to the question well and fast and first and to get the points for being best. But then you think it over and you realize that a silly question like that has probably been posted before. And I get best answer, get my five minutes of feeling smart for giving someone the code to add two values together, then the question gets marked as a duplicate. I learned that it is more satisfying and helpful to look first for the question before providing an answer. And not only it is the right thing to do, but then I get out of my head and see how other people solved the problem and I learn things. All the time.

The overall software development learning is also small, but steady. Soon enough you get to remember similar questions and just quickly google and mark new ones as duplicates. You don't get points for that, and I think that is a problem with StackOverflow: they should encourage this behavior more. Yet my point was that remembering similar questions makes you an expert on that field, however simple and narrow. If you go to work and you see the same problem there, the answer just comes off naturally, enforced by the confidence it is not only a good answer, but the answer voted best and improved upon by an army of passionate people.

Sometimes you work a lot to solve a complex problem, one that has been marked with a bounty and would give you in one shot maybe 30 times more points than getting best answer on a regular question. The situation is also more demanding, you have to not only do the work, but research novel ways of doing it, see how others have done it, explaining why you do things all the way. And yet, you don't get the bounty. Either it was not the best answer, or the poster doesn't even bother to assign the bounty to someone - asshole move, BTW, or maybe it is not yet a complete answer or even the poster snubs you for giving the answer to his question, but not what he was actually looking for. This is where you get your adrenaline pumping, but also the biggest reward. And I am not talking points here anymore. You actually work because you chose to, in the direction that you chose, with no restrictions on method of research or implementation and, at the end, you get to show off your work in an arena of your true peers that not only fight you, but also help you, improve on your results, point out inconsistencies or mistakes. So you don't get the points. Who cares? Doing great work is working great for me!

There is more. You can actually contribute not by answering questions, but by reviewing other people's questions, answers, comments, editing their content (then getting that edit approved by other reviewers) and so on. The quality of my understanding increases not only technically, but I also learn to communicate better. I learn to say things in a more concise way, so that people understand it quicker and better. I edit the words of people with less understanding of English and not only improve my own skills there, but help them avoid getting labelled "people in a remote software development sweat shop" just because their spelling is awful and their name sounds like John Jack or some other made up name that tries to hide their true origins. Yes, there is a lot of racism to go around and you learn to detect it, too.

I've found some interesting things while doing reviews, mostly that when I can't give the best edit, I usually prefer to leave the content as is, then before I know the content is subpar I can't really say it's OK or not OK, so I skip a lot of things. I just hope that people more courageous than me are not messing things up more than I would have. I understood how important it is for many people to do incremental improvements on something in order for it to better reach a larger audience, how important is that biases of language, race, sex, education, religion or psychology be eroded to nothing in order for a question to get the deserved answer.

What else? You realize that being "top 0.58% this week" or "top 0.0008% of all time" doesn't mean a lot when most of the people on StackOverflow are questioners only, but you feel a little better. Funny thing, I've never asked a question there yet. Does it mean that I never did anything cutting edge or that given the choice between asking and working on it myself I always chose the latter?

Most importantly, I think, I've learned a few things about myself. I know myself pretty well (I mean, I've lived with the guy for 39 years!) but sometimes I need to find out how I react in certain situations. For example I am pretty sure that given the text of a question with a large bounty, I gave the most efficient, most to the point, most usable answer. I didn't get the points, instead they went to a guy that gave a one liner answer that only worked in a subset of the context of the original question, which happened to be the one the poster was looking for. I fumed, I roared, I raged against the dying of the light, but in the end I held on to the joy of having found the answer, the pleasure of learning a new way of solving the same situation and the rightness of working for a few hours in the company of like-minded people on an interesting and challenging question. I've learned that I hate when people downvote me with no explanation even more than downvoting me with a good reason, that even if I am not always paying attention to detail, I do care a lot when people point out I missed something. And I also learned that given the choice between working on writing a book and doing what I already do best, I prefer doing the comfortable thing. Yeah, I suck!

It all started with a Tweet that claimed the best method of learning anything is to help people on StackOverflow who ask questions in the field. So far I've stayed in my comfort zone: C#, ASP.NET, WPF, Javascript, some CSS, but maybe later on I will get into some stuff that I've always planned on trying or even go all in. Why learn something when you can learn everything?!

My blog is hosted by Blogger, a Google site, and usually they are quite good, however this month they announced a change that, frankly, I think will hurt them in the short run because it was so sudden and leaves not only blog owners, but Blogger themselves unprepared. The news is about forcefully enabling Secure Hyper Text Transfer Protocol support for all free Blogspot sites. BTW, the link above that explains why Blogger forces HTTPS... doesn't work on HTTPS, which shows me a nice red error while editing this post.

The underlying idea is good: move everything to HTTPS, no matter how relevant it is for people to be safe and anonymous while reading my blog :). In theory, everything should be working the same as with HTTP, with some small issues that are easily fixed. In practice, we are talking about templates that people have installed without modifying or scripts that one can only find on HTTP sites or images and other resources that can only be found on unsecured web sites. For example, Google's default blog bar itself is causing an error in the console because it is trying to search the blog with an HTTP URL, even if the bar frame is loaded from an HTTPS location.

I had several problems:
  • The PGN Viewer that I use for chess games is only found on an HTTP site, therefore Google Chrome blocks loading those scripts when in HTTPS. I had to copy stuff in Google Drive and change the PGN Viewer scripts to use alternate URLs when under HTTPS and host files from Google Drive. I hope it will not reach some hosting limit and randomly fail.
  • Many thumbnails loaded for the related posts list and the blog main page are also loaded via HTTP, causing mostly annoying errors in the console. I tried to fix it programatically, but it relies on knowing which sites support HTTPS and which don't.
  • Videos, pictures and resources inside the blog posts themselves! I can't possibly change all the posts on my blog. There are over 1300 separate posts. While I don't have any posts that load remote scripts through HTTPS, it is still damn scary because I can't manually check everything. It would take me forever!
  • Caching. It is a myth that HTTPS requests cannot be cached, but it does depend on the server headers. If the HTTPS servers that I am blindly connecting to are misconfigured, people are going to perceive it as slowing down. Also, there is an interesting post that explains why loading scripts from third parties is breaking HTTPS security.

With this in mind, please help me test the blog with HTTPS and let me know if you find any issues with it. I've done what I could, but I am a developer, not a tester, so let me know, OK? Thanks!

While it is simple for blog owners to use a small Javascript in order to force users to go to the HTTP URL, not allowing this from the get go is a pretty ballsy, but asshole move. Will it make the internet safer? We'll just have to see.

I've noticed an explosion of web sites that try to put all of their stuff on a single page, accessible through nothing else than scrolling. Parallax effects, dynamic URL changes as you scroll down, self arranging content based on how much you have scrolled, videos that start and stop based on where they are placed in the viewbox, etc. They're all the rage now, like web versions of pop-up books. And, as anything that pops up at you, they are annoying! I know creativity in the design world means copying the hell out of whoever is more fashionable, but I really really really would want people to stop copying this particular Facebook++ type, all slimy fingers on touchscreens abomination.

Take a look at inc.com, for example. Reading about brain hacking and scrolling down I get right into Momofuku, whatever that is, and self playing videos. It's spam, that's what it is. I am perfectly capable of finding links and clicking (or tapping, whatever the modern equivalent of pressing Enter after a few Tab keys is now) to follow the content I am interested in. What I do NOT want is for crappy design asswipes to shove their idea of interesting content down my throat, eyes, ears or any other body organs. Just quit it!

If you are not convinced, read this article that explains how parallax scrolling web sites have become mainstream and gives two different links that list tens of "best web sites" using this design method. They are all obnoxious, slow to load, eye tiring pieces of crap. Oh look, different parts of the same page move at different speeds! How cool, now I have to scroll up and down just in order to be able to pay attention to them all, even if they are at the same bloody place!

Am I the only one who feels that way? Am I too old to understand what the cool kids like nowadays or is this exactly what I think it is: another graphical gimmick that values form over substance?

and has 0 comments
I will be reviewing all three books in The Magicians trilogy, by Lev Grossman, as they are one complete story with a beginning and an end, as well as an overarching moral. My review of the first book only, from the perspective of someone who enjoys the (very different!!) TV show, stands.

To understand The Magicians you need to understand who Lev Grossman is: a book critic for Time magazine. As such, he must have had a very strange experience trying to write after probably demolishing a lot of other writers for their lack of skill or overuse of tropes. Therefore some sort of alarm bells must sound when he undertakes to writing a "trilogy of fantasy books", a concept that is a meta-trope in itself. I believe he attempted to break the mould of the genre by using flawed every day characters on a journey that is less heroic as closer to real life: random things happening to you, bad things which you can't avoid, defeat or change, even if you try, which sometimes you don't, because you are scared or bored or selfish. At the end of said journey you are altered, but is it a better you, or just an old damaged version of the dreamer kid you started out as?

For this belief alone, I say that the books were decent because they achieved their purpose. The topics approached are more adult, the characters different from the plethora of fantasy heroes, the elements that seem to randomly appear get resolved somewhere in the far future rather than in the confined timeframe of an "episode". I loved the concept and therefore I liked the books.

However, that doesn't mean everything is rosy in Fillory. The characters are barely built up, the reader starves for some understanding of why people do the things they do or even think or feel in a certain way. Important influences such as home, childhood, parents, siblings, good friends are being ignored and abandoned, while the action of the people in the books are more often described than explained. Satirical references to well known works in the fantasy and science fiction genres pepper the books, but those stories at least attempted some consistency, while The Magicians, especially the Fillory part, feels like an LSD trip of an autistic dork.

The worst sin the books commit, and that is in direct conflict with what I think their goal was, is to make the characters almost impossible to empathize with. All of them move through the story like pieces on a board, almost indifferent to their surroundings and the people that accompany them and mostly annoyed. Whatever deep feelings they do have come out as quirky and obsessive, rather than real. It was with great dissatisfaction that I realized that the character I most identified with and believed real was The Beast, which is a terrible villain for most of the first half of the story. People died, were hurt, tortured and violated, resurrected and I couldn't care less. Mythological monsters and weird random creations were epically battling at the end of the world, and I was just bored, waiting for something interesting to happen.

Bottom line: good idea, bad implementation. Interesting to read, but hardly something that I would recommend as good writing.

Update 29 August 2017 - Version 3.0.4: The extension has been rewritten in EcmaScript6 and tested on Chrome, Firefox and Opera.

Update 03 March 2017 - Version 2.9.3: added a function to remove marketing URLs from all created bookmarks. Enable it in the Advanced settings section. Please let me know of any particular parameters you need purged. So far it removes utm_*, wkey, wemail, _hsenc, _hsmi and hsCtaTracking.

Update 26 February 2017: Version (2.9.1): added customizing the URL comparison function. People can choose what makes pages different in general or for specific URL patterns
Update 13 June 2016: Stable version (2.5.0): added Settings page, Read Later functionality, undelete bookmarks page and much more.
Update 8 May 2016: Rewritten the extension from scratch, with unit testing.
Update 28 March 2016: The entire source code of the extension is now open sourced at GitHub.

Whenever I read my news, I open a bookmark folder containing my favorite news sites, Twitter, Facebook, etc. I then proceed to open new tabs for each link I find interesting, closing the originating links when I am done. Usually I get a number of 30-60 open tabs. This wreaks havoc on my memory and computer responsiveness. And it's really stupid, because I only need to read them one by one. In the end I've decided to fight my laziness and create my first browser extension to help me out.

The extension is published here: Siderite's Bookmark Explorer and what it does is check if the current page is found in any bookmark folder, then allow you to go forward or backwards inside that folder.

So this is my scenario on using it:
  1. Open the sites that you want to get the links from.
  2. Open new tabs for the articles you want to read or YouTube videos you want to watch,etc.
  3. Bookmark all tabs into a folder.
  4. Close all the tabs.
  5. Navigate to the bookmark folder and open the first link.
  6. Read the link, then press the Bookmark Navigator button and then the right arrow. (now added support for context menu and keyboard shortcuts)
  7. If you went too far by mistake, press the left arrow to go back.

OK, let's talk about how I did it. In order to create your own Chrome browser extension you need to follow these steps:

1. Create the folder


Create a folder and put inside a file called manifest.json. It's possible structure is pretty complex, but let's start with what I used:
{
"manifest_version" : 2,

"name" : "Siderite's Bookmark Explorer",
"description" : "Gives you a nice Next button to go to the next bookmark in the folder",
"version" : "1.0.2",

"permissions" : [
"tabs",
"activeTab",
"bookmarks",
"contextMenus"
],
"browser_action" : {
"default_icon" : "icon.png",
"default_popup" : "popup.html"
},
"background" : {
"scripts" : ["background.js"],
"persistent" : false
},
"commands" : {
"prevBookmark" : {
"suggested_key" : {
"default" : "Ctrl+Shift+K"
},
"description" : "Navigate to previous bookmark in the folder"
},
"nextBookmark" : {
"suggested_key" : {
"default" : "Ctrl+Shift+L"
},
"description" : "Navigate to next bookmark in the folder"
}
}
}

The manifest version must be 2. You need a name, a description and a version number. Start with something small, like 0.0.1, as you will want to increase the value as you make changes. The other thing is that mandatory is the permissions object, which tells the browser what Chrome APIs you intend to use. I've set there activeTab, because I want to know what the active tab is and what is its URL, tabs, because I might want to get the tab by id and then I don't get info like URL if I didn't specify this permission, bookmarks, because I want to access the bookmarks, and contextMenus, because I want to add items in the page context menu. More on permissions here.

Now, we need to know what the extension should behave like.

If you want to click on it and get a popup that does stuff, you need to specify the browser_action object, where you specify the icon that you want to have in the Chrome extensions bar and/or the popup page that you want to open. If you don't specify this, you get a default button that does nothing on click and presents the standard context menu on right click. You may only specify the icon, though. More on browserAction here.

If you want to have an extension that reacts to background events, monitors URL changes on the current page, responds to commands, then you need a background page. Here I specify that the page is a javascript, but you can add HTML and CSS and other stuff as well. More on background here.

Obviously, the files mentioned in the manifest must be created in the same folder.

The last item in the manifest is the commands object. For each command you need to define the id, the keyboard shortcut (only the 0..9 and A..Z are usable unfortunately) and a description. In order to respond to commands you need a background page as shown above.

2. Test the extension


Next you open a Chrome tab and go to chrome://extensions, click on the 'Developer mode' checkbox if it is not checked already and you get a Load unpacked extension button. Click it and point the following dialog to your folder and test that everything works OK.

3. Publish your extension


In order to publish your extension you need to have a Chrome Web Store account. Go to Chrome Web Store Developer Dashboard and create one. You will need to pay a one time 5$ fee to open it. I know, it kind of sucks, but I paid it and was done with it.

Next, you need to Add New Item, where you will be asked for a packed extension, which is nothing but the ZIP archive of all the files in your folder.

That's it.

Let's now discuss actual implementation details.

Adding functionality to popup elements


Getting the popup page elements is easy with vanilla Javascript, because we know we are building for only one browser: Chrome! So getting elements is done via document.getElementById(id), for example, and adding functionality is done via elem.addEventListener(event,handler,false);

One can use the elements as objects directly to set values that are related to those elements. For example my prev/next button functionality takes the URL from the button itself and changes the location of the current tab to that value. Code executed when the popup opens sets the 'url' property on the button object.

Just remember to do it when the popup has finished loading (with document.addEventListener('DOMContentLoaded', function () { /*here*/ }); )

Getting the currently active tab


All the Chrome APIs are asynchronous, so the code is:
chrome.tabs.query({
'active' : true,
'lastFocusedWindow' : true
}, function (tabs) {
var tab = tabs[0];
if (!tab) return;
// do something with tab
});

More on chrome.tabs here.

Changing the URL of a tab


chrome.tabs.update(tab.id, {
url : url
});

Changing the icon in the Chrome extensions bar


if (chrome.browserAction) chrome.browserAction.setIcon({
path : {
'19' : 'anotherIcon.png'
},
tabId : tab.id
});

The icons are 19x19 PNG files. browserAction may not be available, if not declared in the manifest.

Get bookmarks


Remember you need the bookmarks permission in order for this to work.
chrome.bookmarks.getTree(function (tree) {
//do something with bookmarks
});

The tree is an array of items that have title and url or children. The first tree array item is the Bookmarks Bar, for example. More about bookmarks here.

Hooking to Chrome events


chrome.tabs.onUpdated.addListener(refresh);
chrome.tabs.onCreated.addListener(refresh);
chrome.tabs.onActivated.addListener(refresh);
chrome.tabs.onActiveChanged.addListener(refresh);
chrome.contextMenus.onClicked.addListener(function (info, tab) {
navigate(info.menuItemId, tab);
});
chrome.commands.onCommand.addListener(function (command) {
navigate(command, null);
});

In order to get extended info on the tab object received by tabs events, you need the tabs permission. For access to the contextMenus object you need the contextMenus permission.

Warning: if you install your extension from the store and you disable it so you can test your unpacked extension, you will notice that keyboard commands do not work. Seems to be a bug in Chrome. The solution is to remove your extension completely so that the other version can hook into the keyboard shortcuts.

Creating, detecting and removing menu items


To create a menu item is very simple:
chrome.contextMenus.create({
"id" : "menuItemId",
"title" : "Menu item description",
"contexts" : ["page"] //where the menuItem will be available
});
However, there is no way to 'get' a menu item and if you try to blindly remove a menu item with .remove(id) it will throw an exception. My solution was to use an object to store when I created and when I destroyed the menu items so I can safely call .remove().

To hook to the context menu events, use chrome.contextMenus.onClicked.addListener(function (info, tab) { }); where info contains the menuItemId property that is the same as the id used when creating the item.

Again, to access the context menu API, you need the contextMenus permission. More about context menus here.

Commands


You use commands basically to define keyboard shortcuts. You define them in your manifest and then you hook to the event with chrome.commands.onCommand.addListener(function (command) { });, where command is a string containing the key of the command.

Only modifiers, letters and digits can be used. Amazingly, you don't need permissions for using this API, but since commands are defined in the manifest, it would be superfluous, I guess.

That's it for what I wanted to discuss here. Any questions, bug reports, feature requests... use the comments in the post.

Here is a very informative presentation about the internals of await/async, which makes things a lot clearer when you are trying to understand what the hell is going on there:

and has 0 comments
I'm seeing a pattern here already. After The Expanse, which surprised me with how good the TV show was compared to the books, now The Magicians does the same. There is something to be said about hindsight and when you are adapting a series of books for the small screen you get a lot of resources that the writer himself did not have when he began. I have a feeling that many things that happened in the first season of the TV series will not even happen in the second book. The plot has been changed as well, quite a lot, to the point that now I will be reviewing a book that has at most half of it to do with what you might have seen on TV and another half that you probably won't see even in the future.

In The Magicians, the first book in the series with the same name, Lev Grossman describes a pretty dorky character suddenly finding that magic is real and he is a magician. But while it starts like the typical fantasy story, it continues quite differently, with a school of magic that doesn't seem to care about its students much, a way of learning and doing magic that is never quite explained, but described as tedious and difficult, and an overall depressing view on the world. The main character isn't even very heroic, quite the opposite, he really does think and feel like a 'dork'. If anything, he is a coward and a person who's few feelings are confused and pretty much self involved. His friends are none the better and the entire thing soon started to take a toll on me, who failed to empathize with anything and anybody.

Another issue with the book is that it is rarely consistent. Things happen without much explanation and then they turn into others. Modern culture references mix with awe of magic and then seriously fucked up shit, only to slip into irony or even slapstick comedy. It gets the reader curious about what is going to happen next, but always on the brink of "why am I reading this?". Myself I am sometimes completely engrossed in a bit of the story only to see it end abruptly and leading to nowhere. Doors to other realms are opened and nobody really cares for it for any reason other than to become kings and party all the time. People die or characters do some really shitty things, but the others are all calm and going on with their lives.

So yeah, I don't know if I should recommend the books yet. The show is levels of magnitude better so far, in story, consistency and character development. Even if I could buy into the whole borderline autistic asshole of a main character, which I was ready to, the sudden and often context switch made me really difficult for me to enjoy the series so far. However it is original and I have not read a book that sees the world quite in the same way. If you are tired of the same old fantasy stuff, The Magicians is a bit more adult and hard to put in a clear box, touching real young people topics, like sexuality, alcohol, drugs, depression, uncertainty, the search for happiness.

Inspired by my own post about simulating F# active patterns in C# and remembering an old crazy post about using try/catch to emulate a switch on types, I came up with this utility class that acts and looks like a switch statement, but can do a lot more. The basic idea was to use a fluent interface to get the same functionality of switch, but also add the possibility of using complex objects as case values or even code conditions.


First, here is the source code:
namespace Constructs
{
public static class Do
{
public static Switch<T> Switch<T>(T value)
{
return Constructs.Switch<T>.From(value);
}
}

public class Switch<T>
{
private bool _isDone;
private T _value;
private Type _valueType;

private Switch(T value)
{
this._value = value;
}

public static Switch<T> From(T value)
{
return new Switch<T>(value);
}

public Switch<T> Case(Func<T> valueFunc, Action<T> action, bool fallThrough = false)
{
if (_isDone) return this;
return Case(valueFunc(), action, fallThrough);
}

public Switch<T> Case(T value, Action<T> action, bool fallThrough = false)
{
if (_isDone) return this;
return If(v => object.Equals(value, v), action, fallThrough);
}

public void Default(Action<T> action)
{
if (_isDone) return;
action(_value);
}

public Switch<T> If(Func<T, bool> boolFunc, Action<T> action, bool fallThrough = false)
{
if (_isDone) return this;

if (boolFunc(_value))
{
action(_value);
_isDone = !fallThrough;
}

return this;
}

private Type getValueType()
{
if (_valueType != null) return _valueType;
if (object.Equals(_value, null)) return null;
_valueType = _value.GetType();
return _valueType;
}

public Switch<T> OfStrictType<TType>(Action<T> action, bool fallThrough = false)
{
if (_isDone) return this;
if (getValueType() == typeof(TType))
{
action(_value);
_isDone = !fallThrough;
}
return this;
}

public Switch<T> OfType<TType>(Action<T> action, bool fallThrough = false)
{
if (_isDone) return this;
if (getValueType() == null) return this;
if (typeof(TType).IsAssignableFrom(getValueType()))
{
action(_value);
_isDone = !fallThrough;
}
return this;
}
}
}
I use the static class Do to very easily get a Switch<T> object based on a value, then run actions on that value. The Switch class has a _value field and an _isDone field. When _isDone is set to true, no action is further executed (like breaking from a switch block). The class has the methods Case, and If, as well as OfType and OfStrictType, all of which execute an action if either the value, the function, the condition or the type provided match the initial value. Default is always last, executing an action and setting _isDone to true;

Here is an example of use:
for (var i = 0; i < 25; i++)
{
Do.Switch(i)
.Case(10, v => Console.WriteLine("i is ten"), true)
.Case(() => DateTime.Now.Minute / 2, v =>
Console.WriteLine($"i is the same with half of the minute of the time ({v})"), true)
.If(v => v % 7 == 0, v => Console.WriteLine($"{v} divisible by 7"))
.Default(v => Console.WriteLine($"{v}"));
}
where the numbers from 0 to 25 are compared with 10, the half of the minutes value of the current time and checked if they are divisible by 7, else they are simply displayed. Note that the first two Case methods receive an optional bool parameter that allows the check to fall through, so that the value is checked if it is equal to 10, but also if it is twice the minute value or divisible by 7. On the other hand, if the value is divisible by 7 it will not display the value in the Default method.

Here is an example that solves the type check with the same construct:
var f = new Action<object>(x =>
Do.Switch(x)
.OfType<string>(v => Console.WriteLine($"{v} is a string"))
.OfType<DateTime>(v => Console.WriteLine($"{v} is a DateTime"))
.OfType<int>(v => Console.WriteLine($"{v} is an integer"))
.OfType<object>(v => Console.WriteLine($"{v} is an object"))
);
f(DateTime.Now);
f("Hello, world!");
f(13);
f(0.45);

And finally, here is the solution to the famous FizzBuzz test, using this construct:
for (var i = 0; i < 100; i++)
{
Do.Switch(i)
.If(v => v % 15 == 0, v => Console.WriteLine($"FizzBuzz"))
.If(v => v % 3 == 0, v => Console.WriteLine($"Fizz"))
.If(v => v % 5 == 0, v => Console.WriteLine($"Buzz"))
.Default(v => Console.WriteLine($"{v}"));
}

Now, the question is how does this fare against the traditional switch? How much overhead does it add if we would, let's say, take all switch/case blocks and replace them with this construct? This brings me to the idea of using AOP to check if the construct is of a certain shape and then replace it with the most efficient implementation of it. With the new Roslyn compiler I think it is doable, but beyond the scope of this post.

I have tried, in the few minutes that it took to write the classes, to think of performance. That is why I cache the value type, although I don't think it really matters that much. Also note there is a difference between Case(v=>SomeMethodThatReturnsAValue(),DoSomething()) and Case(SomeMethodThatReturnsAValue(),DoSomething()); In the first case, SomeMethodThatReturnsAValue will only be executed if the switch has not matched something previously, while in the second, the method will be executed to get a value and then, when the time comes, the switch will compare it with the initial value. The first method is better, with only 4 extra characters.

Hope it helps someone.

and has 0 comments
Nemesis Games felt like a fixer-upper. The authors had already established a pattern in the books from The Expanse, mainly a psychopathic villain and the motley crew of the Rocinante saving the world through bouts of coincidence and luck that are impossible to believe, and so seeing the exact same formula used again in the fifth book was a disappointment. However, they had another issue: the characters of the story were not very clearly defined. Having hinted since forever that each of the people on the ship had a heavy past, James S.A. Corey decided to explain almost all of those pasts in this book. The fact that the disaster was epic made the book easy to read through, in that "what happens next" trance, but it felt the book version of an elevator show. It even ended badly, with conflicts unresolved and a cliffhanger "to be continued" scene at the end. The sixth book of the series, Babylon's Ashes, is supposed to be published in April this year and seriously I am asking myself if I want to continue reading it.

To be honest, the book was not bad. It was just so recklessly slapped together using book writing rules that it felt like a commercial TV show. And I don't mean one of the good ones like, ironically, the first season of The Expanse, I mean those long winded cop shows that lead to nothing. I wasn't the only one to notice that the characters in the series have not really evolved one bit since they were introduced, despite having passed through five separate world saving scenarios. Taking a page from their mentor, George R.R. Martin, the authors just let the alien presence linger in the shadows, having no role whatsoever besides the one of stage prop. Meanwhile, all the conflict, all the struggle is between ordinary humans. This appeals, but then it bores. And yes, I have to admit to myself, the feeling I am left with after reading Nemesis Games is boredom.

Perhaps if at least one of the books would have explained the actions and motivations and background of the villains, other than being sick in the head, I would have liked the series more. I know that there are short novellas that try to do that and I did try to read some, but after a few tens of pages I gave up. If the books feel like an endlessly rehashed formula, the novellas feel like those quotes from fictional people and books that some sci-fi writers adorn their chapters with. If I make efforts to feel anything for the people in the books, I feel absolutely nothing for the sketched out secondary characters in the novellas.

So there, after reading the five books one after the other like there was no tomorrow, my final verdict is 'meh'. Perhaps they should have hired Brandon Sanderson to finish up the series. That guy is good at that. Hey, Brandon, can you write three books in The Expanse, starting from the second book, Caliban's War, and ignoring the rest?

F# has an interesting feature called Active Patterns. I liked the idea and started thinking how I would implement this in C#. It all started from this StackOverflow question to which only Scala answers were given at the time.

Yeah, if you read the Microsoft definition you can almost see the egghead that wrote that so that you can't understand anything. Let's start with a simple example that I have shamelessly stolen from here.
// create an active pattern

let (|Int|_|) str =
match System.Int32.TryParse(str) with
| (true, int) -> Some(int)
| _ -> None

// create an active pattern

let (|Bool|_|) str =
match System.Boolean.TryParse(str) with
| (true, bool) -> Some(bool)
| _ -> None

// create a function to call the patterns

let testParse str =
match str with
| Int i -> printfn "The value is an int '%i'" i
| Bool b -> printfn "The value is a bool '%b'" b
| _ -> printfn "The value '%s' is something else" str

// test

testParse "12"
testParse "true"
testParse "abc"

The point here is that you have two functions that return a parsed value, either int or bool, and also a matching success thing. That's a problem in C#, because it is strongly typed and if you want to use anything than boxed values in objects, you need to define some sort of class that holds two values. I've done that with a class I called Option<T>. You might want to see the code, but it is basically a kind of Nullable class that accepts any type, not just value types.
Click to expand

Then I wrote code that did what the original code did and it looks like this:
var apInt = new Func<string, Option<int>>(s =>
{
int i;
if (System.Int32.TryParse(s, out i)) return new Option<int>(i);
return Option<int>.Empty;
});
var apBool = new Func<string, Option<bool>>(s =>
{
bool b;
if (System.Boolean.TryParse(s, out b)) return new Option<bool>(b);
return Option<bool>.Empty;
});

var testParse = new Action<string>(s =>
{
var oi = apInt(s);
if (oi.HoldsValue)
{
Console.WriteLine($"The value is an int '{oi.Value}'");
return;
}
var ob = apBool(s);
if (ob.HoldsValue)
{
Console.WriteLine($"The value is an bool '{ob.Value}'");
return;
}
Console.WriteLine($"The value '{s}' is something else");
});

testParse("12");
testParse("true");
testParse("abc");

It's pretty straighforward, but I didn't like the verbosity, so I decided to write it in a fluent way. Using another class called FluidFunc that I created for this purpose, the code now looks like this:
var apInt = Option<int>.From<string>(s =>
{
int i;
return System.Int32.TryParse(s, out i)
? new Option<int>(i)
: Option<int>.Empty;
});

var apBool = Option<bool>.From<string>(s =>
{
bool b;
return System.Boolean.TryParse(s, out b)
? new Option<bool>(b)
: Option<bool>.Empty;
});

var testParse = new Action<string>(s =>
{
FluidFunc
.Match(s)
.With(apInt, r => Console.WriteLine($"The value is an int '{r}'"))
.With(apBool, r => Console.WriteLine($"The value is an bool '{r}'"))
.Else(v => Console.WriteLine($"The value '{v}' is something else"));
});

testParse("12");
testParse("true");
testParse("abc");

Alternately, one might use a Tuple<bool,T> to avoid using the Option class, and the code might look like this:
var apInt = FluidFunc.From<string,int>(s =>
{
int i;
return System.Int32.TryParse(s, out i)
? new Tuple<bool, int>(true, i)
: new Tuple<bool, int>(false, 0);
});

var apBool = FluidFunc.From<string,bool>(s =>
{
bool b;
return System.Boolean.TryParse(s, out b)
? new Tuple<bool, bool>(true, b)
: new Tuple<bool, bool>(false, false);
});

var testParse = new Action<string>(s =>
{
FluidFunc
.Match(s)
.With(apInt, r => Console.WriteLine($"The value is an int '{r}'"))
.With(apBool, r => Console.WriteLine($"The value is an bool '{r}'"))
.Else(v => Console.WriteLine($"The value '{v}' is something else"));
});

testParse("12");
testParse("true");
testParse("abc");

As you can see, the code now looks almost as verbose as the original F# code. I do not pretend that this is the best way of doing it, but this is what I would do. It also kind of reminds me of the classical situation when you want to do a switch, but with dynamic calculated values or with complex object values, like doing something based on the type of a parameter, or on the result of a more complicated condition. I find this fluent format to be quite useful.

One crazy cool idea is to create a sort of Linq provider for regular expressions, creating the same type of fluidity in generating regular expressions, but in the end getting a ... err... regular compiled regular expression. But that is for other, more epic posts.

The demo solution for this is now hosted on Github.

Here is the code of the FluidFunc class, in case you were wondering:
public static class FluidFunc
{
public static FluidFunc<TInput> Match<TInput>(TInput value)
{
return FluidFunc<TInput>.With(value);
}

public static Func<TInput, Tuple<bool, TResult>> From<TInput, TResult>(Func<TInput, Tuple<bool, TResult>> func)
{
return func;
}
}

public class FluidFunc<TInput>
{
private TInput _value;
private static FluidFunc<TInput> _noOp;
private bool _isNoop;

public static FluidFunc<TInput> NoOp
{
get
{
if (_noOp == null) _noOp = new FluidFunc<TInput>();
return _noOp;
}
}

private FluidFunc()
{
this._isNoop = true;
}

private FluidFunc(TInput value)
{
this._value = value;
}

public static FluidFunc<TInput> With(TInput value)
{
return new FluidFunc<TInput>(value);
}

public FluidFunc<TInput> With<TNew>(Func<TInput, Option<TNew>> func, Action<TNew> action)
{
if (this._isNoop)
{
return this;
}
var result = func(_value);
if (result.HoldsValue)
{
action(result.Value);
return FluidFunc<TInput>.NoOp;
}
return new FluidFunc<TInput>(_value);
}

public FluidFunc<TInput> With<TNew>(Func<TInput, Tuple<bool,TNew>> func, Action<TNew> action)
{
if (this._isNoop)
{
return this;
}
var result = func(_value);
if (result.Item1)
{
action(result.Item2);
return FluidFunc<TInput>.NoOp;
}
return new FluidFunc<TInput>(_value);
}

public void Else(Action<TInput> action)
{
if (this._isNoop) return;

action(_value);
}

}