Thursday 29 January 2015

Monday 26 January 2015

Run Chrome with file access AND in a separate instance

Sometimes you want to run your browser without some protections that are enabled by default in it. One of these is the cross-origins protection when running a local filesystem script. For Chrome, the solution is to run the browser with the command line switch --allow-file-access-from-files. Seems straight forward enough, but if your browser is already open (usually I have at least 10 active tabs, ranging from documentation pages, email to the music I listen to), the command line switches will be ignored and your script will be run as just another window in the same instance of Chrome. In order to fix this, you need to use another switch called --user-data-dir. Just make sure this folder exists and it can be deleted (because it will be filled with a zillion useless files).

So, how do I run a test.html file that can access files and is located in C:\SomePath ? Like this:
start "Chrome with access to files" chrome --allow-file-access-from-files "file:///C:\SomePath\test.html" --user-data-dir="C:\SomePath\UserDir"


In your path a UserDir folder will be created which you can delete after you finish your work.

Of course, this issue applies to any other flags that you want to use ad-hoc while Chrome is already open.

Wednesday 21 January 2015

Inserting or updating in MySQL without a primary key or unique index OR how to use EXISTS in MySQL

I was trying to write a simple query in MySQL that only inserted a row if there wasn't one already there, else it would update the existing one. MySQL has a system to take care of that for you if you have a primary key or a unique index on the table you want to insert or update. You can choose between INSERT ... ON DUPLICATE KEY or REPLACE. However, what if you don't want to add an index on your table just for that?

T-SQL (Microsoft SQL Server) has a syntax that works like this:
IF EXISTS(SELECT * FROM MyTable WHERE y=2)
UPDATE MyTable SET x=x+1 WHERE y=2;
ELSE
INSERT INTO MyTable (x,y) VALUES(1,2);
END

MySQL also has an IF...THEN syntax as well as an EXISTS statement. The problem is that they work in a completely different way. IF has an extra THEN keyword, uses ELSEIF instead of ELSE and needs to end with an END IF. EXISTS works only in WHERE clauses. So, let's translate the query above in MySQL and hope for the best:
INSERT INTO MyTable (x,y) 
SELECT 0,2 FROM DUAL
WHERE NOT EXISTS(SELECT * FROM MyTable WHERE y=2);
UPDATE MyTable SET x=x+1 WHERE y=2;

Notice several things: I am not using any IF and I am updating rows all the time after the conditional insert. I am selecting values from DUAL because any select with a where clause needs a table in MySQL and DUAL is a dummy one built into the engine. (SELECT 1 WHERE 2=2; is not valid in MySQL). Also, I am inserting a value, then updating it, which is not the most efficient.

There is another way, closer to the original T-SQL query, but it doesn't use EXISTS. It looks like this:
IF (SELECT 1=1 FROM MyTable WHERE y=2) THEN
UPDATE MyTable SET x=x+1 WHERE y=2;
ELSE
INSERT INTO MyTable (x,y) VALUES(1,2);
END IF;

Thing to notice here: I am using 1=1 to return a TRUE value that will make the IF work. Also, PAY ATTENTION!, this doesn't work as a simple query. I spent the better half of an hour trying to understand where the syntax error was while trying to execute this directly. Any flow operations like IF or WHILE, etc, are only valid in "programs", the MySQL term for stored procedures and functions.

I hope I clarified things for you on this.

Sunday 11 January 2015

TV Series I've Been Watching - Part 21 (and last in this format)

As you know, I have been watching a lot of TV series, some of them good, some of them bad, most of them complete waste of time. As a New Year resolution (yeah, I know, lame) I have decided to create a slot system for TV series. Thus, from now on soon I will switch to a 7/3 method, meaning that I will watch only seven TV shows regularly and reserve three slots for new series, just in order to determine if they are more worth watching than the current ones. If I find a series that needs to go into the magical seven, I have to bump out another. Thus, this is the last post about TV series in this format.



So here is what I have been watching lately:
  • The Legend of Korra - The fourth and final season ended recently. It was a nice ending of an otherwise boring or annoying series. I maintain my opinion that The Last Airbender series was levels of magnitude better.
  • The Good Wife - The story of the legal troubles of Cary Agos is in the foreground, while Alicia's juggling of family, politics and job reaches ridiculous levels. Some interesting moral conundrums are created, but for me this season is kind of unfulfilling.
  • Homeland - The fourth season is focusing on an Afghani terrorist who, with the help of Pakistani intelligence, is wreaking havoc for the Americans. Some interesting dynamics, but far away from the edge of the seat feeling you got from sergeant Brody's story arch.
  • Gotham - I really expected this show to suck. Instead we get solid performances and more or less believable plots. It is acceptably dark for events happening in Gotham, as well. The girlfriend part is really annoying me, but the rest is good.
  • The Honourable Woman - The show is really dark and depressing. So much, in fact, that I couldn't watch it as much as I probably should. I always have issues with stories that show indomitable and incorruptible heroes, but the alternative extreme, where everything is gloomy and hopeless, is not much better. Just as too much fantasy, if you can't affect reality, then it is just as unengaging.
  • The Witches of East End - The series was cancelled before a third season, leaving everything in limbo, with no closure. I think this kind of behavior should be made illegal. No matter how small, the investment of the viewer in a story needs to be repaid. What would you do if you went at the cinema, watched a movie, and it suddenly stopped before the ending, saying that the producers didn't have the money to finish it? Wouldn't you ask for your money back?
  • Tyrant - Weird story, kind of hard to swallow, but interesting in many respects. The show has been renewed for a second season.
  • Extant - The series will get a second season, but I will not watch it. The show is a clumsy cocktail of sci-fi cliches, all thrown together while expecting Halle Berry to hold them together.
  • The Bridge - The series has been cancelled after the second season, while I am still waiting to watch it. I love Diane Kruger, so I probably will watch it someday.
  • Ghost in the Shell - Arise - Solid reboot. Too bad it has only four episodes which pretty much retell the same story. Meanwhile, a GiTS movie is in the works, starring Scarlet Johansson
  • The Strain - the show is pretty good. I kind of dislike the main character, while I totally love Kevin Durand. The series has been renewed for a second season.
  • Longmire - Loved the first seasons, the last was kind of over the top and it showed. The show was cancelled.
  • The Lottery - I've decided, more or less by not feeling like watching it at any time, to stop watching it. I haven't really watched enough of it to make a rational impression, but the pilot totally threw me off. Besides, this show was also cancelled.
  • Manhattan - The show has been renewed for a second season. I have mixed feelings about it. On one hand I like the story, but at the same time I am a bit put off by the fact that is complete fabrication.
  • Legends - The show's concept is a lot cooler than it's implementation. I like Sean Bean's interpretation, but the story is very similar to a zillion cop/government agency shows. They need to focus more on his character, rather than on pointless villains. The show has been renewed for a second season.
  • Outlander - They cancelled it! Good actors, wonderful scenery, an interesting story. A great shame.
  • The Divide - I've stopped watching it after a while, but I can't tell you why, exactly. I will remove it from my watch list. It had been cancelled, anyway.
  • The Knick - Renewed for a second season, this show is great. Good acting, nice depiction of the times, unapologetic critique of pharmaceutical companies and human nature in general. I love it!
  • Doctor Who - What are you doing, Capaldi?! I think this season of Doctor Who was the most boring and pointless of them all. Even the Christmas Special was bad. Something has to be done, if it goes like this, Doctor Who will take another decadal hiatus.
  • Forever - It is difficult to reject this series outright, because I really like the actors. However the story itself is completely boring. Other than this quirk of the main character that he cannot die, the show is a standard cop thing. You know who else cannot die? Deadpool! Isn't that slightly more interesting? Also the show is likely to get cancelled.
  • Hysteria and Hand of God - I love Ron Perlman, but that doesn't mean I liked the Hand of God pilot more than the one from Hysteria. Unfortunately Hand of God will probably get picked up for a series, while Hysteria does not.
  • Haven - It becomes increasingly difficult to give up series as you watch them for more and more time. Unfortunately for Haven, which was never good to begin with, the time has come for the "mother of Audrey/Mara" to appear. When family members appear in a story, it usually means they've run out of ideas. The fifth season will get some extra episodes in order to give viewers closure, afterwards it will probably get cancelled. See? This is how you do it when you know you are cancelling a show!
  • Z Nation - This SyFy clone of The Walking Dead should have sucked ass. Instead, it is a low budget yet fun show, with a lot of tongue in cheek and also original ideas. Who would have thought SyFy could do something entertaining? If you divide entertainment value to the show budget, Z Nation clearly wins over The Walking Dead.
  • Madam Secretary - Oh, the level of obnoxious American propaganda and overall stupidity of this show is off the charts. I refuse to watch this filth. And it appears it will get renewed as well. Ugh!
  • Sleepy Hollow - The second season has just started. This show will never be good, just admit it. Its value is purely guilty pleasure.
  • The Driver - A BBC One miniseries about a cab driver recruited by the mob, starring David Morrissey and Colm Meaney. The story is not new, the acting is good, but the show... just doesn't do it for me. Sorry.
  • Arrow - Oh, Marvel is doing something interesting. Their "phase 3" operation involves spamming the big and small screens with series and films about Marvel superheroes. Now, Arrow is not a great show, and everybody knows it, however they started doing crossover episodes with another new show, The Flash, and probably some of the story ideas will be found or hinted about in the films. Already some things that happened in Captain America movies are found and expanded upon in Marvel's Agents of S.H.I.E.L.D and Marvel's Agent Carter series. Standalone, Arrow went in the "friends and family" direction, which I despise and personally think it means they lack any original ideas. I know that there are some comics that need to be taken into consideration when creating the scripts, but still.
  • South Park - South Park sputtered lately, going from meh! to really funny from episode to episode. The Fremium episode, for example, was really cool. I remain a fan.
  • Stalker - Another police procedural with a twist. I kind of like it, but I wouldn't recommend it, if you know what I mean. The show focuses on stalkers, with the small twist that the main character (and member of the task force that fights them) seems to be one himself. Too bad that they broke the tension on that one. I think I like it because of the lead actors.
  • Marvel's Agents of Shield - Yes, I know it's an acronym, but I am tired of typing S.H.I.E.L.D. all the time. The show is pretty good! It does go into the whole "dad and mom" territory, but not too much. I will continue watching it.
  • Marvel's Agent Carter - Another Marvel TV show, this time about agent Carter, the girlfriend of Captain America. Set in the 1940's, it also has to deal with the sexism of the period. Sexy actress, some interesting characters, this shows promise.
  • Our Girl - This is an interesting series, concerning a young girl that joins the British army. She has to deal with a stupid and petty but well meaning family, fighting in the Middle East and also a love triangle (what else when a woman is concerned?). No, seriously, it's better than Twilight.
  • Tim and Eric's Bedtime Stories - In an era where big budget horror TV series abound, here is this minimalist standalone episode show. And it is fucking scary! The episodes are very short and involve usually similar worlds to ours. No special effects, monsters or whatever, but the subjects are really unsettling and powerful. A must see!
  • Black Dynamite - The second season doesn't seem as funny as the first, but still a lot of fun and makes me learn many things about the American 70's
  • The 100 - I couldn't make myself watch the second season. That probably means that I feel it sucks. However I still might watch it...
  • Constantine - A series based on the Constantine comics and film. Keanu Reeves has been replaced by a skinny British wanker with illusions of grandeur. Actually, the character is a bit more layered than that, but not by much. I had high hopes for the show, but I have to admit that it is subpar and I don't like it.
  • Star Wars Rebels - At first I really hated this animated series. I thought it was too childish. Then I realized that the entire Star Wars franchise is made for little children. Really, this settles the Star Wars/Trek debate for me: the intended audience ages are slightly different, in the sense that Star Trek contains elements that have meaning for adults, as well >:-D.
  • Ripper Street - Ripper Street got cancelled, then got revived by Amazon Prime, and it is now at season 3. I have to admit that the direction of the show feels strained right now. I hope it picks up pace, because I really loved the first two seasons
  • State of Affairs - Another series that tries to be apologetical to the US foreign policy, it portrays romantic comedy star Katherine Heigl as a CIA executive, married to the son of the US president, who is a black woman, and that has dark secrets threatening to get revealed. I couldn't watch more than two episodes. It is just as surreal as her romantic films: all nice and pink, unless it's about non-Americans. They are bad!
  • The Shadow Line - Dark British police/political thriller, it is a miniseries, meaning it ends without having "seasons" and it is pretty amazing. Good acting, interesting story. It came highly recommended and it didn't disappoint.
  • Babylon - The series had an interesting pilot a while ago. I liked it, now it got picked up as a series. I want to watch it, but I haven't started yet.
  • Marco Polo - a series about the explorer Marco Polo, left by his father at the court of Kublai Khan. I like the actors and the show. The story is also interesting, showing the Mongols as more than invading horseriding barbarians, instead a nation covering half of China and with expansion intentions covering the entire known world.
  • The Newsroom - The third season was short and it was meant to give some sort of closure to the ending of the show. However is was so horribly weak, especially the last episode which was made out of fragments of the first two seasons episodes, that I ended up hating it more than I was already hating it. Good riddance!
  • The Librarians - Horrible show, trying to serialize an obscure film that wasn't that good to begin with. Don't watch it!
  • Scorpion - Leaving aside the alleged basis in reality that the show has, it is another cop show, with "geniuses" helping the FBI. Unlike Numb3rs, which had the same idea, this show is not very good at all. Characters are difficult to empathize with and the whole "normal mom helping the helpers" thing is just... offensive.
  • The Musketeers - You will close your browser window in anger for wasting you the time to read so far, but... I like this show. It is silly, has little to do with Dumas' creation, but I enjoy watching it. It probably has to do with the generously endowed beauties that seem all to like D'Artagnan
  • Elementary - I really like both Lucy Liu and Johhny Lee Miller, but this show has gone to shit. Having nothing to do with deductive skills now, it turned into yet another police procedural, with brilliant people helping the police.
  • Broadchurch - Haven't yet started watching the second season - yes! there is a second season. One that is not the Gracepoint American redo starring David Tennant. I believe Tennant has to feel a bit Doctor Whoish when he is starring in both the American remake and the second season of the original... BTW, Gracepoint got cancelled!
  • Ascension - A SyFy miniseries, in the sense that it has only three episodes per season, it involves a ship that was clandestinely sent to another solar system by Kennedy! At first I was all "what?! How can anyone even think of it?", but then the reason for it all got revealed. It also features a *really annoying* little girl that has mental superpowers and, what else?, a government conspiracy. Once you get the hang of it, it is pretty nice and the human branching from a 1950's United States is a nice twist. I am awaiting the second season. Tricia Helfer is almost as cool as in BSG
  • Banshee - The third season started and it is just as satisfying as the first two. I don't know what sort of human button this show pushes, but I love it and have absolutely no idea why.

Now all I have to do is choose 7 series out of this list and implement my resolution. This list alone contains 50 series and I haven't been including new series that I haven't started watching and shows that continue in the summer season. It will be difficult, but necessary. If we consider an average of 10 episodes per season, one hour each, that means I use up around 10 hours of my time each season per series. If I remove 40 from my list, that means a staggering 400 hours of time freed per year, more than an hour per day. Of course, I will use this time to watch movies, which don't have an upper bound :) Let's see how it goes.

Predictably Irrational, by Dan Ariely

Dan Ariely is a professor of behavioral economics, the field that is trying to analyse economics via human behavior studies. In his book, Predictable Irrational - The Hidden Forces that Shape our Decisions, he is arguing that the simple model of market forces constraining people to behave rationally to maximize gain is false, as people are not rational and will never be rational. He then goes to explain various mental fallacies that we are subject to, complete with experiments testing and proving them.

The book is rather short and easy to read, split into 15 chapters and some annexes. Here is a summary:
  • Chapter 1: The Truth About Relativity - People assess the value of something relative to something else that is known. Thus people can be "primed" by being exposed to items that are priced in a certain way, influencing the value they give to something else. Think supermarkets and the three category of items: cheap stuff, expensive stuff and one item that is insanely expensive. Relativity will make people to buy the expensive stuff.
  • Chapter 2: The Fallacy of Supply and Demand - Again, value is not really an objective thing, coming from supply and demand, but by comparing to other things. The example given is that of black pearls, at first no one would buy them, but the importer chose the most beautiful and best, created a line of insanely expensive jewels and advertised them everywhere. Soon black pearls were in demand and at a much higher price than normal pearls.
  • Chapter 3: The Cost of Zero Cost - Ariely argues that zero is a price in a category of its own. He makes an experiment where people have to choose between average and good candy and they are asked to pay 2 cents and 14 cents, respectively. People overwhelmingly choose the good candy, since the price is not that high. However, when the price of the average candy drops to nothing and that of the good candy to 12 cents (so the financial gain is the same for the same quantity) people switch sides and take the average candies.
  • Chapter 4: The Cost of Social Norms - One of the most interesting for me, this chapter discusses how people function on social norms until someone introduces the market norms (tit for tat), in which case the social norms go out the window and the situation may even become really embarrassing socially. Imagine Thanksgiving dinner at the house of mother in law, nice roasted turkey, good wine, the wife's recipe was used for the delicious desert, everybody is happy. What happens if the man thanks the hosts and attempts to give them money to cover the expense? A lot of interesting experiments expand on the concept.
  • Chapter 5: The Power of a Free Cookie - A reverse of Chapter 4, it considers what happens when you get something for free as opposed to having to pay for it. When a colleague comes to the office and brings cookies, people take one or two, taking into consideration that other people in the office need to get a cookie. However, if people are asked to pay a cent on the cookies, they usually take more, again market rules trumping social norms when money is involved.
  • Chapter 6: The Influence of Arousal - Rather funny chapter, but really interesting. It shows that people, when sexually aroused, change their behavior significantly. That is not a surprise, but that change is so large that those people themselves cannot predict what they will actually do. Consider this when you rationally "plan" on how you are going to behave when exposed to temptation or strong emotions.
  • Chapter 7: The Problem of Procrastination and Self Control - People tend to value the present much more than the future. People plan to save money or lose weight, but are deflected by present moment temptations. Can something be done about it?
  • Chapter 8: The High Price of Ownership - People tend to overvalue the things they already possess. In an experiment, Ariely proves that people would not buy the things that they are trying to sell at the price that they would themselves ask. This is used in economics when people are offered the option of "trying out" something and only when they actually "have" the item, decide if they want to give it back.
  • Chapter 9: Keeping Doors Open - One AI researcher came with the idea that intelligent behavior arises spontaneously when trying to maximize the available options. Ariely argues that this kind of behavior is not intelligent at all. He does clever experiments with doors that disappear if not opened in an interval of time and observes people periodically open them just in order to keep them there, even if they gain less by not visiting more lucrative rooms.
  • Chapter 10: The Effect of Expectations - This chapter seems to be incomplete. It is argued that if expecting to enjoy or not enjoy something, the enjoyment will be proportional to the expectations. Personally I feel that this only happens in cases where people can't really tell the difference between good and bad. I often face the opposite effect when watching a movie that I expect to be good and hate it when it is merely average.
  • Chapter 11: The Power of Price - Similar to Chapter 10, this shows how we feel we get more from something that is priced higher. The placebo effect is also discussed here. Interesting, indeed.
  • Chapter 12: The Cycle of Distrust - Economics says that there can be no hundred dollar bills on the ground because someone would have picked them up already. Making fun of this view on things, Ariely discusses dishonest offers that look like great deals, but instead are taking advantage of your gullibility. He argues that originally trustful people quickly lose that trust when cheated and it is hard to get it back. He gives an interesting example where they installed a stall offering free money. Only about one in five people even approached it.
  • Chapter 13: The Context of Our Character part 1 - Both chapters discuss the level of human dishonesty, but show that circumstances change the amount considerably. In an experiment he gives people the chance to cheat after doing some word memory tests, but people almost don't cheat at all if the words were related to honesty or moral codes.
  • Chapter 14: The Context of Our Character part 2 - In this it is shown that people are more likely to cheat if they can rationalize the value of the thing they steal. A concrete example is that they are less likely to steal money than something one step apart from money, like a worthless token. The difference is quite significant.
  • Chapter 15: Beer and Free Lunches - A kind of good bye chapter, this shows how people are influenced in their choices by what other people in their group chose. He makes a clever experiment where people order from several types of beer, either publicly or on a piece of paper. Depending on the culture, they choose differently or similarly to what people before them chose.

Overall I found the book informative. If one can integrate the teachings of the book, the benefit for one's life would be great. Unfortunately, Ariely shows that this kind of rational illusions are predictable, and that people need to make great efforts to dispel them. I leave you with a video presentation from Dan Ariely on TED, just to give you a taste of what he is like and what he does.