F#: Introduction

Adapt from

[1] http://www.tryfsharp.org/Tutorials.aspx

[2] http://www.tryfsharp.org/Tutorials/QuickLanguageOverview/Section0.html

[3] http://www.tryfsharp.org/Tutorials/QuickLanguageOverview/Section1.html

[4] http://www.tryfsharp.org/Tutorials/QuickLanguageOverview/Section2.html

[5] http://www.tryfsharp.org/Tutorials/QuickLanguageOverview/Section3.html

[6] http://msdn.microsoft.com/en-us/library/dd233154.aspx


The Rise of F#

F# is a programming language that provides support for functional programming in addition to traditional object-oriented and imperative (procedural) programming. F# is a first-class member of the .NET Framework languages and retains a strong resemblance to the ML family of functional languages [6].

Features

  • fully type checked at compile time (eliminating many kinds of run-time error)
  • a compiled language (which delivers good performance)
  • combines its functional nature with the imperative paradigm, with the object-oriented paradigm, and with the concurrent paradigm
  • integrates with the .NET Framework and other implementations of the CLI (Common Language Infrastructure) (asynchronous and parallel class libraries is supported)

Example – First program

let x = 7
let y = 6
let z = (float 6.0)

let s = "life the universe and everything"
printfn "The answer to %A is %A" s (x*y)

Key takeaway

  1. A
    let

    statement is not an assignment statement but is used to associate a name with a value. In functional programming, such an association is called a binding. The new binding simply hides the old one if the binding already exists.

  2. There is no declarations. The name
    x

    does represent an

    int

    value but it does not need to be declared as

    int

    because the type can be easily deduced from its associated value

    7

    . Whenever datatypes can be inferred from the code, they can be omitted. The complete form is shown in let

    z = (float 6.0)

    .

  3. printfn

    is a built-in function for outputting lines of text; it is modelled after the

    printf

    function of C. The

    printfn

    function recognizes many of the same formatting codes as

    printf

    in C; however

    <strong>%A</strong>

    is an extra one which works with any datatype.

  4. Function calls are written in this format -- the function name, followed by the arguments which are separated by white space. (No comma and brackets)

Example – Association statement and assignment statement

[Incorrect-Error: Duplicate definition of value 'n']

let n = 2
let n = n + 1
printfn "n = %A" n

[Incorrect-Give "n = 2"]

let n = 2
n = n + 1
printfn "n = %A" n

[Incorrect-Give "n = 2"]

let mutable n = 2
n = n + 1
printfn "n = %A" n

[Correct-Give "n = 3"]

let mutable n = 2
n <- n + 1
printfn "n = %A" n

The associatation statement binds n to a value, which is not mutable. However, mutable variable is required to do the assignment of value. If an assignment statement is really needed, F# does provide it by a special operator (the left arrow

&lt;-

).

Example – Indentation and broken a line of code

[Version 1]

let AVeryLongVariableName = 1
let AnotherLongVariableName = 2
let variableNumberOne = AVeryLongVariableName + AnotherLongVariableName

[Version 2]

let variableNumberOne =

AVeryLongVariableName +

AnotherLongVariableName

[Version 3]

let variableNumberOne = (AVeryLongVariableName

+ AnotherLongVariableName)

[Version 4]

let variableNumberOne =

AVeryLongVariableName + AnotherLongVariableName

All four versions are identical. Indentation matters in F# code. It is used instead of a statement terminator (such as the semicolon in C, C# or Java code) and instead of statement grouping symbols (such as the left and right brace characters in C, C# or Java) to indicate where a F# language construct begins and ends.

發表於 F# | 已標籤 | 發表迴響

Adding GSL Library on Eclipse with the help from MinGW

  1. Download MinGW installer from the official website http://sourceforge.net/projects/mingw/files/Automated%20MinGW%20Installer/mingw-get-inst/
  2. Install MinGW with the latest version
  3. Follow the instruction on the guide Getting Started http://mingw.org/wiki/Getting_Started so as to download and set up the gcc and g++ compiler
  4. Download and unzip GSL library source from the offical website ftp://ftp.gnu.org/gnu/gsl/
  5. Copy the GSL source folder to the MinGW installation path, for example, C:\MinGW\msys\1.0\home, which is equivalent to /home in the GNU system
  6. Read the INSTALL in GSL source folder. If you want to have a quick set up, read the instruction under "The simplest way to compile this package is"
  7. Write the code which invokes function in GSL by following the example of GSL in the offical web site

    http://www.gnu.org/software/gsl/manual/html_node/Compiling-and-Linking.html

    http://www.gnu.org/software/gsl/manual/html_node/Linking-programs-with-the-library.html

  8. Download Eclipse IDE for C/C++ Developers (includes Incubating components) from the offical website. http://www.eclipse.org/downloads/packages/eclipse-ide-cc-developers-includes-incubating-components/indigor
  9. Unzip and open the eclipse.exe inside.
  10. Follow the instruction to do the initial set up for the IDE.
  11. After that, start a new project and choose MinGW as the toolchain for the project. Then click finish.
  12. Right click your project in the Project Explorer then click Properties.
  13. We need to construct the commands as shown in the GSL example with the steps. below.
  14. Under C/C++ Build –> Settings –> GCC C++ Compiler –> Includes, add the following paths: (supposing your MinGW installation path is C:\MinGW)
    "C:\MinGW\include"
    "C:\MinGW\msys\1.0\local\include"
    "C:\MinGW\msys\1.0\local\include\gsl"
    "C:\MinGW\msys\1.0\include"
    "C:\MinGW\lib\gcc\mingw32\4.5.2\include"
  15. Repeat the previous step under C/C++ Build –> Settings –> GCC C Compiler –> Includes
  16. In MinGW C++ Linker –> Libraries –> Libraries (-l), add the followings:
    gsl
    gslcblas
    m
  17. In MinGW C++ Linker –> Libraries –> Library search path (-L), add the foolowing paths:
    "C:\MinGW\msys\1.0\lib"
    "C:\MinGW\msys\1.0\local\lib"
  18. Create a new C++ file and copy the example of GSL to the editor.
  19. Click Run Configuration, add a new configuration under C/C++ Application and press OK
  20. Rebuild the whole project to see the results
    發表於 C++ | 已標籤 , , , | 發表迴響

    Debugging in Android - 001

    Observation

    Cannot see new views(e.g. RadioGroup) after the textbox(i.e. edittext) while running my app with the following XML layout.

    Code

    <?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="5dp">
       
        <EditText
            android:id="@+id/edittext"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
       
       
        <RadioGroup android:id="@+id/people_radioGroup"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content">
          <RadioButton android:id="@+id/radio_red"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Red" />
          <RadioButton android:id="@+id/radio_blue"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Blue" />
        </RadioGroup>  
       
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Country" />
        <AutoCompleteTextView android:id="@+id/autocomplete_country"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"/>

    </LinearLayout>

    More Details

    API Level: 8

    Orientation: Vertical

    Solution

    The line

    android:orientation="horizontal"

    is incorrect.

    It should be

    android:orientation="vertical"

    for veritcal orientation.

    發表於 Android Apps Dev Competition, Programming | 已標籤 , , | 發表迴響

    Android Activity Part 1

    Adopt from

    [1] http://developer.android.com/guide/topics/fundamentals.html


    What is Activity?

    From our daily experience, we need to perform some activities before we can finish a job. For instance, a dinner, you need to go to the supermarket, choose the ingredients, bring them home and cook them all. An activity composes of activities and the basic unit is the action.

    In Android, the idea of activity restricts on a task completed on the screen. An activity represents a single screen with a user interface. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. Although the activities work together to form a cohesive user experience in the email application, each one is independent of the others. As such, a different application can start any one of these activities (if the email application allows it). For example, a camera application can start the activity in the email application that composes new mail, in order for the user to share a picture. [1]

    How to implement Activities?

     

    In simplest case, your activity needs to inherit from Activity. To create your activity, you need to override to onCreate method. Then, you need to put your view (technically, pass the reference of your view) in to the activity as the definition highlighted above.

    public class MyActivity extends Activity {
        public void onCreate(Bundle savedInstanceState) {        
            super.onCreate(savedInstanceState);
            TextView textview = new TextView(this); // Create the view object within the activity class
            textview.setText("This is the a tab");
            setContentView(textview);
        }
    }

    public class MyActivity extends Activity {
        public void onCreate(Bundle savedInstanceState) {        
            super.onCreate(savedInstanceState);
            TextView textview = (TextView)findViewById(R.id.textview); // Get the reference from project resource (the layout is defined in XML)
            textview.setText("This is the a tab");
            setContentView(textview);
        }
    }

    發表於 Android Apps Dev Competition, Programming | 已標籤 , | 發表迴響

    SVG and Canvas

    Reference

    [1] http://www.sitepoint.com/canvas-vs-svg-how-to-choose/


    Below is the HTML5 code with SVG and Canvas:

    <!DOCTYPE html>
    <html>
      <!--
      Source:
    http://msdn.microsoft.com/en-us/library/gg589494(v=VS.85).aspx
      -->

      <script type="text/javascript">
        //This function is called on page load.
        function drawOnCanvas()
        {
            // Get the canvas element
            var canvas = document.getElementById("uIElementJS");
            // Make sure you got it before doing anything.
            if (canvas.getContext)
            {
                // Specify 2d canvas type.
                var ctx = canvas.getContext("2d");
                // Draw gold UI element.
                // Start the path.
                // Define the fill color in RGB for gold.
                ctx.fillStyle = "rgb(255, 215, 0)";
                // Draw the circle using an arc.
                ctx.arc(100, 100, 50, 0, 2*Math.PI, true);
                //Fill the circle.
                ctx.fill();
            }
        }
        // Call when you click on the canvas
        function clickOnUI()
        {
            alert("You clicked the canvas UI element.");
        }
        function clickOnSVG()
        {
            alert("You clicked the SVG UI element.");
        }
      </script>
    </head> 

    <body onload="drawOnCanvas()">
        <h1>
          Canvas User Interface
        </h1>
        <!-- Create the Canvas element. -->
        <canvas id="uIElementJS" width="200" height="200" onclick="clickOnUI()">
        </canvas>
        <p>
          Click on the gold circular user interface element.
        </p>
        <h1>
          SVG User Interface
        </h1>
        <!-- Create the SVG pane. -->
        <svg height="200" width="200">
          <!-- Create the circle. -->
          <circle cx="100" cy="100" r="50" fill="gold" id="uIElementSVG" onclick="clickOnSVG();"
          />
        </svg>
        <p>
          Click on the gold circular user interface element.
        </p>
        <p>
          When should I use Canvas and SVG?
        </p>
      </body>

    </html>

     

    We can see that SVG can draw the circle without caring the drawing procedure.

    It's time to use…

    If the graphic is SVG Canvas
    static (e.g. draw once) **** *
    geometric shape **** *
    irregular shape ** ***
    interactive (e.g. in animation) **** **
    transformation-required **** ***
    needed to be downloaded quickly ***** ***
    cross-browser * (with the help of plugin) **** (with the help of libraries)
    pixel-based (e.g. image processing) * ****

     

    The more the number if stars (*), the higher the preference.

    發表於 HTML5 | 已標籤 , , | 發表迴響

    Python: "if __name__ == '__main__'"

    [1] http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm

    [2] http://docs.python.org/library/__main__.html?highlight=__main__#module-__main__


    In Python, the interpreter's main program excutes a module within a scope. The module executes with commands read either from standard input, from a script file, or from an interactive prompt[2]. This script can be executed independently or called as an module[1]. Suppose we have

    program0.py

    def useAsModule():

        print "useAsModule"

    def useAsStandaloneProgram():

        print "useAsStandaloneProgram is executed"

    if __name__ == "__main__":

        useAsStandaloneProgram()

    As module

    program1.py

    import program0

    useAsModule()

    As standalone program

    In console of Python,

    $ python program0.py

    發表於 Script Languages | 已標籤 | 發表迴響

    Ruby: Symbol

    Adopt from

    [1] http://ruby-doc.org/core/classes/Symbol.html

    [2] http://glu.ttono.us/articles/2005/08/19/understanding-ruby-symbols

    [3] http://www.troubleshooters.com/codecorn/ruby/symbols.htm

    [4] http://www.randomhacks.net/articles/2007/01/20/13-ways-of-looking-at-a-ruby-symbol


    What is Symbol?

    Symbol objects represent names and some strings inside the Ruby interpreter. Symbols are immutable. Their value remains constant during the entire session of the program. They never appear on the left side of an assignment [3]. In fact, [4] has proposed 13 ways to look at symbol.

    How to create a symbol?

    They are generated using the:name and :"string" literals syntax, and by the various to_sym methods.

    When should we use Symbol?

    Symbol allow programmers to make use of the memory efficiently. This is essential when you reuse the same string for a large number of times. One common scenario is in Ruby on Rails, which uses symbols in routes and links [2]. Rails defines actions within controllers to do things within the framework before rendering a web page, so a link in Rails may look like:

    link_to("View Article", :controller => "articles",

    發表於 Programming | 已標籤 | 發表迴響

    SOA & Web Services: Basic

    Adopt from

    [1] http://en.wikipedia.org/wiki/Service-oriented_architecture

    [2] http://msdn.microsoft.com/en-us/library/byxd99hx(v=VS.90).aspx

    [3] http://msdn.microsoft.com/en-us/library/ms996486.aspx


    Developers may prefer object oriented programming nowadays. Instead of installing a piece of assemblies on the local computer, developers want to access the functionalilities hosted in the web directly. Here comes the idea of web service and service-oriented architecture (SOA).

    SOA is a flexible set of design principles used during the phases of systems development and integration in computing. A system based on a SOA will package functionality as a suite of interoperable services that can be used within multiple, separate systems from several business domains [1]. In SOA, server will be responsible for the complex computation, and the clients only needs a simple software(e.g. the browser) for the output. In .net framework, we need to do the following in the simplest case:

    1. Use the WebMethod attribute in the server side.

    public class Service1 : System.Web.Services.WebService
    {
        [System.Web.Services.WebMethod(BufferResponse=false)]
        public int Multiple(int a, int b)
        {
           //implementation code
           return (a*b);
        }
    }

    2. Compile the server code into assembly in WSDL

    WSDL describes the complete contract for application communication [3].

    3. Client downloads the assembly and imports the assembly into the project.

    All networking codes will be generated automatically in the client side system for .Net and Java. This produces the interface using the proxy object, which has a concrete object in the remote server, for the developer to call.

    發表於 C# | 已標籤 , , , | 發表迴響

    SVG and Canvas

    Adopt from

    [1] https://www.svgopen.org/2009/papers/54-SVG_vs_Canvas_on_Trivial_Drawing_Application/

    [2] http://msdn.microsoft.com/en-us/library/gg589488(v=VS.85).aspx

    [3] http://en.wikipedia.org/wiki/Retained_mode


    Introduction

    SVG's retained mode graphic display system allows you to create all the map details in HTML-like tags in the body and modify them in script by changing shape attributes. [2] By using a "retained mode" approach, client calls do not directly cause actual rendering, but instead update an internal model (typically a list of objects) which is maintained within the library's data space. This allows the library to optimize when actual rendering takes place along with the processing of related objects. [3] It is supported since IE9.

    Canvas requires more code to accomplish the same task, because the shapes must be drawn in script and the body only contains the basic Canvas tag. [2] It is supported by most of the browsers.

    SVG is strong and robust with built-in shape handling, while Canvas is fast and efficient for pixel manipulation. [1]

    Both standards allow accessing their data through JavaScript, but there are no shared interfaces to utilize co-operation. SVG gives its data as (serialized) XML, while Canvas as base64-coded PNG. [1]

    Combining two techniques [1]

    Canvas to SVG

    1. Including Canvas as foreignObject into SVG
    2. Import Canvas bitmap data as image element into SVG using Canvas.toDataURL

    SVG to Canvas

    1. Implement full SVG parsing (e.g. CakeJS)
    2. Render in Canvas or do SVG conversion to bitmap server-side (e.g. ImageMagick, Batik or Inkscape)
    發表於 HTML5 | 已標籤 , , | 發表迴響

    Free Flash IDE

    Adopt from

    http://osflash.org/open_source_flash_projects#ides_and_editors


    AjaxAnimator – Online Simple Flash IDE

    http://antimatter15.com/ajaxanimator/wave/

    FlashDevelop – Advanced Open Source ActionScript Editor

    http://www.flashdevelop.org/wikidocs/index.php?title=Main_Page

    Salasaga – Making eLearning material

    http://www.salasaga.org/

    MiniBuilder – Another Lightweight ActionScript 3 Editor

    http://code.google.com/p/minibuilder/

    發表於 Flash, Programming | 已標籤 , | 發表迴響