Latest 100 public snipts »
Fotinakis's
snipts
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 -
∞ 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
-
∞ 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>';
-
∞ 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()
-
∞ 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;
-
∞ Output PostgreSQL command as CSV
psql -F\; -A --pset footer -f input_file.sql -o output_file.csv database_name -
∞ 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)); }
-
∞ Quick find a manufacturer's OUI
grep -i foundry /usr/share/nmap/nmap-mac-prefixes
-
∞ 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
-
∞ 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
-
∞ 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."
-
∞ 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
-
∞ 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
-
∞ 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'
-
∞ 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/', )
-
∞ Simple generation of random string in Python
import string import random print "".join(random.sample(string.letters+string.digits, 8))
-
∞ 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
-
∞ Change Linux hostname without reboot
vim /etc/hostname vim /etc/hosts hostname new-hostname
-
∞ Change initial page state based on location.hash
$(function() { // Hash state determination if (location.hash && location.hash != "") { $('a[href$="'+location.hash+'"]').click(); } });
-
∞ 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 }}


