Category: Geek

Why do escalator handrails move at different speed?

Did you notice that the handrails on escalators are moving at a different speed than the stairs? Well I did too and it bugged me enough to do the research on why is that happening.

There are many different theories around the interwebz to answer the question. One of the most popular one is saying that the slight speed difference is there on purpose to prevent the tired traveler from falling asleep / not paying attention and hurting themselves (basically to prevent lawsuits). I do refuse to believe that theory. My reasoning is simple: The same speed difference exists in Budapest’s metro system and I’m 100% sure they don’t give a rat’s ass about the safety of the travelers.

If you look at the picture above one thing is obvious. The distance that the handrail have to travel is longer than the distance the stairs need to do. Now imagine two circles (or ellipsis rather) that only have one touch point.

If you put a motor at that single point to spin both circles the speed of each circle will be very different. They will be approximately the same speed as you get closer to the touch point but will differ wildly when they are farther apart.

Now you can obviously modify this behavior by adding gears and essentially changing the speed each circle does on a per section basis, but surprisingly enough escalator manufacturers tend not to do that. Instead they have two motors running each thing.

And here is where the speed difference comes in: Turns out when an escalator is new both the handrail and the stairs are running at almost exactly the same speed. But since the handrail motor is doing more or less work it’s gears will degrade at a different rate and sooner or later the handrail will be slightly out of sync from the stairs.

Every day we learn something new (and useless)

Be Sociable, Share!

Writing my first iPhone app – Day 6 – Its all coming together

Finally managed to unpack everything after moving flats so no more boxes, yey! Unfortunately somehow managed to lose the box with my socks and underwear tho. Oh well, you win some you lose some. Anyway, had some time today to work on this app of mine.

First of all I wanted to pretty it up a little bit. I have no sense of style at all (don’t think any coder does) but I do not like working with anything too messy. So here are a couple of things I did to make me feel more comfortable:

I’ve reordered my tabs in my TabBarController to make the “Play” item to be in the center. For much of my surprise the storyboard editor doesn’t let me select the default tab. I realized that I have to extend the TabBarController. So after much research I found a code snippet that did the trick

I’ve also made the tab bar’s color scheme inverse so the above code takes care of the font colors as well. I also wanted to display a heading on all pages with a title so dragged in a Navigation Controller and connected it to my Tab Bar Controller. It displayed the heading placeholder but I couldn’t find a way in the storyboard editor to set the text for each tab element. Clever people of stack overflow said that i can set the title from the ViewDidAppear method of each controller. Here is an example of how:

Since I really don’t like the UIColor API (coming from web development background I think it’s understandable) I was looking for an easy to use alternative. Thats how i found UIColorExtension. Its a simple extension that allows me to use RGB(a) hex codes in my color definitions. So I can write stuff like this:

Winning (except for the 15 minutes it took me how to do # on a mac keyboard)

Also replaced my label that was used for the countdown with a Progress View. Progress View’s are really straight forward to use:

All right. I think I’m done with prettying stuff up. It is still ugly as fuck but bit easier on the eye:

Screen Shot 2015-06-14 at 15.49.32

I hooked it up with the question API I made in my previous post and it worked like a charm. Except one thing: Since the API was using random sometimes it gave me the same question twice. In order to avoid that I needed to log the user’s answers. So created a new table:

And a new class:

The PHP API has been modified a little as well to able to record answers + avoid sending the same question to the same user again:

Great, now the only thing left to do is to make the app send home the user’s answer for logging. In my PlayViewController I modified the logic that happens when the user clicks one of the answer buttons:

When the user hits the button it just checks against self.currentCorrectAnswer and depending on the result it sends home the questionId, userId and 0 or 1 for logging.

Finally I decided to make this project fully open source. Please feel free to fork / do a pull request / whatever, but keep in mind it is very much a work in progress and I have literally no idea what am I doing in Swift

Repo for the app | Repo for the PHP Api and scraper(s)

The game is actually playable now and it is moderately entertaining. Will need to find a new source of questions because the current ones are way too British.

What is next? The gameplay is pretty much ready now. It needs some refactoring and some security on the API but its ok for now. Next time I’m going to work on the leaderboard view. Deal with some TableViews in xcode and probably implement Facebook friend list somehow.

Be Sociable, Share!

Writing my first iPhone app – Day 5

Ok, I’m cheating a little bit here. I did not work on the app during the past two weeks or so but I have very good reasons. First of all I moved to a new flat (which I absolutely love btw) and as you know moving is hard. Secondly the Macbook I borrowed from work pretty much died under me. It kept presenting the so called “black screen of death” 9 out of 10 times I tried to boot. Tried to do all the PRAM resets and mental keyboard combos I could find online but no joy. Anyway, bought the new generation Macbook Pro now (force touch trackpad rulez btw) so I’m back in business.

That being said yesterday I only worked on the back-end of the app. In order to go forward with the actual iOS development I needed some questions and answers in my database so I decided to look around to find a site which I can scrape. I’m really surprised that there are no good quiz sites around with 4 answers for each question and the correct answer included. Found some databases for sale that would fit my needs but the sales page were either crappy or the database was ridiculously overpriced. The only site I could find that met all my requirements is PubQuizArea, which ticks all the boxes, however it is really British. Oh well, it should do for now.

First of all I need a table structure:

The model for this is written with my No-BS Framework. It does not need to modify the base model at all, just need to define the table fields and some validation rules (question needs to be unique:

The main part of the job is writing a simple scraper. Luckily the site’s structure is pretty well thought out so it makes it easy to scrape:

I know I know. Heard it million times: my scraping style is really old school. Guess what? I tried all those hipster libraries for scraping which promise you bells and whistles, none of those worked for me. Every once in a while they stop working and it is really hard to find the actual issue under the hood. As always I’m using my trusty curl class to fetch the data.

The script is just looping through the subpages of the category url from the command line argument and get the question / answer data from them. Luckily the correct answer is highlighted with a separate class (“blue”) so it is easy to recognize. $question->validate($db_data); takes care of removing dupes too.

That site gave me about ~1,800 questions. Obviously not enough, but will do for testing.

Last thing was to add an endpoint to my api. My __construct became:

And the implementation is:

Obviously this logic will change as I hook it up with the app (rand() doesn’t exactly prevents the user from getting the same question over and over again) but again, its ok for testing. If you fancy trying it out, click here

Be Sociable, Share!

Crappy Fizz-Buzz

Read this article today on HN about 5 alternatives for fizzbuzz for coding interviews. The last one was to write the worst fizzbuzz program you can come up with. It sounded like something i should do before my morning coffee so here is my entry:

Can you do worse?

PS: No movement on my iPhone app today since I decided to get drunk yesterday

Be Sociable, Share!

That perfect ding

If I would ask you to think about the most used app on your phone and recall it’s most defining characteristic I guess most people would think about the icon or the app’s color scheme. But I do think that the most important feature of an application is the noise it makes.

When the Facebook app makes that “ding” noise it triggers and almost emotional reaction and excitement. Next time you are travelling by bus and hear that sound just look at the people. Guarantee you that more than a few of them will reach to their pockets with a hopeful expression on their face hoping they are the chosen one who got the message. Literally a pavlovian reflex. I think this is the reason why most of the popular apps are using custom sounds. Instant and free viral marketing.

Now, I never worked in the app business and definitely never worked for a multi billion dollar business like Facebook but I’m really interested in what kind of research these companies do to decide on the sounds.

  • Is it a single person who decides or is it a team?
  • How the hell those brainstorming meetings go? (“hey i have an idea. how about a swooshy noise?”, “don’t be ridiculous, that will never work. i think it should be more like a badabum sound”)
  • Are they using psychiatrists to maximize the viral effect?
  • Do they user test the noises with focus groups? (must be the weirdest temp job ever)

If you work for an app company please comment because I’m really interested.

PS: If you frequently use mass transportation please have the curtesy of muting your phone. It’s nice and all that you have a life but your Facebook app is giving us the false hope of someone thinking about us for a few seconds, and that constant disappointment is not a good way to start a day.

Be Sociable, Share!

I guess I’m into crypto currencies now

I was mad at myself for a long while for not getting into Bitcoin when the price was as low as $10 / btc not too long ago. I guess the main reason why I never invested is because I never fully understood the technology. To be fair I still don’t understand it 100%.

Then came the rise of “altcoins”, the alternative crypto currencies. I got especially excited about DogeCoin. What sets this currency apart from the 100s of other ones?

  1. It started as a joke, “meme” currency and I fucking loves memes
  2. It is dubbed as a “tipping” currency which encourages the flow of the money. The doge community actually donated over $30.000 for the Jamaican bobsled team so they can attend to the winter olympics
  3. Mining is relatively easy even with CPU

With all new crypto currencies there are new marketplaces where you can buy / sell coins. One thing I realized the price of coin is varies wildly depending on how much risk does the seller have to take for a given transaction.

For example: on eBay the price of doge is about £1 / 1000 coins because eBay uses Paypal and Paypal transactions are reversible, while Doge transactions aren’t.

On the price currently around £0.6 / 1000 if you buy via UK bank account. The seller still takes a little risk but not nearly as much with Paypal.

And finally there is the cheapest but most complicated way: Buy Doge with BTC. There is absolutely no risk there and you can get a 1000 coins for like £0.42. Naturally I went with this option, which raised an other issue: I have to acquire some BTC. I was using which is a peer to peer exchange and bought my first 0.5 BTC. Then using coinedup I exchanged them to Doges.

Now for selling i was considering dogeforsale, but got into a price war with some of the other sellers which made the price as low as it no longer worth my time to do it. So I moved on to eBay. As I mentioned selling crypto currencies via paypal is risky. The biggest risk you face is when someone is using a stolen paypal account for the purchase, then later the original owner issues a refund request. There are a few ways to protect yourself though:

  1. Only sell for eBay members with 50+ ratings (100% positive)
  2. Always ask the buyer to send his wallet address from the paypal email address to your email address (so you validate that they actually have access to the email account)

With this I made some good profit, but its still pocket money. I was started looking at profitable ways of mining BTC so I can achieve close to 100% profits. Some people says mining BTC is dead. Well turns out its not strictly true.

I found this cloud mining platform called which makes it possible to mine profitably with a relative small investment. You can purchase gigahash / sec mining power from them. When you purchase lets say 1 Gh/sec you actually own the hardware behind it (they actually deliver it to your door if you want it). If you don’t want to use the mining power anymore you can sell it back to the system.

The price of Gh/sec is fluctuating (oddly, as I see it correlates to the price of BTC which makes no sense, but whatever), at the moment its at 0.01176013 BTC / Gh. Luckily I found my old external hard drive which held my old BTC wallet with 2.3 BTC in it (talk about found money) and invested a portion of it for 100 Gh / sec. This mining power gave me about 0.02 BTC / day which equals about £7 profit daily. If I convert this to doge that will be around 17.000 doge coins and I can push that on eBay for £14-£17. If I get bored of it, or just want to cash out, I will sell back my Gh and exchange my BTC back to cash.

I’m doing this for about a month now. Lots of research, got scammed a couple of times but it kind of worth it. It is just fun to play broker with these virtual currencies. Yesterday for a little while I was a doge millionaire. Too bad you can’t get a physical, monopoly money-esque version of these coins.

Be Sociable, Share!

Facebook Hacker Cup 2013: My solutions

Task 1: Beautiful strings

When John was a little kid he didn’t have much to do. There was no internet, no Facebook, and no programs to hack on. So he did the only thing he could… he evaluated the beauty of strings in a quest to discover the most beautiful string in the world.

Given a string s, little Johnny defined the beauty of the string as the sum of the beauty of the letters in it.

The beauty of each letter is an integer between 1 and 26, inclusive, and no two letters have the same beauty. Johnny doesn’t care about whether letters are uppercase or lowercase, so that doesn’t affect the beauty of a letter. (Uppercase ‘F’ is exactly as beautiful as lowercase ‘f’, for example.)

You’re a student writing a report on the youth of this famous hacker. You found the string that Johnny considered most beautiful. What is the maximum possible beauty of this string?

The input file consists of a single integer m followed by m lines.

Your output should consist of, for each test case, a line containing the string “Case #x: y” where x is the case number (with 1 being the first case in the input file, 2 being the second, etc.) and y is the maximum beauty for that test case.

5 ≤ m ≤ 50
2 ≤ length of s ≤ 500

My solution for this problem was fairly straight forward. Not the fastest solution I guess, but it works: get the string, count the unique alpha characters in it and add up the “beauty”

Task 2: Balanced Smileys

Your friend John uses a lot of emoticons when you talk to him on Messenger. In addition to being a person who likes to express himself through emoticons, he hates unbalanced parenthesis so much that it makes him go :(

Sometimes he puts emoticons within parentheses, and you find it hard to tell if a parenthesis really is a parenthesis or part of an emoticon.

A message has balanced parentheses if it consists of one of the following:
– An empty string “”
– One or more of the following characters: ‘a’ to ‘z’, ‘ ‘ (a space) or ‘:’ (a colon)
– An open parenthesis ‘(‘, followed by a message with balanced parentheses, followed by a close parenthesis ‘)’.
– A message with balanced parentheses followed by another message with balanced parentheses.
– A smiley face “:)” or a frowny face “:(”

Write a program that determines if there is a way to interpret his message while leaving the parentheses balanced.

The first line of the input contains a number T (1 ≤ T ≤ 50), the number of test cases.
The following T lines each contain a message of length s that you got from John.

For each of the test cases numbered in order from 1 to T, output “Case #i: ” followed by a string stating whether or not it is possible that the message had balanced parentheses. If it is, the string should be “YES”, else it should be “NO” (all quotes for clarity only)
1 ≤ length of s ≤ 100

I spent quite a lot of time, about 40 minutes on this one. I ended up with a recursive function which relies on a regular expression: “/(\(.*)(:\))?(:\()?(\))/U”. This regex will match the parts of the string which are in brackets even if the parts are containing a smiley. Then it is just a loop for counting the opening and closing parentheses.

Task 3: Find the min

After sending smileys, John decided to play with arrays. Did you know that hackers enjoy playing with arrays? John has a zero-based index array, m, which contains n non-negative integers. However, only the first k values of the array are known to him, and he wants to figure out the rest.

John knows the following: for each index i, where k <= i < n, m[i] is the minimum non-negative integer which is *not* contained in the previous *k* values of m. For example, if k = 3, n = 4 and the known values of m are [2, 3, 0], he can figure out that m[3] = 1. John is very busy making the world more open and connected, as such, he doesn't have time to figure out the rest of the array. It is your task to help him. Given the first k values of m, calculate the nth value of this array. (i.e. m[n - 1]). Because the values of n and k can be very large, we use a pseudo-random number generator to calculate the first k values of m. Given positive integers a, b, c and r, the known values of m can be calculated as follows: m[0] = a m[i] = (b * m[i - 1] + c) % r, 0 < i < k Input The first line contains an integer T (T <= 20), the number of test cases. This is followed by T test cases, consisting of 2 lines each. The first line of each test case contains 2 space separated integers, n, k (1 <= k <= 10^5, k < n <= 10^9). The second line of each test case contains 4 space separated integers a, b, c, r (0 <= a, b, c <= 10^9, 1 <= r <= 10^9). Output For each test case, output a single line containing the case number and the nth element of m.

Well, I failed this task. Not because my solution wasn’t working. It wasn’t fast enough in some cases. I considered seed (it is not my first time on the Hacker cup) and tested it with large arrays but I missed a case when my script fails. The key speed up was when I realized that the analyzed array slices are repeating. They are repeating after every Kth element, therefor:

It gave me a huge speed up, but apparently not enough. I tried to run my script with the test cases provided by Facebook’s system and it didn’t finish in the 6 minutes limit even on the high-compute Amazon EC2 instances. Epic fail. Well next time. Anyway, my solution for task #3:

Be Sociable, Share!

Howto: Install OSX Lion under Windows 7 and VMware

So I decided to learn objective C, partly because it’s been a long time since I developed anything besides web apps and partly because I have a couple app ideas in my mind. Anyway, it turns out there is no option to code for the iPhone on Windows 7 (besides Visual Studio. Thanks, but no thanks) so I decided to install OSX Lion using VMware. I read a whole bunch of tutorials on how to do it and finally succeeded. Here is a simple step by step guide so you can try it yourself

What will you need?

  1. You need a bootable OSX Lion image. Not sure how to legally acquire it but here is a link for a torrent file
  2. VMWare Workstation. Now this is a paid software but a quick search on isohunt will help you out. I recommend getting the latest version (9.0) if you can
  3. VMWare hard drive files. You can download them from here (self-extracting exe)
  4. “Additional files”. Various tools

Ready? Let’s install!

  1. Install VMware workstation. Don’t run it just yet.
  2. From “Additional files” extract “macosx_guest_vmware_7.tar.gz” and run “windows.bat” as an Administrator. This will patch VMware workstation to enable you to run OSX
  3. Start the self-extracting “Mac OS X Lion VMware Files.exe” (point #3 in the “What will you need section”
  4. Start VMware workstation and click on “Open a Virtual Machine” and browse to the folder extracted in the previous step. Open “Mac OSX Lion/Mac OS X Lion.vmx”
  5. Click on “Edit virtual machine settings” and remove the CD / DVD drive
  6. Still in “Edit virtual machine settings” click “Add…” then “Hard Disk” then “Use an existing virtual disk and browse to the downloaded OSX Lion image (the big one)
  7. Click “Power on this virtual machine” to launch the virtual machine. If it asks you a random question (can’t remember what exactly was it) answer “I copied it”
  8. The installer should start in a couple of moments. Just follow the installation steps and you are ready to go

Couple of problems / tweaks

  1. The image by default will only work with 1024×768 resolution which can be really annoying. To solve this copy “darvin.iso” from your “Sysprobs Lion Files” to an usb drive and install it on your OSX system. After the install and the reboot you will be able to choose whatever resolution you want
  2. Sound doesn’t work. I’m still trying to figure out how to solve this
  3. I tried to install OSX on my work computer which has an AMD processor but it gave me errors. There are some tutorials around the web to solve that problem, but its time consuming so I just didn’t bother. Just google the exact error message and you will be able to solve it if you really want. The method described here works perfectly for my Intel i7 desktop and my Intel i5 laptop (I guess it should work on any Intel chipset systems)

Have fun

Be Sociable, Share!