<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>NinjaCipher &#187; tutorials</title>
	<atom:link href="http://www.ninjacipher.com/category/development/tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.ninjacipher.com</link>
	<description>kungpow programming</description>
	<lastBuildDate>Thu, 25 Mar 2010 14:39:12 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='www.ninjacipher.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
		<item>
		<title>Batch converting avi files for xbox</title>
		<link>http://www.ninjacipher.com/2008/04/27/batch-converting-avi-files-for-xbox/</link>
		<comments>http://www.ninjacipher.com/2008/04/27/batch-converting-avi-files-for-xbox/#comments</comments>
		<pubDate>Sun, 27 Apr 2008 16:33:15 +0000</pubDate>
		<dc:creator>mattd</dc:creator>
				<category><![CDATA[tutorials]]></category>
		<category><![CDATA[video]]></category>
		<category><![CDATA[xbox]]></category>

		<guid isPermaLink="false">http://www.ninjacipher.com/2008/04/27/batch-converting-avi-files-for-xbox/</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 <a href="http://www.joystiq.com/2006/11/07/how-to-transcode-and-stream-videos-on-xbox-360/" target="_blank">this tutorial</a> 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.</p>
<p>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.</p>
<pre>
"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</pre>
<p><em>note</em><br />
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&#8217;t go with the default install location.</p>
<p>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.</p>
<pre>
lfnfor off
for %%x in (*.avi) do call convert.bat %%x</pre>
<p>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.</p>
<p>Enjoy <img src='http://www.ninjacipher.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.ninjacipher.com/2008/04/27/batch-converting-avi-files-for-xbox/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Django Render To Response Hack</title>
		<link>http://www.ninjacipher.com/2007/12/29/django-render-to-response-hack/</link>
		<comments>http://www.ninjacipher.com/2007/12/29/django-render-to-response-hack/#comments</comments>
		<pubDate>Sat, 29 Dec 2007 05:48:28 +0000</pubDate>
		<dc:creator>mattd</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://www.ninjacipher.com/2007/12/29/django-render-to-response-hack/</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>I was working on <a href="http://perva.de" target="pervade">perva.de</a> 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.</p>
<pre>
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</pre>
<p>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.</p>
<pre>
return render_response('index.html',{'param1': 'param1value'},context_instance=RequestContext(request),response=my_response)</pre>
<p>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 <a href="http://www.djangoproject.com/documentation/shortcuts/" target="django">here</a>.</p>
<p>Now for the disclaimer&#8230;</p>
<p>I could be completely missing something simple that already allows you to do this but I didn&#8217;t see it. It seems like a very common prob and the folks at the Django project are sick python masters so it wouldn&#8217;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&#8217;t hate you&#8230; much <img src='http://www.ninjacipher.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p><em>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. </em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ninjacipher.com/2007/12/29/django-render-to-response-hack/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Django Pagination Wrapper</title>
		<link>http://www.ninjacipher.com/2007/12/27/django-pagination-wrapper/</link>
		<comments>http://www.ninjacipher.com/2007/12/27/django-pagination-wrapper/#comments</comments>
		<pubDate>Thu, 27 Dec 2007 18:04:37 +0000</pubDate>
		<dc:creator>mattd</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://www.ninjacipher.com/2007/12/27/django-pagination-wrapper/</guid>
		<description><![CDATA[edit:
This example is no longer appropriate for current versions of Django. Most of the features the wrapper provides are now part of the core pagination classes. Please see my newer post about the topic (with example). 

For my current project perva.de, I&#8217;ve been playing with Django&#8217;s core pagination class django.core.paginator.ObjectPaginator. I wrote this wrapper that [...]]]></description>
			<content:encoded><![CDATA[<p><span style="color: #808080;"><strong><em>edit:</em><br />
This example is no longer appropriate for current versions of Django. Most of the features the wrapper provides are now part of the core pagination classes. Please see my <a title="new example" href="http://www.ninjacipher.com/2008/08/04/new-django-paginator-example/" target="_self">newer post </a>about the topic (with example). </strong></span></p>
<p>
For my current project <a href="http://perva.de" target="pervade">perva.de</a>, I&#8217;ve been playing with <a href="http://www.djangoproject.com/documentation/models/pagination/" target="django-site">Django&#8217;s core pagination class</a> 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 &#8220;hey ro60 your an idiot you should do this instead&#8221; is always welcome too. <img src='http://www.ninjacipher.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Please to enjoy&#8230; yes?!</p>
<pre>"""
    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)</pre>
<p>Then in your view</p>
<pre>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))</pre>
<p>This all makes rendering a template allot simpler. <a href="http://www.ninjacipher.com/wp-content/uploads/2007/12/example-pagination-footer.txt" target="example">Here is a link to a template partial that you can use</a>.</p>
<p>P.S. There are <a href="http://www.ninjacipher.com/2007/12/23/handy-django-logger/" target="logger">calls to my logger class</a> in here as well. Feel free to rip them out if you wish OR better yet include the logger as well.</p>
<p><em><br />
Thx to Timmah for the comments. I&#8217;ve edited the get_page method to fix the blind page display issue.<br />
</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ninjacipher.com/2007/12/27/django-pagination-wrapper/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Handy Django Logger</title>
		<link>http://www.ninjacipher.com/2007/12/23/handy-django-logger/</link>
		<comments>http://www.ninjacipher.com/2007/12/23/handy-django-logger/#comments</comments>
		<pubDate>Sun, 23 Dec 2007 07:05:30 +0000</pubDate>
		<dc:creator>mattd</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://www.ninjacipher.com/2007/12/23/handy-django-logger/</guid>
		<description><![CDATA[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&#8230; http://www.linuxjournal.com/article/5821 for exception formatting code&#8230;
netflippers.py

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

class NFLogger():

    """
  [...]]]></description>
			<content:encoded><![CDATA[<p>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. <img src='http://www.ninjacipher.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Big thx to&#8230; http://www.linuxjournal.com/article/5821 for exception formatting code&#8230;</p>
<p>netflippers.py</p>
<pre>
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 = "<no>"
         excTb = traceback.format_tb(trbk)
         logging.error("nException Name: %snException Arguments: %snException Traceback: %sn",excName, excArgs, excTb)
</no></pre>
<p>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.</p>
<p>In settings.py</p>
<pre>
LOG_FILE = '/tmp/pervade.log'</pre>
<p>In your code</p>
<pre>
from pervade.netflippers import NFLogger
NFLogger.message("hi there")

or

NFLogger.message("hi there","info")</pre>
<p>Or in an except block:</p>
<pre>

import sys

try:
    somecode.thaterrorsout
except:
    NFLogger.message(sys.exc_info(),"exception")</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.ninjacipher.com/2007/12/23/handy-django-logger/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>smarty ternary modifier plug-in</title>
		<link>http://www.ninjacipher.com/2007/11/24/smarty-ternary-modifier/</link>
		<comments>http://www.ninjacipher.com/2007/11/24/smarty-ternary-modifier/#comments</comments>
		<pubDate>Sun, 25 Nov 2007 06:06:04 +0000</pubDate>
		<dc:creator>mattd</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://www.ninjacipher.com/2007/11/24/smarty-ternary-modifier/</guid>
		<description><![CDATA[Here is a modifier plug-in that I wrote for smarty that does a simple ternary operation. I would have thought that they would have this built in but from my searches it doesn&#8217;t seem to be the case.

function smarty_modifier_ternary($value,$option1,$option2)
{
    return ($value)?$option1:$option2;
}
You can use it like so&#8230;

{$post.is_draft&#124;ternary:'draft':'published'}
If you don&#8217;t know how to use [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a modifier plug-in that I wrote for smarty that does a simple ternary operation. I would have thought that they would have this built in but from my searches it doesn&#8217;t seem to be the case.</p>
<pre>
function smarty_modifier_ternary($value,$option1,$option2)
{
    return ($value)?$option1:$option2;
}</pre>
<p>You can use it like so&#8230;</p>
<pre>
{$post.is_draft|ternary:'draft':'published'}</pre>
<p>If you don&#8217;t know how to use smarty plug-ins then you can <a href="http://smarty.php.net/manual/en/plugins.php" target="new">read up here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ninjacipher.com/2007/11/24/smarty-ternary-modifier/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>autoCreated ajax ext dialog</title>
		<link>http://www.ninjacipher.com/2007/08/12/autocreated-ajax-ext-dialog/</link>
		<comments>http://www.ninjacipher.com/2007/08/12/autocreated-ajax-ext-dialog/#comments</comments>
		<pubDate>Mon, 13 Aug 2007 05:17:06 +0000</pubDate>
		<dc:creator>mattd</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://www.ninjacipher.com/?p=27</guid>
		<description><![CDATA[Here is a tidbit that will autoCreate an ExtJs BasicDialog populated by a partial returned from an AJAX call to a rails controller action. 
In your js

function loadDialog(){
    var cb = {
      success: showDialog,
      failure: displayError
    };
   [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a tidbit that will autoCreate an ExtJs BasicDialog populated by a partial returned from an AJAX call to a rails controller action. </p>
<h3>In your js</h3>
<pre>
function loadDialog(){
    var cb = {
      success: showDialog,
      failure: displayError
    };
    Ext.lib.Ajax.formRequest( 'merge_form', '/controller/get_dialog' , cb , null, false, null);
}
function showDialog(response){
   var dlg = new Ext.BasicDialog("example_dialog",{
		        height: 200,
		        width: 300,
		        resizeable: false,
			autoCreate: true,
		        modal: true,
		        draggable:false,
			collapsible:false,
		        shadow: true,
			title:'Hola'
		    });

		    dlg.addKeyListener(27, dlg.hide, dlg);
		    dlg.addButton('Yes', dlg.hide, dlg);
		    dlg.addButton('No', dlg.hide, dlg);
		    dlg.body.dom.innerHTML = response.responseText;
		    dlg.show();
		}
function displayError(response){
   if(response.responseText == null){
	 Ext.MessageBox.alert("Woops!","The requested operation failed.");
   }else{
	Ext.MessageBox.alert("Woops!",response.responseText);
   }
}
</pre>
<h3>In your controller</h3>
<pre>
  def get_dialog
    @msg = "hello world"
    render :partial=>"/dialogs/content"
  end
</pre>
<h3>In your partial</h3>
<pre>
  <%= @msg %>
</pre>
<h3>In your view</h3>
<pre>
&lt;input type="button" onClick="loadDialog();" value="show dialog" /&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.ninjacipher.com/2007/08/12/autocreated-ajax-ext-dialog/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
