블로그 글 찾아보기를 편리하게! 월풍서가(月風書架)

블로그를 시작한 지 꽤 오랜 시간이 흘렀습니다.
가끔 예전에 쓴 글을 보고 싶은데, 글 제목이 생각 안 날 때가 있더라고요.
그래서 페이지를 하나 만들었습니다.
월풍서가(月風書架)
분류별로 글을 정리해 월풍도원 블로그 글을 찾아보기 쉽게 하기 위함입니다.
우선 책 감상평만 정리하였지만,
나머지 부분도 체계적으로 정리해 나갈 생각입니다.

오래전 글을 다시 읽는 재미가 쏠쏠합니다.
‘그 땐 저런 생각을 하고 살았구나.’
‘저건 불과 반 년 전인데도 낯설구나.’
이렇게 저를 돌아보며 블로그를 계속 써온 것에 뿌듯함을 느꼈어요.
월풍서가(月風書架)'
저에겐 지난날을 곱씹는 반추의 공간으로,
블로그를 찾으시는 분들께는 편리한 정보 검색 공간이 되게 하겠습니다.

저의 블로그를 찾아주셔서 고맙습니다.



by


Tags : , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

생소한 맥. OS X에 익숙해지기.

최근에 맥(Mac)을 써볼 기회가 있었습니다.
익숙하지 않은 환경이라 생소했어요.
그렇지만 조금 만지다 보니 금방 익숙해집니다.
다음에 또 맥을 쓰게 되면 참고하려고 사용환경을 정리해봤어요.

유용한 앱

일반
Plain Text : 리치 텍스트를 일반 텍스트로 변환할 때 씁니다.
Textwrangler(http://www.barebones.com/products/textwrangler/) : 가벼운 코드 편집과 텍스트 편집에 씁니다.
Degrees : 메뉴바에 표시되는 날씨 앱입니다.
Chrome : 웹 브라우져 입니다.
Evernote(https://evernote.com) : 메모할 때 좋습니다.
CheatSheet(http://www.cheatsheetapp.com/CheatSheet/) : 맥 단축키를 익히기 좋습니다.
Vox MP3 player(https://www.macupdate.com/app/mac/24852/vox) : MP3플레이어로 메뉴바에 플레이 버튼이 생겨 좋습니다.
Alfred(http://www.alfredapp.com/) : 빠른실행, 검색등 다양한 기능을 담은 유틸리티입니다.
Dropbox(https://www.dropbox.com/) : 파일 저장을 위한 클라우드 서비스입니다.
uTorrent(http://www.utorrent.com/intl/ko/downloads/mac) : 토렌트 클라이언트 입니다.

개발
JSRef : CSS / HTML5 / Javascript 사전입니다.
Pycharm : 파이썬 개발도구입니다.
Iterm(http://www.iterm2.com/#/section/home) : 맥용 터미널 입니다.
Xcode : 맥용 개발 도구 모음입니다.
MariaDB(https://mariadb.org/en/) : 오픈소스 데이터베이스입니다.
Mysql Workbench(http://www.mysql.com/products/workbench/) : Mysql에서 제공하는 데이터베이스 설계 도구입니다.
homebrew(http://mxcl.github.io/homebrew/) : 패키지 설치를 쉽게 도와줍니다.
홈브루 설치법 : ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"
홈브루 패키지 정보 업데이트 : Brew update formula
홈브루 업데이트 : brew update
홈브루에서 파이썬 설치(https://github.com/mxcl/homebrew/wiki/Homebrew-and-Python) : brew install python
홈브루에서 마리아db 설치 : brew install mariadb

단축키

fn + ↑ : Page Up
fn + ↓ : Page Down
fn + ← : Home
fn + → : End
fn + delete : windows del키
Option(alt) + enter : 한자
Command + Option + ESC : 강제 종료
Command+Shift+3 : 캡쳐 파일 저장
Command+Ctrl+3 : 클립보드로 저장
Command+Shift+4 : 영역 지정 캡쳐
Command+Ctrl+4 : 어플리케이션 윈도우 캡쳐

Finder
Command+Shift+N : 새 폴더
Command+Shift+G : 폴더로 이동

사전
Command+Ctrl+D : 사전에서 찾기.(커서를 원하는 텍스트에 두고 누른다. 크롬등의 웹 브라우져에서도 지원한다.)
* 추가할 사전이 있을 때 : /Library/Dictionaries 에 압축 해제

사용자 정의 단축키 설정
automator -> service -> utility -> run shell script
명령어 입력후 키보드 서비스 단축키 설정

기타 팁

맥 부팅 소리 끄기
sudo nvram SystemAudioVolume=%80
맥 부팅 소리 켜기
sudo nvram -d SystemAudioVolume

맥에서 패스 잡기
모든 유저에게 적용할 땐 /etc/paths에,
단일 사용자에 정용할 땐 ~User/.bash_profile에 아래를 추가해 준다.
PATH=$PATH:/my/new/path/
(http://blog.just2us.com/2011/05/setting-path-variable-in-mac-permanently/)

맥 초기화
맥 전원을 끈다.
맥 전원을 켠 후 Command+R키를 누른다.
OS X를 재설치 한다.

맥에서 파이참 디렉토리 위치
/Users/dorajistyle/Library/Preferences/PyCharm20



by


Tags : , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

구글 블로거와 궁합이 맞는 광고. 구글 애드센스.


2011년 말에 제 블로그에서 광고를 지웠었어요.
블로그를 찾아주시는 분들의 가독성을 해치고 싶지 않았기 때문입니다.
대신 기부코너를 만들었었죠.
이번에 다시 광고를 단 건, 요즘 생활이 어려워서입니다.^^;
비록 구글 애드센스 수익이 얼마 되진 않지만, 한 달에 밥 한 끼도 아쉬운 요즘이라 그렇습니다.

구글 애드센스와 블로거의 만남-'시리아 팔미라'

구글 블로거에 애드센스 다는 방법

구글 블로거는 애드센스와 연동이 잘되어 있습니다.

  1. 구글 블로거 내 블로그 메뉴로 갑니다.
  2. 수익 > 내 블로그에 광고 보이기 체크박스에 '예'라고 선택만 하면 광고가 바로 나옵니다.
  3. 물론 애드센스 계정은 가지고 있어야 합니다.
  4. 광고 스타일은 레이아웃에서 변경합니다.

블로그 광고 수익이 아쉽지 않을 정도의 형편이 되면,
구글 애드센스 광고를 내리도록 하겠습니다.:D

꾸준히 월풍도원을 찾아주셔서 고맙습니다.
행복하세요!



by


Tags : , , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

리눅스 환경에 발을 담그다. Arch 리눅스.

오래도록 MS 윈도우를 사용했습니다.
개발자로서 조금은 리눅스를 만질 일이 있었지만,
그야말로 수박 겉핥기였지요.
리눅스를 좀 잘 다뤄보고 싶었습니다.
하지만 공부를 해 볼까 버츄얼 머신에 리눅스를 깔아도, 사용 안 하게 되더라고요.
6년 전엔 큰마음 먹고 노트북에 윈도우 대신 Gentoo를 설치해 보았습니다.
데이터 백업도 안 하고 설치를 하다가 파티션을 잘못 건드려서 모든 자료가 다 날갔었지요.
게다가 일주일 동안 씨름을 했는데도, 그래픽인지 사운든지 드라이버를 하나 못 잡아서 결국 포기했던 기억이 납니다.

이번에 리눅스를 주 OS로 사용하기로 마음먹었을 때 Gentoo의 악몽이 되살아났어요.
설치와 유지 보수가 간편한 리눅스를 사용하기로 마음먹었죠.
설정이 복잡하거나 너무 마이너한 배포판은 설치하지 않기로 했습니다.

디스트로 와치(http://distrowatch.com/dwres.php?resource=popularity)를 참고하여 제게 맞는 배포판을 탐색했어요.

Mint가 가장 인기가 좋았지만 별로 내키지 않았고, Arch 가 눈에 들어왔습니다.
새로운 버전이 나왔을 때 통째로 갈아엎을 필요가 없이,
Pacman을 이용해 업데이트가 유연하게 된다는 점이 특히 마음에 들었지요.
그런데 설정에 너무 많은 시간을 쏟기는 싫었습니다.
그러다 발견한 게 만자로(Manjaro)에요.
사용자 편의에 초점을 맞춘 Arch 기반의 리눅스 배포판입니다.
Cinnamon 데스크을 넣은 Cinnarch도 괜찮아 보였지만, 만자로에 더 끌렸어요.
만자로(Manjaro)를 설치하고 두 달가량 사용을 하고 있는데 아주 만족스럽습니다.
물론 윈도우를 쓰다가 넘어왔으니 불편한 점이 많아요.
윈도우에서 주로 쓰던 소프트웨어와 대응되는 애플리케이션도 찾아야 했고,
각종 설정을 하는데도 많은 시간이 들었지요.
적응 기간 윈도우를 사용할 때보다 불편했지만, 지금은 딱히 그렇지도 않습니다.
앞으로도 리눅스를 쭉 쓰려고 해요.
나중에 좀 익숙해지면 개발에도 참여해 보고 싶습니다.

U43F with 리눅스 시스템 -'Arch linux(Manjaro)'

만자로(manjaro)리눅스를 쓰며 메모한 것들을 정리해 보았습니다.

USB 부팅 디스크 만들기

pendrivelinux.com

manjaro 설치

http://wiki.manjaro.org/index.php/Burn_an_ISO_File
http://wiki.manjaro.org/index.php/Installation_to_SSD_(quick_guide)
GRUB에서 e누른후 linux 라인에 cryptdevice를 추가해준다.
http://wiki.debian.org/SSDoptimization
https://wiki.archlinux.org/index.php/Solid_State_Drives
https://wiki.archlinux.org/index.php/Using_DM-Crypt#GRUB2
http://wiki.manjaro.org/index.php/Installation_Guide_for_Experienced_Users_0.8.2
LVM(Logical Volume Manager) 설정
https://wiki.archlinux.org/index.php/LVM

설정

커널 업데이트
http://wiki.manjaro.org/index.php/Manjaro_Kernels
커널 목록 보기
mhwd-kernel -li
커널 업데이트 하며 오래된 커널 지우기
sudo mhwd-kernel -i linux310 rmc

미러 자동 추가
pacman -S reflector
https://wiki.archlinux.org/index.php/Reflector
reflector --verbose -l 5 --sort rate --save /etc/pacman.d/mirrorlist

grub
yaourt -S grub-customizer

로케일
http://manjaro.org/2012/08/22/change-to-your-personal-locales/

커널 버젼 보기
cat /proc/version
pacman -S base-devel 로 devel 도구 설치
pacman -Syu base-devel linux-headers
pacman -Syu base-devel linux37-headers

서비스 설정
https://wiki.archlinux.org/index.php/Systemd#Basic_systemctl_usage

그래픽 카드
https://wiki.archlinux.org/index.php/Bumblebee
https://github.com/Bumblebee-Project/Bumblebee/wiki/Troubleshooting
/etc/bumblebee/xorg.conf.nvidia
한영키 먹게 하려면
Section "ServerLayout"
Identifier "Layout0"
Option "AutoAddDevices" "true"
EndSection

듀얼 모니터
https://wiki.archlinux.org/index.php/Xorg#Multiple_monitors.2FDual_screen
https://wiki.archlinux.org/index.php/DualScreen
xrandr --output LVDS1 --mode 1366x768 --output HDMI1 --mode 1920x1080 --right-of LVDS1

사운드
pacman -S lib32-alsa-lib
pacman -S lib32-libxml2

유선 인터넷
ifconfig로 인터넷 연결 확인
http://www.linuxfoundation.org/collaborate/workgroups/networking/alx에서 alx 드라이버 받음.(compat)

./scripts/driver-select alx
make
sudo make install
modprobe alx

혹은
sudo yaourt -S dkms-alx

무선 인터넷 관리자 Wicd로 변경
https://wiki.archlinux.org/index.php/Wicd

Before installing WICD I run these commands.
sudo systemctl stop netcfg
sudo systemctl stop dhcpcd
sudo systemctl stop NetworkManager
sudo systemctl stop netctl
sudo systemctl disable dhcpcd.service

After install
systemctl start wicd
systemctl enable wicd.service
gpasswd -a USERNAME users

sudo systemctl disable NetworkManager

rm /var/lib/NetworkManager/NetworkManager.state

블루투스 헤드셋 설치
https://wiki.archlinux.org/index.php/Bluetooth#Headset_and_Alsa_Devices
https://wiki.archlinux.org/index.php/Bluetooth_Headset
sudo hciconfig hci0 voice 0x0060
sudo pacman -S PulseAudio

블루투스 키보드
blueman에서 설정.
키보드에서 블루투스 신호를 보내고 잡아야 한다.

키맵이 이상하게 나오면 블루투스 키보드 연결을 해제하고,
노트북 키보드로 키맵 설정을 고정시킨다.
xmodmap -pke > ~/.Xmodmap
xmodmap ~/.Xmodmap


시작할 때 적용하려면?
~/.xprofile
~/.xinitrc
if [ -s ~/.Xmodmap ]; then
xmodmap ~/.Xmodmap
fi


https://wiki.archlinux.org/index.php/Xmodmap

exfat 마운트
pacman -S fuse-exfat exfat-utils

메모리카드 리더
1. Follow this link to know the exact model of your card reader. mine was RealTek smth smth.
and the output before the solution was like this:
03:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. RTS5229 PCI Express Card Reader (rev 01)
2. Download the suitable driver from this site:
http://www.realtek.com/Downloads/downloadsView.aspx?Langid=1&PNid=15&PFid=25&Level=4&Conn=3&DownTypeID=3&GetDown=false
3. Extract the zipped archive, then again extract the tar archive, then cd into the final directory, open the reademe file and follow the instructions.
4. After reboot, it simply worked :)
5. Note that I didn't notice a change in the output after the solution.
!not work sudo yaourt -S rts5229
원문(http://askubuntu.com/questions/20100/how-can-i-find-out-what-kind-of-card-reader-i-have)

xfce 설정
xfce4-settings-manager
윈도우 메니져에서 윈도우 관련 키 설정 가능하다.

저장된 세션 지우기
~/.cache/sessions/xfce4 를 삭제한다.

Chromium에서 Keyring을 자꾸 물어볼 때
https://wiki.archlinux.org/index.php/GNOME_Keyring

업데이트시 문제 해결

Unable to lock database가 날 때
sudo rm /var/lib/pacman/db.lck
http://wiki.manjaro.org/index.php/Pacman_troubleshooting

kalu나 package-query가 더 낮은 버전이 필요하다고 업데이트가 안 될때.
pacman -Syu
Do you want to cancel the current operation
:: and upgrade these packages now?
에 No라고 대답한다.

시스템 업그레이드시 package-query와 pacman이 충돌할 때
sudo pacman -R yaourt
sudo pacman -R package-query
then sudo pacman -Syyu
mv /etc/pacman.conf /etc/pacman.conf.backup # just in case
mv /etc/pacman.conf.pacnew /etc/pacman.conf

실행 파일 만들기 (batch)
#!/bin/sh
command
...
chmod +x

시작시 자동실행
gedit /etc/rc.local로 파일을 열어서 스크립트를 추가해 준다.

소프트웨어 설치

팩맨(Pacman)

설치
pacman -S 패키지 ( packer -S 패키지)

삭제
pacman -R 패키지

커맨드가 익숙치 않은 사용자를 위한 gui툴 소개
gtkpacman (AUR)

팩맨 미러
/etc/pacman.d/mirrorlis 파일을 수정

설치 가능한 패키지 목록 보기
$ pacman -Ss ^ibus-*

최적화 (안쓰는 패키지 삭제)
sudo pacman -Rns $(pacman -Qqtd)
Clean cache
pacman -Sc
pacman -Qdt

Yaourt (Yet AnOther User Repository Tool)

pacman -S yaourt

AUR과 동기화
yaourt -Syy

AUR 패키지 검색
yaourt package-name

설치
yaourt -S package-name
대부분의 Pacman 명령어와 Yaourt 명령어가 비슷합니다.

한글 키 입력 (ibus-hangul,fcitx 설치해봐도 잘 안되어 uim 설치.)
https://wiki.archlinux.org/index.php/Input_Japanese_using_uim
https://wiki.archlinux.org/index.php/Extra_Keyboard_Keys
https://wiki.archlinux.org/index.php/Extra_Keyboard_Keys_in_Xorg

pacman -S uim
Default input method 에 벼루만 빼고 다 버린다.
Byeoru key bindings 1
[Byeoru] on과 [Byeoru] off에 Hangul(한/영) 키 추가.
한자키에 한자키 추가.

uim 실행
uim-xim& //입력창을 보지 않는경우
uim-toolbar-gtk & //입력창을 따로 표시하는 경우
https://code.google.com/p/uim/wiki/UimSystemConfiguration
http://x86osx.com/bbs/view.php?id=knowhow&no=525&ksn=0&kss=0&ksc=0&kst=1&ksm=0&kw=:X11:

/etc/rc.conf
LOCALE="ko_KR.UTF-8"

~/.xprofile
IM="uim"
export GTK_IM_MODULE=$IM
export XMODIFIERS="@im=$IM
export QT_IM_MODULE=$IM
export XIM=$IM

http://wiki.kldp.org/wiki.php/%C7%D1%BF%B5%C5%B0 를 참조하였으나 아무런 도움이 되지 않았습니다.

아치 리눅스 글꼴
https://aur.archlinux.org/packages.php?ID=17314
https://aur.archlinux.org/packages.php?ID=49832

한글 폰트
yaourt ttf-nanumgothic_coding

http://manjaro.org/2012/08/22/change-to-your-personal-locales/

유용한 소프트웨어

글쓰기
Focus Writer
yaourt -S focuswriter

PKGBUILD
qt4 -> gambas3-gb-qt4
qmake-qt4 -> qmake
https://aur.archlinux.org/packages/focuswriter/
http://gottcode.org/focuswriter/
https://github.com/gottcode/focuswriter

linux Autohotkey
제대로 작동 안함 http://www.ironahk.net/
yaourt -S autokey

와인(Wine - Run Windows apps)
http://appdb.winehq.org/
http://www.howtogeek.com/107462/easily-install-windows-games-software-on-linux-with-playonlinux/
http://www.playonlinux.com/en/download.html
https://wiki.archlinux.org/index.php/Wine

pacman -S wine
pacman -S wine_gecko
pacman -s winetricks
http://wiki.winehq.org/Mono

/usr/share/wine/mono
설정
wine control
재부팅
wineboot -r
한글폰트
winecfg
sudo cp * ~/.wine/drive_c/windows/Fonts/
한글 설정
~/etc/wine.inf
~/.wine/system.reg
"MS Shell Dlg"="Gulim"
"MS Shell Dlg 2"="Gulim"

실행 전
export LANG=ko_KR.UTF-8
또는
export LC_ALL=ko_KR.UTF-8

regedit
[HKEY_CURRENT_USER\Software\Wine\X11 Driver]
"UseXIM"="N"

http://nemonein.egloos.com/4682100
http://kldp.org/node/93502
http://kldp.net/projects/saenaru/wiki/%EC%84%A4%EC%B9%98%EB%AF%B8%EB%A6%AC%EB%B3%B4%EA%B8%B0
http://mingiber.blogspot.kr/2008/12/crossover.html
http://www.dlldump.com/download-dll-files_new.php/dllfiles/K/kbdkor.dll/5.1.2600.0/download.html
kbdkor.dll을 system32에 win.
HKEY_CURRENT_USER\Keyboard Layout\Preload
Locale = 00000412
프로그램 제거
wine uninstaller

리눅스에서 와우(World Of Warcraft) 하기
런쳐에서 32비트 클라이언트로 실행.
p2p 전송 끔.
https://wiki.archlinux.org/index.php/World_of_Warcraft#Using_OpenGL

black textures
S3TC texture compression support. It can be enabled through driconf or by installing libtxc_dxtn.
wine reg add "HKCU\Software\Wine\Direct3D" /v AlwaysOffscreen /d enabled
VideoMemorySize 1024

primusrun opengl모드에선 안되지만 d3d9에선 실행 됨.
__GL_THREADED_OPTIMIZATIONS=1 WINEDEBUG=-all wine wow-64
https://help.ubuntu.com/community/WorldofWarcraft

optirun bash
#!/bin/sh
__GL_THREADED_OPTIMIZATIONS=1 optirun wine /home/dorajistyle/data/games/World\ of\ Warcraft/World\ of\ Warcraft\ Launcher.exe -opengl

리눅스에서 인터넷 뱅킹
Virtual box
http://www.microsoft.com/en-us/download/details.aspx?id=11575
혹은
curl과 unrar 설치후에
curl -s https://raw.github.com/xdissent/ievms/master/ievms.sh | IEVMS_VERSIONS="9" bash
/home/userid/.ievms/vhd'에 저장됨.
http://deviantcj.tistory.com/336

Setting -> Storage -> IDE -> vhd 파일 추가.
Setting -> Storage -> SCSI 삭제.

처음 암호는 Password1
인증 cmd -> slmgr –rearm

리눅스 - x3f
yaourt -S xnviewmp - 속도도 만족, ui도 만족.

Permanent rotation
Also, you can rotate permanently the images based on the EXIF information. This will ensure that the images are oriented properly when viewing in any graphic programs. To do this, you select all your images and select "Tools > JPG Lossless tranformations" (or dropdownlist of symbol 'JPG lossless transformations' in toolbar). In the dialog check the button with "EXIF" on it and then press "Go". XnView will permanently rotate the images based on the EXIF orientation flag.

http://www.xnview.com/en/index.html
http://www.digikam.org/ - 돌아는 가지만 속도가 엄청 느리다.
http://www.proxel.se/x3f.html 속도 빠르고 기본 x3f 추출 기능에 충실하다.
http://www.faststone.org/FSViewerDownload.htm - wine으로 돌리는게 가능하지만 속도가 느리다.

http://www.irfanview.com/ - 지원한다고 써있지만 오류가 난다.

http://www.irfanview.com/plugins.htm

리눅스 - 포토스케이프
wine에서 gdiplus를 native library에 추가 정상 작동.
http://www.oaultimate.com/computers/install-photoscape-3-6-on-ubuntu-11-10.html
일괄변환에서 파일 읽기가 제대로 안될땐 winecfg applications에서 호환성을 윈도우 2003이나 xp로 바꾸니 된다.

Lingoes 대체. Stardict.
http://www.stardict.org/
http://artha.sourceforge.net/neki/index.php/Installation
pacman -S stardict

jpeg 최적화
yaourt -S jpegoptim
jpegoptim --dest=output_folder input_jpegs

mp3 플레이어
sudo pacman -S deadbeef

메신저
pidgin
gtalk
google-talkplugin
pidgin-gtalksharedstatus

토렌트
pacman -S transmission-qt

스크린 캡쳐
yaourt -S shutter

듀얼 모니터 설정
xrandr --output VGA1 --auto --output LVDS1 --auto --right-of VGA1
pacman -S arandr

화면 잠금
yaourt -S slimlock
image : /usr/share/slim/themes/default

날씨
pacman -S xfce4-weather-plugin

지구본,지도
pacman -S kdeedu-marble

시스템 정보.
pacman -S conky
https://wiki.archlinux.org/index.php/Conky
https://aur.archlinux.org/packages/i-nex-bzr
https://wiki.archlinux.org/index.php/Lm_sensors

Temp file clean
yaourt -S bleachbit-svn

용량 큰 파일 검색- Disk usage analyzer with an ncurses interface
sudo pacman -S ncdu

중복파일 검색 / 삭제
sudo pacman -S fdupes
하위 폴더 포함해서 중복파일 검색
fdupes -r /dir

중복 파일 중 첫번째 파일은 제외.
fdupes -f /dir

결과에서 중복 파일 제거
fdupes -d /dir

하위 폴더 포함해서 중복파일을 검사해서 첫번째 파일 빼고 모두 지운다.
fdupes -rdN /dir


빠르고 편리한 파일 검색 ack
http://beyondgrep.com/documentation/
sudo pacman -S ack
검색을 원하는 디렉토리에서 다음과 같이 사용한다.
ack "검색할 문장"


파일 비교(Meld) - Diff 툴
sudo pacman -S meld


동영상 인코딩(handbrake)
sudo pacman -S handbrake


자막 편집(aegisub)
sudo pacman -S aegisub


자막 다운로드(subdownloader)
sudo pacman -S subdownloader


smi srt 변환
승네군님의 smi 2 srt script on archlinux v3.1(http://handmade.egloos.com/5756133)
사용하려면 subs가 필요하다.
yaourt -S perl-subtitles



개발
ssh
pacman -S openssh
ssh-keygen -t rsa
cat ~/.ssh/id_rsa.pub

ruby
pacman -S ruby
mongodb
pacman -S mongodb
bundle
bundle install --deployment
vendor/bundle
젬 환경 보기
gem env
번들 패스 설정
export PATH=$PATH:~/.gem/ruby/1.9.1/bin

libv8 (3.11.8.13 x86_64-linux, 3.3.10.4 x86_64-linux)
therubyracer (0.10.2)
Gemfile
if HOST_OS =~ /linux/i
gem 'therubyracer', '~> 0.10.2'
end

redis 암호 설정
/etc/redis.conf 에서 주석(#)을 제거한다.
# requirepass foobared

mongodb start
mongod --dbpath ~/work/dev/db


Ruby Gem 바이너리 경로 .bashrc에 추가.
export PATH="${PATH}:/home/dorajistyle/.gem/ruby/2.0.0/bin"


문제 해결

libpng cannot open shared object file: No such file or directory
ldd /usr/bin/gtk-update-icon-cache | grep png
LC_ALL=C sudo pacman -Syu


부팅 속도 개선
http://forum.manjaro.org/index.php?topic=6610.0
부팅 속도를 느리게 하는 원인 분석
systemd-analyze plot > plot.svg
systemd-analyze blame

readahead 활성화로 성능 개선
sudo systemctl enable systemd-readahead-collect systemd-readahead-replay

There was an error loading the theme
http://forum.manjaro.org/index.php?topic=8943.0
pacman -S mdm-themes-extra
Customize Desktop Environment for xRDP Session
http://sigkillit.com/tag/xfce/
sudo echo “startxfce4″ > ~/.Xclients
sudo chmod +x ~/.Xclients
sudo systemctl restart xrdp.service


HowTo: LVM encrypted install on SSD disk with cli installer
http://forum.manjaro.org/index.php?topic=1145.15
boot your system now, but when the grub screen comes up
do not press "enter", do not wait 5 seconds, but press "e". just read the text at the bottom of the screenshot: " ’e’ to edit the commands", that's what we need to do now.
search for the line beginning with "linux". this line will end with "ro". now insert "cryptdevice=/dev/sda3:cryptVG" before that "ro".
by pressing F10 grub will now load the kernel with our "modified" command.



by


Tags : , , , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

기름기 쫙 빠진 웹 프레임워크. Python Flask.

15년 전 웹(Web)에 처음 관심을 후로 여러 언어를 접해봤습니다.

우선
HTML, CSS를 사용했고,
더 나아가 Javascript를 사용하게 되었습니다.
백 엔드는 20대 이후에 접하게 되었네요.
그러다 대학에 들어가게 되면서 PHP를 잠시 만졌고,
Java에 빠진 뒤론 JSP가 최고인 줄 알았습니다.
객체지향 개발.
MVC!
그러나 자바에 맛 들인지 얼마 되지 않아,
편한 개발을 돕는다는 명목으로 각종 프레임워크가 난무했고,
새로운 프레임워크를 익히는데 염증을 느꼈습니다.
프레임워크는 개발의 편의를 돕기 위한 것인데 개발이 재미없어지다니, 슬픈 일이었죠.
웹 개발이 싫어졌었어요.

그러다가 Ruby on Rails를 만났습니다.
아~ 이건 정말 신세계에요.
개발하는 재미가 쏠쏠합니다.
루비를 레일즈에 얹으니, 정말 이보다 좋은 개발 도구가 있을까요?
그렇게 RoR에 좋은 감정을 유지해 왔습니다.
하지만 Rails는 군더더기가 좀 있어요.
다음엔 Rails 보다 좀 더 가벼운 Sinatra도 한번 써봐야겠다는 마음먹고 있었죠.

그러다가 우연한 기회에 파이썬 플라스크를 만났습니다.


python-'Python Flask 개발 from http://imgs.xkcd.com'
Python!!!

파이썬.
루비나 펄 같은 스크립트 언어를 접해봐서 그런지 진입 장벽은 그리 높지 않았습니다.
문법이 조금 다르긴 하지만 필요한 함수는 안내에서 찾아 개발하면 됩니다.

마이크로 프레임워크인 플라스크(Flask)를 처음 깔았을 때 좀 당황했습니다.
달랑 7줄 짜리 헬로우 월드 코드를 보고 고민에 빠졌죠.
‘어떻게 사용해야 하지?’
‘정말 이게 다야?’
Rails는 프레임워크를 설치했을 때 설정 파일을 비롯하여 수많은 파일이 생성됩니다.
그런데 Flask는 참 단순하더군요.
아마 덩치와 편의성은 Django가 Rails와 비슷하겠지요.

짧은 튜토리얼만 봐도 바로 개발할 수 있니다.
DB는 Flask-SQLAlchemy를 사용하여 만들었는데, 이 역시 익히기가 간편하여 좋더군요.

그런데 막상 개발하다 보니 눈이 어지럽습니다.
html 코드 때문이었는데요.
즐겨쓰던 haml 템플릿 엔진을 쓰려고 했으나, 지원이 시원치 않아서 Jade로 갈아탔습니다.
설정이 아주 간편해요.

자. 이제 본격적으로 개발해 볼까요?
그런데 뭔가 허전합니다.
템플릿에서 파이썬 함수를 쓰고 싶어요.
레일즈의 helper처럼 말이죠.
그건 flask의 context_processor를 이용하면 됩니다.
자세한 내용은 flask 안내서 있어요.

대체로 개발이 수월했지만,
문법이 달라서 골치가 잠깐 아픈 부분이 한곳 있습니다.
형 변환이 자동으로 안되어서 수동으로 해야 하는데,
jade템플릿에서 숫자를 문자로 바꾸는 함수가 안 통하는 거에요.
찾아보니 바꾸는 방법이 4가지씩이나 된다고 합니다.
이 중 3번과 4번은 Jade템플릿에서도 잘 동작해요.

  1. str(숫자)
  2. repr(숫자)
  3. '숫자'
  4. '%d' % 숫자

간단한 웹 어플리케이션을 만들며, 파이썬 플라스크 개발을 맛보았습니다.

고객제안과 투표 기능을 구현했어요.

코드는 아래 주소에서 보실 수 있습니다.

Python + Flask + Flask-SQLAlchemy + Jade Proposal Center Example



Python Flask 개발에 도움이 되는 링크

파이썬 함수 도움말 (http://docs.python.org/2/library/functions.html)

플라스크(http://flask.pocoo.org/)

Flask-SQLAlchemy(http://pythonhosted.org/Flask-SQLAlchemy/index.html)

플라스크 다국어 지원 (http://pythonhosted.org/Flask-Babel)

파이썬 Jade(https://github.com/syrusakbary/pyjade)

파이썬 Scss(https://github.com/Kronuz/pyScss)



by


Tags : , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

익숙하지만 낯선 운영체제. 윈도우즈 8


저는 오래도록 마이크로소프트사의 제품을 사용해 왔습니다.
MS도스부터 윈도우즈 3.1, 95, 98, 2000, 2003, XP, Vista, 7.
그리고 윈도우즈 8까지.
MS빠라고 해도 할 말이 없군요.
올해는 익숙한 마이크로소프트 진영을 벗어나려고 합니다.
하지만 어무이도 컴퓨터는 쓰셔야 하므로 집 컴퓨터를 윈도우즈 8로 업그레이드했어요.


시작화면-'윈도우즈8'
우선 윈도우즈 8을 설치하고 부팅할 때 뜨는 로딩화면이 단순해 마음에 듭니다.
부팅 속도도 윈도우즈 7보다 빨라졌어요.
시작화면이 조금 낯섭니다.
스마트폰과 비슷하거든요.
앱을 추가해서 마음에 맞는 시작화면을 꾸밀 수 있습니다.
돋보이는 기능은 마이크로 소프트 계정과 동기화 기능인데요.
계정을 동기화해 두면, 어떤 장치에서도 같은 환경으로 윈도우즈를 쓸 수 있습니다.
편리한 기능이지요.

데스크톱은 윈도우즈 7에 비해 크게 바뀐 것은 없습니다.
그런데 어무이께서 전화를 하셨어요.
"컴퓨터 끄려면 어떻게 해야 하니?"
이전 버전의 윈도우즈에선 시작 메뉴를 마우스로 클릭하고 시스템 종료 하면 되었잖아요?
윈도우즈 8엔 시작 메뉴가 없습니다.
그럼 컴퓨터를 어떻게 끄느냐고요?

1. 키보드의 시작 버튼을 누릅니다.
2. 우측 하단의 - 로 커서를 가져다 댑니다.
3. 설정을 누릅니다.
4. 전원을 누릅니다.
5. 시스템 종료를 누릅니다.

컴퓨터 끄기가 참 번거롭지요?

웹서핑을 해보니 윈도우즈 8 종료버튼 만들기 팁이 올라왔습니다.
윈도우8의 필수 팁! 윈도우8 종료버튼 만들기


팁의 도움을 받아 종료버튼을 만들었습니다.
시작 메뉴에 넣어두니 한결 편리하네요.^^

마이크로소프트 윈도우즈가 앞으로도 누구나 쓰기 쉬운 OS로 발전해 나가길 바랍니다.



by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

이젠 담배와 작별을 고하세요. Smoke Free Project


아일랜드에서 지내는 동안, 친구를 도와 금연 서비스를 만들었습니다.

금연을 시작하기 전부터 준비사항을 알려주고,

담배를 끊고 하루하루가 지날 때마다 어려움을 어떻게 극복하면 좋은지 안내가 잘 되어있습니다.

같이 금연을 하는 사람들과 정보를 나누기도 좋지요.

아직 한국어 버젼은 없지만,

다국어 서비스를 생각하고 만들었기에, 번역만 되면 언제든지 한국어로도 서비스가 가능합니다.

혹시 금연에도 관심이 있다면 한 번 들러보시고,

한국어로 번역하고 싶은 마음이 드시면, 서비스를 꾸려가는 세바스찬에게 이메일을 보내세요.:D

Smoke Free Project(SmokeFreeProject.org)




by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

자주 쓰는 엑셀 함수 정리.


엑셀, 문자열 다루기 - 문자열 함수 (텍스트 함수)

  • CHAR - 코드 번호에 해당하는 문자를 반환합니다.
  • CODE - 텍스트 문자열의 첫 문자를 나타내는 코드 값(숫자)을 반환합니다.
  • CONCATENATE - 여러 텍스트 항목을 한 텍스트 항목으로 조인합니다.
  • EXACT - 두 텍스트 값이 동일한지 검사합니다.
  • FIND - 텍스트 값에서 다른 텍스트 값을 찾습니다(대/소문자 구분).
  • LEFT - 텍스트 값에서 맨 왼쪽의 문자를 반환합니다.
  • LEN - 텍스트 문자열의 문자 수를 반환합니다.
  • LOWER - 텍스트를 소문자로 변환합니다.
  • MID - 텍스트 문자열의 지정한 위치로부터 지정한 개수의 문자를 표시합니다.
  • PROPER - 텍스트 값에 있는 각 단어의 첫 글자를 대문자로 바꿉니다.
  • REPLACE - 텍스트 내의 문자를 바꿉니다.
  • REPT - 텍스트를 지정한 횟수만큼 반복합니다.
  • RIGHT - 텍스트 값에서 맨 오른쪽의 문자를 반환합니다.
  • SEARCH - 텍스트 값에서 다른 텍스트 값을 찾습니다(대/소문자 구분 안 함)
  • SUBSTITUTE - 텍스트 문자열에서 기존 텍스트를 새 텍스트로 바꿉니다.
  • T - 인수를 텍스트로 변환합니다.
  • TEXT - 숫자 표시 형식을 지정하고 텍스트로 변환합니다.
  • TRIM - 텍스트에서 공백을 제거합니다.
  • UPPER - 텍스트를 대문자로 변환합니다.
  • VALUE - 텍스트 인수를 숫자로 변환합니다.
  • CONCATENATE (문자열1,문자열2,...)
  • REPLACE(문자열, 시작위치, 바꿀 문자수, 바꿀 문자열)
  • SUBSTITUTE(문자열, 찾을 문자열, 바꿀 문자열)
엑셀, 문자열 다루기 - 문자열 함수 (텍스트 함수) [강동의별님의 블로그]

엑셀, 문자열 다루기 - 문자열 함수 (텍스트 함수)

  • 상대참조(A1 형식) : 셀의 변위에 따라 상대적으로 참조셀의 위치도 변하는 형식.
  • 절대참조($A$1 형식) : 셀의 변위에 상관없이 참조셀이 고정적으로 정해진 형식.
엑셀 절대참조,상대참조 - 기본 중의 기본 [강동의별님의 블로그]

컬럼 합치기

=A1&" "&B1

텍스트 추출하여 날짜/시간 형식으로 변환

=DATE(LEFT(A1,4),MID(A1,5,2),MID(A1,7,2))+TIME(MID(A1,10,2),RIGHT(A1,2),0)

조건절에 만족하면 갯수 세기

=IF(COUNTIF(Sheet1!$A$2:$A$6,Sheet2!A2)=1,1,0)

원하는 범위에서 값 찾아 바꾸기

VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)
=vlookup(B1,sheet1!$C$1:$E$13, 3,false),0)


원하는 범위에서 여러 컬럼 값 찾아 바꾸기

=index(Sheet1!$D$1:$D$44,match(A1&B1,Sheet1!$A$1:$A$44&Sheet1!$B$1:$B$44,0))
Sheet1!$A$1:$A$44&Sheet1!$B$1:$B$44 범위에서 A1&B1값을 찾으면 Sheet1!$D$1:$D$44값을 컬럼에 채운다.


함수를 적용시키려면 CTRL+ENTER
배열 수식{}을 적용시키려면 CTRL+SHIFT+ENTER

엑셀 함수 참조 사이트

Contextures - Excel Tips and Excel Tutorials



by


Tags : , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Web application development References


ISO-639-1


Official languages of the United Nations

  • Arabic
  • Chinese (Mandarin)
  • English
  • French
  • Russian
  • Spanish

CLDR

Unicode Common Locale Data Repository

터미널 한글 설정

windows cmd - chcp 65001
linux shell - export LC_ALL=ko_KR.UTF-8


구글 맵스 지도 검색

https://maps.google.com/?q=이름@위도,경도

구글 정의 검색

define:something

Protocol SPDY

http://www.chromium.org/spdy

MongoDB

사용자추가 스키마생성 DB삭제

mongod 를 기동할 때는 --auth 옵션을 추가해야 함
mongoDB는 system영역 내에서 admin이라는 DB관리를 위한 스키마를 가짐
>use admin // admin DB 사용
>db.addUser('name','pswd') // 사용자 추가
>use newDB => 해당 디비가 없으면, 새로운 디비를 생성함
   mysql의 스키마 생성과 같음
>db.collectionName.drop() => 해당 collection을 삭제함
   mysql의 DROP TABLE과 같음

Mongodb eclipse

log path configuration

"C:\data\mongodb-xxxxxxxxx\bin\mongod" --service  --logpath  c:\data\test.log

import

mongoimport --host localhost --db myapp_development --collection my_collection --type csv --file C:\dev\data\test.csv --headerline --upsert

regex

mongodb regex = '^[work|accus*|planet]'
MongoDB can only use indexes on Regular Expression searches that are front (^) anchored.
RegEx searches that front-anchor and then use a wildcard query like .* will use the index for as much of the un-wildcarded area as it can before scanning --- i.e., ^foo.* will run a partial scan.


Mysql

mysql backup and restore


mysqldump -uUSER -pPASSWORD -hHOST DB > ./filename.sql
mysql -uUSER -pPASSWORD -hHOST DB < ./filename.sql

MySQL index

What should be indexed?
–All attributes where you JOIN
–All attributes where you filter (WHERE)
–All attributes where you ORDER or GROUP BY
–All attributes where you want to do an Index Scaninstead of a Table scan.
–NOT on attributes with an evenly distributed lowcardinality.
•How should be indexed?
–Indexes can only be used from left to right.
–Keep them short.
–Compound indexes: INDEX(a, b).
–Prefixed indexes: INDEX(a, b(10)).
–Do not function-cover indexed attributes

http://www.scribd.com/doc/80792061/MySQL-Performance-Tuning

MySQL Date and Time Functions


Mysql 동일 테이블에서 여러 필드 값의 합 쿼리

//쿼리1 보다 쿼리2가 두 배 이상 빠르다. 단, 하나의 칼럼 갯수를 구할 땐 where절과 count(*)를 쓰는 것이 더 빠르다.
//쿼리1
select sum(cnt) from (
    select count(*) as cnt from `my_table` WHERE `field_x` =1
    union all
    select count(*) as cnt from `my_table` WHERE `field_y` =1
    union all
    select count(*) as cnt from `my_table` WHERE `field_z` =1
) as cnt_all
//쿼리2
SELECT
(SUM(IF(`field_x` = 1,1,0)) +   
    SUM(IF(`field_y` = 1,1,0)) +
    SUM(IF(`field_z` = 1,1,0))) as cnt_all
FROM `my_table`
WHERE 1


firefox - keyword.url

http://www.google.co.kr/search?num=50&hl=ko&lr=&newwindow=1&tbo=1&as_qdr=all&aq=f&aqi=&aql=&oq=&gs_rfai=&ie=UTF-8&oe=UTF-8&sourceid=navclient&gfns=1&q=

리눅스 crontab

crontab -l

CSS FONT BASE-64

/* Fonts as files */
@font-face {
    font-family: 'MyFontFamily';
    src: url('myfont-webfont.eot?') format('eot'),
         url('myfont-webfont.woff') format('woff'),
         url('myfont-webfont.ttf')  format('truetype'),
         url('myfont-webfont.svg#svgFontName') format('svg');
    }
/* Fonts as data uris */
@font-face {
    font-family: 'MyFontFamily';
    src: url('myfont-webfont.eot?') format('embedded-opentype');
    }
   
@font-face {
    font-family: 'MyFontFamily';
         url(data:font/truetype;charset=utf-8;base64,BASE64_ENCODED_DATA_HERE)  format('truetype'),
         url(data:font/woff;charset=utf-8;base64,BASE64_ENCODED_DATA_HERE)  format('woff'),
         url('myfont-webfont.svg#svgFontName') format('svg');
    }


CSS Sticky windows

    .outer {
        width:200px;
        height:600px;
        background-color:red;
        margin:0 auto;
    }
    .inner {
        width:50px;
        border:1px solid white;
        position:fixed;
    }
 


Insert the word (image) into the alt text of an image that hasn’t loaded In Firefox

img:after   { content:" (image)"; }
img::after  { content:" (image)"; } /* New CSS3 standard notation */


FYI

References and Articles

빠른 웹 개발

도구


출처

  • 직접 작성
  • google 검색



by


Tags : , , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Ruby Gems Cheat Sheet


GEM 설정

gem environment
set GEM_PATH = D:\dev\ruby192\lib\ruby\gems\1.9.1\gems
gem update --system
gem uninstall gemname
bundle update
(vendor 폴더에 bundle 설치하기)
bundle install --path vendor/bundle


devise

Controller filters and helpers

Devise will create some helpers to use inside your controllers and views. To set up a controller with user authentication, just add this before_filter:
before_filter :authenticate_user!
To verify if a user is signed in, use the following helper:
user_signed_in?
For the current signed-in user, this helper is available:
current_user
You can access the session for this scope:
user_session
Callbacks
    after_set_user
    after_authentication
    before_failure
    before_logout
    Warden::Manager.after_authentication do |user,auth,opts|
        user.last_login = Time.now
    end
   

generator

devise g view with haml
rails g devise_views -t=haml

OmniAuth

Add :password => Devise.friendly_token[0,20] when creating a new user from facebook omniauth.

Passwords Encrypt manually


Assuming you have a mysql database with a "users" table and a "password" column And an ActiveRecord model class called "user" that is hooked up to devise
Create an ActiveRecord model class in your app app/models/old_user.rb
OldUser < ActiveRecord::Base
  set_table :users
  establish_connection :database => "old_database", :user => "old user", :adapter => "mysql"
end
then create a rake task: app/lib/tasks/migrate_users.rake
task :migrate_users => :environment do
  OldUser.find_each do |old_user|
    u = User.new(:email => old_user.email, :password => old_user.password, :password_confirmation => old_user.password);
    #if your using confirmation
    u.skip_confirmation!
    u.save!
  end
end
Modify as necessary (make sure you're saving any app-specific user attributes)
Then$ rake migrate_users
   
Good news and bad news.
Good news:
The following works to create your user's password manually.
 pepper = nil
 cost = 10
 encrypted_password = ::BCrypt::Password.create("#{password}#{pepper}", :cost => cost).to_s
You can find your pepper and cost in your devise initializer. This method was confirmed using Devise's "valid_password?" method.
Bad news:
The entire reason I was trying to avoid "User.new(password: password).encrypted_password" was because of speed. It's terribly slow. With all my other pieces of my import task, I've intentionally avoided this.
But as it turns out, the major cost here is not instantiating a User object -- but BCrypt itself. There is very little noticeable speed boost when using BCrypt directly because it's intentionally designed to be slow.
My final answer: suck it up, run the rake script, go find a beverage.

mailer locale configuration

-ActionMailer::Base.default_url_options[:locale] = I18n.locale


Simple_form

<%= simple_form_for(@user, :builder => CustomBuilder) do |f| %>
  <%= f.input :name %>
<% end %>


Client side validations

Client side validations Registering own form builder
https://github.com/bcardarella/client_side_validations/wiki/Registering-your-own-custom-form-builder


Client MVC

Spine

Important is only that the public directory of the application is specified
as domainroot in Confixx. If the domain is called Passenger will start automatically.."
rails g spine:model Card text is_private order user_id card_type
rails g spine:controller Cards
rails g spine:scaffold card text is_private order user_id card_type
rails g spine:model Organization title description url image admins members followers
rails g spine:controller Organizations
rails g spine:scaffold organization title description url image admins members followers
var card = App.Card.create({ 
  is_private: true,
  order: 0,
  card_type: 'Reason',
  text: 'Spine & Rails, sitting in a tree!'
});
straightforward way to do that without extending Spine Model's
to allow for instances to be added in memory without syncing
Ajax.disable -> saveStuff()
Model.refresh()
extends
Contact.extend(Spine.Model.Ajax);
Contact.extend({
url: '/users/'
});
'/': ->
    if AuthenticatedUser
         @controller = new OtherController
         @replace @controller.render()
    else
         @controller = new LoginController
         @replace @controller.render()
http://spinejs.com/docs/controller_patterns         
         


Compass

compass init rails D:/dev/workspace/baksisi
compass init rails -r html5-boilerplate -u html5-boilerplate --syntax sass --force
css와 javascript를 asset 폴더로 옮겨준다. rails.js는 제외 (jquery_ujs와 동일하다)


Geo_location

https://github.com/chrisyour/geo_location
http://www.maxmind.com/app/geolitecountry


Mongoid id 변경하기

http://blog.joshdzielak.com/blog/2011/12/24/tame-the-mongoid-id-field-in-your-rails-and-backbone-js-app/
http://lostechies.com/derickbailey/2011/06/17/making-mongoid-play-nice-with-backbone-js/


Mongoid Follow unfollow

class User
  include Mongoid::Document
  field :name, type: String
  has_and_belongs_to_many :following, class_name: 'User', inverse_of: :followers, autosave: true
  has_and_belongs_to_many :followers, class_name: 'User', inverse_of: :following
  def follow!(user)
    if self.id != user.id && !self.following.include?(user)
      self.following << user
    end
  end
  def unfollow!(user)
    !self.following.include?(user)
    self.following.delete(user)
  end    
end
relation_ids instead? that is self.member_count = self.member_ids.size
self.challenged.where(_id: event.id).destroy_all
def unchallenge!(announce)
  self.announcements.destroy_all( conditions: { _id: announce.id })
  self.save!
end
Finally I successfully deleted the relation using self.challenged_ids.delete(event.id)
validates_inclusion_of :foo, in: [['foo'], ['bar']]


Mongoid polymorphic behaviour

When a child embedded document can belong to more than one type of parent document, you can tell Mongoid to support this by adding the as option to the definition on the parents, and the polymorphic option on the child.
class Doctor
  include Mongoid::Document
  embeds_one :name, as: :namable
end
class Nurse
  include Mongoid::Document
  embeds_one :name, as: :namable
end
class Name
  include Mongoid::Document
  embedded_in :namable, polymorphic: true
end


TEST

Cucumber

rails g cucumber:install ?capybara ?rspec
  ruby script/rails generate cucumber:feature user email:string password:string confirm_password:string name:string nickname:string gender:integer location_name:string location:integer email_is_priavate:boolean name_is_private:boolean danted:boolean description:string
  ruby script/rails generate scaffold post title:string body:text published:boolean
  rake db:migrate
  rake cucumber


Cucumber Errors Handling

If SystemStackError: stack level too deep 
Then add gem "rspec", ">= 2.6.0.rc2", :group => [:development, :test] to Gemfile


Cucumber & Capybara Ajax

sleep second
page.driver.browser.execute_script %Q{ $('.ui-menu-item a:contains("#{link_text}")').trigger("mouseenter").click(); }
Clicking any element with Cucumber and Capybara
class Capybara::XPath
  class << self
    def element(locator)
      append("//*[normalize-space(text())=#{s(locator)}]")
    end
  end
end
When 'I click "$locator"' do |locator|
  msg = "No element found with the content of '#{locator}'"
  locate(:xpath, Capybara::XPath.element(locator), msg).click
end
The step looks for any element with the given text. Here it is in use:
Scenario: Creating an item
  Given I am signed in as "brandon@example.com"
   When I click "Add to your list"
    And I fill in "Description" with "blog about clicking any element"
    And I press enter
   Then I should see "The item was added to your list"
    And I should see "blog about clicking any element"
   


Cucumber Capybara

selenium chrome driver
https://github.com/jnicklas/capybara
http://code.google.com/p/chromium/downloads/list
http://code.google.com/p/selenium/wiki/ChromeDriver#Overriding_the_Chrome_binary_location
Capybara.register_driver :selenium_with_firebug do |app|
  Capybara::Driver::Selenium
  profile = Selenium::WebDriver::Firefox::Profile.new
  profile.add_extension(File.expand_path("features/support/firebug-1.6.0-fx.xpi"))
  Capybara::Driver::Selenium.new(app, { :browser => :firefox, :profile => profile })
end
Before("@selenium_with_firebug") do
  Capybara.current_driver = :selenium_with_firebug
end


I18n

I18n-js initialize

layout/application.html.haml
- html_tag :class => 'no-js', :lang => "#{I18n.locale}"
applcation.js
I18n.default_locale = "en"
I18n.locale = $($("html")[0]).prop("lang")
I18n.fallbacks = true


Media - Flickraw

    flickr.upload_photo(params[:photo].tempfile.path)


Gem Trouble shooting

Q. `require': no such file to load -- thin (LoadError)
A. => Add gem 'thin' to Gemfile


Rails Performance

  • Curb for Http (libcurl)
  • Yajl, the fastest JSON library.
  • excon #=> faster http
  • Nokogiri, the fastest XML library.
  • Snappy, super fast compression tool by google.
  • fast_xs
  • Memcache. (libmemcached)
  • use Ree Garbage Collector

Fastest Server

  • Unicorn
  • Thin

Profiling Tools

  • NewRelic - Monitoring Tool (Commercial)
  • Ganglia - Monitoring Tool (OpenSource)
  • Cloudflare - Performance & Security
  • rack-perftools

Rack-bug

1. Install rack-bug (branch rails3) as plugin
cd vendor/plugins
git clone -b rails3 https://github.com/brynary/rack-bug.git
If you want to you it as gem then add following line into Gemfile
gem 'rack-bug', :git => 'https://github.com/brynary/rack-bug.git', :branch => 'rails3'
2. Replace the code from file actionview_extension.rb
which is avilable in vendor/plugins/rack-bug/lib/rack/bug/panels/templates_panel/ as specified in bug of rack_bug repository
if defined?(ActionView) && defined?(ActionView::Template)
ActionView::Template.class_eval do
def render_with_rack_bug(*args, &block)
Rack::Bug::TemplatesPanel.record(virtual_path) do
render_without_rack_bug(*args, &block)
end
end
alias_method_chain :render, :rack_bug
end
end
If you are using gem override the specified file in some way
3. Add following lines into your config.ru
require 'rack/bug'
use Rack::Bug, :secret_key => "someverylongandveryhardtoguesspreferablyrandomstring"
run myapp
4. Start your server and access the URL http://your_app/__rack_bug__/bookmarklet.html
and enter the password.
http://blog.railsupgrade.com/2011/04/configure-rack-bug-for-rails-3.html


출처



by


Tags : , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Ruby on Rails Cheat Sheet


rails 데이터 타입

:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean

Rails Mimetype   

"./."                      => :all
"text/plain"               => :text
"text/html"                => :html
"application/xhtml+xml"    => :html
"text/javascript"          => :js
"application/javascript"   => :js
"application/x-javascript" => :js
"text/calendar"            => :ics  
"text/csv"                 => :csv  
"application/xml"          => :xml
"text/xml"                 => :xml
"application/x-xml"        => :xml
"text/yaml"                => :yaml
"application/x-yaml"       => :yaml
"application/rss+xml"      => :rss  
"application/atom+xml"     => :atom 
"application/json"         => :json
"text/x-json"              => :json

bundle asset precompile

bundle exec rake assets:precompile RAILS_ENV="production"
rake assets:clean< add below code if you want development environment with out precompile config.serve.static.assets = false application.rb use Bundler.require(:default, :assets, Rails.env) instead of Bundler.require(*Rails.groups(:assets => %w(development test)))

compile assets locally

Put below into development.rb
config.assets.prefix = "/temp-assets"
Also put below into application.rb
config.assets.initialize.on.precompile = false

rails logger

Rails.logger.info "My info message"
Rails.logger.debug "My debugging message"
Rails.logger.warn "My warning message"

Environment Log level

config.log_level = :debug, :info, :warn, :error, and :fatal

Validation text length CR filter

before.validation :replace.cr
  protected
  def replace.cr
    if self.description.changed?
      self.description.gsub!(/\r\n?/, "\n")
    end
  end

validation locale


// config/locales/en.yml
en:
  activerecord:
    attributes:
      user:
        email: "E-mail address"
    errors:
      models:
        user:
          attributes:
            email:
              blank: "is required"
If you are using mongoid, replace activerecord: with mongoid:

Validate associated

The answer to this turned out to be rather simple. On the parent model, you simply explicitly declare that you want the associated children validated.
parent.rb
validates_associated :children

Validate if persisted? or new_record?

validates.uniqueness.of :nickname, :message => I18n.t("user.already.taken"), :if => :new.record?
validates.uniqueness.of :nickname, :message => I18n.t("user.already_taken"), :unless => :persisted?

Session Store in rails 3

Use the database for sessions instead of the cookie-based default, which shouldn't be used to store highly confidential information
Create the session table with
rake db:sessions:create
Run the migration
rake db:migrate
Make sure you also tell rails to use ActiveRecord to manage your sessions too.
Rails 3
config/initializers/session.store.rb:
Rails.application.config.session.store :active.record.store

DB Migrate Production

rake db:migrate RAILS_ENV="production"

get rails environment

Rails.env
env["SERVER_NAME"]

rails template

rake print --silent RECIPES=jquery,haml,rspec,cucumber,guard,mongoid,action.mailer,devise,add.user,home.page,home.page.users,seed.database,users.page,css.setup,application.layout,html5,navigation,cleanup,ban.spiders,extras,git,compass,omniauth,omniauth.email,backbone > ~/Desktop/backbone.template.txt
Could you please run it again using the "-T -O -J" flags? As in
rails new template_test -m https://github.com/fortuity/rails3-application-templates/raw/master/rails3-mongoid-devise-template.rb -T -O -J
http://blog.dominicsayers.com/2011/08/16/howto-use-a-rails-template-from-github-on-windows/

thin start

D:\dev\ruby192\bin\ruby.exe -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) D:/dev/workspace/baksisi/script/rails server thin -b 127.0.0.1 -p 3002 -e development
ruby ./script/rails server thin -b smoke-free-online.de -p 3000 -e development -d
thin start

Middle Man

"server" was called incorrectly. Call as "middleman server [-p 4567] [-e development]".
"middleman server [-p 4567] [-e development]" instead of "middleman server -p 4567 -e development

DB migration

Rails g migration change.data.type.for.table_column

I18n

locale join

config/application.rb
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '.*', '..{rb,yml}')]

locale path

routes.rb
  match '/:locale' => "home#index"
  root :to => "home#index"
  scope "/:locale" do   
    controller :models do
      something
    end
    resources :models, :only => :show
ApplicationController
  def default.url.options(options = {})
    options.merge!({:locale => I18n.locale})
  end   

Localize

I18n.l Time.now, :format => :short,  :locale => :"ko"

Pluralization

ko:
  pears:
    zero: ko.zero
    one: ko.one
    few: ko.few
    other: ko.other

generate rake tasks

rails g task namespace task1 task2
rake -T | grep namespace

세션 저장

config.session.store :cookie.store, :key => '.baksisi.session', :domain => :all
environment.rb 메일러에 레이아웃을 지정하고 싶다면.
DeviseMailer.layout "OMG"

show routes

rake routes

SASS

config/application.rb:
config.generators.stylesheet_engine = :sass
sass-convert style.sass style.scss

Trouble Shootings

uninitialized constant

file name confirm (if file name capital, it can be occurred.)

guard-livereload error

gem install eventmachine --pre 

open-uri.rb file in C:/Ruby1.9.2/lib/ruby/1.9.1/ (of course your path might be different).

http.verify.mode = options[:ssl.verify.mode] || OpenSSL::SSL::VERIFY.NONE

[ERROR] V8 is no longer usable

ulimit -v unlimited  

CSV Data Handling

http://www.ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html

get action information at view

    params[:action]

HAML

rails helper using haml
 
def section(name)
haml.tag(:div, :class => 'section') do
  haml.tag(:h2, name)
  haml.tag(:p, :class => 'section.content') do
    yield
  end
end
end
      
def content.box
  haml.tag :div, :class => "holder" do
    haml.tag :div, :class => "top"
    haml.tag :div, :class => "content" do
      yield
    haml.tag :div, :class => "bottom"
  end
end
and in haml
%html
  %head
  %body
    Maybee some content here.
    - content.box do
      Content that goes in the content_box like news or stuff      
     
fields_for with index
<% @questions.each.with.index do |question,index| %>
    <% f.fields.for :questions, question do |fq| %> 
        # here you have both the 'question' object and the current 'index'
    <% end %>
<% end %>
It’s also possible to specify the instance to be used:
<%= form.for @person do |person.form| %>
...
<% @person.projects.each do |project| %>
  <% if project.active? %>
    <%= person.form.fields.for :projects, project do |project.fields| %>
      Name: <%= project.fields.text_field :name %>
    <% end %>
  <% end %>
<% end %>
<% end %>     

Rails Response

namespace "api" do
  resources :regions, :defaults => { :format => 'xml' }
end
Then you should be able to have the following work for your controller methods:
class Api::RegionsController < ApplicationController
  respond.to :xml, :json
  def index
    respond.with(@regions = Region.all)
  end
end
rescue.from  ActionController::MissingFile do |e|
  # User's browser probably wont display this
  # Content-Type is application/x-shockwave-flash
  render :file => File.join(Rails.public.path, '404.html'), :status => 404
end

show details or stream video

def show
  @media = Media.find params[:id]
  respond.to do |format|
    format.html
    format.flv { send.file @media.path, :disposition => 'inline' }
  end
end
render :file => File.join(Rails.public.path, '404.html'), :status => 404, :content.type => 'text/html'

render with variable

render :partial => "my/conejo", :locals => {:my.val => something}
render "my/liebre", :my.val => something

scope

default_scope order('id DESC')
Model.reorder('')
Model.unscoped

render an other action in the controller, in js.

  render 'result', :id => @item.id, :format => :js
 

layout xhr? 

  class ApplicationController < ActionController::Base
  layout proc{|c| c.request.xhr? ? false : "application" }
  end
  layout :layout.xhr?
  def layout.xhr?
    request.xhr? ? false : 'application'
  end
 

AJAX Performance stale? and touch


 def show
    @list_item = @list.list_items.find( params[ :id ] )
    if stale?( :etag => @list_item, :last_modified => @list_item.updated_at.utc, :public => true )
      respond_with( @list_item )
    end
  end
  Also instead of the update_list method being called from after_save/destroy you can pass :touch => true to the belongs_to association which will do the same

AJAX Handler - ?xhr

respond_with( @something, :layout => !request.xhr? )
or
respond_to do |wants|
  wants.html do
    if request.xhr?
      render :partial => "items"
    else
      render
    end
  end
end

Asset

exist

YourApp::Application.assets.find_asset("#{asset}.file").nil?

### pathname

<YourAppName>::Application.assets.find_asset('Rails.png').pathname

absolute asset_path in view using helper

"#{request.protocol}#{request.host.with.port}#{asset.path('person/gravatar.default.png')}"
"#{request.scheme}://#{request.host.with.port}#{request.script_name}"

Mailer

config

environment/production.rb
  config.action.mailer.default.url.options = {:host => 'localhost:3000',:locale =>I18n.locale}
  config.action.mailer.smtp.settings = {
    :address              => "server.addr",
    :port                 => 587,
    :domain               => "sever.domain",
    :user.name            => "user.name",
    :password             => "user.password",
    :authentication       => "plain",
    :enable.starttls.auto => true
  } 
  config.action.mailer.delivery.method = :smtp
  config.action.mailer.perform.deliveries = true
  config.action.mailer.raise.delivery.errors = false
  config.action.mailer.default :charset => "utf-8"

inline attachement

in mailer

attachments.inline['blank'] = {
    :data => File.read("#{Rails.root.to.s + '/app/assets/images/blank.png'}"),
    :mime.type => "image/png",
    :encoding => "base64"
}

in view

if @offer.image.nil?
  = image.tag( attachments['blank'].url, :id => 'attachement.image', :width => "400", :height => "400")
 

validates in I18n

%{attribute} - field name
%{model} - model name 
%{count} - count


rescue log

begin
  ...some code...
rescue Exception => e
  logger.error e.message
 

Ruby

Iterate

a.each.with.index do |item, index|
  puts item, b[index]
end
array.each.slice(3) do |elements|
  fire.the_event
end

Timezone

in client (js):
function set.time.zone.offset() {
    var current.time = new Date();
    $.cookie('time.zone', current.time.getTimezoneOffset());
}
in Application Controller:
before.filter :set.timezone
def set.timezone 
 min = request.cookies["time.zone"].to_i
 Time.zone = ActiveSupport::TimeZone[-min.minutes]
end

DateTime format

  %a - The abbreviated weekday name (Sun)
&nbsp; %A - The&nbsp; full&nbsp; weekday&nbsp; name (Sunday)
  %b - The abbreviated month name (Jan)
&nbsp; %B - The&nbsp; full&nbsp; month&nbsp; name (January)
  %c - The preferred local date and time representation
  %d - Day of the month (01..31)
  %H - Hour of the day, 24-hour clock (00..23)
  %I - Hour of the day, 12-hour clock (01..12)
  %j - Day of the year (001..366)
  %m - Month of the year (01..12)
  %M - Minute of the hour (00..59)
  %p - Meridian indicator (AM&nbsp; or&nbsp;PM)
  %S - Second of the minute (00..60)
  %U - Week  number  of the current year,
          starting with the first Sunday as the first
          day of the first week (00..53)
  %W - Week  number  of the current year,
          starting with the first Monday as the first
          day of the first week (00..53)
  %w - Day of the week (Sunday is 0, 0..6)
  %x - Preferred representation for the date alone, no time
  %X - Preferred representation for the time alone, no date
  %y - Year without a century (00..99)
  %Y - Year with century
  %Z - Time zone name
  %% - Literal ``%'' character
   t = Time.now
   t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 04/09/2003"
   t.strftime("at %I:%M%p")            #=> "at 08:56AM"
  
   datetime seconds, hours, days, weeks, months, and years
  
    Add below lines to one of your initializer files, e.g., config/environment.rb:
    DateTime::DATE.FORMATS[:short]="short %Y-%m-%d %H:%M:%S"
    Time::DATE.FORMATS[:short] = "short %Y-%m-%d %H:%M:%S"
    Date::DATE.FORMATS[:short] = "short %Y-%m-%d"
    modify view:
    <%= item.create_date.to_s(:short) %>
distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {})
today = DateTime.now
=> #<DateTime: 441799066630193/180000000,-301/1440,2299161>
birthday = Date.new(2008, 4, 10)
=> #<Date: 4909133/2,0,2299161>
days_to_go = birthday - today
time_until = birthday - today
=> Rational(22903369807, 180000000)
time_until.to_i             # get the number of days until my birthday
=> 127
hours,minutes,seconds,frac = Date.day_fraction.to_time(time_until)
[3053, 46, 57, Rational(1057, 180000000)]
- mm  = (now-la    st_cigarette).divmod(Rational(1, 1440))[0]
- past.days = mm / 1440
- past.hours = (mm % 1440) / 60
- past_minutes = mm % 60

timezone

def set_api_time_zone
  utc_offset = current.user.session && current.user.session.user ? current.user.session.user.time.zone.offset.to.i.minutes : 0
  user.timezone = ActiveSupport::TimeZone[utc.offset]
  Time.zone = user.timezone if user.timezone
  Time.zone.today
  Time.now.to.date
    # => Thu, 19 May 2011
  Time.now.in.time.zone('Melbourne').to_date
    # => Fri, 20 May 2011
end

Range step

range.step(2) {|x| puts x}


benchmark

require 'benchmark'
n = 1000000
def answer1 current.subdomain
  case current.subdomain
  when 'www', 'blog', 'foo', 'bar'
  else nil
  end
end
def answer2 current.subdomain
  nil unless  ["www", "blog", "foo", "bar"].include?(current.subdomain)
end
Benchmark.bmbm do |b|
  b.report('answer1'){n.times{answer1('bar')}}
  b.report('answer2'){n.times{answer2('bar')}}
end
Rehearsal -------------------------------------------
answer1   0.290000   0.000000   0.290000 (  0.286367)
answer2   1.170000   0.000000   1.170000 (  1.175492)
---------------------------------- total: 1.460000sec
              user     system      total        real
answer1   0.290000   0.000000   0.290000 (  0.282610)
answer2   1.180000   0.000000   1.180000 (  1.186130)
Benchmark.bmbm do |b|
  b.report('answer1'){n.times{answer1('hello')}}
  b.report('answer2'){n.times{answer2('hello')}}
end
Rehearsal -------------------------------------------
answer1   0.250000   0.000000   0.250000 (  0.252618)
answer2   1.100000   0.000000   1.100000 (  1.091571)
---------------------------------- total: 1.350000sec
              user     system      total        real
answer1   0.250000   0.000000   0.250000 (  0.251833)
answer2   1.090000   0.000000   1.090000 (  1.090418)


출처




by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Git cheat sheet


ssh 키페어 만들기

ssh 키 페어 만들기

git 기본 명령어


git init  - 초기화
git add * - git에 파일 목록 넣기
git commit -am 'initial commit' - 커밋
git push repository_name master - 해당 브랜치에 커밋
git clone git@app.repo.com:app/app.git - 코드를 로컬로  복제
cd app
git pull - 변경사항 풀


git 환경 설정


git config --global --list
현재 설정정보 조회할 수 있습니다. --global옵션은 전역설정에 대한 옵션이며 현재 프로젝트에만 적용할때는 주지 않습니다.
git config --global user.name "사용자명"
사용자명을 등록합니다 (필수)
git config --global user.email "이메일주소"
이메일 주소를 등록합니다. (필수)
git config --global color.ui “auto”
터미널에 표시되는 메시지에 칼라를 표시해 줍니다.



gitignore 사용하기


.gitignore
git config --global core.excludesfile ~/.gitignore_global
git rm -r --cached .
git add .
git commit -m ".gitignore 완성!"
git stash branch branchname
git fetch
git merge
git pull (git fetch + git merge branchname)


로컬 변경 무시하고 저장소에서 받아오기

모든 로컬 변경을 스태쉬 한다.
git stash save --keep-index
저장한 stash를 지운다.
git stash drop

파일 하나만 저장소에서 불러오려면 이렇게 한다.
git checkout HEAD^ path/to/file/to/revert

그리고 저장소에서 풀 한다.
git pull


특정 커밋으로 돌아가기
http://stackoverflow.com/questions/4114095/revert-to-previous-git-commit
git reset --hard 0d1d7fc32

Send a pull request on GitHub for only latest commit
http://stackoverflow.com/questions/5256021/send-a-pull-request-on-github-for-only-latest-commit
git checkout -b upstream upstream/master
git cherry-pick <SHA hash of commit>
git push origin upstream



How can I rollback a github repository to a specific commit?
http://stackoverflow.com/questions/4372435/how-can-i-rollback-a-github-repository-to-a-specific-commit
git reset --hard <old-commit-id>
git push -f



참고 자료

http://git-scm.com/
http://github.com/
아웃사이더님의 git 명령어 정리
구글 검색



by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Jquery,Coffeescript Snippet 모음


스타일 변화 시키기


    $('HTML').addClass('JS');
    * In your css */
    .JS #myDiv{display:none;}

coffee script 에서 함수 호출


    contents+="<li class='city_candidate' onclick='h(\""+data[v]+"\")'>"+v+"</li>"
    @h = h = (set) ->
      $('span#cityoutput').replaceWith("<span id='cityoutput'>"+set+"</span>")

Ajax Callback


    url = "locations"
    request = $.get url,data
    request.success (data) -> $("#regionresults").html(data)
    request.error (jqXHR, textStatus, errorThrown) -> $("#region
results").append "AJAX Error: ${textStatus}."

Slide UP


jQuery ->
  $(".search input").focus ->
    if @value == "Search"
      @value = ""
      @className = "textinput"  $(".search input").blur ->
    if @value == ""
      @value = "Search"
      @className = "placeholder"
  $('#message').css { border: '1px solid red' }
  $("p").click(function () {
      $(this).slideUp();
    });
    $("p").hover(function () {
      $(this).addClass("hilite");
    }, function () {
      $(this).removeClass("hilite");
    });

Sticky layer


sticky = () ->
  y = $(window).scrollTop()
  if y > $('#topnavigation').height()
    $('#top
navigation').css({
      'position': 'fixed',
      'top': '0',
      'z-index': "4444"
        'width': $('#top_navigation').width(), 'box-shadow': '0px 20px 20px -15px #CCC'
    })
    $('#topnavigation').removeClass("sixteen columns alpha")
    $('#main').css({'padding-top': $('#top
navigation').height()})
  else
    $('#topnavigation').removeAttr('style')
    $('#main').removeAttr('style')
    $('#top
navigation').addClass("sixteen columns alpha")
$(window).scroll(sticky)
$(window).resize(sticky)
   
   

페이드인 메시지


msg = "world"
inv = "you"
show_message = (x,y) ->
  $('span#message').hide().text(x).fadeIn(1000,
  -> $('span#message').append('!')
  )
  $('#hint').hide().text(x).fadeIn(0)$ ->
  showmessage msg,inv
    [inv, msg] = [msg, inv]
 
  $('span#message').click ->
    show
message inv,msg
    [inv, msg] = [msg, inv]
message fadein and out
.fadeIn(30).fadeOut(1000);
   

다이나믹 add remove


$('input#addlanguageskill').on 'click', () ->
  num = ($('.languageskillinnerbox').length)-1
  newNum  = new Number(num+1)
  sourceElem = $('div#language
skill' +num)
  newElem = sourceElem.clone().prop('id','language
skill'+newNum)
  newElem.find("#user
languageskillsattributes"+num+"languageid").prop({id:'userlanguageskillsattributes'+newNum+'languageid',name:'user[languageskillsattributes]['+newNum+'][languageid]'})
  newElem.append('<input onclick="remove(\''+newElem.prop('id')+'\')" id="removelanguageskill"'+newNum+' type="button" value="Remove Language"/>')
  sourceElem.after(newElem)
@remove = remove = (elemid) ->
  alert "remove : "+elem
id
  $("#"+elem_id).remove()

Nested Model Form 예제


<% formfor @person do |personform| %>  <%= personform.label :name %>
  <%= person
form.text_field :name %>
  <% personform.fieldsfor :children do |child_form| %>
    <%= childform.label :name %>
    <%= child
form.text_field :name %>
    <% unless childform.object.newrecord? %>
      <% # Don't forget to name both of these 'destroy' in Rails 3 %>
      <%= child
form.checkbox 'delete' %>
      <%= childform.label 'delete', 'Remove' %>
    <% end %>
  <% end %>
  <%= submit_tag %>
<% end %>

그리즈 몽키 ajax 콜


var jqxhr = $.ajax({
  type: "POST",
  url: trackback,
  headers: {'User-Agent': 'Trackback',
                  'Content-Type':'application/x-www-form-urlencoded; charset=utf8'},
  data: inputdata,
  datatype:"text"
   });
  jqxhr.done(function() {
    GM
log("Trackback Success : "+jqxhr.responseText);           
  });
  jqxhr.fail(function(data,statusText,error) {                
        GM_log("Trackback faild : "+statusText+" [ "+error+", "+data.responseText+" ]");              
       
       
  });
 

셀렉트 박스 정렬


sortingSelectBox(selectTagId,sortBy,order)
selectTagId <select id="selectTagId"></select>
sortBy [0:Text, 1:Value] - default:0
order[0:Ascending, 1:Descending] - default:0
Examples
sortingSelectBox("mySelectTagId",1,1) sortBy Value in Descending order
sortingSelectBox("mySelectTagId",1) sortBy Value in Ascending order
sortingSelectBox("mySelectTagId") sortBy Text in Ascending order
sortingSelectBox = (selectBoxId,sortBy,order) ->
   sortBy ?= 0
   order ?= 0
   sortVal = 0
   if order is 1 then sortVal = 2
   orderValLeft = -1 + sortVal
   orderValRight = 1 - sortVal
   selectBox = $("select#"+selectBoxId)
   options = $("select#"+selectBoxId+" option")
   selectedVal = selectBox.val()
   sortedOption = options.clone()
   options.empty().remove()
   switch sortBy
     when 0
       sortedOption.sort((left,right)->
         leftText = left.text.toLowerCase()
         rightText = right.text.toLowerCase()
         if leftText < rightText then return orderValLeft
         if leftText is rightText then return 0
         orderValRight
       )
     else
       sortedOption.sort((left,right)->
         leftVal = left.value
         rightVal = right.value
         if leftVal < rightVal then return orderValLeft
         if leftVal is rightVal then return 0
         orderValRight
       )
   selectBox.append(sortedOption)
   selectBox.val(selectedVal)
  
sortingSelectBox("country")

리다이렉트


// simulates similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// simulates similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

JQuery 데이터 타입


dataTypeString
Default: Intelligent Guess (xml, json, script, or html)
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:    "xml": Returns a XML document that can be processed via jQuery.
    "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
    "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
    "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
    "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "
=[TIMESTAMP]", to the URL unless the cache option is set to true.
    "text": A plain text string.
    multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
/*
If you wish to use any of the meta-characters
( such as !"#$%&'()*+,./:;?@[]^`{|}~ ) as a literal part of a name,
you must escape the character with two backslashes: . For example,
if you have an an element with id="foo.bar", you can use the selector
$("#foo.bar").
*/

Session based tokens


If you are using session based tokens, you probably generate a secure token when generating the session, and store that token in the session. When a request comes back to the server, you check that the token is included in the request and compare it to what's in the session. If it's the same token, you accept the request, if not you reject it.
To use this token with jQuery, you need to make it available to javascript. You typically do this by adding it as a javascript variable.
var csrftoken = '<%= tokenvalue %>';
Next, the trick is to bind to the global ajaxSend event, and add the token to any POST request
$("body").bind("ajaxSend", function(elm, xhr, s){
if (s.type == "POST") {
xhr.setRequestHeader('X-CSRF-Token', csrf_token);
}
});

rails-3-1-and-jquery-ui-assets 설정


# http://stackoverflow.com/questions/6133818/rails-3-1-and-jquery-ui-assets
 $ cat app/assets/javascripts/application.js
    //= require jquery
    //= require jquery-ui
    $ cat app/assets/stylesheets/application.css
    /*
     *= require vendor
     *
     */
    $ cat vendor/assets/stylesheets/vendor.css
    /*
     *= requiretree ./jqueryui
     *
     */
    vendor/assets/ $ tree
     stylesheets
         vendor.css
             jqueryui
                      jquery-ui-1.8.13.custom.css
                      ...
     images
        jquery
ui
            ui-bgflat0aaaaaa40x100.png
            ...

Finally run this command:
    vendor/assets/images $ ln -s jquery_ui/ images
   

Get center


$(document).ready(function(){
  jQuery.fn.center = function () {
      this.css("top",$(window).height()/2-this.height()/2 + "px");
      this.css("left",$(window).width()/2-this.width()/2  + "px");
      return this;
  }
  $("#container").center();
 });
 

Multiple selector

$("#txt1, #txt2, #txt3").keyup(fn);

Jquery check CKEditor


$(this).data('initialForm', $(this).serialize());
to
$(this).data('initialForm', $(this).serialize() + '&' + FieldNameOfEditor + '=' + escape(ContentsOfEditor));
And a similar change to line 4 from
if ($(this).data('initialForm') != $(this).serialize()) {
to
var formData = $(this).serialize() + '&' + FieldNameOfEditor + '=' + escape(ContentsOfEditor);
if ($(this).data('initialForm') != formData) {

Jquery Defer


(function() {
      function getScript(url,success){
        var script=document.createElement('script');
        script.src=url;
        var head=document.getElementsByTagName('head')[0],
            done=false;
        script.onload=script.onreadystatechange = function(){
          if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
            done=true;
            success();
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
          }
        };
        head.appendChild(script);
      }
        getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js',function(){
            // YOUR CODE GOES HERE AND IS EXECUTED AFTER JQUERY LOADS
        });
    })();

Scroll to top   


var destination = $(‘#idToScrollTo’).offset().top;
$(‘html’).animate({scrollTop: destination},600);

CKEDITOR


config.toolbar = 'Modati'
config.toolbar_Modati = [['Bold', 'Italic', 'Underline','Strike', '-', 'RemoveFormat','-', 'Outdent','Indent','-','Blockquote','HorizontalRule', '-', 'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','FontSize','TextColor','BGColor']]CKEDITOR.editorConfig = function( config )
{
    config.toolbar = 'MyToolbar';
 
    config.toolbar_MyToolbar =
    [
        { name: 'document', items : [ 'NewPage','Preview' ] },
        { name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
        { name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','Scayt' ] },
        { name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'
                 ,'Iframe' ] },
                '/',
        { name: 'styles', items : [ 'Styles','Format' ] },
        { name: 'basicstyles', items : [ 'Bold','Italic','Strike','-','RemoveFormat' ] },
        { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote' ] },
        { name: 'links', items : [ 'Link','Unlink','Anchor' ] },
        { name: 'tools', items : [ 'Maximize','-','About' ] }
    ];
};
config.toolbar = 'Full';
 
config.toolbarFull =
[
    { name: 'document', items : [ 'Source','-','Save','NewPage','DocProps','Preview','Print','-','Templates' ] },
    { name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
    { name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ] },
    { name: 'forms', items : [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
 
         'HiddenField' ] },
    '/',
    { name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ] },
    { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','CreateDiv','-
 
        ','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl' ] },
    { name: 'links', items : [ 'Link','Unlink','Anchor' ] },
    { name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe' ] },
    '/',
    { name: 'styles', items : [ 'Styles','Format','Font','FontSize' ] },
    { name: 'colors', items : [ 'TextColor','BGColor' ] },
    { name: 'tools', items : [ 'Maximize', 'ShowBlocks','-','About' ] }
];
 
config.toolbar
Basic =
[
    ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink','-','About']
];
CKEDITOR.editorConfig = function( config )
{
    config.extraPlugins = "customparagraph";
    config.toolbar = [ [ 'ThinyP' ] ]; // add other toolbars and keep in mid this can be overwritten in page which loads CKEditor
};
<script type="text/javascript">
//<![CDATA[
    // Replace the <textarea id="editor1"> with a CKEditor
    // instance, using default configuration.
    CKEDITOR.replace( 'editor1',
        {
            extraPlugins : 'customparagraph',
            toolbar :
            [
                [ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],
                [ 'ThinyP' ]
            ]
        });
//]]>
</script>
in the main ckeditor config-file there is an option to disable automatic <p> inserts. try to change the value of CKConfig.EnterMode and CKConfig.ShiftEnterMode for example to 'br'.
config.enterMode = CKEDITOR.ENTER_BR
lostmorethanfive, lostbeetweenfourandfive, lostbeetweenthreeandfour, lostbeetweentwoandthree, lostbeetweenoneandtwo, lostbeetweenzeroandone, gainedbeetweenzeroandone, gainedbeetweenoneandtwo,gainedbeetweentwoandthree, gainedbeetweenthreeandfour, gainedbeetweenfourandfive,gainedbeetweenfiveandsix, gainedbeetweensixandseven,gainedmorethanseven


출처




by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!