martes, 10 de enero de 2012

Pushing to a working webfaction repo from your dev machine

I was able to succesfully push to a git repository in webfaction using this general strategy. Save your self(and my future self) some googling and follow this links.
Set up the ssh connection
Follow the webfaction guide to set up a git repo
Follow Abhijit Menon-Sen guide to setup the push

lunes, 9 de enero de 2012

On yakuake in gnome

Note: I know this blog is called Notes on Using Python, but i'll also do random posts on using linux.

Yakuake its hands down the best drop down terminal emulator on Linux, but it can be tricky to get it to play nice with gnome.

THE PROBLEM
The behavior should be this:
  1. I hit my yakuake hotkeys(defined in the yakuake shortcut settings) and yakuake toggles between hidden or shown.
  2. I hit my show desktop hotkey and it toggles all the windows off and on.
Right now this happens
  1. I hit my yakuake hotkeys(defined in the yakuake shortcut settings) and yakuake does nothing.
  2. If yakuake is being show if i hit my showdesktop hotkey, yakuake ignores it and remains.
THE SOLUTION
My solution involves
Dont set a hotkey in the yakuake shortcut settings(delete any shortcuts)
Set a hotkey using the keyboard shortcuts gnome system application: adding a new shortcut that runs the command yakuake, to my desired hotkey.
To fix the show desktop im using wmctrl, which you can get using a simple:
sudo apt-get install wmctrl
Then create the file showdesktop
sudo gedit /usr/local/bin/showdesktop
Paste this content into the file and save it
#!/bin/sh
if wmctrl -m | grep "mode: ON"; then
    wmctrl -k off
    if ! wmctrl -l | grep Yakuake; then
        yakuake
    fi
else
    wmctrl -k on
    if wmctrl -l | grep Yakuake; then
        yakuake
    fi
fi
Give it permission to run
sudo chmod +x /usr/local/bin/showdesktop
And then go again to the keyboard shortcuts gnome system application and add a new shortcut that simply runs showdesktop.
Boom, now all works as expected.

domingo, 8 de enero de 2012

Different ways to get urls in a django view

During production i've had the need to various urls, and i've found a few ways to do this, i leave this here so hopefully somebody can use it, and as a self reminder.
1. Using the Sites app to get the current domain url
def current_domain_url():
    """Returns fully qualified URL (no trailing slash) for the
    current site."""
    from django.contrib.sites.models import Site
    current_site = Site.objects.get_current()
    protocol = getattr(settings, 'MY_SITE_PROTOCOL', 'http')
    port     = getattr(settings, 'MY_SITE_PORT', '')
    url = '%s://%s' % (protocol, current_site.domain)
    if port:
        url += ':%s' % port
    return url

Good side:
It does'nt need the request to work, only the Sites app with your list of sites.
Bad side:
The problem with this approach is that if it depends on the sites app, this is good enough if you are diciplined enough to keep that app updated with your development enviroment, your stating server and your production server, it can be annoying.
Via Fragments of code 
2. Using the HTTP_REFERER to get the current url

def current_site_url(request):
    """Returns fully qualified URL (no trailing slash) for the 
    current site."""
    return '/'.join(request.meta['HTTP_REFERER'].split('/')[:3])

Good side:
I'm not sure where this function could be used, maybe as a helper to prevent sites from outside yours to load some urls. Because of the:
Bad side:

It only works if the current view was called from another url. If the user types directly the url of the current view, it won't work because there is not http referer. Use it only if you are sure your view will always be called from a hyperlink.
Plus the client can modify the http header to send a different referer so it cannot be relied.


3. Using the request HTTP_HOST get the current url

def current_site_url(request):
    full_path = ('http', ('', 's')[request.is_secure()],
                       '://', request.META['HTTP_HOST'], request.path)
    return ''.join(full_path)

Good side:
It's the simplest form to get your current url. All it takes is a request.
Bad side:

Same problem as the HTTP_REFERER the client can modify the http header so it can't be relied upon.
Credit goes to limodou, the author of this django snippet


4. Using the built in build_absolute_uri to get the current url

from django.core.urlresolvers import reverse
def current_site_url(request,*args,**kwargs):
    """Returns fully qualified URL (no trailing slash) for the
    current site."""
    relative_url = reverse(*args,**kwargs)
    return request.build_absolute_uri(relative_url) 

Good side:
It's pretty solid, it only takes the current view, or an url name, basically everything reverse() accepts this functions does.

Bad side:
This function needs a relative url you want to get the full url, so its uses is limited. Also, the build_absolute_uri was introduce in Django 1.2+ so that could be a problem for older apps. And i'm not really sure about its short comings i haven't .

miércoles, 14 de diciembre de 2011

Fair power making decisions.

This post is not python related i just about i thought that came to me while i was reading the different takes VC's and entrepreneurs have on the work hours, on working hard.
This post is here to capture that thought because I'm building a theory of administration that's based on the balance between power and motivation. I firmly believe that many institutions in my country(México) could be 'fixed' if in the process of design them, the focus were placed on these two concepts. But that's material for another post lets focus on the subject at hand.

To sum it all up these are:
The VC's want you to work hard to make them money.
The entrepreneur wants to work hard to get ahead of the competition.

The decisive argument on the matter, as usual is up to science, and science basically says, the most efficient way for a human being to work is 8 hours at day, 5 days a week, more than that an productivity drops until it actually is dangerous for the human and for the work being done to put more hours. 

The programmers speak 


Science speak


The thought i was talking about is somehow related. In the comment area of the first link there is one particular argument that shows one flaw of the way we rationally argue, quote
We need to readdress the point that work is a negotiation between employer and employee. The first pays mainly money and maybe some other stuff in exchange for something, mainly the ‘production’. As such, the employer has the right to demand high output and quality. The employee has the right to work some place else.
Let me state first that my motivation for this critique is fairness. So the comment sound smart and enlighting and in a way it is. Put it plainly, the employer here has a range of options, a huge degree of possible decisions to make when dealing with a lazy employee, and the employee has only two, stay or leave.

The unfairness resides exactly in that difference, the employer can torture the employee, can motivate him, can move it to other place in the company, can do many many things, he is in a power position. The employee only two. Let me make this clear, there is no unbalance of power here, when it adds up, they both have tremendous power, because the employee is valuable and he carries knowledge and know-how useful for the company, and costly to lose. Is just that the power is too focused on two decisions while the power of the employer is spread in many possible decisions.

TLDR, the power relationships can be balanced fairly if we take into account, the weight each possible decision it enables the parties and the plain number of those possible decisions, not just the sum of the total weight.

In the next post i want to talk about the importance of perceived fairness in motivation.

miércoles, 30 de noviembre de 2011

Using heroku on webfaction

The idea here is to be able to fetch from a herokuapp to our webfaction server so we can have a nice development process like this:
We work on our local repo, this is the dev server.
We push to heroku, this is our staging area, we try and test new features here.
Then we go to webfaction and fetch from heroku and it will automatically update our production server.

Ok lets get started.

Open your ssh session to webfaction
mkdir ~/gems
Open the file .bashrc located at your home
nano ~/.bashrc
Paste this lines on the end of the file
export GEM_HOME=~/gems
export GEM_PATH=~/gems
Save the file with ctrl+o and hit ctrl+x to exit nano
Paste again these lines on your ssh session
export GEM_HOME=~/gems
export GEM_PATH=~/gems
Now install heroku
gem install heroku
Now you'll need to generate ssh keys for heroku we'll use this article,
Please visit the original article, i'll do the copy pasta because i really don't want to lose this information and the internets can be faulty.
 In quite a few situations its preferred to have ssh keys dedicated for a service or a specific role. Eg. a key to use for home / fun stuff and another one to use for Work things, and another one for Version Control access etc. Creating the keys is simple, just use:
ssh-keygen -t rsa -f ~/.ssh/id_rsa.heroku -C "Key for Word stuff"
Use different file names for each key. Lets assume that there are 2 keys, ~/.ssh/id_rsa.work and ~/.ssh/id_rsa.misc . The simple way of making sure each of the keys works all the time is to now create config file for ssh:
touch ~/.ssh/config
chmod 600 ~/.ssh/config
echo "IdentityFile ~/.ssh/id_rsa.heroku" >> ~/.ssh/config
echo "IdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config
This would make sure that both the keys are always used whenever ssh makes a connection. However, ssh config lets you get down to a much finer level of control on keys and other per-connection setups. And I recommend, if you are able to, to use a key selection based on the Hostname. My ~/.ssh/config looks like this :
Host *.heroku.com
  IdentityFile ~/.ssh/id_rsa.heroku
  User nombre.falso@gmail.com
Ofcourse, if I am connecting to a remote host that does not match any of these selections, ssh will default back to checking for and using the 'usual' key, ~/.ssh/id_dsa or ~/.ssh/id_rsa

Again, thanks to Karanbir Singh for this article, i've customized the code for our purposes.
Now, to make our life easier we will create an alias to the heroku bin
Open .bashrc again
nano .bashrc
Paste at the end of the file
alias heroku=~/gems/bin/heroku
Now you can follow the heroku tutorial to configure your account(register one if you don't have it) here are the steps
heroku config
Answer the questions, finish the wizard
Now go to where you want to keep your git repo fetched from heroku
cd ~/webapps/git/repos/
Initialize a new git repo i named mine heroku
git init heroku
cd heroku
Now add the remote heroku
git remote add heroku git@heroku.com:nameofyouraccount.git
Coincidentally my remote is named heroku, but you can name yours whatever you want, substitute nameofyouraccount with the name of your heroku account.
Now do,
git fetch heroku

And tada! you now have an easy way to pull changes from heroku to webfaction.

martes, 29 de noviembre de 2011

installing psycopg2 in Webfaction

If you use webfaction and you'r machine name is Web300 and above(Web301, Web302, etc) and you want to install psycopg2 you'll need
nano ~/.bashrc
Paste this
export PATH=/usr/pgsql-9.1/bin/:$PATH
Now hit ctrl+o and then ctrl+x
Now on the terminal export the path again
export PATH=/usr/pgsql-9.1/bin/:$PATH
And when you do
easy_install psycopg2
or
pip install psycopg2
It won't complain about pg_config executable missing.

sábado, 26 de noviembre de 2011

why post

I just read an awesome tip when learning new stuff, from the article on motivation and learning something from the Freakonomics guys(read the original book it explains the internet as we know it from an economic point of view)
Wheeler recommended that, after we solve any problem, we think of one sentence that we could tell our earlier self that would have “cracked” the problem. This kind of thinking turns each problem and its solution into an opportunity for reflection and for developing transferable reasoning tools.
I would have loved saying to my self.
Writting a new django feature takes this steps:

  • Think of the feature.
  • Think how you would put the data needed to drive the feature in a 2d table.
  • Create a new django app .
  • Write the name of the columns in a model inside models.py.
  • Write the logic that uses that data in views.py
  • Make sure your processed data ends ups in the context that view returns.
  • Write the template that uses the processed data.
And make sure you have the django official docs with your all the time!