July 29, 2010

Conditional context processor for authenticated users

Recently I needed a context processor to display friends of my logged user. Userprofile is the name for extended user model. Here's the code :

def friends_list(request):
    try:
        user = request.user
    except User.DoesNotExist:
        user = AnonymousUser()
    
    userprofile = None
    try:
        userprofile = UserProfile.objects.get(user=request.user)
    except UserProfile.DoesNotExist:
        pass
    if userprofile:
        friends = Friend.objects.filter(friend_of=userprofile)
    else:
        friends = {}
    return {'friends': friends}

July 28, 2010

Python's lambda

Because I don't quite get what and when python's lambda function's can be of any use - I did some research. Then I've found this sleek way of calling one lined function with unnamed parameter :
>>> (lambda x: x*2)(3)
6
Pretty cool.

July 27, 2010

Scroll to top - the new way

Thing you will find useful at some point - how to scroll from random part of page to the top ? Here's a way how to obtain it with jQuery :

$(document).ready(function(){
  $('a[href=#]').click(function(){
    $.scrollTo(0,'slow');
    return false;
  });
});

But remember to include jQuery ScrollTo plugin in your imports. Now every link with hash as target will scroll your page back to the top with nice jquerish effect. Cooll huh ?

July 2, 2010

Random sort of array elements

Recently I came across problem of sorting randomly elements of some array. Here's what I came up with :
Pseudocode :

for each element in the array
calculate a random number with index range from 0 to array size -1
store the current element in a temporary variable
replace the current element in the array with the element at the random index
replace the element at random index with the element at temporary variable

Solution :
        int[] buttons = new int[16];

        for(int i=0; i<16; i++){
            buttons[i] = i;
        }

        int rand;
        int temp;
        Random random;

        random = new Random(System.currentTimeMillis());
        for (int i = 0; i < buttons.length; i++) {
            rand = (random.nextInt() & 0x7FFFFFFF) % buttons.length;
            temp = buttons[i];
            buttons[i] = buttons[rand];
            buttons[rand] = temp;
        }
stat4u