2014년 12월 24일 수요일

CentOS에서 sudo 명령어 사용

CentOS는 일반사용자가 루트권한을 일시적으로 획득하는 sudo 명령어가 비활성 상태이다.
/etc/sudoers 파일을 수정하면 CentOS에서도 sudo를 이용할 수 있다.


[root@cet dev]$ ls -al /etc/sudoers
-r--r----- 1 root root 3381  3월 11  2014 /etc/sudoers

[root@cet dev]$ chmod u+w /etc/sudoers

[root@cet dev]$ ls -al /etc/sudoers
-rw-r----- 1 root root 3381  3월 11  2014 /etc/sudoers


[root@cet dev]# tail /etc/sudoers
## Same thing without a password
# %wheel ALL=(ALL) NOPASSWD: ALL

## Allows members of the users group to mount and unmount the
## cdrom as root
# %users  ALL=/sbin/mount /mnt/cdrom, /sbin/umount /mnt/cdrom

## Allows members of the users group to shutdown this system
# %users  localhost=/sbin/shutdown -h now

/etc/sudoers 파일에 설정 추가

[root@cet ~]$ vi /etc/sudoers

# 특정 사용자가 sudo를 사용할 수 있도록 설정.
dev   ALL=(ALL)       ALL

# 그룹내에 모든 사용자가 이용할 수 있도록 설정.
%wheel  ALL=(ALL)       ALL

# 비밀번호 없이 사용
%wheel  ALL=(ALL)       NOPASSWD: ALL
dev   ALL=(ALL)       NOPASSWD: ALL

/etc/sudoers 파일의 퍼미션은 440이어야 하며 퍼미션 조정이 되어 있지 않으면 아래와 같은 에러가 발생.
[dev@cet ~]$ sudo tail /etc/sudoers
sudo: /etc/sudoers is mode 0640, should be 0440
sudo: no valid sudoers sources found, quitting

root 계정으로 로그인 후 퍼미션 조정
[dev@cet ~]$ su -
[root@cet ~]# chmod u-w /etc/sudoers

2014년 12월 14일 일요일

MacVim 관련 단축키



.vimrc에 직접 설정한 단축키

noremap <c-tab> :tabnext<cr> = vim의 탭이동 ( ctrl + tab )
noremap <c-n> :NERDTreeToggle<CR> = NERDTree 토글 단축키 (ctrl + n)


Vim command모드 단축키

i : insert모드로 변경(커서앞)
a : insert모드로 변경(커서뒤)
A : insert모드로 변경(라인마지막)
x : 커서에 있는 문자 삭제
dd : 한개 라인 삭제
yy : 라인 복제
p : 삭제했거나 복제한 라인 붙여넣기(커서뒤)
P : 삭제했거나 복제한 라인 붙여넣기(커서앞)

/ : /뒤에 오는 문자열 검색
G : 문서의 마지막 라인으로 이동
     1G : 문서의 첫라인으로 이동
     100G : 100번째 라인으로 이동
:wq : 저장하고 나가기
:q! : 저장안하고 바로 나가기


NERDTree

T - NERDTree에서 탭 생성 
t - NERDTree 화면이 없는 탭 생성
gT, gt - Tab 이동


ctrl + q + w - 열려있는 창 닫기
ctrl + ww / ctrl wh - 창 간의 이동



2014년 12월 13일 토요일

iTerm + MacVim + python-mode

django의 잦은 command line 이용때문에 eclipse pydev 에디팅 대신 MacVim을 이용하기로 했다.

환경은 iTerm + MacVim + python-mode + 기타 번들 인스토

현재까지 작성된 .vimrc

"한글깨짐 방지
set enc=UTF-8

set fileencodings=UTF-8

set nocompatible              " be iMproved, required

filetype off                  " required

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/vundle/
call vundle#rc()

call pathogen#infect()
call pathogen#helptags()

" alternatively, pass a path where Vundle should install bundles
"let path = '~/some/path/here'
"call vundle#rc(path)

" let Vundle manage Vundle, required
Bundle 'gmarik/vundle'

" The following are examples of different formats supported.
" Keep bundle commands between here and filetype plugin indent on.
" scripts on GitHub repos
Bundle 'tpope/vim-fugitive'
Bundle 'Lokaltog/vim-easymotion'
Bundle 'tpope/vim-rails.git'
" The sparkup vim script is in a subdirectory of this repo called vim.
" Pass the path to set the runtimepath properly.
Bundle 'rstacruz/sparkup', {'rtp': 'vim/'}
" scripts from http://vim-scripts.org/vim/scripts.html
Bundle 'L9'
Bundle 'FuzzyFinder'
" scripts not on GitHub
Bundle 'git://git.wincent.com/command-t.git'
" git repos on your local machine (i.e. when working on your own plugin)
" python lint
Bundle 'klen/python-mode'
" directory
Bundle 'scrooloose/nerdtree'
" powerline
Bundle 'Lokaltog/powerline', {'rtp': 'powerline/bindings/vim/'}


filetype plugin indent on     " required
syntax on

noremap <c-tab> :tabnext<cr>
noremap <c-n> :NERDTreeToggle<CR>

" Python-mode
" Activate rope
" Keys:
" K             Show python docs
" <Ctrl-Space>  Rope autocomplete
" <Ctrl-c>g     Rope goto definition
" <Ctrl-c>d     Rope show documentation
" <Ctrl-c>f     Rope find occurrences
" <Leader>b     Set, unset breakpoint (g:pymode_breakpoint enabled)
" [[            Jump on previous class or function (normal, visual, operator modes)
" ]]            Jump on next class or function (normal, visual, operator modes)
" [M            Jump on previous class or method (normal, visual, operator modes)
" ]M            Jump on next class or method (normal, visual, operator modes)
let g:pymode_rope = 1

" Documentation
let g:pymode_doc = 1
let g:pymode_doc_key = 'K'

"Linting
let g:pymode_lint = 1
let g:pymode_lint_checker = "pyflakes,pep8"
" Auto check on save
let g:pymode_lint_write = 1

" Support virtualenv
let g:pymode_virtualenv = 1

" Enable breakpoints plugin
let g:pymode_breakpoint = 1
let g:pymode_breakpoint_key = '<leader>b'

" syntax highlighting
let g:pymode_syntax = 1
let g:pymode_syntax_all = 1
let g:pymode_syntax_indent_errors = g:pymode_syntax_all
let g:pymode_syntax_space_errors = g:pymode_syntax_all

" Don't autofold code
let g:pymode_folding = 0


2014년 11월 27일 목요일

Mac의 eclipse에 pydev3.x를 설치했는데도 메뉴에 나타나지 않는 문제

맥의 매버릭 이후 eclipse에 pydev3.x를 설치했으나 메뉴에 나타나지 않는 문제가 발생
JDK 1.7 설치로 해결



    1. Unistall PyDev
    2. Under Eclipse > preferences > Installed JREs you probably only see Java SE 6
    3. Download and install JDK 1.7 from http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html
    4. open terminal and run "/usr/libexec/java_home -v 1.7"
      this will return the directory in which JDK 1.7 reside, something like /Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home
    5. Under Eclipse > preferences > Installed JREs click "add", select "MacOS X VM", click "next"
    6. in JRE Home paste your version of /Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home, give it a name and click "Finish"
    7. Restart Eclipse and re-install PyDev.
http://stackoverflow.com/a/23671271


JDK를 잘못 설치했을 경우

#cd /Library/Java/JavaVirtualMachines
#sudo rm -rf jdk1.7.0_06.jdk

2014년 11월 25일 화요일

CentOS + Apache + mod_wsgi + python + django + mysql


1.django 프레임웍 설치

$ git clone https://github.com/django/django.git
$ cd django
$ python setup.py install
$ python
>>> import django
>>> print django.get_version()
1.7

2. django 프로젝트 생성 및 설정

설치 후 생성된 django-admin.py를 프로젝트 생성을 원하는 폴더로 이동 후 프로젝트 생성

$ python django-admin.py startproject samplepro

프로젝트명을 samplepro로 하였다. 다음처럼 디렉토리가 구성된다.

samplepro/
      manage.py
      samplepro/
          __init__.py
          settings.py
          urls.py
          wsgi.py

생성된 프로젝트를 django 자체서버를 통해 테스트
$ cd samplepro
$ python manage.py runserver 
  Validating models...

  0 errors found
  Django version 1.7, using settings 'samplepro.settings'
  Development server is running at http://127.0.0.1:8000/

  Quit the server with CTRL-BREAK.

웹 브라우져로 http://127.0.0.1:8000/ 에서 웹페이지를 확인


mysql을 사용하기 위한 python 인터페이스(MySql_python) 설치.

$ yum install mysql-devel
$ pip install mysql_python

프로젝트의 settings.py파일에 mysql 접속정보 입력
$ vi settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB명',                       
        'USER': 'USER명',                 
        'PASSWORD': '비밀번호',
        'HOST': '127.0.0.1',  
        'PORT': '3306', 
    }

  }

INSTALL_APPS
settings.py 파일을 보면 django 설치시에 기본적으로 설치된 프로그램이 표시된다.
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',

    'django.contrib.staticfiles',
)

django에 기본적으로 설치된 application을 사용하기 위해 데이터베이스 테이블을 사용할수 있게끔 설정이 필요

$ python manage.py syncdb
  Creating tables ...
  Creating table auth_permission
  Creating table auth_group_permissions
  Creating table auth_group
  Creating table auth_user_user_permissions
  Creating table auth_user_groups
  Creating table auth_user
  Creating table django_content_type
  Creating table django_session
  Creating table django_site

데이터베이스 테이블 생성이 완료되면 관리자 아이디/패스워드 설정을 한다.

  You just installed Django's auth system, which means you don't have any superusers defined.
  Would you like to create one now? (yes/no): yes
  Username (leave blank to use 'root'): 
  E-mail address: 
  Password:
  Password (again):
  Superuser created successfully.


3. mod_wsgi를 이용한 apache 연동

가. 웹서비스를 위한 아파치와의 연동을 위해 아파치의 apxs를 이용하여 mod_wsgi를 설치

# cd /usr/local/src/mod_wsgi-3.3
# ./configure --with-apxs=/usr/local/httpd/bin/apxs --with-python=/usr/local/python2.7/bin/python

# make && make install


나. 프로젝트 디렉토리에 django.wsgi 파일 생성

import os
import sys

sys.path.append('/home/newsb/public_html/sb_community')
sys.path.append('/home/newsb/public_html')

#os.environ['PYTHON_EGG_CACHE'] = '/home/newsb/public_html/.python-egg'
os.environ['DJANGO_SETTINGS_MODULE'] = 'sb_community.settings'

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()


다. apache httpd.conf 모듈 추가와 프로젝트에 작성된 wsgi path 추가

# vi /usr/local/httpd/conf/httpd.conf

LoadModule wsgi_module modules/mod_wsgi.so


<VirtualHost *:80>
    ------------
    WSGIScriptAlias / /home/newsb/public_html/sb_community/django.wsgi
    <Directory /home/newsb/public_html/sb_community>
      Order allow,deny
      Allow from all

    </Directory>

</VirtualHost>          

$ /etc/rc.d/init.d/httpd restart

웹 접속확인.


4. django application 생성

 $ python manage.py startapp sample_app

그 결과 다음과 같은 구조로 파일들이 생성된다.

samplepro/
      manage.py
      samplepro/
            __init__.py
            settings.py
            urls.py
            wsgi.py
      sample_app/
            __init__.py
            models.py
            tests.py

            views.py


settings.py파일에 새로 생성한 application을 추가한다.

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'sample_app',

)

application의 model 설정

application의 models.py 파일을 열어 django의 ORM(Object Relational Mapping) 기능을 이용하여 실제 데이터베이스 테이블과 맵핑하기 위한 모델을 작성한다

$ vi models.py

from django.db import models

class CommBoard(models.Model):
      subject = models.CharField(max_length=50, blank=True)
      name = models.CharField(max_length=50, blank=True)
      memo = models.CharField(max_length=200, blank=True)
      hits = models.IntegerField(null=True, blank=True)

      created_date = models.DateField(null=True, blank=True)

마이그레이션 작업내용을 만든다.
$ python manage.py makemigrations 
Migrations for 'sample_app':
  0001_initial.py:
    - Create model CommBoard

마이그레이션 작업내용을 실행시켜 mysql 테이블을 생성시킨다.
$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, contenttypes, board, auth, sessions
Running migrations:
  Applying board.0001_initial... OK



2014년 11월 21일 금요일

Raspberry Pi + MQTT 설치와 실행 테스트


$ cd /home/pi 
$ sudo mkdir Mosquitto 

//의존성 라이브러리 설치
$ sudo apt-get -y install libwrap0-dev libssl-dev

//mosquitto 다운로드
$ sudo wget http://mosquitto.org/files/source/mosquitto-1.0.2.tar.gz
$ sudo tar zxf mosquitto-1.0.2.tar.gz
$ cd mosquitto-1.0.2
$ make
$ sudo make install
$ sudo ldconfig
$ sudo make clean

// iptables의 1883 포트 허용
$ sudo iptables -A INPUT -p tcp -m tcp --dport 1883 -j ACCEPT
$ mosquitto

//환경파일
/etc/mosquitto/mosquitto.conf

//신규 터미널 생성 후 raspberry pi의 ssh 접속과 mosquitto subcribe
$ mosquitto_sub -d -t hello/world
Client mosqsub/6977-raspberryp sending CONNECT
Client mosqsub/6977-raspberryp received CONNACK
Client mosqsub/6977-raspberryp sending SUBSCRIBE (Mid: 1, Topic: hello/world, QoS: 0)
Client mosqsub/6977-raspberryp received SUBACK
Subscribed (mid: 1): 0
Client mosqsub/6977-raspberryp sending PINGREQ
Client mosqsub/6977-raspberryp received PINGRESP

//신규 터미널 생성 후 raspberry pi의 ssh 접속과 mosquitto publish
$mosquitto_pub -d -t hello/world -m "안녕 안녕" 
Client mosqpub/7002-raspberryp sending CONNECT
Client mosqpub/7002-raspberryp received CONNACK
Client mosqpub/7002-raspberryp sending PUBLISH (d0, q0, r0, m1, 'hello/world', ... (12 bytes))

Client mosqpub/7002-raspberryp sending DISCONNECT

//subscribe했던 클라이언트에서 패킷 수신 확인 
Client mosqsub/6977-raspberryp received PUBLISH (d0, q0, r0, m0, 'hello/world', ... (12 bytes))

안녕안녕

2014년 9월 27일 토요일

안드로이드 ListView의 가장 하단 아이템으로 자동 이동시키는 방법

안드로이드에서 댓글 혹은 채팅 뷰 구현시 리스트뷰의 가장 하단 아이템으로 자동 이동시킬 필요가 있다.


방법1
자바 소스상에서 적용
mListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);

방법2:
XML에서 attribute 추가
android:transcriptMode="alwaysScroll"

방법3:
listview의 selection을 이용하여 마지막 아이템으로 이동

private void scrollMyListViewToBottom() {
    myListView.post(new Runnable() {
        @Override
        public void run() {
            // Select the last row so it will scroll into view...
            myListView.setSelection(myListAdapter.getCount() - 1);
        }
    });

}

2014년 9월 11일 목요일

android 색상 alpha값 적용


android:background="#80000000"

80 : 알파값
000000 : 0-255 색상값 

알파 적용

100% — FF
90% — E6
80% — CC
70% — B3
60% — 99
50% — 80
40% — 66
30% — 4D
20% — 33
10% — 1A
0% — 00

2014년 1월 19일 일요일

Mac에 설치된 mysql 한글 깨짐 현상

mac os x 10.8에 mysql community server를 설치(.dmg) 후 한글 깨짐 현상이 발생.

mysql 접속후 status 명령어 실행 후 캐릭터셋을 확인하면 latin1으로 설정되어 있음.
/etc/my.cnf에 캐릭터셋을 utf8로 재설정하면 아래와 같이 utf8로 변경됨



mysql community server를 .dmg로 설치시 my.cnf가 존재하지 않으므로
아래와 같이 샘플 파일을 /etc 폴더에 복사

$ cp  /usr/local/mysql/support-files/my-default.cnf  /etc/my.cnf

캐릭터셋 추가
$ vi /etc/my.cnf

[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci

init_connect=SET collation_connection=utf8_general_ci
init_connect=SET NAMES utf8

[client]
default-character-set=utf8

[mysql]

default-character-set=utf8


수정이 완료되면 터미널을 종료하고 재시작.
mysql> status 로 재확인하면 캐릭터셋이 설정 완료되어 있음.