Cooking: Bubur Cha-Cha

I just finished cooking bubur cha-cha. Again, it is not as nice as the one in Penang. It is one of my favorite dish during Chinese New Year. It is usually served during the last day (15th) of Chinese New Year for Hokkiens. This version was just sweet potato, sago and black-eyed pea. It is too watery. I will put less water and coconut milk next time.

Gallery

Bubur Cha-Cha

References

Can’t open Finder app in OS X Lion

If you are having problem on opening ‘Finder’ app, solution is here. First, ‘command + option + esc’, then click on ‘Finder’, lastly select ‘relaunch’ button.
Another solution is uncheck ‘Reopen windows when logging back in’ on ‘Shut Down…’ dialog.

Gallery

  • finder

Where is Macintosh HD in OS X Lion

I just updated my Mac with OS X Lion. After playing a while, I realise I can’t find ‘Macintosh HD’. It no longer at left-side bar in Finder. I need it. So I came out with a solution as below.

  1. Right click on ‘Application’ and click ‘Open Enclosing Folder’. It will open ‘Macintosh HD’ folder in new window.
  2. Drag the top center icon, disc, to the left-side bar in Finder under ‘Favorites’.

Now, I have ‘Macintosh HD’ folder as favorited folder in Finder.

Gallery

  • Step 1
  • Step 2

Updates

22 Jul 2011

Another solution is open ‘Finder Preferences’, select / check ‘Hard disks’ on ‘Sidebar’ tab under ‘Devices’ section.

D3: Tutorial – Scale graph

First Protovis, now D3. Both are works from Mike Bostock. Both are data visualization JavaScript libraries.

This tutorial we’re going to create a basic dot graph with scalable y-axis. It is adapted from one of the examples in D3, dot.html.

Step 1: Default html

First of all, we create a default html that contains a div for input button and another for the graph. We also link the d3 JavaScript library. The rest of tutorial will be concentrate of JavaScript code that will be written after the comment, “Scale graph code here.”

Step 2: Random data

We need to generate some random data using Math.random(). We create randomData function for returning a list of ten x and y values. For example, [{“x”: 0, “y”: 0.3}, {“x”: 0.1, “y”: 0.4}, ...]

Step 3: Maximum value of y-axis

For this tutorial, only y axis values are random. We need to get maximum value of the y axis using d3.max, in order to scale the y axis based on the maximum value of the data.

Step 4: Ceil value

Sometime, the maximum value doesn’t suitable for domain range in scale axis. For example, 0.33333. Mike suggested a method to increase the size of domain to next highest rounded value.

Step 5: SVG container

Now, we determine the size of the graph, which are w and h for width and height. We need a svg container for the graph. We will append it inside #mainGraph div with width and height attributes. This is optional, which offset the graph with modify coordinate using translate in transform in a group. The <g> element is used to group SVG shapes together. For example, <g transform="translate(50,50)"> will translate coordinate ["x": 50, "y": 50] as zero in the that group.

Step 6: Rulers

Now, we add both x and y axises line grids and labels. We also notice that d3 supports css style. We make “#ccc” colour stroke style for both x and y line grids.

Step 7: Dots

This is the last step for the dots graph. All the dots are paths. What kind of symbols of the path is determined by d attribute. We also add title attribute in the path, so that when mouse is hovering the dots, tool tip is shown. Color of the dots fill is changed too. After you completed this steps, we will see a basic dot graph.

Step 8: Update button

This step is explaining what will happen after update button is clicked. Before that, we need to add onclick attribute in button type input with the update function name. For example, <input name="updateButton" type="button" value="Update" onclick="updateData()"/>. In the update function, we will get a new data list from randomData function. Then get the maximum ceil value, which is similar in initData function. Since, we are only want to rescale the y axis, we will select g.y. Make sure to select their parent, #mainGraph svg g, first before selecting them, in order to append the extra line grid in the right parent. For updating the line grids and labels, we are going to use update, enter and exit selections. Since we are append new line grid and label, we need to set all the attributes that are needed. On the other hand, we only update attributes that need to be changes in update and exit selections. Lastly, don’t forget about updating the dots data too.

Step 9: Summary

This tutorial is written based on my personal understanding on D3. I am still learning. Any feedback are welcome.

Updates

15 Jul 2011

Ricardo mentions transitioning scales example, Date Ticks by mbostock.

Cooking: Spicy Pumpkin Risotto

Tonight dinner is spicy pumpkin risotto. The recipe was from the italian gardener. our favourite food blog, King Arthur Flour – Baking Banter.

Gallery

References

Javascript: 101 Week 5 Track 2

On week 5 track 2, we continue study chapter 12 and 13 on Eloquent Javascript. Both chapters are related to document-object model and browser events.

Reflection

  1. What factors make accessing nodes according to their structural order (by using the ‘firstChild’ and ‘lastChild’ properties, for example) an inefficient and potentially unreliable approach? What alternatives are available?
    We have been accessing nodes by going through a series of firstChild and lastChild properties. This can work, but it is verbose and easy to break ― if we add another node at the start of our document, document.body.firstChild no longer refers to the h1 element, and code which assumes it does will go wrong. On top of that, some browsers will add text-nodes for things like spaces and newlines between tags, while others do not, so that the exact layout of the DOM tree can vary. An alternative to this is to give elements that you need to have access to an id attribute. We can get the element by calling getElementById function.
  2. How does CSS play a role in JavaScript’s interactive possibilities with the DOM? What are a few of the techniques related to this?
    Closely tied to HTML and the document-object model is the topic of style-sheets. It is a big topic, and I will not discuss it entirely, but some understanding of style-sheets is necessary for a lot of interesting JavaScript techniques, so we will go over the basics.
    In old-fashioned HTML, the only way to change the appearance of elements in a document was to give them extra attributes or to wrap them in extra tags, such as center to center them horizontally, or font to change the font style or colour. Most of the time, this meant that if you wanted the paragraphs or the tables in your document to look a certain way, you had to add a bunch of attributes and tags to every single one of them. This quickly adds a lot of noise to such documents, and makes them very painful to write or change by hand.
    Style-sheets are a way to make statements like ‘in this document, all paragraphs use the Comic Sans font, and are purple, and all tables have a thick green border’. You specify them once, at the top of the document or in a separate file, and they affect the whole document.
    Classes are a concept related to styles. If you have different kinds of paragraphs, ugly ones and nice ones for example, setting the style for all p elements is not what you want, so classes can be used to distinguish between them. And this is also the meaning of the className property which was briefly mentioned for the setNodeAttribute function. The style attribute can be used to add a piece of style directly to an element.
    There is much more to styles: Some styles are inherited by child nodes from parent nodes, and interfere with each other in complex and interesting ways, but for the purpose of DOM programming, the most important thing to know is that each DOM node has a style property, which can be used to manipulate the style of that node, and that there are a few kinds of styles that can be used to make nodes do extraordinary things.
  3. Identify some of the browser events JavaScript is capable of interpreting. What might the practical applications be?
    There are many browser events that JavaScript is capable of interpreting. First one that we can think of straight away is button click. This does in fact work across browsers, but it has an important drawback ― you can only attach one handler to an element. Most of the time, one is enough, but there are cases, especially when a program has to be able to work together with other programs (which might also be adding handlers), that this is annoying.

Homework

  • Write a function asHTML which, when given a DOM node, produces a string representing the HTML text for that node and its children. You may ignore attributes, just show nodes as . The escapeHTML function from chapter 10 is available to properly escape the content of text nodes. Hint: Recursion!
  • Write the convenient function removeElement which removes the DOM node it is given as an argument from its parent node.
  • Write a function called registerEventHandler to wrap the incompatibilities of these two models. It takes three arguments: first a DOM node that the handler should be attached to, then the name of the event type, such as “click” or “keypress“, and finally the handler function. To determine which method should be called, look for the methods themselves ― if the DOM node has a method called attachEvent, you may assume that this is the correct method. Note that this is much preferable to directly checking whether the browser is Internet Explorer. If a new browser arrives which uses Internet Explorer’s model, or Internet Explorer suddenly switches to the standard model, the code will still work. Both are rather unlikely, of course, but doing something in a smart way never hurts.
  • Create an HTML page and some Javascript to allow a user to add n numbers. First display a simple form with the question “How many numbers do you want to add (max is 10)”. The user should enter a number between 2 to 10 and click on a button in the form. You have to validate the answer. If the user has entered a correct value (between 2 and 10), then dynamically create a form with n text input fields and an “Add” button. Once the form is displayed the user will enter n numbers in the n input fields and when they click on the “Add” button, dynamically create a span element with the result. You will have to perform validation on the values entered in the input fields to make sure that they are numbers. If they are not numbers, display an alert dialogue with an error message.

References

Javascript: 101 Week 5 Track 1

On this week, we continue watching ‘An Incovenient API – The Theory of the DOM’ part 2 as below by Douglas Crockford


Douglas Crockford: "Theory of the DOM" (2 of 3) @ Yahoo! Video

Reflection

  1. Why is it better to use either trickling or bubbling of events? Why not just give the event to the node on which it was invoked?
    Trickling is an event capturing pattern which provides compatibility with the Netscape 4 model. Avoid it. On the other hand, bubbling means that the event is given to the target, and then its parent, and then its parent, and so on until the event is cancelled. Bubble is very useful specially we have a very large set of objects. Supposedly we have 100 draggable objects. We could attach 100 sets of event handlers to those objects. Or we could attach one set of event handlers to the container of the 100 objects.
  2. Can you think of one situation where you would want to prevent the browser from submitting a form after a user has clicked on the ‘submit’ button? How would you achieve this?
    Cancel bubbling is to keep the parent nodes from seeing the event.Cancel bubbling is not enough. After all the bubbling is finished, the browser will then do what it’s normally does. An event handler as below can prevent a browser action associated with the event (such as submitting a form).

Homework

Since track 1 is the same as track 2 in week 5, the answer for the homework will be in track 2 post.

References

Javascript: 101 Week 4

Since track 2 is the subset for track 1 in week 4, so we combine them both to this post. On this week, beside watching ‘An Incovenient API – The Theory of the DOM’ as below by Douglas Crockford, we also need to reading these articles below on understanding on DOM.


Douglas Crockford: "Theory of the DOM " (1 of 3) @ Yahoo! Video

Reflection

  1. There were two key innovations to the original (fetch-parse-flow-paint) linear workflow that the Mosaic browser used to render web pages. One allowed for a perception of faster rendering, and the other allowed for us to use AJAX. Explain both?
    This article, The Inconvenient Truth on website performance , do explain clearly.
  2. What are the roles of ‘name’ and ‘id’ attributes in HTML tags? What is an appropriate use of both?
    From bytes’s forum, Douglas Crockford said “name is used to annotate POST data in forms. id is used to identify elements for scripting and styling. Some browsers used them interchangeably, which is confusing.”
  3. Which pointers does each node in the DOM tree typically have?
    From Aticle: Traversing the DOM, each node in the DOM tree typically point to ‘parent’, ‘child’ and ‘sibling’.
  4. Given a node object from a DOM tree, how do we determine if it is a text node or a regular node?
    From Aticle: Traversing the DOM, a text node’s nodeName property is “#text”.

Homework

  • Download the source for the web page ‘http://www.useit.com/about/nographics.html’. In the source page itself, write a Javascript function which counts the number of text nodes in the document and shows the count in an alert dialogue. You can choose how you want to trigger the function (through a button click, link click, or any other event).
  • Change the example above so that instead of displaying the count in an alert dialogue, it is displayed in a span tag in the HTML page itself.
  • Add a link besides the button, such that when the link is click, it changes the style on the span tag to make it’s contents bold.

References

Javascript: 101 Week 3 Track 2

On track 2 week 3, we are continuing reading Eloquent Javascript ebook on chapter 6: Functional Programming and JavaScript code style.

Reflection

  1. Why is it helpful to break a programs logic into functions?
    As programs get bigger, it helps us easy to understand the program logic.
  2. In JavaScript, functions are first class objects. What does it mean to be a first class object?
    From Wikipedia, first class object is an entity that can be passed as a parameter, returned from a subroutine, or assigned into a variable.
  3. What are anonymous functions, and where would you use them?
    In computing, an anonymous functions is a function (or a subroutine) defined, and possibly called, without being bound to an identifier. They are convenient to pass as an argument to a higher-order function and are ubiquitous in languages with first-class functions.
  4. Why is it important to follow good code style in your code?
    From this article, good code style can help in reducing the brittleness of programs.

Homework

Week 3 homework for track 2 are the same as track 1. Here will be the answers that is recommended by JSLint for exercises 6.1 to 6.5. Track 1 will be showing the original answer for exercises 6.1 to 6.5.

  • Ex. 6.1: Write a function countZeroes, which takes an array of numbers as its argument and returns the amount of zeroes that occur in it. Use reduce. Then, write the higher-order function count, which takes an array and a test function as arguments, and returns the amount of elements in the array for which the test function returned true. Re-implement countZeroes using this function.
  • Ex. 6.2: Write a function processParagraph that, when given a paragraph string as its argument, checks whether this paragraph is a header. If it is, it strips of the ‘%’ characters and counts their number. Then, it returns an object with two properties, content, which contains the text inside the paragraph, and type, which contains the tag that this paragraph must be wrapped in, “p” for regular paragraphs, “h1″ for headers with one ‘%’, and “hX” for headers with X ‘%’ characters. Remember that strings have a charAt method that can be used to look at a specific character inside them.
  • Ex. 6.3: Build a function splitParagraph which, given a paragraph string, returns an array of paragraph fragments. Think of a good way to represent the fragments. The method indexOf, which searches for a character or sub-string in a string and returns its position, or -1 if not found, will probably be useful in some way here. This is a tricky algorithm, and there are many not-quite-correct or way-too-long ways to describe it. If you run into problems, just think about it for a minute. Try to write inner functions that perform the smaller actions that make up the algorithm.
  • Ex. 6.4: Looking back at the example HTML document if necessary, write an image function which, when given the location of an image file, will create an img HTML element.
  • Ex. 6.5: Write a function renderFragment, and use that to implement another function renderParagraph, which takes a paragraph object (with the footnotes already filtered out), and produces the correct HTML element (which might be a paragraph or a header, depending on the type property of the paragraph object). This function might come in useful for rendering the footnote references:
    function footnote(number) {
    return tag(“sup”, [link("#footnote" + number,
    String(number))]);
    }
    A sup tag will show its content as ‘superscript’, which means it will be smaller and a little higher than other text. The target of the link will be something like "#footnote1". Links that contain a ‘#’ character refer to ‘anchors’ within a page, and in this case we will use them to make it so that clicking on the footnote link will take the reader to the bottom of the page, where the footnotes live. The tag to render emphasized fragments with is em, and normal text can be rendered without any extra tags.

References

Javascript: 101 Week 3 Track 1

On track 1 week 3, we are continuing understanding JavaScript through Douglas Crockford’ video 3 and video 4 as below.


Douglas Crockford: "The JavaScript Programming Language"/3 of 4 @ Yahoo! Video


Douglas Crockford: "The JavaScript Programming Language"/4 of 4 @ Yahoo! Video

Reflection

  1. In Javascript, functions are first class objects. What does it mean to be a first class object?
    From Wikipedia, first class object is an entity that can be passed as a parameter, returned from a subroutine, or assigned into a variable.
  2. Functions and variables share the same namespace. What does this mean and what important implication does this have?
    We can have same name for both function and variable. They are the same in JavaScript.
  3. Douglas Crockford equates JavaScript functions with Lambdas, and also mentions that they are a secure construct. Can you do some research and reflect on what he means by ‘secure construct’?
    From the presentation, he said it can constraint the scope.
  4. Can you explain the concept of a closure.
    Here got very clear explanation on closure. A “closure” is an expression (typically a function) that can have free variables together with an environment that binds those variables (that “closes” the expression).
  5. What is the difference between a function and a method?
    A function in an object is called a method.
  6. In Javascript there is no implicit type checking of arguments passed to functions. This could lead to bugs if programmers are not careful about what they pass to functions. If you create a function, how would you protect it from well meaning but careless programmers?
    One way, we can use function’s arguments property to verify on each arguments. When a function is invoked, in addition to its parameters, it also gets a special parameter called arguments. It contains all of the arguments from the invocation. It is an array-like object. We can use arguments.length to verify the total of arguments are passed.
  7. JavaScript functions have implicit access to something called this. this points to different things depending on how the function was created. Can you explain why we need this, and what it represents in different type of functions.
    From the presentation, this is an extra parameter. Its value depends on the calling form. It also gives methods access to their objects and it is bound at invocation time. If the invocation form is function, functionObject(arguments), then this is the global object. If the invocation form is method, thisObject.methodName(arguments), then this is the object. Finally, if the invocation form is constructor, new functionObject(arguments), this is the new object.
  8. Why doesn’t JavaScript have a cast operator?
    The cast operator converts one type into another. In C, its general form is (type) variable. Because it uses other way, for example using parseInt() function to convert string type to integer type.
  9. What is reflection and why is it easy in JavaScript (you may need to do research to answer this question)?
    Reflection is the process by which a computer program can observe and modify its own structure and behavior at runtime. Every object is a separate namespace. Use an object to organize your variables and functions.

Homework

Week 3 homework for track 1 are the same as track 2. Here will be exercises 6.1 to 6.5. Track 2 will be showing the answers that is recommended by JSLint.

  • Ex. 6.1: Write a function countZeroes, which takes an array of numbers as its argument and returns the amount of zeroes that occur in it. Use reduce. Then, write the higher-order function count, which takes an array and a test function as arguments, and returns the amount of elements in the array for which the test function returned true. Re-implement countZeroes using this function.
  • Ex. 6.2: Write a function processParagraph that, when given a paragraph string as its argument, checks whether this paragraph is a header. If it is, it strips of the ‘%’ characters and counts their number. Then, it returns an object with two properties, content, which contains the text inside the paragraph, and type, which contains the tag that this paragraph must be wrapped in, “p” for regular paragraphs, “h1″ for headers with one ‘%’, and “hX” for headers with X ‘%’ characters. Remember that strings have a charAt method that can be used to look at a specific character inside them.
  • Ex. 6.3: Build a function splitParagraph which, given a paragraph string, returns an array of paragraph fragments. Think of a good way to represent the fragments. The method indexOf, which searches for a character or sub-string in a string and returns its position, or -1 if not found, will probably be useful in some way here. This is a tricky algorithm, and there are many not-quite-correct or way-too-long ways to describe it. If you run into problems, just think about it for a minute. Try to write inner functions that perform the smaller actions that make up the algorithm.
  • Ex. 6.4: Looking back at the example HTML document if necessary, write an image function which, when given the location of an image file, will create an img HTML element.
  • Ex. 6.5: Write a function renderFragment, and use that to implement another function renderParagraph, which takes a paragraph object (with the footnotes already filtered out), and produces the correct HTML element (which might be a paragraph or a header, depending on the type property of the paragraph object). This function might come in useful for rendering the footnote references:
    function footnote(number) {
    return tag(“sup”, [link("#footnote" + number,
    String(number))]);
    }
    A sup tag will show its content as ‘superscript’, which means it will be smaller and a little higher than other text. The target of the link will be something like "#footnote1". Links that contain a ‘#’ character refer to ‘anchors’ within a page, and in this case we will use them to make it so that clicking on the footnote link will take the reader to the bottom of the page, where the footnotes live. The tag to render emphasized fragments with is em, and normal text can be rendered without any extra tags.

References

« Older Posts