Archive for the ‘Máy tính’ Category

Failure is not an option, it is a requirement

July 4th, 2012 No comments

Of course that statement on it’s own can obviously be shown to be fallacy. When you consider the context of continuous improvement, learning or generally advancing our own capabilities and understanding, though, this statement can be quit liberating. Why? Because without failure, you are not learning anything.

Let’s say you are faced with a problem, a challenge, or a need that you are trying to fulfill. If your first attempt and creating a solution is successful you have learned nothing. You already knew how to provide the solution. it only took some thinking to analyze the situation and apply your existing knowledge. If, however, you stretch yourself as far as you can, put every last effort that you currently have into the solution and employ all of your existing knowledge, capabilities and resources but you still fail the first time, fail again and fail some more before finding a solution, then you are learning. You are stepping outside of your own knowledge and capabilities, learning new things and gaining new insight and experience that leads to new solutions for situations that you did not know how to previously solve.

Consider any endeavor to learn, from this light. Whether it’s adopting a new process or methodology such as an agile process or lean toolkit, using a new tool or technology, contributing to an open source project, or learning how to ride a bicycle – having the correct mentality, that failure is required, will undoubtedly help you succeed.

Mike Rother said it quite well in his book, Toyota Kata (p.138-139), when faced with people who are merely capitulating because they were told to do so, or because they want to prove that some change or new way of doing things won’t work:

Eventually it dawned on me how to deal with this question. Now, when arms fold up and people say, “Let’s see if this will work,” I say, “I can save you the time. We already know it probably won’t work. Despite our best efforts to plan this, we know that within a short time there will be ‘charred and glowing pieces’ lying around. We just don’t know in advance when, where, or why it will fail.”

Think about the last time you delivered any fragment of functionality to a customer or customer representative for feedback. Did you expect that they would be 100% satisfied and would accept it as is? Not if you were asking for feedback. When the customer responds with changes or updates that they would like, you have effectively failed. Hopefully you have failed within a very short cycle, though, and are able to incorporate the feedback of the customer into the next delivery or demonstration.

They key is not learning from mistakes and failures. The key is failing fast, failing cheap, and responding to those failures in a timely manner so that you can learn quickly and still reach your objectives. Failure is critical to success and learning, and short feedback cycles are critical to the effective use of failure as a learning tool.

Derick Bailey


Different points of Java and C#

October 3rd, 2011 No comments

Recently I’ve started discovering C# in .NET world. As my background is Java and its world, I encounter various difficulties in learning C#. It’s not a bad idea for me to take note different points of Java and C#, that would not only let me validate my understanding well, but also help those who are in a situation like me can quickly stick to the core of both worlds.

I make comparison based on:

  • Java 6
  • C# 4.0

Points of difference are written:

  • in pairs
  • one by one
  • in no order

Mostly I will collect materials from Internet for explanation and demonstration. Feel free to comment or drop me an email if I wrote something wrong. Thank you!

1. Class variables


Member variables in a class are called fields.

public class Bicycle {

    // the Bicycle class has three fields
    public int cadence;
    public int gear;
    public int speed;


A class can have fields and properties. They look similar from outside but from inside, a field has no logic while a property may have logic.

public class Stock


decimal currentPrice;  // The private “backing” field

public decimal CurrentPrice    // The public property


get { return currentPrice; }

set { currentPrice = value; }



2. Access modifiers


Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier


private Y N N N

The first data column indicates whether the class itself has access to the member defined by the access level. As you can see, a class always has access to its own members. The second column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member. The third column indicates whether subclasses of the class “declared outside this package” have access to the member. The fourth column indicates whether all classes have access to the member.


The type or member can be accessed by any other code in the same assembly or another assembly that references it.

The type or member can be accessed only by code in the same class or struct.

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

3. Constant variables


A final variable can only be initialized once, either via an initializer or an assignment statement. It need not be initialized at the point of declaration: this is called a ‘blank final’ variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared: otherwise, a compile-time error occurs in both cases.

public class Sphere {
    public static final double PI = 3.141592653589793;  // a constant
    public final double radius;  // a blank final constant
    public Sphere() {
    radius = 1.0;


Constants are declared with the const modifier. Only the C# built-in types (excluding System.Object) may be declared as const. For a list of the built-in types, see Built-In Types Table (C# Reference). User-defined types, including classes, structs, and arrays, cannot be const. Use the readonly modifier to create a class, struct, or array that is initialized one time at runtime (for example in a constructor) and thereafter cannot be changed.

Constants must be initialized as they are declared.

class Calendar1
    public const int months = 12;

When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

class Age
        readonly int _year;
        Age(int year)
            _year = year;
        void ChangeYear()
            //_year = 1967; // Compile error if uncommented.

3. Static Constructors


Static constructor is not really supported by Java, but you can use static initialization block instead. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

static {

    // whatever code is needed for initialization goes here

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.


A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:

  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.


class Apple
 static Apple()
 Console.WriteLine("Apple type is initialized.");

 public Apple()

When you instantiate above class, output will be:

Apple type is initialized.


4. Packages and Namespaces


Classes and interfaces are organized into packages, which in fact are directories on operating system. Package declaration must be first and before any other statement (except comment) in a Java source file.

To declare a package, use keyword package.

//in the file
package graphics;
public class Rectangle {
   . . .

Then, put the source file in a directory whose name reflects the name of the package to which the type belongs:



Classes are organized virtually into namespaces, no directory is required like that of Java. A class can have many namespace declarations.

To declare a namespace, use keyword namespace.

namespace N1     // N1
    class C1      // N1.C1
        class C2   // N1.C1.C2
    namespace N2  // N1.N2
        class C2   // N1.N2.C2

The following code:

namespace N1.N2
   class A {}
   class B {}

is semantically equivalent to

namespace N1
   namespace N2
      class A {}
      class B {}

5. Order of declaration


// declare package first

package A

// then import something

import B


A traditional order is (more):

// use something

using B

// then declare namespace

namespace A

Howeve the correct order is (more):

// declare namespace

namespace A

// then use something

using B

String literal vs String object in Java

September 7th, 2011 No comments

If you’re a Java developer, you might have ever been in trouble distinguishing String literal and String object. I myself have had the trouble too. So I make a search on the internet for this topic and collect good articles for everyone to memorize.

Full topic:


what is difference between String str = new String(“abc”); and String str = “abc”;

Good answer

When you do this:

String str = "abc";

You are calling the intern() method on String. This method references an internal pool of ‘String’ objects. If the String you called intern() on already resides in the pool, then a reference to that String is assigned to str. If not, then the new String is placed in the pool, and a reference to it is then assigned to str.

Given the following code:

String str = "abc";
String str2 = "abc";
boolean identity = str == str2;

When you check for object identity by doing == (you are literally asking – do these two references point to the same object?), you get true.

However, you don’t need to intern() Strings. You can force the creation on a new Object on the Heap by doing this:

String str = new String("abc");
String str2 = new String("abc");
boolean identity = str == str2;

In this instance, str and str2 are references to different Objects, neither of which have been interned so that when you test for Object identity using ==, you will get false.

In terms of good coding practice – do not use == to check for String equality, use .equals() instead.

Method description of java.lang.String


public String intern()
Returns a canonical representation for the string object.A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned. String literals are defined in §3.10.5 of the Java Language Specification

a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

CSF firewall for your CPanel VPS and FTP issue

August 22nd, 2011 No comments

When you have a CPanel VPS, you may also want to have a way to manage firewall easily and effectively. I found that CSF is a good option here. It is free and has UI integration with Web Host Manager. Its features and performance are not so bad. It is recommended in many VPS forums.

Installation is straightforward: download the package, execute install command.

However after you secure your VPS with CSF, you may encounter following issue when you ftp to the server:

Command:    PASV
Response:    227 Entering Passive Mode (69,73,143,39,137,1)
Command:    MLSD
Error:    Connection timed out
Error:    Failed to retrieve directory listing

That means, your FTP client opens data connection in passive mode and tries to MLSD (list content of a given directory) on server, but it fails. The issue lies between CSF configuration and FTP server configuration: passive ports configured in FTP server are not opened in CSF firewall. So one way to fix is:

1. identify passive ports configured in FTP server

– check your /etc/pure-ftpd.conf (if you use Pure-FTP)

– find this line:

# Port range for passive connections replies. – for firewalling.
PassivePortRange 35000 36000

2. add these ports in CSF at TCP_IN entry

– restart CSF and test FTP again.

This solution can be derived from the point 13 in CSF readme content:

13. A note about FTP Connection Issues

It is important when using an SPI firewall to ensure FTP client applications
are configured to use Passive (PASV) mode connections to the server.

On servers running Monolithic kernels (e.g. VPS Virtuozzo/OpenVZ and custom
built kernels) ip_conntrack and ip_conntrack_ftp iptables kernel modules may
not be available or fully functional. If this happens, FTP passive mode (PASV)
won’t work. In such circumstances you will have to open a hole in your firewall
and configure the FTP server to use that same hole.

For example, with pure-ftpd you could add the port range 30000:35000 to TCP_IN
and add the following line to /etc/pure-ftpd.conf and then restart pure-ftpd:
PassivePortRange 30000 35000

For example, with proftpd you could add the port range 30000:35000 to TCP_IN
and add the following line to /etc/proftpd.conf and then restart proftpd:
PassivePorts 30000 35000

FTP over SSL/TLS will usually fail when using an SPI firewall. This is because
of the way the FTP protocol established a connection between client and server.
iptables fails to establish a related connection when using FTP over SSL
because the FTP control connection is encrypted and so cannot track the
relationship between the connection and the allocation of an ephemeral port.

If you need to use FTP over SSL, you will have to open up a passive port block
in both csf and your FTP server configuration (see above).

Perversely, this makes your firewall less secure, while trying to make FTP
connections more secure.

Hope this solution works for you.

Please share with me your feedback or another solution. Many thanks!

Some quick steps to secure your VPS

August 10th, 2011 1 comment

This article describes standard Security Best Practices for Linux servers and provides basic instructions for securing a virtual private server against most common attacks.

User Accounts

  • Observe the Password Security recommendations for your root account
  • Create a user account for any trusted users who should have access to the VPS – do not share your root login
  • Eliminate unnecessary user accounts and disable shell access for daemons
    1. Run cat /etc/passwd and identify unnecessary user accounts
    2. Remove unnecessary users with userdel <username>
    3. Disable interactive logins for daemon accounts by specifying /bin/false for the user’s shell

SSH Configuration

  • Change the SSH port
    1. Open your sshd_config file for editing
    2. Locate the Port directive
    3. Change the default SSH port – any port above the 1-1024 range is preferable (check theInternet Assigned Numbers Authority site for unassigned port numbers if you want to ensure no conflicts are encountered)
    4. Restart SSH and connect to your VPS using the new port
  • Restrict SSH users and hosts in sshd_config
    • Use the PermitRootLogin no directive to disable root logins over SSH (if you have created a user account for yourself and plan to use su to administer your VPS)
    • Use the AllowUsers directive to specify which user accounts may be used to log in
  • Additional Recommendations
    • Limit SSH access to trusted IPs only (iptables example):
      1. -A INPUT -p tcp -m tcp --dport XXXX --source x.x.x.x -j ACCEPT (where XXXX is the port SSH is listening on and x.x.x.x is the trusted source IP)
      2. Prior to closing the established SSH session, test the SSH access rule: Create an additional SSH session from the trusted source IP. Test a non-trusted IP as well. If the non-trusted IP is unable to connect and the trusted IP is allowed, the rule is working as intended.
    • Use the DenyHosts script to block malicious users (if restricting access to a single trusted IP is not practical)
    • Configure your VPS to use public key authentication instead of password authentication

Additional Linux Security Resources

See the Security category for security guides on the VPSLink Wiki.

Linux Distribution Security

If you have an active interest in securing your VPS, you should follow up with recommendations specific to your distribution and recommendations for any daemons or applications which you use.

Security Applications

Applications geared toward security are an invaluable asset – consider installing an auditing tool and an intrusion detection system to automate monitoring and test your system’s configuration.

  • Bastille – Security auditing and configuration tool
  • Samhain – File integrity checker and intrusion detection system
  • SentryTools – A host-level security suite used to protect against port scans, automate log file auditing, and detect suspicious login activity


Categories: Máy tính Tags: , , , ,

Instant web proxy on a Linux VPS server

August 10th, 2011 2 comments

If you are unable to access a website because your computer is behind a firewall, with a VPS server you can make an instant SOCKS proxy for you to bypass the firewall in few minutes. Such a useful guide that I’ve found out from the net. Enjoy!


There are many situations which call for a higher level of security and privacy than the immediate network provides: having a SOCKS proxy at your disposal is often the quickest and most convenient solution.

If you have ever checked POP3 e-mail, accessed an account on an FTP server, or encountered a website which was blocked by the local network administrator, this guide will explain how to protect your passwords over the local network and maintain access to the sites you frequent, regardless of local restrictions.

This guide will explain how to configure your VPS to act as a proxy server and configure your Linux or Windows client software to use the SOCKS proxy.

Note: The VPSLink Acceptable Use Policy expressly prohibits the operation of a public proxy. Please limit user accounts to trusted users to ensure the security of your VPS.

VPS Configuration

No special configuration is required – your VPS will be running an SSH daemon by default.

Note: We strongly recommend that you review our Linux security best practices to change the port which SSH is listening on as a security precaution.

Client Configuration


  • Ensure that the port which will act as your local proxy port is not presently active or listening for connections
  • Despite common port restrictions, most networks will allow traffic over port 80 (HTTP) and port 443 (SSL) – because encrypted traffic is expected over port 443, this port makes an ideal local proxy port
  • Client software (web browsers, e-mail clients, chat clients) must be configured to use the SOCKS proxy and perform DNS lookups over the SOCKS proxy (if you wish to keep the domains which you browse private)


  1. Open a local console
  2. Enter the following command:



    • VPS_SSH_PORT – The port on your VPS which is listening for SSH connections
    • LOCAL_PROXY_PORT – The port on your local machine which will accept SOCKS connections
    • USERNAME – The username for an account with SSH login capabilities on your VPS
    • VPS_IP_ADDRESS – The IP address of your VPS
  3. Log in with your user account password
  4. Open your client applications and enable proxy use on your local SOCKS proxy port


  1. Open the PuTTY SSH client
  2. Complete the following fields under the Session category:
    • Host Name (or IP Address) – Enter the IP address for your VPS
    • Port – Enter the port which the SSH daemon is listening on
  3. Navigate to the ConnectionSSHTunnels category
  4. Complete the following fields under the Tunnels category:
    • Source port – Enter the port on your local machine which will accept SOCKS connections
    • Destination – Enter the IP address for your VPS
    • Select the Dynamic radio button
  5. Click the Add button to add the source port association
  6. If you would like to save your SOCKS proxy settings:
    1. Navigate back to the Session category
    2. Enter a label for your settings in the Saved Sessions field
    3. Click the Save button
  7. Click the Open button to initiate a connection with your VPS
  8. Log in with your username and password
  9. Open your client applications and enable proxy use on your local SOCKS proxy port

Application Configuration

Keep in mind that you will need to have an open an SSH connection to your VPS in order to use application SOCKS proxy settings. If your local machine is no longer listening for connections or your connection to your VPS is interrupted, SOCKS-enabled applications will report that no connection exists.


The FireFox browser can easily be configured to make use of a SOCKS proxy – additionally, the FoxyProxy FireFox extension allows for domain-specific proxying rules.

Use the following steps to modify your FireFox settings to route all browsing over your proxy:

  1. Open FireFox and select the Tools option from the menu bar
  2. Switch to the Advanced section and select the Network tab, then click the Settings button
  3. Select the Manual proxy configuration option
  4. Enter localhost in the SOCKS Host field and your LOCAL_PROXY_PORT in the correspondingPort field
  5. Browse to to confirm that the IP address for your VPS appears


Javascript Data Type Conversion

June 14th, 2011 No comments

Today I discover a pretty good page discussing data type conversion in javascript. I would like to include the content of the page here for my own reference. Thanks to author of the content, Jim Ley.


Javascript (ECMAScript) is a loosely typed language. That does not mean that it has no data types just that the value of a variable or a Javascript object property does not need to have a particular type of value assigned to it, or that it should always hold the same type of value. Javascript also freely type-converts values into a type suitable for (or required by) the context of their use.

Javascript being loosely typed and willing to type-convert still does not save the programmer from needing to think about the actual type of values that they are dealing with. A very common error in browser scripting, for example, is to read the value property of a form control into which the user is expected to type a number and then add that value to another number. Because the value properties of form controls are strings (even if the character sequence they contain represents a number) the attempt to add that string to a value, even if that value happens to be a number, results in the second value being type-converted into a string and concatenated to the end of the first string value from the from control.

That problem arises from the dual nature of the + operator used for both numeric addition and string concatenation. With which the nature of the operation performed is determined by the context, where only if both operands are numbers to start with will the + operator perform addition. Otherwise it converts all of its operands to strings and does concatenation.

The following discussion is illustrated with Javascript generated tables of values resulting from the conversion operations. The headers of those tables display the values as represented in the Javascript source code used rather than their internal representation. So, for example 123e-2 as a number was the character sequence typed into the source code, the interpreter reads that and generates the number value 1.23 from it for internal use. The various values used for the tests have been chosen to illustrate aspects of type converting, those aspects may not apply to all of the tables presented. However, all of the test values are included in all of the tables (except where no type converting occurs) for full comparison. The bodies of the tables list the results of the various type conversion operations.

If you are accepting/using this page’s CSS style suggestions the type of the values at various stages is illustrated by the colour of the text used. The following key shows those type/colour relationships, they are derived from the string values returned by the typeof operator (which returns "object" for the null type when in reality null is distinct from objects).


The boolean values of results also have a coloured background to highlight true or false.

Converting to Boolean

When evaluating the expression of an if statement the Javascript interpreter will type-convert the result of that expression to boolean in order to make its decision. Also various operators internally type-convert their operands to boolean in order to determine what action to take. These include the logical operators like AND (&&), OR (||) and NOT (!). The NOT operator type-converts its operand to boolean and if that value is boolean true it returns false and if false it returns true. As the result of a NOT operation is a boolean value that is the inverse of the type-converted true-ness of its operand, two NOT operations together will return a boolean value that is equivalent to the result of type-converting the operand to boolean:-

var boolValue = !!x;

That technique has been used to generate the following tables.

An alternative method of generating a boolean value that represents the type-converted true-ness of a value is to pass that value to the Boolean constructor called as a function:-

var boolValue = Boolean(x);
Double NOT (!!col) : Numeric Values.
-1.6 -0 +0 1 1.6 8 16 16.8 123e-2 -Infinity +Infinity NaN
!!col true false false true true true true true true true true false

When numbers are converted to boolean, zero becomes false and all other numbers are true. With the excepting of the special numeric value NaN (Not a Number) which is used when another type is converted to a number but that conversion does not result in a meaningful number. NaN is always false. The values of positive and negative infinity, while not finite numbers, are non-zero numeric values and always type-convert to boolean true.

Double NOT (!!col) : String Values.
“-1.6” “0” “1” “1.6” “8” “16” “16.8” “123e-2” “010”
“-010” “-0x10” “xx”
!!col false true true true true true true true true true true true true true true

Type conversion rules are even simpler for string to boolean conversion as all non-empty strings always become true and empty strings become false.

Double NOT (!!col) : Other Values
undefined null true false new Object() function(){
!!col false false true false true true

For the other types, undefined and null are converted to false, boolean values are not converted and objects and functions are always true.

This is the most valuable aspect of type-converting to boolean as it allows a script to distinguish between properties in an environment that may be undefined or may refer to an object. Treating an undefined (or null) value as if it was an object will produce errors. So when there is a doubt (as there usually is where web browsers are concerned) then code can avoid generating errors by wrapping the code that wants to access an object in an if test. Supplying the suspect reference to the object as the expression. The expression will be type converted to boolean and result in false if the object does not exist and true if it does.

    scrollX = document.documentElement.scrollLeft;

The double NOT operation also allows the setting of boolean flags that can be used to indicate the presence of various objects:-

var hasDocEl = !!document.documentElement;
    scrollX = document.documentElement.scrollLeft;

Converting to String

As mentioned above, type conversion to a string most often results from the action of the + operator whenever one of its operators in not a number. The easiest way of getting the string that results from type-conversion is to concatenate a value to an empty string. That technique has been used to generate the following tables.

An alternative method of converting a value into a string is to pass it as an argument to the String constructor called as a function:-

var stringValue = String(x);
type-convert to string (“” + col) : Numeric Values.
-1.6 -0 +0 1 1.6 8 16 16.8 123e-2 -Infinity +Infinity NaN
“” + col -1.6 0 0 1 1.6 8 16 16.8 1.23 -Infinity Infinity NaN

Notice that the number generated from the source code 123e-2 has resulted in the string "1.23" because that is the string representation of the internal number created from the source code. However, Javascript’s internal number representations take the form of IEEE double precision floating point numbers and that means that they cannot represent all numbers with precision. The results of mathematical operations may only produce close approximations and when they are converted to strings the string represents the approximation and may be unexpected and undesirable. It is often necessary to use custom functions to generate string representations of numbers in an acceptable format, the type-conversion mechanism is rarely suited to generating numeric output intended for presentation.

type-convert to string (“” + col) : Other Values.
undefined null true false new Object() function(){
“” + col undefined null true false [object Object]

When objects or functions are type-converted to strings their toString method is called. These default to Object.prototype.toString and Function.prototype.toString but may be overloaded with a function assigned to a “toString” property of the object/function. Type-converting a function to a string does not necessarily result in the function’s source code. The behaviour of Function.prototype.toString is implementation depended and varies quite a lot, as do the results from “host objects” and methods (the objects and methods provided by the environment, such as DOM elements).

Converting to Number

Converting values to numbers, especially strings to numbers, is an extremely common requirement and many methods can be used. Any mathematical operator except the concatenation/addition operator will force type-conversion. So conversion of a string to a number might entail performing a mathematical operation on the string representation of the number that would not affect the resulting number, such as subtracting zero or multiplying by one.

var numValue = stringValue - 0;
/* or */
var numValue = stringValue * 1;
/* or */
var numValue = stringValue / 1;

However, the unary + operator also type-converts its operand to a number and because it does not do any additional mathematical operations it is the fastest method for type-converting a string into a number.

Incidentally, the unary - (minus) operator also type-converts its operand (if necessary) in addition to subsequently negating its value.

var numValue = (+stringValue);

/* The preceding unary + expression has been parenthesised. That is
   unnecessary but is often felt to make the code easier to comprehend
   and make it clear which operations are being applied. Especially
   avoiding confusion with pre and post increment and addition
   operations. Compare:-

var n = anyNumVar++ + +stringVar + ++anotherNumVar;

  - with - 

var n = (anyNumVar++) + (+stringVar) + (++anotherNumVar);
                  ^^     ^              ^^
     (post increment) + (unary plus) + (pre increment)

While unary + is the fastest method for converting a string to a number a final method is available that uses the Javascript type-conversion algorithms. The Number constructor can be called with the string value as its argument and its return value is a number representing the result of the type-conversion.

var numValue = Number(stringValue);

The Number constructor is the slowest of the type-converting methods but when speed is not an overriding consideration its use does produce the clearest source code.

The following tables show the results of type-conversion to a number using the unary + operator. Though all of the preceding alternative method produce the same results as they all use exactly the same algorithm to do the conversion.

type-convert to number (+col) : String Values.
“-1.6” “0” “1” “1.6” “8” “16” “16.8” “123e-2” “010”
“-010” “-0x10” “xx”
+col 0 -1.6 0 1 1.6 8 16 16.8 1.23 10 16 255 -10 NaN NaN

The important considerations when converting strings to numbers with the type-converting methods is the results from strings that do not represent numbers. The empty string is converted into the number zero, depending on the application this can be harmless or disastrous, but it is important to be aware that it is going to happen. In other contexts strings that follow the Javascript format for octal number (leading zero) can be problematic but type conversion treats them as base 10 anyway. However, strings that follow the format for hexadecimal numbers (leading 0x or 0X) are read as hexadecimal. Strings that cannot be read as a number type-convert to NaN, which can be tested for with the isNaN function. Strings representing numbers in an exponential format ("123e-2") are understood along with leading minus signs.

type-convert to number (+col) : Other Values.
undefined null true false new Object() function(){
+col NaN 0 1 0 NaN NaN

Objects and functions always type-convert to NaN numbers, as do undefined values but it is worth noting that null type-converts to zero. Probably because it is being type-converted to boolean first and then to number and, as is clear from the boolean results above, null would become boolean false which would then become numeric zero. There is almost no need to type convert these types of values into numbers. How they convert is only really relevant to a consideration of the accidental result of converting a value that is expected to be a string but actually turns out to be one of these (and/or performing an mathematical operation with one of these as an operand).

Parsing to Number

An alternative method of converting a string into a number is to use one of the global functions designed to parse a string and return a number. The parseFloat function accepts a string argument and returns a floating point number resulting from parsing that string. Non-string arguments are first type-converted to a string as described above.

The string parsing functions read the string character by character until they encounter a character that cannot be part of the number, at which point they stop and return a number based on the characters that they have seen that can be part of the number. This feature of their action can be usefully exploited, for example, given a string representing a CSS length value such as "34.5em" parseFloat would be able to ignore the "em" because those characters cannot be combined with the preceding set to produce a valid number. The returned number would be 34.5, the numeric part of the CSS string stripped of its units.


parseFloat(col) : String Values.
“-1.6” “0” “1” “1.6” “8” “16” “16.8” “123e-2” “010”
“-010” “-0x10” “xx”
parseFloat(col) NaN -1.6 0 1 1.6 8 16 16.8 1.23 10 0 0 -10 0 NaN

With parseFloat empty strings return NaN along with strings that cannot be subject to numeric interpretation. The exponential format is understood and the leading zero in the octal format does not hinder the string’s interpretation as a decimal number. Hexadecimal strings are interpreted as the number zero because the following "x" cannot be interpreted as part of a number so parsing stops after the leading zero.

parseFloat(col) : Other Values.
undefined null true false new Object() function(){
parseFloat(col) NaN NaN NaN NaN NaN NaN

Non-string values are first converted into a string that is employed by parseFloat. As that type-conversion to a string would not normally result in a string that could be interpreted as a number the result is NaN. Objects and functions may have custom toString methods that may return strings that could be interpreted as numbers but that would be an unusual requirement.


The parseInt function works in a similar way to parseFloat except that it is trying to interpret its string argument into an integer and as a result recognises fewer character as possible candidates to be part of that number.

parseInt is occasionally used as a means of turning a floating point number into an integer. It is very ill suited to that task because if its argument is of numeric type it will first be converted into a string and then parsed as a number, very inefficient. This can produce very wrong results with numbers such as 2e-200, for which the next smaller integer is zero, but with which parseInt returns 2. Also, because of the number format used by javascript, numbers are often represented by near approximations. So, for example, 1/2 + 1/3 + 1/6 = 0.9999999999999999, which isn’t quite one and parseInt would return zero if asked to act on the result of the operation.

For rounding numbers to integers one of Math.round, Math.ceil and Math.floor are preferable, and for a desired result that can be expressed as a 32 bit signed integer the bitwise operation described below might also suit.

parseInt(col) : Numeric Values.
-1.6 -0 +0 1 1.6 8 16 16.8 123e-2 -Infinity +Infinity NaN
parseInt(col) -1 0 0 1 1 8 16 16 1 NaN NaN NaN

When it is acting on number the effect of the initial type-conversion of the argument to a string is evident in the results. Note that the value 123e-2 is internally the number 1.23 and that type converts into the string "1.23", so that entry in the table above might look odd but it is correct.

parseInt(col) : String Values.
“-1.6” “0” “1” “1.6” “8” “16” “16.8” “123e-2” “010”
“-010” “-0x10” “xx”
parseInt(col) NaN -1 0 1 1 8 16 16 123 8 16 255 -8 -16 NaN

Strings in octal and hexadecimal number formats do represent integers and parseInt is capable of interpreting them in accordance with the rules for Javascript source code, even when they have leading minus signs.

parseInt(col) : Other Values.
undefined null true false new Object() function(){
parseInt(col) NaN NaN NaN NaN NaN NaN

As parseInt type-converts its non-string arguments to strings it always produces the same results for boolean, null, undefined, object and function arguments as parseFloat (assuming objects and functions do not have custom toString methods).

parseInt with a radix argument

It is rarely desirable to allow parseInt to deduce the base in which the number is represented from the string as leading zeros are rarely intended to indicate data in octal format (particularly with user input). To deal with this problem parseInt recognises a second, radix, argument that can be used to specify the base in which the string is to be interpreted. Specifying a second argument of 10 causes parseInt to interpret the strings as only base 10.

parseInt(col, 10) : String Values.
“-1.6” “0” “1” “1.6” “8” “16” “16.8” “123e-2” “010”
“-010” “-0x10” “xx”
parseInt(col, 10) NaN -1 0 1 1 8 16 16 123 10 0 0 -10 0 NaN

The string in octal format is now interpreted as base 10 and the hexadecimal strings can now only be zero as parsing has to stop when the "x" is encountered.

Number bases 2 to 36 can be used with parseInt. The following is base 16.

parseInt(col, 16) : String Values.
“-1.6” “0” “1” “1.6” “8” “16” “16.8” “123e-2” “010”
“-010” “-0x10” “xx”
parseInt(col, 16) NaN -1 0 1 1 8 22 22 4670 16 16 255 -16 -16 NaN

The hexadecimal 0x format is recognised again with the base 16 interpretation.

Finally base 3:-

parseInt(col, 3) : Numeric Values.
-1.6 -0 +0 1 1.6 8 16 16.8 123e-2 -Infinity +Infinity NaN
parseInt(col, 3) -1 0 0 1 1 NaN 1 1 1 NaN NaN NaN

The consequences of the type-converting of numeric arguments to strings is evident again. The number 8 is coming out as NaN because the "8" character cannot be interpreted as base 3, leaving an empty sequence of acceptable characters and producing the same result as an empty string.

parseInt(col, 3) : String Values.
“-1.6” “0” “1” “1.6” “8” “16” “16.8” “123e-2” “010”
“-010” “-0x10” “xx”
parseInt(col, 3) NaN -1 0 1 1 NaN 1 1 5 3 0 0 -3 0 NaN


ToInt32 is an internal function only available to the Javascript implementation and cannot be called directly from scripts in the way that parseInt can. It is a bit unusual to mention it in connection with converting Javascript values to numbers but it can be used in a limited set of circumstances. The bitwise operators such as bitwise OR (|) and bitwise AND (&) operate on numbers so they type-convert their operands to numbers. However, they also only operate on 32 bit signed integers so given the (possibly type-converted) numeric value they call the internal ToInt32 function with that number as its argument and use the returned value as their operand. That returned value is always a 32 bit signed integer.

The effect can be like parseInt combined with type-converting to numbers. While the result is limited in range to 32 bits, it is always numeric and never NaN, or ± Infinity.

As with using mathematical operators in operations that have no effect on the value of any resulting number it is possible to perform a bitwise operation that will not affect the value returned from the call to ToInt32. The tables below were generated using a bitwise OR zero operation.

ToInt32 (col|0) : Numeric Values.
-1.6 -0 +0 1 1.6 8 16 16.8 123e-2 -Infinity +Infinity NaN
col|0 -1 0 0 1 1 8 16 16 1 0 0 0

NaN and ±Infinity become zero and floating point values are truncated to integers.

ToInt32 (col|0) : String Values.
“-1.6” “0” “1” “1.6” “8” “16” “16.8” “123e-2” “010”
“-010” “-0x10” “xx”
col|0 0 -1 0 1 1 8 16 16 1 10 16 255 -10 0 0

String values that would type-convert to NaN are returned as zero from ToInt32.

ToInt32 (col|0) : Other Values.
undefined null true false new Object() function(){
col|0 0 0 1 0 0 0

Even undefined, objects and functions are converted to zero value numbers by this operation. Note though that boolean true is converted to the number 1.

Converting User Input

Most of the mechanisms for getting input from the user, <input type="text"> and prompt for example, provide their results in the form of strings. If the user is expected to input a number they still might enter anything (at the least they may just make a typo). If the string needs to be converted into a number for later operations one of the methods mentioned above can be chosen based on what best suits the nature of the input expected but some of the results generated with erroneous input may be difficult to detect and handle.

Prior to converting a string to a number it may be advantageous to use a Regular Expression to test the contents of the string to ensure that they conform to an acceptable format. That would serve to eliminate some of the string values that may otherwise suffer from the quirks of the string to number converting processes when applied to unexpected string values.

Regular expression examples

/^\d+$/                 //All-digit
/^\s*[-+]?\d+\s*$/      //Unbroken Signed integer & spaces
/^\d{1,5}$/             //1 to 5 digits
/^\d+\.\d\d$/           //Money
/^\d+(\.\d{2})$/        //Money
/^\d{1,3}(,\d\d\d)*\.\d\d$/  //comma-separated money - 12,432.57

       // optional comma-separated money - 12,432.57 or 12432.57

Modify $PATH for root account Ubuntu / Linux Mint

March 6th, 2011 No comments

The way to modify $PATH on Ubuntu / Linux Mint is a bit different from that of other Linux distros. When you have tried several ways to modify $PATH but to no avail, give yourself a chance to try this and see =).

To modify all users’ $PATH, edit this file: /etc/profile

To modify root’s $PATH, edit this file: /etc/environment

Screen is frozen when watching youtube clips in fullscreen mode (Ubuntu, Linux Mint)

February 28th, 2011 No comments

Try these commands:

sudo mkdir /etc/adobe
echo "OverrideGPUValidation=true" >~/mms.cfg
sudo mv ~/mms.cfg /etc/adobe/

Restart the browser.

If that doesn’t work, then right-click the flash video, select “Settings”, then untick the option “Enable hardware acceleration”.


Facebook Architecture

January 17th, 2011 No comments

If you ever wish to learn about Facebook architecture, see this presentation.

Facebook: Science and the Social Graph

Presented by Aditya Agarwal on Mar 25, 2009 Length 01:01:43

Categories: Máy tính Tags: