Thursday, April 10, 2014

iOS snippets part 1

Here are some snippets I use for the iOS platform. Since I work on several platforms (MS Windows, Linux, Android and iOS using languages like C, C#, C++, Obj-C, Java, PHP etc...) , I thought it would be better to put a bunch of useful and often used snippets on my blog, so I don't have to google a lot. Once you understand how to program, it's not important anymore what language you use or what platform you're developing for.

I hope those sinppets are useful for you, let's start :-)


Message Box

- (IBAction)btnExit:(id)sender {
    UIAlertView *messageBox = [[UIAlertView alloc] initWithTitle:@"Exit"
                                                      message:@"Are you sure?"
                                                     delegate:self
                                            cancelButtonTitle:@"No"
                                            otherButtonTitles:@"Yes", nil];
    [messageBox show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
   
    if([title isEqualToString:@"No"]) {
        NSLog(@"No was selected.");
    }
    else if([title isEqualToString:@"Yes"]) {
        NSLog(@"Yes was selected.");
    }
}




Timer 1

- (void) startTimer {
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target:self selector:@selector(fireMe) userInfo:nil repeats:YES];
}

- (void) fireMe {
    NSLog(@"I'm fired!");
}


By setting the repeats on YES, makes the timer execute every 0.1 sec which is 100 ms. By setting it to NO, will execute the timer just once.


Timer 2

- (void) startTimer {
    NSTimer *timer = [[ NSTimer alloc ] initWithFireDate: [NSDate dateWithTimeIntervalSinceNow: 0.0
                                                 interval: 0.1
                                                   target: self
                                                 selector: @selector(fireMe)
                                                 userInfo: nil
                                                  repeats: NO];
}


This is another way to start a timer.



Worker-thread using GCD (Grand Central Dispatch)

dispatch_queue_t myQueue = dispatch_queue_create("my queue",NULL);
...
...
...
dispatch_async(imageQueue, ^{
        // This will run the method in a separate thread
        [self doSomeLongRunningTask];
    });


- (void) doSomeLongRunningTask {
    dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"We finished a heavy task!");
        });
}


So, we create a dispatch queue handle for our separated thread, than pass a block ^{} to dispatch_async that will be executed in a separate thread ( NOT in the main thread). If you want to call a method in the main thread from another thread, you call:  dispatch_async(dispatch_get_main_queue(), ^{ }); As you see, dispatch_get_main_queue() gives you the queue handle of the main thread.
For more information, check: GDC



Thread with NSThread

NSThread *thread = [[NSThread alloc] initWithTarget:self
                                     selector:@selector(run:)
                                       object:nil];
[thread start];

...
...
- (void) run: (id) object{
    NSLog(@"I'm running in another thread :D");
}


This is a simple example to create another thread and run it by calling the start method.



TCP Sockets with streams

NSInputStream *inputStream;
NSOutputStream *outputStream;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;


CFStreamCreatePairWithSocketToHost( NULL, (__bridge CFStringRef)hostIp, hostPort, &readStream, &writeStream );
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);


inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
...
...
// ope connection
[ inputStream open ];
[ outputStream open ];
...
int len = (int) [outputStream write: buffer maxLength: size];
len = (int) [inputStream read: buffer maxLength: size];


Using streams with NSRunLoop

[inputStream setDelegate:self ]; //This will call stream: handleEvent:

NSRunLoop *runLoop = [ NSRunLoop currentRunLoop ];
[inputStream scheduleInRunLoop: runLoop forMode:NSDefaultRunLoopMode];
[runLoop run]

// This will be called from runLoop
- (void) stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
    switch ( eventCode ) {
        case NSStreamEventOpenCompleted: 

            break;
        case NSStreamEventHasSpaceAvailable:
            break;
        case NSStreamEventHasBytesAvailable:

            break;           
        case NSStreamEventErrorOccurred:
            break;
        case NSStreamEventEndEncountered:
            break;
        default:

    }
}




 

Monday, December 16, 2013

CMake - basic tutorial

This is a short tutorial about CMake with a practical example. CMake is a tool to generate build files but does not compile! So, if you use Linux, CMake creates Makefile which make tool uses it to actually build your C++ application. The advantage of CMake over the standard make, is writing a CMake script is relatively easy comparing to a Makefile script. Another advantage is, CMake can generate build files for other platforms, so if you want to build your application for another platform like MS Windows, CMake does that for you just by telling which platform you want to build for.

Unfortunately a lot of examples found on the internet is based on one simple Hello World file, which doesn't represent the real power of CMake and also doesn't represent a realistic directory structure of real projects.

Ok, below we see how a typical project folder looks like:
Project_folder
             |__ src
             |       |__ main.cpp
             |       |__ xxx.cpp
             |       |__ yyy.cpp
             |       |__ zzz.cpp  
             |__ include
             |__ libs
             |__ build
             |__ CMakeLists.txt
  
Now, we want to tell CMake that in the folder 'src' there is the source files, in 'include' there is the include files (in case of C/C++) and in the 'libs' we have the libraries. The build folder will contain the build files that CMake generates.
CMakeLists.txt is the script CMake will read to know how to build the project.
So, how would our CMakeLists.txt look like?
Below we have an example of CMakeLists.txt:



#------------------------------------
# Minimum CMake version required.

cmake_minimum_required(VERSION 2.6)


#------------------------------------
# Not necessary, but recommended, projectname:

project(MyBoostTest)

#------------------------------------
# The version number.
set (Tutorial_VERSION_MAJOR 1)
set (Tutorial_VERSION_MINOR 0)

set (CMAKE_CXX_FLAGS "-g -Wall")

#------------------------------------

# Declare var names for source path
#------------------------------------
set (INC ${PROJECT_SOURCE_DIR}/include)
set (SRC ${PROJECT_SOURCE_DIR}/src)
set (LIBS ${PROJECT_SOURCE_DIR}/libs)

#------------------------------------

# Add source files to SRCS variable
#------------------------------------
list(APPEND SRCS ${SRC}/main.cpp
${SRC}/xxx.cpp ${SRC}/yyy.cpp ${SRC}/zzz.cpp)
#------------------------------------

# Tell CMake where the include files are
#------------------------------------
include_directories(${INC})
#------------------------------------

# is the same as include_directories
# in this case, we have no real lib files
#------------------------------------
link_directories(${LIBS})
#------------------------------------


# name the executable 'MAIN' and tell
# CMake which files are used
#------------------------------------
add_executable(MAIN ${SRCS})
#------------------------------------

# Tell CMake what libraries to link
# with. For example the BOOST's regex

# but it could also a library in the libs folder,
# which can be built with:
# add_library(mylib ${LIBS}/lib_x)
#------------------------------------
target_link_libraries(MAIN boost_regex)
#------------------------------------


 
If we run CMake in the same directory as where the above CMakeLists.txt resides, a bunch of files and folder will be created in that same directory. This will clutter up our project folder, to prevent that we tell CMake to put the generated build files in the build folder:

cmake -Bbuild -H.
If everything went well, we'll see the build folder with the generated build files. If we than move to the build folder, we can run the following command to compile the sources (assuming this is a C++ project on a Linux machine with the 'make' tool):
make .
If your sourcecode is successfully compiled, you'll see the MAIN executable in the build folder.

So, it's quite easy, you just need to tell CMake where the source files and libraries are, what to build and CMake is doing the ugly work for you.
We also use just one CMakeLists.txt, normally you should have CMakeLists.txt in every sourcecode folder, but for the sake of simplicity, we use only 1 CMakeLists.txt. I'll punt another CMake example next time with multiple CMakeLists.txt. 

Thursday, December 12, 2013

Vim - Reminders part 1

On this page I show some commands which you might forgot. For me it's to quickly look up how to do it again. So let's start.

Thursday, December 5, 2013

Vim - Nice little handy tips and tricks

I found some nice little tricks to perform some actions a little bit faster

Toggle toggle toggle...
If you want to set line numbers you do like this:
:set number
you can even make it a bit shorter"
:se nu

To disable line numbers:
set no number
or
set no nu

But you can also toggle by adding an exclamation mark '!'
:se nu!



Another toggle:
:se cul!
This is to put a line under the cursor, some like it, some not. I really like it!

Sources: http://learnvimscriptthehardway.stevelosh.com/


Another one:
I often like to load a bunch of files at once and when I'm done editing with a file, I'll get another buffer to edit (":h buffer" for more information). But sometimes I want 2 files next to each other, just to see if they look similar (but not identical). In that case I'd like to have 2 files open next to each other, so I want the window split in two vertical windows. This is how we can do that:
:vert sb x
Where x is the buffer number you want, assuming you already loaded a bunch of files. Now you get two windows with current buffer on the right window and buffer x on the left. Cool!

Compare 2 buffers:
Ok, so the above one creates 2 windows, each containing a buffer. Suppose you have a big file like a few thousand lines and want to check the difference, no problem with Vim. On each window you execute the command:
:diffthis
or shorter,
:difft
To turn off:
:diffoff!
With the exclamation mark, it turns off for all windows.

To jump to the next difference:
]c
read as "go to the next compare". The other way around is:
[c

To obtain the difference from the other file to the current file:
do
Note, this is per difference, so not the whole file at once. The other way around:
dp
Exercise with it, you'll love it!
By the way, I mapped diffthis and diffoff as:
nmap [Leader]d :diffthis
nmap [Leader]dd :diffoff!
replace [ with <, this blogger automatically removes '<', I guess because of security point of view (xss).



Other cute commands:
If you have multiple windows, you can close them all except the current one by this:
:only
There is also:
:hide
which closes the current window, but than I rather use Ctrl+w c, which is faster.


Follow the breadcrumbs:
One of the important things an editor should have is navigating forward and backwards my cursor positions. Say you edited a function or a method in your source code, than you jump to another function to do some other editions there or copy a snippet of code, the next thing you want to do is go back to the previous position. In normal mode you type:
Ctrl+o
for jumping back to the previous position, to jump forward again:
Ctrl+i
This is a very useful and powerful Vim command, a must-have desperately tool.


Forgot to sudo:
Very often I forget to add sudo if I want to edit a file with root permission, here is the remedy:
:w !sudo tee %
This one is hackish :)


Let's hex :
As a programmer, coder or hacker you need to check the binary data of a file. For example, you want to check the jfif segment (wiki-jpeg) of a jpeg file. To analyze the data, you can issue the command:
:%!xxd
to go back to the original view:
:%!xxd -r
So light, yet so powerful.


Load multiple files from within Vim:
Sometimes when writing code in Vim, I just need some other files to edit or maybe just to look at some code. Here's how you can do that:
:args somefolder/*.php
or if you want to browse to a folder and than load you can do the following:
:e .
This makes Vim as file browser, than you go to a certain folder, i.e. 'somefolder', than select those files with regular expression by first typing:
mr
than type:
*.php
and than type:
me
So by typing mr you open a regular-expression shell to select the matching files, than type the matching expression and than me to edit the files that match with the regular expression.


Insert date:
I like this one too, inserting date in the current file on the current cursorposition:
:r !date


Are you ready for this:
I sometimes accidentally close a file I was working on and to type
:e myfolder/subfolder/somecrazyfile.crz is just too annoying. But check out the power of Vim:
:ls!
shows you the recently closed files, than type:
:xb
and boom! Your recently closed file is back, where x is the id number of one of the closed files.

But this can be done faster! Check this, really amazing, hit the following keys:
Ctrl+o
You're back to the last cursor position in you last closed file! Amazing, just ONE key combination, amazing!
No plugins, just Vim! I'm sorry, I don't know if Emacs can do that :P


Copy/paste tricks:
I was a bit frustrated to copy a word and than replace another word with the copied one. I don't know why I didn't figured it out much earlier, but check this how to do it:
yiw is to copy the word where your cursor is on it, than do:
viwp this selects the word and than paste it with the yanked word earlier. Cool huh.
If you want to do this for another word, do this:
viw"0p meaning replace it with the word from register 0. When you yank or delete a word, the word is automatcially saved in register 0. You select the register by " and than a number. And of course, p is for paste.


When you yank a complete line with yy, you can than replace another line with:
Vp
To do this again for another line:
V"0p
I found this handy trick on: http://vim.wikia.com/wiki/Replace_a_word_with_yanked_text

Friday, July 5, 2013

Microcontroller - Which microcontroller to choose

For a long time I was thinking about building a robot, but never started to build one, until recently. A week ago me, my wife an my kids visited the Robocup2013 event in Eindhoven, the Netherlands. It was great to taste the enthusiasm during the event. So many young kids have built their little robots challenging other robots. 40 countries participated to the event but unfortunately Morocco was not one of the participants.

So I thought if I build a robot with very cheap components and share the result and knowledge with students from Morocco (and the rest of the world of course), maybe the schools and universities in Morocco will think about to participating to such events as the Robocup2013. We live in an era where knowledge is shared with the rest of the world over the internet. So the Moroccans have no excuse that they can't gain knowledge because it's expensive. Nowadays, knowledge is free and available on the internet.

To build at least an intelligent robot, I need a microcontroller to start with. But which microcontroller is suitable? Some criteria should be met, tom my opinion are I think:
  • it must be cheap, as cheap as possible
  • great community to ask for help and lots of tutorials
  • good development environment, like IDE, compiler, debugger (very important)
  • cheap microcontroller programmer
Since I already have some experience in mircocontroller programming, I found that ARM based microcontrollers are a bit overkill. I mean, just to use for controlling DC/Servo/Stepper motor and read some input pins is a waste to use an ARM based microcontroller. I have also worked with TI microcontrollers a long time ago, but you need to buy an IDE, I've used an IDE at college time that was free. However, the TI microcontroller was a nice one, it looks good, works good, nothing to complain about it. It's just that the compiler is not free. A PIC microcontroller is a popular one too, but it lacks of a good C compiler for free, it does provide a free Assembler . However, I want to realize a project and don't want to waste time in studying assembly, so PIC, no matter how nice this thing is, is no option to me.

After some time I found some projects based on Arduino. Arduino's are openhardware systems based on Atmel's AVR microcontroller, which also has a simple to use IDE including C compiler. The code can be flashed to an Arduino device through usb cable. There is no need for a special JTAG interface or self-built serialport loader. It supports also C++ and it's really easy to write code for it, to me it feels like writing code in Java. The builder of Arduino's really managed to create a microcontroller platform that is accessible to a large audience with no experience of microcontrollers. They really did a tremendous job to achieve that.

Another great advantage of Arduino is they are cheap comparing to others, people with low budget that want to learn or build a microcontroller project, are able to buy one. To program the controller, one just has to download the software for free and need an appropriate usb cable.
If you want to have more control over the AVR microcontroller, there is also a free compiler for it, free IDE and so on. So Arduino is a great way to jump to AVR, because Arduino is based on AVR.

Because as a father, husband and employee I have little free time, my choice is to start with Arduino and next AVR.That's my choice b.t.w. ;-)

Monday, July 1, 2013

Robots - Robocup2013

Last weekend I went to the Robots event Robocup 2013 in the city Eindhoven, in the Netherlands. I went there together with my wife and 3 kids and it was a bit fun. It was more fun for the participants of the event. There were participants from about 40 countries, including Turkey, Iran, China and so on... As a visitor you can only see the robots from a distance on a stand. So finally it wasn't more than watching to a bunch of robots who try to score with a colored ball. There were different leagues, categorized from small simple robots to artificially intelligent robots.

The more interesting robots are those humanoid robots, these robots look like humans, or they try to be.
Also there's some interaction, that makes a robot always interesting, especially for the kids. We saw the famous autonomous robot Asimo too, but it was very crowded and couldn't see much, so it wasn't a great success, but at least we saw something.

If you see how much research, effort and technology it was needed to build a robot like Asimo, how difficult and knowledge is needed to build a real human? That's why I believe in God as our creator and that there's a reason why we we're built.

I really hope the kids like it and that they're interested in building a robot too :-) Who knows, someday I'll post a robot built with my family.

NSNotification example