tag:blogger.com,1999:blog-78612163770331877912024-03-05T09:44:32.219-08:00Let me through... I am a computer scientistYemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.comBlogger25125tag:blogger.com,1999:blog-7861216377033187791.post-39527540608269731062012-07-22T02:05:00.000-07:002012-07-22T02:05:43.107-07:00InterviewQ: Shuffle a deck of cards (52 integers) - Microsoft<br /><br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>///random shuffle of a pack of cards.<br />void shuffle(int arr [], size_t size)<br />{<br /> srand(std::time(NULL));<br /> for(int i = size - 1; size >= 0; --i)<br /> {<br /> int k = rand() % i;<br /> std::swap(arr[i], arr[k]);<br /> }<br />}<br /></code></pre><br /><br />Q: Find if the binary representation of a number is a palindrome.<br />A:<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>bool is_palindrome(unsigned int a)<br />{<br /> unsigned int j = 0;<br /> unsigned int tmp = a;<br /> while(a)<br /> {<br /> j = ( 1 << j ) | (a & 1);<br /> a >>= 1;<br /> }<br /> return j == tmp;<br />}<br /></code></pre><br /><br />Q: Convert a decimal number to its equivalent Roman Numeral.<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>std::string toRoman(int n)<br />{<br /> std::string r;<br /><br /> struct TO_ROMAN {<br /> int num;<br /> const char *str;<br /> } to_roman[] = {<br /> { 1000, "M", },<br /> { 900, "CM", },<br /> { 500, "D", },<br /> { 400, "CD", },<br /> { 100, "C", },<br /> { 90, "XC", },<br /> { 50, "L", },<br /> { 40, "XL", },<br /> { 10, "X", },<br /> { 9, "IX", },<br /> { 5, "V", },<br /> { 4, "IV", },<br /> { 1, "I", },<br /> };<br /><br /> for (int q = 0; q < sizeof(to_roman) / sizeof(to_roman[0]); ++q)<br /> {<br /> TO_ROMAN *t = &to_roman[q];<br /><br /> while (n >= t->num)<br /> {<br /> n -= t->num;<br /> r += t->str;<br /> }<br /> }<br /><br /> return r;<br />}<br /></code></pre><br /><br />Q: Implement sqrt function. <br />A: Using the NewTon method of approximation<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>///using NewTon's method<br />//make a guess: old_guess<br />//new_guess = (old_guess + value/old_guess) / 2<br />//if old_guess increases, the value/old_guess decreases<br />//however if old_guess increases, the value/old_guess decreases<br /><br />double my_sqrt(double value)<br />{<br /> const static double eps = 0.0005;<br /> double old_guess = value / 2;<br /> double new_guess = 0;<br /> do<br /> {<br /> new_guess = (old_guess + value / old_guess ) / 2;<br /> old_guess = new_guess;<br /> double d = abs(new_guess * new_guess - value);<br /> if( d < eps)<br /> d = d;<br /> else<br /> d = d;<br /> }<br /> while( abs(new_guess * new_guess - value) > eps);<br /><br /> return new_guess;<br />}<br /></code></pre><br /><br />Q: Reverse words in a string.<br />A: <br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>void reverse_words(char * ptr)<br />{<br /> size_t size = strlen( ptr );<br /> //reverse all characters first<br /> reverse_chars(ptr, 0, size - 1);<br /><br /> int word_start = 0;<br /> int word_end = 0;<br /> char* tmp = ptr;<br /> while(*tmp)<br /> {<br /> word_start = word_end; //or eat up spaces <br /> while(*tmp && *tmp != ' ') //assuming white space separator<br /> {<br /> word_end++;<br /> ++tmp;<br /> }<br /> //reverse each word. Do not use space.<br /> reverse_chars(ptr, word_start, word_end - 1);<br /> word_end++; //skip space. Assuming just one space.<br /> ++tmp;<br /> }<br />}<br /></code></pre><br /><br />Q: Amazon - Implement an algorithm to generate the prime numbers in the range 1 - 101<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>void generate_primes()<br />{<br /> const static int N = 101;<br /> int numbers [ N ] = {0};<br /><br /> for(int i = 2; i <= N / 2; ++i)<br /> for(int j = 2; j <= N / i; ++j)<br /> numbers[ i * j ] = 1;<br /><br /> for(int i = 2; i < N; ++i)<br /> {<br /> if(!numbers[ i ])<br /> std::cout << i << "\n";<br /> }<br /> std::cout << std::endl;<br /><br />}<br /></code></pre><br /><br />Q: Find if a string a is a substring of another string b.<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>bool is_substr(const char* a, const char* b)<br />{<br /> size_t size_a = strlen( a );<br /> size_t size_b = strlen( b );<br /> <br /> int j = 0, i = 0;<br /> for( i = 0, j = 0; i < size_a, j < size_b; ++i, ++j)<br /> {<br /> if(a[ i ] == b[ j ]) //matching. Keep going<br /> continue;<br /><br /> i = i - j; //return i to the next character after the prev match<br /> j = -1; //reset j = -1, it'll become zero on loop increment<br /> <br /> }<br /> return j == size_b;<br />}<br /></code></pre><br /><br />Q: Google - implement a memcpy function.<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>void* my_memcpy(void * dst, const void* src, int size)<br />{<br /> char* dst_ptr = (char*)dst;<br /> const char* src_ptr = (char*) src;<br /> <br /> while(size--)<br /> *dst_ptr = *src_ptr;<br /> <br /> return dst_ptr;<br />}<br /></code></pre><br /><br />Q: Given a number (say, 7251), write a code to give the number of digits it has (i.e. 4 for 7251).<br /><br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>int countDigits(int n)<br />{<br /> int count = 0;<br /> do<br /> {<br /> ++count;<br /> n /= 10;<br /> }<br /> while (n);<br /><br /> return count;<br />}<br /><br />//second version. Find the dot and remove it from the count<br />int countDigits1(double n)<br />{<br /> std::ostringstream ss;<br /> ss << n;<br /> return ss.str().size();<br /><br />}<br /></code></pre><br /><br /><br />Q: Bloomberg LP: What is a seg fault? Show with code<br /><br />A: Accessing memory that does not belong to your process. See my blog.<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code><br />void foo()<br />{<br /> char* p;<br /> char c;<br /><br /> p = (char*) 0;<br /> c = *p; //generates seg fault<br />}<br /></code></pre><br /><br />Q: Bloomberg - //Bloomberg LP: What does this code do?<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>void bar()<br />{<br /> int *p=0;<br /> double *q=0;<br /> printf("%u %u\n",p,q);<br /> p++;<br /> q++;<br /> printf("%u %u\n",p,q);<br />}<br /></code></pre><br />A: It prints 0 0 4 8. First it initialize both pointers to NULL. Increment both pointers. First is int, increments by 4, sizeof(int), second by 8 (size of double).<br /><br />Q: Amazon. Find out if a tree is a mirror of another tree<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>boolean isMirror(node1,node2){<br />if(node1==null){if(node2==null)return true; else return false;}<br />if(node2==null) return false;<br />if(node1.data!=node2.data)return false;<br />if(isMirror(node1.left,node2.right) && isMirror(node1.right,node2.left)) return true;<br />return false;<br />}<br /></code></pre><br /><br />Q: Write a function that converts an integer into a hex string.<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>std::string getHex(unsigned int num)<br />{<br /> static const char* hex_values = "0123456789ABCDEF";<br /> std::string ret;<br /> int i = 0;<br /> for(int i = 0; num; i++, num >>= 4)<br /> {<br /> ret += hex_values[ num & 0xF ];<br /> }<br /> //reverse string<br /> std::string::size_type end = ret.size() - 1;<br /> for(int i = 0; i < end; ++i, --end)<br /> std::swap(ret[ i ], ret[ end]);<br /> return ret;<br />}<br /></code></pre><br /><br />Q: Implement addition without using any loops and without using +.<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>int add(int p, int q)<br />{<br /> if(q == 0)<br /> return p;<br /> <br /> int k, r;<br /> k = p ^ q; //XOR is called addition modulo 2. <br /> r = p & q; //this is the carry.<br /> return add(k, r<<1);<br />}<br /></code></pre>YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-16745258288414629632009-12-25T14:42:00.000-08:002009-12-25T14:53:06.442-08:00Binding to member variables.When we use boost::bind to bind to a member function, things are pretty easy. You're making a function object of a usually stand-alone or a member function. But when you bind to a member variable of a class, things get a little hazy. When binding to a member variable, usually, you get a member pointer to the type of the member variable. And if you are using this bind in the context of a STL algorithm, then you apply this data member pointer to the passed in argument. This makes absolutely no sense, but see the code below, and it will hopefully make more sense.<br /><br /><pre style="border: 1px dashed rgb(153, 153, 153); padding: 5px; overflow: auto; font-family: Andale Mono,Lucida Console,Monaco,fixed,monospace; color: rgb(0, 0, 0); background-color: rgb(238, 238, 238); font-size: 12px; line-height: 14px; width: 100%;"><code><br />struct entry<br />{<br /> typedef std::pair<int, bool> conn_type;<br /> entry(int i, bool c) : conn_pair(i, c ) { }<br />// bool get_connecting() const { return connecting; }<br /> conn_type conn_pair;<br />};<br /><br />int main()<br />{<br /> std::vector<entry> vec;<br /> vec.push_back(entry(1, false));<br /> vec.push_back(entry(2, false));<br /> vec.push_back(entry(3, true));<br /> vec.push_back(entry(4, false));<br /><br /><br /> /// boost::bind(&entry::connecting, _1<br /> /// Make a function object that willa lways return ***connecting***<br /> /// member variable of the passed in object...<br /> /// make a predicate that returns entry::connecting<br /> /// create a member pointer. In this case of type<br /> /// entry::*connectingPtr = &entry::connecting<br /> /// returns _1.*connecting<br /><br /> if(std::find_if(vec.begin(), vec.end(), boost::bind(<br /> &std::pair<int, bool>::second,<br /> boost::bind(&entry::conn_pair, _1))) != vec.end())<br /> {<br /> std::cout << "Hey. Found one" << std::endl;<br /> bool std::pair<int, bool>::*connectingPtr = &std::pair<int, bool>::second;<br /> std::cout << std::boolalpha << vec.front().conn_pair.*connectingPtr << std::endl;<br /> }<br /><br /> return 0;<br />}<br /></code></pre><br /><br />And if you are one of those who think pointers to data members are not useful, think again. The benefit of them is that once you declare a pointer to point to a data member of a type, you can use on different instances of that type. This link explains it clearly: http://stackoverflow.com/questions/670734/c-pointer-to-class-data-member<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>int main()<br />{ <br /> int Car::*pSpeed = &Car::speed; <br /> Car myCar;<br /> Car yourCar;<br /><br /> //access different instances using the same pointer.<br /> int mySpeed = myCar.*pSpeed;<br /> int yourSpeed = yourCar.*pSpeed;<br /><br /> assert(mySpeed > yourSpeed); // ;-)<br /><br /> return 0;<br />}<br /><br /></code></pre><br /><br />You might argue that you can always add a getter function that returns to you the value you pointed to, and do without pointers headaches. Not so. Like I showed in the example above, sometimes you are using pre-existing classes, like std::pair, and have no better way to have succinct code, except to bind. Oh well.YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-23768299584890952002009-09-04T08:06:00.000-07:002009-09-04T08:11:36.682-07:00Un-install a program programmatically (C++ on Windows)Ever wondered how a program is uninstalled when we remove a program from the control panel? Every installed program stores an uninstallString which is a command to un-install itself in the registry. If you can locate your program by searching for its name (I am using the name 'My Program' here), or if you know the product code, it really is a piece of cake....<br /><br />Here is a sample program to search the registry for a program called My Program and uninstall it.<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>#include <iostream><br />#include <algorithm><br />#include <string><br />#include <windows.h><br />#include <winreg.h><br />#include <iostream><br />#include <cstdlib><br /><br />bool uninstallMyProgram(HKEY hRootKey,const wchar_t *wzKey);<br /><br />bool search(HKEY hRootKey, const wchar_t *wzKey)<br />{<br /> const int KeyNameBufferSize = 512;<br /><br /> LONG result = ERROR_SUCCESS;<br /> TCHAR keyName[KeyNameBufferSize];<br /> DWORD index = 0;<br /> DWORD nameLength = KeyNameBufferSize;<br /> FILETIME lastWriteTime;<br /><br /> HKEY hRegKey;<br /> if(::RegOpenKeyEx(hRootKey, wzKey, 0L, KEY_READ , &hRegKey) != ERROR_SUCCESS)<br /> return false;<br /><br /> while (result == ERROR_SUCCESS)<br /> {<br /> nameLength = KeyNameBufferSize;<br /> result = ::RegEnumKeyEx(hRegKey, index, keyName,<br /> &nameLength, 0, NULL, NULL, &lastWriteTime);<br /><br /> if (result == ERROR_SUCCESS)<br /> {<br /> std::wstring str = wzKey ;<br /> str += keyName;<br /> if(uninstallMyProgram(hRegKey, str.c_str()))<br /> return true;<br /> }<br /><br /> index++;<br /> }<br /> RegCloseKey(hRootKey);<br /> return (result == ERROR_NO_MORE_ITEMS) ? true : false;<br />}<br /><br />bool uninstallMyProgram(HKEY hRootKey,const wchar_t *wzKey)<br />{<br /> const int KeyNameBufferSize = 1024;<br /> wchar_t valueBuffer[ KeyNameBufferSize ];<br /> valueBuffer[0]=0;<br /><br /> DWORD dwType = REG_SZ;<br /> BYTE abValueDat[ KeyNameBufferSize ];<br /> DWORD dwValDatLen = sizeof(abValueDat);<br /> HKEY hKey;<br /><br /> if(::RegOpenKeyEx(HKEY_LOCAL_MACHINE, wzKey, 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)<br /> return false;<br /><br /> if(::RegQueryValueEx(hKey, L"DisplayName", 0L, &dwType, abValueDat, &dwValDatLen) != ERROR_SUCCESS)<br /> return false; <br /><br /> wsprintf(valueBuffer,L"%s", (wchar_t*) abValueDat);<br /> if(::_wcsnicmp(L"My Program", valueBuffer, 14) == 0)<br /> {<br /> wchar_t uninstallCommand[ KeyNameBufferSize ];<br /> BYTE retValueDat [ KeyNameBufferSize ];<br /> dwValDatLen = sizeof(retValueDat);<br /><br /> if(::RegQueryValueEx(hKey, L"UninstallString", 0L, &dwType, retValueDat, &dwValDatLen) == ERROR_SUCCESS)<br /> {<br /> ::wsprintf(uninstallCommand,L"%s", (wchar_t*) retValueDat );<br /> if(-1 == ::_wsystem(uninstallCommand)) //execute the command to uninstall My Program<br /> {<br /> RegCloseKey(hKey);<br /> return false;<br /> }<br /> RegCloseKey(hKey);<br /> return true;<br /> }<br /> }<br /> RegCloseKey(hKey);<br /> return false; //My Program is not installed<br />}<br /><br />int main()<br />{<br /> const wchar_t* path = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\";<br /> bool removed = search( HKEY_LOCAL_MACHINE, path);<br /> if(!removed)<br /> removed = search( HKEY_CURRENT_USER, path);<br />}<br /></code></pre>YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-22084064804476773422009-08-11T01:53:00.001-07:002010-06-14T07:45:30.192-07:00Programming Interview Questions (2)Q: Implement a k-reverse function for reversing the elements of a linked list.<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>Nodeptr ReverseN(Nodeptr head, int number) {<br /> <br /> if(number < 2) <br /> return head;<br /> <br /> Nodeptr pre_sub_list_tail = NULL;<br /> Nodeptr curr_ptr = head;<br /> Nodeptr reversed_list_head = NULL;<br /> <br /> while(curr_ptr) <br /> {<br /> Nodeptr prev_ptr = NULL;<br /> Nodeptr nxt_ptr = NULL;<br /> Nodeptr sub_list_tail = NULL;<br /> Nodeptr sub_list_head = NULL;<br /> <br /> int count = number;<br /> while(curr_ptr && count) <br /> {<br /> if(number == count) <br /> sub_list_tail = curr_ptr;<br /> <br /> nxt_ptr = curr_ptr->nxtptr;<br /> curr_ptr->nxtptr = prev_ptr;<br /> prev_ptr = curr_ptr;<br /> curr_ptr = nxt_ptr;<br /> --count;<br /> if(curr_ptr == NULL) <br /> sub_list_head = prev_ptr;<br /> else if(count == 1) <br /> sub_list_head = curr_ptr;<br /> }<br /> <br /> if(pre_sub_list_tail) <br /> {<br /> pre_sub_list_tail->nxtptr = sub_list_head;<br /> }<br /> else <br /> {<br /> reversed_list_head = sub_list_head;<br /> }<br /> pre_sub_list_tail = sub_list_tail;<br /> }<br /> return reversed_list_head;<br /> <br />} <br /><br /></code></pre><br /><br />Q: write a program to find the nth left-truncatable prime.<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>#include <vector><br />#include <iostream><br />#include <boost/date_time/posix_time/posix_time_types.hpp><br />#include <boost/assign/std/vector.hpp> // for 'operator+=()'<br />#include <boost/optional.hpp><br /><br /><br />///works for p > 2<br />///we check all single digit truncatable primes in nth_truncatable_prime function below<br />bool is_prime(long p)<br />{<br /> for (long i = 2; i * i <= p; i = (i + 1) | 1)<br /> if (p % i == 0) <br /> return false;<br /><br /> return true;<br />}<br /><br />boost::optional<long> nth_truncatable_prime(long nth_truncatable)<br />{<br /> if(nth_truncatable <= 0)<br /> return boost::optional<long> ();<br /><br /> typedef std::vector< long >::size_type size_type;<br /> const size_type initial_size = 200;<br /><br /> std::vector<long> last_primes;<br /> last_primes.reserve( initial_size );<br /><br /> using namespace boost::assign;<br /> last_primes += 2,3,5,7;<br /><br /> if(nth_truncatable < 5)<br /> return boost::optional< long > (last_primes[ nth_truncatable -1 ] );<br /><br /> ///number of truncatable primes so far 4, i.e., (2, 3, 5, 7)<br /> int truncatable_primes = 4;<br /> const int max_power = 9;<br /><br /> ///iterate through powers (10s, 100s, 1000s, etc.)<br /> for(int power = 1, mult_factor = 10; power <= max_power; ++power, mult_factor *= 10)<br /> {<br /> std::vector< long > current_primes;<br /> current_primes.reserve( initial_size );<br /><br /> ///iterate through smaller powers inside the outer power (10s in 100s, 100s in 1000s)<br /> for(int i = 1; i <= max_power; ++i)<br /> {<br /> ///construct a new truncatable prime from previous truncatable primes <br /> std::vector<long>::const_iterator itEnd = last_primes.end();<br /> for(std::vector<long>::const_iterator itBegin = last_primes.begin(); itBegin != itEnd ; ++itBegin)<br /> {<br /> const long result = mult_factor * (i) + *itBegin;<br /><br /> if(is_prime( result ) )<br /> {<br /> ++truncatable_primes;<br /> if(truncatable_primes == nth_truncatable)<br /> return boost::optional<long> (result);<br /> <br /> current_primes.push_back( result );<br /> }<br /> }<br /> }<br /> last_primes = current_primes;<br /> }<br /> return boost::optional<long> ();<br />}<br /></code></pre><br /><br />Q: Reverse a linked list<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>//--------------------------------<br />//Reverse a linked list<br />void reverseLinkedList(node **head)<br />{<br /> node* tmp = *head;<br /> node* prev = NULL;<br /> node* next;<br /><br /> while(tmp)<br /> {<br /> next = tmp->next;<br /> tmp->next = result;<br /> result = tmp;<br /> tmp = next;<br /> }<br /> *head = result;<br />}<br /></code></pre><br /><br />Q: Remove the characters in str2 which are in str1<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>//------------------------------------<br />//remove the characters in str1 which are in str2<br />//untested<br />void stringRemove(char * str1, char * toRemove)<br />{<br /> //put the in array<br /> int a[256], index =0;<br /> const static unsigned size = 2<br /> <br /> for (int i=0; i < 255; i++)<br /> a[ i ] = 0;<br /><br /> for (int i=0; i<strlen(toRemove); i++)<br /> a[ toRemove[ i ] ]=1;<br /><br /> for (int i=0; i<strlen(str1); i++)<br /> {<br /> if ( a[str1[i]] == 1) // to remove<br /> continue;<br /> else<br /> str1[index++] = str1[i];<br /> }<br /> str1[index] = '\0';<br />}<br /></code></pre><br /><br />Q: Perform binary search on a sorted but rotated array.<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>int binary_search(int sortedArray[], int first, int last, int key) <br />{<br /><br /> if (first <= last) {<br /> int mid = (first + last) / 2; <br /> if (key == sortedArray[mid]) <br /> return sortedArray[ mid ]; // found it.<br /> else if (key < sortedArray[mid]) <br /> return binary_search(sortedArray, first, mid-1, key);<br /> else<br /> return binary_search(sortedArray, mid+1, last, key);<br /> }<br /> return -(first + 1); // failed to find key<br />}<br />//-----------------------------<br />int rotate_search(int sortedArray[], int first, int last, int key) <br />{<br /> if(first <= last)<br /> {<br /> int mid = (last + first) / 2;<br /> <br /> if(key == sortedArray[ mid ])<br /> return sortedArray[ mid ];<br /><br /> int sort_start;<br /> int sort_end;<br /><br /> int unsort_start;<br /> int unsort_end;<br /><br /> if (first < mid)<br /> {<br /> sort_start = first;<br /> sort_end = mid;<br /><br /> unsort_start = mid;<br /> unsort_end = last;<br /> }<br /> else <br /> {<br /> sort_start = mid;<br /> sort_end = last;<br /><br /> unsort_start = first;<br /> unsort_end = mid;<br /> }<br /> if (key < sortedArray[ sort_end ])<br /> return binary_search(sortedArray, sort_start, sort_end - 1, key);<br /> else<br /> return rotate_search (sortedArray, unsort_start + 1, unsort_end, key);<br /> }<br /> return -1;<br />}<br /></code></pre><br /><br />Q: Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like.<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>int countDuplicates(int* a, int N)<br />{<br /> int dup = 0;<br /> for(int i = 0; i < N; ++i)<br /> {<br /> if(a[ a[i] - 1 ] == -1)<br /> {<br /> dup++;<br /> continue;<br /> }<br /> a[ a[i] - 1] = -1;<br /> }<br /> return dup;<br />}<br /></code></pre><br /><br />Q: Write a program to check whether the given two logical addresses are in the same page.<br /><br />A: Since the page boundaries are at 0, 4, 8k …we can see that the page size is equal to 4K. Now assuming we have a 32 bit address space, bits 31-20 will always be the same for one block of 4k bytes of memory since 4k is equal to 4*1024 which is equal to 12 lower order bits of the address. Given two addresses the only thing to be checked is their bits from 31-20. If they are same that means both the addresses lie in the same page. (Assuming int size is 4 bytes else we will use long to store the address)<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>bool AreOnSamePage (int *a, int *b)<br />{<br /> return (a & 0xFFFFF000) == (c & 0xFFFFF000);<br />} <br /></code></pre><br /><br />Q: Count the number of SET bits in an integer<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>//Count the number of SET bits in an integer (32-bit)<br />//Method 1<br /><br />unsigned int count;<br />for (unsigned int v = 0; v; v >= 1)<br /> count += v & 1;<br /><br />//a better way. Goes through the loop as many as there are set bits.<br />unsigned int v; // count the number of bits set in v<br />unsigned int c; // c accumulates the total bits set in v<br />for (c = 0; v; c++)<br />{<br /> v &= v - 1; // clear the least significant bit set<br />}<br /></code></pre><br /><br /> Q: I want to see if all the ones in a number appear on the right side of the number and all zeros appear on the left, how can I do this most efficiently? (e.g, 00000111 is true but 100010 is false)<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code> On the right: (x + 1) & x == 0;<br /> On the left: (~x + 1) & ~x == 0;<br /></code></pre><br /><br />Q: Implement a function to generate fib sequence.<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>unsigned int fib(unsigned int n)<br />{<br /> if(n < 2)<br /> return n;<br /><br /> unsigned int i_1 = 1;<br /> unsigned int i_2 = 0;<br /> unsigned sum = 0;<br /> for(unsigned int i = 2; i <= n; ++i)<br /> {<br /> sum = i_1 + i_2;<br /> i_2 = i_1;<br /> i_1 = sum;<br /> }<br /> return sum;<br />}<br /><br />unsigned int fibR(unsigned int n)<br />{<br /> if (n < 2)<br /> return n;<br /> return fib(n - 1) + fib ( n - 2);<br />}<br /></code></pre><br /><br />Q: Print a matrix in a spiral way (i.e., top row, right col, bottom row, left col)<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>void printSpiral(int a[][6], int rows, int cols)<br />{<br /> int topRow = 0;<br /> int rightCol = cols - 1;<br /> int bottomRow = rows - 1;<br /> int leftCol = 0;<br /><br /> while(topRow <= bottomRow && leftCol <= rightCol)<br /> {<br /> //top left to right. TopRow Fixed<br /> for(int i = leftCol; i < rightCol; ++i)<br /> std::cout << a[ topRow ][ i ] << std::endl;<br /> <br /> for(int i = topRow; i < bottomRow; ++i)<br /> std::cout << a[ i ][ rightCol ] << std::endl;<br /><br /> for(int i = rightCol; i > leftCol; --i)<br /> std::cout << a[ bottomRow ][ i ] << std::endl;<br /><br /> //left col. bottom to top<br /> for(int i = bottomRow; i > topRow; --i)<br /> std::cout << a[ i ][ leftCol ] << std::endl;<br /><br /> topRow++;<br /> rightCol--;<br /> bottomRow--;<br /> leftCol++;<br /> }<br />}<br /></code></pre><br /><br />Q: Code to remove spaces from a string.<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>void removSpaces(char *s)<br />{<br /> int i, j = 0;<br /> <br /> for (i = 0; s[i]; i++)<br /> {<br /> if (isspace(s[i]))<br /> continue;<br /><br /> s[j++] = s[i];<br /> }<br /> s[j] = 0;<br />}<br /><br /></code></pre><br /><br />Q: Merge two sorted arrays.<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>//untested<br />int* merge_arrays(int* dst, const int* src, int size_dst, int size_src)<br />{<br /> dst = static_cast<int*>(::realloc(dst, size_dst + size_src) );<br /> <br /> while(size_dst > 0 || size_src > 0)<br /> {<br /> if(dst[ size_dst ] >= src[ size_src ] )<br /> {<br /> dst[ size_dst + sirce_src ] = dst[ size_dst ];<br /> size_dst--;<br /> }<br /> else<br /> {<br /> dst[ size_dst + sirce_src ] = src[ size_src ];<br /> size_src--;<br /> }<br /> }<br /> return dst;<br />}<br /></code></pre><br /><br />Q: Implement preorder, post order and inorder traversals in a single algorithm<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>traverse(s)<br />{<br /> if(s) <br /> {<br /> preorder_queue.add(s);<br /> traverse(s->left);<br /> inorder_queue.add(s);<br /> traverse(s->right);<br /> postorder_queue(s);<br /> }<br />}<br /></code></pre><br /><br />Q: Reverse bits in an integer...<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code><br />unsigned int reverse_bits(unsigned int a)<br />{<br /> unsigned int result = 0;<br /> unsigned int tmp = a;<br /> while(tmp)<br /> {<br /> result = ( 1 << j ) | (tmp & 1);<br /> tmp >>= 1;<br /> }<br /> return result;<br />}<br /></code></pre><br /><br />Q: implement in-place swap:<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>void my_swap(int& a, int& b)<br />{<br /> a ^= b;<br /> b ^= a;<br /> a ^= b;<br />}<br /><br /></code></pre><br />Proof: http://en.wikipedia.org/wiki/XOR_swap<br /><br />Q: Print a tree level by level (BFS algorithm)<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>//print a binary Tree level by level<br />//Essentially doing a breadth first search<br />void BFS(NODE *root)<br />{<br /> if (!root)<br /> return;<br /><br /> Queue q = new Queue();<br /><br /> q->Enqueue(root);<br /> do<br /> {<br /><br /> NODE *curr = q->Dequeue();<br /> print(curr->val);<br /><br /> if (curr->left)<br /> q->Enqueue(curr->left);<br /> if (curr->right)<br /> q->Enqueue(curr->right);<br /><br /> }<br /> while (!q->Empty());<br />}<br /></code></pre><br /><br />Q: Implement a function that returns true if a binary tree is a BST.<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>/*<br /> Returns true if the given tree is a binary search tree<br /> (efficient version).<br />*/<br />int isBST2(struct node* node) {<br /> return(isBSTUtil(node, INT_MIN, INT_MAX));<br />}<br /><br />/*<br /> Returns true if the given tree is a BST and its<br /> values are >= min and <= max.<br />*/<br />int isBSTUtil(struct node* node, int min, int max) {<br /> if (node==NULL) return(true);<br /><br /> // false if this node violates the min/max constraint<br /> if (node->data<min || node->data>max) return(false);<br /><br /> // otherwise check the subtrees recursively,<br /> // tightening the min or max constraint<br /> return<br /> isBSTUtil(node->left, min, node->data) &&<br /> isBSTUtil(node->right, node->data+1, max)<br /> );<br />} <br /></code></pre><br /><br />Q: Count the number of SET bits in an integer.<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>//Count the number of SET bits in an integer (32-bit)<br />//Method 1<br /><br />unsigned int count;<br />for (unsigned int v = 0; v; v >= 1)<br /> count += v & 1;<br /><br />//a better way. Goes through the loop as many as there are set bits.<br />unsigned int v; // count the number of bits set in v<br />unsigned int c; // c accumulates the total bits set in v<br />for (c = 0; v; c++)<br />{<br /> v &= v - 1; // clear the least significant bit set<br />}<br /></code></pre><br /><br />Q: Get the depth of a binary tree (recursively)<br />A: <br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>int get_three_depth(Node* root)<br />{<br /> if(!root)<br /> return 0;<br /> <br /> return 1 + max( get_three_depth(root->right), get_three_depth(root->left) );<br />}<br /></code></pre><br /><br />Q: Get the depth of a tree iteratively<br />A:<br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>void BFS(NODE *root)<br />{<br /> if (!root)<br /> return;<br /><br /> int depth = 1; //root has depth 1<br /> Queue q = new Queue();<br /><br /> q->Enqueue(root);<br /> NODE* nextLevel = NULL;<br /> if(root->left)<br /> nextLevel = root->left;<br /> else if(root->right)<br /> nextLevel = root->right;<br /> else<br /> return depth;<br /><br /> do<br /> {<br /> NODE *curr = q->Dequeue();<br /> print(curr->val);<br /><br /> if(nextLevel = curr)<br /> {<br /> depth++;<br /> nextLevel <br /> }<br /> if (curr->left)<br /> q->Enqueue(curr->left);<br /> if (curr->right)<br /> q->Enqueue(curr->right);<br /><br /> if(!nextLevel)<br /> {<br /> if(curr->left)<br /> nextLevel = root->left;<br /> else if(curr->right)<br /> nextLevel = root->right;<br /> }<br /><br /> }<br /> while (!q->Empty());<br />}<br /></code></pre>YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com1tag:blogger.com,1999:blog-7861216377033187791.post-6373538015900218102009-06-22T04:06:00.000-07:002009-06-22T05:55:10.659-07:00boost intrusive_ptrboost::intrusive_ptr is one of the six smart pointer class templates provided by boost. It is interesting in that it is widely used as shared_ptr, but sometiems very useful. It relies on the stored object to provide its own reference counting semantics using two functions that must be called: <span style="font-weight:bold;">intrusive_ptr_add_ref</span> and <span style="font-weight:bold;">intrusive_ptr_release</span>. These functions take a pointer argument to the pointer that is to be managed and must be defined in the boost namespace, or if the compiler supports Koenig lookup, in the namespace where the arguments are defined. <br /><br />Read more about intrusive_ptr here: http://www.boost.org/doc/libs/1_39_0/libs/smart_ptr/intrusive_ptr.html<br /><br />Here is a simple Example I put together for myself to understand how this works.<br /><br />First, this is a base class that provides reference counting support by defining the <span style="font-weight:bold;">intrusive_ptr_add_ref</span> and <span style="font-weight:bold;">intrusive_ptr_release</span>. functions.<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>#include <ostream><br />#include <boost/checked_delete.hpp><br />#include <boost/detail/atomic_count.hpp><br /><br />template<class T><br />struct intrusive_ptr_base<br />{<br /> intrusive_ptr_base(): ref_count(0) <br /> {<br /> std::cout << " Default constructor " << std::endl;<br /> }<br /> //only construct an intrusive_ptr from another intrusive_ptr. That is it.<br /> intrusive_ptr_base(intrusive_ptr_base<T> const&)<br /> : ref_count(0) <br /> {<br /> std::cout << " Copy constructor..." << std::endl;<br /> }<br /><br /> ///does nto support assignment<br /> intrusive_ptr_base& operator=(intrusive_ptr_base const& rhs)<br /> { <br /> std::cout << " Assignment operator..." << std::endl;<br /> return *this; <br /> }<br /><br /> friend void intrusive_ptr_add_ref(intrusive_ptr_base<T> const* s)<br /> {<br /> std::cout << " intrusive_ptr_add_ref..." << std::endl;<br /> assert(s->ref_count >= 0);<br /> assert(s != 0);<br /> ++s->ref_count;<br /> }<br /><br /> friend void intrusive_ptr_release(intrusive_ptr_base<T> const* s)<br /> {<br /> std::cout << " intrusive_ptr_release..." << std::endl;<br /> assert(s->ref_count > 0);<br /> assert(s != 0);<br /> if (--s->ref_count == 0)<br /> boost::checked_delete(static_cast<T const*>(s));<br /> }<br /><br /> boost::intrusive_ptr<T> self()<br /> { <br /> return boost::intrusive_ptr<T>((T*)this); <br /> }<br /><br /> boost::intrusive_ptr<const T> self() const<br /> { <br /> return boost::intrusive_ptr<const T>((T const*)this); <br /> }<br /><br /> int refcount() const <br /> { <br /> return ref_count; <br /> }<br /><br /> <br />private:<br /> ///should be modifiable even from const intrusive_ptr objects<br /> mutable boost::detail::atomic_count ref_count;<br />};<br /><br /><br /></code></pre><br /><br />By inheriting publicly from intrusive_ptr_base, we make available the essential reference counting functions: intrusive_ptr_add_ref and intrusive_ptr_release. Notice that we defined these arguments in the base class, so we defined these arguments int he namespace where the parameters are defined, and the best way to guarantee that the compiler finds them is to put them as friend functions in the base class. We put them as friends to give them access to the private data members. Notice that if we defined them as member functions, they will take the <span style="font-weight:bold;">*this</span> pointer and they won't match the expected signature that boost::intrusive_ptr requires. The output statements provided in the class are just for debugging purposes. <br /><br />To test it:<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>#include <boost/intrusive_ptr.hpp><br />#include "intrusive_ptr_base.hpp"<br /><br />class Connection : public intrusive_ptr_base< Connection ><br />{<br />public:<br /> Connection(int id, std::string tag) <br /> : connection_id( id )<br /> , connection_tag( tag ) {}<br /><br /> Connection(const Connection& rhs) <br /> : connection_id( rhs.connection_id )<br /> , connection_tag( rhs.connection_tag) {}<br /><br /> const Connection operator=( const Connection& rhs)<br /> {<br /> if(this != &rhs)<br /> {<br /> connection_id = rhs.connection_id;<br /> connection_tag = rhs.connection_tag;<br /> }<br /> return *this;<br /> }<br /><br />private:<br /> int connection_id;<br /> std::string connection_tag;<br />};<br /><br />int main()<br />{ <br /> std::cout << "Create an intrusive ptr" << std::endl;<br /> boost::intrusive_ptr< Connection > con0 (new Connection(4, "sss") );<br /> std::cout << "Create an intrusive ptr. Refcount = " << con0->refcount() << std::endl;<br /> boost::intrusive_ptr< Connection > con1 (con0);<br /> std::cout << "Create an intrusive ptr. Refcount = " << con1->refcount() << std::endl;<br /> boost::intrusive_ptr< Connection > con2 = con0;<br /> std::cout << "Create an intrusive ptr. Refcount = " << con2->refcount() << std::endl;<br /><br /> std::cout << "Create an intrusive ptr. Refcount = " << con2->refcount() << std::endl;<br /> std::cout << "Destroy an intrusive ptr" << std::endl;<br /> return 0;<br />}<br /></code></pre><br /><br />We notice that when we construct an object or assign to it, boost::intrusive_ptr calls our functions to increment the reference count. <br /><br />boost::intrusive_ptr has the same memory footprint as a raw ptr, and can be constructed from any T* raw pointer. <br /><br />Also, shared_ptr if not used carefully can cause subtle crashes and bugs as I already discussed in this <a href="http://alsharabi.blogspot.com/2009/03/why-use-sharedfromthis.html">post here</a>. That is, you should never create two shared_ptr objects using the same raw pointer, if you do, the destructor for the controlled resource will be called twice when the shared_ptr objects are destroyed. Instead, copy the first shared_ptr object to create a second shared_ptr object that controls the resource. To avoid it, always create a shared_ptr from another shared_ptr that points to that resource already. But if we use an intrusive_ptr, that problem goes away.<br /> <br />So use intrusive_ptr....YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-54958397660885685252009-03-12T03:44:00.000-07:002009-03-12T10:51:35.319-07:00postmortem debugging (WinDbg)We write high quality code, but a crash is always possible. So what do you do if it your program crashes? Simple, you analyze the crash dumps, find out where and why it is crashing and fix it. But, what if the crash is not repeatable? Be prepared. The best thing to do is to install a crash dump tool on the computer where the software is going to be run/tested. <br /><br />When a program error occurs in Windows, the operating system searches for a program error handler to deal with the error. If the system does not find such a handler, the system verifies that the program is not currently being debugged, and if not, it considers the error to be unhandled. The system then processes unhandled errors by looking in registry for a program error debugger. An example error handler is dr watson.<br /><br />To install Dr. Watson as your crash dump analysis tool, follow these simple instructions <a href="http://devmentor.org/articles/crash_dump/crashdump1.html">here</a><br /><br />To install Debugging tools for windows as your crash dump tool, do the following:<br /><br /><ul><li>Download debugging tools for windows from <a href="http://www.microsoft.com/whdc/devtools/debugging/default.mspx">here</a></li><li>Install it into your folder of choice, example: <span style="font-style: italic;">C:\Program Files\Debugging Tools for Windows</span>.</li><li>Register Debugging tools for windows as your default debugger, by running this command from the command prompt: "C:\Program Files\Debugging Tools for Windows\WinDbg" -i" You should see this message confirming that WinDbg is your postmortem debugger:<br /><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhBR5V6VsjRCKpOi95jgHjZDknIjqtzHbpx0b8g_CYh568y0ErV23n-npz_tqHDpQCXJ56pIZTfPHSa-Ri-ejcjXUaT2BfTmrUcnp3qaYDJniJRH8ANfwiZYXqU5BEpwNJuyWf5lQhVyrK/s1600-h/WinDbg.bmp"><img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 400px; height: 120px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhBR5V6VsjRCKpOi95jgHjZDknIjqtzHbpx0b8g_CYh568y0ErV23n-npz_tqHDpQCXJ56pIZTfPHSa-Ri-ejcjXUaT2BfTmrUcnp3qaYDJniJRH8ANfwiZYXqU5BEpwNJuyWf5lQhVyrK/s400/WinDbg.bmp" alt="" id="BLOGGER_PHOTO_ID_5312256820785640530" border="0" /></a><br /></li><li>Run regedit (from start->run) and modify this key: <span style="font-style: italic;">HKLM\software\microsoft\windows nt\currentversion\aedebug</span>. Change the value of the key Debugger (creating it if necessary) to the following:</li><li><span style="font-style: italic;">"C:\Program Files\Debugging Tools for Windows\cdb.exe" -p %ld -c ".dump /ma /u C:\Dumps\Crash.dmp; q" -e %ld –g</span></li></ul><br />Any dump files from any programs from now on, will be put in <span style="font-style: italic;">C:\dumps\</span> with a <span style="font-style: italic;">.dmp</span> extension.<br /><br />Now that you have the dump file, take the .exe and .pdb files of the crashing program, drop them in your code's output directory and double click on the .dmp file. Visual studio will open a dump project for you. Start debugging your program, and it will show you where it crashes. This assumes that you built your program with debug symbols and moderate optimization (or no optmization). If you don't know how to do that, well, ask Google.YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-21725678750734449542009-03-11T05:34:00.000-07:002009-03-11T05:36:57.696-07:00Add code expiry for hacks in your projectsSometimes we are under tight deadlines to finish things, and we are forced to put in some hacks and quick fixes int he code, hoping to fix them later and write them propertly. You can add \\todo comments, and other stuff to remind you, but there is nothing better than a compilation error after a certain date.<br /><br />I found this bit of code online, and just modified it slightly. You can put a compilation timebomb in your code, and once a certain date passes, your code will no longer compile. You'll be reminded to fix what you wanted to fix.<br /><br />An example is provided here:<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>#include <iostream><br />#include <sstream><br /><br />void assert_fail(const char* expr, int line, char const* file, const char* function);<br />#ifdef WIN32<br /> #define CUSTOM_ASSERT(x) do { if (x) {} else assert_fail(#x, __LINE__, __FILE__, __FUNCTION__); } while (false)<br />#else<br /> #define CUSTOM_ASSERT(x) do { if (x) {} else assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__); } while (false)<br />#endif //WIN32<br /><br />/////////////////////////////<br />#define YEAR ((((__DATE__ [7] - '0') * 10 + (__DATE__ [8] - '0')) * 10 \<br />+ (__DATE__ [9] - '0')) * 10 + (__DATE__ [10] - '0'))<br /><br />#define MONTH (__DATE__ [2] == 'n' ? (__DATE__ [1] == 'a' ? 1 : 6) \<br />: __DATE__ [2] == 'b' ? 2 \<br />: __DATE__ [2] == 'r' ? (__DATE__ [0] == 'M' ? 3 : 4) \<br />: __DATE__ [2] == 'y' ? 5 \<br />: __DATE__ [2] == 'l' ? 7 \<br />: __DATE__ [2] == 'g' ? 8 \<br />: __DATE__ [2] == 'p' ? 9 \<br />: __DATE__ [2] == 't' ? 10 \<br />: __DATE__ [2] == 'v' ? 11 : 12)<br /><br />#define DAY ((__DATE__ [4] == ' ' ? 0 : __DATE__ [4] - '0') * 10 \<br />+ (__DATE__ [5] - '0'))<br /><br />#define DATE_AS_INT (((YEAR - 2000) * 12 + MONTH) * 31 + DAY)YEAR - 2000) * 12 + MONTH) * 31 + DAY)<br /><br />#define UNIQUE_NAME( Y,M,D ) ReviewBefore##_##Y##_##M##_##D##_##line<br />#define REVIEW_DATE( YYYY, MM, DD ) (((YYYY - 2000) * 12 + MM) * 31 + DD)<br />#define COMPILE_DATE (((YEAR - 2000) * 12 + MONTH) * 31 + DAY)<br /><br />#define REVIEW_BEFORE( YYYY, MM, DD ) \<br />static const struct UNIQUE_NAME(YYYY,MM,DD)##__LINE__ { UNIQUE_NAME(YYYY,MM,DD)##__LINE__() { \<br />assert( COMPILE_DATE < REVIEW_DATE(YYYY, MM, DD) ); \<br />} } UNIQUE_NAME(YYYY,MM,DD)##__LINE__<br /><br />#define EXPIRED "This code has expired"<br />#define REVIEW_BEFORE_STMT( YYYY, MM, DD ) \<br />CUSTOM_ASSERT(COMPILE_DATE < REVIEW_DATE(YYYY, MM, DD) )<br /><br />void assert_fail(const char* expr, int line, char const* file, const char* function)<br />{<br /> std::cerr << "Code obselete" << std::endl;<br /> std::ostringstream str;<br /> str << "Expresion: " << expr << "\n"<br /> << "line: " << line << "\n"<br /> << "file: " << file << "\n"<br /> << "function: " << function << "\n";<br /><br /> std::cerr << str.str() << std::endl;<br />}<br /><br />int main()<br />{<br /> REVIEW_BEFORE_STMT(2000,1,1);<br /> std::cout << COMPILE_DATE << std::endl;<br /><br /> return 0;<br />}<br /></code></pre>YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-38018091871014787112009-03-04T06:09:00.000-08:002009-03-04T06:26:30.794-08:00why use shared_from_this() ?Why would you need to use shared_from_this on an object? As the name implies, if you want to pass a shared pointer to *this (pointer to current object), then you use shared_from_this.<br /><br />What happens if you don't? Well, a scenario could happen where you wrap *this pointer in a smart pointer from a member function, expecting that to work just fine. But what happens when you do that is you create another shared_ptr to *this with reference count of 1. When this member function exits, the shared_ptr gets destroyed, and your *this pointer is deleted, causing the destructor of the object to be called.<br /><br />An example will make this clearer:<br /><pre style="border: 1px dashed rgb(153, 153, 153); padding: 5px; overflow: auto; font-family: Andale Mono,Lucida Console,Monaco,fixed,monospace; color: rgb(0, 0, 0); background-color: rgb(238, 238, 238); font-size: 12px; line-height: 14px; width: 100%;"><code>#include <iostream><br />#include <boost/shared_ptr.hpp><br /><br />class Bar;<br />void foo(const boost::shared_ptr<Bar>& ptr);<br /><br />class Bar<br />{<br />public:<br /> void process()<br /> {<br /> foo(boost::shared_ptr<Bar>(this));<br /> }<br /> void print() const {std::cout << "I am still alive!!" << std::endl; }<br /><br /> ~Bar() { std::cout << "Uh oh... I am dead!!" << std::endl; }<br />};<br /><br />void foo(const boost::shared_ptr<Bar>& ptr)<br />{<br /> ptr->print();<br />}<br /><br />int main()<br />{<br /> boost::shared_ptr<Bar> sPtr(new Bar());<br /> sPtr->process();<br /> sPtr->print();<br /> std::cout << "Just before leavnig main " << std::endl;<br /> sPtr->print();<br /> return 0;<br />}<br /></code></pre><br /><br />When you run this code (fix any errors first), it'll crash. The reason being, when the function process exits, the temporary shared_ptr<Bar> resets its refcount to 0, and the *this object gets deleted. Then when main tries to delete the object again upon exit, it crashes. <br /><br />To fix this, we use shared_from_this(), which will simply make sure that we get a smart pointer *this instead of a raw pointer *this. Read more about it in the <a href="http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/enable_shared_from_this.html">boost docs</a><br /><br /> <br /><pre style="border: 1px dashed rgb(153, 153, 153); padding: 5px; overflow: auto; font-family: Andale Mono,Lucida Console,Monaco,fixed,monospace; color: rgb(0, 0, 0); background-color: rgb(238, 238, 238); font-size: 12px; line-height: 14px; width: 100%;"><code>#include <iostream><br />#include <boost/shared_ptr.hpp><br />#include <boost/enable_shared_from_this.hpp><br /><br />class Bar;<br />void foo(const boost::shared_ptr<Bar>& ptr);<br /><br />class Bar : public boost::enable_shared_from_this<Bar><br />{<br />public:<br /> void process()<br /> {<br /> foo(shared_from_this());<br /> }<br /> void print() const {std::cout << "I am still alive!!" << std::endl; }<br /><br /> ~Bar() { std::cout << "Uh oh... I am dead!!" << std::endl; }<br />};<br /><br />void foo(const boost::shared_ptr<Bar>& ptr)<br />{<br /> ptr->print();<br />}<br /><br />int main()<br />{<br /> boost::shared_ptr<Bar> sPtr(new Bar());<br /> sPtr->process();<br /> sPtr->print();<br /> std::cout << "Just before leavnig main " << std::endl;<br /> sPtr->print();<br /> return 0;<br />}<br /><br /></code></pre>YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com3tag:blogger.com,1999:blog-7861216377033187791.post-80902016806579881502009-02-10T13:29:00.000-08:002009-03-13T03:02:16.728-07:00boost multi-index containerI am usually lazy to write tutorial-like articles, or anything of benefit, but I try to put here just something plain, simple that might direct the reader, and myself as well, in the right direction.<br /><br />If you've worked with data that needs to be sorted according to many criterias, then you have probably struggled with using multiple containers and multiple sorting functions/algorithms. Scenarios include displaying data sorted in different views, such as, files according to size, name, change date, etc.<br /><br />Here is an example of the very powerful boost multi index container. As the name implies it enables you to have multiple indices into your container, which enables you to look at it anyway you desire.<br /><br />Read more about it, and find more examples <a href="http://www.boost.org/doc/libs/1_37_0/libs/multi_index/doc/index.html">here</a><br /><br /><br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>#include <string><br />#include <iostream><br />#include <boost/multi_index_container.hpp><br />#include <boost/multi_index/member.hpp><br />#include <boost/multi_index/ordered_index.hpp><br /><br />using boost::multi_index::multi_index_container;<br />using boost::multi_index::ordered_non_unique;<br />using boost::multi_index::ordered_unique;<br />using boost::multi_index::indexed_by;<br />using boost::multi_index::member;<br /><br />struct employee_entry<br />{<br /> employee_entry( const std::string& first,<br /> const std::string& last,<br /> long id):<br /> first_name_(first),<br /> last_name_(last),<br /> id_(id)<br /> {}<br /> std::string first_name_;<br /> std::string last_name_;<br /> long id_;<br />};<br /><br /><br />typedef multi_index_container<<br />employee_entry, indexed_by<<br /> ordered_unique<member<employee_entry, std::string<br /> , &employee_entry::first_name_> ><br /> , ordered_non_unique<member<employee_entry, std::string<br /> , &employee_entry::last_name_> ><br /> , ordered_non_unique<member<employee_entry, long<br /> , &employee_entry::id_> ><br /> ><br />> employee_set;<br /><br />//employee set.... multi-index<br />employee_set m_employees;<br /><br /><br />int main()<br />{<br /> using boost::multi_index::nth_index;<br /> using boost::multi_index::get;<br /><br /> typedef nth_index<employee_set, 0>::type first_name_view;<br /> first_name_view& fnv = get<0>(m_employees);<br /><br /> fnv.insert(employee_entry("John", "Smith", 110));<br /> fnv.insert(employee_entry("Fudge", "Hunk", 97));<br /> fnv.insert(employee_entry("Tolem", "Bathi", 87));<br /> fnv.insert(employee_entry("Anjal", "Sunfo", 75));<br /> fnv.insert(employee_entry("Heidi", "Clark", 89));<br /><br /> ///get employees sorted by id<br /> typedef nth_index<employee_set, 2>::type id_view;<br /> id_view& idv = get <2> (m_employees);<br /> for(id_view::reverse_iterator it = idv.rbegin(), it_end(idv.rend()); it != it_end; ++it)<br /> {<br /> std::cout << it->first_name_ <<" "<br /> << it->last_name_ << ":"<br /> << it->id_ << std::endl;<br /> }<br /><br /> const std::string str(40, '-');<br /> std::cout << str << std::endl;<br /> <br /> ///get employees sorted by first name<br /> typedef nth_index<employee_set, 0>::type fname_view;<br /> fname_view& fdv = get <0> (m_employees);<br /><br /> for(fname_view::iterator it = fdv.begin(), it_end(fdv.end()); it != it_end; ++it)<br /> {<br /> std::cout << it->first_name_ <<" "<br /> << it->last_name_ << ":"<br /> << it->id_ << std::endl;<br /> }<br /> <br /> return 0;<br />}<br /></code></pre>YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-75763315304588631102008-11-27T14:57:00.000-08:002008-11-27T15:12:52.098-08:00Grub error 22 nightmareSo two nights ago, while trying to free up some space on my windows partition, I just decided to remove the linux SUSE partition which I rarely use. So I launched up partition magic, and off I go. I deleted the Linux partition. When I started my machine again, the nightmare started...<br /><br />Booting grub stage 1.5<br />Grub error 22<br /><br />What happened is that grub is looking for linux startup files that are not there anymore. One way to resolve this is to startup your computer with a windows CD, go to the recovery console, and execute fixmbr, which should restore the original MBR, windows only. I have a Toshiba Sattelite A100 laptop which comes only with a recovery CD (no Windows CD), so I had no luck with that.<br /><br />I had valuable data on my hard-drive and simply wiping it out was not an option. So I did some research online and finally resolved my problem using the following:<br /><br />1- Install the Ultimate Boot CD (free from www.ultimatebootcd.com). Get the self-extracting EXE as it is smaller and installs faster<br />2- Extract the ultimate boot cd into an ISO image and use Nero or some other CD writing software to burn it onto a blank CD<br />3- Insert this blank CD into your computer and startup.<br />4- Click F-12 as your machine is starting up (or the equivalent on your machine) to go to the Boot Menue. Choose to boot from CD/DVD<br />5- Once in the command list of the UltimateBootCD (UBCD), choose filesystem tools.<br />6- Go down to the MBRtool and select it. You should see a screen like the following:<br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijLm2OBk2lNrypVwa-2x5rX0N-I7YMn7tP3Gvf7p0WLEUmWBqbeqdbbD1YaOnIuGRRiykQYdv3w6gV4UlLSbkNRXikg60D8sY-nJtPsmnBjLIYqJp3U01pvuvoLkTuJxY88ziIYHYRUV65/s1600-h/MBRtool.png"><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 400px; height: 310px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijLm2OBk2lNrypVwa-2x5rX0N-I7YMn7tP3Gvf7p0WLEUmWBqbeqdbbD1YaOnIuGRRiykQYdv3w6gV4UlLSbkNRXikg60D8sY-nJtPsmnBjLIYqJp3U01pvuvoLkTuJxY88ziIYHYRUV65/s400/MBRtool.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5273479027415144482" /></a><br /><br />7- Choose Option 4: Work with a MBR ...<br />8- From the next screen select option 9 (write/refresh boot code). It will ask you what Hard disk you want to select, choose 0 (or whichever is right for you). It will ask you whether you want to work with it on a file/sector or original, select 0 for original. Or simply execute this command <span style="font-weight:bold;">/RBC /DSK:0</span><br />9- This usually just takes a second. Once this is done, reboot your machine again and it should boot normally this time.YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-8212535695847953852008-11-11T13:45:00.000-08:002008-11-11T14:26:21.050-08:00boost::any (2) - storing pointers in boost::anyWe know that we can retrieve the value stored in a boost::any using one of the two overloaded boost::any_cast by either passing our any by reference or as a pointer. What if we store a pointer in boost::any?<br /><br />The following example assumes the declaration from the previous boost::any(1) post:<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>int main()<br />{<br /> typedef std::vector<boost::any> MixedContainer_t;<br /> MixedContainer_t mixedContainer;<br /><br /> A* aPtr1 = new A(2);<br /> A* aPtr2 = new A(3);<br /><br /> mixedContainer.push_back(aPtr1);<br /> mixedContainer.push_back(aPtr2);<br /><br /> //would not work. What is stored at front() is a pointer to A<br /> //and not an object of type A.<br /> if(A* a = boost::any_cast<A> (&mixedContainer.front()))<br /> a->print();<br /><br /> //we can even confirm it by testing the types<br /> if(typeid(A*) == mixedContainer.back().type())<br /> {<br /> std::cout << "object at front() is a pointer to A" << std::endl;<br /> }<br /> //to get a pointer to it, we need to retrieve a A**, and pass<br /> //the type of object we think stored at front as A*<br /> if(A** a = boost::any_cast<A*> (&mixedContainer.front()))<br /> {<br /> std::cout << "pointer-> ";<br /> (*a)->print();<br /> }<br /> <br />}<br /></code></pre><br /><br />Storing pointers in boost::any is problematic, because boost::any stores only a value of the pointer, and when the boost::any is destroyed, the only memory that is released is that occupied by the pointer, and not the memory it points to. That is, delete or delete[] is not called. What to do? Use smart pointers. As with standard containers, avoid using auto_ptr because of its 'weird' copy semantics. <br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>#include <iostream><br />#include <vector><br />#include <boost/any.hpp><br />#include <boost/shared_ptr.hpp><br /><br /><br />class A<br />{<br /> int value_;<br />public:<br /> A(int value) : value_(value) {}<br /> void print() const {std::cout << "A's value: " << value_ << std::endl;}<br /> ~A() {std::cout << "A(" << value_ <<") destructor" << std::endl; }<br />};<br /><br />class B<br />{<br /> int value_;<br />public:<br /> B(int value) : value_(value) {}<br /> void print() const {std::cout << "B's value: " << value_ << std::endl;}<br /> ~B() {std::cout << "B(" << value_ <<") destructor" << std::endl; }<br />};<br /><br />int main()<br />{<br /> typedef std::vector<boost::any> MixedContainer_t;<br /> MixedContainer_t mixedContainer;<br /><br /> boost::shared_ptr<A> aPtr0(new A(1));<br /> A* aPtr1 = new A(2);<br /> A* aPtr2 = new A(3);<br /><br /> mixedContainer.push_back(aPtr0);<br /> mixedContainer.push_back(aPtr1);<br /> mixedContainer.push_back(aPtr2);<br /><br /> //and to retrieve the value from shared Ptr is simple<br /> try<br /> {<br /> boost::shared_ptr<A> ptr = boost::any_cast<boost::shared_ptr<A> > (mixedContainer.front());<br /> ptr->print();<br /><br /> }<br /> catch(boost::bad_any_cast& bac)<br /> {<br /> bac.what();<br /> }<br /> //only the destructor of the A pointed to by shared_ptr is printed.<br />}<br /><br /></code></pre>YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-59498566399883179452008-11-09T12:59:00.000-08:002008-11-11T13:44:59.925-08:00boost::any (1)Sometimes you might want to store unrelated types in the same container, and convey the data from one point to another without caring much about it's type. C++ containers are templated on the type and can only store objects of the same type in the same container. Traditionally, this problem has been solved by storing pointers to objects as void pointers, or using discriminated unions. The problem with these two approaches is that they lose type safety. You can access elements using the wrong type and causes disastrous results at run time with no errors from the compiler.<br /><br />boost::any solves this problem. Internally boost::any uses a templates to create a wrapper class for the type you pass to it, and then create an instance of this class on the heap. It then manages retrieving the object inside using boost::any_cast safely. <br /><br />Examples:<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>#include <boost/any.hpp><br />#include <iostream><br />#include <string><br />#include <vector><br /><br />class A<br />{<br /> int value_;<br />public:<br /> A(int value) : value_(value) {}<br /> void print() const {std::cout << "A's print: " << value_ << std::endl; }<br />};<br /><br />class B<br />{<br />public:<br /> void print() const {std::cout << "B's print" << std::endl; }<br />};<br /><br />class C<br />{<br />public:<br /> void print() const {std::cout << "C's print" << std::endl; }<br />};<br /><br />int main()<br />{<br /> typedef std::vector<boost::any> MixedContainer_t;<br /> MixedContainer_t mixedContainer;<br /><br /> mixedContainer.push_back(A(1));<br /><br /> try<br /> {<br /> A a = boost::any_cast<A> (mixedContainer.back());<br /> a.print();<br /> }<br /> catch(boost::bad_any_cast& bac)<br /> {<br /> bac.what();<br /> }<br /> <br /> //you can also retrieve the object via a pointer using the <br /> //the overloaded boost::any_cast<br /> if(A* a = boost::any_cast<A> (&mixedContainer.back()))<br /> {<br /> std::cout << "I can retrieve A by pointer" << std::endl;<br /> }<br /><br /> boost::any a1 = mixedContainer.back();<br /> if(typeid(A*) == a1.type())<br /> std::cout << "last element is of A's type " << std::endl;<br /><br /><br /> mixedContainer.push_back(B());<br /> mixedContainer.push_back(C());<br /><br /> //push a string<br /> std::string str("Hello World!");<br /> mixedContainer.push_back(str);<br /><br /> void print_any(boost::any& element); //declaration<br /> std::for_each(mixedContainer.begin(),<br /> mixedContainer.end(),<br /> print_any);<br /> return 0;<br />}<br /><br />void print_any(boost::any& element)<br />{<br /> try<br /> {<br /> A a = boost::any_cast<A> (element);<br /> a.print();<br /> }<br /> catch(boost::bad_any_cast& ex)<br /> {<br /> std::cout << "bad cast exception" << ex.what();<br /> }<br /> try<br /> {<br /> B b = boost::any_cast<B> (element);<br /> b.print();<br /> }<br /> catch(boost::bad_any_cast& ex)<br /> {<br /> std::cout << "bad cast exception" << ex.what();<br /> }<br /> try<br /> {<br /> C c = boost::any_cast<C> (element);<br /> c.print();<br /> }<br /> catch(boost::bad_any_cast& ex)<br /> {<br /> std::cout << "bad cast exception" << ex.what();<br /> }<br />}<br /><br /><br /></code></pre><br /><br />As you can see in the previous example, we can store any type in boost::any. Boost::any preserves the type and will not let you tamper with it without knowing the correct type. You can store pointers too, but retrieving pointers is a bit tricky and I'll discuss it in a later post. For now, we are interested in the two mechanism for retrieving the values stores in boost::any:<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>template<typename ValueType><br /> ValueType any_cast(const any & operand);<br /></code></pre><br />The argument is the boost::any we want to retrieve, and the ValueType is the type of the stored value. If the type does not correspond to what is stored in boost::any, then this version of any_cast will throw a bad_any_cast exception.<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>template<typename ValueType><br /> ValueType * any_cast(any * operand)<br /></code></pre><br /><br />This overloaded any_cast takes a pointer to any, and returns a pointer to the stored value. If the type in the any isn 't Value_Type, a NULL is returned. There is also a version of this any_cast for const pointers.<br /><br />Note the difference between the first mechanism where an exception is thrown, and the second where a null pointer is returned. Also note that we can use any of the overloaded any_cast exception to retrieve the value by either passing our argument by reference (to use the first mechanism) or value (to use the second) as we show in the preceding example:<br /><br /><pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code> mixedContainer.push_back(A(1));<br /><br /> try<br /> {<br /> A a = boost::any_cast<A> (mixedContainer.back());<br /> a.print();<br /> }<br /> catch(...)<br /> {}<br /><br /> if(A* a = boost::any_cast<A> (&mixedContainer.back()))<br /> {<br /> std::cout << "I can retrieve A by pointer" << std::endl;<br /> }<br /></code></pre><br /><br /><br />References: <br />- Introduction to Boost by Bjorn Karlsson<br />- the boost websiteYemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-9641680636920208562008-10-08T09:53:00.001-07:002009-03-23T02:45:46.666-07:00My master's research accepted for publication in TON<span style="font-style:italic;">This paper is pretty much the jist of my master's research at Simon Fraser University, Canada. It has been accepted for publication ni the very prestigious IEEE/ACM Transactions on Networking. It is an extended version of a conference paper in ICNP. Here is the abstract and a link to it:<br /></span><br /><br />Abstract:<br /><br />Abstract—Peer-to-peer (P2P) file sharing systems generate a<br />major portion of the Internet traffic, and this portion is expected<br />to increase in the future. We explore the potential of deploying<br />proxy caches in different Autonomous Systems (ASes) with the<br />goal of reducing the cost incurred by Internet service providers<br />and alleviating the load on the Internet backbone. We conduct an<br />eight-month measurement study to analyze the P2P traffic characteristics<br />that are relevant to caching, such as object popularity,<br />popularity dynamics, and object size. Our study shows that the<br />popularity of P2P objects can be modeled by a Mandelbrot–Zipf<br />distribution, and that several workloads exist in P2P traffic.<br />Guided by our findings, we develop a novel caching algorithm<br />for P2P traffic that is based on object segmentation, and proportional<br />partial admission and eviction of objects. Our trace-based<br />simulations show that with a relatively small cache size, a byte<br />hit rate of up to 35% can be achieved by our algorithm, which is<br />close to the byte hit rate achieved by an off-line optimal algorithm<br />with complete knowledge of future requests. Our results also show<br />that our algorithm achieves a byte hit rate that is at least 40%<br />more, and at most triple, the byte hit rate of the common web<br />caching algorithms. Furthermore, our algorithm is robust in face<br />of aborted downloads, which is a common case in P2P systems<br /><br /><a href="http://www.cs.sfu.ca/~mhefeeda/Papers/ton08.pdf">Link to the paper</a>YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-67502713239478167782008-06-07T09:16:00.000-07:002010-06-25T06:53:13.343-07:00Boost interview questions- What is boost? And why is it useful?<br />- What is a shared pointer? <br />- What is the difference between shared pointer, auto pointer and intrusive pointer?<br />- How is shared pointer implemented internally? <br />- How would you convert from string to integer using boost?<br /><br /><code>#include <iostream><br />#include <string><br />#include <assert.h><br /><br />/*<br /> Implement as simple a class as possible to pass the test case below.<br /> If possible,<br /> - use only a single container<br /> - do not use a void pointer<br /> - use any stl/boost/mpl algorithms that are of use<br />*/<br /><br /><br />class cNamedVariableContainer<br />{<br />public:<br /> template <class T><br /> void manage(const std::string& name, T& varRef)<br /> {<br /> }<br /><br />public:<br /> void setValue(const std::string& namedVariable, const std::string& value)<br /> {<br /> }<br />};<br /><br /><br /><br />int main()<br />{<br /> cNamedVariableContainer nvc;<br /><br /> int myInt(0);<br /> double myDouble(0.);<br /> std::string myString("");<br /><br /> nvc.manage("int", myInt);<br /> nvc.manage("dbl", myDouble);<br /> nvc.manage("str", myString);<br /><br /> nvc.setValue("int", "43");<br /> nvc.setValue("dbl", "123.8");<br /> nvc.setValue("str", "hello");<br /><br /> std::cout << myInt << std::endl;<br /> std::cout << myDouble << std::endl;<br /> std::cout << myString << std::endl;<br /><br /> assert(myInt==43);<br /> assert(myDouble==123.8);<br /> assert(myString=="hello");<br /><br /> return 0;<br />}</code>YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-71147497261235434262008-06-06T14:47:00.000-07:002008-06-06T15:03:20.538-07:00Interview Questions -- London Finance ITI have been interviewing for a C++ software developer position at some of the UK finest investment banks and hedge funds. Here I'll share some of the questions that I was asked in a series of posts. But to be fair, I won't mention the names of those companies. <br /><br />Those are actual questions I have been asked:<br /><br />C++ Questions:<br /><br />1- When would you prefer passing a reference to a function than a pointer?<br />2- Where is the const keyword used in C++ and what does it mean in each of those places it is used?<br />3- What is a mutable variable? Why might we need one?<br />4- What is a dynamic cast? What is RTTI?<br />5- What is an exception? When would you use exceptions? And why are they better than retyrning error codes?<br />6- How are exceptions implemented in C++?<br />7- How can a function guarantee that its resouces are released if an exception is thrown in the middle? -- Use RAII.<br />8- What is an exception safe function? What are the three types of exception safety? <br />9- What is a dangling pointer? And how does it usually happen?<br />10- What is a memory leak? How would you go about fixing it?<br />11- What is polymorphism? Virtual functions? Virtual tables?<br />12- When do you need a virtual destructor? Why is it not a good idea to always use virtual destructors?<br />13- Why is it a bad idea to throw exceptions from a destructor?<br />14- What is a pure virutal function? Why might we need to use it?<br />15- When do we absolutely need a dynamic cast? What alternatives can we have to dynamic casts?<br />16- Can pure virtual functions have an implementation? Is it a good idea to give them default implementation? Why?<br />17- What is a design pattern?<br />18- Explain Observer, Singleton and Bridge design pattern?<br />19- What is an Agile development?<br />20- Why do we need operator overloading? What concerns might we have with overloading?<br />21- Assume we have four istances of the same class, A, B, C, and D. What is the minimum number of operators called for this operation A = B * C + D?<br />22- Which could be potentially faster: accessing elements of a 2D array column-wise or row-wise? i.e., traversing columns or rows?<br />23- How do you prevent an object from being copyable? When might you need to do that? And in this case, how do you prevent methods of this object from calling its copying functions? What errors might arise?<br />24- How does C++ name mangling work?<br />26- How is polymorphism implemented in C++?<br />27- Can we have static virtual methods? Why?<br />....<br /><br />rest to follow as I remember them.YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com1tag:blogger.com,1999:blog-7861216377033187791.post-23395239861094812422008-04-03T13:02:00.000-07:002008-05-15T15:52:46.674-07:00كان زمانجلس بوقاره وشيخوخته يروي لنا قصة حياته من بدايتها... كيف أنه كان طفلاً صغير لا يستطيع فراق أمه أو الإنفصال عنها للحظات، وظن حينها أنها جزء من حياته وستظل كذلك إلى الأبد... لكنه كبر وشب عن الطوق، وقضى الله على أمه الموت فماتت، لكن كان له عوضه بإخوة أقرب إليه من قلبه بين ضلعيه، كأنه معهم روح واحدة في أجساد متفرقة... أحبهم وأحبوه وظن أن لن يستطيع الحياة بدونهم، لكنهم أيضاً شبوا وتزوجوا وكبروا، ثم أخذ كل منهم وجهته وسافر بعيدا عن بلدته، وبدأ حياته الجديده مع أسرته وأبناءه... ثم جاء دوره هو فتزوج وأنجب من الأبناء والبنين خمسة كالبدور، رباهم هو وزوجته وظن أن هذه هي حياته إذا، وهذه هي السعادة بعينهاً... ماذا يريد أكثر مما أنعم الله عليه به؟ بيت يقيه برد الشتاء وقيض الصيف، ويستره وأهله، وزوجة مخلصة محبه وأولاد طائعين ، وبسطة في العيش والمال... لكنهم، أيضا، شبوا وكبروا كما شب وكبر هو قبلاً... جاء للبنات من يرضين دينهم وخلقهم فزوجهن جميعاً وذهبن من بين يديه، ثم تزوج أبناءه أيضاً وغادرو العش الذي مافكر يوماً واحدا في أن أيا من ساكنية يستطيع التنفس خارجه... غادروه ليبدأوا هم أيضا حياتهم الجديده... لم يطل الزمان على عشه الجديد، فقضى الموت على حبيبة قلبه وشريكة عمره فماتت، وبقي هو ينتظر رحمة الله ودوره في المغادرة إلى عالم أكثر نقاء وخلوداً، عالم تدوم فيه اللذات... <br /><br />ترى في عينيه خبرة في الحياة وحقيقتها، وتحس من كلامه قناعته بحياته وبما أنجر وعذره لنفسه في ما قصر، وإستعداده للموت، بينما أنت الشاب تفزع من مجرد ذكر هذه الكلمة المخيفة المريبه، غير مدرك بأنه كان أيضا شابا مثلك وفي سنك يخاف الموت ويخشاه ويريد من حياته أكثر ما أعطته، لكنه اليوم قنع بعد أن عارك الحياة... أنت تخاف النهاية لأن لديك من العمر فسحة، ومن العمل والمتستقبل الكثير إن كتب الله لك أن تعيش كما عاش، لكنه قد تلذذ بكل لذات الحياة، ثم تجرع مرارة فقدها، وعارك الحياة ليعلم في النهاية أن لكل بداية نهاية، فأصبح قلبه خالياً من كل شئ إلا من رحمة الله. <br /><br />هكذا هي سنة الحياة، لا شئ يدوم، جميلاً كان أو قبيحاً... وحياتنا لا تقاس بالأنفاس التي نجترها، والتي يجترها كل حي، وإنما بأعمالنا التي نقدمها لإصلاح دنيانا كخلفاء لله في أرضه، وبين يدي آخرانا... لا تجعل من عمرك عبئأ على عاتقك، تريد الخلاص منه بأي وسيلة، فعمرك رأس مالك، فلتكن أكثر حرصا أين وكيف ولمن وعلى من تصرفه، ثم بعد هذا كله فكر في إستمثار جزء كبير منه لرحلة طويلة وسفر شاق، لحياة الخلود... ومع هذا فلا تنس نصيبك من الدنيا ولكن قدر نعمتي الصحة الصحة والفراغ التي أسداها الله عليك... <br /><br />إن تنعمت بلذة فإعلم أن لها نهاية فأحسن إستخدامها، وإن أصبت بمصيبة فإعلم أن لها نهاية أيضا فهون عليك. <br /><br />هاقد ولى رمضان، تاركا ألسنة البعض معقودة من شدة الحزن، وألسنة آخرين تقول (رمضان ولى هاتها ياساقي ... مشتاقة تسعى إلى مشتاق)، وكيفما كان حالي أو حالك، لتكن هذه بداية جديدة لحياة أكثر عطاءً وحيوية، ولننظر إلى حياتنا كفرص على ظهر الأرض لفعل شئ بدلا من النظر إليها كعبء ثقيل نشعر بالسعادة مع كل جزء نقتله منها.. إن كنت طالباً فإجعل من تعليمك جهاداً و إملا قلبك وعقلك بالعلم، وإن كنت موظفاً أو عاملا فلتكن حياتك نموذجاً للعالم الذي تحلم به وتريد أن تراه... إن كان لديك وقت فراغ فلا تفكر بطريقة لقضاءه والتخلص منه، بل إنظر إليه ككنز يمكنك إستخدامه وإضافته إلى رصيد حياتك الذي يتناقص مع شروق كل يوم جديد، مالم تضف إليها أنت رصيدا آخر يجعل من الوقت الباقي لحياتك أحد المقاييس لحياتك وليس المقياس الوحيد. <br /><br />أتمنى من الله أن نكون ممن غادرنا شهر رمضان بلا ذنب، وعيدكم مباركYemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-68168133995899923382008-02-15T14:00:00.000-08:002008-05-15T15:47:31.265-07:00أن تحترق<span style="font-weight:bold;">أن تحترق هو أن تحس بحرارة في أحشائك، وبرد في أعضائك وأطرافك، وأن تعالج غصة في حلقك لا تقوى على الخلاص منها... أن تحترق هو أن تعد الثواني وتستمع لعقارب الساعة تقرع شوكاتها على الجدار، هو أن يطول الليل ويظلم كنفسك التي بين جنبيك.... أن تحترق هو أن يبلغ بك اليأس درجة تصبح فيها حياتك عبئا ثقيلاً عليك تتمنى الخلاص منه، وعندها تتمنى للحظة ما لو يقف كل شئ، الحركة والسيارات والضوء والضجيج والحيوانات والحشرات وأن يقف الكون... تتمنى أن لا تدور الأرض... أن تحترق هو أن تتمنى أن تغمض عينيك ثم تفتحها وترى نفسك في عالم آخر غير عالمك الذي تعيشة... أن تحترق هو أن ترى الزمان كذبة كبرى، لأن دقيقتك ليست كدقيقة الناس وساعتك تمر عليك كدهر بائس... لو يقاس الدهر بعذابات المتألمين اليائسين الكادحين أمثالك لإبيضت رءوسهم قبل المشيب<br /><br /> <br /><br />ما أتعسك وأشقاك وما أشد عناءك أيها المسكين. هل وصل بك اليأس حد تمنى الموت؟ أنت وحدك جزيرة لا يعيش بها إلا أنت فأعمرها بما شئت، أعمرها باليأس تعش حياتك يائسا أو أعمرها بالياسمين إن شئت تعش حياة حبورا ونشوانا في غبطة وسرور دائمين.... أن نور نفسك هو النور الوحيد في ظلمتها، هو نهارك، فقليلا من الأمل يبلغك شط الآمان، النفس يتبعه آخر والدقيقة تتلوها أخرى وما حياتك وحياة كل مخلوق على ظهر البسيطة إلا هرولة نحو مصير محتوم، كلنا سيجري وكلنا سيقز القفز تلك إلى المجهول، الموت لكن هناك من يهرول نحو النهاية مدركا تمام الإدراك أنه واصل لا محالة فيجعل من رحلته سفرا جميلا يعيشه ولا يستثقله، وهناك من يتعثر في الطريق من شدة اليأس ومن علمه بالنهاية فيتمنى لو تهرول النهاية إليه قبل أن يصل إليها فلا تكن من الصنف الثاني<br /><br /> <br /><br />حياتي فقدت كل معانها، لم أعد أعرف سببا واحدا للإستيقاظ كل صباح، أراني أكرر ما عملت كل يوم، وأفعل ما يفعل الآخرون علي أجد يوما تعريفا لنفسي أو ماهيتي أو لماذا أنا؟ بل لعلي أعرف يوما ما من أنا ومن أكون؟ أرى كل يوم يجعلني أقل حيوية، لا أطيق النظرإلى ما يستمتع الناس بالنظر إليه.... لا أطيق الأطفال... منظر الطفولة والبراءة يقززني وليس له أي معنى في قاموسي، كما أني لا أرى ما يراه الآخرون من جمال الحياة؟ كيف يكون الجمال داخلي كما تحدثني؟ إن كان الجمال في أنفسنا فلم نبحث عنه في الزهرة الأنيقة، والمرأة الجميله والمنظر الجذاب واللحن العذب؟ لم لا نجلس مع أنفسنا مثلا في غرفتنا، نغلق كل نوافذها وفي الظلمة الحالكة نجعل شعاع النور في أنفسنا وجمالنا الداخلي يضئ حياتنا؟ كذب كل ما يقولون... حياتنا ليست جميله بل كارثية بكل ما تحمل الكلمة من معنى، رحلة معاناة من المهد الى اللحد، نعمل ونكد أنفسنا وعقولنا في تمثلية يلعب كل من دوره ببراعة لأننا لا نصدق للحظة واحدة أننا ممثلون، لكنك إن كنت مكاني وتحترق مثل ما أحترق لرأيت قبسا من الحقيقة: حياتنا كذبة كبرى، وتراجيدية لا تنتهي، والفرق الوحيد بيني وبينك هو أنني أدرك ذلك بينما تنكره أنت<br /><br /> <br /><br />بل حياتك أنت وحدك كذبة كبرى وحياة كل إنسان هي ما يعيشه... أتظن شخصا تحت جهاز التنفس الإصطناعي لسنوات حي؟ الحياة ياصديقي لا تقاس بعدد الأنفاس التي نتجرها أو السنوات التي نعيشها وإنما ماذا نفعل بها... لكي تدرك لحياتك معنى يجب عليك أولا فهم ماهيتها وماذا تكون: حياتك وحياة كل إنسان على وجه الأرض هي ما نفعله في فترتنا القصيرة عليها، فإجعل من حياتك سمفونية تطرب الأسماع، أو شمعة تحترف لتضئ للآخرين دروب حياتهم... ثم ليكن هدفك الأسمى في هذه الحياة مرتبط بالعلوي، بالله، وليس بشخصك أنت، فروحك التي بين جنبيك ماهي إلا وديعة عندك إلى حين.... الجمال الخالد والمعنى الحقيقي لحياة الإنسان يجب أن لا يرتبط معنىً دنيوي ينتهي مع حياة الشخص، كالمال والجمال والشهرة والنجاح، بل يكون مرتبطا بالله الذي له الخلود أبد الدهر، عندها يكون معنى حياتك خالدا... لن تشعر بطمأنينة القلب وراحة البال إن كان سببها دنيوي لأن كل دنيوي زائل، لكنك إن غرست في ذاتك حب الله، وإشتشعرت عظمته، وخفت غضبه ورجوت رحمته فإن عندئذ تكون قد قنعت بأن حياتك على ظهر هذه البسيطة ماهي إلا مقدمة وإختبار لحياة أكثر خلودا، وستعمل حينها على بلوغ معنى الحياة اللازائل بعد موتك، ولن تلهث نحو النهاية بعدها، بل ستخطو خطوات واثق نحو البداية الحقيقه...</span>YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-77893202663189458292008-01-01T13:41:00.000-08:002008-05-15T15:53:31.730-07:00صناعة القائد: وأما من جائك يسعىروي أن رسول اللّه صلى اللّه عليه وسلم كان يوماً يخاطب بعض عظماء قريش، وقد طمع في إسلامه، فبينما هو يخاطبه ويناجيه إذ أقبل عبدلله ابن أم مكتوم، وكان رجلاً أعمى ممن أسلم قديماً، فجعل يسأل رسول اللّه صلى اللّه عليه وسلم عن شيء ويلح عليه، وود النبي صلى اللّه عليه وسلم أن لو كف ساعته تلك، ليتمكن من ذلك الرجل طمعاً ورغبة في هدايته وعبس في وجه ابن أم مكتوم وأعرض عنه، وأقبل على الأخر، فعاتبه الله تعالى بقوله: (عبس وتولى أن جاءه الأعمى * وما يدريك لعله يزكى)... أدبه ربه بأحسن أدب وأعظمه فأحسن تأديبه، وجعله مفخرة الإنسانية جمعاء، ومثالها الأعلى في القيادة والريادة، . كان صلى الله عليه وسلم لا يفرق بين سيد قرشي وعبد حبشي. كلهم سواء في الإسلام فزوج متبناه زيد بن حارثه، من سيدة قريش زينب بنت جحش، وأسدى على سلمان الفارسي المللوك في الجاهلية هوية (سلمان منا أهل البيت)! القادة الحقيقيون لا يفرقون بين تابعيهم أو يحقروا شأنهم ولا يقفون عند مجرد إصدار الأوامر والنصح للآخرين بل ويتجاوزونه إلى حد الإعتقاد بخيريتهم و العفو عن خطاياهم والإشفاق عليهم منها وتحسس مواقع الخير في نفوسهم وتنميتها. <br /><br />غالبا ما تنتشر بين بعض القادة ثقافة الطهرانية لذواتهم ودونية الآخرين وتخلفهم، فهم المتعلمون والمتنورون وغيرهم رعاع جاهلون ، عالة على المجتمع، وسلم يستعمله هؤلاء "القادة" (إن صحت تسميتهم بذلك) للتسلق نحو إرضاء كبرياءهم وإعلاء شأن أنفسهم... عندما نؤمن بخيريتنا وشيطانية الآخرين، أو عدم إحترامهم كأنداد لنا، فلن نكون قادة لأنه ببساطة لن يتبعنا أحد. وعندما نعتزل الناس لأننا أطهر منهم روحا، أو أذكى منهم عقلا، فإننا نكون قد إخترنا لأنفسها أسهل الطرق للهروب من واجبات القيادة وأيسرها مؤنة... <br /><br />ألاحظ كثيراً بين طبقة مثقفينا ألسنة سليطة على أوضاعنا في بلادنا حتى أنها لتبدو ظاهرة متأصلة في تراثنا أن نفخر بكوننا أفضل من بني جلدتنا وأطهر منهم روحا وأطيب قلبا. بل ويتجاوز ذلك إلى حد توصيف الداء والدواء وتشخيص الأخرين بأبشع العلل والأمراض، فهم (الثعابين) ونحن الراقصين على رؤوسهم، وهم (شعب جاهل ومتخلف) ونحن (ذوي العقول التقدميه والمتنوره)، وهم (رعاع الناس) ونحن فخرهم وزينتهم، وما ننساه أو نتناساه دائما أن (أنفك منك ولو كان أجدع)، وأن لا أحد يملك الحق للحكم على أحد.... قد يكون القائد محقا بإيمانه بضرورة تغيير الآخرين وتثقيفهم والإرتقاء بهم إلى مستوى يمكنهم من رؤية ما يراه، لكن إحترام الناس والعطف على ضعفهم ونقصهم وأخطائهم هو الطريق الأوحد لتأليف القلوب حول القائد... كونك قائداً لا يعني أنك أفضل ممن يتبعونك، فقد يكون منهم من هو أذكى منك وأصلح للقيادة، وإن كان الله قد عاتب نبيه وحبيبه على الإعراض للحظات عن رجل أعمى، فكيف بمن يحقرون أممهم ويزعمون بعدها أنهم قادة مشفقون عليها من عللها ومخلصون في أعمالهم للرقاء بها. إن كان الله قد أنعم علينا بالمال أو الجاه أو السلطان أو العلم، فيجب أن لا ننسى أننا جزء من نسيج أمتنا، بحياتها نحيا ومن كل خلية وعضو فيها نستمد طاقتنا وقوتنا. <br /><br />القائد العظيم يشعر كل من حوله أن قضيته قضيتهم، وهمه همهم، ليس لأنه قرأ ذلك في كتاب أو تعلمه من أستاذ بل لأنه يؤمن به إيمانا عميقا متأصلا في نفسه، فيعامل الآخرين سواء، مهما كانت منازلهم في نفسه، وعندها يشعر كل من حوله أنهم ليسو مجرد آداة في آلة لا يفهمون فيها شيئا، بل أنهم جزء لا يتجزأ من جسد حي إذا إشتكى منه عضو تداعى له سائر الجسد بالسهر والحمى... <br /><br />ولكي يكون الطرح أكثر واقعية، فأحب أن أختم بهذه النقاط التي لن أتبعك (أو يتبعك غيري) بدونها...<br />لكي أتبعك:<br />* عاملني بإحترام<br />* علمني ما لا أعلم<br />* أقل عثرتي وتجاوز عن هفواتي وأخطائي<br />* أصغ إلي عندما أتحدث وتكلم معي <br />* قل لي الحقيقة، وعاملني كند، ولتكن أفعالك إنعكاسا لكلماتك<br />* كن كريما بوقتك، وخبرتك، ومعارفك، عندما أحتاج أيا منها عندها فقط أتبعك بعقلي ونفسي وأضحي من أجلك ومن أجل ما تدعوا إليه.YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-56314132596689264562007-12-26T00:19:00.000-08:002007-12-26T00:48:12.308-08:00OS/Architecture notes...<strong>1- What is a segmentation fault, and how does it occur?</strong><br /><br /><br />First, a word about memory protection. Modern operating systems provide the means to control access to the memory system. A user process should not be allowed to modify its read-only text section. It should not be allowed to read or modify any of the code and data structures in the kernel. It should not be allowed to read or write the private memory of other processes. And it should not be allowed to modify any virtual pages that are shared with other processes unless all parties explicitly allow it (via calls to explicit interprocess communication system calls). Each process usually has its own private virtual memory space, which translates to disjoint or safely shareable physical memory pages. <br /><br />Remember that in virtual memory systems, we have a Page Table, which contains Page Table Entries (PTEs). A page table entry contains the base address of a physical page in DRAM, or an allocated page on the desk.<br /><br />Enough of Virtual Memory. The operating system adds three permission bits to PTE entries, called SUP (supervisor), Read, Write bits, and they correspond to root, read, and write privliges respectively. If during the address translation the calling process violates any of those priviliges, it'll generate a protection fault (i.e., segmentation fault)....<br /><br />Take this example<br /><blockquote><br /><em>int main()</em><br /><em>{</em><br /><em> char* p;</em><br /><em> char c;</em><br /><em> </em><br /><em> p = (char*) 0;</em><br /><em> c = *p; //generates seg fault<br />--(1)</em><br /><em>} </em><br /></blockquote><br />The line at (1) generates a seg fault because it is trying to read location zero, and when the OS checks, it can't find a page allocated at location 0, and generates a segmentation fault.<br /><br />p.s. This was a really crude descrition, so don't rely on it completely.... Should allow you to google it better, at the very least.<br /><br /><strong>2- How do you detect if an overflow happened in adding two unsigned integers?</strong><br /><br />If the result is less than any of the operands, an overflow has occured in the case of unsigned addition. If both x and y less than 2^w (where w is the number of bits, we have no overflow). But s = x + y ==> s >= x (or y). So if s is less than x, or s is less than y, then we have an overflow. This is because in case of an overflow, s = x + y - 2^w (wraps around). THis is because we had a carry on of one, which we can't store, so we decrement the sum by 2^w. And since y < 2^w, y - 2^w < 0, which means s < x, hence overflow occured.<br /><br /><strong>3- I get a stack overflow error at run time, but I can't spot any large stack allocations?</strong><br /><strong></strong><br />C++ allows you to delcare variables anywhere in the code (almost), unlike C which only allows you to delcare variables at the beginning of a block of instructions. So check large array allocations in the middle of your function/block. For example:<br /><em><em></em></em><br /><em><em></em></em><br /><em>void myFunction(int<br />iTinyFourByteInteger)<br />{<br /> int tinyInt1;<br /> int tinyInt2;<br /> <br />int tinyInt3;<br /> ....<br /> ....<br /> ....<br /> //after tens of lines of code<br /> int largeArray[65536];<br /> <br />}</em><br /><p>What the compiler did was to inspect your code first, push all local variables on the stack, regardless of where they were declared, then start the executing the first instruction in the function. If you're stepping through a debugger, you won't be able to spot the problem because it'll crash at the opening brace.</p>YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-41562676484207986342007-12-23T23:16:00.001-08:002007-12-23T23:34:16.617-08:00Networking Interview Questions Cont.These are some of the commonly asked, and not very well answered, questions:<br /><br /><strong>What are the main differences between TCP/UDP?</strong><br /><strong></strong><br /><ul><li> UDP has no connection establishment. TCP has three way handshaking (send SYN, receive SYN-ACK, send ACK), while UDP has no connection establishment, hence called connectionless transport protocol</li><li>TCP keeps Connection state at the end systems, UDP doesn't. The This connection state includes receive and send buffers, congestion control parameters, and sequence and acknowledgment number parameters. </li><li>TCP has a 20-byte segment header overhead, while UDP has 8 segment header overhead.</li><li>TCP has a regulated send-rate. TCP has a congestion control mechanism that throttles the sender when one or more links between sender and receiver becomes excessively congested. This throttling can have a severe impact on real-time applications, which can tolerate some packet loss but require a minimum send rate. On the other hand, the speed at which UDP sends data is only constrained by the rate at which the application generates data, the capabilities of the source (CPU, clock rate, etc.) and the access bandwidth to the Internet. </li></ul><p><strong>2- What is Connected UDP?</strong></p><p>Usually when creating a UDP socket we say:</p><p>socket = socket(PF_INET, SOCK_DGRAM, 0); //socket(family, type, proto)<br /></p><p>Then to send using this socket we use:</p><p>ssize_t sendto(sock_fd,<br /> void* buf, size_t nBytes,<br /> int flags,<br /> const struct sockaddr* to,<br /> socklen_t len); //ssize_t is how much data the OS accepted to send.</p><p>If we use a udp socket in a call to connect, we create what is called connected UDP. This simply tells the OS the address of the peer; no handshaking is necessary and no data is sent to establish that the peer exist (i.e., no data is sent as a result of calling connect() on a udp socket. Why use it? If we communicating with a single peer, this might be useful since: </p><ol><li>We can call sendto() with null destination address</li><li>We can use write() and send()</li><li>We can use read() and recv(), which will return only data from the remote peer we connect()ed to.</li></ol><p> </p>YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-4921529152880438142007-10-10T15:42:00.000-07:002008-05-15T15:49:18.009-07:00الحب أولاهل إستيقظت مرة في هجعة الليل تحت إشراقة القمر ليلة كماله لترى عالما آخر لم تعتده؟... تحس بنسيم السحر العليل يدغدغ مشاعرك وأحاسيسك، فتشعر بمثل البرد يسري في أعضاءك ويهز كيانك... شعور غريب ربما... السكون والوحشة والروحانية والليل، تريد التعبير عما يجول بخاطرك فتعجز لأنك لم تعتد في ضجة الحياة أن ترى خلف شكليات يومك... تخذلك لسانك أو قلمك في التعبير عن ما تشعر به لكنك تعلم علم اليقين أن هناك بين أضلاعك قلباً ينبض، وروح تتوهج، وشئ أكبر من هذا القفص الصدري ومضخة الدم والأوردة والشرايين...هناك عاطفة لا تعلم كنها، لكنك تحس بها،،، قد تكون عاطفة حزينة أو سعيده،، قد تكون شوقا أو حنينا أو عاطفة لا تعلم لها تعبيراً،،، قد تكون حباً أيضا. عن الحب... عن الحب أولاً، مع الحب سيكون حديثنا... عن صيفة الساخن وشتائه القارس وخريفة الشائخ... <br /><br />سمه داءًا أو إكسير حياة، لكن الحب حقيقة لا خيالاً ، فالله عز وجل خلقنا بشرا بقلوب تهفوا لقلوب، وبأرواح تأتلف بأرواح، وهو من أقوى العواطف البشرية بناء وتدميرا، ومن أضعفها وأخفاها سريانا وبيانا،، يختبئ في اللحن الشجي من موال عذب، وفي رعشة اليد الحانية من ذات قلب منهك، أو نظرة ناعسة من عين فاتنة أو إبتسامة مومضة من ثغر أغر، أو دمعة صادقة على خد متوهج بنار الوجد...تكون معافاً سليما حتى يأتي على قلبك الحب، فيحيل حياتك جنة أو جحيماًً... فما الحب وما حقيقته؟ <br /><br />لم أكن لأقف هنا ياصديقي لأتفلسف عن كيف أن الحب شرارة بين الرغبة والإمتناع ويموت عند إنعدام أحدهما، أو عالم بيولوجيا أصلع الرأس يرى في الحب مجرد مخدر يجعل من عملية بيولوجية شيئا جميلاً لضمان إستمرار الحياة على وجه الأرض، أو شاعراً يرى الحب لقمته وشربه وعيشه وشمسه وقمره. لست شيخاً فأسفه الحب وطيش الشباب، ولست عالماً فأفتي في الحب تحريما وتحليلاً، كما أنني لست طائشاً فأتمرد على الدين والعادات والتقاليد بإسم الحب...ولكني أحب أن أحدثك حديث الخليل خليله، عسى وربما تجد أو أجد آذانا صاغية وقلوبا واعية... فالمحبون كُثر، وبلاوى الحب وعذاباته تشكل أغلب مشاكل الشباب في أي زمن أو مكان، خاصة في مجتمعنا اليمني حيث يقرن الحب مع تفاهات المراهقين ومعاكسات الشباب التائه. <br /><br />هل الحرم الحب، تسألني؟ لست عالما لأفتيك، لكني أرى أن الله ما كان ليعاقبنا على شئ وضعه وصنعه في قلوبنا، ثم ألم يجعل الله حب الرجل زوجته حلالا؟ ألم يسئل النبي صلى الله عليه وسلم عن أحب الناس إليه فأجاب "عائشة"؟ ألم يدع ربه (صلى) بقوله "اللهم هذا قسمي في ما أملك فلا تؤاخذني في ما لا أملك" –أي العاطفة نحو نسائة، صلى الله عليه وسلم؟ من حرم الحب والحديث فيه؟ ألم يتغن به الفقهاء والشعراء، والعلماء؟ كتب في العشق والحب ثلاثة من أعلام الإسلام: إبن حزم، وإبن القيم وإبن داود كتبا لقنوا فيها المحبين فنون العشق... ثم هل سمعت بصاحب الحجازيات – الشريف الرضي – والذي كان إمام الحج في عصره ونقيب الأشراف ومن قضاة المظالم... نعم لم يكن حبهم غراماً، وكان عذريا ولم يتغنوا بغير العفيف من القول، وكان حبهم لأزواجهم وما أحل الله لهم فقط ، لكنهم مع ذلك لم يجدوا في الحب بأساً، فالحب ليس جريمة بحد ذاتها... "مافي الحب شئ، ولا على المحبين سبيل، إنما السبيل على من ينسى في الحب دينه، أو يضيع خلقه، أو يهدم رجولته أو يشتري بلذة في الدنيا عذاب ألف سنة في جهنم"، كما قال أديب الفقهاء وفقيه الأدباء الشيخ علي الطنطاوي رحمة الله عليه . ثم أما أحسست يوماً مشاهد البؤس فبكيت أو حزنت، ثم رأيت مناظر الجمال فإنفتحت نفسك وأنشرح صدرك؟ أما بكيت وفرحت وحزنت وإكتئبت؟؟ كل هذه عواطف بريئة ومغروسة في ذواتنا, وكذلك الحب. الحب ليس إلا عاطفة أخرى كهذه العواطف...الإنسان مخلوق عاطفي بطبعه، والمحبون هم القادرين على الولوج في أعماق النفس البشرية للبحث عن قلوبهم، فإن كنت وقعت في الحب يوما أو صادف أن صارحك به قريب أو قريبة لك، فهون عليك وإرحم ضعفهم وولع قلوبهم، ولا تقس على المبحين<br /><br /><br /><br />لكن ليس كل الحب حلالاً، الحب في حدود الدين والشرع مرغوب فيه وضروري لسعادة الإنسان، لكن ماذا عن الحب خارج نطاق الزوجية؟ لا شك أن هذا النوع من العاطفة مجلبة للخطر لكلا الطرفين... لا يعطي الأب لإبنه قنبلة يلعب بها، لأنها قابلة للإنفجار في أي وقت مهما كانت إحتياطات السلامه، وكذلك الحب، فلا يمكن أن يبحث عنه الشخص بنية (أريد أن أحب وأعشق) ثم يشكوا بعد ذلك من لواعج الشوق ونار الوجد، وتقوده عواطفه أو عواطفها بعد ذلك للدخول في دائرة المحظور شرعا وتقليداً... الحب لا يوجد بالبحث عنه لكنه يجد الشخص، وإن حدث ووقع في قلب شخص ما حب إنسان آخر فأسلم طريق وآمنه وأحسنه وأحله هو الزواج، أو اللاحب، فلا فائدة عقلاً ولا شرعاً في حلقة مفرغة أخرى من مجنون فلانه أو مجنونة فلان... لا أقول وعود الزواج المعسوله أو الخطط الهلاميه ولكن إستعمال العقل قبل العاطفة... إنه الإبتعاد عن معالجة القنبلة الموقوتة قبل قراءة دليل الإستعمال. وأحب أن أؤكد هنا على حقيقة أومن بها شخصياً فقط ، وهو أن الحب لا يوجد من نظرة أولى أو من لقاء عابر أو إنبهار وقتي ينتهي بمرور الأيام... الحب الحقيقي هو رؤية الخير في غيرك، والشعور بالخصائل التي تكمل من كيانك وتشعرك بأن من تحب هو جزء من كيانك وهذا لا يتأتى إلا بالعشرة والصحبة، حلوها ومرها، وأسلم طريق لصحبة كهذه هي عشرة الزوجية. أما الحب كما يعرفه معظم شبابنا للآسف فليس الحب ذاته وإنما هي فكرتهم عن الحب، وصور تكونت في عقولهم عما يعتقدون انه الحب... يظل حلما هلاميا حتى تشرق عليه شمس الحقيقه فيذوب ذوبان الثلج ... صحيح قد يتعلق الإنسان بآخر دون أي روابط، وذلك لمجرد الإحترام والإفتتان بهم، لكن لدينا دائما القدرة على تجنب هذه الحالات بالإبتعاد عنها من البداية خاصة في حالة التأكد من أن هذه المشاعر لن تفضي لشئ ناحج. كونوا بحب دوماً.YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-74387767607991152542007-10-05T00:51:00.000-07:002007-10-05T00:54:19.563-07:00Explanation of Duff's deviceThis is a neat and informative explanation of Huff's Device. A famous optimization using loop unrolling. Notice that Huff's device was originally developed to avoid "many" loop branching when writing to a serial I/O port, so it is not a YAI of memcpy.<br /><br />------------<br /><p> [Someone asked for some more explanation on Duff's Device, which at first glance looks like it couldn't even be parsed correctly. This was my reply.] </p><p> It's a poser, isn't it? </p><p> There are a several different issues to understand. </p><p> One is that, as far as the compiler is concerned, the formal syntax of a switch statement is <em>not</em> </p><p> </p><pre> switch ( expression )<br /> {<br /> case constant-expression :<br /> statement-list<br /> break ;<br /><br /> case constant-expression :<br /> statement-list<br /> break ;<br /><br /> ...<br /><br /> default :<br /> statement-list<br /> break ;<br /> }<br /></pre> <p> Rather, the syntax is simply </p><p> </p><pre> switch ( expression )<br /> statement<br /></pre> <p> where the statement can either be a single statement or a brace-enclosed list of statements. As you can imagine, this is the same sort of syntax specification as is used for <tt>if</tt>, <tt>for</tt>, and <tt>while</tt> statements. </p><p> Furthermore, the syntax rules for statements say, in effect, that any statement (anywhere) can be “labeled”, either with a goto label (that is, a label that can be the target of a <tt>goto</tt>) or a case label. </p><p> What this means so far is that the case labels in a switch statement do not, strictly speaking, have to be immediately within the outer set of braces that enclose the body of the switch statement; they can instead be hiding inside inner, nested blocks. </p><p> The next question is, if the case labels do not have to be immediately within the outer braces of the switch statement, how does the compiler find them and match them up? There are various ways to answer this, but perhaps the simplest and most convincing is to say that the compiler implements case labels in a similar way as it implements goto labels, and that a switch statement is really a sort of “computed goto”. </p><p> This is a bit of an oversimplification, because a <tt>goto</tt> can jump around to anywhere within a function, whereas case labels must always be somewhere within (if not immediately within) an enclosing <tt>switch</tt> statement. But the essential point is that the compiler simply does not notice that a case label might be “hiding” in a nested block within the body of the switch statement. </p><p> If you really want to understand this, it's worth discussing a few more points. You may not have realized it, but in many languages, including C, it is legal (though ill-advisable) to use a goto to jump into the body of a loop. For example, this code: </p><p> </p><pre> int i = 7;<br /> goto inside;<br /> for(i = 0; i < 10; i++)<br /> {<br /> inside: printf("%d ", i);<br /> }<br /></pre> <p> prints “7 8 9 ”. The related code </p><p> </p><pre> i = 42;<br /> goto in2;<br /> for(i = 0; i < 10; i++)<br /> {<br /> in2: printf("%d ", i);<br /> }<br /></pre> <p> prints “42 ”, and the related code </p><p> </p><pre> i = 42;<br /> goto in3;<br /> for(i = 0; i != 10; i++)<br /> {<br /> in3: printf("%d ", i);<br /> }<br /></pre> <p> runs practically forever, printing thousands or billions of numbers. </p><p> I must emphasize that there are vanishingly few, and perhaps no, reasons why you would ever want to jump into a loop like this. It's sort of an accident that it's possible at all, and anyone who cares about programming style will assert that this questionable freedom is one you would never want to make use of. (They're right, too: this questionable freedom <em>is</em> one you would never want to make use of.) However, thinking about how a <tt>goto</tt> can jump into a loop may make it easier to imagine what's going on when a switch statement causes a jump to a case label buried in a nested inner block. </p><p> Another point worth mentioning concerns the question of why compilers are written like this in the first place. Why <em>is</em> the official syntax for the switch statement simply </p><p> </p><pre> switch ( expression )<br /> statement<br /></pre> <p> rather than the more obvious, explicit syntax which I started this discussion by saying was not the official one? If the explicit syntax were the official syntax, it simply wouldn't be possible to write questionably-valid, impossible-to-understand code like Duff's Device. </p><p> The answer -- which may sound somewhat lame, but anyway -- has to do with making the compiler easier and cleaner to write. There's a whole bunch of machinery having to do with brace-enclosed lists of statements, and it's nice to be able to reuse that machinery in any context where a control flow statement might use a brace-enclosed list as its body. In fact, it's so nice to re-use that machinery that it's worth doing so even though that means the machinery has to be augmented with some additional complexity to handle interspersed case labels, complexity that ought to be needed only when the block being parsed is in fact the body of a switch statement. </p><p> In fact, whenever people say that a surprising feature was accidental, not intended, that it simply “fell out of” the chosen implementation of some system, this is exactly the sort of case they are talking about. It was never intended, I don't think, for case labels to be accepted (let alone properly handled) within nested inner blocks. But when the decision was made to re-use the block statement handling machinery for the body of switch statements, meaning that that machinery had to learn about case labels, it meant that case labels just happened to be accepted in front of statements in the bodies of loops, as long as there was a switch statement somewhere out there for them to hook up to. And, furthermore, though I won't try to argue whether this was accidental or deliberate or an accidental result of deliberately careful coding practices, it did turn out that the case labels were not only accepted, but worked “properly”, even when they were deeply nested. </p><p> </p><center> * * * </center> <p> I'm not sure whether you were more puzzled by the syntactic and semantic implications of an interleaved loop and switch statement, or by the particular way Duff's code made use of that combination to implement a practical algorithm. But if you had questions about the latter, let's now take a look at Duff's Device itself. Actually, for clarity, I'm going to present a variation on Duff's Device, a reimplementation of the standard <tt>memcpy</tt> function. (I presume you know what <tt>memcpy</tt> does.) A straightforward, bare-bones implementation of <tt>memcpy</tt> might look like this: </p><p> </p><pre> void *memcpy(void *dest, const void *src, size_t n)<br /> {<br /> char *destp = dest;<br /> const char *srcp = src;<br /><br /> for(; n > 0; n--)<br /> *destp++ = *srcp++;<br /><br /> return dest;<br /> }<br /></pre> <p> This code works pretty well. But it's not perfect, and there are some things we could worry about, and one of those is efficiency. </p><p> A problem with the code as written is that it checks <tt>n</tt> each time through the loop to see if it's gotten down to 0. That is, if we copy, say, 1000 bytes, the running of the code will involve 1000 byte-copying operations and 1000 increment operations on <tt>srcp</tt> and 1000 more increment operations on <tt>destp</tt> and 1000 decrement operations on <tt>n</tt> and 1000 comparison operations on <tt>n</tt>. It might seem as if there's no way around this, but there is. The technique is called “loop unrolling”, and we can illustrate it with a set of alterations to the sample memcpy code above. Suppose we rewrite the loop like this: </p><p> </p><pre> for(; n > 0; n -= 2)<br /> {<br /> *destp++ = *srcp++;<br /> *destp++ = *srcp++;<br /> }<br /></pre> <p> The intent is to achieve exactly the same result, with a little less work (albeit with a little more code, which is a frequent tradeoff). Using the revised code, if <tt>n</tt> starts out as 1000, there will still be 1000 assignments and 1000+1000 increments on <tt>srcp</tt> and <tt>destp</tt>, <em>but</em> there will only be 500 comparisons of <tt>n</tt> against 0, not 1000. Also, there will be 500 subtractions where before we had 1000 decrements. </p><p> As you may have noticed, however, the revised code has a bug: it works properly only if <tt>n</tt> is even. If <tt>n</tt> is odd, it will copy too much. (In fact, since <tt>n</tt> has type <tt>size_t</tt> which is unsigned, the loop is likely to run out of control, running essentially forever instead of simply copying one byte too many. The situation is similar to our third jump-into-the-loop example, which set <tt>i</tt> to 42 but tested <tt>i != 10</tt>. But this is a side issue, so I won't digress further.) </p><p> To fix the code, we need to test for <tt>n</tt> being odd and handle the case of copying a single byte, since always copying by pairs obviously won't handle odd numbers correctly: </p><p> </p><pre> if(n % 2 == 1)<br /> {<br /> *destp++ = *srcp++;<br /> n--;<br /> }<br /><br /> for(; n > 0; n -= 2)<br /> {<br /> *destp++ = *srcp++;<br /> *destp++ = *srcp++;<br /> }<br /></pre> <p> Suppose we wanted to unroll the loop further. If we put four assignment statements inside the loop, we'll perform only <tt>n/4</tt> subtractions and <tt>n/4</tt> comparisons on <tt>n</tt> during the main loop. But now we have to worry not only about <tt>n</tt> being odd, but about it having a remainder of 1, 2, or 3 when divided by 4. So the code might look like </p><p> </p><pre> switch(n % 4)<br /> {<br /> case 3: *destp++ = *srcp++; n--;<br /> case 2: *destp++ = *srcp++; n--;<br /> case 1: *destp++ = *srcp++; n--;<br /> }<br /><br /> for(; n > 0; n -= 4)<br /> {<br /> *destp++ = *srcp++;<br /> *destp++ = *srcp++;<br /> *destp++ = *srcp++;<br /> *destp++ = *srcp++;<br /> }<br /></pre> <p> Now you're probably starting to see where this is going. It's bad enough that when we unroll the loop by a factor of 4, to reduce the overhead of decrementing and testing <tt>n</tt> by a factor of 4, we also increase the code size by a factor of 4. But it's worse than that, because the initial handle-the-remainder cases mean that the code bloat is more like a factor of 8. Wouldn't it be nice if we could eliminate a few of those <tt>*destp++ = *srcp++</tt> lines? </p><p> As the FAQ list notes, the essence of Duff's device is that it “solves the problem of handling the leftover bytes by interleaving a switch statement with the loop which copies bytes [N] at a time.” The idea is to jump into the middle of the unrolled loop, so that the first trip through the loop isn't a full trip, but one which handles the not-a-multiple-of-four leftover bytes, if necessary. This is obviously a screwy thing to do, at best -- after all, I was claiming up above that you would never want to make use of the questionable freedom C gives you to jump into the middle of a loop. We're about to do just that, and the fact that we're going to use a switch instead of a goto doesn't really make the exercise much (if any) less questionable. </p><p> Anyway, here is the interleaving trick -- that is, the essential idea of Duff's device -- applied to the memcpy example we've been working with: </p><p> </p><pre> int nn = n; /* need signed n to handle underflow */<br /> /* also assumes initial n > 0 */<br /><br /> switch(nn % 4)<br /> {<br /> for(; nn > 0; nn -= 4)<br /> {<br /> case 0: *destp++ = *srcp++;<br /> case 3: *destp++ = *srcp++;<br /> case 2: *destp++ = *srcp++;<br /> case 1: *destp++ = *srcp++;<br /> }<br /> }<br /></pre> <p> This code works, although there are two additional complications. One is that since it always uses “<tt>-= 4</tt>” in the for loop, the count will go negative in the case where the initial <tt>n</tt> was not a multiple of 4. So we must do the subtraction on a signed variable -- if we kept subtracting 4 from <tt>n</tt>, which was passed in as a <tt>size_t</tt>, it would never go negative, but would wrap around to a very large positive number, that is, a number > 0, meaning that the loop would run far too long. (This is the explanation that I was trying to avoid digressing into up above.) </p><p> The second complication is that the code as written can no longer handle an initial <tt>n</tt> value of 0. (The “official” version of Duff's device has the same limitation.) </p><p> The code I've presented here captures, I think, the essential ideas of Duff's device. For the record, I'll explain the differences between this code and the “official” version. Duff's unrolls the loop by a factor of 8, it precomputes an <tt>n</tt> which is the byte count divided by 8 (and then adjusted) so that it can use “<tt>--n</tt>” instead of “<tt>n -= 8</tt>”, and it uses a <tt>do</tt>/<tt>while</tt> loop rather than a <tt>for</tt> loop. Those three differences are all mainly cosmetic; the one big difference is of course that the “official” version of Duff's device does not increment the <tt>to</tt> pointer at all. This is because <tt>to</tt> was pointing, not at a regular memory location into which the data was being copied, but rather, to a memory-mapped device register; the bytes being copied were actually being transmitted to a display device of some kind. (The application was some kind of animation, presumably real-time, which is why efficiency mattered so much.) </p>Source: http://c-faq.com/misc/duffexpln.htmlYemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-62761714205509171652007-10-01T15:37:00.000-07:002008-05-15T15:55:54.778-07:00القيادة رؤية وعمل<p class="MsoNormal" style="text-align: right;" align="right"> <span style="font-size: 13pt; font-family: Arial;">”</span> <span style="font-size: 13pt; font-family: Arial;"> هدف بلا عمل... حلم فارغ<br />وعمل بلا هدف ... مضيعة للوقت<br />ولكن الهدف والعمل ... يغيران العالم<br />“<br />جول بيكر</span></p><br /><p class="MsoNormal" style="text-align: right;" align="right"><span style="font-size: 13pt; font-family: Arial;">لنفترض مثلا أنك تريد أن تبدأ منظمة لإنجاز هدف ما، سواء كانت منظمة طوعية، شبابية، شركة خاصة أو حتى أسرة ناجحة...ماهدفك من إنشاءها؟<span> </span>لكل شيء نقوم به هدف، ولكي يصبح الهدف حقيقة، يجب أن يعمل جميع المسئولين عنه لتحقيقه بنفس القوة والعزيمة. في هذا المقال سنركز على إثنتين من الأبجديات التنظيمية وهي كيفية بلورة الهدف والرؤية وكيفية العمل على جعلها جزءاً من نسيج وثقافة المنظمة التي تقود، وكذلك أهمية الريادة والتغلب على الخوف من الفشل وعواقب التغيير</span></p> <p class="MsoNormal" style="text-align: right;" align="right"><span style="font-size: 13pt; color: red; font-family: Arial;"><strong>الرؤية</strong><strong> </strong></span></p> <p class="MsoNormal" style="text-align: right;" align="right"><span style="font-size: 13pt; font-family: Arial;">الرؤية أو الهدف في القاموس التنظيمي تعني تصور شامل للمستقبل الذي تعمل منظمة أو<span> </span>مجموعة ما لتحقيقه ويلخص عادة في جملة أو عدة جمل بسيطة يمكن الجميع تذكرها وفهمها، وإيصالها للآخرين... كأشخاص، نخلق لحياتنا معنى بسعينا وراء عدة أهداف ننوي تحقيقها، كالوظيفة، والزواج والحياة المستقرة والطمأنينة، وبدون هذه الأهداف تفقد حياة الإنسان جوهرها ومعناها، وكذا هي المنظمات، جوهرها الروية والهدف الذي خلقت من أجل تحقيقه، والسعي لتحقيق الهدف الذي وجدت من أجله هو وحده الذي يجعل لإستمرارها معنى... الروية والهدف هي من أبجديات أي تنظيم ويجب كتابتها والموافقة عليها من الجميع، كما يجب أن تكون عالقة بأذهان كل العاملين على<span> </span>تحقيقها وراسخة في عقولهم وقلوبهم وليس القائد فقط... يخطئ البعض عندما يتصور أن بلورة وتكوين هدف المنظمة هو وحده من مسؤوليات القادة أو المؤسسين وحدهم. مسؤولية القائد ليست تكوين<span> </span>الأهداف التي يجب أن تسعى المنظمه من أجلها بل إقناع الآخرين بحتمية وجود منظمة ما ثم خلق بيئة تتمخص من خلالها أهداف مشتركة من خلال التشاور مع كافة الذين سيعملون على<span> </span>تحقيقها ، لأن الناس ببساطة لن يتبعوا أشياء لم يكونوا جزءأ منها وكل ما كان شعورهم أكبر في خلق هدف المنظمة الناشئة، كلما كانت مشاركتهم أكبر وحماسهم وشعورهم بالمسؤولية أعظم وأسمى</span></p> <p class="MsoNormal"><span style="font-size: 13pt; font-family: Arial;"> </span></p> <p class="MsoNormal" style="text-align: right;" align="right"><strong><span style="font-size: 13pt; color: red; font-family: Arial;">تكرار الرسالة والهدف</span></strong></p> <p class="MsoNormal" style="text-align: right;" align="right"><span style="font-size: 13pt; font-family: Arial;"><span> </span>الله ... نعبده... الوطن ... نحميه ... الثورة ... ضد الظلم</span></p> <p class="MsoNormal" style="text-align: right;" align="right"><span style="font-size: 13pt; font-family: Arial;">كلمات مازالت عالقة بذهني بعد أن ردتتها لإثني عشر عاما في طابور الصباح كل يوم في مدرستي في اليمن... تلخص هذه اللكمات القليله الرسالة المتوخاه من طالب العلم وهدفه الأسمى في طاعة الله والذود عن الوطن ومكتسباته، وأمثال هذه الشعارات تتردد كثيرا في الأناشيد الوطنية لكل بلدان العالم تقريبا وتلقن للصغار في مدارسهم حتى تصير جزءا من تكوينهم الثقافي والحياتي... كلمات كأي كلمات لكنها تحمل رسالة وهدف أمة، وتكرر كثيرا حتى الملل..</span></p> <p class="MsoNormal" style="text-align: right;" align="right"><span style="font-size: 13pt; font-family: Arial;">عندما وقف النبي صلى الله عليه وسلم في عرفات في حجة الوادع يرسم لأمته معالهم رسالتها وهدفها ب "أوصيكم بالنساء" و "كل المسلم على المسلم حرام" وغيرها الكثير من الرسائل الهامه، ردد <u>ثلاثا</u> بعد كل وصية "ألا هل بلغت؟؟" وفي كل مرة يجيب الصحابة بأي نعم..، هنا تتجلى عظمة القيادة في شيء بسيط هو التكرار... تكرار الرسالة, والهدف بل وحتى تكرار الأشياء الروتينية أكثر من مرة من أهم الأشياء التي يقوم بها القادة، لسبب بسيط جدا وهو أن الناس ينسون، وينشغلون بأشياء أخرى حياتية أو حتى متعلقة بأعمالهم التنظيمية و ينسون النقاط العريضة لما يقومون به، وإذا أردت أن تتذكر فلخص لفريقك مثلا أو لأصدقائك عدة نقاط ثم إسألهم عنها في لقاء قادم, ولا تيأس إن لم تجد من يتذكر منهم شيئاً مما قلته، لأن الذنب ذنبك لعدم تكرارها بما فيه الكفاية... تكرار الرسالة أيضا يذكر أعضاء منظمتك أو مجموعتك أنهم جزء من شيء لا زال حيا.. بعض القادة يعتقدون أنهم من موقع القوه عندما يصدرون أمرا أو توجيها فإن مقوديهم قد سمعوه، وفهموه وإبتدأوا في العمل لإنجازه، ولكن هؤلاء قادة لا يعرفون حدود قوتهم أو حتى طبيعة النفس الإنسانية... القادة الفاعلون يدركون أهمية إيصال الرسالة والتذكير بها عند كل فرصة حتى يتذكرها الجميع، بل وربما يمل من سماعها، لكنها تظل من أهم الأشياء التي تربط الناس بالخطوط العريضة للمنظمة</span></p> <p class="MsoNormal"><span style="font-size: 13pt; font-family: Arial;"> </span></p> <p class="MsoNormal" style="text-align: right;" align="right"><strong><span style="font-size: 13pt; color: red; font-family: Arial;">الخوف من الفشل</span></strong></p> <p class="MsoNormal" style="text-align: right;" align="right"><span style="font-size: 13pt; font-family: Arial;">القيادة تحتاج إلى شجاعة فائقة، لأن القادة يضعون أنفسهم في مواطن الخطر في أكثر من مجال: عاطفيا، ونفسيا<span> </span>وإجتماعيا وسياسيا، وإقتصاديا، بل وحتى أنهم يضعون حياتهم في خطرأحياناً. معظم خوف القادة يصعب التغلب عليه لأنه خوف حقيقي ناتج عن ملاحظاتنا لفشل الكثير من القادة الذين حاولوا التغيير بعد أن ضحوا بتضحيات جسام حتى أصبحت قصصهم عبرة لغيرهم، وأصبحت الحكمة السائدة أن التغيير هو الإنتحار بعينه،، ولذا يعمل معظم الذين يدعون أنفسهم قادة كمجرد إداريين بالمحافظة على الأوضاع الراهنة لمنظمتهم وكيانهم ومجتمعهم مهما كانت سيئة بسبب الخوف من الفشل أو إغتيال الشخصية بكل أنواع التسفيه والتحقير في ذات القائد وكيانه و ما يسعى لتحقيقه,,, ولنا في النبي صلى الله عليه وسلم أسوة حيث دعي مجنون وشاعر وساحر وغيره الكثير من الاوصاف من بني قومه وجلدته... الخوف مماا يقوله الغير في حقنا يقيد حريتنا في الريادة والإنطلاق... وتحضرني هنا قصة قرأتها قبل مدة لواحد من أشهر رياضيي العالم في رياضة المشي على الحبل الرفيع....مارس هذه الرياضة لثلاثين عاما ماشيا على الحبل بين الجبال وفي معارض السيرك بكل إتزان وثقه, وعندما لقي حتفه وسقط عن الحبل عام 1978 سئلت زوجته عن<span> </span>ماذا يمكن أن يكون السبب، فقالت أن زوجها الشجاع ركز لثلاثين عاما على المشي على الحبل، وكان لديه كل ثقة بنفسه وقدراته، ولم يفكر قط في الفشل، لكنه في الليلة قبل موته لم سيتطع التفكير في شئ آخر غير إحتمالية السقوط وعبرت بقولها "يبدوا لي أنه وضع كل طاقاته في التركيز على عدم السقوط بدل التركيز على المشي على الحبل" ... نعم عندما نقيس نجاحنا بمقدار بعدنا عن الفشل،، عندما نقيس درجاتنا بمقدار بعدها عن الصفر بدل مقدار قربها من المائة، فإن ذلك هو الإستعداد للسقوط... أبرز خصال القادة وأكثرها تذكرا بين الناس هي قدرتهم على تركيز كل طاقاتهم لهدف ما والعمل على تحقيقه وعدم التفكير بالفشل الذي يشل القدرة لأن التفكير بالفشل يرجح كفة الفشل الثقيلة أصلا في لعبة القيادة ضد المستحيل، وفي النهاية أترككم بهذه الأبيات للمتنبي</span></p> <p class="MsoNormal" style="text-align: right;" align="right"><span style="font-size: 13pt; font-family: Arial;">إذا غامرت في شرف مروم *** فلا تطمع بما دون النجوم</span></p> <p class="MsoNormal" style="text-align: right;" align="right"><span style="font-size: 13pt; font-family: Arial;">فطعم الموت في امر حقير *** كطعم الموت في أمر عظيم</span></p>YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-35792812274081465032007-04-15T15:39:00.000-07:002008-05-15T15:54:28.989-07:00أهمية اللغة في القيادة<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://vivirlatino.com/i/2008/04/martin-luther-king2.jpg"><img style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer; width: 200px;" src="http://vivirlatino.com/i/2008/04/martin-luther-king2.jpg" alt="" border="0" /></a><br /><p class="MsoNormal" style="text-align: right;" align="right"><br /></p><p class="MsoNormal" style="text-align: right;" align="right"><span dir="rtl" style=";font-family:Arial;font-size:12;" lang="AR-SA" ><br /></span></p><p class="MsoNormal" style="text-align: right;" align="right"><span dir="rtl" style=";font-family:Arial;font-size:12;" lang="AR-SA" >عن أبي سعيد قال: لما قسم رسول الله صلى الله عليه وسلم السبى بالجعرانة أعطى عطايا قريش وغيرها من العرب ولم يكن في الأنصار منها شيء فكثرت المقالة وفشت حتى قال قائلهم: أما رسول الله لقد لقى قومه، فأرسل النبي إلى سعد بن عبادة وأمره أن يجمع قومه (الأنصار) وأن لا يكن معهم غيرهم،... ثم جاء النبي صلى الله عليه وسلم فعاتبهم ثم قال: أوجدتم من شيء من دنيا أعطيتها قوما أتألفهم على الإسلام ووكلتكم إلى إسلامكم؟ لو سلك الناس واديا أو شعبا لسلكت واديكم وشعبكم، أنتم شعار والناس دثار، ولولا الهجرة لكنت امرأ من الأنصار، ثم رفع يديه حتى إني لأرى ما تحت منكبيه فقال: اللهم اغفر للأنصار ولأبناء الأنصار ولأبناء أبناء الأنصار! أما ترضون أن يذهب الناس بالشاء والبعير وتذهبون برسول الله صلى الله عليه وسلم إلى بيوتكم؟ فبكى القوم حتى اخضلوا لحاهم وانصرفوا وهم يقولون رضينا بالله وبرسوله حظا ونصيبا</span></p> <p class="MsoNormal" style="text-align: right;" align="right"><span dir="rtl" style=";font-family:Arial;font-size:12;" lang="AR-SA" >هنا تتجلى عظمة القيادة في شخص النبي صلى الله عليه وسلم وفعله وكلماته، فلم يكن الأنصار إلا بشرا تعتريهم الشكوك ويستهويهم بريق الدنيا الزائل في لحظة ضعف، ولم يكونوا ملائكة معصومين، لكن النبي صلى الله عليه وسلم أبكى القوم وبدد شكوكهم فرضوا به من دون الغنائم والأموال وذلك من خلال قوة وقع كلماته التي حملت إليهم شعوره نحوهم بالعرفان لإيوائه عندما أخرجه قومه من مكة ولذا فقد رضوا به صلى الله عليه وسلم من دون الغنائم والأموال وظلت كلماته فيهم وسام شرف لهم بين الإنسانية </span></p> <p class="MsoNormal" style="text-align: right;" align="right"><span dir="rtl" style=";font-family:Arial;font-size:12;" lang="AR-SA" >الناس بطبعهم كائنات عاطفية، واللغة من أهم وسائل التعبير عن ما يجول بداخلنا، ولذا فإن القدرة على إستخدامها وتوظيفها تعرف القادة من غيرهم، وتعكس بعض القبس المتوهج في نفوسهم التواقة للمجد... تخلدهم كلماتهم في التاريخ... عندما وقف مارتن لوثر كنج في واشنطن في مسيرة المليون شخص ضد التمييز العنصري في الولايات المتحدة في وصرخ بملء صوتة "إن لي حلما أن يكون هناك وطن يستطيع فيه الصبي الأسود أن يلعب مع الصبيان البيض كإخوة وأصدقاء" سمعه العالم أجمع وخلدته كلماته البسيطة والمؤثرة كواحد من أهم القادة في القرن العشرين... لم يقل بدبلوماسية أن لديه "فكرة لتحسين التعايش بين البيض والسود" أوبتردد "شئ يريد أن يطرحه على المجتمعين" أو بدون وعي "أن شعورة كشعور أي مواطن أميركي (يمني؟) يريد لوطنه ...." لكنه ككل القادة العظام قالها شحنة عاطفية لغوية متألقة بأن "لديه حلم" بوطن أكثر إشراقا ويتسع للجميع... إختار كلماته بعناية لترسم لمستمعيه وللعالم قوة عاطفته وإعتقاده في ما يناضل من أجله، وخاطب عواطف الخير في الناس قبل أن يخاطب عقولهم...</span></p> <p class="MsoNormal" style="text-align: right;" align="right"><span dir="rtl" style=";font-family:Arial;font-size:12;" lang="AR-SA" >ما آسف له وألاحظه بين معظم قادتنا والعاملين المؤثرين في مجتمعاتنا هو عدم قدرتهم على توظيف جمال وبلاغة اللغة العربية في تجييش العواطف وإستخدام اللغة للتعبير عن أهداف قد يكونوا قادرين على تحقيقها لو إستطاعوا إيصالها بأسلوب جذاب لجماهيرهم... لم ينتج عالمنا العربي في القرن الحالي (وربما قرون قبله) قائدا ببلاغة وكاريزمية القادة الآخرين الذين أنجبتهم أمم أخرى وصنعوا تأريخا للإنسانية كلها، والسبب برأيي هوإغفال القادة لأهمية الخطاب في إيصال رسائلهم لجماهيرهم وإعتمادهم كليا على وسائل أخرى مجتمعيه في غالبها..هذا الإهمال يأتي غالبا من مفهوم خاطي بأن القدرة الخطابية موهبة تولد مع الشخص ولا يمكن إكتسابها....قرأت للقائد الأميركي الأسود والخطابي الشهير مالكوم إكس (أسلم وغير إسمه للحاج مالك شباز) والذي يقول عنه مارتن لوثر كنج بأنه "... واحد من أكثر القادة بلاغة وفصاحة.. إستخدم قدرته اللغوية الفائقة على تشخيص مشاكلنا بعناية"... قرأت له عن كيف أصبح واحدا من أكثر القادة فصاحة في العصر الحديث. يقول مالكوم أنه دخل السجن كفتى لا يجيد قراءة كتاب بسيط جداً، ويجد صعوبة في التحدث عن أشياء بالغة في البساطة، فقرر أن يشتري قاموسا وقضى ليلتان كاملتان في الصفحة الأولى منه، ينقل كلماتها إلى دفتر ملاحظاته، ثم يحفظ معانيها ويرددها بصوت عال...بعدها إنتقل للصفحة الثانية، فالثالثة، حتى أكمل حفظ القاموس كله، وبعدها بدأ في القراءة بنهم وقرأ كل ماوقعت عينه عليه في الثقافة والسياسة والأدب والفلسفة وغيرها... عندما خرج من السجن، كان يقف بين جماهيره ومحبيه وبكلماته يشحذ فيهم الهمم ويقودهم نحو أميركا بلا عنصرية...كان يقف أمام الجمع ويحدثهم بأسلوب أبلغ ما يوصف به أنه "سهل ممتنع"... كلمات سهله وبسيطة، لكنك تحس عندما تسمع خطابا له أن عواطفة وفكرته تنطق من خلال كلماته بل وتتسرب معها إلى قلوب مستمعيه وعقولهم قوية وصادقة كقوتها وصدقها في قلب قائلها...</span></p> <p class="MsoNormal" style="text-align: right;" align="right"><span dir="rtl" style=";font-family:Arial;font-size:12;" lang="AR-SA" >لا أقترح هنا أن نشتري قاموسا ونبدأ بحفظة كما فعل الحاج شباز، لكن يجب علينا أن ندرك أن قدراتنا اللغوية تأتي في أول قائمة الكفاءات التي يجب توافرها فينا كقادة، ثم أنها ليست شيئا مستحيلا لا نستطيع القيام به... نحن الذين أهملنا لغة الضاد فأصبحت تراثا يدرس في الجامعات والأوساط الأكاديميه، وكم يحزنني جدا أن أرى رئيسا أو وزيرا أو صحفيا أو أستاذا يحوم حول حمى "الفكرة" يوشك أن يقع فيها لكن لغته وعدم قدرته على تطويع أدوات اللغة لعنفون الفكرة تخذلانه... إن أردنا التغيير والقياده، فلا بد من مخاطبة الجماهير، وإن أردنا مخاطبة الجماهير فيجب علينا أن نعتني بلغتنا العربية بدلا من العرجليزيه (عربيه- إنجليزيه) لأن الناس حينها سيتحرموننا وينظرون إلينا بعين التقدير والإكبار وسيكون لدينا القدرة على إستعمال عواطف الخير في الناس بكلماتنا وأفعالنا</span></p>YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0tag:blogger.com,1999:blog-7861216377033187791.post-63751892376732288102007-03-15T22:18:00.000-07:002008-05-15T22:18:44.262-07:00القيادة طموح وهدفعندما سئل الزعيم الهندي مَهَنْدِس غاندي (الملقب بالمهاتما) عن السبب الذي ترك من أجله وظيفته وحياته الرغده كمحام، وسلك طريق القيادة السياسية الشائك الوعر لتحرير الهند من الإحتلال البريطاني، أجاب ببساطة: الطموح. <br />في كلمة واحدة يصف غاندي القوة المحركة التي دفعت به للتضحية بكل شئ والمخاطرة حتى بحياتة من أجل الوصول إلى غاية نبيله آمن بها وعمل لأجلها، بل ويجيب على سؤال آخر وهو لماذا لم يكن قبله (أي غاندي) قائدا بحجمه وتأثيره وصموده رغم أن الهند رزحت تحت نير الإحتلال البريطاني لمائة وخمسين عاما قبله؟ طموحه وإيمانه بإمكان تغلب الهند على شعورها بالدونية الثقافية والإجتماعية صنعا منه قائدا من أعظم قادة القرن العشرين وأكثرهم شهره، ولذا فإنه على مدى أربعين سنة من عمره سافر في كل النهد يشحذ الهمم في أمته ويعلمهم معنى الكرامة وأن لا يأس مع الحياة، وأنه بإمكانهم تحقيق ما يصبون إليه، مهما كانت الصعاب. كانت النتيجة إستقلال الهند، وتخليد إسم غاندي في التاريخ. سنجد في كتب التاريخ الحديث أمثله كثيرة لقادة عظماء من لم يكونوا بنبل غاندي ولم يحذوا حذوه في القياده وربما لم يحققوا ما حققه من النحاج، لكن الشئ الذي سنجده بين عامة هؤلاء القادة هو نفس الدافع والقوة المحركة التي تجعلهم متميزين عن غيرهم: الطموح،<br /><br /> القيادة من أصعب المهمات على الإطلاق ومن أكثرها عرضة للفشل، كما أنها أكثر الوظائف الإنسانية مسؤوليه، ولذا يتحاشاها معظم المدركين لمسؤلياتها حتى بعض القادرين على تحمل أعباءها، لكن القليلين الذين يحاولون هم الذين ينالون شرف المحاوله، ويحقق بعضهم نجاحا باهرا. <br /><br />في هذه السلسة من المقالات عن صناعة القائد سأحاول إلقاء الضوء على بعض الصفات التي يتسم بها القادة وسأحاول قدر الإمكان الإبتعاد عن التنظير الفكري والتركيز على الجانب العملي، لأنه من الصعب ( إن لم يكن المستحيل) أن تصبح شخصا آخر، لكن ليس من الصعب أن تتعلم من تجارب القادة الآخرين، لتسهيل مهمتك كقائد في أسرتك، في قريتك ومدرستك، وجامعتك وفي مجتمعك وأمتك، وقد قيل، أفضل السبل لمعرفة الطريق هو سؤال من سلكوه من قبل، ولكي نكون أكثر واقعيه فسنحاول أن نُسْقِط هذه الدروس على واقعنا اليمني، وأود هنا التأكيد على أني لا أتكلم هنا من برج عاجي، بل أجدها فرصة لأتعلم وعزيزي القارئ من خبرات الكثيرين في القيادة حتى نكون جميعا قادة ناجحين من مستوى الإسرة إلى مستوى الأمة، لأن كل منا (راع ومسئول عن رعيته)<br /><br />القيادة لماذا؟<br /><br />من أبشع أخطاء بيل كلنتون في مهرجانه الإنتخابي عام 1994 أنه سُئل: لماذا تريد أن تكون رئيساً، فأجاب بعدة أسباب منها أنه إلتقى الرئيس الأميركي الأسبق جون كندي، والسؤال الذي برز في أذهان الناخبين (الواعين منهم على الأقل) هو لماذا يريد أن يكون رئيساً؟ هل لأن لديه برنامجا يريد تحقيقه أم من أجل تحقيق أحلام شخصية فقط وإرضاء كبرياء نفسه بأن يكون "الرئيس"؟<br /><br /> القائد مملوك لتابعيه، ولذا فإن القيادة لأجل القيادة ذاتها ،على طريقة حبذا الإمارة ولو على الجحارة، خطيرة جدا لأنها تفتح السبل لأخطاء قاتله تؤثر في المقودين والمنظمة ككل وتقدم مصلحة القائد وطموحاته الشخصية على مصلحة من يقود، ولكن القيادة الطموحه من أجل تحقيق هدف نبيل وواضح شئ سام وضروري. ولذا فالنبي ـ صلى الله عليه وسلم ـ يقول في تقليد الولايات: "إنا لا نعطي هذا الأمر من يطلبه ولا من يحرص عليه"، لأن كثير ممن يطلب القيادة قد يريدها فقط لما تحتويه ظاهرا دون إدراك لمسئولياته وتبعاتها. قد يكون من المرغوب، بل والضروري أحيانا، أن يتقدم أحدنا لتقلد المسؤوليه لكن يجب أن نكون صريحين مع أنفسنا ونسأل أنفسنا سؤالا واحدا: هل أريد أن أكون قائدا لإرضاء كبرياء النفس بكوني "القائد" أم لأن لدي أهداف أريد تحقيقها للمنظمة التي أقودها ولمن أقود؟ فإن كانت أهدافنا بعيده عن المطامع الشخصية، وشعرنا بأن لدينا ما يمكننا أن نفعله كقادة، فهناك يبدأ طريق القيادة الوعر نحو التغيير للأفضل.<br /><br /><br />إبدأ بنفسك:<br /><br />قيل أن حركة حقوق الإنسان والمطالبة بالمساواة في أميركا بدأت بإمراة سوداء رفضت أن تتخلى عن مقعدها في الباص لشخص أبيض، مما إضطر سائق الباص والسلطات لطردها، فاشتكت أمرها إلى قس أميركي أسود يدعى (مارتن لوثر كنج)، والذي قام بدورة بالخروج من محيط كنيسته كقس إلى الشعب الأميركي ككل، خطيبا مفوها وسياسيا بارعا... سافر من مدينة إلى أخرى يوعي الناس بأهمية المساواة، وعمل ليل نهار من أجل خلق محيط يتساوى فيه الجميع بالقانون والأعراف، حتى تم تحقيق أهدافه بإلغاء التفرقة العنصرية التي كانت سائدة في أميركا في الستينات. <br /><br />غالبا ما نقرأ عن لحظات، كحادثة الباص هذه، غيرت أناس عاديين إلى قادة عظام، ونتمنى أن تأتينا لحظتنا لنتغير يوما ما ونصبح أشخاصاً آخرين قادرين على القياده. لكن الحقيقة المرة هي أنه من المستحيل تقريبا أن يغير الإنسان شخصيته تماما ليصبح شخصاً آخر، فلكل إنسان خصائصه التي تميزه... قد تكون القيادة أسهل مثلاً لو كان الشخص أوسم وأجمل أو أغنى أو من أسرة شهيره أو عدة سنتميترات أطول مما هو عليه وذو صوت جهوري وملكة لا تبارى في الخطابة (آسف)، لكن هناك أشياء ولدت معنا وستظل معنا، هي التي تعرف من نكون. قد لا نستطيع تغيير من نكون لكننا نستطيع تغيير ما نفعله كقادة، وأول شئ يجب أن نغيره في أنفسنا أن نقبل أن كل ميسر لما خلق له ونقبل ما لا نستطيع تغييره في أنفسنا، ثم إدراك أنه إن لم يكن بالإمكان تغيير من نكون فإنه بالإمكان أن أن نغير أساليبنا وتعلم أشياء كثيرة عن القيادة الحقيقيه مثل كيف نتعامل مع الآخرين بحساسية أكثر، كيف نسأل أسئلة، وأهمية الإستماع لما يقوله الآخرين في محيطنا، وكيف نشركهم في إتخاذ القرارت، كيف نقول "نحن" بدلا من "أنا" عندما نخاطب مجموعة، كيف نشكر الآخرين على جهدهم ووقتهم في، وكيف نحترم الجميع مهما إختلفت المشارب والآراء، وكيف نعلم الآخرين كيف يكونوا قادة وأعضاء فاعلين في مجتمعاتهم... هذه وأشياء أخرى ستكون موعدنا مع مقالات قادمة نستقرئ فيها خصائص القيادة بأمثله ودروس تعلمها قادة قبلنا بتجارب ربما كانت قاسية...<br />المشاهدة: 407YemeniProgrammerhttp://www.blogger.com/profile/10144498764306495246noreply@blogger.com0