content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Let Tkinter continue to process next event without closing current pop-up window I am using tkinter to write a simple GUI program to plot figure of some data, the plot function is realized using matplotlib module, here is my simplified code: #!/usr/bin/env python import Tkinter, tkFileDialog, tkMessageBox from plo...
Let Tkinter continue to process next event without closing current pop-up window
I am using tkinter to write a simple GUI program to plot figure of some data, the plot function is realized using matplotlib module, here is my simplified code: #!/usr/bin/env python import Tkinter, tkFileDialog, tkMessageBox from plot_core import berplot class BerPlotTk(Tkinter.Frame): def __init__ (self, master ...
[ "you can embed matplotlib figure in to Tk GUI:\nimport matplotlib\nmatplotlib.use('TkAgg')\n\nfrom numpy import arange, sin, pi\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nfrom matplotlib.figure import Figure\nimport Tkinter as Tk\n\nclass TkPlot(Tk.Frame):\n def __...
[ 1 ]
[]
[]
[ "matplotlib", "python", "tkinter" ]
stackoverflow_0007020380_matplotlib_python_tkinter.txt
Q: django: creating a background process using os.fork? I wish to run a long-running script in the background upon receiving a request. I read about subprocess but I require that the call is nonblocking so that the request can complete in time. def controlCrawlers(request): if request.method == 'POST' and 'type'...
django: creating a background process using os.fork?
I wish to run a long-running script in the background upon receiving a request. I read about subprocess but I require that the call is nonblocking so that the request can complete in time. def controlCrawlers(request): if request.method == 'POST' and 'type' in request.POST and 'cc' in request.POST: if req...
[ "Yeah, don't do this, use celery instead. It makes running asynchronous tasks a lot easier, more reliable.\n", "If you don't want to use asynchronous task queues with something like celery you can always just run a python script via cron. There are several options to do this. An example:\n\ncreate a model which s...
[ 5, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007020630_django_python.txt
Q: Help using *args in tuple matching Python function I am trying to build a function in python that yields values of two dictionaries IF a particular value from dict1 matches a particular value of dict2. My function looks like this: def dict_matcher(dict1, dict2, item1_pos, item2_pos): """Uses a tuple value from dic...
Help using *args in tuple matching Python function
I am trying to build a function in python that yields values of two dictionaries IF a particular value from dict1 matches a particular value of dict2. My function looks like this: def dict_matcher(dict1, dict2, item1_pos, item2_pos): """Uses a tuple value from dict1 to search for a matching tuple value in dict2. If a m...
[ "You could use slice objects:\ndef dict_matcher(dict1, dict2, pos1, pos2, slicer1=(), slicer2=()):\n slice1 = slice(*slicer1) if slicer1 else slice(len(dict1))\n slice2 = slice(*slicer2) if slicer2 else slice(len(dict2))\n for data1 in dict1.values():\n for data2 in dict2.values():\n if d...
[ 1, 0, 0 ]
[]
[]
[ "args", "dictionary", "match", "python", "python_3.x" ]
stackoverflow_0007019709_args_dictionary_match_python_python_3.x.txt
Q: A way to animate transition with Python, Gtk and Cairo? people I have seen some tutorials showing how to create animations with PyGtk, the best one being this: https://cairographics.org/cookbook/animationrotation/ This tutorial uses gobject.timeout_add() to set some clock to constantly refresh the animation. What ...
A way to animate transition with Python, Gtk and Cairo?
people I have seen some tutorials showing how to create animations with PyGtk, the best one being this: https://cairographics.org/cookbook/animationrotation/ This tutorial uses gobject.timeout_add() to set some clock to constantly refresh the animation. What I wanted to do, instead, is to create FINITE animations, whic...
[ "gobject.timeout_add() can be used for finite animations. The callback you set up will keep being called until it returns False, at which point your method won't be called again.\nFor example, if you want a ball to be animated for 5 seconds, you would be responsible for determining how long the animation has been g...
[ 4 ]
[]
[]
[ "animation", "cairo", "gtk", "pygtk", "python" ]
stackoverflow_0007016509_animation_cairo_gtk_pygtk_python.txt
Q: Broken PUT request with jquery/python GAE I'm using jQuery's AJAX function, like so: $.ajax ({ "url" : "/note", "async" : true, "type" : "POST", "data" : {"id" : id, "content" : el.value} }); On the backend (Python Google App Engine, currently using webapp.RequestHandler), PUT re...
Broken PUT request with jquery/python GAE
I'm using jQuery's AJAX function, like so: $.ajax ({ "url" : "/note", "async" : true, "type" : "POST", "data" : {"id" : id, "content" : el.value} }); On the backend (Python Google App Engine, currently using webapp.RequestHandler), PUT requests are handled by the same function that ha...
[ "self.request.POST, and hence self.request.get() don't return form data for PUT requests (or any non-POST requests). While it's not usual to submit form data using a PUT request (more commonly, you're submitting something as the body of the request), it's certainly a little odd that they're deliberately disabling i...
[ 1 ]
[]
[]
[ "google_app_engine", "http", "jquery", "python" ]
stackoverflow_0007020562_google_app_engine_http_jquery_python.txt
Q: Python/mysql: Result into two Lists I was trying to plot MySQL result using Python script and matplotlib import MySQLdb import matplotlib.pyplot as plt conn = MySQLdb.connect (host = "localhost", user = "testuser", passwd = "testpass", ...
Python/mysql: Result into two Lists
I was trying to plot MySQL result using Python script and matplotlib import MySQLdb import matplotlib.pyplot as plt conn = MySQLdb.connect (host = "localhost", user = "testuser", passwd = "testpass", db = "test") cursor = conn.curso...
[ "The answer is \nid,secondid=zip(*row)\n\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0007016038_matplotlib_python.txt
Q: Drawing & Rendering Multiway Tree in Python Does somebody know how do I plot a multiway-tree in a aesthetically plausible way? info: more or less 100 items each level have approximately the same number of items 10 levels each node have between 0(leaf) and 6 childs each node specify it's own level, no matter his...
Drawing & Rendering Multiway Tree in Python
Does somebody know how do I plot a multiway-tree in a aesthetically plausible way? info: more or less 100 items each level have approximately the same number of items 10 levels each node have between 0(leaf) and 6 childs each node specify it's own level, no matter his roots. I'm currently using PIL, dividing each "...
[ "So, rendering graphs is the particular genius of graphviz, which also happens to have several libraries that provide python bindings. In my opinion, the best of these bindings libraries is pygraphviz. Graphviz is probably the best solution and also likely the simplest.\nThe particular layout you describe in your Q...
[ 20 ]
[]
[]
[ "graph", "graphviz", "multiway_tree", "python", "tree" ]
stackoverflow_0007020741_graph_graphviz_multiway_tree_python_tree.txt
Q: urllib2.HTTPError: HTTP Error 500: Internal Server Error if data.find('!exploits') != -1: nick = data.split('!')[ 0 ].replace(':','') results = api.exploitdb.search(arg) sck.send('PRIVMSG ' + chan + " :" + ' Results found: %s' % results['total'] + '\r\n') for exploit in results['matches'][:5]...
urllib2.HTTPError: HTTP Error 500: Internal Server Error
if data.find('!exploits') != -1: nick = data.split('!')[ 0 ].replace(':','') results = api.exploitdb.search(arg) sck.send('PRIVMSG ' + chan + " :" + ' Results found: %s' % results['total'] + '\r\n') for exploit in results['matches'][:5]: sck.send('PRIVMSG ' + chan + "" + '%s:' % (exp...
[ "Your code should be ok. \nThat's should be the server problem .\nInternal Error--the server could not fulfill the request because of an unexpected condition\nYou can check the return status of what its meaning.\n" ]
[ 2 ]
[]
[]
[ "http", "irc", "python", "sockets", "urllib2" ]
stackoverflow_0005632351_http_irc_python_sockets_urllib2.txt
Q: Python: xpath + regex with lxml and onclick? Suppose I'm looking for all <a onclick=...> that call the String.fromCharCode javascript code. What's the simplest way to find all of them? A: You could use contains(): doc.xpath('//a[contains(@onclick, "String.fromCharCode")]')
Python: xpath + regex with lxml and onclick?
Suppose I'm looking for all <a onclick=...> that call the String.fromCharCode javascript code. What's the simplest way to find all of them?
[ "You could use contains():\ndoc.xpath('//a[contains(@onclick, \"String.fromCharCode\")]')\n\n" ]
[ 3 ]
[]
[]
[ "python", "xpath" ]
stackoverflow_0007021193_python_xpath.txt
Q: python class not instantiated - ways to catch/debug? Im having some trouble with a python module (webpy.session) and Ive narrowed the problem down to a class not being instantiated. Is there a way I can catch this happening and log the reason/error to a log file? p.s (Ive tried running it in the python console and...
python class not instantiated - ways to catch/debug?
Im having some trouble with a python module (webpy.session) and Ive narrowed the problem down to a class not being instantiated. Is there a way I can catch this happening and log the reason/error to a log file? p.s (Ive tried running it in the python console and it works without error there)
[ "I use pdb to debug this kind of thing.\nFor example, to debug the code you posted, I would add:\ndb = web.database(dbn='mysql', db='auth', user='root', pw='')\nstore = web.session.DBStore(db, 'sessions')\nimport pdb; pdb.set_trace() # BREAK <<<< this line\nsession = web.session.Session(app, store, initializer={})\...
[ 0 ]
[]
[]
[ "error_handling", "python" ]
stackoverflow_0007020769_error_handling_python.txt
Q: Telling Zope/Chameleon to not parse a section? I have a Pyramid app that uses Chameleon. I need to declare some attributes in my DOCTYPE, like so: <!DOCTYPE public html ......... [ <!ATTLIST tag attributes CDATA #IMPLIED> ]> When I add this to my template, id doesn't get rendered properly and my browser dra...
Telling Zope/Chameleon to not parse a section?
I have a Pyramid app that uses Chameleon. I need to declare some attributes in my DOCTYPE, like so: <!DOCTYPE public html ......... [ <!ATTLIST tag attributes CDATA #IMPLIED> ]> When I add this to my template, id doesn't get rendered properly and my browser draws "]>". When I remove the ATTLIST and only do <!DOC...
[ "That has absolutely nothing to do with Chameleon. If I paste that code into a file and open it in my browser, I see ]> as well.\nEdit: I figured it out. Rename the file to .xhtml and it will work (at least for me).\nIf you're receiving it over the network, having the content-type set to application/xhtml+xml would...
[ 2 ]
[]
[]
[ "chameleon", "html", "pyramid", "python", "zope" ]
stackoverflow_0007021581_chameleon_html_pyramid_python_zope.txt
Q: Django 1.3, how to signal when a post has ended like on ebay? I'm totally confused and have no idea how to do this, so please forgive me if my description/information is bad. So I want say to do a notification via django-notification or simply send an e-mail to one of my user when a post of his had ended like on e...
Django 1.3, how to signal when a post has ended like on ebay?
I'm totally confused and have no idea how to do this, so please forgive me if my description/information is bad. So I want say to do a notification via django-notification or simply send an e-mail to one of my user when a post of his had ended like on ebay. In my database I have a model which stores the datetime of wh...
[ "You could use django-celery -- connect a post_save handler that checks if created is True, and if so schedules a Task that'll notify the user at the correct time (using the eta keyword arg).\n", "It sounds to me like you've at least thought through some solutions. One thing to keep in mind though is that Django...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_models", "django_signals", "python", "sql" ]
stackoverflow_0007020108_django_django_models_django_signals_python_sql.txt
Q: Get the binary representation of a ctypes Structure in Python I want to encode a message...This is the message that i have generated from ctypes import memmove, addressof, Structure, c_uint16,c_bool class AC(Structure): _fields_ = [("UARFCN", c_uint16), ("ValidUARFCN", c_bool ),("PassiveActi...
Get the binary representation of a ctypes Structure in Python
I want to encode a message...This is the message that i have generated from ctypes import memmove, addressof, Structure, c_uint16,c_bool class AC(Structure): _fields_ = [("UARFCN", c_uint16), ("ValidUARFCN", c_bool ),("PassiveActivationTime", c_uint16) ] def __init__(self , UARFCN ,ValidUARF...
[ "For C structures, all you have to do to write it to a file is open the file, then do\nfileobj.write(my_c_structure).\n\nThen you can reload it by opening the file and doing\nmy_c_structure = MyCStructure()\nfileobj.readinto(my_c_structure)\n\nAll you need is to make your __init__ arguments optional. See this post ...
[ 4 ]
[]
[]
[ "ctypes", "python", "struct" ]
stackoverflow_0007021841_ctypes_python_struct.txt
Q: Django Admin: not seeing any app (permission problem?) I have a site with Django running some custom apps. I was not using the Django ORM, just the view and templates but now I need to store some info so I created some models in one app and enabled the Admin. The problem is when I log in the Admin it just says "Yo...
Django Admin: not seeing any app (permission problem?)
I have a site with Django running some custom apps. I was not using the Django ORM, just the view and templates but now I need to store some info so I created some models in one app and enabled the Admin. The problem is when I log in the Admin it just says "You don't have permission to edit anything", not even the Auth...
[ "Hopefully this helps someone, but we had this same problem because someone added a different authentication backend to settings.py and did not keep the default ModelBackend. Changing the setting to:\nAUTHENTICATION_BACKENDS = (\n 'auth.authentication.EmailBackend',\n 'django.contrib.auth.backends.ModelBacken...
[ 23, 12, 2, 2, 0 ]
[]
[]
[ "django", "django_admin", "permissions", "python" ]
stackoverflow_0001929707_django_django_admin_permissions_python.txt
Q: Python, GTK, Webkit & scraping, big memory problem I'm trying to mirror a website for content, unfortunately large chunks of it is javascript based, including code that generates hrefs. That wipes out most standard web scraping tools (like httrack) as their attempts at processing javascript, if they even do attem...
Python, GTK, Webkit & scraping, big memory problem
I'm trying to mirror a website for content, unfortunately large chunks of it is javascript based, including code that generates hrefs. That wipes out most standard web scraping tools (like httrack) as their attempts at processing javascript, if they even do attempt it, are highly unreliable. So I decided to write my o...
[ "I haven't actually used WebKit, but shouldn't self.destroy be changed to self.destroy()? This may be causing a memory leak.\n" ]
[ 1 ]
[]
[]
[ "gtk", "memory", "python", "webkit" ]
stackoverflow_0007019788_gtk_memory_python_webkit.txt
Q: Safe using user input as key_name? I would like to use a string that was input by the user in a web form as part of a key name: user_input = self.request.POST.get('foo') if user_input: foo = db.get_or_insert(db.Key('Foo', user_input[:100], parent=my_parent)) Is this safe? Or should I do some inexpensive encodin...
Safe using user input as key_name?
I would like to use a string that was input by the user in a web form as part of a key name: user_input = self.request.POST.get('foo') if user_input: foo = db.get_or_insert(db.Key('Foo', user_input[:100], parent=my_parent)) Is this safe? Or should I do some inexpensive encoding or hash? If yes, which one?
[ "It's safe as long as you don't care about a malicious user filling up your database with junk. get_or_insert won't let them overwrite existing entries, just add new ones.\nMake sure you limit it's length (both in the UI and after it's been recieved), even if you do no other validation on it, so at least they can't...
[ 3 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007021954_google_app_engine_google_cloud_datastore_python.txt
Q: multiple search and replace in python I need to search in a parent folder all files that are config.xml and in those files replace one string in another. (from this-is to where-as) A: import os parent_folder_path = 'somepath/parent_folder' for eachFile in os.listdir(parent_folder_path): if eachFile.endswith...
multiple search and replace in python
I need to search in a parent folder all files that are config.xml and in those files replace one string in another. (from this-is to where-as)
[ "import os\nparent_folder_path = 'somepath/parent_folder'\nfor eachFile in os.listdir(parent_folder_path):\n if eachFile.endswith('.xml'):\n newfilePath = parent_folder_path+'/'+eachFile\n file = open(newfilePath, 'r')\n xml = file.read()\n file.close()\n xml = xml.replace('thing to...
[ 1, 0 ]
[]
[]
[ "python", "replace" ]
stackoverflow_0007022059_python_replace.txt
Q: python exception handling In the below python the message RSU is not supported on single node machine** is not getting printed. can anyone help please?? #! /usr/bin/env python import sys class SWMException(Exception): def __init__(self, arg): print "inside exception" Exception.__init__(self, ...
python exception handling
In the below python the message RSU is not supported on single node machine** is not getting printed. can anyone help please?? #! /usr/bin/env python import sys class SWMException(Exception): def __init__(self, arg): print "inside exception" Exception.__init__(self, arg) class RSUNotSupported(SWM...
[ "It is not printed, because you're even not trying to print it :) Here:\ntry:\n isPrepActionNeeded()\nexcept RSUNotSupported as e:\n print str(e)\n sys.exit(1)\n\n", "Because you handle the exception with your try/except clause.\n", "Change the last two lines to:\nexcept Exception as e:\n print e\n ...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007022148_python.txt
Q: Applying different commands at different location I am working in Ubuntu. I have a bunch of commands (say 10 commands like cmd1, cmd2, cmd3..............cmd10) I want to write a python script, which can achieve the following: It should traverse through the directory structure and apply a command at particular dir...
Applying different commands at different location
I am working in Ubuntu. I have a bunch of commands (say 10 commands like cmd1, cmd2, cmd3..............cmd10) I want to write a python script, which can achieve the following: It should traverse through the directory structure and apply a command at particular directory path. The location and the commands are already ...
[ "Maybe something like this:\nimport subprocess\nimport os\njobs=[\n ('/local/mnt/myspace/sample1', 'cmd1'),\n ('/local/mnt/myspace/sample2', 'cmd2'),\n ('/local/mnt/myspace', 'cmd3'),\n ('/local/mnt', 'cmd4'),\n ('/local/mnt/myspace/sample9', 'cmd', '8'),\n ('/local/mnt/myspace/sample3', 'cmd10'),...
[ 3, 1, 0 ]
[]
[]
[ "android", "python", "ubuntu" ]
stackoverflow_0007022030_android_python_ubuntu.txt
Q: Can python be used to log onto password protected sites for checking gmail, forums, etc...? I know you can open webpages quite simply using the webbrowser module like: import webbrowser webbrowser.open('http://www.google.com') but is it possible to pass log-in credentials to these websites? I would like to create...
Can python be used to log onto password protected sites for checking gmail, forums, etc...?
I know you can open webpages quite simply using the webbrowser module like: import webbrowser webbrowser.open('http://www.google.com') but is it possible to pass log-in credentials to these websites? I would like to create a script that automates some stuff that I do on a regular basis, for example, open gmail in fire...
[ "Depending on how the server handles authentication, you might be able to create a GET request that would do the trick:\nfrom urllib import urlencode\n\ncredentials = {\n 'username': 'bob',\n 'password': 'secret'}\nurl = \"http://example.com/login?\" + urlencode(credentials)\n\nWhether this will work depends ...
[ 0, 0, 0 ]
[]
[]
[ "python", "python_webbrowser", "scripting" ]
stackoverflow_0007021903_python_python_webbrowser_scripting.txt
Q: Is there a good way to apply pychecker/pylint to the python code in Tornado templates? I am using Tornado 2.0 (Python 2.6.5) to build a simple web app. Naturally, my Tornado templates contain snippets of Python code. For my non-template code, I am using pychecker and pylint to check for errors, etc. However, obvio...
Is there a good way to apply pychecker/pylint to the python code in Tornado templates?
I am using Tornado 2.0 (Python 2.6.5) to build a simple web app. Naturally, my Tornado templates contain snippets of Python code. For my non-template code, I am using pychecker and pylint to check for errors, etc. However, obviously pychecker and pylint can't be run over the templates directly, b/c the templates are no...
[ "You need to use view class pattern to avoid cluttering your template with Python code which cannot be analyzed.\n\nCreate a Python class to process your view, instead of function\nHave all \"template logic\" code as class methods. Your template calls them like {{ view.get_full_name }} and def get_full_name(self): ...
[ 0 ]
[]
[]
[ "pychecker", "pylint", "python", "tornado" ]
stackoverflow_0006963724_pychecker_pylint_python_tornado.txt
Q: Python variable declarations I came across this piece of code and am wondering what it means: typ, dat = imap_conn.search(None, search_string) What exactly does the typ, dat part of the line mean? A: It is tuple unpacking, see Python documentation. If your function returns a tuple you can always unpack it using...
Python variable declarations
I came across this piece of code and am wondering what it means: typ, dat = imap_conn.search(None, search_string) What exactly does the typ, dat part of the line mean?
[ "It is tuple unpacking, see Python documentation. If your function returns a tuple you can always unpack it using a syntax similar to a, b = func().\nAlso, you can use tuples on the fly, like a, b = b, a can be used for swapping two values.\n", "typ, dat is a tuple. When used on the left hand side of an assignmen...
[ 7, 3, 2, 0, 0, 0, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0007022701_python_syntax.txt
Q: archive list with django templatetags I have a django application, a blog. The entries for the blog can be accessed through a /year/month/day/slug url pattern, it works fine. My problem is, I want to have an archive list accessible to any template on my website. So i thought the best solution would be to create a ...
archive list with django templatetags
I have a django application, a blog. The entries for the blog can be accessed through a /year/month/day/slug url pattern, it works fine. My problem is, I want to have an archive list accessible to any template on my website. So i thought the best solution would be to create a templatetag that would create and return th...
[ "There is no need to return something special. Django is just Python, so it is your choice what you want to return. In this case I would recommend to return dictionary like this (just inventing) {{'title':'some title if you want','year': 'year if you want', 'url': url}, {...}, ...}. Then in template you just run th...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007022510_django_python.txt
Q: python + django: unable to find module with Popen I use subprocess.Popen in one of the my views: path = os.path.join(os.path.dirname(__file__), 'foo/bar.py') subprocess.Popen(["python",path]) In my wsgi file, I have import os import sys ppath = '/home/socialsense/ss/src' if ppath not in sys.path: sys.pat...
python + django: unable to find module with Popen
I use subprocess.Popen in one of the my views: path = os.path.join(os.path.dirname(__file__), 'foo/bar.py') subprocess.Popen(["python",path]) In my wsgi file, I have import os import sys ppath = '/home/socialsense/ss/src' if ppath not in sys.path: sys.path.append(ppath) os.environ['DJANGO_SETTINGS_MODULE'] =...
[ "It will only be in sys.path for the current Python instance. To get it for another, use the env argument to Popen with os.pathsep:\nimport subprocess\nimport os\nimport sys\nsubprocess.Popen([\"python\",path], env = {'PYTHONPATH': os.pathsep.join(sys.path)})\n\nYou should really look into the multiprocessing modul...
[ 5, 0 ]
[]
[]
[ "django", "mod_wsgi", "python", "subprocess", "wsgi" ]
stackoverflow_0007022807_django_mod_wsgi_python_subprocess_wsgi.txt
Q: Django - How am I using python map incorrectly? I am receiving a Type error from django in my view code. While attempting to round up to the nearest 5. i.e. 7 becomes 10 or 123 becomes 125, etc I have a list of integers valList = [ int(i) for i in str(int(math.ceil(result))) ] I then change a digit valList[len(va...
Django - How am I using python map incorrectly?
I am receiving a Type error from django in my view code. While attempting to round up to the nearest 5. i.e. 7 becomes 10 or 123 becomes 125, etc I have a list of integers valList = [ int(i) for i in str(int(math.ceil(result))) ] I then change a digit valList[len(valList)-1] = 5 and then combine the values to create ...
[ "How about a mathematical solution:\n>>> def f(n):\n... q, r = divmod(n,5)\n... if r == 0:\n... return q * 5\n... else:\n... return (q * 5) + 5\n...\n>>> f(7)\n10\n>>> f(123)\n125\n>>> f(120)\n120\n\n", "The generic way to round up to a number, with integer math, is:\n(((number - 1) // base) + 1) * ...
[ 3, 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007023009_django_python.txt
Q: AES encryption/decryption between Ruby-OpenSSL, PyCrypto I have to encrypt a piece of text using Ruby. I've used the Ruby-Openssl gem for that purpose. This encrypted text is them passed to a python program using which I have to decrypt it. I've used Pycrypto for the purpose. The problem is, in Pycrypto we have to...
AES encryption/decryption between Ruby-OpenSSL, PyCrypto
I have to encrypt a piece of text using Ruby. I've used the Ruby-Openssl gem for that purpose. This encrypted text is them passed to a python program using which I have to decrypt it. I've used Pycrypto for the purpose. The problem is, in Pycrypto we have to specify the padding convention manually. In Ruby, the padding...
[ "OpenSSL applies PKCS#5Padding by default, so this is also used automatically when encrypting data with OpenSSL::Cipher in AES-CBC mode (cf. OpenSSL docs). So there's no need to perform manual padding when using Ruby. \nThe padding has to be done manually in Python when using PyCrypto.\nOnce you apply this padding...
[ 3, 0 ]
[]
[]
[ "pycrypto", "python", "ruby" ]
stackoverflow_0007021410_pycrypto_python_ruby.txt
Q: Python thinks I'm passing more arguments than I am? Trying to set up some basic socket code in Python (well, Jython, but I don't think that's relevant here). import socket class Foo(object): def __init__(self): #some other init code here s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
Python thinks I'm passing more arguments than I am?
Trying to set up some basic socket code in Python (well, Jython, but I don't think that's relevant here). import socket class Foo(object): def __init__(self): #some other init code here s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect("localhost", 2057) s.send("Testin...
[ "You have to pass a Tuple to connect() method.\ns.connect( ('localhost', 2057) )\n\nThe first (implicit) argument expected is self, the second is the Tuple.\n", "You are passing three arguments! s is being passed as the implicit first argument, and the other two arguments you have specified are the second and th...
[ 12, 9, 4, 4, 3, 0 ]
[]
[]
[ "jython", "python", "sockets" ]
stackoverflow_0007022338_jython_python_sockets.txt
Q: [python]: how to get the string from the pointer by using ctypes? Here is the thing, I wrote a program using windows api EnumWindows which requires a callback func as the first arg, my poor code is as follows: User32 = WinDLL('User32.dll') LPARAM = wintypes.LPARAM HWND = wintypes.HWND BOOL = wintypes.BOOL def Pr...
[python]: how to get the string from the pointer by using ctypes?
Here is the thing, I wrote a program using windows api EnumWindows which requires a callback func as the first arg, my poor code is as follows: User32 = WinDLL('User32.dll') LPARAM = wintypes.LPARAM HWND = wintypes.HWND BOOL = wintypes.BOOL def Proc(hwnd, lparam): print("hwnd = {}, lparam = {}".format(hwnd, cast(...
[ "Because you are using Python 3 which is treating abcd as a Unicode string which ctypes encodes with UTF-16. But you then cast it assuming it is a single byte ANSI string.\nYou can make the program behave the way you want by one of the following methods:\n\nUse Python 2.x\nCall EnumWindows like so: EnumWindows(cb_p...
[ 2 ]
[]
[]
[ "ctypes", "pointers", "python" ]
stackoverflow_0007023285_ctypes_pointers_python.txt
Q: Django View ValueError when render_to_response I am going through some tutorials of learning Django for an upcoming project, and I could not load templates correctly. The debug mode returns a "ValueError" saying that it "need more than 1 value to unpack". I am running Django's bundled server. Any idea what's the p...
Django View ValueError when render_to_response
I am going through some tutorials of learning Django for an upcoming project, and I could not load templates correctly. The debug mode returns a "ValueError" saying that it "need more than 1 value to unpack". I am running Django's bundled server. Any idea what's the problem? Any help is appreciated. Here's the trace: ...
[ "You've set the wrong thing in settings.py. TEMPLATE_LOADERS is for Python code that finds and loads templates. You want to put your directory into TEMPLATE_DIRS.\n" ]
[ 6 ]
[]
[]
[ "django", "python", "render", "templates" ]
stackoverflow_0007023308_django_python_render_templates.txt
Q: How to get underlined title report by converting sxw to rml format using base_report_designer module? Problem: I have sxw file and whenever I convert it in rml file using base_report_designer module(OpenERP module), and generate report I do not get underlined fonts in report which are underlined in sxw though but ...
How to get underlined title report by converting sxw to rml format using base_report_designer module?
Problem: I have sxw file and whenever I convert it in rml file using base_report_designer module(OpenERP module), and generate report I do not get underlined fonts in report which are underlined in sxw though but not in rml file.I changed font format & size then after I did not get underlined fonts in report.Currently ...
[ "For better report customisation, use Aeroo Reports from Alistek. With this module, you can use your odt file without changing anything...\n" ]
[ 0 ]
[]
[]
[ "openerp", "python", "reportlab" ]
stackoverflow_0007021671_openerp_python_reportlab.txt
Q: dropdown event/callback in combo-box in pyqt4 is there a callback or event for dropdown in pyqt4 combo box? Just like self.connect(self.ui.combobox,SIGNAL("activated(int)"),self.refresh A: The QCombobox uses a QAbstractItemView (QListView by default) to display the dropdown items (accessible via the view() prope...
dropdown event/callback in combo-box in pyqt4
is there a callback or event for dropdown in pyqt4 combo box? Just like self.connect(self.ui.combobox,SIGNAL("activated(int)"),self.refresh
[ "The QCombobox uses a QAbstractItemView (QListView by default) to display the dropdown items (accessible via the view() property).\nI am not aware of any signal for that purpose.\nBut you can set an eventFilter that will do the trick by using installEventFilter on the view of the combobox and implement the eventFil...
[ 2, 0 ]
[]
[]
[ "combobox", "pyqt4", "python" ]
stackoverflow_0007021768_combobox_pyqt4_python.txt
Q: converting a date to string for manipulation in python I am new to python and i have written a script that converts a string date coming in to a datetime format going out. My problem is that cannot convert the datetime object back to a string for manipulation. i have a date eg 2011-08-10 14:50:10 all i need to to ...
converting a date to string for manipulation in python
I am new to python and i have written a script that converts a string date coming in to a datetime format going out. My problem is that cannot convert the datetime object back to a string for manipulation. i have a date eg 2011-08-10 14:50:10 all i need to to is add a T between the date and time and a Z at the end. unf...
[ "toValue = fromValue.strftime(\"%Y-%m-%dT %H:%M:%SZ\")\n\nThis should work fine. datetime.strftime was available on Python 2.3.\nYou'd certainly be better off upgrading to at least Python 2.5 if at all possible. Python 2.3 hasn't even received security patches in years.\nEdit: Also, you don't need to initialize or ...
[ 8, 3, 3 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0007023641_datetime_python.txt
Q: How to change file access permissions in linux? How does one change file access permissions? f = open('test','w') f.close() Defaults access permissions: 10600 A: You can use os.chmod os.chmod(path, mode) You probably want to use an octal integer literal, like 0777 for the mode. A: Use os.chmod(path, mode)
How to change file access permissions in linux?
How does one change file access permissions? f = open('test','w') f.close() Defaults access permissions: 10600
[ "You can use os.chmod\nos.chmod(path, mode)\n\nYou probably want to use an octal integer literal, like 0777 for the mode.\n", "Use os.chmod(path, mode)\n" ]
[ 20, 5 ]
[]
[]
[ "python" ]
stackoverflow_0007023981_python.txt
Q: Embed Python CLI in a Ruby process? As part of a larger project, I'm trying to "embed" a Python interactive interpreter in a Ruby process. I'd like to be able to do something like the following: $ irb irb(main):001:0> pipe = IO.popen("python", "w+") => #<IO:0x7f3dba4977e0> irb(main):002:0> pipe.puts "print 'hello'...
Embed Python CLI in a Ruby process?
As part of a larger project, I'm trying to "embed" a Python interactive interpreter in a Ruby process. I'd like to be able to do something like the following: $ irb irb(main):001:0> pipe = IO.popen("python", "w+") => #<IO:0x7f3dba4977e0> irb(main):002:0> pipe.puts "print 'hello'" => nil irb(main):003:0> pipe.gets => 'h...
[ "Here's an alternative approach using Ruby's pseudo-terminal library. I've tested this with ruby 1.9 on Linux and MacOS X, it won't probably run on Windows:\nrequire 'pty'\n\nbegin\n # stty -echo turns off terminal echo, without it tty input would be repeated\n # on output\n PTY.spawn( \"stty -echo; python\" ) d...
[ 2, 1 ]
[]
[]
[ "interactive", "pipe", "python", "ruby", "subprocess" ]
stackoverflow_0007001064_interactive_pipe_python_ruby_subprocess.txt
Q: is there any way to run a other function after a function run finish? def foo(): pass def bar(): print 'good bay' two function like blow and now i want to run bar function after foo run finish is there some method like class use __del__? as i know in class method i can use __del__ like follow: class A(o...
is there any way to run a other function after a function run finish?
def foo(): pass def bar(): print 'good bay' two function like blow and now i want to run bar function after foo run finish is there some method like class use __del__? as i know in class method i can use __del__ like follow: class A(object): def __init__(self): pass def __del__(self): ...
[ "This is what decorators are for. This decorator, used on foo with bar as an argument will will run bar after foo and still return foos result. It will work on functions with any number of arguments.\ndef run_before(lastfunc, *args1, **kwargs1):\n def run(func):\n def wrapped_func(*args, **kwargs):\n ...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007024206_python.txt
Q: Facebook Authentication for Desktop (Console based) application I am working on a python application which allows me to post updates/statuses to Facebook. I am facing a basic problem with getting access tokens. Since this application is working on the desktop, there is no question of using some web server. I under...
Facebook Authentication for Desktop (Console based) application
I am working on a python application which allows me to post updates/statuses to Facebook. I am facing a basic problem with getting access tokens. Since this application is working on the desktop, there is no question of using some web server. I understand that I have to open a URL: https://www.facebook.com/dialog/oaut...
[ "Maybe you can have some setup process where you obtain the tokens with offline access, that way the user will need to be presented with facebook login page only once, then you use this token later with the console app.\nSee offline_access on http://developers.facebook.com/docs/authentication/permissions/ \n", "C...
[ 2, 1 ]
[]
[]
[ "facebook", "oauth", "python" ]
stackoverflow_0006162063_facebook_oauth_python.txt
Q: Choice for building a online bulk mail sending system? I am sorry that there is some similar topic exists, but they are asked a long time ago. So allow me to open a new thread for asking this. Recently i am asked to build a online bulk mailing system . The mail is approved and subscribed. I found that phplist is e...
Choice for building a online bulk mail sending system?
I am sorry that there is some similar topic exists, but they are asked a long time ago. So allow me to open a new thread for asking this. Recently i am asked to build a online bulk mailing system . The mail is approved and subscribed. I found that phplist is exactly what i want but unfortunely i have to do a system by ...
[ "Can't you possibly integrate with a API of a Service like Mailchimp? Realize you said you have to roll your own but you could off load all the worries of sending mail to them. So you don't have to worry and can just focus on your application.\nProbably not the Answer you are looking for more of a suggestion.\n" ]
[ 0 ]
[]
[]
[ "email", "php", "python", "sendmail", "smtp" ]
stackoverflow_0007022161_email_php_python_sendmail_smtp.txt
Q: Speeding up socket send behavior (in Python) I have a script which sends 5-10 requests a second to the server. The most crucial requirement i have is a limit of requests per second. It must always be the specific figure, not more and no less. To do it i send requests after a given interval of time (minus time requ...
Speeding up socket send behavior (in Python)
I have a script which sends 5-10 requests a second to the server. The most crucial requirement i have is a limit of requests per second. It must always be the specific figure, not more and no less. To do it i send requests after a given interval of time (minus time required to send previous request). Problem: some req...
[ "\nThe most crucial requirement i have is a limit of requests per second.\n It must always be the specific figure, not more and no less.\n\nThat requirement is completely unimplementable via TCP. You would also need real-time guarantees of service times at the peer.\n", "(From How can I force a socket to send th...
[ 2, 0 ]
[]
[]
[ "buffer", "network_programming", "performance", "python", "sockets" ]
stackoverflow_0006880483_buffer_network_programming_performance_python_sockets.txt
Q: how to use the row [a,b] to index another array as data[a:b]? I have two arrays, the first one is a (n, 2) array which contains the start and the end of a selection in a data pool, the second one is the data pool. The general idea is to use the first to extract the relevant data from the second but I don't see ho...
how to use the row [a,b] to index another array as data[a:b]?
I have two arrays, the first one is a (n, 2) array which contains the start and the end of a selection in a data pool, the second one is the data pool. The general idea is to use the first to extract the relevant data from the second but I don't see how to do it cleanly with numpy. I found the following solution, but...
[ "Use slice:\nIn [1]: row = [4,7]\n\nIn [2]: data = range(10000)\n\nIn [3]: data[slice(*row)]\nOut[3]: [4, 5, 6]\n\n", "An even simpler solution than using slice() is\nrow = [4, 7]\ndata[row[0]:row[1]]\n\nwhich might be easier to read since it is a bit more explicit.\n" ]
[ 6, 4 ]
[]
[]
[ "indexing", "numpy", "python" ]
stackoverflow_0007024120_indexing_numpy_python.txt
Q: python global name 'self' is not defined Just started learning python and I am sure its a stupid question but I am trying something like this: def setavalue(self): self.myname = "harry" def printaname(): print "Name", self.myname def main(): printname() if __name__ =...
python global name 'self' is not defined
Just started learning python and I am sure its a stupid question but I am trying something like this: def setavalue(self): self.myname = "harry" def printaname(): print "Name", self.myname def main(): printname() if __name__ == "__main__": main() The error I ...
[ "self is the self-reference in a Class. Your code is not in a class, you only have functions defined. You have to wrap your methods in a class, like below. To use the method main(), you first have to instantiate an object of your class and call the function on the object. \nFurther, your function setavalue should ...
[ 42, 6, 4, 4, 0 ]
[]
[]
[ "python", "self", "variables" ]
stackoverflow_0007024452_python_self_variables.txt
Q: Sending message via Python + xmpppy: AttributeError in minimal example I found in a related question a minimal example to send a message via xmpp(py); see below. But when I execute the script I get the following error: client = xmpp.Client('gmail.com') AttributeError: 'module' object has no attribute 'Client' ...
Sending message via Python + xmpppy: AttributeError in minimal example
I found in a related question a minimal example to send a message via xmpp(py); see below. But when I execute the script I get the following error: client = xmpp.Client('gmail.com') AttributeError: 'module' object has no attribute 'Client' I'm working with Eclipse and PyDev, and xmpppy should definitely be installe...
[ "You've named a script xmpp.py. You're accidentally importing it instead of the real xmpp module.\nRename the script and everything should work fine.\n" ]
[ 3 ]
[]
[]
[ "eclipse", "pydev", "python", "python_module", "xmpppy" ]
stackoverflow_0007024430_eclipse_pydev_python_python_module_xmpppy.txt
Q: decimal range in for Sorry for my beginner question. I want to construct decimal range step in for cycle using the following construction: max_value = 10 my_range = [r * 0.01 for r in range(0, max_value) ] for i in range ( my_range ): //Error print (i) But there is the following error: TypeError: 'li...
decimal range in for
Sorry for my beginner question. I want to construct decimal range step in for cycle using the following construction: max_value = 10 my_range = [r * 0.01 for r in range(0, max_value) ] for i in range ( my_range ): //Error print (i) But there is the following error: TypeError: 'list' object cannot be inter...
[ "Your my_range is already a list. Just do:\nfor i in my_range:\n print(i)\n\n", "The error appears because range() function accepts three arguments: starting value (included in iteration), end value (not included) and a step. From mathematical point of view, it's: [a1, a2, ... an) where d = a2 - a1 is the ste...
[ 3, 1, 0 ]
[]
[]
[ "python", "range" ]
stackoverflow_0007024196_python_range.txt
Q: Simple solitaire I'm trying to make a simple solitaire in wich you get a random number of card heaps with a random number of cards in ex. heap1: 4 cards, heap2 5 cards and so on. Lets say we have four heaps with values 4, 5, 7, 1. Now what is done is that one card is removed from each heap to create a new one. So...
Simple solitaire
I'm trying to make a simple solitaire in wich you get a random number of card heaps with a random number of cards in ex. heap1: 4 cards, heap2 5 cards and so on. Lets say we have four heaps with values 4, 5, 7, 1. Now what is done is that one card is removed from each heap to create a new one. So the next step would l...
[ "So the actual cards (colors, faces) do not matter at all since all you model is a number of heaps?\nUse a list for the setup, integers to represent the heaps, and the random module to generate the initial configuration. Programming the game logic should be rather straight-forward.\n\nUPDATE\nYou're code is a good ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007024757_python.txt
Q: Is this bad practice? In this piece of code, if I match the given pattern on the line, I replace the line by a self-built string. Is this actually good practice? It looks a little bit like reusing the variable line for output, where it actually contains the contents of the currently read line. for line in lines: ...
Is this bad practice?
In this piece of code, if I match the given pattern on the line, I replace the line by a self-built string. Is this actually good practice? It looks a little bit like reusing the variable line for output, where it actually contains the contents of the currently read line. for line in lines: match = re.search(r'@Table...
[ "I'd say the intent in your code is clear and the code is short and simple so there is nothing wrong in it. If it still bothers you to be reusing the variable, you can do something like this:\nfor line in lines:\n match = re.search(r'@Table\\(name = \"(.*)\"\\)', line)\n\n if match:\n output_line = \"\...
[ 3 ]
[]
[]
[ "python", "python_2.4" ]
stackoverflow_0007025051_python_python_2.4.txt
Q: Splitting list into multiple lists to gain a speedup? Let's say my list is about 1,000,000 entries long. To acess an item, the time would be O(500,000), which seems very long to me. What happens when I split the list up into multiple lists ? Let's look at an example: Splitting the list into 10 parts, I'd have a ...
Splitting list into multiple lists to gain a speedup?
Let's say my list is about 1,000,000 entries long. To acess an item, the time would be O(500,000), which seems very long to me. What happens when I split the list up into multiple lists ? Let's look at an example: Splitting the list into 10 parts, I'd have a list as follows: splitted_list = [ [list with 100,000 e...
[ "Get item by index from list is O(1) whatever the size of the list.\n", "The answer to your question is that you are thinking of linked lists, in which each element holds a pointer to the next. These have O(n) indexing, since the only way to get the nth element is to walk through the list from the beginning.\nYou...
[ 5, 4, 3 ]
[]
[]
[ "list", "nested_lists", "performance", "python" ]
stackoverflow_0007024874_list_nested_lists_performance_python.txt
Q: Python MixIn standards So I'm writing some code and have recently come across the need to implement a few mixins. My question is, what is the proper way to design a mix-in? I'll use the example code below to illustrate my exact query. class Projectile(Movable, Rotatable, Bounded): '''A projectile.''' def _...
Python MixIn standards
So I'm writing some code and have recently come across the need to implement a few mixins. My question is, what is the proper way to design a mix-in? I'll use the example code below to illustrate my exact query. class Projectile(Movable, Rotatable, Bounded): '''A projectile.''' def __init__(self, bounds, positi...
[ "You can have both behavior in Python. You can force the reimplementation by using Abstract Base Classes, or by raising NotImplementedError in virtual functions.\nIf init are important in parent's classes, then you have to call them. As eryksun said, use the super builtin function to call the parent's initializers ...
[ 2 ]
[]
[]
[ "design_patterns", "mixins", "python" ]
stackoverflow_0007003284_design_patterns_mixins_python.txt
Q: How can I exclude a certain wiki page from appearing in the trac search? We use the trac project management software. I want to be able to prevent certain wiki pages appearing in the trac search results. For example, some developers keep timesheets in the wiki and they contain a lot of keywords but never much usef...
How can I exclude a certain wiki page from appearing in the trac search?
We use the trac project management software. I want to be able to prevent certain wiki pages appearing in the trac search results. For example, some developers keep timesheets in the wiki and they contain a lot of keywords but never much useful documentation. Is there a way to configure trac to ignore a list of wiki p...
[ "You can't do that out-of-the-box, and I don't know of a plugin that allows to do that. You would have to write a small plugin that monkey-patches the method get_search_results() of WikiModule (see here) and filters the results (probably by matching the URL, which would be a bit of a hack).\n" ]
[ 2 ]
[]
[]
[ "python", "trac", "wiki" ]
stackoverflow_0007023016_python_trac_wiki.txt
Q: How can I group equivalent items together in a Python list? I have a list like x = [2, 2, 1, 1, 1, 1, 1, 1] I would like to put the repeated numbers together like [[2,2],[1,1,1,1,1,1]] A: [list(g) for k, g in itertools.groupby(iterable)] This is exactly what itertools.groupby is for. If you want nonconsecut...
How can I group equivalent items together in a Python list?
I have a list like x = [2, 2, 1, 1, 1, 1, 1, 1] I would like to put the repeated numbers together like [[2,2],[1,1,1,1,1,1]]
[ "[list(g) for k, g in itertools.groupby(iterable)]\n\nThis is exactly what itertools.groupby is for.\nIf you want nonconsecutive numbers grouped, like in the comment by @Michal,\n[list(g) for k, g in itertools.groupby(sorted(iterable))]\n\n" ]
[ 27 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007025581_list_python.txt
Q: python locale for gtk does not work on windows I have python 2.7 and pygtk. I am trying to set locale language for gtk in my application but no luck. My windows is in slovak language and I would like to have button labels in my app in english. How to solve it? I tried this but no luck (all labels are still in slov...
python locale for gtk does not work on windows
I have python 2.7 and pygtk. I am trying to set locale language for gtk in my application but no luck. My windows is in slovak language and I would like to have button labels in my app in english. How to solve it? I tried this but no luck (all labels are still in slovak): import os os.environ['LANGUAGE'] = 'en_US' #t...
[ "This is becoming a common question these days and should probably become a PyGTK FAQ.\nSee for example this PyGTK bug report\nIn short, there's a whole lot of details you're missing. For example:\n1) Starting with Python 2.4, on Windows, assigning values to os.environ only\nchanges the copy of the environment vari...
[ 4 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0007013500_gtk_pygtk_python.txt
Q: In python, if a module calls upon another module's functions, is it possible for the function to access the first module's filepath? Without passing it as a parameter... Ex. In test1.py: def function(): print (?????) and in test2.py import test1 test1.function() Is it possible to write ????? so running test...
In python, if a module calls upon another module's functions, is it possible for the function to access the first module's filepath?
Without passing it as a parameter... Ex. In test1.py: def function(): print (?????) and in test2.py import test1 test1.function() Is it possible to write ????? so running test2.py prints out 'test2.py' or the full filepath? __file__ would print out 'test1.py'.
[ "This can be achieved using sys._getframe():\n% cat test1.py\n#!/usr/bin/env python\n\nimport sys\n\ndef function():\n print 'Called from within:', sys._getframe().f_back.f_code.co_filename\n\ntest2.py looks much like yours but with the the import fixed:\n% cat test2.py\n#!/usr/bin/env python\n\nimport test1\n\n...
[ 3, 1, 0, 0 ]
[]
[]
[ "filepath", "module", "python" ]
stackoverflow_0007025538_filepath_module_python.txt
Q: Check status of process and restart process if unresponsive/stopped - Python I'm trying to build a small process monitoring script on Windows Server 2008. The script would: find target process check status (running/unresponsive/stopped) kill and restart process if unresponsive/stopped Any suggestion on the best ...
Check status of process and restart process if unresponsive/stopped - Python
I'm trying to build a small process monitoring script on Windows Server 2008. The script would: find target process check status (running/unresponsive/stopped) kill and restart process if unresponsive/stopped Any suggestion on the best way to implement this?
[ "Naming a process 'unresponsive' is quite subjective. It might be waiting for data and seem unresponsive, or it might be in a (endless) loop and seem unresponsive.\nUsually, what people do is implement hartbeat. That is - have a very tiny socket server in the process where other processes can connect and send ping ...
[ 1 ]
[]
[]
[ "operating_system", "process", "python", "windows", "windows_services" ]
stackoverflow_0007024626_operating_system_process_python_windows_windows_services.txt
Q: Padding a list in python with particular value Possible Duplicate: Some built-in to pad a list in python I have a method that will return a list (instance variable) with 4 elements. Another method is used to assign values to the list. But at the moment I can't guarantee that the list has 4 elements when it's ask...
Padding a list in python with particular value
Possible Duplicate: Some built-in to pad a list in python I have a method that will return a list (instance variable) with 4 elements. Another method is used to assign values to the list. But at the moment I can't guarantee that the list has 4 elements when it's asked for, so I want to fill it up with 0's. Is there ...
[ "self.myList.extend([0] * (4 - len(self.myList)))\n\nThis works when padding with integers. Don't do it with mutable objects.\nAnother possibility would be:\nself.myList = (self.myList + [0] * 4)[:4]\n\n", ">>> out = [0,0,0,0] # the \"template\" \n>>> x = [1,2]\n>>> out[:len(x)] = x \n>>> print out\n[1, 2, 0, 0...
[ 39, 10, 6, 3, 3, 2, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007026131_list_python.txt
Q: Modelling many-to-many with relation data in Google App Engine I have two models in my application, Transaction and Person, with a many-to-many relationship. There are persons included in each Transaction. For each person, there is also a amount connected to each Transaction the Person is connected to. Therefor I ...
Modelling many-to-many with relation data in Google App Engine
I have two models in my application, Transaction and Person, with a many-to-many relationship. There are persons included in each Transaction. For each person, there is also a amount connected to each Transaction the Person is connected to. Therefor I need to model a many-to-many relationship with relation data. Google...
[ "I suspect you're solving the wrong problem. The intermediate association entity is a good approach. The problem you have is that summaries take a long time to compute; You should be concerned more about that; \nThe preferred approach is to calculate the summary data ahead of time. \nIn the specific case of \"T...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007026219_google_app_engine_google_cloud_datastore_python.txt
Q: How to use my own locale for pyGTK? I'm writing a soft using pyGTK. I'd like to know how to force pyGTK to use my own *.mo files for GTK. In fact my problem is, I code under Linux but I want to distribute it under Windows. To get a Windows executable, I use cx_Freeze, I can include my own gettext for my texts and ...
How to use my own locale for pyGTK?
I'm writing a soft using pyGTK. I'd like to know how to force pyGTK to use my own *.mo files for GTK. In fact my problem is, I code under Linux but I want to distribute it under Windows. To get a Windows executable, I use cx_Freeze, I can include my own gettext for my texts and it's work well, but I want to include pyG...
[]
[]
[ "You're initializing Python's gettext correctly, but not libintl which is used\nby GTK+ and friends. You could take a look at my elib.intl module to see how\nthat's done.\n" ]
[ -1 ]
[ "gettext", "gtk2", "pygtk", "python" ]
stackoverflow_0006412850_gettext_gtk2_pygtk_python.txt
Q: python metaclasses at module level I read What is a metaclass in Python? and I tried to replicate the upper metaclass from the example and found that this doesn't work in all cases: def upper(cls_name, cls_parents, cls_attr): """ Make all class attributes uppper case """ ...
python metaclasses at module level
I read What is a metaclass in Python? and I tried to replicate the upper metaclass from the example and found that this doesn't work in all cases: def upper(cls_name, cls_parents, cls_attr): """ Make all class attributes uppper case """ attrs ...
[ "The module level metaclass isn't really \"module level\", it has to do with how class initialization worked. The class creation would look for the variable \"__metaclass__\" when creating the class, and if it wasn't in the local environment it would look in the global. Hence, if you had a \"module level\" __metacl...
[ 12, 4 ]
[]
[]
[ "metaclass", "python", "python_3.x" ]
stackoverflow_0007023932_metaclass_python_python_3.x.txt
Q: What is the best way to copy a list of lists of strings in Python? I'm new to Python, and to copy a matrix to another, I'm doing: import copy matrix1.append(copy.deepcopy(matrix2)) Is there a better, maybe a shorter, way? --update: The types are lists of strings, like [["asdf", "fdsa"], ["zxcv", "vcxz"]], and I w...
What is the best way to copy a list of lists of strings in Python?
I'm new to Python, and to copy a matrix to another, I'm doing: import copy matrix1.append(copy.deepcopy(matrix2)) Is there a better, maybe a shorter, way? --update: The types are lists of strings, like [["asdf", "fdsa"], ["zxcv", "vcxz"]], and I want to add this to my other list, but I don't want them to be the same r...
[ "\nAre you sure you need to copy anything? The strong majority of the time, it's best not to copy data like this. Doing so implies you're going to mutate the copy. Very often it's possible just to make a new thing rather than to mutate a copy, which ends up being less errorprone as your program develops. What were ...
[ 2, 1, 0 ]
[]
[]
[ "matrix", "python" ]
stackoverflow_0007025868_matrix_python.txt
Q: SQLite no return type in Python I am trying to find a way to know whether or not some value was returned from an SQLite query when using python. conn = sqlite3.connect('/path/to/database.db') cursor=conn.cursor() t=(value,) cursor.execute("select field from table where other_field = ?", t) returnObject = cursor.fe...
SQLite no return type in Python
I am trying to find a way to know whether or not some value was returned from an SQLite query when using python. conn = sqlite3.connect('/path/to/database.db') cursor=conn.cursor() t=(value,) cursor.execute("select field from table where other_field = ?", t) returnObject = cursor.fetchone()[0] If the table does contai...
[ "You have a couple options, depending on your preferences. \nOption 1: check the value of returnObject before using it. \nconn = sqlite3.connect('/path/to/database.db')\ncursor=conn.cursor()\nt=(value,)\ncursor.execute(\"select field from table where other_field = ?\", t)\nreturnObject = cursor.fetchone()\nif retu...
[ 6 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0007026911_python_sqlite.txt
Q: Get variables from a settings.py file in a Jinja template with Flask Say I have settings.py file with a bunch of constants (maybe more, in the future). How do I access those variables in a Jinja template? A: Flask automatically includes your application's config in the standard context. So if you used app.config...
Get variables from a settings.py file in a Jinja template with Flask
Say I have settings.py file with a bunch of constants (maybe more, in the future). How do I access those variables in a Jinja template?
[ "Flask automatically includes your application's config in the standard context. So if you used app.config.from_envvar or app.config.from_pyfile to pull in the values from your settings file, you already have access to those values in your Jinja templates (e.g., {{ config.someconst }}).\n", "You need to define a ...
[ 18, 7 ]
[]
[]
[ "flask", "jinja2", "python" ]
stackoverflow_0007017990_flask_jinja2_python.txt
Q: Event lists in Python I'm looking for an efficient way of solving a particular problem in Python. I have a stream of events arriving each with an associated timestamp. Conceptually I add these events to the end of a time ordered list and do some processing on them, making some changes to various counts and average...
Event lists in Python
I'm looking for an efficient way of solving a particular problem in Python. I have a stream of events arriving each with an associated timestamp. Conceptually I add these events to the end of a time ordered list and do some processing on them, making some changes to various counts and averages (depending on the type o...
[ "You can use three deques but like this:\n\nthe original one for 1 minutes interval (instead of 15)\nanother one for 5 minutes, will receive events from the previous deque\nanother one for 15 minutes, will receive events from the previous deque.\n\nThis way, no duplicates and no indexing is needed. And this can be ...
[ 2 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0007026934_data_structures_python.txt
Q: Python: name variables with a loop for our ansys software i would like to generate a script to automate certain things. when i record my actions I get the following template1 = GetTemplate( TemplateName="Random Vibration", Solver="ANSYS") system1 = GetSystem(Name="Modal (ANSYS)") component1 = system1.GetCo...
Python: name variables with a loop
for our ansys software i would like to generate a script to automate certain things. when i record my actions I get the following template1 = GetTemplate( TemplateName="Random Vibration", Solver="ANSYS") system1 = GetSystem(Name="Modal (ANSYS)") component1 = system1.GetComponent(Name="Engineering Data") compone...
[ "I'm not sure I fully undesrtood your question but from your code naming I think this is what you want:\nsystems1 = []\nsystems2 = []\ntemplates = []\ncomponents1 = []\ncomponents2 = []\ncomponents3 = []\ncomponents4 = []\nfor i in range(72): \n template = GetTemplate(\n TemplateName=\"Random Vibration...
[ 0 ]
[]
[]
[ "loops", "python", "variables" ]
stackoverflow_0007026953_loops_python_variables.txt
Q: return to the top of a loop At print("you dont have that many cards!") i want the while loop to start over from print("how many cards in heap no:", n, end="") instead of breaking. How can this be done? y = [] def cardHeaps(): global cards n = 1 while int(cards) > 0: print("how many cards in he...
return to the top of a loop
At print("you dont have that many cards!") i want the while loop to start over from print("how many cards in heap no:", n, end="") instead of breaking. How can this be done? y = [] def cardHeaps(): global cards n = 1 while int(cards) > 0: print("how many cards in heap no:", n, end="") x = i...
[ "You have to use continue instead of break.\nPython docs on continue\n", "Use continue instead of break.\n" ]
[ 17, 12 ]
[]
[]
[ "python" ]
stackoverflow_0007027355_python.txt
Q: Is this a legal use of global variables in Python? I've written a small script in Python for simple text manipulation, consisting of a bunch of functions. Some of these functions contain magic numbers or string constants. Is it okay to store them in global variables? I do not intent to modify them, they are more l...
Is this a legal use of global variables in Python?
I've written a small script in Python for simple text manipulation, consisting of a bunch of functions. Some of these functions contain magic numbers or string constants. Is it okay to store them in global variables? I do not intent to modify them, they are more like constants.
[ "Yes, it's legimitate use. You will encounter that in many good Python codes. Just note that the convention is to write the names of such \"constants\" in UPPER_CASE.\n", "This is the preferred way of dealing with constants. At the top of the file you can easily modify them. \nYou could also move them to a seper...
[ 6, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007027323_python.txt
Q: Porting from platform.popen to subprocess.Popen? I have a bunch of code that uses the old deprecated popen from the platform package. Since this is deprecated, I will be moving this to the subprocess package. What is the equivalent statement to popen("some_command")? Is there a reason that popen was deprecated...
Porting from platform.popen to subprocess.Popen?
I have a bunch of code that uses the old deprecated popen from the platform package. Since this is deprecated, I will be moving this to the subprocess package. What is the equivalent statement to popen("some_command")? Is there a reason that popen was deprecated?
[ "\nplatform.popen has not been deprecated as best as I can tell. However, this is a low-level function that you should not make use of for flexibility and portability reasons.\nLots of other process-launching things were deprecated and some removed in Python 3. Many, many attempts at doing this well were made in th...
[ 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0007025833_python_subprocess.txt
Q: Trouble making a table with HTML.py in python I'm trying to make a table showing different values in each cell, and depending on the value of cell, have a different bgcolor. So I have managed to do this successfully with one column by using a simple loop, but I cannot figure out a way to do this with multiple colu...
Trouble making a table with HTML.py in python
I'm trying to make a table showing different values in each cell, and depending on the value of cell, have a different bgcolor. So I have managed to do this successfully with one column by using a simple loop, but I cannot figure out a way to do this with multiple columns holding the same pattern. I am not very experie...
[ "This\nt.rows.append([colored_result])\n\nappends a complete row of one cell.\nThis\nt.rows.append([colored_result, colored_result])\n\nwould append this cell twice, hence creating a row of 2 cells (identical).\nThis\ncolored_result = HTML.TableCell(new, bgcolor=color)\ncolored_result2 = HTML.TableCell(new, bgcolor...
[ 1 ]
[]
[]
[ "html", "python" ]
stackoverflow_0007027243_html_python.txt
Q: For items in a dictonary, split the name of one item, add and remove some info python I have a dictionary with this info: x = {Country:{City:Population},.....} but City name is now like: Country_City_Neighbourhood_Population (for some reason). I need to remove all the information and just keep the City and Neigh...
For items in a dictonary, split the name of one item, add and remove some info python
I have a dictionary with this info: x = {Country:{City:Population},.....} but City name is now like: Country_City_Neighbourhood_Population (for some reason). I need to remove all the information and just keep the City and Neighbourhood like this: CityNeighbourhood. I did this: for country in x: for city, pop in x[co...
[ "\"\".join(city.split(\"_\")[1:-1])\n\n\ncity.split(\"_\") gives a list of the words in \"city\" separated by \"_\".\n[1:-1] slices the list to remove the first and last elements\n\"\".join connects them back together, with the empty string in between\n\n", "Try something like this:\nfor country in x:\n for ci...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007027434_python.txt
Q: How do I format code neatly in HTML/CSS ? I especially want to use the numerical circle callouts, with Python Docutils if I can see: http://diveintopython.net/native_data_types/lists.html#d0e5623 I have a website with code examples on it, generated through docutils, and the CSS is always not quite right. I would l...
How do I format code neatly in HTML/CSS ? I especially want to use the numerical circle callouts, with Python Docutils if I can
see: http://diveintopython.net/native_data_types/lists.html#d0e5623 I have a website with code examples on it, generated through docutils, and the CSS is always not quite right. I would like to know if there is best practise CSS for displaying code (ie can it handle wrap arounds, long lines, any chance of getting col...
[ "You can't do syntax highlighting with CSS alone. You need the various parts of the code to be marked up; you can do that on the server if you are using dynamic pages, or you can use JavaScript on the client. Here is a comparison of a few JavaScript syntax highlighters.\nThe circled numbers are images in the site y...
[ 0 ]
[]
[]
[ "css", "docutils", "python" ]
stackoverflow_0007027342_css_docutils_python.txt
Q: Best way to launch a process and block until it is finished I'm told subprocess.Popen does not block, so the process runs in the background and your python program does not wait until it has finished. However, this is not what I want. I'm having my program call into an external python program, which I have no con...
Best way to launch a process and block until it is finished
I'm told subprocess.Popen does not block, so the process runs in the background and your python program does not wait until it has finished. However, this is not what I want. I'm having my program call into an external python program, which I have no control over. It does not return any return codes, just runs, opera...
[ "Call communicate or wait on the subprocess.\n", "Use the call method from subprocess.\n\nsubprocess.call(*popenargs, **kwargs)\n Run command with arguments. Wait for command to complete, then\n return the returncode attribute.\n\nsee → http://docs.python.org/library/subprocess.html#subprocess.call\n", "Best ...
[ 5, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007027809_python.txt
Q: Python: If-elses inside a class "init"; does this work? I'm yet another programming newb going through "Learn Python the Hard Way" and have come up against something that I don't fully understand. I'll preface this by saying that while I'm really enjoying his lesson plan, one unfortunate side-effect seems to be th...
Python: If-elses inside a class "init"; does this work?
I'm yet another programming newb going through "Learn Python the Hard Way" and have come up against something that I don't fully understand. I'll preface this by saying that while I'm really enjoying his lesson plan, one unfortunate side-effect seems to be that I don't understand a lot of the technical talk involved in...
[ "What happens when you have 100 rooms? Will your play function have 100 if statements, just to set the room you are in? (set it again, basically)\nIt would probably be much better to just set the game state directly to whatever you want when it changes.\nedit: I just re-read what you have an now the problem seems k...
[ 1 ]
[ "I suppose by this:\n if not 'principal' in game.goals:\n\nyou meant this:\n if 'principal' not in game.goals:\n\nor this:\n if not ('principal' in game.goals):\n\nnot 'somestring' is False, because non-empty string is always True and you don't have False in your goals, so it always evaluates to False.\n\n...
[ -1 ]
[ "class", "if_statement", "python" ]
stackoverflow_0007028136_class_if_statement_python.txt
Q: How to ensure there are no pdb calls out of debugging configuration? What do you suggest to get rid of pdb calls on production software? In my case, I'm developing a django website. I don't know if I should: Monkey patch pdb from settings.py (dependding on DEBUG boolean). Make a pdb wrapper for our project whic...
How to ensure there are no pdb calls out of debugging configuration?
What do you suggest to get rid of pdb calls on production software? In my case, I'm developing a django website. I don't know if I should: Monkey patch pdb from settings.py (dependding on DEBUG boolean). Make a pdb wrapper for our project which expose set_trace or print basic log if DEBUG = True Dissalow comitting b...
[ "The third one. You have to enforce some commit rules. For example, run a serie of tests before a commit, etc. This way, developpers have a simple way to check if a pdb break remain. If someone commit a set_trace, he has to bake a cake for the rest of the team.\nThis works fine in my company :-)\nedit: you may pres...
[ 2, 1, 0 ]
[]
[]
[ "django", "git", "pdb", "python" ]
stackoverflow_0007027803_django_git_pdb_python.txt
Q: How to use Alias as well as Redirect together on same url I have two projects on same IP. I want /www/site/fortis/ served by /projects/fortis and /www/site/myfood/ served by /projects/myfood, but I am not using DocumentRoot. My code is: Alias /myfood /opt/bitnami/projects/myfood/ <Directory /opt/bitnami/projects/...
How to use Alias as well as Redirect together on same url
I have two projects on same IP. I want /www/site/fortis/ served by /projects/fortis and /www/site/myfood/ served by /projects/myfood, but I am not using DocumentRoot. My code is: Alias /myfood /opt/bitnami/projects/myfood/ <Directory /opt/bitnami/projects/myfood/> Order allow,deny Allow from all </Directory> Alias /...
[ "For the more complex tasks like this, I always find myself falling back to mod_rewrite. I don't have a setup at hand where I can pull together a config for you, but it would be something along the lines of:\nRewriteEngine On\n\nRewriteRule ^/projects/fortis/(.*) /www/site/fortis/$1 [NC,R,N]\nRewriteRule ^/p...
[ 0 ]
[]
[]
[ "amazon_web_services", "apache2", "django", "python" ]
stackoverflow_0007028106_amazon_web_services_apache2_django_python.txt
Q: How to Separate Output Data Here is my code: #------------------------------------------------------------------------------- # Name: Mocha Rotoscoping Via Blender # Purpose: Make rotoscoping more efficient # # Author: Jeff Owens # # Created: 11/07/2011 # Copyright: (c) jeff.owens 2011 # Lice...
How to Separate Output Data
Here is my code: #------------------------------------------------------------------------------- # Name: Mocha Rotoscoping Via Blender # Purpose: Make rotoscoping more efficient # # Author: Jeff Owens # # Created: 11/07/2011 # Copyright: (c) jeff.owens 2011 # Licence: Grasshorse #------------...
[ "The points are tuples, so it's rather simple.\nYou can unpack them first (where p is a point):\n>>> x, y, *data = p\n>>> x\n0.793803\n>>> y\n0.136326\n>>> data\n[0, 0.5, 0]\n\nOr you can index into them:\n>>> p[0]\n0.793803\n\nOr you can go crazy with string formatting:\n>>> str.format(\"x{0[0]} y{0[1]}\", p)\n'x0...
[ 3 ]
[]
[]
[ "parsing", "pyparsing", "python", "regex" ]
stackoverflow_0007028435_parsing_pyparsing_python_regex.txt
Q: Extending new user creation form, Django I am trying to work on adding a location field to the User Profile and associate it with a user. I currently have something like this: This is my models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_sa...
Extending new user creation form, Django
I am trying to work on adding a location field to the User Profile and associate it with a user. I currently have something like this: This is my models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): u...
[ "You may use Model Inheritance for that, which do similar things for you...\nModel Inheritance and proxy models...\n", "Have you tried to use a simple inline for the profile? Yes, it will be shown at the bottom, but otherwise it would work.\nfrom django.contrib import admin\nfrom django.contrib.auth.models import...
[ 3, 2 ]
[]
[]
[ "django", "model", "python" ]
stackoverflow_0007027985_django_model_python.txt
Q: formating string in a particular order I am trying to make a simple layout like this: --------- - - - ABC - - - --------- And I have tried two ways but failed: 1st method: Put the cursor at the right position, but I cannot seem to place the second vertical line where I want it: # making first ho...
formating string in a particular order
I am trying to make a simple layout like this: --------- - - - ABC - - - --------- And I have tried two ways but failed: 1st method: Put the cursor at the right position, but I cannot seem to place the second vertical line where I want it: # making first horizontal linefrom position 00 string_lin...
[ ">>> foo = 'ABC'\n>>> head = ['-' * (len(foo)+6), '-%s-' % (' '*(len(foo)+4))]\n>>> print '\\n'.join(head + ['- %s -' % foo] + head[::-1])\n---------\n- -\n- ABC -\n- -\n---------\n\n" ]
[ 3 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007028547_python_string.txt
Q: Why a procedure is so much faster when put into a function? Here is what I did, I created 2 procedures, one in a function and one in the python file itself. The one on the python file itself run almost 2 times slower even if it's exactly the same. WHY ? Bellow is an example with 2 procedures that are just loops o...
Why a procedure is so much faster when put into a function?
Here is what I did, I created 2 procedures, one in a function and one in the python file itself. The one on the python file itself run almost 2 times slower even if it's exactly the same. WHY ? Bellow is an example with 2 procedures that are just loops on P element I have the following python file : from time import *...
[ "The only significant difference is that the version in the function is only updating the local variable for that function, whereas the version not in a function is updating a global variable k.\nAs mentioned here:\n\nThe final speedup available to us for the non-map version of the for loop is to use local variable...
[ 14 ]
[]
[]
[ "local_variables", "performance", "python" ]
stackoverflow_0007028770_local_variables_performance_python.txt
Q: Using eval() with Undefined Variables I want to create a Python script that takes in a string representation of a dictionary and outputs a list of tuples representing the items of the dictionary. The rub is, I want it to take in variables that have not been defined. An example illustrates this best: Input: {'test'...
Using eval() with Undefined Variables
I want to create a Python script that takes in a string representation of a dictionary and outputs a list of tuples representing the items of the dictionary. The rub is, I want it to take in variables that have not been defined. An example illustrates this best: Input: {'test': test} Output: [('test': test)] I've creat...
[ "I would use the ast module, but not literal_eval. Walk the tree, when you find a variable reference, just insert the name of the variable into the output.\n", "You can trick eval into giving you what you want:\nclass Reflector(object):\n def __getitem__(self, name):\n return name\n\ns = \"{'test':test...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007027312_python.txt
Q: Django : Long Object Attribute Error This is my first introduction to 'Long' Objects, and I haven't found much in the Django docs on Querysets & long objects. I am trying to join two different queries into a list which I can email each user. Two questions - is this the proper way to join these queries? If so, how...
Django : Long Object Attribute Error
This is my first introduction to 'Long' Objects, and I haven't found much in the Django docs on Querysets & long objects. I am trying to join two different queries into a list which I can email each user. Two questions - is this the proper way to join these queries? If so, how do I access the profile.user.email attrib...
[ "You are adding to the list 'long' objects (they are just numbers) instead of actual User instances:\nemail_list.append(profile.user.id)\n\nit should be:\nemail_list.append(profile.user)\n\n" ]
[ 4 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0007028867_django_django_views_python.txt
Q: Adding Keyboard input to Directories I want to create a directory but I also want to add Keyboard input. Specifically, I want the user to chose the directory name, and location, and then it displays the name and location that the user entered. Directory: #!/usr/bin/python import os # Create a directory that the u...
Adding Keyboard input to Directories
I want to create a directory but I also want to add Keyboard input. Specifically, I want the user to chose the directory name, and location, and then it displays the name and location that the user entered. Directory: #!/usr/bin/python import os # Create a directory that the user choses when and where os.mkdir() Keyb...
[ ">>> import os\n>>> os.curdir\n'.'\n>>> filename = raw_input('Filename:')\nFilename:mydir\n>>> os.mkdir(filename)\n>>> os.listdir(os.curdir)\n['mydir']\n\n" ]
[ 1 ]
[]
[]
[ "input", "python" ]
stackoverflow_0007028447_input_python.txt
Q: Python - if directory contains file beginning with...move file I need to create a script in Python which will look to a directory (which contains only one file) and move it if the file is not for the current day. For reference the file has a suffix which relates to the current day (myfile_030811.xls) Does anyone h...
Python - if directory contains file beginning with...move file
I need to create a script in Python which will look to a directory (which contains only one file) and move it if the file is not for the current day. For reference the file has a suffix which relates to the current day (myfile_030811.xls) Does anyone have any ideas for this?
[ "try this? This assumes that a directory called 'archived' is present under the current directory. you might want to tweak it to suit your needs. Also this assumes that all files under your directory have a name of the structure _ddmmyy. format. It won't work otherwise\nfrom stat import *\nimport os\nimport time\ni...
[ 2, 0 ]
[]
[]
[ "directory", "if_statement", "move", "python" ]
stackoverflow_0007028609_directory_if_statement_move_python.txt
Q: What is the Problem with iteritems() in OrderedDict() in python? Here is my OrderedDict dictionary: >>> dic = OrderedDict([('16-17,1,5,BUY,BUY,-6,9', 10), ('19-20,1,1,BUY,BUY,-1,1',1)]) >>> dic OrderedDict([('16-17,1,5,BUY,BUY,-6,9', 10), ('19-20,1,1,BUY,BUY,-1,1', 11)]) >>> for k,v in dic.iteritems(): .....
What is the Problem with iteritems() in OrderedDict() in python?
Here is my OrderedDict dictionary: >>> dic = OrderedDict([('16-17,1,5,BUY,BUY,-6,9', 10), ('19-20,1,1,BUY,BUY,-1,1',1)]) >>> dic OrderedDict([('16-17,1,5,BUY,BUY,-6,9', 10), ('19-20,1,1,BUY,BUY,-1,1', 11)]) >>> for k,v in dic.iteritems(): ... print k ... k1 = k.split(',') ... print k1 ... pr...
[ "Because append returns nothing.\nprint prints the return value of k1.append(v), but there is no return value from k1.append(v)\n", "It's not a problem with OrderedDict.\nappend returns None but modifies the list in place. So you could replace the line with\nk1.append(v)\nprint k1\n\n" ]
[ 7, 2 ]
[]
[]
[ "python", "python_2.6" ]
stackoverflow_0007029264_python_python_2.6.txt
Q: How can I use bcrypt/scrypt on appengine for Python? I want make an authentication system for my app along the lines of SUAS, except instead of using SHA256 for hashing passwords I'd like to use bcrypt or scrypt. Unfortunately both py-bcrypt and scrypt for python use native c, which is unsupported by GAE. Any way ...
How can I use bcrypt/scrypt on appengine for Python?
I want make an authentication system for my app along the lines of SUAS, except instead of using SHA256 for hashing passwords I'd like to use bcrypt or scrypt. Unfortunately both py-bcrypt and scrypt for python use native c, which is unsupported by GAE. Any way around this?
[ "Scrypt and BCrypt are both extremely processor-intensive (by design). Because of this, I very much doubt any pure-python implementation is going to be fast enough to be secure - that is, be able to hash using a sufficient number of rounds within a reasonable amount of time. \nI can personally attest to this, I've...
[ 24, 8 ]
[]
[]
[ "authentication", "encryption", "google_app_engine", "python" ]
stackoverflow_0007027196_authentication_encryption_google_app_engine_python.txt
Q: Django problematic view I have this Django generic view: def post_list(request, page=0, paginate_by=1, **kwargs): page_size = getattr(settings,'BLOG_PAGESIZE', paginate_by) return list_detail.object_list( request, queryset=Post.objects.published(), paginate_by=page_size, page=page, **kwargs ) p...
Django problematic view
I have this Django generic view: def post_list(request, page=0, paginate_by=1, **kwargs): page_size = getattr(settings,'BLOG_PAGESIZE', paginate_by) return list_detail.object_list( request, queryset=Post.objects.published(), paginate_by=page_size, page=page, **kwargs ) post_list.__doc__ = list_detai...
[ "Pass the year in via extra_context, for the current year:\nfrom datetime import datetime\nyear = datetime.now().year\n\n", "You core problem is using generic views - http://stdout.be/2010/05/25/generic-views-suck/\ndef post_list(request, page=0, paginate_by=1, **kwargs):\n page_size = getattr(settings,'BLOG_P...
[ 2, 0 ]
[]
[]
[ "django", "django_generic_views", "django_templates", "django_views", "python" ]
stackoverflow_0007023905_django_django_generic_views_django_templates_django_views_python.txt
Q: How can I send python code to another machine to be executed? I'm building a test app on AWS. I have a 'master' machine that owns the application. I'd like, upon occasion, to be able to offload processing to some on-demand slave machines. Assuming an instantiated slave, with the bare minimum of required software (...
How can I send python code to another machine to be executed?
I'm building a test app on AWS. I have a 'master' machine that owns the application. I'd like, upon occasion, to be able to offload processing to some on-demand slave machines. Assuming an instantiated slave, with the bare minimum of required software (not including my main app), how can I 'send' functional units of Py...
[ "I've run into this problem several times in various flavors. \nOption 1 - eval()\nWhen I want to just hack something out quickly, I use eval() or one of it's cousins in the stdlib. Transfer the source to your master, then compile and eval:\nsrc = getSourceFromMaster()\nobj = compile(src, \"master.py\", \"exec\")\...
[ 4, 1, 0, 0 ]
[]
[]
[ "amazon_web_services", "python" ]
stackoverflow_0007029157_amazon_web_services_python.txt
Q: PYTHON problem with negative decimals I have a list of negative floats. I want to make a histogram with them. As far as I know, Python can't do operations with negative numbers. Is this correct? The list is like [-0.2923998, -1.2394875, -0.23086493, etc.]. I'm trying to find the maximum and minimum number so I can...
PYTHON problem with negative decimals
I have a list of negative floats. I want to make a histogram with them. As far as I know, Python can't do operations with negative numbers. Is this correct? The list is like [-0.2923998, -1.2394875, -0.23086493, etc.]. I'm trying to find the maximum and minimum number so I can find out what the range is. My code is giv...
[ "The results of split() are a list of split values, which is probably why you are getting that error.\nFor example, if you do '-0.2'.split(), you get back a list with a single value ['-0.2']. \nEDIT: Aha! With your input file provided, it looks like this is the problem: -0.733029194040.765257900121. I think you mea...
[ 6, 1 ]
[]
[]
[ "floating_point", "list", "max", "min", "python" ]
stackoverflow_0007029716_floating_point_list_max_min_python.txt
Q: Get Contents of in beautiful soup I am trying to get the contents of a specific <td> tag in a document. Currently my code looks like this For row in rows: data = row.findAll('td') for col in data: if col.string == 'Address': address = col.findNext('td') print address The print address...
Get Contents of in beautiful soup
I am trying to get the contents of a specific <td> tag in a document. Currently my code looks like this For row in rows: data = row.findAll('td') for col in data: if col.string == 'Address': address = col.findNext('td') print address The print address on console reveals this: <td> Victoria...
[ "Use the Tag.getText() method\ndata = row.findAll('td')\n for col in data:\n if col.string == 'Address':\n address = col.findNext('td')\n print address.getText()\n\nEdit: that gets all the text, not just before the <br>. Try try this instead\ndata = row.findAll('td')\n for col in data:\n if col.st...
[ 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0007027968_beautifulsoup_python.txt
Q: telling django to use an integer as a foreign key on demand I'm new to Django and currently defining an existing database scheme as a Django model. I have a central repository to store values like: (some_qualifier_id_1, some_qualifier_id_2, measure_id, value) The value is database-wise an integer. It can howeve...
telling django to use an integer as a foreign key on demand
I'm new to Django and currently defining an existing database scheme as a Django model. I have a central repository to store values like: (some_qualifier_id_1, some_qualifier_id_2, measure_id, value) The value is database-wise an integer. It can however refer to categorical data, in which case I want to link it to a...
[ "If the measure_id value is semantically a foreign key, so each value must be an index for something in the measure table, then declare it as such, and everythin will come together alone.\nIf the measure_id value is not a foreign key, you can annotate your resultset on demand, using\nMyModel.objects.filter(**your_f...
[ 1 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0007029652_database_django_python.txt
Q: Python String stripping and splitting I'm working with image metadata and able to extract a string that looks like this Cube1[visible:true, mode:Normal]{r:Cube1.R, g:Cube1.G, b:Cube1.B, a:Cube1.A}, Ground[visible:true, mode:Normal]{r:Ground.R, g:Ground.G, b:Ground.B, a:Ground.A}, Cube3[visible:true, mode:Normal]{r...
Python String stripping and splitting
I'm working with image metadata and able to extract a string that looks like this Cube1[visible:true, mode:Normal]{r:Cube1.R, g:Cube1.G, b:Cube1.B, a:Cube1.A}, Ground[visible:true, mode:Normal]{r:Ground.R, g:Ground.G, b:Ground.B, a:Ground.A}, Cube3[visible:true, mode:Normal]{r:Cube3.R, g:Cube3.G, b:Cube3.B, a:Cube3.A},...
[ "If the data is indeed formated like that: \n import re\n i = [the listed string] \n names = [j.strip('[') for j in re.findall(\"\\w+\\[\\.*\", i)]\n\nOutput: \n['Cube1', 'Ground', 'Cube3', 'Cube4', 'Sphere', 'OilTank', 'Cube2']\n\n", "If you just need the left-most portion, I would use:\nname, _ = line....
[ 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0007030234_python_split_string.txt
Q: Neural network library for Python? Can anyone (preferably with actual experience of the recommended library), suggest a good ANN library for Python? [Edit] ideally, the library/framework supports more than the basic FF paradigm. I would like one that has (or allows you to build) other network types e.g. a SO netwo...
Neural network library for Python?
Can anyone (preferably with actual experience of the recommended library), suggest a good ANN library for Python? [Edit] ideally, the library/framework supports more than the basic FF paradigm. I would like one that has (or allows you to build) other network types e.g. a SO network for example
[ "If you don't need native Python library, considering using an established neural network library with Python bindings. For instance FANN (Fast Artificial Neural network Library) provides such binding.\nIf you explicitly need a library written in Python, I would suggest checking out Orange. Orange is an open sourc...
[ 4, 3, 1 ]
[]
[]
[ "neural_network", "python" ]
stackoverflow_0003889077_neural_network_python.txt
Q: Cannot Import GTK in Ubuntu Python 2.7 I'm trying to import GTK in Ubuntu Python 2.7, and I get the following error. PyGTK imports just fine. When I import gtk, I get the following error: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __c...
Cannot Import GTK in Ubuntu Python 2.7
I'm trying to import GTK in Ubuntu Python 2.7, and I get the following error. PyGTK imports just fine. When I import gtk, I get the following error: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__ return self.func(*args) File "/usr...
[ "This is a bug in idle. Looking at the last line of that error message:\nFile \"/usr/lib/python2.7/idlelib/PyShell.py\", line 64, in idle_showwarning\n lineno, file=file, line=line))\nTypeError: idle_formatwarning() got an unexpected keyword argument 'file'\n\nThis is saying that the warning.idle_showwarning me...
[ 2, 1 ]
[]
[]
[ "gtk", "pygtk", "python", "python_idle", "ubuntu" ]
stackoverflow_0007016625_gtk_pygtk_python_python_idle_ubuntu.txt
Q: How to transfer files in a python program using UDP sockets So, I've got a program consisting of two processes, that are often running on different machines. One is a display server, the other a controller. Right now they communicate using UDP Datagram sockets, since a missed packet only means a skipped frame, and...
How to transfer files in a python program using UDP sockets
So, I've got a program consisting of two processes, that are often running on different machines. One is a display server, the other a controller. Right now they communicate using UDP Datagram sockets, since a missed packet only means a skipped frame, and TCP sockets are too slow. These computers know each others' IP a...
[ "I would not use UDP for file transfer, period. It would be less complex to open TCP sockets on each end and roll your own file transfer protocol on top of it than to implement reliable transfer on top of UDP. \nSome management of filenames and permissions will be required if you really need to have a file at both ...
[ 2, 1 ]
[]
[]
[ "file_transfer", "networking", "python", "udp", "windows" ]
stackoverflow_0007030191_file_transfer_networking_python_udp_windows.txt
Q: Django: Clean unicode for UrlEncoding I am trying to take unicode and clean it to be used for URLs. Examples : "Bird's Milk" Cake OR Pão com Ovo In converting these, my goal is to make them as human readable as possible so, the urls following those examples would be - /birds-milk-cake/ or /pao-com-ovo/ To get t...
Django: Clean unicode for UrlEncoding
I am trying to take unicode and clean it to be used for URLs. Examples : "Bird's Milk" Cake OR Pão com Ovo In converting these, my goal is to make them as human readable as possible so, the urls following those examples would be - /birds-milk-cake/ or /pao-com-ovo/ To get the ASCII of the accented characters, title ...
[ "There is an old, unmaintained but working code that extends django.template.defaultfilters.slugify() by adding support for all characters you can imagine. If you need to support all kinds of languages then this may be a good solution. It's called slughifi.\n", ">>> from django.template.defaultfilters import slug...
[ 1, 0 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0007030429_character_encoding_python.txt
Q: App Engine + Webmaster Tools I've been trying for a while now to get my Python App Engine app onto the Chrome Web Store, however, when I try to upload, Google tells me I need to confirm that its my domain (I'm on an appspot.com domain). I have tried the first 3 methods (meta tag, file, and analytics) in several di...
App Engine + Webmaster Tools
I've been trying for a while now to get my Python App Engine app onto the Chrome Web Store, however, when I try to upload, Google tells me I need to confirm that its my domain (I'm on an appspot.com domain). I have tried the first 3 methods (meta tag, file, and analytics) in several different ways but they haven't work...
[ "When I go to http://book-tracker.appspot.com/ it asks me for my Google Account.\nTry disabling login required before trying activation.\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007030563_google_app_engine_python.txt
Q: Django - Admin custom field display & behavior Let's imagine this model: class ScribPart(models.Model): name = models.CharField(max_length=50, unique=True) text = models.TextField() I'd like to attach a specific class to the field text and call a specific js file. So that the admin page would be like: ... <sc...
Django - Admin custom field display & behavior
Let's imagine this model: class ScribPart(models.Model): name = models.CharField(max_length=50, unique=True) text = models.TextField() I'd like to attach a specific class to the field text and call a specific js file. So that the admin page would be like: ... <script type="text/javascript" src="/static/js/mymarkup...
[ "To insert a <script> in an admin page the simplest thing to do is:\nclass ScribPartAdmin(model.ModelAdmin):\n ...\n your normal stuff...\n ...\n\n class Media:\n js = ('/path/to/your/file.js',)\n\nModelAdmin media definitions documentation\nNow to add the class attribute to the textarea I think ...
[ 5, 2, 0 ]
[]
[]
[ "django", "django_admin", "django_widget", "html", "python" ]
stackoverflow_0007027752_django_django_admin_django_widget_html_python.txt
Q: Setting an axis in matplotlib I'm producing a graph in matplotlib and I would like to set the x-axis between 0-10000 but I do not want to change the y axis I want the graph to do that on it's own. Right now both axis are automatically generated. Here's an example: import matplotlib.pyplot as plt plt.plot([1,2,3,4...
Setting an axis in matplotlib
I'm producing a graph in matplotlib and I would like to set the x-axis between 0-10000 but I do not want to change the y axis I want the graph to do that on it's own. Right now both axis are automatically generated. Here's an example: import matplotlib.pyplot as plt plt.plot([1,2,3,4], [1,4,9,16], 'ro') plt.axis([0, 6...
[ "This seems to work fine for me: \nimport matplotlib.pyplot as plt\nplt.plot([1,2,3,4], [1,4,9,16], 'ro')\n# print plt.xlim()\nplt.xlim(0, 10000)\n# or \n# plt.xlim(xmin=0, xmax=10000)\n\n" ]
[ 25 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0007030807_matplotlib_python.txt
Q: Python: Regex to find but not include an alphanumeric Is there an regular expression to find, for example, ">ab" but do not include ">" in the result? I want to replace some strings using re.sub, and I want to find strings starting with ">" without remove the ">". A: You want a positive lookbehind assertion. See...
Python: Regex to find but not include an alphanumeric
Is there an regular expression to find, for example, ">ab" but do not include ">" in the result? I want to replace some strings using re.sub, and I want to find strings starting with ">" without remove the ">".
[ "You want a positive lookbehind assertion. See the docs.\nr'(?<=>)ab'\n\nIt needs to be a fixed length expression, it can't be a variable number of characters. Basically, do \nr'(?<=stringiwanttobebeforethematch)stringiwanttomatch'\n\nSo, an example:\nimport re\n\n# replace 'ab' with 'e' if it has '>' before it\n\...
[ 7, 6, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007030584_python_regex.txt
Q: Returning millisecond representation of datetime in python Using Python, I'm storing a date & time as datetime.datetime into GAE. Is there a way to get the value of the date time in milliseconds as opposed to the fully formatted string version? Based on the docs for datetime.datetime, I don't see any native method...
Returning millisecond representation of datetime in python
Using Python, I'm storing a date & time as datetime.datetime into GAE. Is there a way to get the value of the date time in milliseconds as opposed to the fully formatted string version? Based on the docs for datetime.datetime, I don't see any native methods on the date time class that does this. http://docs.python.org/...
[ "To get the seconds since the epoch:\ndate_time_secs = time.mktime(datetimeobj.timetuple())\n\nor for the whole thing in miliseconds\ndate_time_milis = time.mktime(datetimeobj.timetuple()) * 1000 + datetimeobj.microsecond / 1000\n\nor similar.\n" ]
[ 14 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007031031_google_app_engine_python.txt
Q: passing a variable form a loop to a conditional statement I have got this function in my program. def time(transcriptionFile) : ''' This function changes the time values in secs from the transcription file and keeps a list of start time and duration for each phoneme.''' with open("transcriptions.txt", "r")...
passing a variable form a loop to a conditional statement
I have got this function in my program. def time(transcriptionFile) : ''' This function changes the time values in secs from the transcription file and keeps a list of start time and duration for each phoneme.''' with open("transcriptions.txt", "r") as tFile : timeList = [] parameterList = [] ...
[ "If you want the line number then you should do \npoly = poly_coeff(start_time, end_time, lines)\n\nIf you want to use line number * frame\nthen do \npoly = poly_coeff(start_time, end_time, lines * frame)\n\nI dont know what you are trying to do with \nfor i in range(lines) : \n i = i * frame\n\n", "i is only ...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007031011_python.txt
Q: specifiying directory of Python module when calling it from C++ When trying to to import and execute a function within a Python module from a C++ executable, how can I pass in the directory where the module is located as a command line argument? A: Python honors PYTHONPATH environmental variable. It is a PATH li...
specifiying directory of Python module when calling it from C++
When trying to to import and execute a function within a Python module from a C++ executable, how can I pass in the directory where the module is located as a command line argument?
[ "Python honors PYTHONPATH environmental variable. It is a PATH like environmental variable specifying paths where Python loads modules.\nInside .py script PYTHONPATH can be accessed and updated through the sys.path variable.\nIf you can show more source code how you create Python interpreter more helpful answer can...
[ 2 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0007031077_c++_python.txt
Q: Python XML: write " instead of &quot I am using Python's xml minidom and all works well except that in text sequences it writes out &quot escape characters instead of ". This of course makes sense if a quote appears in a tag, but it bugs me in the text. How do I change this? A: looking at the source (Python 3.2 ...
Python XML: write " instead of &quot
I am using Python's xml minidom and all works well except that in text sequences it writes out &quot escape characters instead of ". This of course makes sense if a quote appears in a tag, but it bugs me in the text. How do I change this?
[ "looking at the source (Python 3.2 if it matters), this is hardcoded in the _write_data() function. you would need to modify the writexml() method of TextNode - either by subclassing it or simply editing it - so that it didn't call that method, but instead did something similar to escape only < and >.\nif you crea...
[ 5 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0007030463_minidom_python_xml.txt
Q: simplejson build hang On windows 7 32-bit I'm having trouble getting simplejson installed. I have fresh installs of Python 2.7.1 and setuptools 0.6c11. easy_install -v simplejson stalls when building ._speedups. Running simplejson-2.1.6\setup.py bdist_egg --dist-dir c:\users\user\appdata\ local\temp\easy_install-...
simplejson build hang
On windows 7 32-bit I'm having trouble getting simplejson installed. I have fresh installs of Python 2.7.1 and setuptools 0.6c11. easy_install -v simplejson stalls when building ._speedups. Running simplejson-2.1.6\setup.py bdist_egg --dist-dir c:\users\user\appdata\ local\temp\easy_install-jwfwpp\simplejson-2.1.6\egg...
[ "Don't install visual studio to a non-standard location. setuptools can't seem to find it. easy_install ended up being happy with MSVC either removed (in which case no speedups were compiled) or in the default installation path. \n", "I think that installing simplejson on 2.7 is not usefull as it is available as ...
[ 0, 0 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0007029402_python_setuptools.txt
Q: Is there a way to efficiently yield every file in a directory containing millions of files? I'm aware of os.listdir, but as far as I can gather, that gets all the filenames in a directory into memory, and then returns the list. What I want, is a way to yield a filename, work on it, and then yield the next one, wit...
Is there a way to efficiently yield every file in a directory containing millions of files?
I'm aware of os.listdir, but as far as I can gather, that gets all the filenames in a directory into memory, and then returns the list. What I want, is a way to yield a filename, work on it, and then yield the next one, without reading them all into memory. Is there any way to do this? I worry about the case where file...
[ "tl;dr <update>: As of Python 3.5 (currently in beta) just use os.scandir\n</update>\nAs I've written earlier, since \"iglob\" is just a facade for a real iterator, you will have to call low level system functions in order to get one at a time like you want. Fortunately, calling low level functions is doable from P...
[ 14, 10, 8, 8, 6, 1 ]
[]
[]
[ "file", "list", "python", "yield" ]
stackoverflow_0005090418_file_list_python_yield.txt