Thursday, December 10, 2009

Support Google Chrome

Google chrome by far ..

Thursday, April 2, 2009

Arm Cortex M3 If-then (IT) instruction

The if then instructions allow up to four succeeding instructions (called an IT block) to be conditionally executed. They are in following formats:

IT[x] [cond]
IT[x][y] [cond]
IT[x][y][z> [cond]

where:

[x] specifies the execution condition for the second instruction
[y] specifies the execution condition for the third instruction
[z] specifies the execution condition for the fourth instruction
[cond] Specifies the base condition of the instruction block; the first instruction following IT executes if is true

Each of [x], [y] and [z] can be either T (then) or E (else), which refers to the base condition , whereas uses traditional syntax such as EQ, NE, GT, or the like.

Here is an example of IT use:

if (R0 equal R1) then
{
R3 = R4 + R5
R3 = R3 / 2
}
else
{
R3 = R6 + R7
R3 = R3 / 2
}

This can be written as:

CMP R0, R1 ; Compare R0 and R1
ITTEE EQ ; If R0 equal R1, Then-Then-Else-Else
ADDEQ R3, R4, R5 ; Add if equal
ASREQ R3, R3, #1 ; Arithmetic shift right if equal
ADDNE R3, R3, #1 ; Add if not equal
ASRNE R3, R3, #1 ; Arithmetic shift right if not equal

Some IT instruction:

ITT
ITE
ITTT
ITEE
ITTE
ITTTT
ITEEE
ITTET

Reference: The Definitive Guide to the ARM Cortex-M3 by Joseph Yiu

Special Control Register that controls the ARM Cortex M3 Operation Mode

ARM Cortex M3, when running in thread mode, has two privilege modes: "privileged" and "user". When thread mode is in "user" mode, it can not access to system control space and some instructions that access to special registers such as MSR are restricted.

Special control register is used to define the privilege level and the stack pointer selection. This register has 2 bits, bit zero and bit one.

CONTROL[0] : Stack status
1 = Alternate stack is used
0 = Default stack (Main stack pointer) is used

CONTROL[1] : Privilege status
1 = User state in thread mode
0 = Privileged in thread mode

Control bit 1 is writable only when the core is in thread mode and privileged.
Control bit 0 is writable only in a privileged state. Once it enters the user state, the only way to switch back to privileged is to trigger an interrupt and change this bit in priveleged hander mode.

PrivilegedUser
When running an exceptionHandler Mode
When running main programThread ModeThread Mode


Reference: The Definitive Guide to the ARM Cortex-M3 by Joseph Yiu pg 36

Saturday, July 19, 2008

How to enable tab key navigation in a Mac OS X dialog box

In Mac OS X Leopard, by default navigation between dialog box buttons with tab key is disabled. It is really hard to find configuration.

Here is the screen shot of what I am talking about. By default, blue circle surrounding the "Show Web Page" button is not visible and you can't move between buttons by pressing on "tab" button on the keyboard.



To enable this feature, all you need to do is set "Full keyboard access:" to "All controls" (on the bottom)

Sunday, July 13, 2008

How to reverse a linked list (3 different ways)

Purpose: Purpose of this article is to show how to reverse a linked list.

Introduction: There are couple of ways to reverse a linked list. One of them requires a pointer knowledge and one of them is pretty straight forward. In this article, 3 different ways of reversing a linked list is demonstrated. All the linked list reversing algorithms assume that given linked list is a double linked list.



Technique 1: In this way, a new linked list will be created and all the items of the first linked list will be added to the new linked list in reverse order.

Code:


public void ReverseLinkedList (LinkedList linkedList)
{
// ------------------------------------------------------------
// Create a new linked list and add all items of given
// linked list to the copy linked list in reverse order
// ------------------------------------------------------------

LinkedList copyList = new LinkedList();

// ------------------------------------------------------------
// Start from the latest node
// ------------------------------------------------------------

LinkedListNode start = linkedList.Tail;

// ------------------------------------------------------------
// Traverse until the first node is found
// ------------------------------------------------------------

while (start != null)
{
// ------------------------------------------------------------
// Add item to the new link list
// ------------------------------------------------------------

copyList.Add (start.Item);

start = start.Previous;
}

linkedList = copyList;

// ------------------------------------------------------------
// Thats it!
// ------------------------------------------------------------
}


This way is probably the most inefficient way among 3. Even though objects of each node is not copied to memory, a new link list node is created for each call to “Add” property. A new link list node means at least 3 pointers (Next, Previous, Item) will be created for each item. This way not only wastes memory, but also wastes processing power.


Technique 2: In this way, we will swap linked list node objects (references to the data). Swapping starts from the first node’s object and first node’s object is swapped with last node’s object. Then, second node’s object is swapped with one before the last node’s object.



Assuming we have N nodes in the link list.

Swap : 1st node’s object with Nth node’s object
Swap : 2nd node’s object with (N-1) node’s object
Swap : 3rd node’s object with (N-2) node’s object

After swapping:




Swapping goes on until the middle of the linked list is found.

Code:


public void ReverseLinkedList (LinkedList linkedList)
{

// ------------------------------------------------------------
// Create variables used in the swapping algorithm
// ------------------------------------------------------------

LinkedListNode firstNode; // This node will be the first node in the swapping
LinkedListNode secondNode; // This node will be the second node in the swapping
int numberOfRun; // This variable will be used to determine the number of swapping runs

// ------------------------------------------------------------
// Find the tail of the linked list
// ------------------------------------------------------------

// Assume that our linked list doesn’t have a property to find the tail of it.
// In this case, to find the tail, we need to traverse through each node.
// This variable is used to find the tail of the linked list
LinkedListNode tail = linkedList.Head; // Start from first link list node and go all the way to the end
while (tail.Next != null)
tail = tail.Next;

// ------------------------------------------------------------
// Assign variables
// ------------------------------------------------------------

firstNode = linkedList.Head;
secondNode = tail;
numberOfRun = linkedList.Length / 2;
// Division will always be integer since the numberOfRun variable is an integer

// ------------------------------------------------------------
// Swap node’s objects
// ------------------------------------------------------------

object tempObject; // This will be used in the swapping 2 objects
for (int i=0; i < numberOfRun; i++)
{
// Swap the objects by using a 3rd temporary variable
tempObject = firstNode.Item;
firstNode.Item = secondNode.Item;
secondNode.Item = tempObject;

// Hop to the next node from the beginning and previous node from the end
firstNode = firstNode.Next;
secondNode = secondNode.Previous;
}

// ------------------------------------------------------------
// Thats it!
// ------------------------------------------------------------

}


This way of reversing a linked list is pretty optimized and pretty fast. The only overhead of this algorithm is finding the end of the linked list.

Technique 3: In this way, the head of the linked list will point to the last node of the linked list. Also, each node’s “Next” and “Previous” properties need to be swapped too.

Next(red arrow) and Previous(blue arrow) are swapped




Code:


public void ReverseLinkedList (LinkedList linkedList)
{
LinkedListNode start = linkedList.Head;
LinkedListNode temp = null;

// ------------------------------------------------------------
// Loop through until null node (next node of the latest node) is found
// ------------------------------------------------------------

while (start != null)
{
// ------------------------------------------------------------
// Swap the “Next” and “Previous” node properties
// ------------------------------------------------------------

temp = start.Next;
start.Next = start.Previous;
start.Previous = temp;

// ------------------------------------------------------------
// Head property needs to point to the latest node
// ------------------------------------------------------------

if (start.Previous == null)
{
linkedList.Head = start;
}

// ------------------------------------------------------------
// Move on to the next node (since we just swapped
// “Next” and “Previous”
// “Next” is actually the “Previous”
// ------------------------------------------------------------

start = start.Previous;
}

// ------------------------------------------------------------
// Thats it!
// ------------------------------------------------------------
}


This way of reversing the linked list is performed in a single traverse through the link list. This way is more optimized than the second method. If the reversing requires to keep the link list nodes at their same position. Technique 2 will fail in that case.

Conclusion: Way 1 is the most straight forward and it can be implemented pretty quickly. However it uses lot’s of system resources. Every time a new node is added, a new memory in the heap will be reserved. Way 2 is pretty professional but if link list doesn’t keep track of the tail of it, link list will be traversed twice. In this case, it will be slower than way 3. Way 3 is the most professional and the fastest one.

Sunday, June 8, 2008

How to optimize html pages if your target is slow networks

These days mobile devices are getting very popular. It is really cool to access internet while you are in middle of no where. Unfortunately the network you use to access the internet is your phone companies network and still they are pretty slow.

If you are developing web sites for mobile devices you have to consider their network capabilities. Making couple of changes on your html code can make your users save tremendous amount of time.

I am planning to write more optimization tips but today I will mention about the line breaks to optimize time.

Following is a html code sample:

<span>Your text here!</span>
<span>Another line</span>

Usually, we put a line break to make code clear and easy to read. Even though you don't see the line break, it is a byte too. Actually, in windows environment it is 2 bytes (\r\n). Line breaks are ignored by html.

So, previous code sample is no different than this:

<span>Your text here!</span><span>Another line</span>

I just saved 1 byte (or 2 bytes in windows machine). Client doesn't have to get these bytes.

It might look like a very minor save but if you think that your site is getting 10,000 hits a day, you do the math!

For example, facebook mobile (http://iphone.facebook.com) can optimize their html code. On the other hand, http://google.com/m is pretty optimized by removing line breaks.

Sunday, June 1, 2008

C# Circular Buffer - First in first out (Not thread safe)

I needed a circular buffer for c# and I couldn't find it on the web. I implemented my version and here it is:

Note: There is no head and tail on this buffer. All you can do is write and read forever. Also, this buffer is not thread safe.

using System;
using System.Collections.Generic;
using System.Text;

namespace Utezduyar.IO.CoreCommunicator
{
    /// <summary>
    /// A circular buffer object.
    /// </summary>
    /// <example>
    /// CircularBuffer<byte> buffer = new CircularBuffer<byte>(3);
    /// buffer.Add(0x41);
    /// buffer.Add(0x42);
    /// buffer.Add(0x43);
    /// buffer.Add(0x44);
    /// buffer.Add(0x45);
    /// 
    /// Console.WriteLine("0:" + buffer.Get(0).ToString("X2"));
    /// Console.WriteLine("1:" + buffer.Get(1).ToString("X2"));
    /// Console.WriteLine("2:" + buffer.Get(2).ToString("X2"));
    /// Console.WriteLine("3:" + buffer.Get(3).ToString("X2"));
    /// Console.WriteLine("4:" + buffer.Get(4).ToString("X2"));
    /// 
    /// // Output:
    /// // 0:45
    /// // 1:44
    /// // 2:43
    /// // 3:45
    /// // 4:44
    /// </example>
    public class CircularBuffer<T>
    {
        private T[] buffer; // Buffer
        private int bufferIndex = 0; // Latest index of the buffer

        /// <summary>
        /// Constructor to initialize the buffer
        /// </summary>
        /// <param name="size">Size of the buffer</param>
        public CircularBuffer(int size)
        {
            // Parameter check
            if (size <= 0)
                throw new ArgumentException("Size must be greater than 0");

            // Assing variables
            buffer = new T[size];
        }

        /// <summary>
        /// Default constructor. Initializes a <c>CircularBuffer</c>
        /// that can hold 256 items in it.
        /// </summary>
        public CircularBuffer() : this (256)
        { 
        
        }

        /// <summary>
        /// Returns the size of the buffer
        /// </summary>
        /// <remarks>
        /// This function returns only the size of the buffer.
        /// This function can not be used to determine how 
        /// many bytes are in the buffer.
        /// </remarks>
        public int Length
        {
            get
            {
                return this.buffer.Length;
            }
        }

        /// <summary>
        /// Adds one item to the next available place in the buffer
        /// </summary>
        /// <remarks>
        /// If the buffer is full, it overwrites 
        /// the very first item.
        /// </remarks>
        /// <param name="item">Item to add</param>
        public void Add(T item)
        {
            if (bufferIndex == this.Length)
                bufferIndex = 0;

            buffer[bufferIndex++] = item;
        }

        /// <summary>
        /// Used to retrieve item array from the buffer.
        /// </summary>
        /// <param name="numberOfItems">Number of items needed.</param>
        /// <returns>Array of the item type. The array lenght 
        /// is same as <c>numberOfItems</c>.
        /// </returns>
        public T[] GetItems(int numberOfItems)
        {
            // Check arguments
            if (numberOfItems <= 0)
                throw new ArgumentException("numberOfItems needs to be greater than zero");

            // Create the byte buffer. This byte buffer will be returned
            T[] items = new T[numberOfItems];

            // Get bytes from buffer
            for (int i = 0; i < numberOfItems; i++)
                items[i] = Get(i);

            // Return
            return items;
        }

        /// <summary>
        /// Returns latest byte from buffer
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        /// <example>
        /// CircularBuffer b = new CircularBuffer(10);
        /// b.Add(0x41);
        /// b.Add(0x42);
        /// b.Get(0); // This would be 0x42
        /// b.Get(1); // This would be 0x41
        /// </example>
        public T Get(int index)
        { 
            // Argument check
            if (index < 0)
                throw new ArgumentException("Index must be greater than or equal to zero");

            if (this.Length <= 0)
                throw new ArgumentException
                    (string.Format("Buffer size is {0}. Buffer needs to be greater than 0", this.Length));

            // Algorithm to find the buffer index
            index = index % this.Length;
            if (index < bufferIndex)
                index = bufferIndex - index - 1;
            else
                index = bufferIndex - index - 1 + this.Length;            

            // Return the item
            return buffer[index];
        }
    }
}

Sunday, April 20, 2008

Fletcher Checksum C# Algorithm


protected virtual void CalculateFletcherChecksum(byte[] bytes)
{
   byte c0 = 0, c1 = 0;
   int count = 0;
   for (count = 0; count < bytes.Length; count++)
   {
      c1 += (c0 += bytes[count]);
   }
   bytes[bytes.Length - 2] = (byte)((c0 - c1) & 0xFF);
   bytes[bytes.Length - 1] = (byte)((c1 - 2 * c0) & 0xFF);
}

Friday, March 14, 2008

How to send an SMS with an AT command

at+cmgf=1
OK
>at+cmgs=18583373799
>> Type your message!
+CMGS: 1
OK

First, type "at+cmgf=1" to put the modem into SMS mode.
Then type "at+cmgs=phonenumber" and press enter.
Start writing your message.
When you are done, press "Ctrl+Z" to send the message.

Sunday, November 19, 2006

Sample usage of fetchmail with gmail

You can configure fetchmail to access your @gmail account using pop protocol and to forward the emails to another email address.

To access your @gmail account using pop protocol, first, you have to enable pop support in gmail.
Follow this link if pop access is disabled in your @gmail account:
http://www.google.com/search?q=how+to+enable+pop+in+gmail

From the shell type (Don't include $:)
$: fetchmail -p POP3 -k -v -a --ssl -P 995 --smtpname xxx@xxx.xxx -u xxx@gmail.com pop.gmail.com

It will ask your password. Type your password and your emails will be forwarded to xxx@xxx.xxx address.

Parameter descriptions:
--ssl Gmail needs ssl connection to their mail server.
-P 996 Default pop3 port is 110. Gmail is using different port number and you have to define that port number. Remark: this is capital p.
-p POP3 Specify the protocol to use
-k Keep retrieved messages on the remote server mailserver.
-v Verbose mode. This writes the detailed output of the fetchmail to standard output.
-a Retreive both old and new messages from the mail server.
xxx@xxx.com Email address that emails will be forwarded
xxx@gmail.com Your gmail account.

Output should be like this:

Enter password for [xxx@gmail.com@pop.gmail.com]:
fetchmail: 6.2.5 querying pop.gmail.com (protocol POP3) at Fri 17 Nov 2006 05:03:00 PM PST: poll started
fetchmail: Issuer Organization: Equifax
fetchmail: Unknown Issuer CommonName
fetchmail: Server CommonName: pop.gmail.com
fetchmail: pop.gmail.com key fingerprint: 59:51:61:89:AB:DD:B2:35:94:BB:44:97:A0:39:D5:B4
fetchmail: Warning: server certificate verification: unable to get local issuer certificate
fetchmail: Issuer Organization: Equifax
fetchmail: Unknown Issuer CommonName
fetchmail: Server CommonName: pop.gmail.com
fetchmail: Warning: server certificate verification: certificate not trusted
fetchmail: Issuer Organization: Equifax
fetchmail: Unknown Issuer CommonName
fetchmail: Server CommonName: pop.gmail.com
fetchmail: Warning: server certificate verification: unable to verify the first certificate
fetchmail: POP3< +OK Gpop ready for requests from [XXX.XXX.XXX.XXX] 55pf8639445ugq fetchmail: POP3> CAPA
fetchmail: POP3< +OK Capability list follows fetchmail: POP3<> USER [xxx@gmail.com]
fetchmail: POP3< +OK send PASS fetchmail: POP3> PASS *
fetchmail: POP3< +OK Welcome. fetchmail: POP3> STAT
fetchmail: POP3< +OK 0 0 fetchmail: No mail for [xxx@gmail.com] at pop.gmail.com fetchmail: POP3> QUIT
fetchmail: POP3< +OK Farewell.
fetchmail: 6.2.5 querying pop.gmail.com (protocol POP3) at Fri 17 Nov 2006 05:03:05 PM PST: poll completed
fetchmail: normal termination, status 1

Monday, August 22, 2005

WYSIWYG Progress Circle for .Net Framework (C#)





Would you like to add some visual enhancement to your windows forms application? Do you have processes that take too long? This control is for you.

Basically, it is a progress bar but it is circular. You can fully customize it's appearance. For example, you can change the ring thickness, number of segments, ring color, progress color, interval, etc.

Control can be added to the toolbox and it can be added to controls by just dragging and dropping from toolbox.

It is an open source (C#) project and compiled with .net framework 2.0

this.progressBar1.BackColor = System.Drawing.Color.Transparent;
this.progressBar1.ForeColor = System.Drawing.Color.Gold;
this.progressBar1.Interval = 100;
this.progressBar1.Location = new System.Drawing.Point(235, 90);
this.progressBar1.Name = "progressBar1";
this.progressBar1.RingColor = System.Drawing.Color.White;
this.progressBar1.RingThickness = 30;
this.progressBar1.Size = new System.Drawing.Size(80, 80);
this.progressBar1.Rotate = true;


Click here to download the source code

Sunday, April 17, 2005

Gradient Panel C# Control (Inherits System.Windows.Forms.Panel)

This control enhances System.Windows.Forms.Panel control by adding a gradient display.



It is very simple to use:

this.panel1.BackColor = Color.Red;
this.panel1.GradientColor = Color.Blue;


Click here to download the source code