IMPORTANT!

Snipt is going open source. We've toyed with this idea for quite a while, and have finally decided it's the right way to move forward.

A few things:
  • The entire Snipt source code will be released on GitHub under the 3-clause BSD License on Friday, September 10th.
  • While we'd like to think we're perfect, we realize we're only human. By open sourcing the software that runs this website, certain bugs or security flaws may be discovered that could compromise the privacy of your snipts.
  • Only the Lion Burger team will be able to push commits to the Snipt.net site. Contributors should send a pull request to add new features or submit patches.
  • By using this site, you agree not to be too angry or take any legal action against Lion Burger should this whole thing go up in flames some day.
  • Follow us on Twitter for updates.
I agree, close this message
Sign up to create your own snipts, or login.

Latest 100 public snipts » pkarl's snipts The latest snipts from pkarl.

showing 1-20 of 50 snipts
  • unicode to HTML entity conversion for python
    import cgi
    cgi.escape(posts).encode('ascii', 'xmlcharrefreplace')
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Aug 09, 2010 at 2:20 p.m. EDT
  • basic HTML template for bill
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html lang="en">
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    	<title>untitled</title>
    </head>
    <body>
    
    </body>
    </html>
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Jul 10, 2010 at 5:09 p.m. EDT
  • sample HTML for Bill
    <html>
    	<head>
    		<title>I'm a title!</title>
    	</head>
    	<body>
    		<h1>Features of a cat</h1>
    		<p>This is a paragraph of information, and I'm going to say so if I need to say a lot at once, I can.</p>
    		<p>This is a paragraph of information, and I'm going to say so if I need to say a lot at once, I can.</p>
    		
    		<h2>The Tail</h2>
    		<p>This is a paragraph of information, and I'm going to say so if I need to say a lot at once, I can.</p>
    		
    		<h2>The Whiskers</h2>
    		<p>This is a paragraph of information, and I'm going to say so if I need to say a lot at once, I can.</p>
    		<p>This is a paragraph of information, and I'm going to say so if I need to say a lot at once, I can.</p>
    		
    		<h2>The Face</h2>
    		<p>This is a paragraph of information, and I'm going to say so if I need to say a lot at once, I can.</p>
    		<p>This is a paragraph of information, and I'm going to say so if I need to say a lot at once, I can.</p>
    		<p>This is a paragraph of information, and I'm going to say so if I need to say a lot at once, I can.</p>
    		
    		<h2>The Fur</h2>
    		<p>This is a paragraph of information, and I'm going to say so if I need to say a lot at once, I can.</p>
    		<p>This is a paragraph of information, and I'm going to say so if I need to say a lot at once, I can.</p>
    	</body>
    </html>
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Jul 10, 2010 at 4:10 p.m. EDT
  • URL-encode string for Django slug
    # coding=utf-8
    import re
    
    # expanded for readability
    
    u = u'Pelé is Here TO ståy: how do \' do math!'
    
    u = u.lower()
    u.encode('ascii', 'ignore')
    
    p = re.compile('[^a-z\-\s]', re.IGNORECASE)
    u = p.sub('', u)
    
    p = re.compile('(\s+)')
    u = p.sub('-', u)
    
    print u
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Jun 04, 2010 at 10:16 a.m. EDT
  • Google-hosted jQuery
    <script src="http://www.google.com/jsapi"></script>
    <script>
      // Load jQuery
      google.load("jquery", "1");
    </script>
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Apr 05, 2010 at 2:56 p.m. EDT
  • See which modules are loaded in Apache (on OSX)
    /usr/sbin/apachectl -l
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Dec 15, 2009 at 10:26 a.m. EST
  • afeedapart.com CSS
    /* Eric Meyer's CSS reset (http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded) */
    html, body, div, span, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, code, del, em, img, strong, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0; font-weight: inherit; font-style: inherit; font-size: 100%; font-family: inherit; vertical-align: baseline; }
    body { line-height: 1; color: black; background: white; }
    ol, ul { list-style: none; }
    table { border-collapse: separate; border-spacing: 0; }
    caption, th, td { text-align: left; font-weight: normal; }
    blockquote:before, blockquote:after, q:before, q:after { content: ""; }
    blockquote, q { quotes: "" ""; }
    
    /* Clearfix (http://www.positioniseverything.net/easyclearing.html) */
    .group:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
    .group { display: inline-block; }
    /* \*/
    * html .group {height: 1%; }
    .group { display: block; }
    /* */
    
    .promo {
        color: #333333;
        font: 46px Georgia, Serif;
        line-height: 55px;
        margin: 100px auto;
        text-align: center;
    }
    .promo h1 { margin-left: -70px; }
    .promo h2 { font-size: 28px; font-style: italic; color: #888; margin-left: 100px; margin-top: -15px;}
    .promo a { border-bottom: 1px dashed #999999; color: #999999; text-decoration: none; }
    .promo a:hover { border-bottom: 1px solid #333333; color: #333333; text-decoration: none; }
    .promo .sub { font-size: 16px; margin-top: 20px; padding: 50px 50px 0; line-height: 26px;}
    .promo .sub span { margin: 0 10px; white-space: nowrap; }
    .promo .afa-link { font-size: 72px; display: block; margin: 40px 20px; padding-bottom: 20px; border-bottom: 5px dashed #999999; text-decoration: none;}
    .promo .afa-link:hover { text-decoration: none !important; border-bottom: 5px dashed #333; }
    
    /* Generic */
    .left {float: left;}
    .right {float: right;}
    .disabled {display: none;}
    em {font-style: italic;}
    strong {font-weight: bold;}
    
    body a {color: #999999; text-decoration: none; border-bottom: 1px dashed;}
    body a:hover {color: #333333; border-bottom: 1px solid;}
    
    /* Structure */
    body {background-color: #F9F8F3; color: #333333; font: 18px "Georgia", Serif;}
    #frame {margin: 0 auto; width: 910px;}
    
    /* Header */
    #header {padding: 20px 15px; }
    #header h1 {font-size: 46px;}
    #header h1 a {border: 0; color: #333333; text-decoration: none;}
    #header h1 a:hover {color: #999999;}
        #subtitle {color: #999999; font-size: 18px; font-style: italic; margin-top: -3px; }
        #countdown-container { color: #5AAEF1; margin-top: -5px; font-size: 12px;}
        #activity-indicator { padding-right: 5px; }
        #retweet-control, #links-control { margin-top: -1px; font-size: 12px; margin-left: 1em; }
    
    /* Nav */
    #nav, #feed {float: left;}
    #nav li.nav a {
        border-bottom: 0;
        color: #999999;
        display: block;
        font-size: 26px;
        padding: 15px 0 15px 25px;
        text-decoration: none;
        -moz-border-radius-bottomleft: 10px;
        -webkit-border-bottom-left-radius: 10px;
        -moz-border-radius-topleft: 10px;
        -webkit-border-top-left-radius: 10px;
    }
    #nav li.nav a:hover {background-color: #EBE8DB; border-bottom: 0;}
    #nav li.nav a.active {background: #D1CCBC url('/media/images/arrow.gif') center right no-repeat; color: #333333;}
    
    .dev-message {
        font-style: normal !important;
        color: #666;
    }
    .dev-message em {
        color: #222;
    }
    
    /* Footer */
    #footer {color: #999999; font-size: 14px; font-style: italic; line-height: 1.6em; padding: 25px; width: 174px;}
    
    /* Feed */
    #feed {
        background-color: #EBE8DB;
        min-height: 400px;
        padding: 25px 10px;
        padding-top: 10px;
        width: 665px;
        -moz-border-radius-bottomleft: 10px;
        -webkit-border-bottom-left-radius: 10px;
        -moz-border-radius-topright: 10px;
        -webkit-border-top-right-radius: 10px;
        -moz-border-radius-bottomright: 10px;
        -webkit-border-bottom-right-radius: 10px;
    }
    #feed ul {margin: 0;}
    #feed li {border-top: 1px dotted #D1CBBB; margin: 0; padding: 10px; -moz-border-radius: 5px; border-radius: 5px; -webkit-border-radius: 5px;}
    #feed li:first-child {border-top: 0;}
    #feed li:last-child {margin-bottom: 0;}
    #feed li.new {background-color: #CDEAC9;}
    #feed li.retweet {background-color: #dcd9cd;}
    #feed .tweet-text, .photos {font-size:14px; float: left; line-height: 1.3em; margin-left: 15px; width: 572px;}
    #feed .profile-image {
        border-bottom: 0;
        display: block;
        float: left;
        height: 48px;
        margin-top: 5px;
        position: relative;
        width: 48px;
        -moz-background-size: 48px 48px;
        -moz-border-radius: 5px;
        -webkit-background-size: 48px 48px;
        -webkit-border-radius: 5px;
    }
    #feed li.retweet {
        display: none;
    }
    .posted {font-size: 12px; line-height: normal; margin-top: 7px; color: #666;}
    
    
    /* Sessions */
    .sessions-title, .sessions-subtitle {background-color: #5AAEF1; border-radius: 5px; font-size: 26px; font-style: italic; padding: 15px; -moz-border-radius: 5px; -webkit-border-radius: 5px; margin-bottom: 3px; line-height: 1.3em;}
    .sessions-title a {color: #333;}
    .sessions-subtitle {background-color: #D1CBBB; font-size: 16px; margin-bottom: 10px;}
    .sessions li {padding: 0 !important;}
    .sessions li:last-child {margin-bottom: 10px !important;}
    .sessions li a {
        border-bottom: 0;
        border-radius: 5px;
        color: #333333;
        display: block;
        margin: 0;
        padding: 15px;
        -moz-border-radius: 5px;
        -webkit-border-radius: 5px;
        }
    .sessions li a:hover {background-color: #D2CCBC;}
    .sessions li a span.time {color: #999999; display: block; margin-left: 10px; margin-top: -2px;}
    .sessions li a span.counts {color: #999999; display: block; margin-top: 5px;}
    .sessions li.dimmed { opacity: .30; -ms-filter: "alpha(opacity=30)"; }
    .conference-title:hover { background-color: #4483B6 !important; color: #FFF; }
    
    .new-tweet { background-color: #fbf6d7; }
    .speaker-tag { padding: 0 0 0 10px; margin-bottom: -3px; }
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Dec 08, 2009 at 3:07 p.m. EST
  • Retrieve Django objects grouped by first letter of an attribute
    """
    ex:
      authors_by_letter = fetch_objects_by_letter(Author, 'name')
    
    returns:
      {u'A': [<Author: Ayn Rand>], u'J': [<Author: Jessica Simpson>], u'L': [<Author: Lord Voldemort>], u'T': [<Author: Trey Parker>]}
    
    """
    def fetch_objects_by_letter(model, attr):
    	qs = model.objects.all().order_by(attr)
    	
    	objs_by_letter = dict()
    	for obj in qs:
    		try:
    			tmp = objs_by_letter[obj.__dict__[attr][0]]
    		except KeyError:
    			objs_by_letter[obj.__dict__[attr][0]] = list()
    			
    		objs_by_letter[obj.__dict__[attr][0]].append(obj)
    		
    	return objs_by_letter
    

    copy | embed

    2 comments - tagged in  posted by pkarl on Nov 05, 2009 at 1:15 p.m. EST
  • Perform a packet dump for your Mac airport express card
    $ sudo tcpdump -i en1 -vvv -n -s 0 -w ~/Desktop/DumpFile.dmp
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Sep 30, 2009 at 3:53 p.m. EDT
  • PHP/HTML Date & Time picker
    <?php function drawDateTimePicker() { ?>
    	<select name="month">
    		<?php for($x=1;$x<=12;$x++) { ?>
    			<option value="<?= $x ?>"<?= (date("n") == $x ? ' selected="selected"' : '') ?>><?= date('F', mktime(0,0,0,$x)) ?></option>	
    		<?php } ?>
    	</select>
    	<select name="day">
    		<?php for($x=1;$x<=31;$x++) { ?>
    			<option value="<?= $x ?>"<?= (date("j") == $x ? ' selected="selected"' : '') ?>><?= $x ?></option>	
    		<?php } ?>
    	</select>
    	<select name="year">
    		<?php for($x=2009;$x<=2015;$x++) { ?>
    			<option value="<?= $x ?>"<?= (date("Y") == $x ? ' selected="selected"' : '') ?>><?= $x ?></option>	
    		<?php } ?>		
    	</select> / 
    	<select name="hour">
    		<?php for($x=1;$x<=12;$x++) { ?>
    			<option value="<?= $x ?>"<?= (date("H") == $x ? ' selected="selected"' : '') ?>><?= $x ?></option>	
    		<?php } ?>
    	</select>	
    	<select name="minute">
    		<option value="00">00</option>
    		<option value="15">15</option>
    		<option value="30">30</option>
    		<option value="45">45</option>
    	</select>
    	<select name="period">
    		<option value="pm">pm</option>
    		<option value="am">am</option>
    	</select>
    <?php } ?>
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Sep 04, 2009 at 8:09 a.m. EDT
  • Create a symbolic link on windows
    C:\mklink /D C:\TestFolder C:\Users\Geek\TestFolder
    
    symbolic link created for C:\TestFolder <<===>> C:\Users\Geek\TestFolder
    
    src: http://www.howtogeek.com/howto/windows-vista/using-symlinks-in-windows-vista/
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Aug 24, 2009 at 1:25 p.m. EDT
  • PHP Find & Replace, to fix unquoted array indexes [key] => ['key']
    regex:
    (\[)[a-zA-Z0-9\-]*(\])
    
    replace:
    ['$2']
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Jul 20, 2009 at 9:36 a.m. EDT
  • combine tweets & photos into a single timeline
    from syncr.flickr.models import Photo
    from syncr.twitter.models import Tweet
    
    import pytz
    
    def get_media_for_session(session):
        """
            Collect Tweets & Photos that were created between the session start & end times
            
            Photos are sorted into batches by their owner, and then receive an index in the update
            timeline that is the datetime of the last photo in the set
            
            accepts session object
            returns updates=list(dicts), # of tweets, # of photos
        """
        updates = list()
    
        tweets = Tweet.objects.filter(created__gte=session.session_start, created__lte=session.session_end)
        for tweet in tweets:
            updates.append({'type':'tweet', 'tweet': tweet, 'datetime':tweet.local_pub_time()})
        
        photoset = list()
        counter = 0
        photos = Photo.objects.filter(taken_date__gte=session.session_start, taken_date__lte=session.session_end).order_by('owner','taken_date')
        for photo in photos:
            # this should be on the photo model as 'get_thumbnail_url'
            photo.thumbnail_url = "http://farm%s.static.flickr.com/%s/%s_%s_s.jpg" % (photo.farm, photo.server, photo.flickr_id, photo.secret)
            photoset.append(photo)
            
            try:                nextOwner = photos_by_owner[counter+1].owner
            except IndexError:  nextOwner = False
            
            if photo.owner != nextOwner:
                date_taken_tmz = photo.taken_date.replace(tzinfo=pytz.utc).astimezone(pytz.timezone(TIME_ZONE))
                updates.append({'type':'photo','photoset': photoset, 'owner': photo.owner,'owner_nsid': photo.owner_nsid, 'count':len(photoset), 'datetime': date_taken_tmz})
                photoset = list()
                
            counter += 1
        
        updates.sort(key=lambda x:x['datetime'])
        
        return updates, len(tweets), len(photos)
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Jun 28, 2009 at 12:08 p.m. EDT
  • Django tip from StackOverflow
    Install Django Command Extensions and pygraphviz and then issue the following command to get a really nice looking Django model visualization:
    
    ./manage.py graph_models -a -g -o my_project.png
    
    See the rest here:
    http://stackoverflow.com/questions/550632/favorite-django-tips-features
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Jun 19, 2009 at 10:40 a.m. EDT
  • Iterate over a dict in a Django template
    {% for key,value in dictionary.items %}{{ value }}{% endfor %}
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Jun 11, 2009 at 8:59 p.m. EDT
  • Generate a list of your bit.ly shortened URLs (ordered by popularity)
    from Cheetah.Template import Template
    import feedparser
    import urllib2
    from BeautifulSoup import MinimalSoup
    from urlparse import urlparse
    from datetime import datetime
    import sys
    
    try: # so we can run this on a CRON w/out losing our minds
        filepath = sys.argv[1]
    except IndexError:
        filepath = ''
    
    def getDomain(url):
        u = urlparse(url)
        url = u.netloc.replace('www.','')
        return url.sub(':[0-9]{2,3,4,5}','')
        
    def getDomainFromShortUrl(link, username, api_key):
        tmp = eval((opener.open('http://api.bit.ly/expand?version=2.0.1&shortUrl=%s&login=%s&apiKey=%s' % (entry.link, username, api_key))).read())
        return getDomain(tmp['results'][bitly_hash]['longUrl'])
        
        
    #TODO - how can we make this dynamic? user/key in URL!?! YOU SHALL NOT PASS!
    username = '[hidden]'
    api_key = '[hidden]'
    opener = urllib2.build_opener()
    
    bitly_user_rss = 'http://bit.ly/user/recent_rss/%s' % username
    feed = feedparser.parse(bitly_user_rss)
    
    links = list()
    for entry in feed.entries:
        bitly_hash = entry.comments[entry.comments.rindex('/')+1:]
        longUrl = ''
        
        if entry.title[:4].lower() == 'http': # weak URL check
            if '403' in entry.title: # bit.ly sometimes gets blocked by sites
                offending_page = opener.open('http://bit.ly/%s' % bitly_hash).read()
                try:    domain = getDomainFromShortUrl(entry.link, username, api_key)
                except  urllib2.HTTPError: pass
            else:
                domain = getDomain(entry.title)
                offending_page = opener.open(entry.title).read()
            
            try: # get the real title
                soup = MinimalSoup(offending_page)
                entry.title = soup.html.head.title.string
            except:
                entry.title = offending_page[offending_page.index('<title>')+7:offending_page.index('</title>')]
                
        else:
            try:    domain = getDomainFromShortUrl(entry.link, username, api_key)
            except  urllib2.HTTPError: pass # if there's a 500 error, then skip
            
        try:
            stats = eval((opener.open('http://api.bit.ly/stats?version=2.0.1&shortUrl=%s&login=%s&apiKey=%s' % (entry.link, username, api_key))).read())
            links.append({'title': entry.title, 'hash': bitly_hash, 'url': entry.link, 'clicks': stats["results"]["userClicks"], 'worldClicks': stats["results"]["clicks"], 'domain': domain })
        except urllib2.HTTPError: # Again, no love for the 500
            pass
            
        print entry.title
        print bitly_hash, entry.link
        print domain
        print
    
    date = (datetime.now()).strftime("%A, %d. %B %Y %I:%M%p")
    
    links.sort(key=lambda x:x['clicks'])
    links.reverse()
    
    t = Template(file=open("%slinks.tmpl" % filepath), searchList=[{'username' : username, 'linklist': links, 'date': date }])
    
    f = open('%sindex.html' % filepath, 'w')
    f.write(str(t))
    f.close()
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Jun 09, 2009 at 3:12 p.m. EDT
  • awk command for printing out a list of unique IP addresses from an apache access_log
    awk '{ip[$1]=0} END {for (address in ip) { print address} }' /home/admin/logs/access_log
    

    copy | embed

    0 comments - tagged in  posted by pkarl on May 30, 2009 at 10:02 p.m. EDT
  • Globally ignore .pyc files
    nano ~/.subversion/config
    global-ignores = *.pyc
    ctrl-x-z
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Apr 20, 2009 at 7:36 p.m. EDT
  • Apache2 permanent redirect to external URL
    ## APACHE2: permanently redirect local link to external URL
    
    Redirect 301 /blog/rss http://feeds2.feedburner.com/petekarl
    

    copy | embed

    0 comments - tagged in  posted by pkarl on Apr 13, 2009 at 3:59 p.m. EDT
  • Nginx permanent (301) redirect to external URL
    ## NGINX: permanently redirect local link to external URL
    
    server {
        listen   80;
        server_name pkarl.com;
    
        location /blog/rss {
          rewrite ^ http://feeds2.feedburner.com/petekarl permanent;
        }
    ...
    }
    

    copy | embed

    1 comment - tagged in  posted by pkarl on Apr 13, 2009 at 3:56 p.m. EDT
Sign up to create your own snipts, or login.