NinjaCipher:-*-:ro60

Archive for the ‘tutorials’ Category

Batch converting avi files for xbox

Sunday, April 27th, 2008

So awhile back (when I switched to Vista which had built in windows media center) I started getting into streaming videos from my pc to my xbox over the network so I could watch them on my tv. I did some searching and found that you have to convert everything to wmv first. So since all the files I have were avi files I found this tutorial to help me convert the files without having to pay for some shady converter software. Following that tutorial I got up and running fairly quickly and everything was peachy. Well sorta. My only issue was with this method you can only do one video at a time. So since I have a huge library of episodic anime this quickly became a prob. So I wrote a little add on to the instructions above that allows you to batch convert your avi files to wmv file using vlc player.

First the convert.bat file. Copy this code to a file and name it convert.bat. Put it in the directory where all your avi files are.

"C:\Program Files\VideoLAN\VLC\vlc" -vvv %1 --sout-ffmpeg-qscale 1 :sout=#transcode{vcodec=WMV2,scale=1,acodec=wma,ab=96,channels=2}:duplicate{dst=std{access=file,mux=asf,dst=%1.wmv}} vlc:quit

note
You may have to change this part C:\Program Files\VideoLAN\VLC\vlc to point at the path you installed your alc player if you didn’t go with the default install location.

Next the the bulk-convert script. Save the following code into a file and name it bulk-convert.bat. Put this script in the same directory as you convert.bat and all your avi files.

lfnfor off
for %%x in (*.avi) do call convert.bat %%x

From there all you have to do is click on the bulk-convert.bat file and it will cycle through all the avi files in the directory and feed them into your convert.bat file.

Enjoy :)

Django Render To Response Hack

Saturday, December 29th, 2007

I was working on perva.de and I needed to add a cookie to the response. Now thats not really a tough thing to do but it has one unfortunate side effect. Basically it makes you have to use the long handed method for rendering the template instead of being able to use the more concise render_to_response shortcut. Reason being that the render_to_response shortcut creates a HttpResponse object for you and when you create a cookie you already have a HttpResponse object thats holding your cookie. So I wrote this simple function that lets you pass in your own pre initialized HttpResponse object instead.

def render_response(*args, **kwargs):
        response = kwargs.pop('response', None)
        if response == None:
            from django.shortcuts import render_to_response
            return render_to_response(*args, **kwargs)
        else:
            from django.template import loader
            response.content = loader.render_to_string(*args, **kwargs)
            return response

You call it the same way as the normal render_to_response except it has an optional param that lets you pass in your pre initialized HttpResponse object.

return render_response('index.html',{'param1': 'param1value'},context_instance=RequestContext(request),response=my_response)

If you pass None as the first param the normal render_to_response is called. The context_instance and the params dict are both optional. You can read about how the normal render_to_response works here.

Now for the disclaimer…

I could be completely missing something simple that already allows you to do this but I didn’t see it. It seems like a very common prob and the folks at the Django project are sick python masters so it wouldn’t surprise me if they already though this through. So if that is the case please leave me a comment and/or call me names and enlighten me to the folly of my ways. I won’t hate you… much ;)

EDIT: I refactored the way the request arg was passed to make it more python like and cleaner. Now you pass it as a kwargs key val pair.

Django Pagination Wrapper

Thursday, December 27th, 2007

For my current project perva.de, I’ve been playing with Django’s core pagination class django.core.paginator.ObjectPaginator. I wrote this wrapper that adds some nice functions that are helpful for rendering. Drop me some comments if you have ideas on how it could be better or “hey ro60 your an idiot you should do this instead” is always welcome too. ;)

Please to enjoy… yes?!

"""
    This object inherits from the Django core ObjectPaginator class and
    provides some aditional helpful calculations for rendering pagination links
"""
from django.core.paginator import ObjectPaginator, InvalidPage
class NFPaginator(ObjectPaginator):

    def _set_current_page(self, current_page):
        try:
            self._current_page = int(current_page)
        except:
            self._current_page = 0

    def _get_current_page(self):
        return self._current_page

    def _get_display_page(self):
        if self._current_page == 0:
            return 1
        else:
            return self._current_page

    def _get_next_page(self):
        try:
            if ObjectPaginator.has_next_page(self,self._current_page):
                return self._current_page + 1
            else:
                return -1
        except:
            NFLogger.message(sys.exc_info(),"exception")

    def _get_previous_page(self):
        try:
            if ObjectPaginator.has_previous_page(self,self._current_page):
                return self._current_page - 1
            else:
                return -1
        except:
            NFLogger.message(sys.exc_info(),"exception")

    def get_page(self, page_number):
        #if the page is invalid then we get the first page
        try:
            return ObjectPaginator.get_page(self,page_number)
        except InvalidPage:
            self._current_page = 0
            return ObjectPaginator.get_page(self,self._current_pager)

    def render_next(self):
        return ObjectPaginator.has_next_page(self,self._current_page)

    def render_previous(self):
        return ObjectPaginator.has_previous_page(self,self._current_page)

    display_page = property(_get_display_page)
    current_page = property(_get_current_page,_set_current_page)
    next_page = property(_get_next_page)
    previous_page = property(_get_previous_page)

Then in your view

from pervade.netflippers import NFPaginator
def index(request):
    if 'page' in request.GET:
        page = request.GET['page']
    else:
        page = 0

    paginator = NFPaginator(Bookmark.objects.all().order_by(’-created_at’), 2,0)

    paginator.current_page = page
    latest_bookmark_list = paginator.get_page(page)
    return render_to_response(’bookmarks/index.html’, {’latest_bookmark_list’: latest_bookmark_list, ‘paginator’:paginator}, context_instance=RequestContext(request))

This all makes rendering a template allot simpler. Here is a link to a template partial that you can use.

P.S. There are calls to my logger class in here as well. Feel free to rip them out if you wish OR better yet include the logger as well.


Thx to Timmah for the comments. I’ve edited the get_page method to fix the blind page display issue.

Handy Django Logger

Sunday, December 23rd, 2007

Here is a handy little logger I wrote for Django. Feel free to use it if you want and to give me your thoughts on improvements. It was my first stab so be gentle. ;)

Big thx to… http://www.linuxjournal.com/article/5821 for exception formatting code…

netflippers.py

from django.conf import settings
import logging
import sys
import traceback

class NFLogger():

    """
        The only requirement for this logger is that you have LOG_FILE
        set in your settings.py
    """
    def __init__(self):
        logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename=settings.LOG_FILE)

    """
        Static method that will call any of our members based on a string name
        for example: NFLogger.message(sys.exc_info(),"exception")
    """
    @staticmethod
    def message(message,methodname='debug'):
        logger = NFLogger()
        if hasattr(logger, methodname):
            _member = getattr(logger, methodname)
            _member(message)
        else:
            logger.debug(message)

    def info(self,message):
        logging.info(message)

    def error(self,message):
        logging.error(message)

    def warn(self,message):
        logging.warn(message)

    def critical(self,message):
        logging.critical(message)

    def debug(self,message):
        logging.debug(message)

    """
        This will output formatted info about the current exception.
        Just pass sys.exc_info() from inside your except block
    """
    def exception(self,sys_exc_info):
         cla, exc, trbk = sys_exc_info
         excName = cla.__name__
         try:
             excArgs = exc.__dict__["args"]
         except KeyError:
             excArgs = “”
         excTb = traceback.format_tb(trbk)
         logging.error(”nException Name: %snException Arguments: %snException Traceback: %sn”,excName, excArgs, excTb)

Just stick this in your Django app and set the path to your desired log file in your settings.py and you should be good to go.

In settings.py

LOG_FILE = '/tmp/pervade.log'

In your code

from pervade.netflippers import NFLogger
NFLogger.message("hi there")

or

NFLogger.message("hi there","info")

Or in an except block:


import sys

try:
    somecode.thaterrorsout
except:
    NFLogger.message(sys.exc_info(),"exception")