Add facebook’s like button to your WP

This is very easy to integrate facebook’s like button to your posts. Ok here is step-by-step procedere.

1-Login to your Wordpress admin

2-Go to the appearance –> editor section

3-From right panel click on Main index Template

4-On the line before

<p class="postmetadata"></p>

5-Paste the below code

<div class="postmetadata" id="facebooklikebtn">
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php the_permalink() ?>&amp;layout=standard&amp;show-faces=false&amp;width=450&amp;action=like&amp;font=verdana&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:450px; height:20px"></iframe>
</div>

6-Do the above for the Page Template and Single Post
7-You Done!

If you have any question find me @digvan

Introduction to Redis

Introduction to Redis

Redis is a key-value database that has very nice features which every computer scientist love it.

Why I love Redis?

  • Redis give the data structure like all computer scientist learn in the school such as Set, sorted set, List, and Hash. So you don’t need to think in SQL anymore.
  • Redis is very fast it can gives you the performance about 50,000 to 100,000 operation per second in basic basic computers (2GHz CPU with 2GB RAM).
  • you can install Redis in 2 minutes. (Linux and Windows)
  • It’s written in ANSI-C so you can easily pick the source code (Yes, it’s open source!) and modify the code if you want.
  • There are native clients for almost every language (include PythonRuby and PHP) and Yes, you don’t need Thrift.
  • You can setup master-slave replication of Redis in 2 minutes.
  • Redis has great community lead by Salvatore Sanfilippo. (also check Redis Google group)
  • Redis is great for large scale web programming without need of MySQL. (Check Retwis )
  • Redis is very easy to learn.

Where should I start the basic?

  • First download the source code from Github or Google code.
  • Second compile the source code (basically just type ./make)
  • Download and install your language client if you prefer to work with Redis from your language here is list all language.
  • Run Redis server — $ ./redis-server — (Redis use port # 6379 by default)
  • Run Redis client  – $ ./redis-cli – and enter follow commands to see “Hello World!”

1- > set foo bar
2- > get foo
3- > lpush myList world!
4- > lpush myList Hello
5- > lpop myList
6- > lpop myList

In line 1, we set the key name “foo” to the value “bar”

In line 2, we get the value for the key name “foo” so the return value is “bar”

In line 3, we (left) push the value “world!” to the list “myList”

In line 4, we (left) push the value “Hello” to the list “myList”

In line 5, we (left) pop the value from “myList” and the return value is “Hello”

In line 6, we (left) pop the value from “myList” and the return value is “world!”

Now, you get the idea how Redis works, so lets do one real project in Python and Redis.

Can I see Redis in real project?

Yes, In this project I want to design a program that get the RSS from source, then parse the RSS and send the title of each news to Twitter.

What you need to do before start to code?

0- Python 2.5 or higher

1- Redis and py-redis

2- Twitter python library (included in package)

3- Yahoo social python

Next:    Enter the following code in your favorite text editor and save the file.

import redis,twitter
import yahoo.yql

def getandset():
	''' Get the weather condition for WOID=12778445 and save in the database'''

	q = yahoo.yql.YQLQuery().execute('select * from rss where url="http://weather.yahooapis.com/forecastrss?w=12778445"')
	temp = q["query"]["results"]["item"]["condition"]["temp"]
	text = q["query"]["results"]["item"]["condition"]["text"]
	date = q["query"]["results"]["item"]["condition"]["date"]
	#forecast
	high = q["query"]["results"]["item"]["forecast"][0]['high']
	low  = q["query"]["results"]["item"]["forecast"][0]['low']

	r = redis.Redis('localhost')
	r.set('weather:current:temp', temp)
	r.set('weather:current:cond', text.lower())
	r.set('weather:tomorrow:high', high)
	r.set('weather:tomorrow:low', low)

def post():
	API = twitter.Api(username = "YOUR TWITTER USERNAME", password = 'YOUR TWITTER PASSWORD')
	r = redis.Redis('localhost')
	temp = r.get('weather:current:temp')
	cond = r.get('weather:current:cond')
	tom_high = r.get('weather:tomorrow:high')
	tom_low = r.get('weather:tomorrow:low')
	if (temp or cond or tom_high or tom_low):
	tweet = 'Currently %s F and %s at %s. Tomorrow: high %s F, low: %s F'
	name = 'West Lafayette'
	tweet = tweet % (temp, cond, name, tom_high, tom_low)
	print tweet
	print "Posting...."
	API.PostUpdate(tweet)
	print "Done!"

if __name__ == '__main__':
getandset()
post()

Summery of code:
In this code we first use YQL (the service form Yahoo!) to get the RSS (in this example we get the weather condition for West Lafayette, IN)
Then we parse the RSS to get our desired field which is basically temperatures and forecast. After that we save these values to our database using ‘SET’ function. Please make attention to the key name style I use “‘weather:current:temp’” which is basically tell you in this key we want to have the today’s temperature. In the post function, I basically retrieve the value we inserted to database and post it to your Twitter account.
You can download the source code for this tutorial from here.
Now that you should learnt the SET data structure, next time I will explain LIST which is one of the most important structure in Redis.
Further Reading:

Extract Abstracts from PubMed

I’m in the research group that we want to extract protein-protein interaction by using partial matching. After a while we found we need some article’s abstracts from  National Center for Biotechnology Information by using PUBMED ID. Here is my program to get articles from NCBI, extract abstract section and save abstract part into new file name by PUBMED ID.

import urllib2
import re
import os
from BeautifulSoup import BeautifulSoup

DIRECTORY = "abstractFiles"
try:
        os.mkdir(DIRECTORY)

except OSError:
        print "the directory %s is already exist" %DIRECTORY

f=open('output-1.txt', 'r')

tickers = []
for line in f:
        tickers.append(line[13:21])

os.chdir(DIRECTORY)
for t in tickers:
        try:

                rows=urllib2.urlopen( \
                'http://www.ncbi.nlm.nih.gov/sites/entrez?db=pubmed&cmd=search&term=%s' \
                %t).read()

                soup = BeautifulSoup(rows)
                abs = soup.findAll('p',attrs={'class' : re.compile("abstract")})

                ab = str(abs[0])
                ab = ab[20:]

                ab = ab.replace('</p>','')
                t = open(t+'.txt','w')

                t.write(ab)
                t.close()

        except IOError:

                errors = [t]
                errf = open('bad_trickers.txt','w+')

                errf.write(str(errors))
                errf.close()

                print errors
f.close()

Note: This program is written in Python. To run this program you will need an external library named BeautifulSoup.

Click here to download the source code.

Artificial Intelligence

Finally this semester I got AI. I always like to be involve much and much in AI world, and now I feel AI and ML are my final goal. I would spend all my spare time to study more and more AI. I found some useful links for everyone interested too.

Digvan.Com!

Finally, after several month I updated my personal homepage. In this version I use jQuery as my AJAX framework. About jQuery, I should say it’s amazing easy to learn and work with. In my homepage I will keep my resume and portfolio up to date. Also I will add my pictures in photo section. Another intersting feature I added last night is “Latest Status” in footer. Now, I can update my latest status from my iPhone anytime, anywhere. It would be cool to review my status after 20 years!

Life Data Visualization

There is a guy who made this video with help of data mining and data visualization. He try to define the meaning of life and he is successful! Enjoy it!

 

Python usful libraries

In this post I want to make a list for all useful Python libraries that I use until now.

The good news is I will update this every once I use new library.

So now Let’s chill with Python Libraties.

You are more than welcome to share your favorite Python library in comment section.

Stock Historical Data

In my DB project I want to design a site for stock mining. First thing I did is writing a bot for downloading all stock historical data  in Python. I really like Python it makes my life a lot easier and more effective. Unless I don’t feel I’m really live effectively!

Here is code:

import urllib2

f=open(‘cusip.txt’, ‘r’)

tickers = []
for line in f:
tickers.append(line.split(‘,’)[0])
for t in tickers:
# Open the URL
try:
rows=urllib2.urlopen(‘http://ichart.finance.yahoo.com/table.csv?’+\
’s=%s&d=09&e=05&f=2008&g=d&a=3&b=12&c=1997′%t +\
‘&ignore=.csv’).read()
t = open(t+’.csv’,'w’)
t.write(rows)
t.close()

except IOError:
errors = [t]
errf = open(‘bad_trickers.txt’,'w’)
errf.write(str(errors))
errf.close()
f.close()
print errors

Click here to download!

lesson from Mark Cuban

Whats the best piece of advice you can give a young entrepreneur?

Ill tell you what I learned from Bobby Knight: everybody’s got the will to win but when it comes time to doing something, it’s always about someone else. Not many people have the will to prepare. You got to be willing to know your product and environment better than anybody. No matter what you do there is someone out there trying to kick your ass. You got to be the smartest guy in the room about your product. Then you need to have a revenue source. You need a company with a revenue to make money. Concept, competition, and where the money is — plus something you love doing. I’ve never had a day of work. When I die I want to come back as me.

Who’s the entrepreneur you respect most? Current or past?

I guess Bill Gates. Larry Ellison I respect. You know, old school entrepreneurs, it was just diffferent. There was a different crede. I used to want to be profitable every month, before going IPO. But then later I accepted running at a loss. From the Netscape moving on, that’s what has happened since — the whole idea now is to get pageviews and then figure out a revenue model. I think entrepreneurs these days have been cheated because for them, its not about understanding how to make money. But when the money goes dry, you’re shit out of luck. When the bubble burst, 9 out of 10 businesses went away. With weblogs, our mantra was sales cures all. We used to talk about bottom line, not top line. It always came down to what you’re putting into your pocket. I want a cash-in-pocket strategy not an exit strategy.When you walk down these halls, you dont have people making money yet.

Building a Successful Enterprise Software Company in the Microsoft Age

  • The bad news: It would be nice to collect money from thousands of customers in exchange for shrink-wrapped closed-source software, packaged by prison labor. Sadly this niche is occupied by Microsoft. Don’t be fooled by survivorship bias into thinking that your company has a chance of ascending to this privileged position.
  • The big question: “Why would a customer want to adopt software from any supplier other than Microsoft?”
  • You can’t be richer than Microsoft or smarter than its thousands of brilliant employees; you can attack a problem that Microsoft is not attacking (and the first company to deliver a solution to a customer is the first company that can learn from watching users)
  • If the problem area is new, and it probably is if Microsoft hasn’t been there already, requirements will be evolving rapidly; open-source is the best way of ensuring that requirements are met (note that “open source” need not mean “free”)
  • Achieving critical mass before Microsoft kills you, Part I: educational marketing via high-level papers and books, one-day high-level courses, and multi-day bootcamps
  • Achieving critical mass before Microsoft kills you, Part II: freely downloadable software, easy-to-understand software architecture, clear (not voluminous) documentation
  • Key to supra-normal return on investment in a free open-source world: you control what gets added to the next version of the software, i.e., you control which customers are running a standard version of the software and can upgrade painlessly and which customers are forced into ownership of customizations.
  • Consider releasing the product from a running system with real users (instead of the usual loop of users talk to marketing, marketing talks to product management, product management talks to programmers, new version gets released after 2 years and the cycle starts anew)

Resource:

1- http://philip.greenspun.com/teaching/short-talks