likely, unlikely in Linux

likely and unlikely

You would have seen "likely" and "unlikely" macros in Linux kernels, modules or other programs. What are the macros doing? How do I properly use them?

kernel newbies – FAQ/LikelyUnlikely

Please visit kernel newbies' FAQ, it'll give you more detail and correct information.

compiler.h

The macros live in compiler.h, and looks pretty simple.

#define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0)

What is the expected behavior?

likely and unlikely does nothing to do with program logic. This means that you don't need to change the conditions due to likely and unlikely.

__builtin_expect(long EXP, long c)

Programs do prefetching following commands. When it sees a branch it follows the prediction information. So, if the prediction is wrong, it should discard the prefetched commands. Here you can give an information that this EXP will be true almost times or vice versa. This enables programs do a right prediction and enhances the performance.

Example

<code>// Let&#39;s say we have a do_something() function that returns 1 when succeed.
// And you expect that it succeeds for happy cases (most of the time)
// You can utilize likely
if (likely(do_something())) {
   // Do happy logics
}

// Or you may love this more
if (unlikely(do_something())) {
    // Computer can expect that this part will not be executed mostly, and it can prefetching the out of this if statement (or else part).
}
</code>

Semaphore vs. Mutex

Good posts about Semaphore vs. Mutex

MUTEX IS NOT THE SAME AS BINARY SEMAPHORES.

Important difference between Mutex and Semaphore.

– Mutex lock is released by the thread which have acquired the lock.

– Semaphore can be released by other threads.

Semaphore is suitable for producer & consumer pattern.

Install python and openCV to windows7

reference :

http://imky.egloos.com/2969966

http://www.davidhampgonsalves.com/2011/05/OpenCV-Python-and-Windows-7-setup-in-5-minutes-or-less

http://mitchtech.net/opencv-python/

Prerequisites

Python 2.7 – http://www.python.org/

NumPy(Numerical Python) – http://sourceforge.net/projects/numpy/files/

SciPy – http://sourceforge.net/projects/scipy/files/scipy/

Download openCV with .exe from http://opencv.org

Install it to c:openCV

copy c:openCVbuildpython2.7cv2.pyd c:Python27Libsite-packages
test by running C:openCVsamplespythondrawing.py

JD-GUI bug, it dropped explicit casts

최근에, framework 을 수정할 일이 있었는데, 큰 문제를 일으킬뻔 한 jd-gui 버그가 있어 글로 정리..

1. 시스템이 여러개라 메인시스템을 제외하고 framework library 의 소스가 따로 관리되지 않고 있었음.

2. framework 의 개선이 있어서 작업을 하고 메인시스템 외의 시스템은

decompile 해서 해당 함수 수정하고 다시 compile 해서 jar로 생성 후 반영

위와 같은 작업을 하고 있었는데 decompiler 로 jd-gui를 사용했다. jar 전체를 java 소스로 뽑아주는 기능이 있었기 때문이다.

전체 소스를 비교하면서 작업을 꼼꼼히 하기 위해서 사용했었는데..

문제는 이것.

원 소스 :

public class TestClass {

	public int ceil(int a, int b) {
		return (int) Math.ceil((double)a/(double)b);
	}
}

jd-gui가 de-compile 한 java (BUG!)


public class TestClass
{
  public int ceil(int a, int b)
  {
    return (int)Math.ceil(a/b);
  }
}

jad.exe가 de-compile 한 java


public class TestClass
{

    public TestClass()
    {
    }

    public int ceil(int a, int b)
    {
        return (int)Math.ceil((double)a / (double)b);
    }
}

jd-gui가 명시적 casting을 날려먹음..

결과.. 2, 100 이 파라미터로 넘어가면..

원함수는 1을 리턴했으나, jd-gui를 믿었다면 0을 리턴하게 되므로 로직이 변경됨..

주의하세요 !

Tip of uploading images to tumblr using OAuth on iOS

To make my app, merge&share, I had to use OAuth to upload multiple services including tumblr.

There’s some problem, and I still don’t know which one is problem between OAuthConsumer library and tumblr.

OAuthConsumer Library makes authorization header using all parameters and if I include NSData, it may not work correctly.

– OR –

Tumblr doesn’t recognize the authorization header that OAuthConsumer made correct.

Therefore, I makes different approach to upload tumblr.

Step 1. Create OAuthHeader with only string parameters

Step 2. Create another request by using ASIFormDataRequest again and set header directly

here’s code

- (void)exportImage:(NSData *)image message:(NSString *)message withAccount:(Account *)account {

    OAToken *token = [[[OAToken alloc] initWithKey:account.token secret:account.key] autorelease];
    OAConsumer *consumer = [[[OAConsumer alloc] initWithKey:TUMBLR_API_KEY secret:TUMBLR_API_SECRET] autorelease];

    NSString *baseHost = [[account.album stringByReplacingOccurrencesOfString:@"http://" withString:@""]
                          stringByReplacingOccurrencesOfString:@"https://" withString:@""];

    NSString *requestUrl =

    [NSString stringWithFormat:@"http://api.tumblr.com/v2/blog/%@post", baseHost];

    OAMutableURLRequest *request = [[[OAMutableURLRequest alloc] initWithURL:[NSURL URLWithString:requestUrl]
                                                                    consumer:consumer
                                                                       token:token
                                                                       realm:@"http://api.tumblr.com"
                                                           signatureProvider:nil] autorelease];

    [request setHTTPMethod:@"POST"];

    [request setParameters:[NSArray arrayWithObjects:
                            [OARequestParameter requestParameter:@"type" value:@"photo"],
                            [OARequestParameter requestParameter:@"caption" value:message],
                            nil]];
    [request prepare];
    NSString *oAuthHeader = [request valueForHTTPHeaderField:@"Authorization"];
    DLog(@"OAuthHeader : %@", oAuthHeader);

    ASIFormDataRequest *req = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:requestUrl]];

    [req setRequestMethod:@"POST"];
    [req addRequestHeader:@"Authorization" value:oAuthHeader];
    [req addPostValue:@"photo" forKey:@"type"];
    [req addPostValue:message forKey:@"caption"];
    //    [req addPostValue:@"photo.jpg" forKey:@"file"];
    [req addData:image withFileName:@"photo.jpg" andContentType:@"image/jpeg" forKey:@"data"];

    [req startSynchronous];
    int statusCode = [req responseStatusCode];
    DLog(@"sending completed with status code : %d", statusCode);
    DLog(@"RESP : %@", [req responseString]);

    NSData *respData = [req responseData];

    [req release];

    if( statusCode != 201 ) {
        @throw [NSException exceptionWithName:NSLocalizedString(@"Error", @"")
                                       reason:[NSString stringWithFormat:@"status : %d", statusCode]
                                     userInfo:nil];

    }

}

Apache – tomcat 연동 virtualhost 사용

mod_jk를 사용하여 apache와 톰캣을 연동한다.

mod_jk 다운로드 : http://tomcat.apache.org/download-connectors.cgi

httpd.conf

#TOMCAT
LoadModule jk_module /ssw/apps/apache/modules/mod_jk-1.2.31-httpd-2.2.x.so

<IfModule jk_module>
JkWorkersFile /ssw/apps/apache/modules/jk_module/workers.properties
JkShmFile    /ssw/log/apache/mod_jk/mod_jk.shm
JkLogFile    /ssw/log/apache/mod_jk/mod_jk.log
JkLogLevel   trace
JkLogStampFormat "[%a %b %d %H:%M:%S %Y]"
#JkMount /*.jsp worker1
#JkMountCopy On
</IfModule>

httpd-vhosts.conf

<VirtualHost *:80>
ServerAdmin admin@adonsocial.com
DocumentRoot "/ssw/web/docs/dev"
ServerName dev.adonsocial.com
ErrorLog "/ssw/log/apache/docs/dev/error_log"
CustomLog "/ssw/log/apache/docs/dev/access_log" common
JkMount /*.jsp worker1
JkMountCopy On
</VirtualHost>

install ruby on rails and redmine on ubuntu

1. used source files

ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7-p174.tar.gz
http://rubyforge.org/frs/download.php/69365/rubygems-1.3.6.tgz
( 최신버전으로 1.6.x를 설치해보았으니 rubygem 1.6과 redmine 1.1.2와 호환되지 않는듯
http://rubyforge.org/frs/download.php/74419/redmine-1.1.2.tar.gz

2. ruby

ruby 압축을 풀고
>./configure
>make
>make install

3. rubygems 설치

압축을 풀고
>ruby setup.rb ( 필요한 경우 sudo )

4. Rails 설치

&gt;gem install rake
&gt;gem install rails -v=2.3.5
<code>&gt;gem install rack -v=1.0.1</code>
<code>
</code>

5. Mysql 구성

>mysql -u root mysql -p
mysql&gt; create database redmine character set utf8;
mysql&gt; create user 'redmine'@'localhost' identified by '암호;
mysql&gt; grant all privileges on redmine.* to 'redmine'@'localhost';

<strong>6.Redmine 구성</strong>
>cd /usr/local/
>tar xvfz /usr/local/src/redmine-1.1.2.tar.gz
>cd redmine-1.1.2/
>config/database.yml.example config/database.yml
>nano config/database.yml
   production:
   adapter: mysql
   database: redmine
   host: localhost
   username: redmine
   password:암호
   encoding: utf8
<pre id="aeaoofnhgocdbnbeljkmbjdmhbcokfdb-mousedown">&gt;gem install -v=0.4.2 i18n

>RAILS_ENV=production rake config/initializers/session_store.rb

&gt;apt-get install libmysqlclient15-dev (MySql 4.x 인 경우 libmysqlclient12-dev)
<pre id="aeaoofnhgocdbnbeljkmbjdmhbcokfdb-mousedown">&gt;gem install mysql

>RAILS_ENV=production rake db:migrate

>RAILS_ENV=production rake redmine:load_default_data

>ruby script/server webrick -e production

http://IP:3000/으로 확인

서버 종료시 Ctrl+C 사용

<strong>7. Passenger 사용하여 Rails 프로젝트 Apache에 연결</strong>
 * 참고사이트 : http://srue.net/91
> gem install passenger
  잘 안되는 경우에는 rm -r ~/.gem
> passenger-install-apache2-module
  시키는대로 설치한다.
  apache가 다른 경로에 있는 경우에는 path에 추가 후 실행한다.
> export PATH=/usr/local/apache2/bin:$PATH
  PATH를 지정해도 안되는 경우에 sudo 명령을 사용하지 말고 디렉토리 권한을 변경 후 다시 시도해본다.
  설치가 완료되면 Apache를 어떻게 수정하라고 알려준다. 알려준대로 수정 후 아파치 리스타트
* 가상호스트 없이 접속하는 방법으로
<a href="http://mattconnolly.wordpress.com/2010/09/19/redmine-ruby-on-rails-without-virtual-hosts/">http://mattconnolly.wordpress.com/2010/09/19/redmine-ruby-on-rails-without-virtual-hosts/</a>
를 참조하였으나 뭔가 오류 발생
<div id="_mcePaste">*** Exception SecurityError in spawn manager (Insecure operation - exist?) (process 27151, thread #&lt;Thread:0xb781a1ac&gt;):</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/utils/tmpdir.rb:51:in `exist?'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/utils/tmpdir.rb:51:in `passenger_tmpdir'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/utils/tmpdir.rb:31:in `passenger_tmpdir'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/abstract_server.rb:119:in `initialize'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/classic_rails/application_spawner.rb:117:in `initialize'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/spawn_manager.rb:201:in `new'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/spawn_manager.rb:201:in `spawn_rails_application'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/spawn_manager.rb:215:in `call'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/spawn_manager.rb:215:in `spawn_rails_application'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/abstract_server_collection.rb:132:in `lookup_or_add'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/spawn_manager.rb:214:in `spawn_rails_application'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/abstract_server_collection.rb:82:in `synchronize'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/abstract_server_collection.rb:79:in `synchronize'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/spawn_manager.rb:213:in `spawn_rails_application'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/spawn_manager.rb:132:in `spawn_application'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/spawn_manager.rb:275:in `handle_spawn_application'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/abstract_server.rb:357:in `__send__'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/abstract_server.rb:357:in `server_main_loop'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/lib/phusion_passenger/abstract_server.rb:206:in `start_synchronously'</div>
<div id="_mcePaste">from /usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.5/helper-scripts/passenger-spawn-server:99</div>
아직 원인 해결 못함.. ㅠㅗㅜ

DismissingAlertView

Automatically dismissing UIAlertView.

DismissingAlertView.h

//
//  DismissingAlertView.h
//
//  Created by hytgbn on 10. 4. 29..
//  Copyright 2010 hytgbn. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol DismissingAlertViewDelegate 

-(void)onDismissingAlertView:(id)control;

@end

@interface DismissingAlertView : UIAlertView <UIAlertViewDelegate> {
	id<DismissingAlertViewDelegate> dismissingDelegate;
}

@property(nonatomic, assign) id<DismissingAlertViewDelegate> dismissingDelegate;

+ (id)alertWithTitle:(NSString *)title message:(NSString*)msg interval:(NSTimeInterval)ti delegate:(id<DismissingAlertViewDelegate>)obj;
+ (id)alertWithTitle:(NSString *)title message:(NSString*)msg interval:(NSTimeInterval)ti;

@end

DismissingAlertView.m

//
//  DismissingAlertView.m
//
//  Created by hytgbn on 10. 4. 29..
//  Copyright 2010 hytgbn. All rights reserved.
//

#import "DismissingAlertView.h"


@implementation DismissingAlertView

@synthesize dismissingDelegate;

+ (id)alertWithTitle:(NSString *)title message:(NSString*)msg interval:(NSTimeInterval)ti delegate:(id<DismissingAlertViewDelegate>)obj {
	DismissingAlertView *alertView = nil;
	if( alertView = [[super alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:nil] ) {
		
		[NSTimer scheduledTimerWithTimeInterval:2 target:alertView selector:@selector(hideUI:) userInfo:nil repeats:NO];
		[alertView setDismissingDelegate:obj];
		[alertView show];
		
	}
	return [alertView autorelease];
}

+ (id)alertWithTitle:(NSString *)title message:(NSString*)msg interval:(NSTimeInterval)ti {
	return [DismissingAlertView alertWithTitle:title message:msg interval:ti delegate:nil];
}

- (void)hideUI:(NSTimer *)timer {
	[self dismissWithClickedButtonIndex:0 animated:NO];	 
	
	if( dismissingDelegate != nil ) {
		[dismissingDelegate onDismissingAlertView:self];
	}
}

@end

Usage :

    [DismissingAlertView alertWithTitle:@"Error" message:@"You got the error!" interval:3.0];

Also you can get dismissing event.
self implements DismissingAlertViewDelegate

    [DismissingAlertView alertWithTitle:@"Error" message:@"You got the error!" interval:3.0 delegate:self];