Latest 100 public snipts »
pkarl's
snipts
showing 1-20 of 50 snipts
-
∞ unicode to HTML entity conversion for python
import cgi cgi.escape(posts).encode('ascii', 'xmlcharrefreplace')
-
∞ 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>
-
∞ 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>
-
∞ 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
-
∞ Google-hosted jQuery
<script src="http://www.google.com/jsapi"></script> <script> // Load jQuery google.load("jquery", "1"); </script>
-
∞ See which modules are loaded in Apache (on OSX)
/usr/sbin/apachectl -l
-
∞ 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; }
-
∞ 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
-
∞ Perform a packet dump for your Mac airport express card
$ sudo tcpdump -i en1 -vvv -n -s 0 -w ~/Desktop/DumpFile.dmp -
∞ 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 } ?>
-
∞ 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/
-
∞ PHP Find & Replace, to fix unquoted array indexes [key] => ['key']
regex: (\[)[a-zA-Z0-9\-]*(\]) replace: ['$2']
-
∞ 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)
-
∞ 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
-
∞ Iterate over a dict in a Django template
{% for key,value in dictionary.items %}{{ value }}{% endfor %}
-
∞ 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()
-
∞ 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 -
∞ Globally ignore .pyc files
nano ~/.subversion/config global-ignores = *.pyc ctrl-x-z -
∞ Apache2 permanent redirect to external URL
## APACHE2: permanently redirect local link to external URL Redirect 301 /blog/rss http://feeds2.feedburner.com/petekarl -
∞ 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; } ... }


