Finding who has achieved in fewer attempts in MySQL

August 15, 2012

Let’s say we have a game where each will give be move into level or the chances of getting a score among 2+ users is high.

I’ll frequently get into tie when 2+ users get the same score so I’ll be confused to whom I should list in leaderboard. It’s logical to list the user who have achieved a particular level/score in fewer attempts. The idea is to attach the attempt no. to all the rows for each user for all their games and sort it by user_id, level (or score), attempt_no and then date. We then group the result by user_id to get only the least attempt for their latest achievement in level or greatest score. Now we would have got each user’s maximum level (or score) along with their attempt no. and it is straightforward to sort the result.

Consider the following table,


CREATE TABLE `users_games` (</code></pre>
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
 `user_id` INT(10) UNSIGNED NOT NULL,
 `level_id` TINYINT(3) UNSIGNED NOT NULL,
 `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
 ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin

We store the user_id, their level and the date when they have achieved the level.

The complete query to the problem

</code></pre>
SET @attemptnum = 1, @prev_val = NULL, @rownum = 0 ;

SELECT @rownum := @rownum + 1 AS rank, id, user_id, attempt, level_id, DATE

FROM (

SELECT id, user_id, attempt, level_id, DATE FROM (

SELECT id, user_id, level_id,

IF(@prev_val = user_id, @attemptnum := @attemptnum + 1, @attemptnum := 1) AS attempt,

@prev_val := user_id, DATE FROM (

SELECT id, user_id, level_id, DATE

FROM users_games ORDER BY user_id ASC, level_id, DATE ASC)

rs)rs1

GROUP BY user_id

ORDER BY level_id DESC, attempt ASC, DATE ASC

)rs2

ORDER BY level_id DESC, attempt ASC, DATE ASC

The inner most query ensures the users_games table is sorted by user_id, then their level, then by date. Then, we attach attempt_now for each row by checking through their levels. Note, a user can be in the same level for many times and will be counted as attempts to achieve their max level.

We further sort the result by level_id by DESC, their attempt, then date. The date is to break any tie, if 2+ users have achived the same level in the same attempt. In that case, we give appreciation to the user who have done it first.

We group the result by user_id to keep only the first row for each user that will contain their best level and their attempt, ordering it again by level_id DESC, attempt ASC to ensure the desire result.

IRCTC – Ticket booking tricks

January 31, 2011

IRCTC is most trafficked site since most people reserve tickets for their journeys. With this imperfect world, we cannot plan our jouneys very earlier so most of us depend on Tatkal booking that will open only 2 days before the date of travel. When we try to book tickets at 8:00 (which is the start time of Tatkal booking), IRCTC will be unresponsive and Service Unavailable message will continuously irritate us. Don’t be panic! By following few techniques, you can increase your chance of getting your ticket confirmed with Tatkal, though it will not guarantee your ticket.

Necessary Tools:
Firefox with Firebug+Web developer (Generally, add-ons will make surfing slow, but this help you in this matter)

Roboform – Form filler

Make sure to fill the quick book form with necessary details using Roboform the previous night.

The next day morning at 7:58AM, pre-fill the form (that you have already saved in Robo form) in IRCTC’s quick booking form.

Once it reached 8:00 and 10 seconds in OS (You can believe windows time since it will sync time automatically, if you are using Windows), disable javascript in your browser and click the quick book submit button. If that takes you to the next, enable javascript and make the payment and click on return to merchant link in your online banking page. You should have seen a green message showing your ticket has been confirmed!

Troubeshooting & Tips:
1) If you see Service Unavailable, gently  press F5.(means only when you see that error, NOT continuously, otherwise you may receive session expired error).
2) Use Netbanking for payment, it seems to be faster. My colleague suggested Credit card payment also seems to be faster since there is no OTP, just the Verified by Visa password.
3) If session expired, re-login and go to quick book form and use our already saved form to fill and try again. Never give up too easily. You can try till 8:15AM to test your luck.
4) You can the same login detail in multiple browser and try in all the browsers. You can try booking in other browser, if your main browsers continuously shows Service Unavailable Error.
5) If CAPTCHA did not appear quickly, disable javascript and INSPECT the Captcha element. I once tried this, captcha code is available in the browser itself( site bug).
6) Use Roboform to fill authentication credentials of online banking details. Don’t type at that moment. Use HDFC, I presume it will directly make payment without OTP that was sent to Mobile (This is the only place SBI perform badly and making delay in the payment). Use whatever payment that will not require addition authentication.

Because every second counts…

Note: In fact, sharing the tricks will decrease my chances of getting the ticket confirmed, still I share it because this approach will force me to think new ways of tricking IRCTC (How nice it would be, if my scheduler script automatically fetch my journey date from my Calender program and make a request to Firefox’s GreaseMonkey script, which in turn, fill the necessary details from my notes about Passenger list and retrieves the CAPTCHA code from browser (or to send the CAPTCHA code to Abby Fine Reader that will recognize the code, if Sify guys realizes the CAPTCHA bug and fixed it) and will send it to GreaseMonkey script that will forward this request to my SBI Netbanking and auto-make payment and finally it should alert me with the SMS, “Boss!, we have completed the mission critical operation successfully and got your ticket confirmed. Please remember to make a hard-copy of the ticket that we have sent to your Email. Have a nice journey”)

 

 

How to become a ZCE (Zend Certified Engineer)?

October 5, 2009

How to become a ZCE?
Becoming a ZCE is not a difficult process. Few people in zend’s yellow pages actually mean people are not interested in exam and less people are writing comparing to Sun/Microsoft/Oracle. Anyone can become ZCE if they ‘prepare’ correctly. Zend exam, tests the candidate’s knowledge on various topics of PHP, both core language features and key extensions.( http://www.zend.com/services/certification/php-5-certification/)
Key facts about the exam:
Zend exam checks your knowledge on PHP rather than your knowledge on programming, though the official website says like that, there are questions that require logical thinking. Don’t forget to read Zend’s PHP exam faq. You’ll key information such as exam covers PHP version 5.1
MySqli, SQLite will include in the exam, though the syllabus says only standard SQL will be covered.
Exam checks the sound working knowledge of core PHP (But I cracked it with 90% reading & 10% practising). Most of the time, you’ll be a given a code snippet and need to find the bug, output, etc. So get ready to make your hands dirty with a good PHP IDE
There is no mark or grade for the exam. Just a PASS/FAIL based on the questions answered. Based on reply from Zend for a clarification, I even suspect there should be different weight for each questions
The questions will not be evenly distributed among the syllabus and some chapters have more ‘weightage’ than others. For eg, you may get more questions from OOP than SOAP
Failing in single topic, will not make you FAIL in ZCE as whole.
The Official Zend Certification Study guide will not cover the entire syllabus. Of course, if you read this book alone, I’m sorry you are wasting your money. The book just gives you an idea about syllabus, just a big syllabus book.(The book didn’t include even a single about PDO or SQLite)
References:
PHP Manual – Language reference (Don’t miss even a single word in this section) and function reference (Just have a look at all the function and give deep look at commonly used functions). For eg, exam may include a objective type options as string_split & str_split so you may need to differentiate ‘fake one’ from original
PHP 5 Certification Study Guide(2nd edition might have less typo, get it, if you can)
This is the official study guide and you should read it whether you like it or not
PHP.in.a.Nutshell.Oct.2005
This book provides precise info about each topic of PHP, especially output buffering & file management
PHP Architect Guide to PHP Design Patterns 2005
Just get to know about what are the design patterns available, though you don’t need to know how to implement each, but you should be identify each pattern with the code snippet given
Sklar – Learning PHP5 (O’Reilly)
Form, functions & arrays are good to read and the entire book would be
PHP5 Recipes – A Problem-Solution Approach (2005)
PHP Cookbook, 2nd Edition (2006)
Both cook books provide good recipes to practice, I use Oreilly’s cookbook extensively
Apress.Beginning.PHP.and.MySQL.3rd.Edition.2008
(A book that touches almost every topic in PHP and in the exam too, can be used as quick ref)
Apress.Pro.PHP.XML.and.Web.Services.Mar.2006
(I thought I should read this, the day before exam, unfortunately, I got no time.)
Apress.Pro.PHP.Patterns.Frameworks.Testing.and.More(2008)
(good intro to OOP, Standard PHP Library(Iterators, ArrayAccess)
Essential PHP Security (2005)
–extremely essential book. Never miss a single line. It’ll pay back both in exam point of view & knowledge point view
Pro PHP Security – Apress – If u r more interested in security
Hacker Web Exploitation Uncovered (2005) – If you are interested in breaking, others’

Additional Reference:
Bruce.Eckel.Thinking.In.Java.4th.Edition.Dec.2007.eBook-BBL
Chapter – 1 – an excellent intro to theoretical OOP
Addison.WesleyCore.Web.Application.Development.with.PHP.and.MySQL.Sep.2005
PHP and MySQL web development 4th Ed.2009

About Mock Exam:
Copy & paste exam questions and make a research later on each question in mock.
I purchased 10 exam practice test pack along with my friend, but I passed in the very first exam itself and got excellent in 3rd mock exam and exam result prejudge the exam to schedule too early than actually it should be and made me to feel in the centre that I’d have ‘prepared’ well. So don’t be cheated with mock exam, though you must need it before taking the exam.
Those who are from computer stream will be benefited with their academic knowledge (actually, my exam result was highly influence by C++ & academic OOP) and they can easily build new knowledge from their existing one. Non-computer stream guys need to do a slight hard work to keep things smooth (Of course, the exam itself is for those who are from non-computer streams to prove their ability to their employers.)
Personal exp.: Mock exams are direct questions & simple logic rather than real exam that requires practical exposure and deep understanding of the language
How to prepare?
Sincere study – simply no substitute. Share your knowledge with others and make a collaborative study
Give importance to minor details-eg-get to know about what print will return and what will if it has been combined with another string or added with quoted number.
Practice programs, especially the ones related to strings, arrays, domxml & oops. Unless otherwise you know how OOP has been implemented in PHP4 & PHP5, you’ll not be able to tell the difference between two by just seeing the code in PHP 4 vs PHP 5, for eg.
Check you readiness with mock exam, till you get 3 excellent grades to save your money
Professional guess – (method of elimination, checking for verbal clues, believing ‘none of the above’ is genuine answered, if you got a question that you have never come across. Yes, there is not –ve pts. Exploit it)
In the exam centre:
Make sure that you two form of pho identify
Read & understand the question. Don’t get fooled by the word! The method named ‘generate_even’ doesn’t need to be generating even nos.
Answer all the question ( no –ve marks)
Mark for review, if a particular question takes time
**Remove** mark for review before ending the exam as such questions will be evaluated as wrong. One ZCE shared this in his blog
Optional:
Speed reading:
Use the proven tools such as EyeQ/Acereader to speed up your reading and hence learning
Note: please do not ask the exact questions asked in the exam and don’t put me in a critical situation as revealing questions may invalidate my certification and I have agreed not to do so :D. Thanks for understanding

IRCTC Security flaw exposed

August 19, 2009

Already one security flaw has been reported in a blog http://blog.mayankkapoor.com/2008/06/security-hole-on-irctc-train-ticket.html

For my part, I found one. IRCTC has a good validation at client side, but poor validation at server side. So I tricked IRCTC and changed some values after form submission, the system failed to validate properly. I changed berth preference to ‘dummy berth;it accepted. Worse, I tried to book a ticket with Rs.3/-, the system accepted and redirected me to SBI for money transfer. When I transfered Rs.13/-(with commission), irctc failed with communcation error(Thank God!). I thought somehow the system failed to deliver ticket for a fake amount. The next day I got a automated mail from IRCTC that the ticket has been cancelled and a refund for Rs.262(????!!!) will be credited to my account within ‘n’ working days. I shocked with the mail and have reported IRCTC to fix the bug soon

Update: IRCTC fixed this issue

Protected: About my life parter

May 13, 2009

This content is password protected. To view it please enter your password below:

The things I like most

May 10, 2009

Obviously everyone will be addicted to something or someone all the time or at least for some extent.At my childhood I liked to play outdoor games, roaming with friends, watching movies, etc. But now a days my taste differs as the time moves.

My PC

In fact, I can live without spouse but not without mouse. The only thing which quenches my loneliness. I use it for my profession, chess(professional hobby), entertainment and personal use

Travel

I always love to go for tours and picnis with friends and family, especially at hill stations and forest areas.

Chess

Once I had even thought I should take it as my primary profession, but later I realized that it would not help me to survive.  Still I play it, read it, watch it, explore it at all my free time.

Reading

At my childhood, I hate to read/study and lost all my valuable time and knowledge. I never thought reading would be much fun, tasty and worthy. Now I’m reading,reading,reading. Whenever I have time i’ll read. I prefer to read self help, leadership, relationships and tech computer books and also chess

Friends

I always like to be with friends, but you may wonder why I’m staying alone. I am very different from most of my friends. The only thing which matches with my friends is ‘outing'(Unfortunately, that too is became rare, now-a-days. If that continues, I’ll become a bot). Reason is, I hate movies and games, whereas most of my friends are interested and it is quite natural. I’d be much happy, if get a friend who matches my mind’s frequency