Nadim is Simple

April 17, 2009

Calendar Control for iPhone

Filed under: Creativity — Tags: , , — Nadim Jahangir @ 10:09 pm

Somedays ago when I was developing an iPhone application, I required to use a calendar control to show date specific information on it. First I thought that I might get a built-in control in Cocoa Touch UIKit, but unfortunately there is no such thing in that. So I create my own calendar control which is fully customizable. Here is the screenshot of my calendar control.

 

 

Calendar Control Demo

Calendar Control Demo

You can set the color theme, cell background image, day tag image, weekends and their colors. You can also change the first day of week. Actions can be set for event Touch Up Inside each day cell. Months and years can be navigated individually. Current day can be selected by passing goToday message to the calendar conrol object. This control is to be added as a subview of any view and I made it by inheriting UIView class. There is only a single class to do all this.

If anyone of you need this then go to http://nrg.com.bd/blog/archives/36

December 30, 2008

Math for Simple Particle Generation with ActionScript 3.0

Filed under: Creativity, Tutorial — Tags: , , , , — Nadim Jahangir @ 8:48 pm

I was just passing my time and built a simple but pretty nice particle generator in ActionScript 3.0. I assumed the particles to be small projectiles and motion of which are driven by the following equations,

x = x0 + vxt

y = y0 + vyt – 0.5gt2

where,

x0 = initial position along x-axis

y0 = initial position along y-axis

vx = initial velocity along x-axis

vy = initial velocity along y-axis

g = acceleration due to gravity

In the demo http://nadimjahangir.net/xp/particle.swf the initial position are set to mouse position. And initial velocities are set randomly.

Particle Generation Demo

Particle Generation Demo

This can further be enhanced by adding air friction terms.

ActionScript 3.0 Pseudo-3D Drawing Performance

Filed under: Study — Tags: , , — Nadim Jahangir @ 11:58 am

Since there is no 3D library in ActionScript 3.0 we need to do pseudo-3D drawing by some projection calculations which requires expensive matrix and vector calculations. I was just wondering if Flash player is capable of handling such huge load due to this massive calculations when there are lot of 3D objects and complex scene construction is required. But fortunately Flash player can do this quiet satisfactorily though when the 3D scene to be rendered is very much complex the exact timing slips due to increased time complexity. But in most of our applications we don’t need that much calculations and Flash player can give us pretty smooth and glitchless 3D animations.

I tried drawing some 3D scenes. Two of them are shown below.

To see “ball bouncing in 3D space” go to http://nadimjahangir.net/xp/test3d.swf

A Ball Bouncing in 3D Space

A Ball Bouncing in 3D Space

To see “wavy 3D surface” demo go to http://nadimjahangir.net/xp/wave3d.swf
Wavy 3D Surface

Wavy 3D Surface

December 27, 2008

Bush hottShot

Filed under: News — Tags: , , — Nadim Jahangir @ 1:46 am

I’ve just finished developing a Flash game for hottMedia Ltd. It’s a fun game for throwing shoe at Bush. Since it’s a fad game I had a very short notice (only 2 days) and so there may be still some bugs there in the game. The game title is Bush hottShot. This game can be played in hottDhaka.com and Facebook as well. Danny bhai is the graphic designer and Hasan bhai did the animations. I did all the coding in ActionScript 3.0.

December 12, 2008

Bitmap Manipulation in ActionScript 3.0

Filed under: Creativity, Tutorial — Tags: , , , — Nadim Jahangir @ 5:22 pm

In ActionScript 3.0 I found very useful classes for bitmap manipulation. The classes are BitmapData and Bitmap. I can now do image processing from right inside ActionScript. Using the BitmapData class you can access each pixel in a bitmap individually. The bitmap data can contain any image data of any movie clip. The following is an example code for this,

var bmpData:BitmapData = new BitmapData(mc.width, mc.height);

bmpData.draw(mc);

// do image processing tasks by bmpData.getPixel(x, y) and bmpData.setPixel(x, y, color)

var bmp:Bitmap = new Bitmap(bmpData);

addChild(bmp);

Here mc is the instance name of a target movie clip of which you want to manipulate pixels. bmpData got the pixel info of mc by calling draw() method. To make the bitmap visible after processing, a new Bitmap instance (bmp) is created and added to the display list by addChild() method.

I’ve made a demo of this pixel manipulation, here I made a wavy effect to an image of Angelina Jolie. Check this in here AS3 Bitmap Manipulation Demo by Nadim. Here is the screenshot.

Wavy Effect of Image by AS3

Wavy Effect of Image by AS3

December 11, 2008

Genetic Algorithm Driven Template Matching in ActionScript 3.0

Template Matching is used for object detection in images but this is computationally expensive task. If the image size is m×n and the template size is p×q then in worst case it requires m×n×p×q computations for normal template matching. If scaling factor and rotation are introduced for scale and rotation invariance then the complexity becomes O(m×n×p×q×sx×sy×theta) where sx and sy are the maximum allowed value of scaling factor along x-axis and y-axis respectively and theta is the maximum allowed rotation angle. So each parameter of the template deformation adds a new order to the template matching complexity and it soon becomes infeasible to cope with. In such case Genetic Algorithm (GA) can be useful to some extent. Although GA doesn’t gurantee that it will find the object in fewer iteration than exhaustive template matching does but there is a good probability for GA to find the object in fewer iteration. In GA based template matching the template deformation parameters are encoded into chromosomes. For example for a simple template matching where there is no scaling and rotation factor, the position of the template can be used to form the chromosome. I built a demo where the template co-ordinates are used as the chromosome, you can see it from here Genetic Algorithm Driven Template Matching Demo by Nadim

Here is a screenshot. The eye (the template) of Katrina Kaif is being searched by GA from the picture.

GA Driven Template Matching

GA Driven Template Matching

December 10, 2008

Use Bayes’ Net: Predict User Taste

Filed under: Creativity, Tutorial — Tags: , , , — Nadim Jahangir @ 6:18 pm

I’ve always been a fan of Probabilistic Modeling and Soft Computing because this is the only tool by which we can capture the uncertainty that we find in the nature. Among various probabilistic tools Bayes’ Net (BN) is one of my favorites (in full form Bayesian Belief Network). Use of BN is not new to software development. It has been used extensively for Machine Learning. Once Bill Gates said in LA Times that their competitive advantage of their software is due to their expertise in Bayes’ net. You can see how intelligently and beautifully Microsoft Office Assistant suggests you while you work in MS Office Applications. BN is also used for developing smart web applications with Collective Intelligence.

Now let me show you the use of BN for an interesting purpose. Before that I need to briefly explain about BN. BN is a probabilistic modeling technique that shows the causal relationship among various random variables in a particular context and used for answering any probabilistic questions regarding the random variables using Bayes’ theorem. For giving examples let me use hottDhaka.com which is social networking site and focused mainly on various spots in Dhaka city including restaurants, hotels, shopping centers etc. There is a spot in hottDhaka that is Aarong in Gulshan-1 which is a shopping center that provides with traditional handicraft dresses to home decor items to fashion accessories etc. Now what type of user visits that place and likes it is uncertain. But the person who loves to wear new and exceptional dresses with traditional flavor is most likely to visit that place. Moreover who lives in Gulshan-1 has a higher probability to visit that frequently than a person who lives in Dhanmondi. But we can’t say it for sure because user behavior is uncertain. A person for example a husband may not like Aarong and may also not live in Gulshan-1 but may need to visit that place because his wife loves that. So there are lot of uncertainties but the behavior of users maintains a definite probability distribution which we can model. [there are Aarong in many places, in this article I'm particularly talking about Aarong in Gulshan-1]

Let me model this Gulshan-Dress-Aarong scenario by BN. I assume Gulshan (G), Dress (D), and Aarong (A) to be three random variables which can take either of two values True(T) or False(F). G is True means the person under consideration lives in Gulshan-1, D is True means s/he loves wearing new traditional dresses, and A is True means s/he likes to visit Aarong etc. In BN diagram there are nodes for each random variable and the arrow from one node to another indicates causal relationships. Below is the model diagram for this example.

Baye's Net for Gulshan-Dress-Aarong Scenario

Bayes' Net for Gulshan-Dress-Aarong Scenario

There is an arrow from D to A indicates that D (dress loving) may influence the liking of Aarong. An arrow from G to D means that living in Gulshan-1 may influence in dress loving to visiting Aarong. A direct arrow from G to A means living or non-living in Gulshan-1 may also influence in liking Aarong. Now how much does a random variable influence to another is described by joint probability distribution associated with each node. The probabilities in consideration are,

P(G) = probability of a person living in Gulshan-1

P(~G) = probability of a person not living in Gulshan-1

P(D|G) = probability of a person loves dress given that s/he lives in Gulshan-1

P(D|~G) = probability of a person loves dress given that s/he doesn’t live in Gulshan-1

P(~D|G) = probability of a person doesn’t love dress given that s/he lives in Gulshan-1

P(~D|~G) = probability of a person doesn’t love dress given that s/he doesn’t live in Gulshan-1

P(A|G, D) = probability of a person likes Aarong given that s/he lives in Gulshan-1 and loves dress

P(A|G, ~D) = probability of a person likes Aarong given that s/he lives in Gulshan-1 and doesn’t love dress

P(A|~G, D) = probability of a person likes Aarong given that s/he doesn’t live in Gulshan-1 and loves dress

P(A|~G, ~D) = probability of a person likes Aarong given that s/he doesn’t live in Gulshan-1 and doesn’t love dress

etc.

Probabilities Associated with Nodes

Probabilities Associated with Nodes

The number of probability terms increases exponentially with the number of random variables and probability calculation becomes difficult when the network size gets large. Problem of BN calculation is NP-Hard. But the good news is there have already some efficient algorithms been developed in the literature for BN calculations.

The above BN can help us finding the answers to queries like,

  • What is the probability that a person likes Aarong given that s/he doesn’t live in Gulshan-1 but loves new dresses?
  • What is the probability that we find a person who likes Aarong but doesn’t like dresses lives in Gulshan-1?
  • What is the probability that a person lives in Gulshan-1 but doesn’t like dresses will like Aarong?
  • What is the probability that a person likes dress given that s/he lives in Gulshan-1?

We can find answers to any queries with probability. The above four are only a few for this particular example.

Now let me show you how BN can be used to predict user taste in your website (in this case hottDhaka). For simplicity of calculation let me consider the following simple BN.

Bayes' Net for User Taste Prediction

Bayes' Net for User Taste Prediction

Suppose by past user activity you found that 50 users like Aarong out of 100 users. Out of these 50 Aarong loving users 40 like new dresses and among these 40 users 28 live in Gulshan-1.  Now in the 10 dress non-loving users, 3 live in Gulshan-1. Further of other 50 non-aarong loving users 20 like new dresses. Now we can calculate the following probabilities.

P(A) = probability of Aarong loving users = 50/100 = 0.5

P(~A) = probability of Aarong non-loving users = 1 – P(A) = 1 – 0.5 = 0.5

P(D|A) = probability of dress loving users given that they also like Aarong = 40/50 = 0.8

P(D|~A) = probability of dress loving users given that they don’t like Aarong = 20/50 = 0.4

P(~D|A) = probability of dress non-loving users given that they also like Aarong = 10/50 = 0.2

P(~D|~A) = probability of dress non-loving users given that they don’t like Aarong = 30/50 = 0.6

P(G|D) = probability of users living in Gulshan-1 given that they love dress = 28/40 = 0.7

P(G|~D) = probability of users living in Gulshan-1 given that they don’t love dress = 3/10 = 0.3

P(~G|D) = probability of users not living in Gulshan-1 given that they love dress = 12/40 = 0.3

P(~G|~D) = probability of users not living in Gulshan-1 given that they don’t love dress = 7/10 = 0.7

Now suppose you want to suggest users of hottDhaka about spots when they are finished creating new account and filling up profile.

When any user fills in his/her home location and enters his/her home is in Gulshan-1, the probability that s/he would like new dresses can be calculated in the following way,

P(D) = P(D|A)P(A) + P(D|~A)P(~A) = 0.8×0.5 + 0.4×0.5 = 0.6

P(G) = P(G|D)P(D) + P(G|~D)P(~D) = 0.7×0.6 + 0.3×(1-0.6) = 0.54

P(D|G) = P(G|D)P(D)/P(G) = 0.7×0.6/0.54 = 0.78

So the probability that a user may like new dresses when s/he fills up his/her profile and puts his/her home is in Gulshan-1 is 0.78 or 78%. Now suppose after filling his/her home location he also chooses dress to be his/her choise from a favorites selection list, now you want to calculate the probability that s/he would like Aarong can be done in the following way,

P(A) = 0.5

P(G) = 0.54

P(G|A) = P(G|D)P(D|A) + P(G|~D)P(~D|A) = 0.7×0.8 + 0.3×0.2 = 0.62

P(A|G) = P(G|A)P(A)/P(G) = 0.62×0.5/0.54 = 0.57

Well now the probability of that particular user to like Aarong after filling his/her home location in Gulshan-1 and likes new dresses is 0.57 or 57%. So now based on this probability you can predict that this user may like to visit Aarong and you can then suggest him/her to visit Aarong :)

This decision process can further be improved by incorporating Fuzzy Inference Engine which will infer about the user taste more intelligently than simple hard limiting threshold. Using Fuzzy Inference Engine the following type of decision can be done using Fuzzy terms like pretty high, good, not bad etc,

IF probability of dress loving is pretty high AND probability of Aarong loving is good THEN suggest user to visit Aarong

Well, I’ve shown a very very and very simple example of application of Bayes’ net. You can’t imagine how beautifully it can be used to enhance user experience and making your web site smarter.

December 9, 2008

A* Search: A Nice Tool for AI Game Developers

Filed under: Creativity, Tutorial — Tags: , , — Nadim Jahangir @ 3:33 am

If a game is not developed with Artificial Intelligence (AI) then the characters in that game seem brainless which we don’t like. We want games seem realistic although the whole thing is virtual. The most important problem in AI is searching. Let me describe with an example. Suppose in an action game there is a maze like one shown in the image below. A man is walking in this maze and there is a bug that tries to attack that man. Now how can that bug reach to that man? In brute-force fashion we can try all the possible paths between the bug and the man but in a large world brute-force search is not feasible which requires both huge CPU cycles and memory. Moreover in brute-force means the bug will not show any intelligence. Also the bug needs to avoid obstacles shown by black blocks.

The world

The world

If you are to go to Sylhet from Dhaka, what will you do? Maybe first you think to go to Mymansing then from Mymansing to Sylhet. You will not start for going to Rajshahi because you know that Rajshahi is more far from Sylhet than Mymansing. If you have no knowledge about the distance among places then it’d be very difficult to find the optimal path. This type of prior knowledge is called Heuristics in terms of AI. A* searching algorithm is a very efficient and complete heuristic search algorithm. The completeness characteristic says that if there is a possible path then this algorithm must converge to a solution.

Now let me explain the algorithm in detail. First we need to encode the actual world into a convenient form so that the algorithm can be implemented easily. In the above world the bug and the man can stand at any point inside the maze within the blue areas other than the obstacles which is shown by black regions. But if we consider all the points in the region then it’ll be infeasible for implementation. So I tiled the whole world into small squares as shown above. Each tile/block is assumed to be a node in a graph which has 8 adjacent nodes on left, right, top, bottom, top-left corner, top-right corner, bottom-left corner, and bottom-right corner. So by a single step the bug can go into any of 8 adjacent blocks as shown below.

8 Adjacent Blocks

8 Adjacent Blocks

We need a distance function which takes two blocks as input and gives the distance between them. There are several distance functions namely Euclidean distance, city block distance, chessboard distance etc. You can choose any of these depending on the application. For now I’m using city block distance which is defined as follows,

dist(b1, b2) = |row(b1) – row(b2)| + |col(b1) – col(b2)|

where b1, b2 are two blocks and row(.) returns the row corresponding to the input block and col(.) returns column. Following is the city block distances of 8 adjacent blocks with respect to the center block.

City Block Distance from the Center Block

City Block Distance from the Center Block

Now by this distance we can make rough estimate about the distance between the bug and the man (without considering the obstacles). We’ll use this distance as search heuristics. During the execution of the algorithm a cost function will be used which is defined as follows,

cost(current_block, start_block, end_block) = dist(current_block, start_block) + dist(current_block, end_block)

During the execution we will choose the least cost block. The algorithm pseudo-code is given below,

put the start_block into a list named list_open

while list_open is not empty

current_block = least cost block in list_open

if current_block is the end_block then

path is complete

else

move current_block to another list named list_closed

for each adjacent block of current_block do

if it is not in list_open and in list_closed and it is not obstacle then

move it to list_open and calculate cost

When a least cost block is chosen then we need to keep track about from which block this block is selected and for this we will use arrow direction as shown below. Below is the execution result of A* search algorithm on the world we considered.

Execution Result of A*

Execution Result of A*

Deep explanation of this A* is beyond the scope of this article, I apologize for that. You can get this algorithm explained in details in any book of AI. You can enjoy a demo of this that I developed by Flash ActionScript 3 here A* Pathfinding Demo by Nadim.

Now consider the following case where there is no way out from the bug to the man.

Dead End

Dead End

In such cases how can we find that the bug has reached a dead end? Well, it’s easy, when the bug reaches the dead boundary and has no new blocks to step toward, the list_open becomes empty and if it is not then there is no adjacent blocks available to put into list_closed.

Terrain Cost

The above example is the simplest use of heuristics which is based on simple spatial distance. In some cases this simple distance may not suffice to achieve realism.  For example same distance in swamp area takes more time to travel than plain area takes. So we need to assign bigger cost for swamp area than to plain area. The cost calculation just needs to be changed, everything in the algorithm remain same. The cost calculation will be as follows,

cost = distance from start position + distance to end position + terrain cost

Let’s consider three types of areas namely plain, grassland, and swamped. The terrain costs are,

Terrain Cost Assignment

Terrain Cost Assignment

Example Terrain World

Example Terrain World

Influence Mapping

The calculation of terrain cost requires prior knowledge about the land features which is fixed for particular land. But in some cases the cost may be dynamic. For example suppose the man in the above example got a gun and he can shoot the bug when it comes closer. If there are more than one bug, the real world bugs will not go to the way where previously some bugs got killed by that man. If we can somehow program the bugs so that they don’t go along the path where previously some bugs got killed then it becomes more realistic and the bugs seem to act intelligently. We can do this by simply incorporating dynamic cost calculation or influence map. When any bug gets killed in a block, the cost of that block needs to be increased so that other bugs avoid that block when possible (during selection from list_open). A simple influence map is shown below.

Example Influence Map

Example Influence Map

This map changes over time each time the man moves and each time a bug is killed. In cost calculation the influence is just added with the total cost. More realism can be achieved by smart heuristics. It is not necessary to divide the world into blocks, we can choose any kind of encoding that is convenient for us. Below is an example of graph for a world where tanks are fighting.

Another World

Another World

References:

  1. Artificial Intelligence (Stuart J. Russell and Peter Norvig).
  2. AI for Game Developers (O’Reilly).
  3. A* Search Algorithm (WikiPedia).


November 27, 2008

Inverse Kinematics in Adobe Flash CS4

Filed under: Uncategorized — Nadim Jahangir @ 11:20 am

I first studied about Inverse Kinematics (IK) in a book on Robotics. IK is aka motion planning that calculates the motion parameters for various segments in an articulated structure. IK is used in Game Programming and 3D Animations. Recently Adobe introduced IK in Flash CS4 which is really a big addition and I think it’ll give more power to Flash Animators and Flash Game Developers. The IK task is done by articulated bone structure for which Flash CS4 provides necessary tools. You can find more on this in Adobe Flash CS4 What’s New Page. Flash CS4 introduces other features too which are really cool and useful.

A shape with an IK armature added

A shape with an IK armature added

A group of several symbols with IK bones attached

A group of several symbols with IK bones attached

November 12, 2008

My Headless Client Can Be a Headache for HottDhaka

Filed under: Observations — Tags: , , — Nadim Jahangir @ 10:15 am

My previous post was regarding the creation of fake account due to security leak in hottDhaka. Hopefully hottDhaka fixed it (but haven’t yet added any Captcha). I also found several other leaks. Now I’m gonna describe a new one which I found yesterday night.

hottDhaka management is worried (so far I’m concerned) about fake messages or spams that come to any persons inbox. One of the causes of this problem may be the leak in the message sending process. The problems are,

  1. They don’t use any Token and no Challenge-Response measures.
  2. The message sending is Cookie independent.
  3. It is user login independent.
  4. It is also Session independent.
  5. It is also HTTP Request and Requests Frequency independent.
  6. The message form is very plainly typed.
  7. They don’t use any Bayesian filter or other kinda Machine Learning tools.

I wrote a headless client (bot) by Java and managed to send 5000 fake messages automatically (without any user interaction) to Ariba Arusha Huq (contents executive, hottMedia), her member ID is 22079. My program looks like the following,

URL url = new URL (“http://www.hottdhaka.com/member/mail/sendmessage.php“);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection ();
urlConn.setRequestMethod (“POST”);
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setAllowUserInteraction (true);
urlConn.setFollowRedirects (true);
urlConn.setInstanceFollowRedirects (true);
urlConn.setRequestProperty (“Content-Type”,  “application/x-www-form-urlencoded”);
DataOutputStream out = new DataOutputStream (urlConn.getOutputStream ());
String content = “uid[]=” + URLEncoder.encode (“22079“)
+ “&title=” + URLEncoder.encode (“this is spam, visit http://nadimissimple.wordpress.com/ for solution”)
+ “&text=” + URLEncoder.encode (“hi! i’m nadim. this message is generated by my headless client (bot). hottDhaka security mechanisms are sooooooooooo childish. plz visit my blog http://nadimissimple.wordpress.com/ for solution”);
out.writeBytes (content);
out.flush ();
out.close ();

[red colored stuffs are the parameters in the form, uid[] is for a hidden field, title is for a textfield, and text is for a textarea]

Following is a screenshot of the console while my Bot was running,

Screenshot of Console while My Bot was Running

Screenshot of Console while My Bot was Running

I just wrote a Java method for this and called that in a loop for 5000 times :D . I didn’t even need to simulate Cookie. I didn’t also need to login, huh! how funny!. You can send message to other members by changing the ID, so randomly chosen IDs can be used to abuse this message sending feature.

Another leak is, the email address of members are shown in plain-text format in the profile which is prone to web crawling and spam.

Hope hottDhaka would fix this, best of luck :)

Older Posts »

Theme: Shocking Blue Green. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.