Tuesday, April 28, 2015

你若是獅子,何須炫耀 ? 如果你夠強,想藏都藏不住,還怕人家不知道嗎








小伙子正想要藏獒欺負一下這 老頭和 老狗,























clear cache programatically on Magento

Method 1:

$typeArr = Mage::app()->useCache();

foreach ($typeArr as $k => $v) {

Method 2:

$typeArr = Mage::app()->getCacheInstance()->getTypes();

foreach ($typeArr as $k => $v) {

Method 3:


Method 4:


Install Munin 2.0.25 on CentOS 7

Munin will not be found in base repositories, hence we add EPEL repository to install Munin.

Install EPEL and additional repositories on CentOS and Red Hat:

# yum install wget
# yum install epel-release

Note: for more information https://fedoraproject.org/wiki/EPEL

# yum install munin munin-node

Uncomment the following lines:

# vim /etc/munin/munin.conf

dbdir /var/lib/munin
htmldir /var/www/html/munin
logdir /var/log/munin
rundir  /var/run/munin

# a simple host tree
    use_node_name yes

Comment out all lines in /etc/httpd/conf.d/munin.conf:

# vim /etc/httpd/conf.d/munin.conf

Note: the reason why we comment out all the lines in munin.conf file is because we are going to move these lines under the VirtualHost block in httpd-vhosts.conf file.

Edit httpd-vhosts.conf, and add your IP address to the Allow from line:

# vim /etc/httpd/conf.d/httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host.example.com
    DocumentRoot "/var/www/html/munin"
    ServerName munin.mydomain.com

    <directory /var/www/html/munin>
        AuthUserFile /etc/munin/munin-htpasswd
        AuthName "Munin"
        AuthType Basic
        require valid-user

        # This next part requires mod_expires to be enabled.
        # We could use <IfModule mod_expires> around here, but I want it to be
        # as evident as possible that you either have to load mod_expires _or_
        # you coment out/remove these lines.

        # Set the default expiery time for files 5 minutes 10 seconds from
        # their creation (modification) time.  There are probably new files by
        # that time.

        ExpiresActive On
        ExpiresDefault M310

        Order Deny,Allow
        Deny from all
        Allow from

    ScriptAlias /munin-cgi/munin-cgi-graph /var/www/cgi-bin/munin-cgi-graph

    ErrorLog "/var/log/httpd/munin.mydomain.com-error_log"
    CustomLog "/var/log/httpd/munin.mydomain.com-access_log" common

Make sure the permission:

# chown -R munin:munin /var/www/html/munin/

# ls -dlaZ /var/www/html/munin/

drwxr-xr-x. munin munin system_u:object_r:httpd_munin_content_t:s0 /var/www/html/munin/

To verify the Apache configuration file:

# httpd -t

Syntax OK

Create the munin admin account:

# htpasswd -c /etc/munin/munin-htpasswd Munin

Note: you don't have to use -c parameter if you want to add additional users.

Make sure the permission:

# chown root:apache /etc/munin/munin-htpasswd
# chmod 640 /etc/munin/munin-htpasswd

If you would like to change the admin's name, edit:

# vim /etc/httpd/conf.d/munin.conf

AuthName "Munin"

Enable munin on system boot:

# systemctl enable munin-node


# chkconfig --add munin-node
# chkconfig munin-node on

Start munin:

# systemctl restart munin-node

Restart Apache:

# systemctl restart httpd

Wait for a couple of minutes or reboot your system to allow munin to create necessary files/folders automatically on your apache root folder.




Monday, April 27, 2015

To Install Nagios 4.0.8 on CentOS 7

To Install Nagios 4.0.8 on CentOS 7

It all depends what you mean by "monitor"!

1. Is it (system or service) available? We use nagios.
2. What is it doing? We use munin for linux servers, and cacti for just about everything else, even though it is a pain to configure sometimes...
3. What has it done? We use syslog-ng to concentrate syslogs in one place and then run a customized logcheck script daily to send reports via email. We are looking for something similar for Windows servers.

Install the required packages:

# yum install gcc glibc glibc-common gd gd-devel make net-snmp openssl-devel

Install mailx:

# yum install mailx

Note: the reason why we install mailx is because Nagios use /bin/mail to send the notification mails out.
Note: Postfix is the default mta for Centos 7.

# which mail


Send a simple testing email:

# echo "Your message" | mail -s "Message Subject" email@address.com

Send a testing email with an attachment:

# echo "Message" | mail -s "Subject" -a /loc/to/attachment.txt email@address.com

Reading the message body from a file:

# echo | mail -s "Subject" -r from@address.com -q /loc/to/body.txt email@address.com

Add the Nagios user:

# useradd nagios

Note: do not intend to create the user with /sbin/nologin or with the -r (system account) parameter. Because if the Nagios user can't send email then Nagios running as the nagios user won't be able to send mail either. You have to be able to send mail via a console terminal as the nagios user before you do any additional debugging.

Add the Nagios group:

# groupadd nagcmd

Add the nagios user and apache user to the Nagios group:

# usermod -a -G nagcmd nagios
# usermod -a -G nagcmd apache

Downloading and install Nagios:

# cd ~/tmp

# curl -L -O http://prdownloads.sourceforge.net/sourceforge/nagios/nagios-4.0.8.tar.gz

# tar xvf nagios-*.tar.gz

# cd nagios-*

# ./configure --with-command-group=nagcmd

# make all

# make install
# make install-commandmode
# make install-init
# make install-config
# make install-webconf

Downloading and install Nagios Plugins:

# cd ~/tmp
# curl -L -O http://nagios-plugins.org/download/nagios-plugins-2.0.3.tar.gz
# tar xvf nagios-plugins-*.tar.gz

# cd nagios-plugins-*
# ./configure --with-nagios-user=nagios --with-nagios-group=nagios --with-openssl

# make
# make install

Configure Nagios:

# vim /usr/local/nagios/etc/nagios.cfg



Note: regarding the admin_email and admin_pager, Nagios never uses these values itself, but you can access them by using the $ADMINEMAIL$ and $ADMINPAGER$ macros in your notification commands.

# mkdir /usr/local/nagios/etc/servers

Verify the Nagios configuration file:

# /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg

Configure Nagios contacts:

# vim /usr/local/nagios/etc/objects/contacts.cfg

email                           nagios@localhost        ;

Set up the Nagios admin account:

# htpasswd -c /usr/local/nagios/etc/htpasswd.users nagiosadmin

Note: you don't have to use -c parameter if you want to add additional users.

# chmod 440 /usr/local/nagios/etc/htpasswd.users
# chown root:apache /usr/local/nagios/etc/htpasswd.users

Comment out all lines /etc/httpd/conf.d/nagios.conf:

# vim /etc/httpd/conf.d/nagios.conf

Move all of lines in /etc/httpd/conf.d/nagios.conf to your VirtualHost block, since we are using PHP-FPM to process php scripts:

# vim /etc/httpd/conf.d/httpd-vhosts.conf

<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host.example.com
    DocumentRoot "/usr/local/nagios/share"
    ServerName nagios.mydomain.com

    DirectoryIndex /index.php index.php index.html index.htm
    ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://$1

    ErrorLog "/var/log/httpd/nagios.mydomain.com-error_log"
    CustomLog "/var/log/httpd/nagios.mydomain.com-access_log" common

    ScriptAlias /nagios/cgi-bin "/usr/local/nagios/sbin"

    <Directory "/usr/local/nagios/sbin">
    #  SSLRequireSSL
       Options ExecCGI
       AllowOverride None
       #Order allow,deny
       #Allow from all
       Order deny,allow
       Deny from all
       Allow from
       AuthName "Nagios Access"
       AuthType Basic
       AuthUserFile /usr/local/nagios/etc/htpasswd.users
       Require valid-user

    Alias /nagios "/usr/local/nagios/share"

    <Directory "/usr/local/nagios/share">
    #  SSLRequireSSL
       Options None
       AllowOverride None
       #Order allow,deny
       #Allow from all
       Order deny,allow
       Deny from all
       Allow from
       AuthName "Nagios Access"
       AuthType Basic
       AuthUserFile /usr/local/nagios/etc/htpasswd.users
       Require valid-user

Verify the Apache configuration files:

# httpd -t

Syntax OK

If you have enabled SELinux, set the correct security context:

# chcon -R --reference=/var/www/html /usr/local/nagios/share
# chcon -R --reference=/var/www/html /usr/local/nagios/var
# chcon -R --reference=/var/www/cgi-bin /usr/local/nagios/sbin
# chcon -R -t httpd_sys_rw_content_t /usr/local/nagios/var/rw

Or do:

# chcon -R -t httpd_sys_content_t /usr/local/nagios/share
# chcon -R -t httpd_sys_content_t /usr/local/nagios/var
# chcon -R -t httpd_sys_script_exec_t /usr/local/nagios/sbin
# chcon -R -t httpd_sys_rw_content_t /usr/local/nagios/var/rw

Enable and Run services:

# systemctl enable nagios.service


# chkconfig --add nagios
# chkconfig nagios on

# systemctl start nagios.service

# systemctl restart httpd.service

Check http process:

# /usr/local/nagios/libexec/check_http -H

If you see the following message:

HTTP WARNING: HTTP/1.1 403 Forbidden - 5194 bytes in 0.001 second response time |time=0.000542s;;;0.000000 size=5194B;;;0

Try to touch index.html file in your root directory.

# cat /usr/local/nagios/var/nagios.log

# cat /var/log/maillog

postfix/sendmail[24452]: fatal: open /etc/postfix/main.cf: Permission denied

# setsebool -P httpd_can_network_connect 1
# setsebool -P httpd_can_sendmail 1

Note: -P in the above command means Persistent (across reboots).

# getsebool -a | grep -i httpd_can
# sestatus -b | grep httpd_can

httpd_can_network_connect on
httpd_can_sendmail on

# ll -Z /etc/postfix/main.cf

-rw-r--r--. root root system_u:object_r:postfix_etc_t:s0 /etc/postfix/main.cf

If you did not get the nofitication email, please check to see if the mail client path has been set correctly:

# vim /usr/local/nagios/etc/objects/commands.cfg

Note: the default setting is set to /bin/mail.
Note: postfix is the default mta for Centos 7.

To see the visual graphics:

PNP4Nagios is an addon to Nagios which analyzes performance data provided by plugins visually and stores them automatically into RRD-databases.



Add Swap to a Amazon EC2 instance with an EBS (Elastic Block Store) volume

The Amazon EC2 instance does not come with the swap partition by default. You will need to add the swap or paging space manually.

Swap space are useful for systems having less memory (RAM). If your system facing problem of lack of memory continuously and you don’t want to increase memory on server, Then it can be helpful to enable swap in your system. Swap is comparatively much slower than physical memory but operating system uses swap space in case system goes out of memory. To know more about working of swap visit here.

Creating a swap file in current file system:

# dd if=/dev/zero of=/myswap bs=1M count=2048

Note: if - input file.
Note: of - output file.
Note: bs - block size.

# mkswap /myswap
# chown root:root /myswap
# chmod 0600 /myswap

# swapon /myswap

# free -h

             total       used       free     shared    buffers     cached
Mem:          1.8G       1.6G       208M        80M         0B       674M
-/+ buffers/cache:       957M       882M
Swap:         2.0G         0B       2.0G

# swapon -s

Filename                                Type            Size    Used    Priority
/myswap                                 file    2097148 0       -1

To make the swap enable on system boot, run the following command:

# sh -c "echo /myswap swap swap defaults 0 0 >> /etc/fstab"

Or edit the /etc/fstab:

# vim /etc/fstab

/myswap   swap   swap   defaults  0 0

To verify the swap:

# cat /etc/fstab | grep -i swap

/myswap swap swap defaults 0 0

# cat /proc/meminfo | grep -i swap

SwapCached:            0 kB
SwapTotal:       2097148 kB
SwapFree:        2097148 kB

To check the current system's swappiness:

Swappiness is a ratio of how often the system will write to the swapfile: if set to zero, the system will only swap to avoid running out of memory (the error above); if set to 100, the system will attempt to swap all the time. The default is set at 60. Since we want to utilize the swap only when necessary.

The Linux kernel provides a tweakable setting that controls how often the swap file is used, called swappiness.

A swappiness setting of zero means that the disk will be avoided unless absolutely necessary (you run out of memory), while a swappiness setting of 100 means that programs will be swapped to disk almost instantly.

Ubuntu system comes with a default of 60, meaning that the swap file will be used fairly often if the memory usage is around half of my RAM.

# cat /proc/sys/vm/swappiness


To configure swappiness:

# sh -c "echo vm.swappiness = 0 >> /etc/sysctl.conf && sysctl -p"

Add the swap space to a second disk instead of the current disk:

If you would like to add the swap space to a second disk, first we need to add extra disk in our system first. In my case new disk mounted as /dev/xvdd (It may change in your case). Then, run the following commands:

# mkswap -f /dev/xvdd
# swapon /dev/xvdd

# vim /etc/fstab

dev/xvdd   swap   swap   defaults  0 0

If at all possible, I'd advise not to use swap on EC2 unless you're 99% certain you won't have to use it (I.E. it's only there for emergency). When we disabled swap on some of our EC2 instances our monthly EBS IO costs probably halved.

You are right, the Ubuntu EC2 EBS images don't come with swap space configured (for 11.04 at least). The "regular" instance-type images do have a swap partition, albeit only 896 MB on the one I tested.

If some process blows up and you don't have swap space, your server could come to a crawling halt for a good while before the OOM killer kicks in, whereas with swap, it merely gets slow. For that reason, I always like to have swap space around, even with enough RAM. Here's your options:

Create an EBS volume (2-4 times the size of your RAM), attach it to your instance (I like calling it /dev/xvdm for "memory"), sudo mkswap /dev/xvdm, add it to fstab, sudo swapon -a, and you're good to go. I have done this before and it works fine, and it is probably a bit faster than using a swap file, but for a server that doesn't normally depend on swap performance, I personally think the minor performance improvement is not worth the added complexity of having to attach a volume. (Update: It's probably not faster than a swap file on instance storage, since EBS has become known for lousy and unpredictable performance.)

Or you might be able to repartition your disk to add a swap partition, though this might require creating a new AMI. I have not been able to do this in a running instance, because I cannot unmount the root file system, and I do not even have access to the disk device (/dev/xvda), only the partition (xvda1).

Or you can create a swap file. This is my preferred solution right now.

# dd if=/dev/zero of=/var/swapfile bs=1M count=2048 &&
# chmod 600 /var/swapfile &&
# mkswap /var/swapfile &&
# echo /var/swapfile none swap defaults 0 0 | tee -a /etc/fstab &&
# swapon -a

Done. :) I know a lot of people feel icky about using files instead of partitions, but it certainly works well enough as emergency swap space.



To prevent vim from auto-wrapping at column 80, try:

:set tw=0
:set textwidth=0


:set wrapmargin=0

'textwidth' 'tw'        number  (default 0)
                        local to buffer
                        {not in Vi}
        Maximum width of text that is being inserted.  A longer line will be
        broken after white space to get this width.  A zero value disables
        this.  'textwidth' is set to 0 when the 'paste' option is set.  When
        'textwidth' is zero, 'wrapmargin' may be used.  See also
        'formatoptions' and |ins-textwidth|.
        When 'formatexpr' is set it will be used to break the line.
        NOTE: This option is set to 0 when 'compatible' is set.

'wrapmargin' 'wm'       number  (default 0) 
                        local to buffer
        Number of characters from the right window border where wrapping
        starts.  When typing text beyond this limit, an <EOL> will be inserted
        and inserting continues on the next line.
        Options that add a margin, such as 'number' and 'foldcolumn', cause
        the text width to be further reduced.  This is Vi compatible.
        When 'textwidth' is non-zero, this option is not used. 
        See also 'formatoptions' and |ins-textwidth|.  {Vi: works differently
        and less usefully}



Saturday, April 25, 2015

How can I find which version of libmysqlclient is installed in Centos?

# repoquery --whatprovides *libmysqlclient*

# repoquery -l mysql-libs-0:5.1.71-1.el6.x86_64 | head -9

# yum whatprovides "*libmysqlclient*"

# yum info mysql-devel



Friday, April 24, 2015

Apache configuration for Django

Install mod_wsgi:

# yum install mod_wsgi

Edit httpd-vhosts.conf:

# vim /etc/httpd/conf.d/httpd-vhosts.conf

<VirtualHost *:80>
    ServerName myproj.cent-dev.local
    ServerAdmin webmaster@example.com

    DocumentRoot "/var/www/html/django/myproj"

    Alias /media/ /var/www/html/django/myproj/media/
    Alias /static/ /var/www/html/django/myproj/static/

    <Directory "/var/www/html/django/myproj">
        #<Files wsgi.py>
        #Require all granted

    WSGIDaemonProcess myproj.cent-dev.local python-path=/var/www/html/django/myproj:/usr/lib64/python2.7/site-packages  processes=2 threads=15 display-name=%{GROUP}
    #WSGIDaemonProcess myproj.cent-dev.local python-path=/var/www/html/django/myproj:/usr/lib64/python2.7/site-packages
    #WSGIDaemonProcess myproj.cent-dev.local python-path=/var/www/html/django/myproj

    WSGIProcessGroup myproj.cent-dev.local

    ### use the following on the production server.
    #WSGIScriptAlias / /var/www/html/django/myproj/myproj/wsgi.py process-group=myproj.cent-dev.local

    ### use the following two lines on the development server.
    ProxyPass /
    ProxyPassReverse /

    #SetEnv DJANGO_SETTINGS_MODULE myproj.settings

    ErrorLog "/var/log/httpd/myproj-cent-dev.local-error_log"
    CustomLog "/var/log/httpd/myproj-cent-dev.local-access_log" common

Install pip:

# wget https://bootstrap.pypa.io/get-pip.py

# python get-pip.py

Install django:

# pip install django==1.7.6

To verify that Django can be seen by Python:

# python -c "import django; print(django.get_version())"


To listens on local interface on port 8000:

# python manage.py runserver

0 errors found
March 15, 2015 - 19:56:59
Django version 1.6.2, using settings 'myproj.settings'
Starting development server at

To listens on every interface on port 8000:

# python manage.py runserver

Store PHP sessions in Memcached

Install Memcached:

If Memcached is installed, storing PHP session files in RAM can be much more efficient than storing on disk and can also save some IO. To configure this, you should modify the main php.ini file and change session.save_handler to memcached.

# yum install memcached

# vim /etc/sysconfig/memcached


# systemctl enable memcached.service

# systemctl restart memcached.service

# memcached-tool stats

# yum install php-pecl-memcached

# vim /etc/php.ini

session.save_handler = memcached

#session.save_path = unix:/tmp/memcached.sock
session.save_path = ""

# systemctl restart php-fpm.service

# php -r 'echo phpinfo();' | grep memcached

memcached support => enabled
Registered save handlers => files user redis memcached
session.save_handler => memcached => memcached

Wednesday, April 22, 2015

Show memory usage in Magento

To turn on memory usage and script execution time:

1. go to Admin->System->Configuration->Developer, find the ‘Profiler’ option in the ‘Debug’ section and enable it (set to ‘Yes’).

2. edit index.php and uncomment out the following line:


The proper way to disable a module:

Go to app/etc/modules. Here you can find the list of *.xml files.

Each of them is corresponding to some extension. If you open some of the files with a text editor, you will see the following line there:


To disable the extension just change the parameter inside the ‘active’ node to FALSE in the following manner:


Remember, that’s the correct universal way to disable an extension. Do not use Admin->System->Configuration->Advanced admin page to turn off the extensions. It’s a common mistake since this tool does not disable an extension – it only disables the extension’s output. It might cause a lot of problems on your store.



Tuesday, April 21, 2015

MariaDB log file location directory path



Sunday, April 19, 2015


物體在黑暗中會發光, 原理主要有兩大類...

1. 含有微量放射性物質: 這也是最早的夜光材料, 但有傷害人體的疑慮, 現已較少被採用. 不過仍有軍用手表使用. 其特性是自身發光, 不必經過吸光-發光週期, 其發光時間視衰變而定, 數十年至數千年甚至更長...

2. 含有蓄光材質: 這類材質, 當受到外界光或熱激發, 其電子會由基態進入激態, 當外界能量消失, 在由激態回到基態, 其能量則以光的方式釋放出來. 其特性為無幅射, 但在黑暗中發光會逐漸衰退, 必需重新照射光線蓄光.

古代所謂夜明珠, 夜光石, 大抵是含有這兩種成份, 天然者固然珍貴, 但要瞭解其原理其實很簡單, 不必聽販售者吹捧, 還需自行判斷是否物有所值... 而夜明珠在古代是稀世珍寶, 現在到處買得到, 怎麼來的? 自己想...




荧光棒中的化学物质主要由三种物质组成:过氧化物、酯类化合物和荧光染料。简单地说,荧光棒发光的原理就是过氧化物和酯类化合物发生反应,将反应后的能量传递给荧光染料,再由染料发出荧光。目前市场上常见的荧光棒中通常放置了一个玻璃管夹层,夹层内外隔离了过氧化物和酯类化合物,经过揉搓,两种化合物反应使得荧光染料发光。 由于荧光棒中的液体化学物质被聚乙烯(塑料)包装,所以不会对人体造成太大伤害。因为荧光棒所发出的光是靠化学反应激发染料发出的非放射性光,而不是由放射线激发染料发出的光,不会伤害人体。但赵福群也对时下有些人为追赶时髦,将荧光棒弄破,把里面的液体涂抹在身上的做法表示反对,因为荧光棒中的化学物质直接接触皮肤会对人体造成一定的损害。尤其注意不要让儿童误食。 之所以有观点认为荧光物质会伤害人体,是因为在有些夜光手表、矿井应急信号灯等中用的都是放射性物质,使染料在黑暗处发光,所以人们误认为荧光棒中也是运用了放射性物质,形成认识上的误差。消费者鉴别某夜光产品是否为放射性发光的办法是,放射性发光持续的时间比较长,并且光强度弱些;而非放射光持续的时间比较短。


在黑暗中能发出各色荧光的物质,称为夜光材料。人类使用夜光材料,已经有相当悠久的历史,比如用在手表的盘面上,就制成了一种夜光表。 夜光材料分为自发光型和蓄光型两种。自发光型夜光材料的基本成分为放射性材料,不需要从外部吸收能量,可持续发光,不仅黑夜,白天也是如此。正是因为含有放射性物质,所以在使用时受到较大的限制,废弃后的处理也是一大问题。蓄光型夜光材料很少含有放射性物质,没有使用方面的限制,但它们要靠吸收外部的光能才能发光,而且要储备足够的光能才能保证一直发光。蓄光型夜光材料的另个缺陷是辉度不够。例如,以前一直使用硫化锌作为余辉型荧光体,但发光时间太短,辉度也不够。于是后来就掺和了一种放射性同位素钜147,发光的效果是理想了,但放射性同位素的介入。不符合环境保护的要求。 对人体有害,虽然很小













Django translation in views


from django.utils.translation import ugettext

def getOptDict():
    optArr = {
        1: ugettext('Test 1'),
        2: ugettext('Test 2'),
    return optArr

Thursday, April 16, 2015

Internet Explorer Adds Twice the Quantity to Cart

IE 8 (Internet Explorer 8) will add the product twice and cause the quantity of that product in the cart to double up (two quantities).

<button onclick="productAddToCartForm.submit(this)"><?php echo $this->__('Add to Cart') ?></button>

<button onclick="productAddToCartForm.submit(this); return false;"><?php echo $this->__('Add to Cart') ?></button>



Wednesday, April 15, 2015


Ok, guys this confusion is because of lack of detail from several sources, and the naming of these protocols, and what WSGI actually is.


1. WSGI and uwsgi both are protocols, not servers. It is used to communicate with web servers for load balancing and especially to take advantage of extra features that pure HTTP can not provide. So far Nginx and Cherokee have implemented this protocol.

2. uWSGI is a server and one of the protocols it implements is WSGI. WSGI is a Python specification. There are several implementations of the WSGI specification and it's intended to be used for more than just application servers/web servers, but there are quite a few WSGI application servers (ie. CherryPy, which also happens to have a production ready WSGI compliant web server, if you weren't confused enough already!).

3. Comparing uwsgi to WSGI is comparing oranges to apples.



disable remove default css style sheet on Drupal 6


function zen_test_preprocess_page(&$vars, $hook) {
  foreach ($vars['css']['all']['module'] as $_k => $_v) {
    if (in_array($_k, array('not_yet'))) {


    $vars['styles'] = drupal_get_css($vars['css']);

Monday, April 13, 2015

check if Apache compression is working

# curl -i -H 'accept-encoding:gzip, deflate, sdch' http://example.com | head -n 13


# curl -i --compressed http://example.com | head -n 13

Content-Encoding: gzip

Thursday, April 9, 2015

Jquery UI Autocomplete with vertical scrollbar

scrollable dropdown instead of a plain dropdown list


function bindDealerNameAC(idToBind) {
    minLength: 1,
    create: function( event, ui ) {
        'max-height': '300px',
        'overflow-y': 'auto',
        'overflow-x': 'hidden',
    //source: ["choice 1", "choice"],
    source: function( request, response ) {
      $.get('/bg/crm/js_dealerarr', request, function(dataObj) {
        if (dataObj.status == true) {
        else {
      }, 'json');

Django taxonomy category

# pip install django-taggit

# python manage.py schemamigration taggit --auto

# python manage.py migrate taggit

If you are using South you’ll have to add the following setting, since taggit uses Django migrations by default:

    'taggit': 'taggit.south_migrations',

And then to any model you want tagging on do the following:


from django.db import models

from taggit.managers import TaggableManager

class News(models.Model):
    # ... fields here

    tags = TaggableManager()

If, when saving a form, you use the commit=False option you’ll need to call save_m2m() on the form after you save the object, just as you would for a form with normal many to many fields on it:

if request.method == "POST":
    form = MyFormClass(request.POST)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.user = request.user
        # Without this next line the tags won't be saved.


from taggit.forms import TagField, TagWidget

class NewsForm(ModelForm):
    tags = TagField(label=_('Tags'), widget=TagWidget(attrs={'size': 80}), help_text='A comma-separated list of tags')
    title = forms.CharField(label=_('Title'), widget=forms.TextInput(attrs={'size': 80}))
    class Meta:
        model = News
        fields = ['tags', 'title']
        #widgets = {
        #    'tags': TagWidget(),


def ls_news(request):
    news_list = News.objects.order_by('-update_date')
    return render(request, 'administrator/news/index.html', locals())


{% for n in news_list %}
    <!-- method 1 -->
    {{ n.tags.all|join:", " }}

    <!-- method 2 -->
    {% for t in n.tags.all %}
       {{ t.name }}
    {% endfor %}
{% endfor %}

To show all available tags:

from taggit.models import Tag

def add_news(request):
    tagsall = Tag.objects.all()
    return render(request, 'administrator/news/add.html', locals())
add_news = login_required(add_news)

{{ tagsall|join:', ' }}




Monday, April 6, 2015

JavaScript ZLIB Decompression

Download Pako: https://github.com/nodeca/pako

  <script src="pako-master/dist/pako.min.js"></script>

  $str = 'Hello, World!';
  $strGZCompressedBase64Encoded = base64_encode(gzcompress($str));

  var strGZCompressedBase64Encoded = '<?php echo $strGZCompressedBase64Encoded; ?>';
  var str = uncompress_base64decode(strGZCompressedBase64Encoded);

  function uncompress_base64decode(strGZCompressedBase64Encoded) {
    // Decode base64 (convert ascii to binary)
    var strData = atob(strGZCompressedBase64Encoded);

    // Convert binary string to character-number array
    var charData = strData.split('').map(function(x){return x.charCodeAt(0);});

    // Turn number array into byte-array
    var binData = new Uint8Array(charData);

    // Pako magic
    var data = pako.inflate(binData);

    // Convert gunzipped byteArray back to ascii string:
    return String.fromCharCode.apply(null, new Uint16Array(data));




Saturday, April 4, 2015

jQuery text input change event

$('#test').on('input', function(e){

$('#test').on('keydown', function(e){

JavaScript events

This is when the different event are triggered:
  • change
    This will be called when the blur event is triggered if the value of the  has been changed. In other words it will trigger when the input loses focus the value is different to what it was.
  • input
    The input event is basically everything you are looking for, it captures the event on any input change and most likely came about due to the headaches causes when developing something that watches every keystroke. The input event even manages to catch the case where the mouse pastes in content.
    Unfortunately the input event is relatively new and only available to modern browsers (IE9+).
  • keydown
    The keydown event is pretty simple, it triggers when the user pushes the key down..
  • keypress
    The keypress event is supposed to represent a character being typed. Because of this is does not capture backspace or delete which immediately dismisses it for use over keydown.
  • keyup
    Much like keydown, it triggers whenever the user releases a key.
  • paste
    This handy event triggers when data is pasted into the element.

Modifier keys

Note that keydownkeypress and keyup carr with them information about the modifier keys ctrl shift and alt in the properties ctrlKeyshiftKey and altKey respectively.

The cases

Here is a list of the cases you need to consider:
  • Entering input with keyboard (includes holding down a key)
    Triggers: keydownkeypressinputkeyup
  • Deleting input (backspace/delete)
    Triggers: keydowninputkeyup
  • Pasting using ctrl+v
    Triggers: keydownpasteinputkeyup
  • Using mouse to paste
    Triggers: pasteinput
  • Select an item from the autocomplete (/)
    Triggers: keydownkeyup


Given the above, you could implement your autocomplete box handling the input event for all changes to the input, and then keydown event to handling up and down. This would really separate everything nicely and lead to some pretty clean code.
If you want to support IE8, you will need to throw everything except pasting into the keydown event and then handle paste. The paste event is quite widely supported now and has been in IE since v5.5).



Creating a JSON response using Django and Python

Pre-Django 1.7:

import json
from django.http import HttpResponse

def testjson(request):
  response_data = {}
  response_data['result'] = 'failed'
  response_data['message'] = 'You messed up'
  return HttpResponse(json.dumps(response_data), content_type="application/json")

Django 1.7+:

from django.http import JsonResponse

def testjson(request):
  response_data = {}
  response_data['result'] = 'failed'
  response_data['message'] = 'You messed up'
  return JsonResponse(json.dumps(response_data))



Get selected element's outer HTML

<div id="test">
  <p><span>test 1</span></p>
  <p><span>test 2</span></p>
  <p><span>test 3</span></p>
  <p><span>test 4</span></p>

  var test1 = $('#test p:nth-last-child(2)')[0].outerHTML;
  var test2 = $('#test p:nth-last-child(1)')[0].outerHTML;




Friday, April 3, 2015

Django duplicate key value violates unique constraint "taggit_tag_name_key"