Author Archives: Etay Cohen-Solal

About Etay Cohen-Solal

Development Specialist, Artist and Activist
Personal Website

PHP Twitter Followers Count script (v1.1 API)

Php Twitter Followers Count

The following PHP Twitter Followers Count script is using the new v1.1 Twitter API.

 

Overview

Recently, Twitter have changed their API and v1.0 is obselete. The new API requires OAuth. I’ll explain how to get your twitter followers count using PHP.

 

Create Application

First, you’ll need to get yourself a twitter dev account, if you haven’t done so yet.

Go here and register your app free.

 

TwitterAPIExchange

Download the TwitterAPIExchange library files created by J7mbo into your application.

you can git clone https://github.com/J7mbo/twitter-api-php.

I recommend the git method as you can git pull later to recieve updated.

 

Get Followers Count

Insert your OATH and Consumer Access-Token & Access-Token secret the the following code. Also, change the $getfield screen name to yours.

Now combine everything to make it work

require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "YOUR_OAUTH_ACCESS_TOKEN",
'oauth_access_token_secret' => "YOUR_OAUTH_ACCESS_TOKEN_SECRET",
'consumer_key' => "YOUR_CONSUMER_KEY",
'consumer_secret' => "YOUR_CONSUMER_SECRET"
);

$ta_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = '?screen_name=replace_me;
$requestMethod = '
GET';
$twitter = new TwitterAPIExchange($settings);
$follow_count=$twitter->setGetfield($getfield)
->buildOauth($ta_url, $requestMethod)
->performRequest();
$data = json_decode($follow_count, true);
$followers_count=$data[0]['
user']['followers_count'];
echo $followers_count;

 

Notes

I’ve placed the entire twitter-api-php folder inside my project. you can extract the files also, but make sure to require_once() from the correct path.

require_once(‘twitter-api-php/TwitterAPIExchange.php’);

if you’ve placed it inside the folder, or

require_once(‘TwitterAPIExchange.php’); if you extracted the files to the same folder as your script.

 

More information

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

CentOS Tornado server installation tutorial

Centos Tornado Server Installation Tutorial

 

Install using repository

yum install python-tornado

 

First ‘Hello World’ App

I’ve copied the hello world sample from Tornado documentation:

Create a new file called ‘hello.py‘ (or any other name) and fill it with:

1
2
3
4
5
6
7
8
9
10
11
12
13
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
   def get(self):
      self.write("Hello, world")
 
application = tornado.web.Application([
   (r"/", MainHandler),
])
 
if __name__ == "__main__":
   application.listen(8888)
   tornado.ioloop.IOLoop.instance().start()
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
   def get(self):
      self.write("Hello, world")

application = tornado.web.Application([
   (r"/", MainHandler),
])

if __name__ == "__main__":
   application.listen(8888)
   tornado.ioloop.IOLoop.instance().start()

Now start your server with simply typing at bash:

1
python hello.py
python hello.py

Now you can visit ‘127.0.0.1:8888‘ to watch your hello world first torando app.

It should return the ‘Hello, world‘ output into your browser.

 

Nginx

Good implementation of your server would be behind nginx server, where you can run multiple instances of your app on different port and serve them all throw port 80 using nginx load balancer.

http://www.tornadoweb.org/en/latest/overview.html#running-tornado-in-production

 

After you know how to start a torando server, you can jump into the documentation and learn how-to build your first Torando server!

 

Django Centos 6 Beginners Installation Guide

NOTE: This article was rewritten for CentOS 6.4. please read the updated post.

 

Django Centos 6

So you want your first django centos based web site? This is quite easy to install and configure. I’ll cover how to install Python/Django on your centos.

Django Centos

Prerequisite

  • Centos 6.x
  • Apache (httpd)

 

What is Python?

Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Its syntax is said to be clear and expressive.” from Wikipedia.

Visit http://www.python.org/

 

What is Django?

“Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.” from https://www.djangoproject.com/

Installing Python

Prerequisites

you may need the EPEL repositories for Centos.

1
2
3
4
cd /opt/
wget http://mirrors.nl.eu.kernel.org/fedora-epel/6/i386/epel-release-6-8.noarch.rpm
rpm -Uvh epel-release-6-8.noarch.rpm
rm epel-release-6-8.noarch.rpm -f
cd /opt/
wget http://mirrors.nl.eu.kernel.org/fedora-epel/6/i386/epel-release-6-8.noarch.rpm
rpm -Uvh epel-release-6-8.noarch.rpm
rm epel-release-6-8.noarch.rpm -f

 

Installation Process

Simple as:

1
yum install python
yum install python

test python by typing: “python” and you should see something similar to:

As for this time being of writing (June 18 2012), the version of python@EPEL is 2.6.6

Django works with any Python version from 2.6.5 to 2.7. It also features experimental support for versions 3.2 and 3.3. All these versions of Python include a lightweight database called SQLite so you won’t need to set up a database just yet unless you need other SQL

 

Installing SQL

If you need other SQL Server else then SQLite,  you can follow:
MySQL/MongoDB/CouchDB on RHEL/Centos 6.3
If you don’t need SQL and you installed Python 2.5 or later, you can skip this step for now.

 

 

 

 

Installing Django

1
yum install Django
yum install Django

 

Testing Django

Test Django by typing python on your command and then:

1
2
import django
print django.get_version()
import django
print django.get_version()

As you can see, the RPM version is version 1.3.1, while the current release version is 1.4.1. while you are not too far behind using EPEL, you won’t get to play with the last options. Internationalization: in template code is not available in 1.3.1 for example but only from Django 1.4

 

 

Creating Project

From the command, cd into a directory where you’d like to store your app, then run the following command:

1
2
django-admin startproject mysite
cd mysite
django-admin startproject mysite
cd mysite

 

Starting Server

1
python manage.py runserver
python manage.py runserver

You’ve started the Django development server, a lightweight Web server – easier to startwithout having to deal with configuring a production server — such as Apache — until you’re ready for production.

Browse to http://127.0.0.1:8000/ with your Web browser. You’ll see a “Welcome to Django” page. It worked!

To change port:

1
python manage.py runserver 8080
python manage.py runserver 8080

If you need to start the server to answer not only locally, use:

1
python manage.py runserver 0.0.0.0:8000
python manage.py runserver 0.0.0.0:8000

 

Remember: Apache loads Django environment when starting and keep running it even when source is changed! I suggest you to use Django ‘runserver’ (which automatically restarts on source code changes) in development sessions, unless you need some Apache-specific features.

 

Configure more…

Config Database

Edit mysite/settings.py. It’s a normal Python module with module-level variables representing Django settings.

Help here.

 

Django using Apache

To run your Django application inside apache – use either mod_python or mod_wsgi, Support for mod_python will be deprecated in a future release of Django. If you are configuring a new deployment, you are strongly encouraged to consider using mod_wsgi or any of the other supported backends.

 

Install mod_python

For this to work, you must have apache installed and configured.

1
yum install mod_python
yum install mod_python

python using mod_python

you need to configure you apache/VirtualHost to:

    AddHandler mod_python .py
    PythonHandler mod_python.publisher | .py
    AddHandler mod_python .psp .psp_
    PythonHandler mod_python.psp | .psp .psp_
    PythonDebug On</pre>
[/code]

 
<h3>Testing mod_python</h3>
Create a '<em>test.py'</em> file in your apache server. put inside:
[code lang="py"]<% req.write("Hello World!") %>[/code]

and browse to www.your.server/test.py and you should see the "Hello World!" there.
<h3>Django using mod_python</h3>
Edit your <tt>httpd.conf</tt> file:

[code lang="apache"]
<pre><Location "/mysite/">
    SetHandler python-program
    PythonHandler django.core.handlers.modpython
    SetEnv DJANGO_SETTINGS_MODULE mysite.settings
    PythonOption django.root /mysite
    PythonDebug On
</Location>

read more…

 

 

Install mod_wsgi

Deploying Django with Apache and mod_wsgi is the recommended way to get Django into production.

1
yum install mod_wsgi
yum install mod_wsgi

 

to use mod_wsgi, create an apache folder inside your project and create a django.wsgi file:

import os, sys
sys.path.append('/var/www/django')
sys.path.append('/var/www/django/mysite')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

import django.core.handlers.wsgi

application = django.core.handlers.wsgi.WSGIHandler()

 

and configure your apache with:

<VirtualHost *:80>

ServerName www.example.com
ServerAlias www.example.com
WSGIScriptAlias / /var/www/django/mysite/apache/django.wsgi

# Alias /robots.txt /var/www/django/mysite/static/robots.txt
# Alias /favicon.ico /var/www/django/mysite/static/favicon.ico
Alias /static/admin/ /usr/lib/python2.6/site-packages/django/contrib/admin/media/
Alias /static/ /var/www/django/mysite/static/
Alias /media/ /var/www/django/mysite/media/

<Directory /var/www/django/mysite>
Order allow,deny
Allow from all
</Directory>

<Directory /var/www/django/mysite/media>
Order deny,allow
Allow from all
</Directory>

<Directory /var/www/django/mysite/static>
Order deny,allow
Allow from all
</Directory>
</VirtualHost>

 

read more on: multiple django sites with apache & mod_wsgi

 

 

That’s it!

 

You’ve Python / Django installed on your Centos 6.3 and a new project template waiting for you to work on.

 

Continue reading…

* this article is an edited version of an older article.

unfortunately android keyboard has stopped FIX

unfortunately android keyboard has stopped

unfortunately android keyboard has stopped error in Google Android CyanogenMod CM10.1 custom rom is a very simple issue to fix.

  • Goto your phone settings -> Apps
  • Change from “Downloaded” tab to “All” tab.
  • Click on “Android keyboard (ASOP) and click on “Clear Data”.
  • Click on “Dictionary Provider” and click on “Clear Data”.

unfortunately android keyboard has stopped FIX

Yamaha P-95 out of tune solution

Overview

Yamaha P-95 out of tune? I’ll explain the keys to reset your keyboard to default tune and…. I’ll teach you how to retune it again when you want to.

Yamaha P-95 out of tune

Your P-95 keyboard may be pitched or in trasposition.

Pitch

Reset

To reset your P-95 pitch hold down the A-1, B-1, C0 and C#0 keys simultaneously (most left 3 white keys of your keyboard) and press any key between C3 and B3.

p95-reset

Raise

to raise pitch in your P-95 keyboard hold down the A-1, B-1 and C0 keys simultaneously and press any key between C3 and B3.

p95-raise

Lower

to lower pitch in your P-95 keyboard hold down the A-1, B-1 and C#0 keys simultaneously and press any key between C3 and B3

p95-lower

Transposition

Reset

To reset transposition in your P-95 hold down the [DEMO/SONG] and [METRONOME] buttons, press the C3 key

Raise or lower

To raise transposition in your P-95 or lower hold down the [DEMO/SONG] and [METRONOME] buttons, press one of the F#2–F#3 keys to set the desired amount of transposition

  • any key between C#3 and F#3 to transpose up.
  • any key between F#2 and B2 to transpose down.
Yamaha P-95 out of tune

Yamaha P-95 out of tune

That’s it! for more information consider reading the manual.

configure apache

Apache Variables using system variables or mod_macro

Apache Variables

Apache Variables are not supported by defaultby apache but you can do two things to achieve this functionality::

  • Option 1 – Use system variables
  • Option 2 – Use mod_macro

Applicable to

  • Centos 6.x

This article was written with instructions for Centos 6.x, but the concept applies any distibution.

 

Option 1 – System Variables

Add variables in init script

To set environment variables in your Apache init script (/etc/init.d/httpd) before the line that calls httpd. For example, add:

MYVAR=value

Better would be to store all the variables in an external file, for example you can call it: /etc/httpd/conf/vars.txt and add to it all your variables:

MYAPP=/path/to/dir
BAR=/path/to/dir

and then include these into your Apache init.d script with:

. /etc/httpd/conf/vars.txt

you can also reload the file into memory by using the last command on shell.

to check that the variables added to your system variables use the set command:

set

Using inside configuration

Variables can be used in the configuration like so:

${MYVAR}

The variables can be used anywhere.

You can pass the variable into your CGI scripts and SSI pages using mod_env by adding to your confs:

PassEnv LD_LIBRARY_PATH

 

Option 2 – mod_macro

You can use apache Variables as functions using mod_macro extension,

mod_macro enables you to create macro functions with variables like:

<Macro VHost $host $port $dir>
  Listen $port
  <VirtualHost *:$port>

    ServerName $host
    DocumentRoot $dir

    <Directory $dir>
      # do something here...
    </Directory>

    # limit access to intranet subdir.
    <Directory $dir/intranet>
      order deny,allow
      deny from all
      allow from 10.0.0.0/8
    </Directory>
  </VirtualHost>
</Macro>

## Use of VHost with different arguments.

Use VHost www.apache.org 80 /projects/apache/web
Use VHost www.perl.com 8080 /projects/perl/web
Use VHost www.ensmp.fr 1234 /projects/mines/web

* example taken from here.

Prerequisites for mod_macro

  • The scripts in the article uses wget: yum install wget
  • apxs: yum install httpd-devel.i386
  • apache version 2.3

check your apache version using:
httpd -v

centos repository have apache 2.2.15, so you’ll need to compile newer version from source which is out of the bounds of this article. if you have later version of apache you can still use mod_macro which is better solution (for me) over system variables

 

mod_macro

to download and install mod_macro type:

cd /tmp
wget http://people.apache.org/~fabien/mod_macro/mod_macro-latest.tar.gz
tar xzvf mod_macro-1.2.1.tar.gz
apxs -cia mod_macro-1.2.1/mod_macro.c

Update 1.2.1 if wget returns newer version.

read more information and view demonstration code of how to use this extension check: http://www.cri.ensmp.fr/~coelho/mod_macro/

 

That’s it! select the way appropriate for your apache variables…

Android preference multiple dependency with CheckBoxPreference

Android preference multiple dependency

Android preference multiple dependency is not out-of-the-box feature until api level 14 introduced us with SwitchPreference (extends TwoStatePreference) to implement such feature. the old CheckBoxPreference can’t do that.

 

If your app is designed for newer systems only, (min-api equal or higher than 14) that won’t be a problem for you – because you can use the new SwitchPreference element to get at least 2 states, but if your app designed to work with older api support, or more than 2 dependencies on one element – you need another method.

Note: you can always implement both ways! use the ‘/xml-v14‘ directory to create multiple version of your XML, better with include, one for API 14 with SwitchPreference, and one for the old API’s with the following solution.

Continue reading

Tutorial: Your first WSGI Python web application served on Apache HTTPd.

Abstract

We’ll create a new python project using wsgi (web server gateway interface)

 

Introduction

Python based web applications can be served in several ways. You can use the old and good CGI interface, or use the more common used mod_python. FastCGI and SCGI are also an option. but most of those ways supports the WSGI interface which is the recommended way. You can learn more about each way, and the cons and pros of each, and what is wsgi  in this great tutorial/article: How to use python in the web.

We’ll build a skeleton for a Python based WSGI web application hosted on Apache HTTPd. I’ve choosed WSGI over other methods to promote web application portability across a variety of web servers.

 

Prerequisities

  • Python
  • Apache HTTPd Service running and working. trim instance is better.

 

Setup

mod_wsgi

red-hat/fedora/centos: install mod_wsgi using:

yum install mod_wsgi

debain/ubuntu: install mod_wsgi using:

apt-get install mod_wsgi

 

Virtual Application

configure your httpd with:

1
2
3
4
5
WSGIScriptAlias /myapp /var/www/myapp/myapp.wsgi
<Directory /var/www/myapp>
   Order allow,deny
   Allow from all
</Directory>
WSGIScriptAlias /myapp /var/www/myapp/myapp.wsgi
<Directory /var/www/myapp>
   Order allow,deny
   Allow from all
</Directory>

 

WSGI

Create the file myapp.wsgi at ‘/var/www/myapp’ and fill it with the example from mod_wsgi documentation:

1
2
3
4
5
6
7
8
9
def application(environ, start_response):
    status = '200 OK'
    output = 'Hello World!'
 
    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)
 
    return [output]
def application(environ, start_response):
    status = '200 OK'
    output = 'Hello World!'

    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]

You may need to restart your apache using: service httpd restart.

Now use your browser to see the ‘Hello World’ response from your first wsgi server.

Helloworld

 

More information

 

Happy wsgi python-ing…!