컴퓨터2012. 10. 23. 15:22

이 코드를 짜려고 그렇게 힘들었나 봅니다.. 


다음 코드는 파이썬에 트위터 아이디를 인증하는 코드입니다. 


api를 사용한 부분도 있고 부족한 부분은 BeautifulSoup으로 마무리 했습니다. 


전체 코드는 저렇고 주석으로 하나씩 설명해보도록 하죠. 


import tweepy

import urllib, urllib2

import BeautifulSoup


user_id='아이디'

password='패스워드'


def find_auth_token(page):

a=page.find('twttr.form_authenticity_token =')

b=page.find('\'',a)

c=page.find('\'',b+1)

return page[b+1:c]


## 이부분은 authorization token을 찻는 부분입니다. 

## 문자열 처리를 사용했지요. 


def find_oauth_verifier(page):

a=page.find('oauth_verifier')

b=page.find('=',a)

c=page.find('"',b+1)

return page[b+1:c]


##위의 이부분도 마찮가지 입니다. verifier값을 찻기 위해서 작성한 함수입니다. 


opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())

##urllib2로 세션을 오픈합니다. 


consumer_key  = '어플의 키값'

consumer_secret = '어플의 시크릿값'


##어플을 만들면 컨슈머키와 시킛을 발급 받을수 있습니다. 어플을 만드는건 

## http://dev.twitter.com 에 가시면 됨니다. 


auth = tweepy.OAuthHandler(consumer_key, consumer_secret)

## auth 객체를 생성합니다. 

redirect_url = auth.get_authorization_url()

## 인증 url를 받아옵니다. 

page_temp=opener.open(redirect_url).read()

## redirect_url을 열어서 authorization token을 받아오기 위해서 읽어들입니다. 

## 이 경우에는 소스보기 형식으로 문자열 저장이 됩닏. 

auth_token=find_auth_token(page_temp)


login_params = urllib.urlencode({'authenticity_token':auth_token,'session[username_or_email]':user_id, 'session[password]':password , 'Authorize app':'allow'})

## dictionary형태로 로그인 값들을 만들어 줍니다. 

## 아까 받은 authorization token을 사용합니다. 

page_content=opener.open(redirect_url, login_params) 

soup = BeautifulSoup.BeautifulSoup(page_content)

##로그인 파라미터들을 넣고 페이지를 열어서 beautifulSoup로 열어줍니다. 

tag=soup.findAll('meta')[3]

verifier=find_oauth_verifier(str(tag))

##verifier를 찻는 과정이구요. 소스 열어보시면 뭘 하는건지 알게 되실거에요. 

auth.get_access_token(verifier)

##verifier를 통해 유저의 access_token을 얻고, 이제 계정에 권한에 접근할수 있습니다. 


api = tweepy.API(auth)

## api 객체를 생성하구요. 


api.update_status("test tweet")

##테스트로 트윗을 날려봤습니다. 



이 과정을 습득하느라 얼마나 많은 삽질을 했는지 모르겠습니다. 

우리나라, 외국 모든 구글을 뒤져도 잘 나오지 않는 정보라 포스트 해봅니다. 

중간에 한 한국분의 포스트가 상당히 결정적으로 잘 설명되어 있어서 도움이 많이 되었습니다. 


http://imp17.com/tc/myevan/archive/201103


아! 이분이시군요. ㅎ


Posted by blindfish
컴퓨터2012. 8. 11. 02:13

보통 파이썬에서 웹브라우져를 띄우는 방법은 간단히 생각나는건. 


>>import os

>>os.system('explorer http://blindfish.tistory.com')


이러한 방법이 있지만 이런경우 특정 웹브라우저에 한정되기 마련이다. 

그래서 다음과 같은 방법을 쓴다. 


>>import webbrowser

>>url = 'http://blindfish.tistory.com'

>>webbrowser.open(url)


대충 이러한 방법들이군요.. 나중에 상당히 쓸만할듯.. 

Posted by blindfish
컴퓨터2012. 8. 11. 00:28

언젠간 누군가 한번 보시고 짜보길.. 


#include<stdio.h>

#include<stdlib.h>


int fib(int n);

int fib_eter(int n);


int main(int argv, char **argc)

{

int n=atoi(argc[1]);

printf("fib(%d)==%d\t%d\n", n, fib(n), fib_eter(n));


return 0;

}


int fib(int n)

{

if(n==0)

return 0;

else if(n==1)

return 1;

else

return fib(n-1)+fib(n-2);

}


int fib_eter(int n)

{

int a=0,b=1;

int c;

if(n==0)

return 0;

else if(n==1)

return 1;

while(n>1)

{

c=a+b;

a=b;

b=c;

n--;

}

return c;

}



Posted by blindfish
컴퓨터/linux2012. 3. 28. 02:14

latex의 dvi 파일을 txt로 바꿔주기    

catdvi -e 1 -U file.dvi | sed -re "s/\[U\+2022\]/*/g" | sed -re "s/([^^[:space:]])\s+/\1 /g" > file.txt


이 한줄의 스크립이 엄청난 힘을 가지고 있다..

Posted by blindfish
컴퓨터2012. 1. 18. 01:07
시간이 없는 관계로 길게는 포스팅을 못하겠지만..  지난 삽질을 생각하면 눈물이 앞을 가린다.. ㅠ_ㅠ 

우선 포스팅을 해주신 이분
http://cshong.tistory.com/entry/py2exe-인스톨-팩토리-install-factory-사용법

이분에게 깊은 경외와 감사를 보내며..
긴삽질을 마치려고 한다. (물런 테스트 해봐야 아는거지만;; ) 

python 코드를 exe파일로 만드는 법은 우선 py2exe란 패키지가 필요하다. 
그다음에 만드는 법은 웬만한 웹사이트에 잘 알려져 있다.
하지만 나처럼 배포판으로 하나의 실행파일로 만들고 싶은 경우 이야기가 조금 다르다.

위의 링크의 방법대로

from distutils.core import setup
import py2exe

excludes = [
    "pywin",
    "pywin.debugger",
    "pywin.debugger.dbgcon",
    "pywin.dialogs",
    "pywin.dialogs.list",
    "win32com.server",
]

options = {
    "bundle_files": 1,                 # create singlefile exe
    "compressed"  : 1,                 # compress the library archive
    "excludes"    : excludes,
    "dll_excludes": ["w9xpopen.exe"]   # we don't need this
}

setup(
    options = {"py2exe": options},
    zipfile = None,                    # append zip-archive to the executable
    console = ["sample.py"]
)

이것을 넣고 돌려주면 무리 없이 완성된다..

ps. 그외에 한동안 삽질을 한게 있었는데 기존 소스코드에서 import한 파일이 include가 안되는 경우다.
이 경우에는 패키지 파일을 직접 python의 디렉토리에 넣어놓으면 자연스럽게 해결된다.
(???.egg파일을 압축을 풀어서 디렉토리에 넣으면 끝. ) 
 

자.. 이제 테스트 결과를 기다려 볼까..

 
Posted by blindfish
컴퓨터2011. 10. 31. 12:10
연구실 형님에게 설명해주려고 간단히 쓴 이메일입니다. 다시 보니 나름 잘 설명해놨네요.

우선은 간단하게 python을 설치 하셨으면 다음과 같은 패키지들을 더 설치 해야합니다.

먼저 numpy 라고 불리는 패키지 인데.. 흠... 이건 정확하게 윈도우에서 어떻게 설치하는지 알고 있는 바가 없어요.
(리눅스에선 sudo apt-get install python-numpy 이거 하나면 끝;; )


여기 링크를 들어가니까 설치하는 법이 있네요. 이것만 설치하면 나머지는 의존성 있는 패키지 까는것에 아주 쉬워져요. 

이걸 일단 설치하면 easy_install 이란 명령어로 여러가지 패키지를 설치하는데 쉬워져요.

도스창에서 

>easy_install twitter

라고 치면 twitter 관련 api가 설치됨니다. (아마도; 맞을거에요. 리눅스에선 apt로 python-twitter 이거면 끝이죠. ㅎ)

설치가 완료되면 이제 본격적으로 시작할수 있는데요. 


이 페이지를 참고하시면 쉬울거에요. 

>>import twitter
우선 패키지를 불러오구요.

>>api=twitter.Api()
api라는 어떤 변수(object?)에 넣습니다. 

>>statuses=api.GetPublicTimeline()
이렇게 statuses란 변수에 현재 전세계에서 트위터에 올라오는 글을 실시간으로 받은후에.

>>print [s.user.name for s in statuses]

이런 식으로 출력하면 되는거죠. 

['Libbie Galindo', u'\u5343\u96c5\u8336\u623f', u'\u30a4\u30a8\u30db\u30af', 'SantiagO Ruiz', "Chalan' ", 'Rachel Chu', 'Michael Pritchett', 'Kevin Miller', 'Hailey Johnson', 'njrym1011', 'Chassity A.', 'D~air', 'Matthew Martinez III', 'Manu Newells Maure', 'hidemi', u'\u3044\u3057 \u3042\u3044', 'Richard', 'chelly ', u'\u2708Dos_Cabeza \u2708 FLYing', 'Michael Iaconetti']

이런 글들이 출력되네요. 

앞에는 유저네임인거 같구요. u 다음에는 실제 트윗글인것 같습니다. 

영어를 제외한 다른 글들은 저런식으로 인코딩이 이상하게 나오는데요. 
아직 요것은 어떻게 하는지 잘은 모르겠어요.

다음으론 
>>> statuses = api.GetUserTimeline(user)
>>> print [s.text for s in statuses]

이거 같은경우에는.. 어떤 유저의 타임라인을 가져오는건데요. 
user라고 쓴 부분에 'blindfish_' 이런 식으로 넣으면 됨니다. 

그럼 [u'@shinbbong \uc5f0\uad6c\uc2e4\uc774\ub0d0 \u314b \ucd94\uc6b4 \uacc4\uc808\uc774\uc9c0 \u314b', u'@minjuletter \ud5db;; \uc800\ub3c4;; \uc624\ub298\uc740 \ub0a0\uc774 \uc548\uc88b\uc740\uac00 \ubcf4\ub124\uc694;;', u'@titan2573 GMF\uac00\uc2e0\uac74\uac00\uc694?? \u314b', u'@chisun84 \uadf8\ub7f4\ub550 \uc0dd\uac01\uc744 \ud558\uba74 \uc548\ub3fc \uadf8\ub0e5 \ub2ec\ub824\uac00\uc11c \uc778\uc0ac \ud558\ub294\uac70\uc57c \u314b\u314b\u314b', u'@chisun84 \uc624\ub298 \ub108\uc758 \uc6b4\uc744 \ub2e4\uc168\ub2e4;;', u'ktx\ube60\ub974\ub124 \u314b (@ \ubd80\uc0b0\uc5ed (KTX Busan Sta.) w/ 3 others) http://t.co/ClHMht8r', u'\ub09c \ub208\uc6c3\uc74c\uc774 \uc608\uc05c \uc5ec\uc790\ub97c \uc88b\uc544\ud558\ub294\uad6c\ub098.. \ube0c\ub85c\ucf5c\ub9ac\ub108\ub9c8\uc800\uc758 \uc601\uc0c1\uc744 \ubcf4\ub2e4\uac00.. \ub958\uc9c0\uc758 \ub208\uc6c3\uc744\uc744 \ubcf4\uace0 \uc54c\uc558\uc74c;; #fb', u'@ysprime \uc2e4\uc81c\ub85c \ub4e4\uc5b4 \ubcf8\uc801\ub3c4 \uc788\uace0 \ud558\uace0 \uc788\ub294 \ud559\uc0dd\ub3c4 \ubcf8\uc801 \uc788\uc2b5\ub2c8\ub2e4. @sioum', u'\ub2a6\uc740 \uc2dc\uac04 \ubf40\uae00\uc774.. GOP\uac00 \ub5a0\uc624\ub978\ub2e4.. http://t.co/MH7RsftD', u'@seongwhi \ub208\uc740 \ub9ce\uc774 \uc815\ucc29\ub418\uc5c8\ub098\uc694?', u'@hachuly \ud615 \uc5f0\uad6c\uc2e4\uc774\uc5d0\uc694?', u"\ube0c\ub85c\ucf5c\ub9ac \ub108\ub9c8\uc800 '\uc0ac\ub791\ud55c\ub2e4\ub294 \ub9d0\ub85c\ub294 \uc704\ub85c\uac00 \ub418\uc9c0 \uc54a\ub294' http://t.co/d287uUUT"]

이런식으로 저의 타임라인이 나오게 되죠. 역시나 한글은 깨져서 나오구요. 

맨처음이 봉규(@shinbbong)란 후배에게 보내는 맨션이 담겨져 있습니다. 

그다음 기능들은 유저인증 (authentication) 을 하고 나서 뭔가를 더 할수 있는데.. 
저는 이것을 시도해 보다가 아직 성공하지 못했습니다. 

더 디테일한 정보는 
$ pydoc twitter.Api
pydoc이란 명령어로 쳐서 보시면 

더 자세하고 디테일한 사용법이 알려져 있어요. 

처음 파이썬을 사용하시면 반복 loop나 리스트 변수의 기능들이 잘 이해가 되지 않는 경우가 많아요. 

이부분을 잘 보고 쓰시면 코드 보기가 한결 수월해질거에요. 

파이썬은 다른 언어처럼 filename.py 이런 파일을 생성해서 

코드(라고 하기엔 거의 스크립;;)를 넣어서 쉽게 사용할수 있으니 참고 하세요. ^^






이전에 올린 글이 맥과 윈도우에선 안되더라구요.
새로운 방법을 제시하였습니다.

twitter 패키지는 맥과 윈도우에서 너무 안되서 tweepy라고 하는 패키지를 사용하였는데

너무 잘 되네요.

아래 두개의 블로그를 참고 해서 해봤어요.

http://jof4002.net/냥날/PythonTwitter

http://www.halotis.com/2009/09/19/python-twitter-api-library-reviews-and-samples/

방법은 전과 동일하게 easy_install 을 이용해서 tweepy 를 설채해줍니다.

일단 간단한 test code를 보여드릴게요.

>>from tweepy import *
>>api=API()
>>public_timeline = api.public_timeline()
>>print [tweet.text for tweet in public_timeline]

이렇게 입력 하시면

우선은 public timeline 을 가지고 올게에요.
Posted by blindfish
컴퓨터/linux2011. 7. 4. 23:41
우리나라에 이런 설명이 없는게 너무 아쉬워서 제가 하나 써내려 갑니다.
하.. 하루종일 이 간단한걸 해보기 위해 구글을 뒤지고 다녔던 걸 생각하면 눈물이 앞을 가리네요.

 우선 출처부터 써내려 갑니다. 
 
http://www.daniweb.com/software-development/python/threads/119693 

 제가 하려고 하는것은 어떤 컬럼으로 구분된 데이터 파일에 있는 숫자를 읽어서 

각각의 변수들을 제가 원하는 어떤 함수에 집어 넣는것입니다.

참 간단한데. 아무리 찻아도 찻아도 찻을수가 없는.. 팁입니다.

우선 numpy 라고 불리는 numerical한 계산을 많이 해주는 패키지를 import 합니다.
(앞으로 물리학을 하면서 python을 계속 쓰려면 이 패키지를 심층 분석해봐야 겠습니다. ) 

>>from numpy import *
>>f = loadtxt("test.txt")
>>firstculum = f[:, 0]
>>print firstculum
[1,2,3,....., 999, 1000] 


딱 봐도 느낌이 팍오는 소스입니다.  
 
첫번째 컬럼을 읽는 소스이죠? 
이제 잘 활용해서 쓰기만 하면 되겠죠?  
Posted by blindfish
컴퓨터/linux2011. 4. 8. 18:37
리눅스를 사용하는 많은 분들이 즐겨 쓰는 컴파일러는 단연 gcc 이죠. 리눅스의 웬만한 프로그램들의 기본을 이루고 있을 뿐만 아니라 무엇보다도 무료라는 점이 매력적입니다. (vidual stdio의 가격을 생각해 본다면 참;; )

그런데 의외로 사람들이 잘 모르는 부분중에 하나가 gcc가 시중에 있는 웬만한 컴파일러에 비해 컴파일한 프로그램의 속도가 느리다는 것입니다. 계산 과학쪽을 하는 사람들뿐만 아니라 어떤 상용프로그램들도 느리다는 건데요. (그렇다고 인텔 cpu에서만 작동하는 프로그램도 웃기겠네요.)
그런 문제를 해결해 주는 상당히 고속의 컴파일러가 있습니다. 
바로 intel compiler에요. ^^ 리눅스에서 명령어로 쓸려면 icc 라고 쓰고 gcc랑 동일하게 사용하시면 됨니다. 

우선 설치를 해보도록 하죠. 먼저 인텔 홈페이지에 들어가서 무료인 noncommercial version을 받습니다. noncommercial version은 아쉽게도 맥이나 윈도우에서는 사용할수가 없습니다. 
가서 약관에 동의하고 자신의 머신의 기종에 따라(32bit인지 64bit인지) 컴파일러를 다운받습니다.  기종을 확인하는 법은
$cat /proc/cpuinfo
를 봐서 CPU기종을 확인 하는 방법이 있고
$uname -a
란 명령어로 운영체제의 종류를 파악합니다. i686 이면 32bit, x86_64이면 64bit 입니다. 중간에 메일주소를 써줘야하는데 잘 써줘야 합니다. 그래야 씨리얼번호가 제대로 오거든요. 
다운을 다 받았으면 먼저 JAVA Runtime Environment 란걸 먼저 설치해줍니다. 이게 없으면 인스톨이 안되요. 원래 어느정도 충족조건이 있지만 웬만한건 다 충족하고 이게 충족이 잘 안됩니다. 

$sudo apt-get install gcj

JAVA Runtime Environment 가 이렇게 설치가 되면

$tar xvfz l_ccompxe_(.....).tgz
$cd ./l_ccompxe_(.......)
$sudo ./install.sh
을 해주면 인스톨을 하기 시작합니다. 

Step no: 1 of 6 | Welcome
--------------------------------------------------------------------------------
Welcome to the Intel(R) Composer XE 2011 Update 2 for Linux* installation
program.

Intel(R) C++ Composer XE 2011 Update 2 for Linux* includes not only the
high-performance Intel(R) C++ Compiler XE, but also Intel(R) Debugger, Intel(R) 
Threading Building Blocks (Intel(R) TBB), Intel(R) Integrated Performance
Primitives (Intel(R) IPP), and Intel(R) Math Kernel Library (Intel(R) MKL) to
create a strong foundation for building robust, high performance parallel code
at significant price savings.
--------------------------------------------------------------------------------
You will complete the steps below during this installation:
Step 1 : Welcome
Step 2 : License
Step 3 : Activation
Step 4 : Options
Step 5 : Installation
Step 6 : Complete
--------------------------------------------------------------------------------
Press "Enter" key to continue or "q" to quit: 

이런글이 나옵니다. 간단한 설명인데 그냥 엔터 치시면 됨니다. 

Step no: 1 of 6 | Options > Missing Optional Pre-requisite(s)
--------------------------------------------------------------------------------
There is one or more optional unresolved issues. It is highly recommended to fix
it all before you continue the installation. You can fix it without exiting from
the installation and re-check. Or you can quit from the installation, fix it and
run the installation again.
--------------------------------------------------------------------------------
Missing optional pre-requisite
-- unsupported OS
--------------------------------------------------------------------------------
1. Skip missing optional pre-requisites [default]
2. Show the detailed info about issue(s)
3. Re-check the pre-requisites

h. Help
b. Back to the previous menu
q. Quit
--------------------------------------------------------------------------------
Please type a selection or press "Enter" to accept default choice [1]: 

지원하지 않는 운영체제다고 하는데 그냥 무시하시면 됨니다. 
그다음에 약관이 좌르륵 나옵니다. 알았다고 accept이라고 타이핑하고 엔터

Step no: 3 of 6 | Activation
--------------------------------------------------------------------------------
If you have purchased this product and have the serial number and a connection
to the internet you can choose to activate the product at this time. Activation
is a secure and anonymous one-time process that verifies your software licensing
rights to use the product. Alternatively, you can choose to evaluate the
product or defer activation by choosing the evaluate option. Evaluation software
will time out in about one month. Also you can use license file, license
manager, or the
system you are installing on does not have internet access activation options.
--------------------------------------------------------------------------------
1. I want to activate my product using a serial number [default]
2. I want to evaluate my product or activate later 
3. I want to activate either remotely, or by using a license file, or by using a
   license manager

h. Help
b. Back to the previous menu
q. Quit
--------------------------------------------------------------------------------
Please type a selection or press "Enter" to accept default choice [1]: 
 
라이센스를 인정받으라고 하네요. 우리는 씨리얼 넘버가 있으니까 엔터를 쳐서 1번으로 갑니다.

다음에 바로 씨리얼 넘버 넣으라고 하는데 침착하게 이메일에 있는 씨리얼넘버를 넣어줍니다.

--------------------------------------------------------------------------------
Activation completed successfully.
--------------------------------------------------------------------------------
Press "Enter" key to continue: 

된다고 하네요. ㅎ 

 --------------------------------------------------------------------------------
You are now ready to begin installation. You can use all default installation
settings by simply choosing the "Start installation Now" option or you can
customize these settings by selecting any of the change options given below
first. You can view a summary of the settings by selecting 
"Show pre-install summary".
--------------------------------------------------------------------------------
1. Start installation Now

2. Change install directory      [ /opt/intel/composerxe-2011.2.137 ]
3. Change components to install  [ All ]
4. Show pre-install summary

h. Help
b. Back to the previous menu
q. Quit
--------------------------------------------------------------------------------
Please type a selection or press "Enter" to accept default choice [1]: 

이제 인스톨을 하려고 합니다. 원래 이부분은 dependency라고 하죠. 깔수있는 조건들을 만족하는지 확인하는 곳입니다. gcj를 깔았으니 조건을 잘 만족하는거죠. 혹시 안되더라도 깔라고 시키는것만 잘 깔면 됨니다. 엔터.

Step no: 5 of 6 | Installation
--------------------------------------------------------------------------------
Each component will be installed individually. If you cancel the installation,
components that have been completely installed will remain on your system. This
installation may take several minutes, depending on your system and the options
you selected.
--------------------------------------------------------------------------------
Installing Intel(R) C++ Compiler XE 12.0 Update 2 for Linux*
              (for applications running on IA-32) component... done
--------------------------------------------------------------------------------
Installing Intel(R) Debugger 12.0 Update 2 for Linux*
              (for applications running on IA-32) component... done
--------------------------------------------------------------------------------
Installing Intel(R) Math Kernel Library 10.3 Update 2 for Linux*
              (for applications running on IA-32) component... done
--------------------------------------------------------------------------------
Installing Intel(R) Integrated Performance Primitives 7.0 Update 2 for Linux*
              (for applications running on IA-32) component... done
--------------------------------------------------------------------------------
Installing Intel(R) Threading Building Blocks 3.0 Update 5 core files and
examples for Linux* component... done
--------------------------------------------------------------------------------
Press "Enter" key to continue

살살 깔리네요. 엔터.

 Step no: 6 of 6 | Complete
--------------------------------------------------------------------------------
Thank you for installing and for using the
Intel(R) Composer XE 2011 Update 2 for Linux*.

Support services start from the time you install or activate your product, so
please create your support account now in order to take full advantage of your
product purchase. Your Subscription Service support account provides access to
free product updates interactive issue management, technical support, sample
code, and documentation.

To create your support account, please visit the Subscription Services web site
https://registrationcenter.intel.com/RegCenter/registerexpress.aspx?clientsn=N5D
5-F4K7MMS7

To get started using Intel(R) Composer XE 2011 Update 2 located in
/opt/intel/composerxe-2011.2.137: 
- Set the environment variables for a terminal window using one of the following
  (replace "intel64" with "ia32" if you are using a 32-bit platform).
     For csh/tcsh:
        $ source install-dir/bin/compilervars.csh intel64
     For bash:
        $ source install-dir/bin/compilervars.sh intel64
     To invoke the installed compilers:
        For C++: icpc
        For C: icc
        For Fortran: ifort
  To get help, append the -help option or precede with the man command.
- To view a table of getting started documents: 
  install-dir/Documentation/en_US/documentation_c.htm.

Movies and additional training are available on our website at
www.intel.com/software/products.
--------------------------------------------------------------------------------
q. Quit [default]
--------------------------------------------------------------------------------
Please type a selection or press "Enter" to accept default choice [q]: 

잘깔렸다고 하네요. 그 다음에 shell에 설정을 해주어야 쓸수가 있는데요. 우리는 모두 bash 쉘을 쓰니까 $ source install-dir/bin/compilervars.sh intel64 쓰면 되겠네요. installed-dir 은 일반적으로 /opt/intel/composerxe-(......)에 있습니다.

$echo "source /opt/intel/composerxe-(......)/bin/compilervars.sh intel64" >> ~/.bashrc
위에 써있듯이 64bit면 intel64 를 쓰고 32bit면 ia32라고 써야합니다.
$bash
bash 한번 실행해주고 나서 
$icc 
라고 치면 잘 된다는걸 알수 있습니다. ^^ 이제 잘 쓰기만 하면되요.
(C++은 icpc란 명령어를 사용합니다. fortran은 ifort)

제 경험상 계산 시간이 1/3정도 더 줄어들더라구요. 1/3이 작아 보이지만 삼일 계산할걸 이틀만에 끝낸다는거니.. 정말 기가 막힙니다. 알고리즘에 따라서 반 정도밖에 안걸리거나 빨리지지 않는 경우도 있는데 그건 어쩔수 없죠. ㅋ 그래도 피부로 느낄수 있는 속도향상을 맛볼수가 있습니다. 
Posted by blindfish
컴퓨터/linux2011. 4. 7. 21:44
Ubigraph 란 것을 알게된지도 좀 됬었는데 그동안 포스팅을 한다고한다고 하는걸 이제야 포스팅 하게 되네요. 물런 잘쓰시는 분은 그냥 보기만 하면  바로바로 따라 하실수 있습니다. 
Ubigraph란 어떤 종류의 네트워크나 시스템의 움직임이나 모습을 시뮬레이션을 하면서 실시간으로 그것들의 동력학적 변화를 눈으로 볼수 있게 해주는 아주 유용한 툴입니다.  일단 동영상을 보시죠.  


그냥 봐도 화려하죠?  
우선 설치하는 법부터 알려드리죠. 


http://ubietylab.net/ubigraph/index.html

홈페이지에 들어가셔서 자신의 컴퓨터와 운영체제에 맞는 것을 다운로드 합니다. 

$ tar xvfz UbiGraph-....tar
$ cd UbiGraph-...
$ bin/ubigraph_server & (empty black window)
$ cd examples/Python
$ ./run_all.sh
이렇게 하면 설치가 완료된것입니다. 마지막에 보면 실행이 잘 될거에요. 중간에 검은 윈도우가 떠야합니다. 그게 안뜨면 안돼요. 그게 안될경우에는 xmlrpc쪽이 문제일수도 있지만 웬만하면 잘 뜹니다. 잘 안뜨면 컴퓨터가 정말 이상한것일 가능성이 있습니다. 이 글을 쓰면서 그 문제를 어떻게 해결해야 하는 기억이 나지 않아서 한 4시간을 버렸네요... 정말 이럴때마다 이런야가 너무 싫어지네요. 너무 화가 나요. 전에 몇번 깔아 봤었기 때문에 쉬울줄 알았는데 엉뚱하고 쓸데없는데서 시간을 허비했네요 ㅠ_ㅠ 다시한번 기록의 중요성을 느낌니다. 이제 뭘 하든간에 무조건 다 기록하는 습관을 남겨야겠습니다. 

홈페이지에 나온 템플릿대로 쓰면 웬만하면 다 됩니다. 
소스 코드에 대한 설명을 하자면 이것은 랜덤 그래프인데요. 

소스코드 쓰실땐 한글부분은 모두 지우고 쓰세요. 

#!/usr/bin/python

import random as rd
#랜덤함수를 사용하기 위해서 라이브러리를 불러줍니다.

import xmlrpclib 

import time
#중간에 쉬는 시간을 주기위해 넣어줍니다. 너무 빨리 없어지면 보지를 못하죠. 


server_url = 'http://127.0.0.1:20738/RPC2'

server = xmlrpclib.Server(server_url)

G=server.ubigraph
#이 부분은 템플릿이라고 생각하시면 됩니다. 자세한건 저도 xml쪽을 잘 몰라서 모르겠네요. 


G.set_edge_style_attribute(0, "color", "#fff000")

G.set_edge_style_attribute(0, "width", "3.0")
#edge 즉 링크의 색과 굵기를 지정해줍니다. 


G.set_vertex_style_attribute(0, "color", "#ff0000")

G.set_vertex_style_attribute(0, "shape", "sphere")

#vertex 즉 노드의 색과 모양을 지정해 줍니다. 크기도 조절할수 있고 라벨도 붙일수 있습니다.

for i in range(100) :

G.new_vertex_w_id(i)
#일단은 공간에 노드들을 만들어서 뿌립니다.  


time.sleep(0.5)
#잠깐 쉬어주구요. 

for i in range(100) :

for j in range(i+1, 100) :

if rd.random() < 0.15 :

G.new_edge(i,j)

time.sleep(0.1)

#어떤 확률에 따라서 가능한 링크들을 연결해줍니다. 

ubigraph의 장점은 무엇보다도 웬만한 모든 언어를 지원 한다는 것입니다. 어떤 놈들을 python만 지원 되거나 어떤 놈들은 c만 지원 되거나 하는 단점이 있는데 이 프로그램은 들어본 거의 모든 언어에 사용할수 있다는 장점이 있습니다. 

홈페이지에 들어가면 아주 다양하게 응용해서 쓰는데요. 물리학분야에서 많이 쓸수 있을거라고 기대해 봅니다. 이것을 이용해서 복잡한 분자의 구조라던지 결정모양의 고체의 구조를 나타낼수 있을 뿐만 아니라, 그것들을 움직이게 하므로써 물질의 동력학적인 행동들을 눈으로 확인할수 있다는 장점이 있습니다. 

Posted by blindfish
컴퓨터/linux2011. 3. 29. 15:13
gnuplot을 쓰다 보면 대부분 사람들이 그렇지만 (저도 그렇고) 그냥 패키지를 apt-get 으로 깔아서 사용합니다. 
sudo apt-get install gnuplot 

하지만 이렇게 하는 경우 종종 불편을 호소하는 경우가 많은데요.  
del키가 안먹는 다든가.. 맘에 안드는 wxt를 써야 한다던가의 일이죠. (전 그냥 깔아서 쓰는걸 좋아합니다..ㅠ_ㅠ 삽질 미워요..)
X11 포워딩으로 쓰는게 좋기도 하구요.(결국 실패.. ) 확실히 한번 고생하면 그후론 참 편하죠.

  • libwxgtk2.8-dev – for the wxt terminal
  • libpango1.0-dev – for the cairo (pdf, png) and wxt terminals
  • libreadline5-dev – readline support (editing command lines)
  • libx11-dev and libxt-dev – X11 terminal
  • texinfo (optional) – needed for the tutorial
  • libgd2-xpm-dev (optional) – old png, jpeg and gif terminals based on libgd

sudo apt-get install libwxgtk2.8-dev libpango1.0-dev libreadline5-dev libx11-dev libxt-dev texinfo libgd2-xpm-dev

컴파일 인스톨을 위해선 우선 위의 패키지가 꼭 필요 합니다. 

그다음에 웹에서 gnuplot 의 소스 파일을 다운 받습니다.

압축을 풀고 (tar xvf gnuplot-4.4.3.tar)
디렉토리로 들어갑니다. (cd gnuplot-4.4.3)
자.. 이 작업이 끝났으면
./configure
make
make check 
(gnuplot 이 잘 작동하는지 테스트합니다. skip하셔도 됨. 현란한 움직임들을 보고 있자니 제가 gnuplot의 능력을 1%도 못쓰고 있다는 기분에 빠져듭니다.. =_=;;;)
sudo make install

끝... 참 쉽죠? 이럼 wxt기준으로 깔리면서 텝이나 다른 커멘드라인 명령어를 잘 수행하는 gnuplot을 설치하게 됩니다.

원래는 ./configure 뒤에 많은 옵션들을 해줘야 하지만..
( ./configure --prefix=$HOME/usr --enable-history-file --with-readline=gnu --x-include=/usr/include/X11 --x-libraries=/usr/X11/lib 이런 옵션들요.. )

요즘은 이렇게만 해도 잘 깔리네요.. 

ps. X11을 터미널로 설정하는 법 알아냈습니다. 위의 방법을 쓴다음에 .gnuplot 이란 파일을 홈디렉토리에 만들어서 set term x11을 한줄 넣으시면 됨니다. 그냥 echo "set term x11" > .gnuplot 하시면 되겠네요. ㅋ  
Posted by blindfish