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 » python The latest public python snipts.

showing 1-20 of 239 snipts for python
  • Generate SECRET_KEY value
    from random import choice
    
    print ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])
    

    copy | embed

    0 comments - tagged in  posted by jonbiddle on Aug 31, 2010 at 2:01 p.m. EDT
  • Sort Python Dictionary by Value
    # Populate test dictionary
    d = {}
    d['d'] = 6;
    d['e'] = 5;
    d['t'] = 4;
    d['r'] = 3;
    d['o'] = 2;
    d['s'] = 1;
    
    # Define comparison function.
    # Args to this function will be
    # dictionary keys.
    byValue = lambda a,b: cmp(d[a], d[b])
    
    # Sort keys by value and walk the dict
    # in the desired sorting order.
    for key in sorted(d.keys(), byValue):
        print key, '=>', d[key]
    

    copy | embed

    0 comments - tagged in  posted by davidev on Aug 31, 2010 at 11:36 a.m. EDT
  • Re-check pass form
    class PasswordCheckForm(forms.Form):
        password = forms.CharField(widget=forms.PasswordInput)
        
        def __init__(self, user, *args, **kwargs):
            self.user = user
            super(PasswordCheckForm, self).__init__(*args, **kwargs)
        
        def clean(self):
            password = self.cleaned_data.get('password')
            if self.user.check_password(password):
                raise forms.ValidationError(_('Password is incorrect.'))
            
            return self.cleaned_data
    
    def recheck_pass(request, template_name='registration/recheck_pass.html',
                     redirect_field_name=REDIRECT_FIELD_NAME,
                     authentication_form=PasswordCheckForm):
        
        redirect_to = request.REQUEST.get(redirect_field_name, '')
        
        if request.method == 'POST':
            form = authentication_form(request.user, request.POST)
            
            if form.is_valid():
                if not redirect_to or ' ' in redirect_to:
                    redirect_to = settings.LOGIN_REDIRECT_URL
                if '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
                    redirect_to = settings.LOGIN_REDIRECT_URL
        else:
            form = authentication_form(request.user)
            
        return render_to_response(template_name, {
            'form': form,
        }, RequestContext(request))
    

    copy | embed

    0 comments - tagged in  posted by TomL on Aug 25, 2010 at 10:51 a.m. EDT
  • Guess The Number v2
    # import random module, to pick a random number
    import random
    
    #import sys to exit the program if user "wins"
    import sys
    
    # pick a random number between 1 -100, convert to string, and save to variable
    magicNumber = str(random.randrange(100) + 1)
    
    # init a variable that will hold the user's input
    userGuess = ""
    
    # set amount of user tries to 0. They only get 10.
    userTries = 0
    
    
    #welcome user
    print "\n******************************\n\
    Welcome! We are going to play \n\n     'Guess That Number'\n\
    ******************************\n"
    
    # Function to make sure input is a number, and positive
    def is_number(userGuess):
        return userGuess.lstrip('-').isdigit() 
    
    
    
    # Function to make sure input is between 1 and 100
    def is_in_range(userGuess):
    
        if int(userGuess) in range(101):
            return True
        else:
            return False
    
    
    
    # Function to increment User Tries
    def inc_user_tries(userTries):
        userTries =+ 1
    
    
    
    # Function to calculate remainder of Tries
    def rem_user_tries(userTries):
        remainingTries = 9 - userTries
        return remainingTries 
    
    
    # Function to give a hint
    def give_hint(userGuess, magicNumber):
        if userGuess > magicNumber:
            return "try a lower number."
        elif userGuess < magicNumber:
            return "try a higher number."
        else:
            pass
    
    
    # Ask the question
    def ask_the_question(userGuess, userTries, magicNumber):
    
        # loop, give the user 10 tries
        while userTries < 9:
    
            # ask the user to pick a number
            userGuess = raw_input("\nPick a whole number between 1 and 100 >>>  ")
        
            # increment the amount of user tries
            inc_user_tries(userTries)
    
    	if is_number(userGuess):
            
                # if user gets the correct number, congratulate them and exit
                if int(userGuess) == int(magicNumber):
                    print "\nYou Win!"
                    raw_input("\nPress 'Enter' to exit")
                    sys.exit()
        
                # if the user enters a valid number within range   
                if is_number(userGuess) == True and is_in_range(userGuess) == True:
            
                    # give the user a hint if they are too low / high
                    hint = give_hint(userGuess, magicNumber)
            
                    #put all this info in a string for the user
                    print "\n%s you have %s tries left." % (give_hint(userGuess, magicNumber), rem_user_tries(userTries))
    
                    # increment number of tries
                    userTries += 1
                    continue
    
                # if the user enters a valid number, but it is out of range 
                if is_number(userGuess) == True and is_in_range(userGuess) != True:
    
                    # give them an error       
                    print "\nERROR! only enter numbers between 1- 100. you have %s tries left" % rem_user_tries(userTries) 
    
                    # increment number of tries
                    userTries += 1
                    continue
        
            #if the user enters something that is not a number
            else:
            
                print "\nERROR! that's either not a number, or it's not a whole number. you have %s tries left" % rem_user_tries(userTries)
    
                # increment number of tries
                userTries += 1
                continue
    
        # Tell the user they used all of their tries, and give them the correct answer.
        print "\nYou are all out of tries. The answer is %s." % magicNumber
        raw_input("\nPress 'Enter' to exit")
        sys.exit()
        
    
    
    # run the program
    ask_the_question(userGuess, userTries, magicNumber)
        
         
    

    copy | embed

    2 comments - tagged in  posted by tomwolber on Aug 16, 2010 at 1:34 p.m. EDT
  • "Guess the number" program
    # import random module, to pick a random number
    import random
    
    #import sys to exit the program if user "wins"
    import sys
    
    # pick a random number between 1 -100, convert to string, and save to variable
    magicNumber = str(random.randrange(101) + 1)
    
    # init a variable that will hold the user's input
    userGuess = ""
    
    # set amount of user tries to 0. They only get 10.
    userTries = 0
    
    
    # Function to make sure input is a number
    def is_number(userGuess):
        try:
    	int(userGuess)        
            return True
    
        except ValueError:
            return False
    
    
    
    # Function to make sure input is between 1 and 100
    def is_in_range(userGuess):
    
        if int(userGuess) in range(101):
            return True
        else:
            return False
    
    
    
    # Function to increment User Tries
    def inc_user_tries(userTries):
        userTries =+ 1
    
    
    
    # Function to calculate remainder of Tries
    def rem_user_tries(userTries):
        remainingTries = 9 - userTries
        return remainingTries 
    
    
    # Function to give a hint
    def give_hint(userGuess, magicNumber):
        if userGuess > magicNumber:
    	return "try a lower number."
        elif userGuess < magicNumber:
    	return "try a higher number."
        else:
    	pass
    
    
    # Ask the question
    def ask_the_question(userGuess, userTries, magicNumber):
    
        # loop, give the user 10 tries
        while userTries < 9:
    
            # ask the user to pick a number
            userGuess = raw_input("\nPick a whole number between 1 and 100 >>>  ")
    	
    	# increment the amount of user tries
    	inc_user_tries(userTries)
    	
    	# if user gets the correct number, congratulate them and exit
    	if int(userGuess) == int(magicNumber):
       	    print "\nYou Win!"
    	    sys.exit()
    	
    	# if the user enters a valid number within range   
    	if is_number(userGuess) == True and is_in_range(userGuess) == True:
    		
    		# give the user a hint if they are too low / high
    	   	hint = give_hint(userGuess, magicNumber)
    		
    		#put all this info in a string for the user
    		print "\n%s you have %s tries left." % (give_hint(userGuess, magicNumber), rem_user_tries(userTries))
    
    		# increment number of tries
    		userTries += 1
    		continue
    
    	# if the user enters a valid number, but it is out of range	
    	if is_number(userGuess) == True and is_in_range(userGuess) != True:
    
    		# give them an error	   
    		print "\nERROR! only enter numbers between 1- 100. you have %s tries left" % rem_user_tries(userTries) 
    
    		# increment number of tries
    		userTries += 1
    		continue
    	
    	#if the user enters something that is not a user
    	else:
    	    
    		print "\nERROR! that's not a number at all. you have %s tries left" % rem_user_tries(userTries)
    
    		# increment number of tries
    		userTries += 1
    		continue
    
        # Tell the user they used all of their tries, and give them the correct answer.
        print "\nYou are all out of tries. The answer is %s." % magicNumber
    	
    
    
    # run the program
    ask_the_question(userGuess, userTries, magicNumber)
    	
         
    

    copy | embed

    1 comment - tagged in  posted by tomwolber on Aug 13, 2010 at 3:25 p.m. EDT
  • Python Fortune Cookie Generator
    # welcome user
    # pick a number
    # relate number to fortune
    # display fortune
    # ask to play again
    
    import random
    
    print "\n\nWelcome!\n"
    
    def getFortune():
    
        fortuneRand = random.randrange(6) + 1
    
        if fortuneRand == 1:
            print "\nThe joyfulness of a man prolongeth his days."
    
        elif fortuneRand == 2:
            print "\nYour everlasting patience will be rewarded sooner or later."
    
        elif fortuneRand == 3:
            print "\nMake two grins grow where there was only a grouch before."
    
        elif fortuneRand == 4:
            print "\nSomething you lost will soon turn up. "
    
        else:
            print "\nYour heart is pure, and your mind clear, and your soul devout."
    
    
    getFortune()
    
    anotherOne = ""
    
    while anotherOne != 'n':
    
        anotherOne = raw_input("\nAnother? Type 'y' or 'n' >>>  ")
    
        if anotherOne == 'y':
            getFortune()
        elif anotherOne == 'n':
    	print "\nThanks. Have a good day"
            raw_input("\n\nPress the enter key to exit.")
        else:
    	print "\nInvalid answer
    

    copy | embed

    0 comments - tagged in  posted by tomwolber on Aug 12, 2010 at 9:32 a.m. EDT
  • 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
  • SimpleHTTPServer on custom port
    import SimpleHTTPServer
    import SocketServer
    
    PORT = 8000
    
    Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    
    httpd = SocketServer.TCPServer(("", PORT), Handler)
    
    print "serving at port", PORT
    httpd.serve_forever()
    

    copy | embed

    0 comments - tagged in  posted by jonbiddle on Jul 22, 2010 at 4:18 p.m. EDT
  • pygtk textview limit information like twitter 140 chars
    #!/usr/bin/env python
    # -*- cofing: utf-8 -*-
    # vim:noet:sw=4:ts=4:ft=vim
    
    '''
    Filename: test.py
    Descrition: Simple textview test with characters counter
    Author: Vladimir kolev
    '''
    
    import gtk
    import gobject
    
    class PyApp:
            def __init__(self):
                    self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
                    self.window.connect("destroy", gtk.main_quit)
                    self.window.set_size_request(250, 150)
                    self.window.set_position(gtk.WIN_POS_CENTER)
                    
                    self.vbox = gtk.VBox()
    
                    self.counter = gtk.Label()
                    self.counter.set_markup("<b>140</b>")
                    self.sw = gtk.ScrolledWindow()
                    
                    self.textview = gtk.TextView()
                    self.textview.set_wrap_mode(gtk.WRAP_WORD_CHAR)
                    self.textbuff = self.textview.get_buffer()
                    self.textbuff.connect('changed', self.on_text_change)
    
                    self.sw.add(self.textview)
    
                    self.vbox.pack_start(self.sw)
                    self.vbox.pack_start(self.counter)
    
                    self.window.add(self.vbox)
    
                    self.window.show_all()
    
            def main(self):
                    """docstring for main"""
                    gtk.main()
    
            def on_text_change(self, buff):
                    count = 140 - buff.get_char_count()
                    if count >= 0:
                            self.counter.set_markup("<b>%s</b>" % (count))
                    else:
                            count = 0 - count
                            self.counter.set_markup("<span foreground=\"#FF0000\"><b>%s</b></span> chars too much!" % count)
    
    if __name__ == "__main__":
            app = PyApp()
            app.main()
    

    copy | embed

    0 comments - tagged in  posted by vkolev on Jul 16, 2010 at 5:39 a.m. EDT
  • pragha multimedia key support v.2
    #!/usr/bin/env python
    """
    Getting the multimedia key events and converting them
    to Pragha commands
    """
    import gobject
    import dbus
    import dbus.service
    import dbus.mainloop.glib
    import os, sys, commands
    
    
    def on_mediakey(comes_from, what):
        """
        gets called when multimedia keys are pressed down.
        """
        if "pragha" in commands.getoutput('ps -A | grep pragha'):
            if what in ['Stop','Play','Next','Previous']:
                if what == 'Stop':
                    os.system('pragha --stop')
                elif what == 'Play':
                    if "Playing" in commands.getoutput('pragha -c'):
                        os.system('pragha --pause')
                    else:
                        os.system('pragha --play')
                elif what == 'Next':
                    os.system('pragha --next')
                elif what == 'Previous':
                    os.system('pragha --prev')
        else:
            print ('Pragha player is not running...')
    
    # set up the glib main loop.
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
    bus_object = bus.get_object('org.gnome.SettingsDaemon',
                                '/org/gnome/SettingsDaemon/MediaKeys')
    
    # this is what gives us the multi media keys.
    dbus_interface='org.gnome.SettingsDaemon.MediaKeys'
    bus_object.GrabMediaPlayerKeys("MyMultimediaThingy", 0,
                                   dbus_interface=dbus_interface)
    
    # connect_to_signal registers our callback function.
    bus_object.connect_to_signal('MediaPlayerKeyPressed',
                                 on_mediakey)
    
    # and we start the main loop.
    if "pragha" in commands.getoutput('ps -A | grep pragha'):
        print "Pragha player is running..."
    else:
        print "Pragha player is not running..."
        print "Exiting!"
        sys.exit(0)
    mainloop = gobject.MainLoop()
    mainloop.run()
    

    copy | embed

    0 comments - tagged in  posted by vkolev on Jun 19, 2010 at 7:43 a.m. EDT
  • download special webpage and print all ed2k links
    #!/usr/bin/env python
    #-*- coding:utf-8 -*-
    
    import urllib2
    import re
    from sys import argv, exit
    def main(url):
        fd = urllib2.urlopen(url)
        data = fd.read()
        fd.close()
        p = re.compile(r'ed2k="(.*|/)"')
        matches = p.findall(data)
        if matches:
            for l in matches:
                print urllib2.unquote(l)
    
    if __name__ == '__main__':
        if len(argv) < 2:
            print 'one argument is necessary'
            exit(2)
        main(argv[1])
    

    copy | embed

    0 comments - tagged in  posted by wgzhao on Jun 18, 2010 at 6:03 a.m. EDT
  • monitor clipboard and correct ed2k links
    #!/usr/bin/python -tt
    #-*- coding:utf-8 -*-
    __DOC__="""
    monitor your clipboard
    convert your ed2k links into "correct" encode
    """
    
    import gtk
    import urllib2
    import re
    
    class Ed2kConvert(object):
    
        def __init__(self):
            self.clip = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)
            self.clip.connect("owner-change", self._clipboard_changed)
    
    
        def ed2k_handler(self,links):
            '''
            use unquote method included by urllib2 correct nonormal url
            '''
            cvtlinks = []
            for link in links:
                link = urllib2.unquote(link)
                cvtlinks.append(link)
            self.clip.set_text('\n'.join(cvtlinks))
    
    
        def _clipboard_changed(self,clipboard, event):
            self.text = clipboard.wait_for_text()
            #print text
            if self.text:
                self.plugins_routing()
    
        def plugins_routing(self):
            p = re.compile(r'(ed2k://.*?/)')
            matches = p.findall(self.text.replace('\n', ''))
            if not matches:
                return False
            else:
                self.ed2k_handler(matches)
    
    if __name__ == '__main__':
        s = Ed2kConvert()
        gtk.main()
    

    copy | embed

    0 comments - tagged in  posted by wgzhao on Jun 18, 2010 at 5:58 a.m. EDT
  • Simple Python HTTP Server
    python -m SimpleHTTPServer
    

    copy | embed

    0 comments - tagged in  posted by jonbiddle on Jun 17, 2010 at 9:14 a.m. EDT
  • Python rm -rf
    def remove_path(path):
        """Equivalent to rm -f or rm -rf"""
        import os, errno, shutil
        try:
            os.unlink(path)
        except OSError, exc:
            if exc.errno == errno.EISDIR:
                shutil.rmtree(path)
            elif exc.errno != errno.ENOENT:
                raise
    

    copy | embed

    0 comments - tagged in  posted by kergoth on Jun 03, 2010 at 12:50 p.m. EDT
  • get temporary root access to a box using the python interpreter
    sudo python -c "import os; os.system('bash');"
    

    copy | embed

    0 comments - tagged in  posted by deegeedubb on Jun 03, 2010 at 12:40 p.m. EDT
  • Get contents of a web page w/Python
    # Get contents of a web page
    import httplib
    conn=httplib.HTTPConnection("www.python.org") 
    conn.request("GET", "/index.html") 
    r1 = conn.getresponse() 
    print r1.status, r1.reason 
    data1 = r1.read() 
    conn.close()
    

    copy | embed

    0 comments - tagged in  posted by shacker on May 24, 2010 at 10:43 a.m. EDT
  • Script that determines and shows how much RAM is currently being used per program
    #!/usr/bin/env python
    
    # Try to determine how much RAM is currently being used per program.
    # Note the per program, not per process. So for example this script
    # will report mem used by all httpd process together. In detail it reports:
    # sum(all RSS for process instances) + max(shared mem for any process instance)
    #
    # The shared calculation below will factor out shared text and
    # libs etc. within a program, but not between programs. So there
    # will always be some overestimation. This will be the same for
    # all processes that just use libc for e.g. but more for others
    # that use larger shared libs like gnome, kde etc.
    
    # Author: P@draigBrady.com
    
    # V1.0      06 Jul 2005    Initial release
    # V1.1      11 Aug 2006    root permission required for accuracy
    # V1.2      08 Nov 2006    Add total to output
    #                          Use KiB,MiB,... for units rather than K,M,...
    # V1.3      22 Nov 2006    Ignore shared col from /proc/$pid/statm for
    #                          2.6 kernels up to and including 2.6.9.
    #                          There it represented the total file backed extent
    # V1.4      23 Nov 2006    Remove total from output as it's meaningless
    #                          (the shared values overlap with other programs).
    #                          Display the shared column. This extra info is
    #                          useful, especially as it overlaps between programs.
    # V1.5      26 Mar 2007    Remove redundant recursion from human()
    # V1.6      05 Jun 2007    Also report number of processes with a given name.
    #                          Patch from riccardo.murri@gmail.com
    
    # Notes:
    #
    # All interpreted programs where the interpreter is started
    # by the shell or with env, will be merged to the interpreter
    # (as that's what's given to exec). For e.g. all python programs
    # starting with "#!/usr/bin/env python" will be grouped under python.
    # You can change this by changing comm= to args= below but that will
    # have the undesirable affect of splitting up programs started with
    # differing parameters (for e.g. mingetty tty[1-6]).
    #
    # For 2.6 kernels up to and including 2.6.13 and later 2.4 redhat kernels
    # (rmap vm without smaps) it can not be accurately determined how many pages
    # are shared between processes in general or within a program in our case:
    # http://lkml.org/lkml/2005/7/6/250
    # A warning is printed if overestimation is possible.
    # In addition for 2.6 kernels up to 2.6.9 inclusive, the shared
    # value in /proc/$pid/statm is the total file-backed extent of a process.
    # We ignore that, introducing more overestimation, again printing a warning.
    #
    # I don't take account of memory allocated for a program
    # by other programs. For e.g. memory used in the X server for
    # a program could be determined, but is not.
    #
    # This script assumes threads are already merged by ps
    
    # TODO:
    #
    # use ps just to enumerate the pids and names
    # so as to remove the race between reading rss and shared values
    
    import sys, os, string
    
    if os.geteuid() != 0:
    	sys.stderr.write("Sorry, root permission required.\n");
    	sys.exit(1)
    
    PAGESIZE=os.sysconf("SC_PAGE_SIZE")/1024 #KiB
    our_pid=os.getpid()
    
    #(major,minor,release)
    def kernel_ver():
    	kv=open("/proc/sys/kernel/osrelease").readline().split(".")[:3]
    	for char in "-_":
    		kv[2]=kv[2].split(char)[0]
    	return (int(kv[0]), int(kv[1]), int(kv[2]))
    
    kv=kernel_ver()
    
    def getShared(pid):
    	if os.path.exists("/proc/"+str(pid)+"/smaps"):
    		shared_lines=[line
    			for line in open("/proc/"+str(pid)+"/smaps").readlines()
    				if line.find("Shared")!=-1]
    		return sum([int(line.split()[1]) for line in shared_lines])
    	elif (2,6,1) <= kv <= (2,6,9):
    		return 0 #lots of overestimation, but what can we do?
    	else:
    		return int(open("/proc/"+str(pid)+"/statm").readline().split()[2])*PAGESIZE
    
    cmds={}
    shareds={}
    count={}
    for line in os.popen("ps -e -o rss=,pid=,comm=").readlines():
    	size, pid, cmd = map(string.strip,line.strip().split(None,2))
    	if int(pid) == our_pid:
    		continue #no point counting this process
    	try:
    		shared=getShared(pid)
    	except:
    		continue #ps gone away
    	if shareds.get(cmd):
    		if shareds[cmd] < shared:
    			shareds[cmd]=shared
    	else:
    		shareds[cmd]=shared
    	#Note shared is always a subset of rss (trs is not always)
    	cmds[cmd]=cmds.setdefault(cmd,0)+int(size)-shared
    	if count.has_key(cmd):
    		count[cmd] += 1
    	else:
    		count[cmd] = 1
    
    #Add max shared mem for each program
    for cmd in cmds.keys():
    	cmds[cmd]=cmds[cmd]+shareds[cmd]
    
    sort_list = cmds.items()
    sort_list.sort(lambda x,y:cmp(x[1],y[1]))
    sort_list=filter(lambda x:x[1],sort_list) #get rid of zero sized processes (kernel threads)
    
    #The following matches "du -h" output
    #see also human.py
    def human(num, power="Ki"):
    	powers=["Ki","Mi","Gi","Ti"]
    	while num >= 1000: #4 digits
    		num /= 1024.0
    		power=powers[powers.index(power)+1]
    	return "%.1f %s" % (num,power)
    
    def cmd_with_count(cmd, count):
    	if count>1:
    		return "%s (%u)" % (cmd, count)
    	else:
    		return cmd
    print " Private  +  Shared  =  RAM used\tProgram \n"
    for cmd in sort_list:
    	print "%8sB + %8sB = %8sB\t%s" % (human(cmd[1]-shareds[cmd[0]]), human(shareds[cmd[0]]), human(cmd[1]), cmd_with_count(cmd[0], count[cmd[0]]))
    print "\n Private  +  Shared  =  RAM used\tProgram \n"
    
    #Warn of possible inaccuracies
    #1 = accurate
    #0 = some shared mem not reported
    #-1= all shared mem not reported
    def shared_val_accurate():
    	"""http://wiki.apache.org/spamassassin/TopSharedMemoryBug"""
    	if kv[:2] == (2,4):
    		if open("/proc/meminfo").read().find("Inact_") == -1:
    			return 1
    		return 0
    	elif kv[:2] == (2,6):
    		if os.path.exists("/proc/"+str(os.getpid())+"/smaps"):
    			return 1
    		if (2,6,1) <= kv <= (2,6,9):
    			return -1
    		return 0
    	else:
    		return 1
    
    vm_accuracy = shared_val_accurate()
    if vm_accuracy == -1:
    	sys.stderr.write("Warning: Shared memory is not reported by this system.\n")
    	sys.stderr.write("Values reported will be too large.\n")
    elif vm_accuracy == 0:
    	sys.stderr.write("Warning: Shared memory is not reported accurately by this system.\n")
    	sys.stderr.write("Values reported could be too large.\n")
    

    copy | embed

    0 comments - tagged in  posted by d1s4st3r on May 20, 2010 at 6:43 a.m. EDT
  • PyBrowser
    #!/usr/bin/env python
    #
    #       pybrowse.py
    #
    #       Copyright 2010 Vladimir Kolev <admin@vladimirkolev.com>
    #
    #       Created with help of the TuxRadar video tutorial in pyGTK and webkit
    #       See: http://www.tuxradar.com/content/python-pygtk-webkit-20-minutes
    #
    #       Licensed under the GNU GPL v.3 License
    #
    
    import gtk
    import os
    # the next is needed so we don't see a nasty Glibc error
    import gobject
    gobject.threads_init()
    # ofcourse the webkite showld be imported too
    import webkit
    
    class PyBrowser:
        def __init__(self):
            # Define the window
            self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
            self.window.connect("delete_event", self.delete_event)
            self.window.set_title("PyBrowser v.0.1")
            self.window.set_icon_from_file("icons/pybrowser_small.png")
            self.window.resize(600, 480)
            # the container for the webkitview
            self.scroller = gtk.ScrolledWindow()
            # hbox and vbox needed for positioning the widgets
            self.vbox = gtk.VBox()
            self.hbox = gtk.HBox()
            # define the widgets for the window
            self.urltext = gtk.Entry()
            self.urltext.set_text("http://") # not needed, but better then nothing
            self.urltext.set_size_request(600,38)
            self.urltext.connect("activate", self.enter_pressed) # Enter in the
            # Some buttons are needed                            # Entry box
            self.gobutton = gtk.Button()
            self.goimage = gtk.Image()
            self.goimage.set_from_file("icons/go.png")
            self.gobutton.set_image(self.goimage)
            self.gobutton.connect("clicked", self.go_clicked) # the Go! button
            self.refresh = gtk.Button()
            self.refreshimage = gtk.Image()
            self.refreshimage.set_from_file("icons/reload.png")
            self.refresh.set_image(self.refreshimage)
            self.refresh.connect("clicked", self.refresh_browser) # The reload button
            self.progress = gtk.ProgressBar() # the progress bar for loading the pages
            self.hbox.pack_start(self.urltext)
            self.hbox.pack_start(self.gobutton, False)
            self.hbox.pack_start(self.refresh, False)
    
            # define the webbrowser
            self.browser = webkit.WebView()
            self.browser.open("http://www.google.com/webhp?hl=en")
            self.browser.connect("title-changed", self.title_changed)
            # Signal to know that we are loading a new webpage, so the next actions
            # can start
            self.browser.connect("load-progress-changed", self.load_progress_changed)
            # Starting loading the page, means we have to show the progressbar
            self.browser.connect("load-started", self.load_started)
            # The page is loaded, so we change the URL to the actual one
            # and hide the progressbar
            self.browser.connect("load-finished", self.load_finished)
            self.scroller.add(self.browser)
    
            self.vbox.pack_start(self.hbox, False) # We don't need big buttons don't we
            self.vbox.pack_start(self.scroller)
            self.vbox.pack_start(self.progress, False) # And we want more place for the browser
    
            self.window.add(self.vbox)
            self.window.show_all() # Just show everything
    
        def main(self):
            gtk.main()
    
        def delete_event(self, widget, data=None):
            gtk.main_quit()
    
        def enter_pressed(self, entry):
            self.browser.open(self.urltext.get_text())
    
        def go_clicked(self, btn):
            self.browser.open(self.urltext.get_text())
    
        def refresh_browser(self, btn):
            self.browser.reload()
    
        def title_changed(self, webview, frame, title):
            self.window.set_title(title)
    
        def load_progress_changed(self, webview, amount):
            # As in the tutorial - the fraction is amount devided by double value of 100
            # We don't devide by an integer
            self.progress.set_fraction(amount / 100.0)
    
        def load_started(self, webview, frame):
            self.progress.show()
    
        def load_finished(self, webview, frame):
            # Get the actual URI (fom the frame) and put it in the Addressbox
            self.urltext.set_text(frame.get_uri())
            self.progress.hide()
    
    if __name__ == "__main__":
        browse = PyBrowser()
        browse.main()
    

    copy | embed

    0 comments - tagged in  posted by vkolev on May 12, 2010 at 9:55 a.m. EDT
  • Copy current playing song to clipboard
    #!/usr/bin/env python
    #
    #       playCopy 1.0 (python script)
    #       
    #       Copyright 2009 Vladimir Kolev <admin@vladimirkolev.com>
    #       
    #       This program is free software; you can redistribute it and/or modify
    #       it under the terms of the GNU General Public License as published by
    #       the Free Software Foundation; either version 2 of the License, or
    #       (at your option) any later version.
    #       
    #       This program is distributed in the hope that it will be useful,
    #       but WITHOUT ANY WARRANTY; without even the implied warranty of
    #       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    #       GNU General Public License for more details.
    #       
    #       You should have received a copy of the GNU General Public License
    #       along with this program; if not, write to the Free Software
    #       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
    #       MA 02110-1301, USA.
    #	
    #	Special thanks to Umang <umang.me@gmail.com> for the changes in the script.
    #	See section 4. in INSTALL file for the changes
    #
    
    
    import os
    import commands
    # python-dbus used for getting the information from Audaicous
    import dbus
    
    # Set show_not to 0 to disable the notifications
    show_not = 1
    
    def cur_song():
    	"""Attempts to find the name of the song playing by checking which music player is running and retreiving the song name from the application.
    	
    	Players currently supported: Rhythmbox, mocp, Exaile, Banshee, Audacious"""
    	if "banshee" in os.popen('ps -A | grep banshee').readline():
    		# Get the banshee artist and title and replace the unneccessery tiles from the string
    		artist = os.popen('banshee --query-artist').readline().replace('artist: ', '').replace('\n', '')
    		title = os.popen('banshee --query-title').readline().replace('title: ', '').replace('\n', '')
    		song = "%s - %s" % (artist, title)
    	elif "exaile" in os.popen('ps -A | grep exaile').readline():
    		# Get the exaile artist and title and replace the unneccessery tiles from the string
    		artist = os.popen('exaile --get-artist').readline().replace('artist: ', '').replace('\n', '')
    		title = os.popen('exaile --get-title').readline().replace('title: ', '').replace('\n', '')
    		song = "%s - %s" % (artist, title)
    	elif "rhythmbox" in os.popen('ps -A | grep rhythmbox').readline():
    		# Get the rhythmbox current playing information and set it to artist
    		song = os.popen('rhythmbox-client --print-playing').readline().replace('\n', '')
    	elif "mocp" in os.popen('ps -A | grep moc').readline():
    		# Get the information from mocp
    		info = commands.getoutput("mocp --info").splitlines()
    		if info == ["State: STOP"]:
    			#If mocp is stopped, then change the artist to Nothing to show
    			song = "moc is stopeed"
    		else:
    			# If there is a song information split it and formatid for the final string
    			artist = info[3].replace('Artist:', '')
    			title = info[4].replace('SongTitle:', '')
    			song = "%s - %s" % (artist, title)
    	elif "audacious" in os.popen('ps -A | grep audacious').readline():
    		 # initialise the dbus
    		 session_bus = dbus.SessionBus()
    		 # create two proxies 
    		 # proxy_obj1 gets integer for the current playing track in the playlist
    		 proxy_obj1 = session_bus.get_object('org.mpris.audacious', '/TrackList')
    		 selecter = dbus.Interface(proxy_obj1, 'org.freedesktop.MediaPlayer')
    		 # store the integer for the playing track so to be sended to proxy_obj2
    		 ct = selecter.GetCurrentTrack()
    		 # proxy_obj2 retrieves the title of the current playing track
    		 proxy_obj2 = session_bus.get_object('org.mpris.audacious', '/org/atheme/audacious')
    		 player = dbus.Interface(proxy_obj2, 'org.atheme.audacious')
    		 # Store the title in the song variable
    		 song = player.SongTitle(ct)
    	elif "listen" in os.popen('ps -A | grep listen').readline():
    		# Get the current song from the commandline interface
    		info = commands.getoutput("listen -c")
    		if info == ["No song playing"]:
    			# If No song playing create song variable with "Listen player is paused"
    			song = "Listen player is not playing"
    		else:
    			# if Listen is playing then create the song variable with the information:
    			song = info.replace("\n", "")
    	elif "quodli" in os.popen('ps -A | grep quodli').readline():
    		# Get the current playing song from the command line
    		info = os.popen('quodlibet --print-playing').readline()
    		song = info.replace('\n', '')
    	elif "bluemindo" in os.popen('ps -A | grep bluemin').readline():
    		# Get the current playing song from the command line
    		info = os.popen('bluemindo --current').readline()
    		song = info.replace('\n', '')
    	elif "jajuk" in os.popen('ps -A | grep jajuk').readline():
    		session_bus = dbus.SessionBus()
    		proxyobj1 = session_bus.get_object('org.jajuk.dbus.DBusSupport', '/JajukDBus')
    		selected = dbus.Interface(proxyobj1, 'org.jajuk.services.dbus.DBusSupport')
    		song = selected.current()
    	else:
    		if show_not == 1:
    			import pynotify
    			pynotify.init("playCopy")
    			ne = pynotify.Notification("playCopy", "\nNo supported player running", "error")
    			ne.show()
    	return song
    
    if __name__ == "__main__":
    	import pygtk
    	import gtk	
    	# Define the clipboard
    	clipboard = gtk.clipboard_get()
    	# Get the song name from cur_song(), copy the string to the clipboard and store it
    	clipboard.set_text(cur_song())
    	clipboard.store()
    	if show_not == 1:
    		try:
    			import pynotify
    			if pynotify.init("playCopy"):
    				n = pynotify.Notification("playCopy", "\n%s" % clipboard.wait_for_text(), "audio-volume-medium")
    				n.show()
    		except:
    			print "You don't have pynotify installed!"
    	
    

    copy | embed

    0 comments - tagged in  posted by vkolev on May 11, 2010 at 3:46 a.m. EDT
  • Connect to a Shotgun setup with Python
    import sys
    from pprint import pprint
    #sys.path.append ('z:/software/scripts')
    # you need to either append the path to where the shotgun api is or
    #you need to add it to your PYTHONPATH as i have done at home
    #from getShotData import *
    
    print ('Loading Shotgun Support')
    
    URL = ""
    name = ""
    API = ""
    
    # connect to shotgun
    def shotgunConnect():
        from shotgun_api3_preview import Shotgun
        sg = Shotgun(URL,name,API)
        return sg
    
    # find a project given the name
    def sgProject (sg, input):
        return sg.find_one("Project", [["name", "is", input]] )
    
    # finding a shot given the name :
    def sgShot (sg, shot, project):
        return sg.find_one('Shot',[['code','is',shot],['project','is',project]],['sg_cut_in','sg_cut_out','sg_client_version', 'code'])
    
    
    # expects a project in the proper naming, and a shot 
    def createShot (sg, proj, shot):
        filters = [['code','is','CGI / Live Action Shot' ]]
        template = sg.find_one('TaskTemplate',filters)
        project = sgProject(proj)
    
        data = { 'project': {"type":"Project","id": project['id']},
                 'code': shot,
                 'task_template' : template,
                 'description': '',
                 'sg_status_list': 'wtg' }
        result = sg.create('Shot', data)
        return result
    
    
    
    # find multiple notes given a shot ID (from above)
    # order in newest to oldest
    # requires you call it like note[0]['content']
    def sgNotesFind (sg, shotID):
        note = sg.find('Note',[['note_links','is', shotID]],['subject','content', 'created_at'],[{'field_name':'created_at','direction':'desc'}])
        return note
    
    # find a single (most recent) note given a shot ID
    # then call it like note['content']
    def sgNotesFindLatest (sg, shotID):
        note = sg.find_one('Note',[['note_links','is', shotID]],['subject','content','created_at'],[{'field_name':'created_at','direction':'desc'}])
        return note
    
    
    def sgCreateNote(sg, project, shotID, subject, content):
        # enter data here for a note to create
        data = {'subject':subject,'content':content,'note_links':[shotID],'project':project}
        # create the note
        noteID = sg.create('Note',data)
        return noteID
    
    # create a version
    def sgCreateVersion(sg, project, shotID, verName, description, framePath, firstFrame, lastFrame, clientName=''):
    
        data = {'project': project,
                'code': verName,
                'description': description,
                'sg_path_to_frames': framePath,
                'frame_range': firstFrame + '-' + lastFrame,
                #'sg_uploaded_movie': '/Users/throb/Downloads/test.m4v',
                #'sg_first_frame': 1,
                #'sg_last_frame': 100,
                'sg_status_list': 'rev',
                'entity': shotID}             
        # in case we're putting a client version in here we need this code.
        # we are expecting a field called sg_client_name in the version table.
        # please make sure you create this in the shotgun setup
        if clientName != '' :
            data['sg_client_name'] =  clientName
    
                #'user': {'type':'HumanUser', 'id':165} }
        return sg.create('Version',data)  
    
    #add a task version to the system
    def sgCreateVersionTask(sg, project, shotID, verName, description, framePath, firstFrame, lastFrame, task):
        filters = [['content','is',task],['entity','is',shot]]
        taskID = sg.find_one('Task',filters)
        data = {'project': project,
                'code': verName,
                'description': description,
                'sg_path_to_frames': framePath,
                'frame_range': firstFrame + '-' + lastFrame,
                #'sg_uploaded_movie': '/Users/throb/Downloads/test.m4v',
                #'sg_first_frame': 1,
                #'sg_last_frame': 100,
                'sg_status_list': 'rev',
                'sg_task': taskID,
                
                'entity': shotID}             
        # in case we're putting a client version in here we need this code.
        # we are expecting a field called sg_client_name in the version table.
        # please make sure you create this in the shotgun setup
        #'user': {'type':'HumanUser', 'id':165} }
        return sg.create('Version',data) 
    
    # look for versions in a shot:
    def sgVersionFind(sg, shotID):
        return sg.find('Version',[['entity','is',shotID]],['code','task','sg_path_to_frames'])
    
    # search for the latest task given shotID and task info
    def sgVersionFindLatestTask(sg, shotID, task):
        # first look for the task and get the ID
        filters = [['content','is',task],['entity','is',shotID]]
        taskID = sg.find_one('Task',filters)
        # then look for the latest 
        #version using the task ID.  note that we need to use the [0] or else we're sending the array versus the hash
        versionLatest = sg.find_one('Version',[['entity','is',shotID],['sg_task','is',taskID]],['code','sg_task','sg_path_to_frames'],[{'field_name':'created_at','direction':'desc'}])
        return versionLatest
    
    # look for latest comp version
    ## can deprecate since there is a way to get latest version including task type above
    '''
    def sgVersionFindLatestComp(sg, shotID):
        # first look for the task and get the ID
        filters = [['content','is','Comp'],['entity','is',shotID]]
        taskID = sg.find('Task',filters)
        # then look for the latest 
        #version using the task ID.  note that we need to use the [0] or else we're sending the array versus the hash
        versionComp = sg.find_one('Version',[['entity','is',shotID],['sg_task','is',taskID[0]]],['code','sg_task','sg_path_to_frames'],[{'field_name':'created_at','direction':'desc'}])
        return versionComp
    '''
    
    ## The following requires a field called "client_version" be added to shotgun
    def sgVersionClientUpate (sg, shotID, version):
        data = { 'sg_client_version': version}
        result = sg.update('Shot', shotID['id'], data)
        return result
    
    # connect to shotgun and get the latest "client version" number
    def sgGetClientVersion (sg, currShot):
        '''sg = shotgunConnect()
        sgproject = sgProject(sg, getJob(input))
        currShot = getSeq(input) + '_' + getShot(input)
        '''
        sgshot = sgShot(sg, currShot)
        try :
            currentVersion = sgshot['sg_client_version']
        except : 
            currentVersion = 0
        return currentVersion
    

    copy | embed

    0 comments - tagged in  posted by throb on May 02, 2010 at 6:27 p.m. EDT
Sign up to create your own snipts, or login.