A better diigo bookmarklet (diigolet)

Posted March 29th, 2013 in Uncategorized by Florentin

What is the ‘diigolet’

The diigolet is a Diigo.com tool used to manage a user’s bookmarks. It is a bookmarklet, a bookmark stored in a browser that contains Javascript.
The original diigolet is here:

https://www.diigo.com/tools/diigolet

How is BetterDiigolet different ?

BetterDiigolet by default opens the “bookmark” menu from the diigolet toolbar, it fills in the description and clicks all recommended tags. All is left for the user is to click “Save Bookmark”.
If it’s used on a already bookmarked url, it will color the tags previously used in ‘green’. The new recommended tags will remain ‘blue’.
This is an easy way for the user to find out if the url has been bookmarked before.
By using better_diigolet.js one can save time with clicking though all the tags and filling in the bookmark’s description field.

How it’s built

Diigo’s diigolet is loading a js file named “diigolet_b_h_b.js” which in turns loads “diigolet.js”. diigolet.js contains jQuery v1.4.3.
BetterDiigolet loads everything in better_diigolet.js, jQuery has been replaced with v1.8.3
The downside is the missing “Loading Diigolet…” tooltip.

How to install it in Firefox

  1. Make sure the “Bookmarks Toolbar” is visible. If it is not, go to menu View > Toolbars.
  2. Drag this button: BetterDiigolet up to your Bookmarks Toolbar.

Django reusable apps

Posted October 31st, 2012 in Python by Florentin

Warning: this article is still a draft

Explaining the Django reusable apps in an agile way

  • as a developer
    • i want to easily plug the app into the project so that i can improve the productivity
    • i want to customize and extend existing Django apps so that they fit the requirements
  • some of the things that need customization:
    • models
      • e.g. make the app work with a different model class than the ones provided by the app
      • e.g. create a custom model based on the one supplied by the app and add extra fields or modify the existing field definition
    • forms
      • e.g. the app should use a custom form
      • e.g. a custom form which adds extra fields or change the definition of the existing ones
    • template names
    • success or redirect urls
    • template variables (extra_context)

1 James Bennett’s approach – the custom objects are passed as arguments to the views

 

(APP/views.py)
def register(request, success_url=None,
form_class=RegistrationForm
template_name=’registration/registration_form.html’,
extra_context=None):

2 Use the settings to define the custom objects

 

  • in settings.py, define the values for models/forms/etc which will be later used by the app
  • it’s useful to prefix all the names required by a specific app, i.e. BLOGAPP_MODEL, BLOGAPP_FORM etc
  • example

(settings.py)
MY_APP_MODEL = MyAppModel

(APP/views.py)
from django.conf import settings
from .models import AppModel

def register(request):

my_model = getattr(settings, ‘MY_APP_MODEL’, AppModel)

What the current approaches don’t offer

  • an easy way to modify or extend the urls. The urlpatterns is just a list, it’s difficult to delete/edit/insert url definitions.
  • models placed in models.py are used by Django in different db operations (i.e. syncdb).

One might want to ignore those models and let Django use customized/child Models.

  • the Model and Form fields are not easy to alter

Ideas for a new solution

  • make everything a class. Forms and Models are classes but the urls (or maybe the views) are not.
  • move the Model definitions from models.py and allow the developer to use it’s own Models (i.e. though getters or factories)
    • instead one can play with abstract models but without any concrete Models the app won’t work out of the box
  • define the Form and Model fields inside a method so that the derived classes can modify the definitions

Resources

Django project skeleton

Posted October 24th, 2011 in Python by Florentin

If you need a Django project skeleton to base your work upon, please check this one:

https://github.com/florentin/django-project-skeleton

And now a Django app skeleton as well

https://github.com/florentin/django-app-skeleton

Django settings

Posted October 24th, 2011 in Python by Florentin

I’m going to talk here about various techniques regarding the Django’s settings.

Let’s assume the following project layout:
.
├── __init__.py
├── manage.py
├── settings
└── urls.py

How do I use custom settings or overwrite existing ones on my development machine ?

Answer 1

Create your custom settings file under the same parent as the existing settings.py. Let’s name the new file settings_local.py
At the bottom of settings.py, add the following:

try:
    from settings_local import *
except ImportError:
    pass

Pros

  • no need to change the manage.py or the wsgi file in order to apply the new settings

Cons

  • hard/impossible to use different settings for different environment

 Answer 2 (preferred)

Create a new directory called “settings” and move the existing setting file there. Then make a different file for each type of environment.
.
├── __init__.py
├── manage.py
├── settings
│   ├── __init__.py
│   ├── development.py
│   ├── production.py
│   └── settings.py
└── urls.py

settings.py will include the default Django settings, probably the file created by django-admin.py
development.py will hold settings/overwrites needed for the development environment.
The extra settings files (production.py, development.py, etc) will extend the existing settings.py (or another parent file which in turn extends settings.py) and add their own settings customizations.
This could be your development.py file:

from .production import *
DEBUG = True
TEMPLATE_DEBUG = True
DJANGO_SERVE_PUBLIC = True
PREPEND_WWW = False
SEND_BROKEN_LINK_EMAILS = False
# APP: debug_toolbar
MIDDLEWARE_CLASSES += (
"debug_toolbar.middleware.DebugToolbarMiddleware",
)
INSTALLED_APPS += (
"debug_toolbar",
)
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
}
TEMPLATE_CONTEXT_PROCESSORS += [
'django.core.context_processors.debug'
]

Where production.py is:
from .settings import *
import os.path
PROJECT_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../')
DEBUG = False
TEMPLATE_DEBUG = False

Once your settings setup is in place, all you have to do is change manage.py and your WSGI file.
The manage.py file could now look like this:

#!/usr/bin/env python
from django.core.management import execute_manager
import sys, os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, PROJECT_ROOT)
try:
import settings.development # Assumed to be in the same directory.
except ImportError, e:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things. You'll have to run django-admin.py, passing it your settings module. (If the file settings.py does indeed exist, it's causing an ImportError somehow.) " % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings.development)

In the same time, your WSGI file would use settings.production:

os.environ["DJANGO_SETTINGS_MODULE"] = “settings.production”
Pros

  • easy to create settings for each of your environments (production, development, etc)
  • it’s a great way to keep your settings organized, easy to find and edit.
  • easier to reuse your settings for other projects. For example, we could use the same development.py file (as shown above) with other production.py settings.

Cons

  • you have to change the manage.py and the WSGI file, which might not be possible on your client server.

 Other Django settings tips

  • do not use your project name in the settings, i.e. use ROOT_URLCONF = ‘urls’ and not ROOT_URLCONF = ‘myproject.urls’, use INSTALLED_APPS = (“appname”,) and not INSTALLED_APPS = (“myproject.appname”, ). You will then be able to easily move settings and applications between one project to another
  • use calculated paths for TEMPLATE_DIR, MEDIA_ROOT, STATIC_ROOT etc, i.e. PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) and then MEDIA_ROOT = os.path.join(PROJECT_ROOT, “media”)

This means business

Posted August 23rd, 2011 in Funny by Florentin

This is how it goes …

Father: Son, I would like to be the one who chooses your future wife.

Son: No way

Tata: That girl is Bill Gates’s doughter

Son: AAA, then it is ok.

Father goes to Bill Gates

Father: I want my son to marry your daughter.

Bill Gates: No chance

Dad: My son is CEO of the World Bank

Bill Gates: aa, then it is ok.,

Father goes to World Bank President

Tata: I would like to offer my son as CEO of the World Bank

Presenintele: No chance

Dad: My son is the future husband of Bill Gates’s doughter

President: Oh, that’s ok.

This means BUSINESS

How Rational Are You?

Posted August 2nd, 2011 in Uncategorized by Florentin

Five questions to get you thinking

By Kurt Kleiner

I recommend reading the whole article here

Although intelligence as measured by IQ tests is important, so is the ability to think rationally about problems. The surprise is that less intelligent people usually perform just as well as highly intelligent people on problems that test rationality. Here are a few questions that test if you’re a rational thinker.

1. A bat and ball cost $1.10 in total. The bat costs $1 more than the ball. How much does the ball cost?

2. Is the following conclusion logically valid?

Premise 1: All living things need water.

Premise 2: Roses need water.

Therefore, roses are living things.

3. XYZ virus causes a disease in one in every 1,000 people. A test always correctly indicates if a person is infected. The test has a false-positive rate of five per cent – in other words, the test wrongly indicates that the XYZ virus is present in five per cent of the cases in which the person does not have the virus. What is the probability that an individual testing positive actually has the XYZ virus?

4. There are four cards on a table. Each has a letter on one side and a number on the other. The cards look like this:

K A 8 5

Here is a rule: If a card has a vowel on its letter side, it has an even number on its number side. Which card(s) must be turned over to find out if the rule is true or false?

5. According to a comprehensive study by the U.S. Department of Transportation, a particular German car is eight times more likely than a typical family car to kill the occupants of another car in a crash. The U.S. Department of Transportation is considering recommending a ban on the sale of this German car. Do you think the United States should ban the sale of this car?

Answers

1. Five cents. Many people, including students at MIT, Princeton and Harvard, automatically answer 10 cents. After all, a dollar plus 10 cents equals $1.10. But that cognitive shortcut doesn’t work, since it would mean the bat costs only 90 cents more than the ball.

2. No, it is not logical, even though 70 per cent of university students given the problem think it is. Although the conclusion is true, it doesn’t follow from the premises. Consider the same problem worded in a different way:

Premise 1: All insects need oxygen.

Premise 2: Mice need oxygen.

Therefore, mice are insects.

In the original problem, the tendency is to be a cognitive miser, and let the obvious truth of the conclusion substitute for reasoning about its logical validity. (In the second problem, though, our cognitive miser makes the problem easy.)

3. Two per cent. (Most people say 95 per cent.) If one in 1,000 people has the disease, 999 don’t. But with a five per cent false-positive rate, the test will show that almost 50 of them are infected. Of 51 patients testing positive, only one will actually be infected. The math here isn’t especially hard. But thinking the problem through is tricky.

4. A and 5. Ninety per cent of people get this one wrong, usually by picking A and 8. They think they need to confirm the rule by looking for a vowel on the other side of the 8. But the rule only says that vowels must have even numbers, not that consonants can’t. An odd number on the back of the A, or a vowel on the back of the 5, would show that the rule is false.

5. OK, there’s no right or wrong answer here. However, 78 per cent of the people Stanovich sampled thought the German car should be banned. But when he turned the question around so that Germany was considering banning an American car (he was quizzing people in the U.S., by the way), only 51 per cent thought Germany should ban the car. This is an example of “myside bias” – evaluating a problem from a standpoint that is biased toward your own situation.

reCaptcha for Django’s comments framework

Posted July 26th, 2011 in Python by Florentin

This is how you add reCaptcha (the captcha system built by Google) to the Django’s comments framework.

Requirements

For this task you will need to build a custom module which depends on django-recaptcha-works. recaptcha-works provides a special Form field named “RecaptchaField”
and a decorator function “fix_recaptcha_remote_ip” which inserts the request’s REMOTE_ADDR (IP) into the request.POST data.

django-recaptcha-works can be downloaded from http://pypi.python.org/pypi/django-recaptcha-works/ or install it with:
pip install django-recaptcha-works

You also need a pair of reCaptcha keys from this address:

https://www.google.com/recaptcha/admin/create

Build a custom comment module

Create a new comment module, add it to INSTALLED_APPS and set a special settings COMMENTS_APP. The process is described on this page:

https://docs.djangoproject.com/en/dev/ref/contrib/comments/custom/

cd /path/to/your/project
mkdir my_comment_app

Make these changes to your settings file (usually settings.py):

INSTALLED_APPS = [
...
'my_comment_app',
...
]
COMMENTS_APP = 'my_comment_app'
RECAPTCHA_PUBLIC_KEY = 'public key'
RECAPTCHA_PRIVATE_KEY = 'private key'

recaptcha-works provides more settings, please check the settings.py from inside the recaptcha-works module.
Here are some interesting settings:

RECAPTCHA_USE_SSL = False
RECAPTCHA_OPTIONS = {
        'theme': 'white',
        'lang': 'en',
        'tabindex': 0,
}
RECAPTCHA_VALIDATION_OVERRIDE = False

Inside your new module “my_comment_app”, create these files:

__init__.py

from .forms import CustomCommentForm
def get_form():
return CustomCommentForm

forms.py

from django.contrib.comments.forms import CommentForm
from django.contrib.comments.models import Comment
from recaptcha_works.fields import RecaptchaField

class CustomCommentForm(CommentForm):
    recaptcha = RecaptchaField(label='Human test', required=True)
    def get_comment_model(self):
        return Comment

models.py

from django.db import models
from django.contrib.comments.models import Comment

class CustomComment(Comment):
    pass

urls.py

from django.conf.urls.defaults import patterns, include, url
from . import views

urlpatterns = patterns("",
    url(r'^post/$', views.custom_post_comment, name='comments-post-comment'),
    url(r'', include('django.contrib.comments.urls')),
)

views.py

from django.contrib.comments.views.comments import post_comment
from recaptcha_works.decorators import fix_recaptcha_remote_ip

def custom_post_comment(request, next=None, using=None):
    return fix_recaptcha_remote_ip(post_comment)(request, next, using)

You can download a sample of the module here.

Configure Apache and Mysql the easy way

Posted July 18th, 2011 in Php by Florentin

This is a simple way to setup a LAMP environment after you have just installed a Linux (i.e. Ubuntu)
or if you’d like to replicate the setup of another machine (i.e. duplicate your desktop’s environment to your laptop)
The key is to keep all your customizations in separate files and directories.
We start by creating a new folder where all our custom settings will live.

1. prerequisites

Create a directory named "lamp" with the following structure:

├── apache
│   └── elmo.conf
├── install.sh
├── mysql
│   └── elmo.cnf
├── php
│   └── elmo.ini
└── virtualhosts
├── 000-localhost.conf
└── phpmyadmin.conf

2. configure Apache 2

The default apache2.conf (/etc/apache2/apache2.conf) is setup to include every settings file it can find inside the "conf.d" directory (/etc/apache2/conf.d)
so make sure this line is included:
Include conf.d/

We will sym link our Apache customizations into this directory:
sudo ln -s /lamp/apache/elmo.conf /etc/apache2/conf.d/

You may now add your own Apache settings into the elmo.conf file.
The files under "conf.d" are loaded in order of their file names i.e. aaa.conf loads before bbb.conf
All the files inside "conf.d" are loaded at the end of the apache2.conf so your custom settings may override the defaults.

After the settings are in place, you may want to automatically configure some virtual hosts.
Optionally, you could delete the default/old virtual hosts:
rm /etc/apache2/sites-enabled/*

Now new hosts are ready to be enabled:
ln -s /lamp/virtualhosts/000-localhost.conf /etc/apache2/sites-enabled/

3. configure Mysql 5

Mysql does the same configuration loading as Apache.
The last my.cnf directive is "!includedir /etc/mysql/conf.d/" which loads every settings file from the "conf.d" directory.
Let’s do the symbolic linking:
sudo ln -s /lamp/mysql/elmo.cnf /etc/mysql/conf.d/

Place all your Mysql customizations inside the elmo.cnf file.

4. configure Php / Zend Server CE 5.2

My Php environment is provided by Zend Server Community Edition.
The php.ini file located under /usr/local/zend/etc/ uses this directive to include the settings file from inside "conf.d":
[Zend]
zend.ini_scandir=conf.d

Obviously, we will create a symbolic link to our custom Php settings:
sudo ln -s /lamp/mysql/elmo.ini /usr/local/zend/etc/conf.d/

5. other

If you wish to automate things further add all the commands inside a bash script:

#!/bin/bash
# USAGE: sudo ./install.sh

ROOT="/lamp"

# mysql
ln -s $ROOT/mysql/elmo.cnf /etc/mysql/conf.d/

# apache
ln -s $ROOT/apache/elmo.conf /etc/apache2/conf.d/

# remove old virtual hosts
rm /etc/apache2/sites-enabled/*

# add my virtual hosts
ln -s $ROOT/virtualhosts/000-localhost.conf /etc/apache2/sites-enabled/
ln -s $ROOT/virtualhosts/phpmyadmin.conf /etc/apache2/sites-enabled/

# php configuration
ln -s $ROOT/php/elmo.ini /usr/local/zend/etc/conf.d/

Here you can download a sample

Searching for Django help and inspiration

Posted July 18th, 2011 in Python by Florentin

docs.djangoproject.com

The most important resource which will answer most of your questions is the manual.
1. You can either use the built in search:
https://docs.djangoproject.com/search/?q=forms&release=5
2. Or search the documentation though Google (my preference):
http://www.google.com/search?hl=en&tbo=1&q=forms%20site%3Ahttp%3A%2F%2Fdocs.djangoproject.com/en/dev%2F

stackoverflow.com

This is the second biggest resource of information regarding Django development.
There are several ways to search for answers:
1. Use the search form and look for the terms "django" and the topic you are interested in (e.g. "forms"):
http://stackoverflow.com/search?q=django%20forms
2. Search for the tag "django" and your topic of interest (e.g. "forms")
http://stackoverflow.com/search?q=[django]+forms

The first form yields many more results than the second, but the relevance of the second type of search is higher.
Furthermore, you can sort your results by "relevance", "newest", "votes" and "active". I recommend using "votes" when searching for a high level topic like "forms".

Google

If the first 2 methods don’t help, you may need to ask the big boss:
http://www.google.com/search?hl=en&tbo=1&q=django%20forms

You may have to remember to use "+" or "*" inside your queries if you are looking for something very specific.

djangosnippets.org

Small fragments of code that you can use or get inspiration from.

pypi.python.org

Search for Python modules. Try your search with and without the "django" term added to the query.
Example: http://pypi.python.org/pypi?%3Aaction=search&term=django%20forms
A nicer list of Django packages with details about usage, contributions and others is http://djangopackages.com/

others

If you are used to IRC channels, mailing lists or forums this page gives some indications:
https://docs.djangoproject.com/en/dev/faq/help/

search with firefox shortcuts

One last trick for Firefox users, "Add a keyword for this search" improves your query rate a lot. Some of my settings:

Location: http://stackoverflow.com/search?q=%s
Keyword: so

Location: http://www.google.com/search?hl=en&tbo=1&q=%s%20site%3Ahttp%3A%2F%2Fdocs.djangoproject.com/en/dev%2F
Keyword: dj

Location: http://www.google.com/search?hl=en&q=%s%20site%3Adjangosnippets.org
Keyword: djsnip

Location: http://pypi.python.org/pypi?%3Aaction=search&term=%s
Keyword: pip

Host based PHP settings

Posted July 18th, 2011 in Php by Florentin

How do you deploy a php settings file on multiple hosts which require different configurations ?
Let’s use the wp-config.php (WordPress configuration file) as an example.
The following snippets are going to be used inside your project’s config file (wp-config.php in this case)

Solution 1

1.a

if($_SERVER['HTTP_HOST']==’example.com’ || $_SERVER['HTTP_HOST']==’www.example.com’) {
# settings for the host example.com
} else {
# default settings
}

1.b

if(strpos($_SERVER['HTTP_HOST'], ‘example.com’)!==false) {
# settings for example.com
} else {
# default settings
}

If you need to define settings for multiple hosts, use a "switch" statement instead of "if"

Instead of "HTTP_HOST" one can also use "SERVER_NAME"

Alternatively to HTTP_HOST one can set the following in the apache’s virtual host
SetEnv APPLICATION_ENV "development"
then check for $_SERVER['APPLICATION_ENV']

Pros
- light on the CPU and no disk access

Cons
- only works when the PHP file (wp-config.php in our example) runs though a web server environment, i.e. $_SERVER['HTTP_HOST'] is available.
- all settings live in the same file, if the file is added to a version control system everyone can view those settings.

Running the code though command line won’t work as expected.

Solution 2

if($_SERVER['REMOTE_ADDR']==’127.0.0.1′) {
# localhost settings, host1
} else {
# any other settings, host2
}

Cons
- only works for 2 hosts, a localhost host (host1) and a remote host (host2)
- the settings for the host considered remote (host2) only work when the visitors come from a non-local IP.
If one uses SSH or VCN to access the remote machine (host2) then load the site/script locally, the host1′s settings will get loaded.

Solution 3

Create a file named "wp-config-local.php" in the same directory as wp-config.php then add the following to wp-config.php

if ( file_exists( dirname( __FILE__ ) . ‘/wp-config-local.php’ ) ) {
# the current host’s settings
} else {
# default settings
}

Every host would then manage it’s own wp-config-local.php without the need to share it though a version control system.

Pros
- privacy, it remains private to the host’s users
- works fine even if the script is called though the command line

Cons
- disk access