VMWare Workstation start on boot CentOS

CentOS RPMForge Installation Instructions (for Centos 6.x)

CentOS RPMForge Installation Instructions (for Centos 6.x)

Overview

If you want to add the RPMForge repo to your CentOS, use the following instructions

 

Downloading RPMForge repo

cd /tmp
# for 32 bit:
wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.i686.rpm
# for 64 bit:
wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm

Note: Visit here to see if newer version exist.

Installing RPMForge

rpm –import http://apt.sw.be/RPM-GPG-KEY.dag.txt

# for 32 bit:
rpm -i rpmforge-release-0.5.3-1.el6.rf.i686.rpm
# for 64 bit:
rpm -i rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm

yum clean all

Open Extra Repo

If you want, you can enable the extra repo using:

cd /etc/yum.repos.d

edit using vi/vom/mc rpmforge.repo:
change the enabled flag to enabled=1 in the section [rpmforge-extras].

 

Update all

yum update

 

That’s it!

VMWare Workstation start on boot CentOS

Update Git CentOS – to version 1.7.11+ (on CentOS 6.x)

Update Git Centos – to version 1.7.11+ (on CentOS 6.x)

Overview

If you want to update your Git to newer version then on CentOS repository, use the following instructions

 

Downloading RPMForge repo

cd /tmp
# for 32 bit:
wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.i686.rpm
# for 64 bit:
wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm

Note: Visit here to see if newer version exist.

Installing RPMForge

rpm –import http://apt.sw.be/RPM-GPG-KEY.dag.txt
# for 32 bit:
rpm -i rpmforge-release-0.5.3-1.el6.rf.i686.rpm
# for 64 bit:
rpm -i rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm

Open Extra Repo

yum clean all

cd /etc/yum.repos.d

edit using vi/vom/mc rpmforge.repo:
change the enabled flag to enabled=1 in the section [rpmforge-extras].

 

Update Git

yum update git

yum provides git will help you see all versions available.

git –version

Will show you have the new release installed. (1.7.11.3 for me)

 

That’s it!

Copy SSH public key to another server instructions

copy ssh public key

Prerequisities

You need to have a public key. If you haven’t generated keys before use:

ssh-keygen -t rsa

copy ssh public key is very simple. there are some ways to achieve this:

Using ssh-copy-id (recommended)

ssh-copy-id user@host

with this very simple command you can copy your public key to any user@host combination

Using scp

scp .ssh/id_rsa.pub user@host2:.ssh/authorized_keys

cd ~/ before.

The different is that scp will create a new file called authorized_keys while ssh-copy-id will add to id.

Windows 8 Screen Capture Shortcut

Windows 8 Screen Capture Shortcut

Windows 8 Screen Capture Shortcut is:

  • Press the <PrintScn> (print screen) button to capture all screens and then paste it into your favorite image editor (like Paint/Photoshop/GIMP/etc..).

 

Capture portion of the screen

  • Load the snipping tool (located in All programs > Accessories). then do your stuff.
  • If you want to use the mouse (for example to highlight menu item), just leave the snipping tool open and use the CTRL+PrtScn buttons.

 

Capture using OneNote

  • If you have OneNote installed – you can capture portion of the screen by pressing & holding the  Win key (Start) then press “s” key.

 

That’s all!

Windows 7 Screen Capture Shortcut

Windows 7 Screen Capture Shortcut

Windows 7 Screen Capture Shortcut is:

  • Press the <PrintScn> (print screen) button to capture all screens and then paste it into your favorite image editor (like Paint/Photoshop/GIMP/etc..).

 

Capture portion of the screen

  • Load the snipping tool (located in All programs > Accessories). then do your stuff.
  • If you want to use the mouse (for example to highlight menu item), just leave the snipping tool open and use the CTRL+PrtScn buttons.
Windows 7 Screen Capture Shortcut

Snipping Tool

Capture using OneNote

  • If you have OneNote installed – you can capture portion of the screen by pressing & holding the  Win key (Start) then press “s” key.

 

That’s all!

FIXED: UnicodeEncodeError ‘ascii’ codec can’t encode characters in position ordinal not in range(128)

The Error

This is a solution for UnicodeEncodeError raised when saving a ‘POST’ in Django form where filename is in different encoding then ‘ASCII’. ( ‘ascii’ codec can’t encode characters in position )

'ascii' codec can't encode characters in position

‘ascii’ codec can’t encode characters in position

Posting the form raising error in Django:

UnicodeEncodeError at /upload/add/
‘ascii’ codec can’t encode characters in position 52-54: ordinal not in range(128)

UnicodeEncodeError raised when saving a ‘POST’ in Django form where filename is in UTF-8 encoding and converted by Django to ‘ASCII’.

Posting the form raising error in Django:

Trackback

File “/usr/lib/python2.6/site-packages/django/core/handlers/base.py” in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File “/usr/lib/python2.6/site-packages/django/views/generic/base.py” in view
47. return self.dispatch(request, *args, **kwargs)
File “/usr/lib/python2.6/site-packages/django/views/generic/base.py” in dispatch
68. return handler(request, *args, **kwargs)
File “/usr/lib/python2.6/site-packages/django/views/generic/edit.py” in post
138. return self.form_valid(form)
File “/var/www/websites/mysite/fileupload/views.py” in form_valid
54. obj.save()
File “/var/www/websites/mysite/fileupload/models.py” in save
25. super(Picture, self).save(*args, **kwargs)
File “/usr/lib/python2.6/site-packages/django/db/models/base.py” in save
460. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File “/usr/lib/python2.6/site-packages/django/db/models/base.py” in save_base
543. for f in meta.local_fields if not isinstance(f, AutoField)]
File “/usr/lib/python2.6/site-packages/django/db/models/fields/files.py” in pre_save
255. file.save(file.name, file, save=False)
File “/usr/lib/python2.6/site-packages/django/db/models/fields/files.py” in save
92. self.name = self.storage.save(name, content)
File “/usr/lib/python2.6/site-packages/django/core/files/storage.py” in save
48. name = self.get_available_name(name)
File “/usr/lib/python2.6/site-packages/django/core/files/storage.py” in get_available_name
74. while self.exists(name):
File “/usr/lib/python2.6/site-packages/django/core/files/storage.py” in exists
218. return os.path.exists(self.path(name))
File “/usr/lib64/python2.6/genericpath.py” in exists
18. st = os.stat(path)

Exception Type: UnicodeEncodeError at /upload/add/
Exception Value: ‘ascii’ codec can’t encode characters in position 52-54: ordinal not in range(128)

 

The Code

In the model I have:

file = models.ImageField(upload_to=”pictures”)

 

the error raised on the line in the view.py:

obj.save()

 

 

Explanation of the error

Ticket #11030 is talking about this error.

Reverted a change that assumed the file system encoding was utf8, and changed a test to demonstrate how that assumption corrupted uploaded non-ASCII file names on systems that don’t use utf8 as their file system encoding (Windows for one, specifically).

Some servers do not have the necessary files to allow successfully setting the locale to one that supports utf-8 encoding. See here.

The meaning of this is that Django assumes the file system is non UTF-8 and validates that the filename is ASCII. The error raised when the file name is in UTF-8.

 

 

Test FileSystem

The problem may be in different places. We need to search for the problem:

Sys.getfilesystemencoding()

from here:

Django is passing a unicode string “path” to the os.stat() function. On many operating systems, Python must actually pass a bytestring, not unicode, to the underlying OS routine that implements “stat”.  Therefore Python must convert the unicode string to a bytestring using some encoding. The encoding it uses is whatever is returned by os.getfilesystemencoding

To get the system encoding using the sys.getfilesystemencoding(), enter python at bash and then:

import sys
sys.getfilesystemencoding()

If the output is:

‘UTF-8’

You don’t have problem with your system encoding.

If the problem is here, and you get back ‘ASCII’, change it according to your system.

 

Locale

Check the locale Object (again in python shell)

import locale
locale.getdefaultlocale()

Again, if the output is: (‘en_US’, ‘UTF8’) – the problem is not here. if it is – change it according to your system.

If the system is ok, then probably the problem is with you web server (Apache, Nginx, etc)

 

Test Apache

Are you using apache? mod_wsgi? Maybe the problem is here.

 

LC_ALL & LANG

To see locale on your centos type at bash:

locale

You should see something like this:

# locale
LANG=en_US.UTF-8
LC_CTYPE=”en_US.UTF-8″
LC_NUMERIC=”en_US.UTF-8″
LC_TIME=”en_US.UTF-8″
LC_COLLATE=”en_US.UTF-8″
LC_MONETARY=”en_US.UTF-8″
LC_MESSAGES=”en_US.UTF-8″
LC_PAPER=”en_US.UTF-8″
LC_NAME=”en_US.UTF-8″
LC_ADDRESS=”en_US.UTF-8″
LC_TELEPHONE=”en_US.UTF-8″
LC_MEASUREMENT=”en_US.UTF-8″
LC_IDENTIFICATION=”en_US.UTF-8″
LC_ALL=en_US.UTF-8

if you see:

LC_ALL=

then probable using this python script:

import locale
locale.getlocale()

will return (None, None)

type for all available locale:

locale -a

 

Unfortunately LANG is often set incorrectly when running under Apache. Documenting the need to set LANG properly under Apache is the subject of #10426,

In [11170] Added note on language variables required for Apache to survive non-ASCII file uploads:

If you get a UnicodeEncodeError
===============================

If you’re taking advantage of the internationalization features of Django (see
:ref:`topics-i18n`) and you intend to allow users to upload files, you must
ensure that the environment used to start Apache is configured to accept
non-ASCII file names. If your environment is not correctly configured, you
will trigger “UnicodeEncodeError“ exceptions when calling functions like
“os.path()“ on filenames that contain non-ASCII characters.

To avoid these problems, the environment used to start Apache should contain
settings analogous to the following::

export LANG=’en_US.UTF-8′
export LC_ALL=’en_US.UTF-8′

Consult the documentation for your operating system for the appropriate syntax
and location to put these configuration items; “/etc/apache2/envvars“ is a
common location on Unix platforms. Once you have added these statements
to your environment, restart Apache.

Check your Django app settings.py to see if  I18N is enabled:

USE_I18N = True

 

Check locale using Django View/Template

Create view:

1
2
3
4
5
6
7
8
9
10
import locale
import sys
 
def view_locale(request):
    loc_info = "getlocale: " + str(locale.getlocale()) + \
        "<br/>getdefaultlocale(): " + str(locale.getdefaultlocale()) + \
        "<br/>fs_encoding: " + str(sys.getfilesystemencoding()) + \
        "<br/>sys default encoding: " + str(sys.getdefaultencoding())
        "<br/>sys default encoding: " + str(sys.getdefaultencoding())
    return HttpResponse(loc_info)
import locale
import sys

def view_locale(request):
    loc_info = "getlocale: " + str(locale.getlocale()) + \
        "<br/>getdefaultlocale(): " + str(locale.getdefaultlocale()) + \
        "<br/>fs_encoding: " + str(sys.getfilesystemencoding()) + \
        "<br/>sys default encoding: " + str(sys.getdefaultencoding())
        "<br/>sys default encoding: " + str(sys.getdefaultencoding())
    return HttpResponse(loc_info)

and also create a url pattern:

    url(r’^locale/$’, ‘myapp.views.view_locale’),

Browse to ‘yoursite.com/locale‘, to check for problems:

getlocale: (None, None)
getdefaultlocale(): (None, None)
fs_encoding: ANSI_X3.4-1968
sys default encoding: ascii

If the view return something like the above, and everything we checked is ok until now, It’s mean that maybe the problem is with your web-server (apache, nginx, etc.):

 

Solution for Apache encoding problem

Set LANG & LC_ALL

non-ascii filenames with the Django storage system with the default apache settings on most systems will trigger UnicodeEncodeError exceptions when calling functions like os.path(). To avoid these issues, ensure that the following lines are included in your apache envvars file (typically found in /etc/apache2/envvars).

export LANG='en_US.UTF-8'
export LC_ALL='en_US.UTF-8'

To see your active envvars use:

printenv

This error likely wont rear its head during development on the test server as, when run from the command line, the ./manage.py script inherits the users language and locale settings.

Consult the documentation for your operating system for the appropriate syntax and location to put these configuration items; /etc/apache2/envvars is a common location on Unix platforms (Not all Apache distributions have a envvars file). Once you have added these statements to your environment, restart Apache.

if the ‘envvars’ file doesn’t exist. In that case you will need
to modify the environment of the startup script which is used to
startup Apache in the first place. I believe that for most Linux
systems this can be done by modifying:

/etc/sysconfig/httpd

or

/etc/init.d/httpd

or

/etc/init.d/apache

depending on the distro.

 

If everything fine, when you’ll add those lines and restart the httpd (apache) server you should get at the /locale view:

getlocale: (‘en_US’, ‘UTF8’)
getdefaultlocale(): (‘en_US’, ‘UTF8’)
fs_encoding: UTF-8
sys default encoding: utf-8

And your app should work now!

Some had also add the lines to ~/.bashrc or to the .htaccess, but I haven’t tested it.

 

Do not use the .wsgi script!

I tried to add the LANG and LC_ALL to the .wsgi instead (from some instructions) and failed becuase:

Some are adding the LANG & LC_ALL to the .WSGI loading script:

os.environ['LANG']='en_US.UTF-8'
os.environ['LC_ALL']='en_US.UTF-8'

Using the view we created earlier (if you had problem) you can see now that

getdefaultlocale(): (‘en_US’, ‘UTF8’).

But the others function may still return ASCII values:

getlocale: (None, None)
getdefaultlocale(): (‘en_US’, ‘UTF8’)
fs_encoding: ANSI_X3.4-1968
sys default encoding: ascii

adding:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

And now you can see that the sys default encoding is: UTF-8.
reload is important This is python 2.x problem, not the django.

BUT

as you can see:

1
(sys.getfilesystemencoding()
(sys.getfilesystemencoding()

return:

ANSI_X3.4-1968

and that is the problem we have. Django doesn’t recognize the filesystem as UTF-8

SetEnv directive does not modify process environment variables, except
for CGI scripts spawned from Apache. In Apache/mod_wsgi they only
affect the per request WSGI environment.

Setting them in the WSGI script file also will have no affect, as
Python works out the default encoding when the interpreter is first
initialised, which means that doing it in the script file is too late.

What this is mean that you should insert export the LANG and LC_ALL earlier.

 

 

Test AddDefaultCharset (httpd.conf)

Check the httpd.conf for:

AddDefaultCharset

The problem may be there.

You can try to set it to

AddDefaultCharset UTF-8

or to off:

AddDefaultCharset Off

Test Nginx

If you have nginx installed, Add 

1
charset utf-8;

 line in 

1
http

 section in main Nginx config file (

1
/etc/nginx/nginx.conf

) or in section 

1
server

 in your virtual server config file.

Read more about Nginx HttpCharsetModule.

 

Django Admin

So, you’ve fixed the app.. now you can upload non ascii files but the Django admin return UnicodeEncodeError when you try to view the row in the admin panel?

Just fix your model __UNICODE__ function to return unicode (u”):

1
2
def __unicode__(self):
   return u'%s' % (self.file)
def __unicode__(self):
   return u'%s' % (self.file)

 

Read more..

Python vs PyPy installation and comparison (on Centos 6.x)

Python vs PyPy

in this article: Python vs PyPy I’ll explain how-to install both compilers (Python (CPython) and PyPy) on CentOS and the difference between them.

Requirements for examples:

  • Centos 6.x

 

Overview

The Download section of the Python official website (python.org) include list of several Alternative Implementations for python complier. some of them for Linux, some for Windows (.NET) and others.

I am going to review the default Python compiler vs PyPy on my CentOS 6.x machine.

 

python-logo

Python (nicknamed CPython)

Installation

yum install python

From Official website:

Python is a programming language that lets you work more quickly and integrate your systems more effectively. You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs.

Python (nicknamed CPython) is the default Python Compiler you get with you installing Python.

Example

Create a file named ‘example.py‘ and fill it with:

print 'Hello, world!'

and type on bash:

python example.py

Note: you can also insert the following line as the first line in your .py file and then chmod +x this file to execute it as script:

#!/usr/lib/env python
print “Hello, world!”

and then on bash:

chmod +x example.py

and you can run the script (code) using:

./example.py

 

 

pypy-logo

PyPy

fast python implementation with a JIT compiler (generate native code on the fly) written in RPython and currently translated partly to C.
Arguments against PyPy compiled in Python are everywhere, but when C compiler gcc is implemented in C, is there any reason for the Python compiler to not be written in Python?

From Wikipedia:

PyPy is a Python interpreter and just-in-time compiler. PyPy focuses on speed, efficiency and compatibility with the original CPython interpreter.[1]

PyPy started out as a Python interpreter written in the Python language itself. Current PyPy versions are translated from RPython to C code and compiled. The PyPy JIT compiler is capable of turning Python code into machine code at run time.

 

Mission

The mission of PyPy is:

We aim to provide:

  • a common translation and support framework for producing implementations of dynamic languages, emphasizing a clean separation between language specification and implementation aspects. We call this the RPython toolchain.
  • a compliant, flexible and fast implementation of the Python Language which uses the above toolchain to enable new advanced high-level features without having to encode the low-level details. We call this PyPy.

By separating concerns in this way, our implementation of Python – and other dynamic languages – is able to automatically generate a Just-in-Time compiler for any dynamic language. It also allows a mix-and-match approach to implementation decisions, including many that have historically been outside of a user’s control, such as target platform, memory and threading models, garbage collection strategies, and optimizations applied, including whether or not to have a JIT in the first place.

 

How can it possibly beat CPython?

Manual memory management (which is what CPython does with its counting) can be slower than automatic management in some cases.

Limitations in the implementation of the CPython interpreter preclude certain optimisations that PyPy can do (eg. fine grained locks).

The JIT. Being able to on the fly confirm the type of an object can save you the need to do multiple pointer dereferences to finally arrive at the method you want to call.

 

Installation

yum install pypy

 

Using PyPy

To use pypy instead of your default CPython compiler you need to run your .py file with the pypy compiler.

to use pypy compiler you type at bash:

and type on bash:

pypy myapp.py

 

Summary

Python compiler (CPython) is the default and probably the safe choice so most python applications and modules will work; where PyPy can break some.

You should play with them both. Install them both on your CentOS and test / benchmark your applications using both compilers.

PyPy can rebust your web applcations (or any other code).

For example, Django app can be run on top of PyPy, with drawbacks.

 

Read more…

gevent CentOS 6.x Installation Guide

gevent CentOS 6.x Installation Guide

gevent CentOS 6.x Installation Guide

Installation

Requirments

  • yum install python python-devel
  • yum install libevent-devel

 

Install Setuptools

install python-setuptools (for easy_install)

yum install python-setuptools

Install greenlet

Install greenlet:

easy_install greenlet

Install gevent

There are several ways to install gevent:

using easy_install (recommended)

easy as:

easy_install gevent

centos gevent

from source

You need wget to download source:

yum install wget

Now, installing gevent: (Check here for the latest package)

cd /tmp wget http://pypi.python.org/packages/source/g/gevent/gevent-0.13.8.tar.gz tar -xvzf gevent-0.13.8.tar.gz cd gevent-0.13.8 python setup.py install

U may need to add –no-check-certificate to the wget if something is wrong.

from GitHub

You can also install gevent from github using pip.

Test

to test simply run in bash:

python

and then:

import gevent

if no error found, you have installed it correctly python-import-gevent

First App

Example taken from the community documentation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from gevent.wsgi import WSGIServer
 
def application(environ, start_response):
    status = '200 OK'
    body = '<p>Hello World</p>'
 
    headers = [
        ('Content-Type', 'text/html')
    ]
 
    start_response(status, headers)
    return [body]
 
WSGIServer(('', 8000), application).serve_forever()
from gevent.wsgi import WSGIServer

def application(environ, start_response):
    status = '200 OK'
    body = '<p>Hello World</p>'

    headers = [
        ('Content-Type', 'text/html')
    ]

    start_response(status, headers)
    return [body]

WSGIServer(('', 8000), application).serve_forever()

copy the example into a file (server.py for ex), and start the server by:

python server.py

and that’s it! browse to the machine on port 8000 using something like this:

http://[ip of the machine]:8000

gevent-working

What’s next..?

 

Production

In production you can host your gevent after several WSGI server racks like: Gunicorn, Circus, Meinheld, uWSGI, etc..

Gunicorn is the most common WSGI server to host gevent applications. one benchmark shows that Circus is faster then Gunicorn. other tested uWSGI vs Gunicorn and found that uWSGI is faster.

recommend you run them behind a reverse proxy such as nginx. Additional advantages of running them behind a reverse proxy include improved handling of slow clients and bad HTTP requests

 

SocketIO

You need socketio? you may want to install it:

easy_install gevent-socketio

 

Read more…

 

need microframework? (flask/bottle)?

You can use a python web framework on top of gevent.

 

PHP GitHub followers count script (v3.0 API)

Php GitHub Followers Count

The following PHP GitHub Followers Count script is using the v3.0 GitHub API.

 

Overview

 I’ll explain how to get your github  followers count using PHP.

 

Get Followers Count

</span>

<?php
function curl_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$github_data = json_decode(curl_get_contents('https://api.github.com/users/your-user-name'), true);
$github_followers_count = $github_data['followers'];
echo $github_followers_count;
?>

 

 

More information

This article was based on the work of Jimbo and Meenakshi Sundaram R