Public snipts »
pkarl's
snipts
showing 1-20 of 45 snipts
-
∞ 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; } ... }
-
∞ Import Excel CSV into mysql table
LOAD DATA LOCAL INFILE 'file.cvs' INTO TABLE tablename FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' (field1, field2, field3)
-
∞ Check MySQL table size & meta for a specific table
SELECT count(*) TABLES, concat(round(sum(table_rows)/1000000,2),'M') rows, concat(round(sum(data_length)/(1024*1024*1024),2),'G') DATA, concat(round(sum(index_length)/(1024*1024*1024),2),'G') idx, concat(round(sum(data_length+index_length)/(1024*1024*1024),2),'in Gb') total_size, concat(round(sum(data_length+index_length)/(1024*1024),2),'in Mb') total_size, round(sum(index_length)/sum(data_length),2) idxfrac FROM information_schema.TABLES WHERE table_name LIKE "%random_name%";
-
∞ full-text search stopwords list
the of and that for by as be or this then we which with at from under such there other if is it can now an to but upon where these when whether also than after within before because without however therefore between those since into out some abs about accordingly affecting affected again against all almost already although always among any anyone apparently are arise aside away became become becomes been being both briefly came cannot certain certainly could etc does done during each either else ever every following found further gave gets give given giving gone got had hardly has have having here how itself just keep kept kg knowledge largely like made mainly make many mg might ml more most mostly much must nearly necessarily neither next none nor normally not noted obtain obtained often only our put owing particularly past perhaps please poorly possible possibly potentially predominantly present previously primarily probably prompt promptly quickly quite rather readily really recently refs regarding regardless relatively respectively resulted resulting results said same seem seen several shall should show showed shown shows significantly similar similarly slightly so sometime somewhat soon specifically state states strongly substantially successfully sufficiently their theirs them they though through throughout too toward unless until use used usefully usefulness using usually various very was were what while who whose why widely will would yet
-
∞ Sample Sphinx conf for django-sphinx
source editorial_stories { type = mysql sql_host = localhost sql_user = [django mysql user] sql_pass = [django mysql user password] sql_db = [django mysql database] sql_port = 3306 sql_query_pre = sql_query_post = sql_query = SELECT id, title, slug, section_id, tease, body, modified, tags FROM editorial_stories sql_query_info = SELECT * FROM `editorial_stories` WHERE `id` = $id # ForeignKey's sql_attr_uint = section_id # DateField's and DateTimeField's sql_attr_timestamp = modified } index editorial_stories { source = editorial_stories path = /usr/local/sphinx/data/editorial_stories docinfo = extern morphology = none stopwords = /usr/local/sphinx/stopwords.txt min_word_len = 2 charset_type = sbcs min_prefix_len = 0 min_infix_len = 0 } indexer { # memory limit, in bytes, kiloytes (16384K) or megabytes (256M) # optional, default is 32M, max is 2047M, recommended is 256M to 1024M mem_limit = 32M # maximum IO calls per second (for I/O throttling) # optional, default is 0 (unlimited) max_iops = 60 } searchd { # IP address to bind on # optional, default is 0.0.0.0 (ie. listen on all interfaces) # # address = 127.0.0.1 # address = 192.168.0.1 # searchd TCP port number # mandatory, default is 3312 port = 3312 # log file, searchd run info is logged here # optional, default is 'searchd.log' log = /usr/local/sphinx/log/searchd.log # query log file, all search queries are logged here # optional, default is empty (do not log queries) query_log = /usr/local/sphinx/log/query.log # client read timeout, seconds # optional, default is 5 read_timeout = 5 # maximum amount of children to fork (concurrent searches to run) # optional, default is 0 (unlimited) max_children = 30 # PID file, searchd process ID file name # mandatory pid_file = /usr/local/sphinx/log/searchd.pid # max amount of matches the daemon ever keeps in RAM, per-index # WARNING, THERE'S ALSO PER-QUERY LIMIT, SEE SetLimits() API CALL # default is 1000 (just like Google) max_matches = 1000 # seamless rotate, prevents rotate stalls if precaching huge datasets # optional, default is 1 seamless_rotate = 1 # whether to forcibly preopen all indexes on startup # optional, default is 0 (do not preopen) preopen_indexes = 0 # whether to unlink .old index copies on succesful rotation. # optional, default is 1 (do unlink) unlink_old = 1 } # --eof--
-
∞ Find the location of the currently used binary on unix
$ which mysql /usr/bin/mysql



Python in a Nutshell, Second Edition