Posts Tagged ‘python’

Tabs vs. Spaces

December 1st, 2009

Every time I’ve seen one of these “vs” posts its gone into great length about the philosophy behind such and such.  You’ll never convince someone based on ‘religious argument’. So I’m going to take a different approach here and state who does what and hopefully the weight of ‘who does what’ will make the point quite clear.

Screw the Scientific Method!!

Language/Organisation Spaces Tabs Reference
PHP Pear * [1]
Zend (PHP) * [1]
Python * [1]
Ruby * [1]
Java * * [1]
.Net * [1]
C# * [1 Philips (PDF)] [2 - Microsoft]
Lua * [1]
Erlang * * [1]
Object Pascal * [1]
Adobe Flex * [1]
Ada 95 * [1]
Mozilla (Javascript) * [1]
Mozilla * [1]
Google * [1] [2]
Mono Project * [1]
Webkit * [1]
NASA * [1]
Apache (C) * [1]
Linux Kernel * [1]
Gnome * [1]
KDE Libs * [1]
Joomla * [1]
Wordpress * [1]
Zope * [1]
Django * [1]

Notes:

  • Tabs may be rendered differently on different editors and systems.  So they make for less friendly code sharing.
  • Its interesting to note that the ones using tabs all have histories of mental instability, cannibalism, Morris Dancing, witchcraft and heresy.

Clear win for Spaces, which happens to be what I use.

Python’s Beards and Ruby’s ‘Cool’ Guys

July 30th, 2009

I was having a chat on the MicroSoft Networks fancy comms protocol. Aka: MSN. Along came someone with an opinion. As is customary I shot it down with wild abandon!!

The quickie backstory:

  • I suggested Python is better than Ruby.
  • They argued using two example pictures – see below.

Rubyists

ruby_programmers.jpg



I Said:

The Ruby pic: The guy on the right has his eyebrow raised as if to say: “I’m fucking amazing”. The rest of them are all geeks who are using Ruby as their way to be cool in a world that rejected them at high school age for being geeks. Little do they realise (maybe deep down they do) but the only people who may think they’re cool is a small fringe group of other Ruby-ists and beginner coders. The other Ruby-ists will be consumed by an undertone of competitiveness. The Python coders will think they’re rubbish fanboys. The hot girl who rejected them at high school will think they’re just like any other geek.

Pythonistas

504x_Picture_2_23-18-44.png



I Said:

The good thing about the Python coders is they’re not bothered. They’re just not even trying. They’re so past giving a shit about being cool that they’ve all grown ugly facial hair.

This piercing psychological insight into the programmers of Python and Ruby is just the tip of the iceberg. For $200 I’ll furnish you with a graph showing my facts in a nice way that will go well in a professional report.

Excellent Apache Log Analyser & Monitor

July 23rd, 2009

python-logo-master-v3-TM.pngI’ve been looking up hill and down dale for a good (Python-based – fanboy!! Woo!!) log analyser and monitor for Apache.

It looks like I’ve found one – and awesome it is too!

wtop is by far the best I’ve come across of the options available and I’m not just saying that because its Python based. It nicely formats based on a variety of rules you give to it.

I plan on using it to monitor when certain IP’s access my server then hooking it upto an SMS API to text me when it happens. You can use it for monitoring of dodgy behaviour such as accesses to Paypal folders and such.

Some important points though:

  1. Make sure your log format is configured properly. You need to add the %D option which the default “combined” format doesn’t have.
  2. After changing the formats and making sure the wtop config matches your new Apache log format you may need to delete or archive your old ‘badly’ formatted logs. As wtop won’t cope well with the new/old format mix.
  3. Install it – don’t think it’ll work straight off the bat.
  4. Read the instructions.
  5. To make sure you’ve got it working run a very basic command with it that does no filtering.
    logrep -o 'class,max(bytes),avg(msec)' access.log
  6. More info on using logrep for monitoring your Apache logs is here.

Some More Examples…

  • Show all 404 page errors in log with a count:
    logrep -m grep -o 'status,count(*),url' -f 'status=404' access.log
  • Show visits of a certain IP to the homepage of the site:
    logrep -f 'ip~192.29.29,class=home' -o hour,minute,ip,url access.log

ASE Makes Android Development Pleasant

July 12th, 2009

android-logo.jpgHaving got myself a G1 phone a few weeks back I’ve been tinkering a lot. Mainly with the Android Scripting Environment that I plan on writing about soon but I thought I’d give a quick summary of what I’ve found so far on this platform – and why I don’t like it (kind of)!

It uses Java – of a sort. More specifically it uses the Dalvik VM which is a register based as opposed to stack based VM and has many of its core classes based on Apache Harmony.

(Did I sound like I knew what that meant? Because I didn’t. I was paraphrasing Wikipedia – I love Wikipedia’s ability to make you sound like an expert at anything)

That’s why I hate it – the Java part. I hate Java. I’ve not developed in Java since university and have conducted a mental cleansing of all my painful memories of the language. As such I am a desperate ‘newbie’ on this platform. Scrabbling round like some lost raccoon on the North York Moors (there are no raccons in England so it would be VERY lost).

ASE comes to rescue the day but first….

Why ASE? Android programs are ‘easy” enough to write.

This is in the wiki docs of ASE. This question gets asked – apparently quite frenquently.

All I can say is: “Holy mother of jesus-bloody-ballsing-christ”.

What I find even more shocking is the answer…

That’s very true. Android’s development environment does make life pretty easy.

PRETTY EASY?!?!

WHAT?!?!

Are you a masochist??

It took an hour just to get it all up & running. Getting Eclipse working how its meant to with the right plugins, setting up emulator images, downloading tutorials and the multitude of other faffing tasks.

If you’ve gotten used to scripting languages like Python, Ruby or PHP then programming Java is akin to stabbing your eyeballs repeatedly with a rusty fork. Its rammed full of verbose bullshit, silly configs, insane amounts of setup, strict typing, misery, self abuse, pain, kitten torture, puppy genocide, etc, etc.

For example try taking a look at the Android Dev tutorial. Part 1 will consume 6hrs of your life. After which you will have created a useless ‘notepad app’ that doesn’t allow you to edit or delete notes. Only create a new one with hard coded contents and a name. 6 hours and I could have built Athens Online – an online city of dreams and Greek pornography. What? Everything online is porn.

Anyway…

Java Can Come Later

I hate JavaThe Android Scripting Environment is a breath of fresh air though. This was released in May/June and allows development of quick, funky scripts in Python, Lua or BeanShell (*hiss*, *spit*). Ruby and Javascript are to follow soon.

If you fancy developing the scripts on your PC and running them on the phone you’ll need a tool available in the Android SDK called ADB (Android Debug Bridge). Though if you’re following the ASE docs don’t forget you need to turn on USB Debugging on the phone to enable it.

What It Can’t Do – Yet

I love ASE and I love the German gent who made it even more – even though I know only his name. I’m sure that he’s a great man for only a great man would create ASE.

Okay – I’ll stop now.

ASE can’t do the following at the moment:

  • Compile in to APK/packages for selling or distributing on Market or elsewhere.
  • Its restricted to a subset of the Android API made available by an RPC interface.
  • It can’t cure cancer.

I’ve got high hopes for ASE and its making my life more fun. If you’re a Python/Lua/scripting sort then you’ll love it too.

Django Debug Toolbar

December 20th, 2008
Django Debug Toolbar

Django Debug Toolbar

This looks very sexy – almost as sexy as DjangoPony.  Its a debug toolbar that was inspired by the PHP Symphony project.  Hold on now, don’t run away just cos I mentioned PHP.  This is pure Python goodness and its damn useful too.  It provides a load of debug info such as headers, exec time, SQL queries, variables, etc.

Its a MiddleWare app you can install into your Django installation.  Methinks I’ll give it a go at the weekend and report back.

Get it here.

Python Virtual Host Creator

December 10th, 2008

I just threw together a quick Python script which generates a virtual host file, enables it, creates the web directory and restarts the webserver.

It’s basic – but I found it useful.  Maybe someone else will too.

#!/usr/bin/python
import os, sys, getopt

def main(argv):

  try:
    opts, args = getopt.getopt(argv, "hd:a:", ["help", "domain="])
  except getopt.GetoptError:
    usage()
    sys.exit(2)

  if len(opts) < 1:
    usage()
    sys.exit(2)

  for o, a in opts:
    if o in ("-h", "--help"):
      usage()
      sys.exit()
    if o in ("-d", "--domain"):
      domain = a
    else:
      assert False, "unhandled option"

  directory = domain.split('.')[0]

  if not os.path.isdir("/var/www/%s" % directory):
    os.mkdir("/var/www/%s" % directory)

  if not os.path.isdir("/var/www/%s/htdocs" % directory):
    os.mkdir("/var/www/%s/htdocs" % directory)

  vhost_template = """
  
    ServerName www.__DOMAIN__
    ServerAlias __DOMAIN__
    DocumentRoot /var/www/__DIR__/htdocs
    CustomLog /var/log/apache2/__DOMAIN__-access.log combined
    ErrorLog /var/log/apache2/__DOMAIN__-error.log

    ErrorDocument 404 /404.html
    ErrorDocument 401 /401.html
    ErrorDocument 500 /500.html

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^__DOMAIN__
    RewriteRule (.*)$ http://www.__DOMAIN__$1 [R=301,L]

    
      Options +Indexes FollowSymlinks IncludesNoExec +Includes -MultiViews
      AllowOverride All
      Order Allow,Deny
      Allow from all
    
  
  """

  vhost = vhost_template.replace('__DIR__', directory).replace('__DOMAIN__', domain)
  open('/etc/apache2/sites-available/%s.conf' % directory, 'w').write(vhost)
  os.system('a2ensite %s.conf' % directory)
  os.system('/etc/init.d/apache2 restart')

def usage():
  print 'usage: newv.py [-d domain.com]'

if __name__=="__main__":
  main(sys.argv[1:])

Download It

Python 3.0 Breaks Backwards Compat

December 8th, 2008

But has lots of shiny new thigns to play with.

My Take

It feels like its been in development for a lifetime and its hard to believe its finally come around.  Some highlights include:

  • Print is now a function so must be called like:
    print("Doug is king of the world")
  • Comparisons tightened up – No longer can you mix and match differing types without getting a ValueError raised.
  • No longer a need for “long” as all ints are technically longs.
  • Finally the “1/2″ expression returns a float.
  • “as” and “with” introduced.
  • Can no longer use back ticks.
  • No longer use <> to mean != (thank god – I hated that!!)
  • Automatically attempts to import C-based modules when importing the standard Python versions.

Loads, loads more but I’m hardly going to rewrite the entire changes document verbatim.  If you really want the full list then go here.

I’m happy with change though I can see some of these taking some getting used to.  Especially some of the most commonly used, core areas of the language.

Top 15 Python E-Books (legal & free)

November 29th, 2008

I’ll not soil this posting with talk of copyrighted works and will keep it to strictly free, ebooks available to all.  These are the top 15:

  1. Dive Into Python – The original but not the best anymore.  It taught me Python so I’ve got fond memories and a special place in my heart for it.
  2. How to Think Like a Computer Scientist: Learning With Python – A newly revised edition of this book is due out in Feburary 2009 but its still worth taking a look at the original.
  3. Text Processing in Python – I haven’t read it but I thoguht I’d add it for the sake of completeness.
  4. Start Programming With Python – Its a relatively new project started by an enthusiast.  A hell of a lot has already been produced and its due to be finished by Xmas.
  5. PLEAC Python – Its like a rapid-fire Python Cookbook with short, concise examples of how to solve a variety of low-level problems.  Form string manipulation to database access.
  6. Non-Programmers Tutorial for Python – Its for non-programmers but its sometimes useful to read form a different point of view.  I find the perspective refreshing.
  7. Python 101 – Part of a university course this goes through the fundamentals as well as providing exercises.
  8. Thinking in Python Design Patterns and Problem-Solving Techniques – A mammoth title written by the great Bruce Eckel.
  9. Python Standard Library – This is seriously showing its age as it was originally written for Python 2.0.  Although there’s updates they’re incomplete.  Its still worth a look though to get a good idea of the Python core.
  10. Python Programming Tutorial – It looks okay, though nothing ground breaking.
  11. Django Book – A book on Pythons greatest web framework.
  12. Pylons Book – A book on Pythons 3rd best web framework.
  13. Sockets Programming in Python – I found this over at Scribd which is fast turning out to be a great little site.  I recommend you look at some of the other books on offer once you’ve looked at this.
  14. Python Network Programming – Heavy on theory and light on practice.  Still a worthy read when you need to sleep.
  15. Advanced Python Programming – This is actually a 126 slide lecture given by a Chicago University lecturer.  Some good stuff in here.

If I’ve missed any off you think are worthy then let me know.

If you’re after something in paper form then I’d recommend one of the books below.

Django and PayPal

November 25th, 2008

Found a nice snippet at the DjangoSnippets site that shows how to integrate your Django app with PayPal.

See the magic here.

Script OpenOffice Using Python

November 24th, 2008

Looks like Python is everywhere – even OpenOffice.  The PyUNO Bridge enables you to interact with the OOo API to extend its functionality.  Its feature complete but undergoing testing – get involved.