2013-03-16

Apache+php+mysql on Mac OS

All process could be easely found in the web. For example read this http://jason.pureconcepts.net/2012/10/install-apache-php-mysql-mac-os-x/ or this http://coolestguyplanettech.com/downtown/install-and-configure-apache-mysql-php-and-phpmyadmin-osx-108-mountain-lion


What else you may need todo:
1. edit User and Group in /private/etc/apache2/httpd.conf or you could get some strange permission errors. find in you httpd.conf and change to this:
User username
Group #-1
2. Edit you /private/etc/php.ini ... I just copied my old one :)

2013-01-14

python .isalpha() for utf-8




>>> s='ахалаймахалай'
>>> s.isalpha()
False
>>> unicode(s.decode('utf-8')).isalpha()
True

2012-10-21

Yii Tips: Add user role to accessRules() in controller


By default there is no such thing as 'role'.

To add role to accessRules() in controller you could use expressions... smth like this: 'expression' => function(){return Yii::app()->user->getState("role") == 'admin';}

My accessRules():
public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions                                                                
                'actions'=>array('index','view'),
                'users'=>array('*'),      
            ),              
            array('allow', // allow authenticated user to perform 'create' and 'update' actions                                                      
                'actions'=>array('create','update'),
                'users'=>array('@'),      
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions                                                              
                'actions'=>array('admin','delete'),
                //Check if user role is admin                                                  
                'expression' => function(){return Yii::app()->user->getState("role") == 'admin';},
            ),              
            array('deny',  // deny all users  
                'users'=>array('*'),      
            ),              
        );


BTW, you need to set state for user's role in userIdentity component in authenticate.. like this $this->setState('role', $user->role);
My authenticate() in userIdentity.php:
public function authenticate()
    {
        $user = User::model()->findByAttributes(array('email'=>$this->username));

        if ($user===null) { // No user found!
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        } else if ($user->password !== md5($this->password) ) { // Invalid password!
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        } else { // Okay!    
            $this->errorCode=self::ERROR_NONE;
            $this->setState('email', $user->email);
            $this->setState('username', $user->username);
            // Store the role in a session: 
            $this->setState('role', $user->role);
            $this->_id = $user->id;      
        }
        return !$this->errorCode;    
    }

2012-10-20

My Vim Cheat Sheet



COMMAND mode:
:ci( - replace text between brackets
:ci" - replace text between quotes
ctrl+g - see where you are
g ctrl+g - advanced where you are
`. - jum to location of last modification
dtx - deletes upto and including the next x
dftx - deletes downto the previous x
:%s/TEXT//ng - count the number of matches
:e - reload current file (similar to :edit)
:set ft=html - change filetype (for example, to indent html inside php file)
Splited views (also helpfull with NERDTree plugin):
ctrl+ww - toogle between splited views 
ctrl+wv - split vertical
ctrl+wh - split horizontal

INSERT mode:
ctrl+t - insert indent to current line
ctrl+d - delet indent to current line
ctr+y - insert chars frome above line
ctrl+e - insert chars frome below line

ctrl+x xtrl+o - omni autocomplete(ctrl+n, ctrl+p to move next/previos line in omni autocomplete)


VISUAL mode:
ctrl+v - enter VISUAL BLOCK selection mode
Adding smth to multipple lines: select VISUAL BLOCK, press "I" (capital i) type smth you want to add (it appears only in first line which were selected), hit "ESC"... tadam chars you've entered added to every line which been previously selected. BTW: instead of "I" you could type "c" - it will cut selected blocks and qfter that you could type anything you want (also helpfull to uncomment block of code)


...to be continued

Other stuff:
:cd %:p:h '  - will change the working directory to the dir for current editing file
J - will join that line and the next line together (shift+j)

2012-10-19

Mac OS terminal/iterm tips (autocomplete, ignore case etc.)


add this to your ~/.inputrc:



#Pressing alt+left/right arrow force cursor to jump 1 word left/right
"\e[1;9D": backward-word
"\e[1;9C": forward-word
#this will print all ambiguous variant if you presse TAB
set show-all-if-ambiguous ON
#ignore case in files/folders names in terminal
set completion-ignore-case on
#tab cycles through completion
TAB: menu-complete
#shift+TAB to show all ambiguous variant
"\e[Z": complete 

2012-10-15

Install rockmongo in MAMP in mac os X


You should have mongodb installed and running on standart port. mamp instaled.
Turn off MAMP (if it's running)
Download sources from https://github.com/mongodb/mongo-php-driver to /Users/your_username/Temp/
Just do like written here in Installation section: https://github.com/mongodb/mongo-php-driver
phpize
./configure
make
sudo make 

after that you will have mongo.so and mongo.la somewhere 
in /Users/your_username/Temp/mongodb-mongo-php-driver-622828c/modules/

Then copy mongo.so and mongo.la to your MAMP (path should be smth like this):
/Applications/MAMP/bin/php/php5.3.6/lib/php/extensions/no-debug-non-zts-20090626/

Edit your php.ini, it will be somwhere here: 
/Applications/MAMP/bin/php/php5.3.6/conf). Add this line to it's extension section:
extension=mongo.so

Turn on MAMP
Check phpinfo at http://localhost/MAMP/ (search for 'mongo')
Go to rockmongo http://localhost/rockmongo
Thanks to: 
http://www.joyceleong.com/log/mongodb-with-mamp-on-os-x/
https://github.com/mongodb/mongo-php-driver

2012-10-14

Writing An Hadoop MapReduce Program In Python

Great article: Writing An Hadoop MapReduce Program In Python


My bash history (replace "const" with your username):
  543  cd /usr/local/Cellar/hadoop/1.0.3/libexec
  544  hadoop dfs -copyFromLocal /Users/const/Dev/PrjGit/mrpy/tmp/ /user/const/mrpy
  545  hadoop dfs -la
  546  hadoop dfs -ls
  547  hadoop dfs -ls /user/const/mrpy/
  550  jar /usr/local/Cellar/hadoop/1.0.3/libexec/contrib/streaming/hadoop-*streaming*.jar -file /Users/const/Dev/PrjGit/mrpy/mapper.py -mapper /Users/const/Dev/PrjGit/mrpy/mapper.py -file /Users/const/Dev/PrjGit/mrpy/reducer.py -reducer /Users/const/Dev/PrjGit/mrpy/reducer.py -input /user/const/mrpy/* -output /user/const/mrpy-output
  551  hadoop dfs -ls /user/const/mrpy-output
  552  hadoop dfs -cat /user/const/mrpy-output/part-00000

2012-10-09

Automator script: open chosen/selected folder in iTerm terminal

Here is the AppleScript:
on run {input, parameters}
   tell application "iTerm"
   activate
      repeat with someFilename in input
         make new terminal
         tell the first terminal
            activate current session
            launch session "Default Session"
            tell the last session
               set thePath to (quoted form of POSIX path of ¬
                  (someFilename as string))
               set cdCommand to "if [ -d " & thePath & " ]; then cd " ¬ 
                  & thePath & "; else cd `dirname " & thePath & ¬ 
                  "`; fi; clear"
               write text cdCommand
            end tell
         end tell
      end repeat
   end tell
   return input
end run

2012-10-06

Iterm2 how to setup word jumpig using alt+left alt+right arrow


In Preferences->Profiles->Keys:

find "option ←" and edit its "action" like this: select "send escape sequence" and in the "escape sequence box" enter "b"

find "option  →" and edit its "action" like this: select "send escape sequence" and in the "escape sequence box" enter "f"

Add this to your ~/.inputrc:
#Pressing alt+left/right arrow force cursor to jump 1 word left/right
"\e[1;9D": backward-word
"\e[1;9C": forward-word

2012-03-16

Python MySQLdb with MAMP

U need xCode, mySQL instaled and MySQL-python-1.2.3
Also you need MAMP instaled.

in MySQL-python-1.2.3 folder in site.cfg file add mysql_config path:
# The path to mysql_config.
# Only use this if mysql_config is not on your PATH, or you have some weird
# setup that requires it.
mysql_config = /Applications/MAMP/Library/bin/mysql_config


in terminal in MySQL-python-1.2.3 folder do this:
$ sudo python setup.py clean
$ sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql
$ sudo python setup.py build
$ sudo python setup.py install

If you got error "Reason: image not found" try this:
sudo cp /usr/local/mysql/lib/libmysqlclient_r.18.dylib /usr/local/mysql/lib/mysql/libmysqlclient_r.18.dylib

or this:

export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/


in your python script use unix_socket = path_to_MAMP_socket:
#!/usr/bin/python
import sys
import MySQLdb
import MySQLdb.cursors
db= MySQLdb.connect(unix_socket = '/Applications/MAMP/tmp/mysql/mysql.sock', host="localhost", port=3306 ,user="username", passwd="password",db="database")



related links:
http://paikialog.wordpress.com/2011/05/02/mac-install-python-mysqldb-to-mamp/
http://www.mangoorange.com/2008/08/01/installing-python-mysqldb-122-on-mac-os-x/

2012-03-03

Recursively delete .svn directories

rm -rf `find . -type d -name .svn`

Fixing the “unix:///var/mysql/mysql.sock” not found error on MAMP

If you've got this problem on mac (with MAMP):
PHP Error[2]: PDO::__construct(): [2002] No such file or directory (trying to connect via unix:///var/mysql/mysql.sock)

Try this:
sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

2011-08-17

PySide in Eclipse generates false errors

PyDev starts generating false errors for my code after installing PySide.

To fix this problem follow this steps:
1. In Eclipse open Window -> Preferences -> Pydev -> Interpreter - Python
2. Add C:\Python27\Lib\site-packages to SystemPYTHONPATH (if you already have it... remove this line and add it again)

Installing Eclipse IDE for C++ and QT with MinGW on Windows

Follow next steps to install Eclipse IDE for C++ and QT with MinGQ on Windows:
1. Instal MinGW (with MSYS) http://sourceforge.net/projects/mingw/files/
2. Install gdb-6.3-2.exe http://citylan.dl.sourceforge.net/project/mingw/MinGW/BaseSystem/GDB/Release%20Candidate_%20gdb-6.3/gdb-6.3-2.exe
3. Add path to MinGW and MSYS folder (for me it's C:\MinGW\bin;C:\MinGW\msys\1.0\bin;) to system variable (PATH)
4. Install QT (qt-win-opensource-4.6.4-mingw.exe) http://get.qt.nokia.com/qt/source/qt-win-opensource-4.6.4-mingw.exe
5. Install Eclipse IDE for C/C++ Developers (includes Incubating components), http://www.eclipse.org/downloads/ - just download and unzip it. INSTALL 32-bit version (and of course you need JRE 32-bit version ...for example this one jre-6u27-windows-i586.exe from here http://www.oracle.com/technetwork/java/javase/downloads/jre-6u27-download-440425.html
6. install QT Eclipse integration http://get.qt.nokia.com/qteclipse/qt-eclipse-integration-win32-1.6.1.exe
7. Reboot and then Run Eclipse
8. In eclipse Preferense->Qt press "Add new Qt version"... and add path to your ...\qt\4.4.1\bin folder

2011-05-26

multiple virtualhost in wampserver2

1. add this line to c:\windows\system32\drivers\etc\hosts
127.0.0.1 mysite.com

2. add this block to httpd.conf file:

NameVirtualHost 127.0.0.1
<virtualhost 127.0.0.1>
ServerName localhost
DocumentRoot "C:/wamp/www"
</VirtualHost>

<virtualhost 127.0.0.1>
ServerName mysite.com
DocumentRoot "C:\wamp\www\share\www"
</VirtualHost>




fo MAMP users, just add this

ServerName devshara
DocumentRoot "/Users/const/Dev/svn/sharamba/development/www"

2011-05-21

Light Explorer in Notepad++

Light Explorer in Notepad++ "allows documents to be opened from a dockable file explorer, that is very light weight and fast. Author: Javier Sanjose"

2011-05-15

PHP: Netbeans block comment (like /* comment */)

To comment multiple lines in Netbeans (like this /* comment */) you need to create macros

Tools -> Options -> Editor -> Macros -> New
The code of macros is:
cut-to-clipboard "/*" paste-from-clipboard "*/"

and Set shortcut to Ctrl+Shift+Q.

2011-04-26

Python: how to remove duplicates from list

# -*- coding: utf-8 -*-
qi=[1,1,3,1,6,4,5,1,6] #some elements repeat
qi.sort() #sort urls (just for fun)
qi_normal=set(qi) #this removes duplicate URL's
print "list wit repeated elemnts:", qi
print "list without repeted ellemnts:",qi_normal

Python: How to remove \n (end of line) symbol

# -*- coding: utf-8 -*-
str = [u"afaaas\n", "adasf \t"]
print "withouth strip():", str
print "with strip:\n", str[0].strip()
print str[1].strip()

as you can see .strip() also remove \t

2011-04-25

Python: read utf-8 file

This how I read utf-8 (without BOM) file in python:
import codecs
txtfile = codecs.open("bla.txt", "r", "utf-8")
t= txtfile.read()
txtfile.close()
print t