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 » Fotinakis's snipts The latest snipts from Fotinakis.

showing 1-20 of 26 snipts
  • Iptables map port 8080 to privileged port 80
    sudo iptables -t nat -A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080
    sudo iptables -t nat -A OUTPUT -p tcp -m tcp -d $HOST --dport 80 -j REDIRECT --to-ports 8080
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Aug 09, 2010 at 6:02 p.m. EDT
  • AppleScript to save and restore window positions
    #!/usr/bin/osascript
    
    -- Usage:
    -- $ osacompile -o windowPositions.compiled.scpt windowPositions.scpt
    -- $ osascript windowPositions.compiled.scpt --save
    -- $ osascript windowPositions.compiled.scpt --restore
    
    -- Change this to be the list of windows you want to save/restore
    property affectedProcesses : {"Chrome", "Adium", "Eclipse", "Terminal"}
    property windowRecord : {}
    
    on run argv
    	if (count of argv) is equal to 0 then
    		log "Please specify one of --save or --restore."
    		return
    	end if
    	
    	tell application "System Events"
    		if (item 1 of argv is equal to "--save") then
    			set windowRecord to {}
    			repeat with i from 1 to count affectedProcesses
    				set end of windowRecord to {0, {}, {}}
    			end repeat
    			repeat with p from 1 to count affectedProcesses
    				set processName to (item p of affectedProcesses)
    				if exists process processName then
    					log "Process '" & processName & "' exists"
    					tell process processName
    						set numWindows to count windows
    						set item 1 of item p of windowRecord to numWindows
    						repeat with i from 1 to numWindows
    							set end of item 2 of item p of windowRecord to position of window i
    							set end of item 3 of item p of windowRecord to size of window i
    						end repeat
    					end tell
    				end if
    			end repeat
    		else
    			repeat with p from 1 to count affectedProcesses
    				set processName to (item p of affectedProcesses)
    				if exists process processName then
    					log "Process '" & processName & "' exists"
    					tell process processName
    						set numWindows to item 1 of item p of windowRecord
    						repeat with i from 1 to numWindows
    							set position of window i to (item i of item 2 of item p of windowRecord)
    							set size of window i to (item i of item 3 of item p of windowRecord)
    						end repeat
    					end tell
    				end if
    			end repeat
    		end if
    	end tell
    end run
    

    copy | embed

    2 comments - tagged in  posted by Fotinakis on Jun 11, 2010 at 2:23 p.m. EDT
  • Monitor active PostgreSQL queries against a database
    SELECT procpid, current_query, waiting
    FROM   pg_stat_activity
    WHERE  datname = 'your_database_name'
    AND    current_query <> '<IDLE>';
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Mar 29, 2010 at 5:45 p.m. EDT
  • Dynamic Django mod_wsgi hook files
    # --- django.wsgi - in any project
    from some_common_module import wsgi_helper
    application = wsgi_helper.setup(__file__)
    
    
    # --- wsgi_helper.py - in some_common_module
    import os, sys
    import django.core.handlers.wsgi
    
    def setup(filename):
    	project_root = os.sep.join(filename.split(os.sep)[:-2])
    	project_dir = None
    	
    	for path in os.listdir(project_root):
    		# Find each dir off the root, and check it for settings.py
    	
    		path = os.path.join(project_root, path)
    	
    		if os.path.isdir(path):
    			file = "".join([path, os.sep, "settings.py"])
    			if os.path.exists(file):
    				# We have found /project_name/settings.py
    				project_dir = path
    				os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % path.split(os.sep)[-1]
    	
    	if not project_dir:
    		raise Exception("Could not find project settings file! Checked path: %s" % path)
    	
    	if project_root not in sys.path: sys.path.insert(0, project_root)
    	if project_dir not in sys.path: sys.path.insert(0, project_dir)
    
    	return django.core.handlers.wsgi.WSGIHandler()
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Feb 26, 2010 at 6:39 p.m. EST
  • Drop all tables, constraints, and sequences within an Oracle schema
    BEGIN
    
    FOR c IN (SELECT table_name FROM user_tables) LOOP
    EXECUTE IMMEDIATE ('DROP TABLE ' || c.table_name || ' CASCADE CONSTRAINTS');
    END LOOP;
    
    FOR s IN (SELECT sequence_name FROM user_sequences) LOOP
    EXECUTE IMMEDIATE ('DROP SEQUENCE ' || s.sequence_name);
    END LOOP;
    
    END;
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jan 29, 2010 at 5:22 p.m. EST
  • Output PostgreSQL command as CSV
    psql -F\; -A --pset footer -f input_file.sql -o output_file.csv database_name
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Nov 10, 2009 at 4:04 p.m. EST
  • Tokenize a string in C++
    #include <string>
    #include <sstream>
    #include <algorithm>
    #include <iterator>
    #include <vector>
    using namespace std;
    
    int main() {
    	string sentence = "All of this has happened before...";
    	
    	vector<string> tokens;
    	istringstream iss(sentence);
    	copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(tokens));
    }
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Sep 13, 2009 at 7:34 p.m. EDT
  • Quick find a manufacturer's OUI
    grep -i foundry /usr/share/nmap/nmap-mac-prefixes
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Aug 20, 2009 at 11:43 a.m. EDT
  • Mount SSH volume on Mac with sshfs
    # With sshfs installed:
    
    MOUNTPOINT=/Volumes/mountdir
    REMOTE=user@hostname:/home/dir
    OPTIONS=-oping_diskarb,volname=mountdir
    TESTHOST=hostname
    #test if sshfs already mounted
    if ! [ -e $MOUNTPOINT ]
    then
            #test if connected to internet
            if ! [ -z "`ping -c 1 $TESTHOST 2>/dev/null | grep "time="`" ]
            then
                    mkdir $MOUNTPOINT
                    sshfs $REMOTE $MOUNTPOINT $OPTIONS
                    echo "$REMOTE mounted on $MOUNTPOINT"
            else
                    echo "Network down, unable to mount $REMOTE"
            fi
    fi
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Aug 18, 2009 at 6:59 p.m. EDT
  • Change SSH port on OS X
    # Add a service on an unused port in:
    sudo vim /etc/services
    
    # Change the string "ssh" below "SockServiceName" to whatever name used in the above file
    sudo vim /System/Library/LaunchDaemons/ssh.plist
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Aug 18, 2009 at 6:14 p.m. EDT
  • Change Active Directory password via LDAP modify call
    #!/usr/bin/python
    
    import ldap
    
    host = 'ldaps://ldap.example.com:636'
    
    con = ldap.initialize(host)
    con.set_option( ldap.OPT_X_TLS_DEMAND, True )
    con.set_option( ldap.OPT_DEBUG_LEVEL, 255 )
    
    # Encode the password in UTF-16 Little Endian
    #
    # ASCII "new":     0x6E 0x65 0x77
    # UTF-16 "new":    0x6E 0x00 0x65 0x00 0x77 0x00
    # UTF-16 "new"
    #     with quotes: 0x22 0x00 0x6E 0x00 0x65 0x00 0x77 0x00 0x22 0x00
    #
    # http://msdn.microsoft.com/en-us/library/cc200469%28PROT.10%29.aspx
    #
    # NOTE: The article says to BER encode the password octet stream before
    # sending for change, but doing so causes the server to give its standard
    # "will not perform" error on password change. So, no BER encoding is done here.
    username = 'someUser'
    new_pass = 'ne$wP4assw0rd3!'
    new_password = ('"%s"' % new_pass).encode("utf-16-le")
    
    try:
    	con.simple_bind_s( "admin@ldap.example.com", "password" )
    	
    	# For some reason, two MOD_REPLACE calls are necessary to change the password.
    	# If only one call is performed, both the old and new password will work.
    	mod_attrs = [( ldap.MOD_REPLACE, 'unicodePwd', new_password)],( ldap.MOD_REPLACE, 'unicodePwd', new_password)]
    	con.modify_s('CN=%s,OU=Users,DC=ldap,DC=example,DC=com' % username, mod_attrs)
    except:
    	raise
    else:
    	print "Successfully changed password."
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Aug 03, 2009 at 4:56 p.m. EDT
  • Make copy and transfer entire PostgreSQL DB
    pg_dump -d prod_db -U prod_db -h localhost > /tmp/transferdump.sql
    
    psql -U prod_db_user -h localhost -t -d other_db -c "SELECT 'DROP TABLE ' || n.nspname || '.' ||
    c.relname || ' CASCADE;' FROM pg_catalog.pg_class AS c LEFT JOIN
    pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace WHERE relkind =
    'r' AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND
    pg_catalog.pg_table_is_visible(c.oid)" >/tmp/dropothertables.sql;
    
    psql -d other_db -h localhost -U other_db_user < /tmp/dropothertables.sql;
    psql -d other_db -h localhost -U other_db_user < /tmp/transferdump.sql
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jul 28, 2009 at 6:15 p.m. EDT
  • Disassembler for Python bytecode
    $ python -m dis test.py 
      1           0 LOAD_CONST               0 ('Hello world')
                  3 PRINT_ITEM          
                  4 PRINT_NEWLINE       
                  5 LOAD_CONST               1 (None)
                  8 RETURN_VALUE        
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jul 14, 2009 at 1:50 a.m. EDT
  • Bash—please save my history for ever and eternity (or, at least a really long time)
    # In .bashrc or .bash_profile
    export HISTCONTROL=ignoredups:ignorespace
    export HISTSIZE=10000
    export HISTFILESIZE=1000000
    export HISTTIMEFORMAT="%F %T "
    export PROMPT_COMMAND='history -a'
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jul 02, 2009 at 6:33 p.m. EDT
  • Dynamic directories in Django settings.py
    # In settings.py
    PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
    ROOT_DIR = os.path.split(PROJECT_DIR)[0]
    
    
    MEDIA_ROOT = ROOT_DIR + '/static/'
    MEDIA_URL = '/static/'
    
    TEMPLATE_DIRS = (
    	# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    	# Always use forward slashes, even on Windows.
    	# Don't forget to use absolute paths, not relative paths.
    	PROJECT_DIR + '/templates/',
    )
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jun 29, 2009 at 5:51 p.m. EDT
  • Simple generation of random string in Python
    import string
    import random
    
    print "".join(random.sample(string.letters+string.digits, 8))
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jun 18, 2009 at 1:14 p.m. EDT
  • Install VMWare Tools on Debian
    # Make sure you have contrib and non-free in /etc/apt/sources.list
    # Then:
    
    apt-get install module-assistant
    m-a a-i open-vm
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jun 15, 2009 at 1:21 p.m. EDT
  • Change Linux hostname without reboot
    vim /etc/hostname
    vim /etc/hosts
    hostname new-hostname
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on Jun 15, 2009 at 1:18 p.m. EDT
  • Change initial page state based on location.hash
    $(function() {
    	// Hash state determination
    	if (location.hash && location.hash != "") {
    		$('a[href$="'+location.hash+'"]').click();
    	}
    });
    

    copy | embed

    0 comments - tagged in  posted by Fotinakis on May 18, 2009 at 4:25 p.m. EDT
  • Django template tag for dynamic attribute lookups
    import re
    from django import template
    from django.conf import settings
    
    numeric_test = re.compile("^\d+$")
    register = template.Library()
    
    def getattribute(value, arg):
    	"""Gets an attribute of an object dynamically from a string name"""
    	
    	if hasattr(value, str(arg)):
    		return getattr(value, arg)
    	elif hasattr(value, 'has_key') and value.has_key(arg):
    		return value[arg]
    	elif numeric_test.match(str(arg)) and len(value) > int(arg):
    		return value[int(arg)]
    	else:
    		return settings.TEMPLATE_STRING_IF_INVALID
    
    register.filter('getattribute', getattribute)
    
    # Then, in template:
    # {% load getattribute %}
    # {{ object|getattribute:dynamic_string_var }}
    

    copy | embed

    1 comment - tagged in  posted by Fotinakis on May 11, 2009 at 6:32 p.m. EDT
Sign up to create your own snipts, or login.