Wednesday, April 27, 2011

Windows Ping command output detail

The command ping www.google.com might produce this output:

ping www.google.com
Pinging www.l.google.com [64.233.167.99] with 32 bytes of data:
Reply from 64.233.167.99: bytes=32 time=31ms TTL=239
Reply from 64.233.167.99: bytes=32 time=31ms TTL=239
Reply from 64.233.167.99: bytes=32 time=31ms TTL=239
Reply from 64.233.167.99: bytes=32 time=33ms TTL=239
Ping statistics for 64.233.167.99: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds: Minimum = 31ms, Maximum = 33ms, Average = 31ms

The first line of output confirms the command you issued Lets look at the first such output line:

bytes = 32 is the size of the ICMP Echo reply

time=... -- This is the time between the Echo Request and Reply. Since networks are dynamic, this time will probably be different for each reply received.

ttl=239 -- ``TTL'' means Time to Live. This is a counter in every IP packet. The sender (ping in this case) sets it to whatever it thinks a reasonable number is (the maximum is 255). Each router subtracts one, and packets get thrown out if TTL ever reaches 0. Assuming we started with TTL=255, this report gives us an estimate of the number of routers we passed through (16 in our example).

Source:
http://www.csis.ysu.edu/~gcperera/cclasses/3723/lab1.pdf
Reference:
http://en.kioskea.net/contents/outils-reseau/ping.php3

Tuesday, April 26, 2011

command to Get linux distro and version

enter the following command at the shell prompt:
$ cat /etc/*-release

Source: 
http://www.cyberciti.biz/faq/find-linux-distribution-name-version-number/

Objective c: NSString uppercase and lowercase

NSString to lowercase:

searchText = [searchText lowercaseString];

NSString to uppercase:

searchText = [searchText uppercaseString];






IPhone: Custom Table Cell

In order to make a custom table cell you have to handle the cell contentView:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
   
    // Set up the cell...
    pinFreeNumberItem *cellValue = [tableData objectAtIndex:indexPath.row];
   
    UIView *myContentView = cell.contentView;
    UILabel* topLeftLabel = [[UILabel alloc] initWithFrame: CGRectMake(2, -6, 350, 30)];
    topLeftLabel.text = @"hi1";
   
    [myContentView addSubview:topLeftLabel];
   
    UILabel* bottomRightLabel = [[UILabel alloc] initWithFrame: CGRectMake(170, 24, 350, 15)];
    bottomRightLabel.text =@"hi2";
   
    [myContentView addSubview:bottomRightLabel];
   
    UILabel* bottomLeftLabel = [[UILabel alloc] initWithFrame: CGRectMake(2, 24, 150, 15)];
    bottomLeftLabel.text = @"hi3";
   
    [myContentView addSubview:bottomLeftLabel];
   
    return cell;
}

Resources:
http://stackoverflow.com/questions/5337340/custom-uitablecell
http://iphone.zcentric.com/2008/08/05/custom-uitableviewcell/

IPhone Table View Styles

Tuesday, April 19, 2011

Python: Getting the class name

>>> import itertools>>> x = itertools.count(0)
>>> x.__class__.__name__'count'
 
Source:
http://stackoverflow.com/questions/510972/getting-the-class-name-of-an-instance-in-python 

Python: Class to dict including and excluding methods

>>> class Foo(object):
...     bar = 'hello'
...     baz = 'world'
...
>>> f = Foo()
>>> [name for name in dir(f) if not name.startswith('__')]
[ 'bar', 'baz' ]
>>> dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__')) 
{ 'bar': 'hello', 'baz': 'world' }

Now, if you have a class with methods and you need to get the resulting dict excluding the methods, you can use the isfunction() method from inspect module

>>> from inspect import isfunction
>>> class Foo(object):
...     bar = 'hello'
...     baz = 'world'
...     def calculate(self):
...         return 0
...     def calculate1(self):
...         return 1
...
>>> f = Foo()
>>> dict((name, getattr(f, name)) for name in dir(f) if not isfunction(getattr(f, name)) and not name.startswith('__')) 

{ 'bar': 'hello', 'baz': 'world' }

Source:
http://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields
http://stackoverflow.com/questions/624926/how-to-detect-whether-a-python-variable-is-a-function

python public and private attributes and methods

 
 
class MyClass:
# public var 
var1
# protected var
_var2
# private var
__var3
def public(self):
        pass
    def __private(self):
        # mangled to _MyClass__private
        pass

c = MyClass()
c.public() # this works
c.__private() # this doesn't
 
References:
http://stackoverflow.com/questions/735975/static-methods-in-python 

python staticmethod declare

>>> class C:
...     @staticmethod
...     def hello():
...             print "Hello World"
...
>>> C.hello()
Hello World
 
source:
http://effbot.org/pyfaq/tutor-how-do-i-make-public-and-private-attributes-and-methods-in-my-classes.htm 

ExtJS (2.2.1): making keypress event work

This doesn't work for me:

listeners:{
     keypress: function(field, e){
     alert("kp");
}


this one works just fine:

listeners:{
        'render': function(c) {
          c.getEl().on('
keypress', function() {
               alert(
"kp");
      }, c);
        }
}


Source:
http://www.extjses.com/mensaje7282.html



Getting unique Id from ABPersonInstance

iterate a Dict in objective c


NSEnumerator *enumerator = [myDict keyEnumerator];
id key;
// extra parens to suppress warning about using = instead of ==
while((key = [enumerator nextObject]))
    NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);
 
source:
http://stackoverflow.com/questions/1284429/is-there-a-way-to-iterate-over-an-dictionary 

request to send from iphone data and files to server using http post


-(NSMutableURLRequest *)requestWithURL:(NSURL *)url withBody:(NSMutableDictionary *)body  withUrlAndAttachedFile:(NSString *)fileAndUrl withFileName:(NSString *)fileName withFileFormat:(NSString *)fileFormat

{
    NSMutableURLRequest *request;
    NSString *requestBody;
       
    request = [[NSMutableURLRequest alloc] initWithURL:url
                                           cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                       timeoutInterval:60];
   
    request= [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSMutableData *postbody = [NSMutableData data];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file_0\"; filename=\"%@.%@\"\r\n", fileName, fileFormat] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    NSData *postData = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:fileAndUrl]];
    [postbody appendData:[NSData dataWithData:postData]];
    [postbody appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
   
   
    // iterate body dict
    NSEnumerator *enumerator = [body keyEnumerator];
    id key;
    // extra parens to suppress warning about using = instead of ==
    while((key = [enumerator nextObject])){
        //NSLog(@"key=%@ value=%@", key, [body objectForKey:key]);
        [postbody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
        [postbody appendData:[[body objectForKey:key] dataUsingEncoding:NSUTF8StringEncoding]];
        [postbody appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }
   
   
    // close form
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postbody];
   
   
    return request;
}
references:
http://stackoverflow.com/questions/4458112/mac-os-nsurlconnection-in-iteration

"UIApplication" undeclared (first use in this function)

you have to add this import line:

#import <UIKit/UIKit.h>


Monday, April 18, 2011

iphone error: expected '=', ',', ';', 'asm' or '__attribute__' before error

Noted that this error happened only for the NSString*, for e.g.,
  • extern double const kTimeout; // fine
  • extern NSString* const kImageType; // compile error
After the above analysis & little break, eventually the problem is resolved by adding the the following import to the .h - "Foundation/Foundation.h"

Source:http://stackoverflow.com/questions/990906/iphone-error-expected-asm-or-attribute-before-foo

Tuesday, April 12, 2011

Read and Write Text Files on IPhone OS

/Method writes a string to a text file
-(void) writeToTextFile{
      //get the documents directory:
      NSArray *paths = NSSearchPathForDirectoriesInDomains
           (NSDocumentDirectory, NSUserDomainMask, YES);
      NSString *documentsDirectory = [paths objectAtIndex:0];

      //make a file name to write the data to using the documents directory:
      NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                   documentsDirectory];
      //create content - four lines of text
      NSString *content = @"One\nTwo\nThree\nFour\nFive";
      //save content to the documents directory
      [content writeToFile:fileName 
                   atomically:NO 
                       encoding:NSStringEncodingConversionAllowLossy 
                          error:nil];

}
 
 
//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
      //get the documents directory:
      NSArray *paths = NSSearchPathForDirectoriesInDomains
                      (NSDocumentDirectory, NSUserDomainMask, YES);
      NSString *documentsDirectory = [paths objectAtIndex:0];

      //make a file name to write the data to using the documents directory:
      NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                                   documentsDirectory];
      NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
                                                      usedEncoding:nil
                                                             error:nil];
         NSLog(@"content: %@" , content)
      [content release];

} 
Source:  
http://howtomakeiphoneapps.com/2009/06/reading-and-writing-text-files-in-iphone-os-3-0/

Friday, April 8, 2011

Nice article about launching other apps from an iphone application

warning: passing argument 1 of 'localizedStringForKey:value:table:' from incompatible pointer type

 NSString *paramVia    = NSLocalizedString("share_on_twitter_url_via", nil);

there was missing something, so add @ to "share_on_twitter_url_via" : @"share_on_twitter_url_via"

 NSString *paramVia    = NSLocalizedString(@"share_on_twitter_url_via", nil);

iphone call programmatically


 NSString* telephone = @"tel:";
 telephone = [telephone stringByAppendingString:@"45345678"]; // set phone number
 NSURL *url = [ [ NSURL alloc ] initWithString: telephone ];
 [ [ UIApplication sharedApplication ] openURL: url ];

source: http://www.experts-exchange.com/Apple/Hardware/iPhone/Q_24182155.html

Wednesday, April 6, 2011

Simple Custom loading alert view

UIActivityIndicatorView* spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[spinner setCenter:CGPointMake(140, 100)];

NSString* messageTitleToUser = @"Favorites list";
 UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:messageTitleToUser message:@"loading..." delegate:self cancelButtonTitle:@"Done" otherButtonTitles:nil];

  [alertView addSubview:spinner];
  [spinner startAnimating];
  [alertView show];

....
...
...

//if you programmatically want to close the alert view
 [alertView dismissWithClickedButtonIndex:0 animated:YES];
// stop spinner
[spinner stopAnimating];


References:
http://stackoverflow.com/questions/593234/how-to-use-activity-indicator-view-on-iphone


Friday, April 1, 2011

Objective-c Getting Started ".objc_class_name_NSObject", referenced from

Following the http://www.otierney.net/objective-c.html#gettingstarted tutorial, I got the following error:

".objc_class_name_NSObject", referenced from:
.objc_class_name_Fraction in Fraction.o
"_objc_msgSend", referenced from:

It was caused because there was missing a link to a framework: "Foundation.framework".

So, you can add existing frameworks to you project in XCode4 following these steps:

  1. In the project navigator, select your project
  2. Double click your target
  3. Select the 'Build Phases' tab
  4. Open 'Link Binaries With Libraries' expander
  5. Click the '+' button
  6. Select your framework (Foundation.framework)
Done.

references:
http://forums.macnn.com/79/developer-center/391122/newby-trying-learn-obj-c-xcode/
http://stackoverflow.com/questions/3352664/how-to-add-existing-frameworks-in-xcode-4

Real Objective C Hello World

Finally found a real HelloWorld in Objective c:

http://cupsofcocoa.wordpress.com/2010/09/03/objective-c-lesson-1-hello-world/

After that, we can know continue with this Complete Tutorial:

http://www.otierney.net/objective-c.html