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: Defining a classpath for a Jython virtual environment I have installed Jython, a virtualenv named "jython-env" and have installed "bottle" for doing some web application development. I have to use some JAR files in this application for consumption by some Python code. I know I have to set the classpath which shoul...
Defining a classpath for a Jython virtual environment
I have installed Jython, a virtualenv named "jython-env" and have installed "bottle" for doing some web application development. I have to use some JAR files in this application for consumption by some Python code. I know I have to set the classpath which should include these JAR files. I tried setting the classpath us...
[ "jython -Dpython.path=/path/to/myjar.jar\n\nHere's another idea: you could use a .pth file. \nCreate a file - /path/to/jythonenv/Lib/site-packages/myjars.pth:\npath/to/jar1.jar\npath/to/jar2.jar\n\nWould also do the trick.\n", "I'd like to suggest jip for you. With jip, you can manage your Java dependencies and c...
[ 6, 3 ]
[]
[]
[ "bottle", "jython", "python", "virtualenv" ]
stackoverflow_0005839300_bottle_jython_python_virtualenv.txt
Q: How do I Access File Properties on Windows Vista with Python? The question is as simple as in the title, how do I access windows file properties like date-modifed, and more specifically tags, with Python? For a program I'm doing, I need to get lists of all the tags on various files in a particular folder, and I'm ...
How do I Access File Properties on Windows Vista with Python?
The question is as simple as in the title, how do I access windows file properties like date-modifed, and more specifically tags, with Python? For a program I'm doing, I need to get lists of all the tags on various files in a particular folder, and I'm not sure on how to do this. I have the win32 module, but I don't se...
[ "You can use os.stat with stat\nimport os\nimport stat\nimport time\n\ndef get_info(file_name):\n time_format = \"%m/%d/%Y %I:%M:%S %p\"\n file_stats = os.stat(file_name)\n modification_time = time.strftime(time_format,time.localtime(file_stats[stat.ST_MTIME]))\n access_time = time.strftime(time_format,...
[ 7, 3, 1, 1 ]
[]
[]
[ "properties", "python", "winapi", "windows_vista" ]
stackoverflow_0001484746_properties_python_winapi_windows_vista.txt
Q: How to clean up mysql out in python? Hi everyone in php when you fetch data from a mysql database and echo it out you get just whats in the selected row . Say i have a database named workers and a table called names and names have 5 names in it mic,joe,ashley,lee,and jean. Using SELECT names from names where name ...
How to clean up mysql out in python?
Hi everyone in php when you fetch data from a mysql database and echo it out you get just whats in the selected row . Say i have a database named workers and a table called names and names have 5 names in it mic,joe,ashley,lee,and jean. Using SELECT names from names where name = 'jean' and then echoed out the name php ...
[ "fetchone() and fetch_row() return objects of type called tuple.\nYou can use indexes to access elements of tuples, print data[0]\n", "if data[0] == \"jean\"\n" ]
[ 3, 2 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0005846077_mysql_python.txt
Q: Python Glade GTK - How to prepare many windows application A simple application with a few screens. The user can navigate with BACK-NEXT buttons. How do you prepare such an application in Python and GTK Glade? I mean how do you hide the previous components? What is the most practical way? I couldn't find any tutor...
Python Glade GTK - How to prepare many windows application
A simple application with a few screens. The user can navigate with BACK-NEXT buttons. How do you prepare such an application in Python and GTK Glade? I mean how do you hide the previous components? What is the most practical way? I couldn't find any tutorial on the net. Can someone point me in the right direction plea...
[ "Sounds like you're looking for GtkAssistant.\nI tried playing around with it and found that Glade makes it really hard to use, but the things you should be looking at are:\n\nBack and Forward to navigate through the pages\nNumber of Pages in the GtkAssistant properties\nPage Type and Position in the children prope...
[ 3 ]
[]
[]
[ "glade", "gtk", "pygtk", "python" ]
stackoverflow_0005845392_glade_gtk_pygtk_python.txt
Q: how to recover python 2.6.1 that was pre-installed in my macbook pro? I download python 3.2 and my first thought was that I need to uninstall the python 2.6.1 pre-installed in my computer. But later I found in python.org "You should never modify or delete these, as they are Apple-controlled and are used by Apple- ...
how to recover python 2.6.1 that was pre-installed in my macbook pro?
I download python 3.2 and my first thought was that I need to uninstall the python 2.6.1 pre-installed in my computer. But later I found in python.org "You should never modify or delete these, as they are Apple-controlled and are used by Apple- or third-party software". I used "sudo rm -rf /Library/Frameworks/Python.Fr...
[ "Reinstalling would work. In the future, don't delete Frameworks you didn't install.\n", "Don't worry, that command will not remove it. The Apple-supplied Python in Mac OS X 10.6 is located at /System/Library/Frameworks/Python.framework.\n$ ls -l /usr/bin/python2.6\nlrwxr-xr-x 1 root wheel 75 Nov 7 23:52 /usr...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005846022_python.txt
Q: Need help with python script with bash commands I copied this script from internet but idon't know how to use it. i am newbiw to python so please help. When i execute it using ./test.py then i can only see usage: py4sa [option] A unix toolbox options: --version show program's version number and exit -h,...
Need help with python script with bash commands
I copied this script from internet but idon't know how to use it. i am newbiw to python so please help. When i execute it using ./test.py then i can only see usage: py4sa [option] A unix toolbox options: --version show program's version number and exit -h, --help show this help message and exit -i, --i...
[ "It seems to me you have stored the script under another name: test.py rather than py4sa. So typing ./test.py, like you did, is correct for you. The program requires arguments, however, so you have to enter one of the options listed under 'usage'.\nNormally 'py4sa [OPTIONS]' would mean that OPTIONS is optional, but...
[ 2, 0, 0 ]
[]
[]
[ "bash", "linux", "python" ]
stackoverflow_0005846494_bash_linux_python.txt
Q: wxpython - resize image without flicker? I'm new to wxPython and GUI in general. Right now the application just displays a toolbar, statusbar, and the following panel. The panel contains a boxSizer with a staticBitmap in it. I'm trying to have an image resize itself to fit its container whenever the window is resi...
wxpython - resize image without flicker?
I'm new to wxPython and GUI in general. Right now the application just displays a toolbar, statusbar, and the following panel. The panel contains a boxSizer with a staticBitmap in it. I'm trying to have an image resize itself to fit its container whenever the window is resized, but I'm running into a lot of flickering....
[ "In your resizeImage method, it might help to add a Freeze and a Thaw, like this:\ndef resizeImage(self, event):\n self.SetSize(event.data)\n if self.total:\n w = event.data[0] - self.padding*2\n h = event.data[1] - self.padding*2\n self.Freeze()\n bmp = self.scaleImage(self.image,...
[ 1, 1 ]
[]
[]
[ "flicker", "image", "python", "user_interface", "wxpython" ]
stackoverflow_0005845452_flicker_image_python_user_interface_wxpython.txt
Q: how do I use the json google translate api? I am trying to use google translate from python with utf-8 text. How do I call the json api? They have a document for embedding it in html but I can't find a proper API or wsdl anywhere. Thanks Raphael A: Here is the code that finally works for me. Using the website wi...
how do I use the json google translate api?
I am trying to use google translate from python with utf-8 text. How do I call the json api? They have a document for embedding it in html but I can't find a proper API or wsdl anywhere. Thanks Raphael
[ "Here is the code that finally works for me.\nUsing the website without the ajax api can get your ip banned, so this is better.\n#!/usr/bin/env python\nfrom urllib2 import urlopen\nfrom urllib import urlencode\nimport urllib2\nimport urllib\nimport simplejson\nimport sys\n\n# The google translate API can be found h...
[ 7, 2, 1, 0 ]
[]
[]
[ "api", "google_translate", "json", "python" ]
stackoverflow_0001136604_api_google_translate_json_python.txt
Q: Python - Create new variables using list I would like to create new variables from a list. For example: mylist=[A,B,C] From which i would like to create the following variables: self.varA self.varB self.varC How can create these new variables in a loop? A: mylist=['A','B','C'] for name in mylist: setattr(s...
Python - Create new variables using list
I would like to create new variables from a list. For example: mylist=[A,B,C] From which i would like to create the following variables: self.varA self.varB self.varC How can create these new variables in a loop?
[ "mylist=['A','B','C']\nfor name in mylist:\n setattr(self, name, None)\n\nbut this is nearly always a bad idea and the values should be in a dict like:\nself.v = {}\nfor name in mylist:\n self.v[name] = None\n\n", "Your question ignores the fact that the variables need values ... who is going to supply what...
[ 6, 0 ]
[]
[]
[ "list", "python", "variables" ]
stackoverflow_0005847113_list_python_variables.txt
Q: In python, how can you determine the values of variables in a local scope For debugging purposes, I have found that it could be beneficial if I could print the variables that are in local scope and only those in local scope. Sample: def showAuthUser(self): """Make a request to the campfire server. Retur...
In python, how can you determine the values of variables in a local scope
For debugging purposes, I have found that it could be beneficial if I could print the variables that are in local scope and only those in local scope. Sample: def showAuthUser(self): """Make a request to the campfire server. Returns a getPage object which is deferred. """ u = self.uri + self._resourc...
[ "you can use the locals() function\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0005847338_python.txt
Q: python error with Popen while using subprocess I have my python script this var1 = subprocess.Popen("pwd | grep 'home' "); print var1 But it is giving me error A: You need to add shell=True if you want the shell to interpret the pipe correctly: var1 = subprocess.Popen("pwd | grep 'home' ", shell=True) (Note th...
python error with Popen while using subprocess
I have my python script this var1 = subprocess.Popen("pwd | grep 'home' "); print var1 But it is giving me error
[ "You need to add shell=True if you want the shell to interpret the pipe correctly:\nvar1 = subprocess.Popen(\"pwd | grep 'home' \", shell=True)\n\n(Note that you don't need a semi-colon at the end of the line.) That might not do what you expect, though - that returns a Popen object so then you need to check whethe...
[ 6 ]
[]
[]
[ "bash", "linux", "python" ]
stackoverflow_0005847419_bash_linux_python.txt
Q: Why is that when I enable packat, pyparsing returns different parse trees? This is just a toy grammar to test backtracking: from pyparsing import * a = Literal("a") b = Literal("b") c = Literal("c") abb = a + b + b abc = a + b + c aba = a + b + a grammar = MatchFirst( [ abb.setDebug(), abc.setDebug(), aba.setDeb...
Why is that when I enable packat, pyparsing returns different parse trees?
This is just a toy grammar to test backtracking: from pyparsing import * a = Literal("a") b = Literal("b") c = Literal("c") abb = a + b + b abc = a + b + c aba = a + b + a grammar = MatchFirst( [ abb.setDebug(), abc.setDebug(), aba.setDebug() ] ) grammar.parseString( "aba" ) With packrat disabled, the returned parse...
[ "This is a bug in pyparsing. Corrected version has been checked into SVN.\n" ]
[ 2 ]
[]
[]
[ "pyparsing", "python" ]
stackoverflow_0005847342_pyparsing_python.txt
Q: Exception in Twisted when calling getPage I'm calling client.getPage and I receive the following traceback. Can anyone make any sense of this? Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/Twisted-10.0.0-py2.6-linux-i686.egg/twisted/python/log.py", line 84, in callWithLogger ...
Exception in Twisted when calling getPage
I'm calling client.getPage and I receive the following traceback. Can anyone make any sense of this? Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/Twisted-10.0.0-py2.6-linux-i686.egg/twisted/python/log.py", line 84, in callWithLogger return callWithContext({"system": lp}, func, *...
[ "You are calling web.client.getPage in the wrong way. The second argument should be a contextFactory but you provide a string:\ndef getPage(url, contextFactory=None, *args, **kwargs)\n\nModify your last line to look like this:\nreturn client.getPage(url, contextFactory=None, method, headers=headers)\n\n(You can ski...
[ 2 ]
[]
[]
[ "python", "twisted", "twisted.client" ]
stackoverflow_0005847415_python_twisted_twisted.client.txt
Q: Decentralized networking in Python - How? I want to write a Python script that will check the users local network for other instances of the script currently running. For the purposes of this question, let's say that I'm writing an application that runs solely via the command line, and will just update the screen ...
Decentralized networking in Python - How?
I want to write a Python script that will check the users local network for other instances of the script currently running. For the purposes of this question, let's say that I'm writing an application that runs solely via the command line, and will just update the screen when another instance of the application is "fo...
[ "One of the ways to do this would be the Application under question is broadcasting UDP packets and your application is receiving that from different nodes and then displaying it. Twisted Networking Framework provides facilities for doing such a job. The documentation provides some simple examples too.\n", "Well,...
[ 8, 3, 2, 2 ]
[]
[]
[ "networking", "python" ]
stackoverflow_0005846209_networking_python.txt
Q: How to connect the "show" and "hide" signals with PyGTK? I would like to have a callback called when some widget (a Menu) is shown or hidden. Doing this way : menu = gtk.Menu() menu.connect("show", self.menu_show, menu) menu.connect("hide", self.menu_hide, menu) Callback functions are never called. Are show and h...
How to connect the "show" and "hide" signals with PyGTK?
I would like to have a callback called when some widget (a Menu) is shown or hidden. Doing this way : menu = gtk.Menu() menu.connect("show", self.menu_show, menu) menu.connect("hide", self.menu_hide, menu) Callback functions are never called. Are show and hide signals the ones I am looking for ? Are they special ? Is ...
[ "I think those signals are emitted only when the respective methods on an object are called. If you want to connect to when a widget is (re-) drawn, take the expose-event signal. But why do you want to anyway? A menu is there to provide to the user choices for actions, not to run some setup/teardown code when it is...
[ 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0005847677_gtk_pygtk_python.txt
Q: where can i find python tutorials for doing linux tasks I want to learn python to do some linux system administartion but on internet i find basic python tutorials . they don't teach anything with linux in mind but general python. is there any pdf which can teach me how do linux things like backup , restore , mysq...
where can i find python tutorials for doing linux tasks
I want to learn python to do some linux system administartion but on internet i find basic python tutorials . they don't teach anything with linux in mind but general python. is there any pdf which can teach me how do linux things like backup , restore , mysql backups , log files processing in python
[ "I like the O'Reilly book Python for Unix and Linux System Administration\n", "take a look at Popular recipes tagged \"sysadmin\" on ActiveState. They are not tutorials in PDF but once you know Python you can learn a lot reading the source of recipes.\n" ]
[ 3, 1 ]
[]
[]
[ "linux", "python", "system_administration" ]
stackoverflow_0005847685_linux_python_system_administration.txt
Q: How to check if python module exists and can be imported I am using debug toolbar with django and would like to add it to project if two conditions are true: settings.DEBUG is True module itself exists It's not hard to do the first one # adding django debug toolbar if DEBUG: MIDDLEWARE_CLASSES += 'debug_too...
How to check if python module exists and can be imported
I am using debug toolbar with django and would like to add it to project if two conditions are true: settings.DEBUG is True module itself exists It's not hard to do the first one # adding django debug toolbar if DEBUG: MIDDLEWARE_CLASSES += 'debug_toolbar.middleware.DebugToolbarMiddleware', INSTALLED_APPS +=...
[ "You can use the same logic inside your function:\ndef module_exists(module_name):\n try:\n __import__(module_name)\n except ImportError:\n return False\n else:\n return True\n\nThere is no performance penalty to this solution because modules are imported only once.\n" ]
[ 47 ]
[]
[]
[ "django", "python", "python_import" ]
stackoverflow_0005847934_django_python_python_import.txt
Q: Extracting all links from webpage I want to write a function that takes a web page URL, downloads the web page and returns a list of the URLs in that page.(with using urllib module) any help would be appreciated A: Here you go: import sys import urllib2 import lxml.html try: url = sys.argv[1] except IndexEr...
Extracting all links from webpage
I want to write a function that takes a web page URL, downloads the web page and returns a list of the URLs in that page.(with using urllib module) any help would be appreciated
[ "Here you go:\nimport sys\nimport urllib2\nimport lxml.html\n\ntry:\n url = sys.argv[1]\nexcept IndexError:\n print \"Specify a url to scrape\"\n sys.exit(1)\n\nif not url.startswith(\"http://\"):\n print \"Please include the http:// at the beginning of the url\"\n sys.exit(1)\n\nhtml = urllib2.urlop...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0005848014_python.txt
Q: python -Weird Print... HW Write a function called exactly weird() which takes three strings as arguments and prints the longest one backwards. (In the case of a tie, the string which is the earlier argument should be selected. The function call: weird("I", "Love", "Python") Should result in the following termina...
python -Weird Print... HW
Write a function called exactly weird() which takes three strings as arguments and prints the longest one backwards. (In the case of a tie, the string which is the earlier argument should be selected. The function call: weird("I", "Love", "Python") Should result in the following terminal output: nohtyP This is what ...
[ "A faster approach (and it works for an arbitrary number of strings) is:\ndef weird(*s):\n return sorted(s,key=len,reverse=True)[0][::-1]\n\n", "Unfortunately I'm somewhat of a novice myself with python, but the simplest way I see to do this is refer to this Reverse a string in Python to see a simple way to r...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005587419_python.txt
Q: How to route with no subdomain Hi I've a question about how to enable the routing I want. My app is at appspot and the domain is hosted via google apps where it also was bought. When making the call mydomain.com/li I come to www.mydomain.com where more appropriate would be www.mydomain.com/li The actual usage is h...
How to route with no subdomain
Hi I've a question about how to enable the routing I want. My app is at appspot and the domain is hosted via google apps where it also was bought. When making the call mydomain.com/li I come to www.mydomain.com where more appropriate would be www.mydomain.com/li The actual usage is http://koolbusiness.com/li and http:/...
[ "This is down to your domain registrar - they're the ones issuing the 302 redirects for the naked domain. If they don't provide the service you need, you may want to point your DNS elsewhere, such as zoneedit, or another provider who preserves the path correctly.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005848040_google_app_engine_python.txt
Q: Putting other widgets in gtk.Menu I'd like to be able to put a gtk.ProgressBar in my gtk.Menu, but since menus only takes gtk.MenuItems and its subclasses, what I've done instead is take a plain gtk.MenuItem and tried adding my progress bar as a child to that. Since gtk.MenuItem is a subclass of gtk.Bin, it should...
Putting other widgets in gtk.Menu
I'd like to be able to put a gtk.ProgressBar in my gtk.Menu, but since menus only takes gtk.MenuItems and its subclasses, what I've done instead is take a plain gtk.MenuItem and tried adding my progress bar as a child to that. Since gtk.MenuItem is a subclass of gtk.Bin, it should be able to hold pretty much any widget...
[ "This is a limitation of Ubuntu's Application Indicators, see this question at askubuntu. \n", "Your example code works here(I tested it by modifying a pygtk example that I will paste below).\nMaybe its an issue with the rest of your code or your theme?\n\n#!/usr/bin/env python\n\n# example menu.py\n\nimport pygt...
[ 8, 6 ]
[]
[]
[ "appindicator", "pygtk", "python" ]
stackoverflow_0005685103_appindicator_pygtk_python.txt
Q: get_serving_url question Hi My question is whether I've understood the usage correctly: Adding =s120 to the url will scale the image to 120 pixels and adding the parameter size=120 will behave differently: It will only shrink images larger than 120 pixels. Is this true? Thank you A: No. size=120 is something you...
get_serving_url question
Hi My question is whether I've understood the usage correctly: Adding =s120 to the url will scale the image to 120 pixels and adding the parameter size=120 will behave differently: It will only shrink images larger than 120 pixels. Is this true? Thank you
[ "No.\nsize=120 is something you could pass as the 2nd argument to the get_serving_url method. =s120 would be something that you append to the URL returned by get_serving_url.\nThe effect is the same: larger images are scaled down, but smaller images are not scaled up.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005847679_google_app_engine_python.txt
Q: completion of part x using n-1 parts I've build a small module in python which takes a list of strings/buffers in the same size, and returns a xor string in the same size. Then, using that string, together with n-1 strings, I can complete the missing one. It works great, so my question is: do you know an already ...
completion of part x using n-1 parts
I've build a small module in python which takes a list of strings/buffers in the same size, and returns a xor string in the same size. Then, using that string, together with n-1 strings, I can complete the missing one. It works great, so my question is: do you know an already made python module for that? is there a wa...
[ "(1) There is unlikely to be a published module for that.\n(2) I think that you mean that a ^ b ^ c ^ d == e, and you ask if the values of c and d can be recovered (\"completed\") if the values of a b and e are known. The answer to that question is no -- you have one equation with two unknowns. \nUpdate in respons...
[ 0, 0 ]
[]
[]
[ "algorithm", "math", "python", "xor" ]
stackoverflow_0005848147_algorithm_math_python_xor.txt
Q: CGI - Good Design Practice: setattr/eval/if-then? I have a question about good practice. In developing a back-end for my company, wherein our sales staff can manage clients remotely, I want them to simply be able to click "Edit Contact Info." (for instance) and have the python script "manageClients.py" call the "e...
CGI - Good Design Practice: setattr/eval/if-then?
I have a question about good practice. In developing a back-end for my company, wherein our sales staff can manage clients remotely, I want them to simply be able to click "Edit Contact Info." (for instance) and have the python script "manageClients.py" call the "editContactInfo" function. Obviously, the easiest way t...
[ "CGI? This is an ancient culprit of the last century.\nPlease use a decent Python web-framework for implementing your functionality\nin a decent and modern way.\nSmall framework like Flask or Bottle are much, much, much better than dealing with CGI\nnowadays - no excuses please. There is no reason nowadays for usin...
[ 1, 1 ]
[]
[]
[ "cgi", "eval", "python" ]
stackoverflow_0005848494_cgi_eval_python.txt
Q: What's wrong with my code? WSGI, beaker, python, apache2 I'm using apache2, python26, more or less latest version of beaker, mod_wsgi Here's my code, I got this from http://beaker.groovie.org/sessions.html#using from beaker.middleware import SessionMiddleware def simple_app(environ, start_response): # Get the...
What's wrong with my code? WSGI, beaker, python, apache2
I'm using apache2, python26, more or less latest version of beaker, mod_wsgi Here's my code, I got this from http://beaker.groovie.org/sessions.html#using from beaker.middleware import SessionMiddleware def simple_app(environ, start_response): # Get the session object from the environ session = environ['beaker...
[ "for the session.save() error it says that you haven't told it where to save by setting the data_dir session cache parameter\nfor the cookie error, it needs a secret key validate_key set so that the cookies can be encoded when sent to the browser and decoded and authenticated when it gets the cookies from the brows...
[ 3 ]
[]
[]
[ "apache", "beaker", "mod_wsgi", "python", "wsgi" ]
stackoverflow_0005847933_apache_beaker_mod_wsgi_python_wsgi.txt
Q: Learning pyramid (python) and am struggling with the @view_config decorator. Should it just work out of the box? I am still learning pyramid, and I am at a point where I am trying to learn how to use decorators. Below is a copy of my test view callable. from pyramid.response import Response from pyramid.view im...
Learning pyramid (python) and am struggling with the @view_config decorator. Should it just work out of the box?
I am still learning pyramid, and I am at a point where I am trying to learn how to use decorators. Below is a copy of my test view callable. from pyramid.response import Response from pyramid.view import view_config from pyramid.renderers import render_to_response def my_blog(request): return {'project':'tricky...
[ "In order for the configurations added via @view_config to work, you need to call config.scan() at some point.\n" ]
[ 7 ]
[]
[]
[ "decorator", "pyramid", "python" ]
stackoverflow_0005847030_decorator_pyramid_python.txt
Q: how to map url with usernames prefixed? Suppose there is a web app name thesite.com. I need to give every user a url of his own. For eg- if alice signs up, she gets a space of her own at the url "alice.thesite.com".. How do I achieve this. Thanks Alice A: First, use a wildcard DNS entry to point all subdomains t...
how to map url with usernames prefixed?
Suppose there is a web app name thesite.com. I need to give every user a url of his own. For eg- if alice signs up, she gets a space of her own at the url "alice.thesite.com".. How do I achieve this. Thanks Alice
[ "First, use a wildcard DNS entry to point all subdomains to your server. Then in flask, read the request host header, and pull out the subdomain (if any) that was used to access your web app:\nhost = request.host\nhost = host.split(':', 1)[0] # Strip off optional ':##' port number\nusername = None\nif host.endswith...
[ 2, 0 ]
[]
[]
[ "flask", "python", "url" ]
stackoverflow_0005848496_flask_python_url.txt
Q: How to use a generator to split socket read data on newlines I have a simple generator that reads data from a socket and yields each chunk of data as it is received. while True: data = s.recv(512) if not data: break yield data The data looks like a csv file and so contains newlines. How can I...
How to use a generator to split socket read data on newlines
I have a simple generator that reads data from a socket and yields each chunk of data as it is received. while True: data = s.recv(512) if not data: break yield data The data looks like a csv file and so contains newlines. How can I change my code to yield the lines of text instead of the buffer s...
[ "You could call socket.makefile() and then work with a file object (either iterate over lines or call .readline()):\nimport socket\nfrom contextlib import closing\n\nwith closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:\n s.connect((\"127.0.0.1\", 8080))\n s.sendall(\"GET / HTTP/1.0\\r\\n\\r\\...
[ 5 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0005848087_python_sockets.txt
Q: I'm using a straight forward regex pattern ('\s+') that is not ignoring white space I'm not sure why this regex pattern ('\s+') is not ignoring whitespace: the code below searches all of the .txt and .log files in a directory and returns the matched string entered by the user. It takes the string and converts it i...
I'm using a straight forward regex pattern ('\s+') that is not ignoring white space
I'm not sure why this regex pattern ('\s+') is not ignoring whitespace: the code below searches all of the .txt and .log files in a directory and returns the matched string entered by the user. It takes the string and converts it into hex and ASCII, then concurrently searches all .txt and .log files for the string, hex...
[ "I haven't tested it myself, but I think if regex.search(line): should be if result:\n", "For option one you wrote:\nresult = regex.search(line)\n if regex.search(line):\n\nfor option two you wrote:\nresult = regex.search(re.sub(r'\\s+', '',line))\n if regex.search(line):\n\nIf your have a result variable, th...
[ 2, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005848734_python_regex.txt
Q: Can I use generated swig code to convert C++ object to PyObject? I'm working on embedding python into my C++ program using swig. At the moment I have a object written in C++ which I want to pass to a python function. I've created the swig interface to wrap the class. What I'm trying to do is take this C++ object w...
Can I use generated swig code to convert C++ object to PyObject?
I'm working on embedding python into my C++ program using swig. At the moment I have a object written in C++ which I want to pass to a python function. I've created the swig interface to wrap the class. What I'm trying to do is take this C++ object which I've created and pass it to a python function with the ability to...
[ "You can use PyObject_CallMethod to pass a newly created object back to python. Assuming ModuleName.object is a python object with a method called methodName that you want to pass a newly created C++ object to you want to roughly (from memory, I can't test it right now) do this in C++:\nint callPython() {\n PyObj...
[ 2 ]
[]
[]
[ "python", "swig" ]
stackoverflow_0005849012_python_swig.txt
Q: How can I use Python's super() to update a parent value? I'm new to inheritance and all of the previous discussions about inheritance and Python's super() function are a bit over my head. I currently use the following code to update a parent object's value. #!/usr/bin/env python # test.py class Master(object): ...
How can I use Python's super() to update a parent value?
I'm new to inheritance and all of the previous discussions about inheritance and Python's super() function are a bit over my head. I currently use the following code to update a parent object's value. #!/usr/bin/env python # test.py class Master(object): mydata = [] def __init__(self): s1 = Sub1(self) ...
[ "super only applies to class inheritance structures, where Sub1 and Sub2 are subclasses of Master.\nIn your example, you use a containment structure, Sub1 and Sub2 are attributes of Master, and you have no use for super calls.\nAlso, you generally really do not want to use a mutable list as a class attribute; appen...
[ 4, 3 ]
[]
[]
[ "inheritance", "python", "super" ]
stackoverflow_0005849113_inheritance_python_super.txt
Q: Braintree python transparent redirect with vault option Braintree's transparent redirect works beautifully, I don't have to pass any credit card info through my servers, and I'd like to keep it this way. My question is what is the preferred method to allow returning customers to use vaulted credit card/billing inf...
Braintree python transparent redirect with vault option
Braintree's transparent redirect works beautifully, I don't have to pass any credit card info through my servers, and I'd like to keep it this way. My question is what is the preferred method to allow returning customers to use vaulted credit card/billing information? Credit card token is a protected field, so it canno...
[ "You're right that using credit card tokens with transparent redirect is slightly difficult to deal with using the current Braintree API. \nHowever if you already have the users credit card information stored in the vault, you can use a server to server request since you won't have to capture any sensitive informat...
[ 3, 0 ]
[]
[]
[ "ajax", "braintree", "credit_card", "django", "python" ]
stackoverflow_0005607535_ajax_braintree_credit_card_django_python.txt
Q: python struct unpack I'm trying to convert the following perl code: unpack(.., "Z*") to python, however the lack of a "*" format modifier in struct.unpack() seems to make this impossible. Is there a way I can do this in python? P.S. The "*" modifier in perl from the perldoc - Supplying a * for the repeat count i...
python struct unpack
I'm trying to convert the following perl code: unpack(.., "Z*") to python, however the lack of a "*" format modifier in struct.unpack() seems to make this impossible. Is there a way I can do this in python? P.S. The "*" modifier in perl from the perldoc - Supplying a * for the repeat count instead of a number means t...
[ "python's struct.unpack doesn't have the Z format\nZ A null-terminated (ASCIZ) string, will be null padded.\n\ni think this\nunpack(.., \"Z*\")\n\nwould be:\ndata.split('\\x00')\n\nalthough that strips the nulls\n", "I am assuming that you create the struct datatype and you know the size of the struct. If that i...
[ 3, 2, 0 ]
[]
[]
[ "perl", "python", "struct", "unpack" ]
stackoverflow_0005849167_perl_python_struct_unpack.txt
Q: Python open("x", "r") function, how do I know or control which encoding the file is supposed to have? If a python script uses the open("filename", "r") function to open, and subsequently read, the contents of a text file, how can I tell which encoding this file is supposed to have? Note that since I'm executing th...
Python open("x", "r") function, how do I know or control which encoding the file is supposed to have?
If a python script uses the open("filename", "r") function to open, and subsequently read, the contents of a text file, how can I tell which encoding this file is supposed to have? Note that since I'm executing this script from my own program, if there is any way to control this through environment variables, then that...
[ "You can't. Reading a file is independent of its encoding; you'll need to know the encoding in advance in order to properly interpret the bytes you read in.\nFor example, if you know the file is encoded in UTF-8:\nwith open('filename', 'rb') as f:\n contents = f.read().decode('utf-8-sig') # -sig deals with BO...
[ 5 ]
[]
[]
[ "encoding", "python", "text_files" ]
stackoverflow_0005849654_encoding_python_text_files.txt
Q: ImageField won't delete file when using os.unlink() I have this model: class UserProfile(models.Model): """(UserProfile description)""" user = models.ForeignKey(User) image = models.ImageField(upload_to=upload_to) def save(self): os.unlink(self.image.path) super(UserProfile, self)....
ImageField won't delete file when using os.unlink()
I have this model: class UserProfile(models.Model): """(UserProfile description)""" user = models.ForeignKey(User) image = models.ImageField(upload_to=upload_to) def save(self): os.unlink(self.image.path) super(UserProfile, self).save() The script fails on the unlink() method, and says...
[ "You need more specific debugging. Furthermore, the way you've written the code probably ensures errors will happen. I'm not entirely sure, but I wouldn't be surprised if the value for UserProfile.image isn't set before a UserProfile record is created.\nSo I would rewrite your code thusly:\nclass UserProfile(models...
[ 2 ]
[]
[]
[ "delete_file", "django", "image", "imagefield", "python" ]
stackoverflow_0005849669_delete_file_django_image_imagefield_python.txt
Q: How can I load byte strings into a file and put them in another location (python) Sorry if that doesn't describes what I need to do but i need to make a program or script that goes to the 'Pictures' folder on a windows system grab a picture (I assume using a byte string) store it in a file (pickle or...) and load ...
How can I load byte strings into a file and put them in another location (python)
Sorry if that doesn't describes what I need to do but i need to make a program or script that goes to the 'Pictures' folder on a windows system grab a picture (I assume using a byte string) store it in a file (pickle or...) and load the file into another folder... long story short, I have a program that would be comple...
[ "As I mentioned in my earlier comment you could write something that open()ed both the source image file and a destination file in binary mode, and then use the file read() and write() methods to copy the bytes from one file to the other.\nHowever that's a somewhat low-level approach would be reinventing the wheel....
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005845877_python.txt
Q: Static type checking conditionals The following is code for the StaticCharme type checker: I need help defining the method typeConditional(expr, env). It needs to check that all of the predicate expressions evaluate to a Boolean value. In order for a conditional expression to be type correct, the consequent expre...
Static type checking conditionals
The following is code for the StaticCharme type checker: I need help defining the method typeConditional(expr, env). It needs to check that all of the predicate expressions evaluate to a Boolean value. In order for a conditional expression to be type correct, the consequent expressions of each clause produce values of...
[ "For a case like this I usually try to start with the simple expressions and then build up to more complicated ones:\ndef typeConditional(expr, env):\n # handle a literal\n # handle a variable\n\nthen think about how to break the more complicated cases into a composition of simpler cases...\nAlso when you write t...
[ 1, 1 ]
[]
[]
[ "conditional", "python" ]
stackoverflow_0005849442_conditional_python.txt
Q: django: creating a generic form completion page I have several forms in my application, and like all forms after the users have completed them, I would like to redirect them to a form completion page, which the particulars of the forms are displayed after the submission. Now, assuming that my forms all have differ...
django: creating a generic form completion page
I have several forms in my application, and like all forms after the users have completed them, I would like to redirect them to a form completion page, which the particulars of the forms are displayed after the submission. Now, assuming that my forms all have different attributes, how can I create a common view and di...
[ "According to this Django: How do I redirect a post and pass on the post data you can't redirect with the post data, so you have to either 1) display the success page at the same url as the form or 2) put all the variables into the redirect URL.\nIf you are ok displaying the success at the same URL as the form, i....
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005849973_django_django_forms_python.txt
Q: Program to draw weights in edges not working correctly + networkx I have this program to draw a labelled edge with the nodes using matplotlib inside a wx frame. I have combined it using examples at the site and queries asked by other people. But it isn't working correctly as the nodes and edges do get drawn but th...
Program to draw weights in edges not working correctly + networkx
I have this program to draw a labelled edge with the nodes using matplotlib inside a wx frame. I have combined it using examples at the site and queries asked by other people. But it isn't working correctly as the nodes and edges do get drawn but the weights do not. Can somebody help me find the reason for it... import...
[ "Credits to Mr Aric Hagberg of networkx community for this answer.\nHowever since I came to know about it I thought I should answer here for further users.\nThe only problem in above code is \nnx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels,ax= self.axes)\n\nNow it gives weighted edges inside wx using ne...
[ 2 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0005849878_networkx_python.txt
Q: Executing the printed statement I have a print statement in python script. print "mysql -e\"insert into test.syllabalize values (",text_index, ",", index, ",", "'",syllable,"')\"" This output the correct mysql statement... mysql -e"insert into test.syllabalize values ( 3 , 5 , 'abc')" How do I execute this state...
Executing the printed statement
I have a print statement in python script. print "mysql -e\"insert into test.syllabalize values (",text_index, ",", index, ",", "'",syllable,"')\"" This output the correct mysql statement... mysql -e"insert into test.syllabalize values ( 3 , 5 , 'abc')" How do I execute this statement? It only prints it to the standa...
[ "import subprocess\np = subprocess.Popen(\"mysql -e\\\"insert into test.syllabalize values (\",text_index, \",\", index, \",\", \"'\",syllable,\"')\\\"\",shell=True)\np.wait()\n\nbut you should look at using one of python modules for mysql database access rather than doing this. those let you use:\ndb.execute(\"ins...
[ 3, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005848785_python.txt
Q: how can I plot 4 histograms on the same graph I have the following problem: I am using hist() in matplotlib.pyplot I am trying to create 4 histograms on the same graph. and an approximation gaussian for each one of them. how can I plot the 4 histograms on the same graph, without them blocking each other (side by ...
how can I plot 4 histograms on the same graph
I have the following problem: I am using hist() in matplotlib.pyplot I am trying to create 4 histograms on the same graph. and an approximation gaussian for each one of them. how can I plot the 4 histograms on the same graph, without them blocking each other (side by side)? any ideas?
[ "There are several examples in the matplotlib documentation. This one looks like it answers your question:\nimport numpy as np\nimport pylab as P\n#\n# first create a single histogram\n#\nmu, sigma = 200, 25\nx = mu + sigma*P.randn(10000)\n#\n# finally: make a multiple-histogram of data-sets with different length\...
[ 10 ]
[]
[]
[ "histogram", "matplotlib", "python" ]
stackoverflow_0005850207_histogram_matplotlib_python.txt
Q: Removing Trailing Zeros in Python I need to find a way to convert the following strings in python: 0.000 => 0 0 => 0 123.45000 => 123.45 0000 => 0 123.4506780 => 123.450678 and so forth. I tried .rstrip('0').rstrip('.'), but that doesn't work if the input is 0 or 00. Any ideas? Thanks! A...
Removing Trailing Zeros in Python
I need to find a way to convert the following strings in python: 0.000 => 0 0 => 0 123.45000 => 123.45 0000 => 0 123.4506780 => 123.450678 and so forth. I tried .rstrip('0').rstrip('.'), but that doesn't work if the input is 0 or 00. Any ideas? Thanks!
[ "Updated Generalized to maintain precision and handle unseen values:\nimport decimal\nimport random\n\ndef format_number(num):\n try:\n dec = decimal.Decimal(num)\n except:\n return 'bad'\n tup = dec.as_tuple()\n delta = len(tup.digits) + tup.exponent\n digits = ''.join(str(d) for d in ...
[ 26, 20, 9, 4, 1, 1, 1 ]
[]
[]
[ "python", "string", "zero" ]
stackoverflow_0005807952_python_string_zero.txt
Q: does anybody knows pickle with commandline? I am trying to make a dictionary with pickle by using command line but while getting input from command line I am getting "module object has no attribute load " ? Here's my code: import pickle import sys dfile = open ("new.dat","w") print "get argument" lifesize=(sys.arg...
does anybody knows pickle with commandline?
I am trying to make a dictionary with pickle by using command line but while getting input from command line I am getting "module object has no attribute load " ? Here's my code: import pickle import sys dfile = open ("new.dat","w") print "get argument" lifesize=(sys.argv[1]) print "get another argument" two=sys.argv[2...
[ "The code you posted is perfectly fine, please check your version of Python, and possibly update/reinstall.\n\nThe Python interpreter complains that pickle.load() doesn't exist, while it certainly does: http://docs.python.org/library/pickle.html#pickle.load\n" ]
[ 0 ]
[]
[]
[ "cmd", "dictionary", "pickle", "python" ]
stackoverflow_0005850669_cmd_dictionary_pickle_python.txt
Q: Wordlist Generator. Split file Size. How? I am trying to get this python script to create a new file and continue generating word combinations once a certain file size is reached. f=open('wordlist', 'w') def xselections(items, n): if n==0: yield [] else: for i in xrange(len(items)): fo...
Wordlist Generator. Split file Size. How?
I am trying to get this python script to create a new file and continue generating word combinations once a certain file size is reached. f=open('wordlist', 'w') def xselections(items, n): if n==0: yield [] else: for i in xrange(len(items)): for ss in xselections(items, n-1): ...
[ "You can encapsulate the file rotation behavior in a class. When you are writing some data, the write method will first check if the write would exceed the file size limit; then it calls the rotate method which closes the current file and opens a new one, incrementing the sequence number on the filename:\nimport os...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005845330_python.txt
Q: Using Scrapy with authenticated (logged in) user session In the Scrapy docs, there is the following example to illustrate how to use an authenticated session in Scrapy: class LoginSpider(BaseSpider): name = 'example.com' start_urls = ['http://www.example.com/users/login.php'] def parse(self, response)...
Using Scrapy with authenticated (logged in) user session
In the Scrapy docs, there is the following example to illustrate how to use an authenticated session in Scrapy: class LoginSpider(BaseSpider): name = 'example.com' start_urls = ['http://www.example.com/users/login.php'] def parse(self, response): return [FormRequest.from_response(response, ...
[ "In the code above, the FormRequest that is being used to authenticate has the after_login function set as its callback. This means that the after_login function will be called and passed the page that the login attempt got as a response.\nIt is then checking that you are successfully logged in by searching the pag...
[ 72 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0005850755_python_scrapy.txt
Q: Change color of nodes when in a spring layout+ networkx How can I change the nodes of a color where the location is not known So i have seen this link on stackoverflow where the answer has been given for an explicitly set positions of nodes. But say i have a graph like this G = nx.Graph() for i in range(10):...
Change color of nodes when in a spring layout+ networkx
How can I change the nodes of a color where the location is not known So i have seen this link on stackoverflow where the answer has been given for an explicitly set positions of nodes. But say i have a graph like this G = nx.Graph() for i in range(10): G.add_node(i) for i in range(9): G.add_edge(i...
[ "Here is some code that might help. This choses a random node to color blue and colors the rest red.\nimport random\nimport matplotlib.pyplot as plt\nimport networkx as nx\nG=nx.Graph()\nG.add_edges_from([('a','b'),('b','d'),('c','e'),('b','e')])\npos=nx.spring_layout(G)\nnodes=G.nodes()\nrandom.shuffle(nodes)\nbl...
[ 1 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0005850782_networkx_python.txt
Q: Implementing PyObjc NsObject Subclass I have an Objc-C project in which I would like to be able to process some data trough Python. For that, I decided to implement a PyObjc NSObject subclass, which I would then link to my Obj-C classes trough the interface builder. I added the Python framework to my project, and ...
Implementing PyObjc NsObject Subclass
I have an Objc-C project in which I would like to be able to process some data trough Python. For that, I decided to implement a PyObjc NSObject subclass, which I would then link to my Obj-C classes trough the interface builder. I added the Python framework to my project, and an python file with the following simple co...
[ "I have heard that Xcode 4 does not play so nicely with PyObjC, but I'm still using 3, so I can't be sure.\nThe reason for your second error (and this bites me too all the time) is that you need to import your custom classes into your project's main.py:\n#import modules required by application\nimport objc\nimport ...
[ 0 ]
[]
[]
[ "cocoa", "pyobjc", "python", "xcode" ]
stackoverflow_0005848282_cocoa_pyobjc_python_xcode.txt
Q: Scrapy - parse a page to extract items - then follow and store item url contents I have a question on how to do this thing in scrapy. I have a spider that crawls for listing pages of items. Every time a listing page is found, with items, there's the parse_item() callback that is called for extracting items data, ...
Scrapy - parse a page to extract items - then follow and store item url contents
I have a question on how to do this thing in scrapy. I have a spider that crawls for listing pages of items. Every time a listing page is found, with items, there's the parse_item() callback that is called for extracting items data, and yielding items. So far so good, everything works great. But each item, has among o...
[ "After some testing and thinking, I found this solution that works for me.\nThe idea is to use just the first rule, that gives you listings of items, and also, very important, add follow=True to that rule.\nAnd in parse_item() you have to yield a request instead of an item, but after you load the item. The request ...
[ 21, 2 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0005825880_python_scrapy.txt
Q: Is it possible to acces stdout via regular open/write in Python I am trying to create a scipr which would enable either writing on stdout or in file. Is it somehow possible to write to each via the same snippet instead of using print for stdou and io.write() for files? Examples of both: out_file = open("test.txt",...
Is it possible to acces stdout via regular open/write in Python
I am trying to create a scipr which would enable either writing on stdout or in file. Is it somehow possible to write to each via the same snippet instead of using print for stdou and io.write() for files? Examples of both: out_file = open("test.txt", "wt") out_file.write("Text") out_file.close() and print("Text", fil...
[ "is this what you want?\nfrom __future__ import print_function, with_statement\ndef my_print(text, output):\n if type(output) == str:\n with open(output, 'w') as output_file:\n print(text, file=output_file)\n elif type(output) == file:\n print(text, file=output)\n else:\n ra...
[ 1 ]
[]
[]
[ "file_io", "python", "stdout" ]
stackoverflow_0005850587_file_io_python_stdout.txt
Q: Problem accessing attributes in BeautifulSoup I am having problems using Python (2.7). The code basically consists of: str = '<el at="some">ABC</el><el>DEF</el>' z = BeautifulStoneSoup(str) for x in z.findAll('el'): # if 'at' in x: # if hasattr(x, 'at'): print x['at'] else: print 'n...
Problem accessing attributes in BeautifulSoup
I am having problems using Python (2.7). The code basically consists of: str = '<el at="some">ABC</el><el>DEF</el>' z = BeautifulStoneSoup(str) for x in z.findAll('el'): # if 'at' in x: # if hasattr(x, 'at'): print x['at'] else: print 'nothing' I expected the first if statement to work ...
[ "The in operator is for sequence and mapping types, what makes you think the object returned by BeautifulSoup is supposed to implement it correctly? According to the BeautifulSoup docs, you should access attributes using the [] syntax.\nRe hasattr, I think you confused HTML/XML attributes and Python object attribut...
[ 7, 1, 1, 0 ]
[]
[]
[ "attributes", "beautifulsoup", "python" ]
stackoverflow_0005848261_attributes_beautifulsoup_python.txt
Q: How to unread a line in python I am new to Python (2.6), and have a situation where I need to un-read a line I just read from a file. Here's basically what I am doing. for line in file: print line file.seek(-len(line),1) zz = file.readline() print zz However I notice that "zz" and "line" are...
How to unread a line in python
I am new to Python (2.6), and have a situation where I need to un-read a line I just read from a file. Here's basically what I am doing. for line in file: print line file.seek(-len(line),1) zz = file.readline() print zz However I notice that "zz" and "line" are not the same. Where am I going wron...
[ "I don't think for line in file: and seek make a good combination. Try something like this:\nwhile True:\n line = file.readline()\n print line\n file.seek(-len(line),1)\n zz = file.readline()\n print zz\n\n # Make sure this loop ends somehow\n\n", "You simply cannot mix iterators and seek() this...
[ 12, 3, 2, 2 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0005850127_file_io_python.txt
Q: How to wrap c++ object with boost.Python, so that Python will never call it destructor automatically For example, I have C++ class "A", and python class "B". Class "A" wrapped with boost::python, so I can use it in my python code. Class "B" has a member of type "A", I create it in constructor of "B". When I remove...
How to wrap c++ object with boost.Python, so that Python will never call it destructor automatically
For example, I have C++ class "A", and python class "B". Class "A" wrapped with boost::python, so I can use it in my python code. Class "B" has a member of type "A", I create it in constructor of "B". When I remove my object of class "B", it automatically calls destructor of "A" in C++. I want to avoid this call, so th...
[ "You should keep a pointer in your \"B Class\" to the \"A Class object\", So that when the \"B object\" is destructed the \"Class A Object\" is not reclaimed.\nEDIT:\nI think this could solve your problem:\naObjectPTR = POINTER(aObj)\n\nNow, you have a pointer called \"aObjectPTR\".\nplace instead of \"AObj\" the n...
[ 0 ]
[]
[]
[ "boost", "c++", "python" ]
stackoverflow_0005851353_boost_c++_python.txt
Q: Help adding the Prime Number Hypothesis by C.F. Gauss to my Sieve of Eratosthenes Hey all! So I'm almost done with a problem that I started working on for school that deals with the Sieve of Eratosthenes. I managed to get the program to print out all the prime numbers from 2 to the square root of 1000. However, my...
Help adding the Prime Number Hypothesis by C.F. Gauss to my Sieve of Eratosthenes
Hey all! So I'm almost done with a problem that I started working on for school that deals with the Sieve of Eratosthenes. I managed to get the program to print out all the prime numbers from 2 to the square root of 1000. However, my teacher is asking me to use the Prime Number Hypothesis (?) by C.F. Gauss. This is wha...
[ "The problem seems to be in the line j=i. You want to start j = 1 so that you catch all multiples of i and add them to your \"x\" list of non-prime elements. If you start j = i you will miss some. And when you test for \"i not in x\" it will evaluate to true for some non-primes. \nAlso instead of x.append(i*j) you ...
[ 0 ]
[]
[]
[ "math", "primes", "python", "sieve_of_eratosthenes" ]
stackoverflow_0005851574_math_primes_python_sieve_of_eratosthenes.txt
Q: Difference between __file__ and sys.argv[0] Is there any difference between: __file__ and sys.argv[0] Because both seem to be doing the same thing: they hold the name of the script. If there is no difference, then why is it that __file__ is used in almost all someplaces whereas I have never seen sys.argv[0] being...
Difference between __file__ and sys.argv[0]
Is there any difference between: __file__ and sys.argv[0] Because both seem to be doing the same thing: they hold the name of the script. If there is no difference, then why is it that __file__ is used in almost all someplaces whereas I have never seen sys.argv[0] being used.
[ "__file__ is the name of the current file, which may be different from the main script if you are inside a module or if you start a script using execfile() rather than by invoking python scriptname.py. __file__ is generally your safer bet.\n", "It's only the same if you are in the \"main\" script of your python...
[ 26, 6, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005851588_python.txt
Q: How can I make my list of lists better indexable? I'm trying to store data in a list of lists, such that each sample, which has a variety of info associated with it, all together in a list, and then store a large number of those in a list. What I have so far is: #!/usr/bin/env python from operator import itemgett...
How can I make my list of lists better indexable?
I'm trying to store data in a list of lists, such that each sample, which has a variety of info associated with it, all together in a list, and then store a large number of those in a list. What I have so far is: #!/usr/bin/env python from operator import itemgetter # For sorting class XaDatum (object): fields =...
[ "You can manipulate tables like these quite conveniently with NumPy's record arrays. NumPy is a de facto standard for array operations in Python.\nYou could also think of using a database table, for instance through SQLite.\n", "Seems to me like slicing is working as expected. daf[:] returns a copy of daf.data w...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005851468_python.txt
Q: Python: How do you convert n-bits to base 64? I have this: struct.pack('I', 0b10101010101100101010001000001000).encode('base64') which is good for converting 32 bits to base 64... but is there an easy way to convert any number of bits to base 64? like, anywhere between 128 and 512? EDIT: where I'm at: My original...
Python: How do you convert n-bits to base 64?
I have this: struct.pack('I', 0b10101010101100101010001000001000).encode('base64') which is good for converting 32 bits to base 64... but is there an easy way to convert any number of bits to base 64? like, anywhere between 128 and 512? EDIT: where I'm at: My original command: >>> struct.pack('I', 0b10101010101100101...
[ "If you have an arbitrary-long binary string, use string hex escapes:\n'\\x00\\x01\\x02\\x03'.encode('base64')\n\nSo your example would be:\n'\\xaa\\xb2\\xa2\\x08'.encode('base64')\n\n", "I have written an article which describes a simple solution in Python which can be used to transfrom a series of numbers from ...
[ 4, 1 ]
[]
[]
[ "base64", "binary", "python" ]
stackoverflow_0005305575_base64_binary_python.txt
Q: What should a Window Manager do with a ConfigureRequestEvent? For my sins (and for fun the learning experience) I am writing a window manager (I know, I know). I'm using python and XCB (python-xpyb). So far I have figured out that I need to use a SubStructureRedirect mask on the root window(s), and I am successful...
What should a Window Manager do with a ConfigureRequestEvent?
For my sins (and for fun the learning experience) I am writing a window manager (I know, I know). I'm using python and XCB (python-xpyb). So far I have figured out that I need to use a SubStructureRedirect mask on the root window(s), and I am successfully being passed events related to applications' top-level windows. ...
[ "The short answer is configure the window (size, stacking, etc.) by calling ConfigureWindow. The long answer is here you impose policy and honor specs such as XSizeHints. Best to have a look at some existing WMs' source and get a sense of what they do. Exactly what you do depends on your desired UI. \nThe simplest ...
[ 1 ]
[]
[]
[ "python", "window_managers", "x11", "xcb" ]
stackoverflow_0005845717_python_window_managers_x11_xcb.txt
Q: Getting pyHook and SendKeys to work together I'm trying to write an auto-correct mechanism in Python. I log the user's keystrokes, and when they stop typing for a second I want to erase everything and retype the corrected sentence. The code below is working fine, except for the fact that SendKeys is running very ...
Getting pyHook and SendKeys to work together
I'm trying to write an auto-correct mechanism in Python. I log the user's keystrokes, and when they stop typing for a second I want to erase everything and retype the corrected sentence. The code below is working fine, except for the fact that SendKeys is running very slowly. I think the PumpMessages call is interfer...
[ "Nevermind. I just needed to call hm.UnhookKeyboard() before calling SendKeys.\nEdit: Somebody asked me for more info. I decided to just dump my key related experiments onto GitHub: https://github.com/JesseAldridge/Keyboard-Tricks\n" ]
[ 0 ]
[]
[]
[ "keylogger", "python", "sendkeys", "winapi" ]
stackoverflow_0005851942_keylogger_python_sendkeys_winapi.txt
Q: Changing the font on a wxPython TextCtrl widget I'd like to set the font of a wx.TextCtrl widget to Consolas, or at least another monospaced font. How would I go about this? A: font1 = wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Consolas') myTextCtrl.SetFont(font1)
Changing the font on a wxPython TextCtrl widget
I'd like to set the font of a wx.TextCtrl widget to Consolas, or at least another monospaced font. How would I go about this?
[ "font1 = wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Consolas')\nmyTextCtrl.SetFont(font1)\n\n" ]
[ 23 ]
[]
[]
[ "fonts", "python", "textctrl", "wxpython" ]
stackoverflow_0005851932_fonts_python_textctrl_wxpython.txt
Q: How to exit a multithreaded program? I was just messing around with threading in python, wrote this basic IM thingy [code at bottom] I noticed that when I kill the program with C-c it doesn't exit, it just hangs forever. I'm just guessing it's waiting for each thread to finish what they are doing, but since it's...
How to exit a multithreaded program?
I was just messing around with threading in python, wrote this basic IM thingy [code at bottom] I noticed that when I kill the program with C-c it doesn't exit, it just hangs forever. I'm just guessing it's waiting for each thread to finish what they are doing, but since it's an endless loop that will never happen. S...
[ "I see several causes of the misbehavior in your code.\n\nCtrl+C causes a \"KeyboardInterrupt\" exception in the main thread. So you should handle it there.\nYour socket is in blocking mode. This causes several socket functions to block the calling thread until the function returns. During this state the thread can...
[ 7, 5 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0005849484_multithreading_python.txt
Q: Region Growing Algorithm Hey everyone. I'm really struggling to figure out the logic with this one and was hoping you could help me out. Before I continue I just want to let you know that I am amateur programmer and a beginner at that, with no formal Computer Science training of any sort, so please bear with me. :...
Region Growing Algorithm
Hey everyone. I'm really struggling to figure out the logic with this one and was hoping you could help me out. Before I continue I just want to let you know that I am amateur programmer and a beginner at that, with no formal Computer Science training of any sort, so please bear with me. :D Also, I'm using Python, but ...
[ "Basic region growing, in pseudocode looks something like:\nseed_point // starting point\nvisited // boolean array/matrix, same size as image\npoint_queue // empty queue\n\npoint_queue.enqueue( seed_point )\nvisited( seed_point ) = true\n\nwhile( point_queue is not empty ) {\n this_point = point_queue.dequeue()\...
[ 5, 2, 1, 1 ]
[]
[]
[ "algorithm", "flood_fill", "image", "image_processing", "python" ]
stackoverflow_0005851266_algorithm_flood_fill_image_image_processing_python.txt
Q: Storing UUIDs in sqlite using Pylons and SQLalchemy I'm working on my first Pylons project using SQLalchemy and sqlite. I'd like to use UUIDs as the primary key for one of my tables. I found the question below and I used the code to add a custom UUID() type to SQLalchemy. (the second solution, I wasn't able to fig...
Storing UUIDs in sqlite using Pylons and SQLalchemy
I'm working on my first Pylons project using SQLalchemy and sqlite. I'd like to use UUIDs as the primary key for one of my tables. I found the question below and I used the code to add a custom UUID() type to SQLalchemy. (the second solution, I wasn't able to figure out how to use the suggestion by zzzeek.) Random ids ...
[ "You were right this just work for postgresql (db I use).\nbut I dive in the post you provide Random ids in sqlalchemy (pylons), it really work in sqlite, just don't follow the zzzeek answer\ngo to the Tom Willis solutions, just some things to take in consideration I follow complete this code but change some things...
[ 9, 2 ]
[]
[]
[ "pylons", "python", "sqlalchemy", "sqlite" ]
stackoverflow_0005849389_pylons_python_sqlalchemy_sqlite.txt
Q: create objects on runtime in python how do i create object-instances on runtime in python? say i have 2 classes: class MyClassA(object): def __init__(self, prop): self.prop = prop self.name = "CLASS A" def println(self): print self.name class MyClassB(object): def __init__(sel...
create objects on runtime in python
how do i create object-instances on runtime in python? say i have 2 classes: class MyClassA(object): def __init__(self, prop): self.prop = prop self.name = "CLASS A" def println(self): print self.name class MyClassB(object): def __init__(self, prop): self.prop = prop ...
[ "You might create a dispatcher, which is a dictionary with your keys mapping to classes.\ndispatch = {\n \"a\": MyClassA,\n \"b\": MyClassB,\n}\n\ninstance = dispatch[which_one]() # Notice the second pair of parens here!\n\n", "You create a class instance by calling the class. Your class dict {('a': MyClass...
[ 6, 2 ]
[]
[]
[ "dynamic", "object", "python", "runtime" ]
stackoverflow_0005852459_dynamic_object_python_runtime.txt
Q: Python: CGI update webpage before script exit Okay here's my situation. I wrote a HTML form with a textarea that submits a POST request to my python script. I use cgi library to parse the textarea and split it into an array. I then process the items using a loop and print items as they're processed. It seems that ...
Python: CGI update webpage before script exit
Okay here's my situation. I wrote a HTML form with a textarea that submits a POST request to my python script. I use cgi library to parse the textarea and split it into an array. I then process the items using a loop and print items as they're processed. It seems that even though I put the print statement in the loop i...
[ "see\nhttp://docs.python.org/library/cgi.html#common-problems-and-solutions\nIt says most HTTP servers buffer the output of cgi scripts until completed. \n" ]
[ 1 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0005227166_cgi_python.txt
Q: Python equivalent of php's foreach($array as $key => &$value) is there any equivalent to this PHP notation, which changes the original array (be aware of reference operator)? // increase value of all items by 1 foreach ($array as $k => &$v) { $v++; } I know only this way, which is not so elegant: for i in ran...
Python equivalent of php's foreach($array as $key => &$value)
is there any equivalent to this PHP notation, which changes the original array (be aware of reference operator)? // increase value of all items by 1 foreach ($array as $k => &$v) { $v++; } I know only this way, which is not so elegant: for i in range(len(array)): array[i] += 1
[ "When the built in enumerate() function is called on a list, it returns an object that can be iterated over, returning a count and the value returned from the list.\nfor i, val in enumerate(array):\n array[i] += 1\n\n", "You could use list comprehension:\nnewArray = [i + 1 for i in array]\n\n", "Regarding re...
[ 65, 5, 2, 1 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0005851753_for_loop_python.txt
Q: Python problems: AttributeError: 'dict' object has no attribute 'upper' I'm getting this error from AppEngine while attempting to POST a tweet. I'm thinking my syntax isnt quite right, but I'm at a loss at the moment. For the life of me I cant seem to send my status arguments to **extra_params in the post functio...
Python problems: AttributeError: 'dict' object has no attribute 'upper'
I'm getting this error from AppEngine while attempting to POST a tweet. I'm thinking my syntax isnt quite right, but I'm at a loss at the moment. For the life of me I cant seem to send my status arguments to **extra_params in the post function using: args = {} <br/> args.update({'status': 'THIS IS MY TWEET'})<br/> inf...
[ "You're not passing it as extra_params, you're passing it as http_method.\ninfo2 = client.post('/statuses/update', **args)\n\n", "If you want to pass extra paramaters (keyword parameters) from a dictionary you need to call it like this:\nclient.post('/path', **args)\n\n" ]
[ 6, 1 ]
[]
[]
[ "google_app_engine", "python", "twitter" ]
stackoverflow_0005852692_google_app_engine_python_twitter.txt
Q: Python: How do I display a timer in a terminal I'm new to python programming and using ubuntu to do so. In a program I have done I used a delay of 1 minute until it executes the code again. How can I program a timer to be displayed in the terminal based on the value of the delayed time? Thanks in advance... A: T...
Python: How do I display a timer in a terminal
I'm new to python programming and using ubuntu to do so. In a program I have done I used a delay of 1 minute until it executes the code again. How can I program a timer to be displayed in the terminal based on the value of the delayed time? Thanks in advance...
[ "The simplest way is as follows.\nimport time\nimport sys\n\nfor remaining in range(10, 0, -1):\n sys.stdout.write(\"\\r\")\n sys.stdout.write(\"{:2d} seconds remaining.\".format(remaining)) \n sys.stdout.flush()\n time.sleep(1)\n\nsys.stdout.write(\"\\rComplete! \\n\")\n\n\"\\r\" returns the...
[ 25 ]
[]
[]
[ "python", "timer" ]
stackoverflow_0005852981_python_timer.txt
Q: python matplotlib clock signal type graph help: I am looking to plot a graph that depicts a clock signal. The following is what I am looking forward to plot. I have say four objects. Object one is either in state 1 or state 0 for a particular length of time. I also have to mention (some where on the top of the clo...
python matplotlib clock signal type graph help:
I am looking to plot a graph that depicts a clock signal. The following is what I am looking forward to plot. I have say four objects. Object one is either in state 1 or state 0 for a particular length of time. I also have to mention (some where on the top of the clock signal) how long is the zero period and how long i...
[ "\nTo draw the lines themselves, use the plot method of an \"axes\" object. The plot method needs a range of y values for each signal. You'd have to generate those from your object, taking into account the required resolution. [Edit: the step method seems to be even easier to use for clock-like singals. Thanks to J...
[ 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005853164_matplotlib_python.txt
Q: mobilize my django, python and google app engine website i am currently developing a web application for a mobile phone. the website is written using google app engine (GAE) under python and django. i have tried using jqtouch to mobilize my website but jqtouch (or django-jqtouch) does not appear to be working.. an...
mobilize my django, python and google app engine website
i am currently developing a web application for a mobile phone. the website is written using google app engine (GAE) under python and django. i have tried using jqtouch to mobilize my website but jqtouch (or django-jqtouch) does not appear to be working.. any ideas on what i should do?
[ "Hi Daniel\nI'd try with full django + GAE for the django that's missing from pure GAE. There is a project called www.allbuttonspressed.com that enables full django with google app engine. I hope it can do what you want. \n" ]
[ 0 ]
[]
[]
[ "django", "google_app_engine", "jqtouch", "python" ]
stackoverflow_0005849925_django_google_app_engine_jqtouch_python.txt
Q: Concatenating a string to the result of input() I want to do something like this in command line: Enter input filename: filename When user specifies the filename, this should happen lines = [line.strip() for line in open('filename.txt')] I tried using lines = [line.strip() for line in open('input().txt')] But i...
Concatenating a string to the result of input()
I want to do something like this in command line: Enter input filename: filename When user specifies the filename, this should happen lines = [line.strip() for line in open('filename.txt')] I tried using lines = [line.strip() for line in open('input().txt')] But it just looks for a file with name 'input().txt' How c...
[ "You need the input() to be outside of the quotes, and then concatenate it with the '.txt' using the + operator. Additionally, it would increase the clarity of your code to get the filename, open the file, and read the file on separate lines.\nfilename = input()\nwith open(filename + '.txt', 'r') as f:\n lines =...
[ 4, 2, 1 ]
[]
[]
[ "command_line_arguments", "python" ]
stackoverflow_0005853374_command_line_arguments_python.txt
Q: Beginner problem with pygame I'm just beginning a very simple pygame code that draws a green line on a white background. However, I have to use pygame.display.flip() in order for it to show up, but it seems that I would have to use this every time I made a change and this seems too impractical for me to be doing i...
Beginner problem with pygame
I'm just beginning a very simple pygame code that draws a green line on a white background. However, I have to use pygame.display.flip() in order for it to show up, but it seems that I would have to use this every time I made a change and this seems too impractical for me to be doing it right. Am I missing something?
[ "Yes, you will have to call it each time you want to update screen. By default pygame uses double buffering Wiki link. \n", "There's a good reason for this. Double buffering is a technique used to prevent \"flickering\". Basically, you want to draw a frame to memory instead of to the monitor and then push the f...
[ 3, 3 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0005851656_pygame_python.txt
Q: How to make tar backup using python I have directory /home/user1 , user2 . I want to loop through all usernames home dir and then make the tar.gz file and then store it in /backups directory. I am new to python so confused how to start A: This should work: import os import tarfile home = '/home/' backup_dir = ...
How to make tar backup using python
I have directory /home/user1 , user2 . I want to loop through all usernames home dir and then make the tar.gz file and then store it in /backups directory. I am new to python so confused how to start
[ "This should work:\nimport os\nimport tarfile\n\nhome = '/home/'\nbackup_dir = '/backup/'\n\nhome_dirs = [ name for name in os.listdir(home) if os.path.isdir(os.path.join(home, name)) ]\n\nfor directory in home_dirs:\n full_dir = os.path.join(home, directory)\n tar = tarfile.open(os.path.join(backup_dir, dire...
[ 10, 1 ]
[]
[]
[ "backup", "python", "shell" ]
stackoverflow_0005849999_backup_python_shell.txt
Q: Why isn't my initial value getting set for my Django form? Here are the relevant snippets forms.py usersegment = [['non-paying','Non-paying (Coming soon)'],['paying','Paying (Coming soon)'], ['all', 'All']] class SegmentForm(forms.Form): usersegment = forms.ChoiceField(label="", widget=RadioSelect(), choices=...
Why isn't my initial value getting set for my Django form?
Here are the relevant snippets forms.py usersegment = [['non-paying','Non-paying (Coming soon)'],['paying','Paying (Coming soon)'], ['all', 'All']] class SegmentForm(forms.Form): usersegment = forms.ChoiceField(label="", widget=RadioSelect(), choices=usersegment) views.py if request.method == 'GET' and 'datestart...
[ "initials are key:value (fieldname/value) pair. it should go like this,\nelse:\n return render_to_response('activation/activation_signupcount.html', \n {'form': SegmentForm(initial={'usersegment':'all'}), \n 'form2': DateSelectForm()\n })\n\n" ]
[ 3 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005853806_django_django_forms_python.txt
Q: How do i use table data from my sqlite3 database as a python variable My code so far conn = sqlite3.connect('databaserm/database') curs = conn.cursor() curs.execute('SELECT * FROM saves') lvl = curs.fetchone() conn.close() ok maybes its the code i used to add the data to the db i've tried ...
How do i use table data from my sqlite3 database as a python variable
My code so far conn = sqlite3.connect('databaserm/database') curs = conn.cursor() curs.execute('SELECT * FROM saves') lvl = curs.fetchone() conn.close() ok maybes its the code i used to add the data to the db i've tried this cn = sqlite3.connect(/databaserm/database") curs = cn.cursor() curs.ex...
[ "Executing select and then fetchone will return a tuple. What else do you need?\nHere's an example:\nimport sqlite3 as sqlite\n\ncon = sqlite.connect(':memory:')\ncursor = con.cursor()\n\ncursor.execute('''\n create table names (id integer primary key,\n name varchar(50), email varchar(50)...
[ 0 ]
[]
[]
[ "database", "python", "sqlite" ]
stackoverflow_0005854210_database_python_sqlite.txt
Q: Does this code follow Python coding standards\style and idioms? I have written this code in log.py. import logging import os # make directory directory = 'logs' if not os.path.exists(directory): os.makedirs(directory) # create logger logger = logging.getLogger('testfile') logger.setLevel(logging.DEBUG) logha...
Does this code follow Python coding standards\style and idioms?
I have written this code in log.py. import logging import os # make directory directory = 'logs' if not os.path.exists(directory): os.makedirs(directory) # create logger logger = logging.getLogger('testfile') logger.setLevel(logging.DEBUG) loghandler = logging.FileHandler(directory + '\log.txt') # create forma...
[ "You're creating a whole module for a single global object. If you want to save code, just have a function that creates it:\ndef make_logger():\n logger = logging.getLogger('testfile')\n # initializations...\n # ...\n return logger\n\nlogger = make_logger()\nlogger.warn('ghj')\n\nWith keyword arguments and defa...
[ 3, 2, 1 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0005854129_coding_style_python.txt
Q: How to read symbols of an object file using C Question is simple, i have a object file and i want to read the symbols of the object file via code. I am aware that the linux command "nm" would be able to do this, but i want to be able to do it inside code. Also note id like to do this either via C or Python. Regar...
How to read symbols of an object file using C
Question is simple, i have a object file and i want to read the symbols of the object file via code. I am aware that the linux command "nm" would be able to do this, but i want to be able to do it inside code. Also note id like to do this either via C or Python. Regards Paul
[ "It would be nice to provide more details.\nFor some pointers:\n\nhttp://sourceforge.net/projects/python-elf/\nhttp://www.grant-olson.net/python/pyasm\n\n", "You might also want to take a look into the python package BinTools:\nhttp://code.google.com/p/pydevtools/\nAlthough not completely documented, it is able t...
[ 1, 1, 0 ]
[]
[]
[ "c", "linux", "python" ]
stackoverflow_0003607254_c_linux_python.txt
Q: Null matrix with constant diagonal, with same shape as another matrix I'm wondering if there is a simple way to multiply a numpy matrix by a scalar. Essentially I want all values to be multiplied by the constant 40. This would be an nxn matrix with 40's on the diagonal, but I'm wondering if there is a simpler fu...
Null matrix with constant diagonal, with same shape as another matrix
I'm wondering if there is a simple way to multiply a numpy matrix by a scalar. Essentially I want all values to be multiplied by the constant 40. This would be an nxn matrix with 40's on the diagonal, but I'm wondering if there is a simpler function to use to scale this matrix. Or how would I go about making a matri...
[ "If you want a matrix with 40 on the diagonal and zeros everywhere else, you can use NumPy's function fill_diagonal() on a matrix of zeros. You can thus directly do:\nN = 100; value = 40\nb = np.zeros((N, N))\nnp.fill_diagonal(b, value)\n\nThis involves only setting elements to a certain value, and is therefore li...
[ 15, 9 ]
[]
[]
[ "matrix", "numpy", "python" ]
stackoverflow_0005852495_matrix_numpy_python.txt
Q: Is it bad nesting try/catch statements? My case right now: try: try: condition catch try: condition catch catch major failure Is it bad to have the code like that? Does it clutter too much, or what are the implications of something like that? A: No, that's somewhat common (except the keyword ...
Is it bad nesting try/catch statements?
My case right now: try: try: condition catch try: condition catch catch major failure Is it bad to have the code like that? Does it clutter too much, or what are the implications of something like that?
[ "No, that's somewhat common (except the keyword is except rather than catch). It depends on what you need to do and the design.\nWhat IS bad, that I see too much of, is catching top-level Exception class, rather than something more specific (e.g. KeyError). Or raising the same.\n", "I wouldn't just cut a verdict ...
[ 3, 2 ]
[]
[]
[ "coding_style", "exception", "python" ]
stackoverflow_0005854758_coding_style_exception_python.txt
Q: Argparse incorrect order of positional and optional parameters Why won't argparse parse these arguments? --foo 1 2 3 bar Using parser = argparse.ArgumentParser() parser.add_argument('--foo', nargs='+') parser.add_argument('bar') which gives the following error: error: too few arguments If I p...
Argparse incorrect order of positional and optional parameters
Why won't argparse parse these arguments? --foo 1 2 3 bar Using parser = argparse.ArgumentParser() parser.add_argument('--foo', nargs='+') parser.add_argument('bar') which gives the following error: error: too few arguments If I pass the bar argument first though, it works: bar --foo 1 2 3 Now...
[ "nargs='+' tells argparse to gather all remaining args together, so bar is included. It has no magical way to guess you intend bar to be a meaningful argument by itself and not part of the args taken to --foo.\nThe example in the docs refers to a simple --foo argument, not one with nargs='+'. Be sure to understand ...
[ 4, 3 ]
[]
[]
[ "argparse", "command_line", "command_line_arguments", "python" ]
stackoverflow_0005854920_argparse_command_line_command_line_arguments_python.txt
Q: Python: write multiple str.format() lines to a file? for host in platforms: f = open(host, 'w') f.write('define host {\n') f.write(' host_name {}\n'.format(host)) f.write(' alias {}\n'.format(host)) f.write(' display_name {}\n'.format(host)) f.writ...
Python: write multiple str.format() lines to a file?
for host in platforms: f = open(host, 'w') f.write('define host {\n') f.write(' host_name {}\n'.format(host)) f.write(' alias {}\n'.format(host)) f.write(' display_name {}\n'.format(host)) f.write(' address {}\n'.format(str(socket.gethos...
[ "You can use named substitutions in a long, triple-quoted string.\ndef print_host(host, address):\n f = open(host, 'w')\n f.write(\"\"\"define host {{\n host_name {host}\n alias {host}\n display_name {host}\n address {address}\n ...
[ 5, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005852704_python.txt
Q: execute 'ls' command as a different User within python script Folks, Here's what I am trying to do: my script will be running as root, I wish to execute various commands (say ls, rm, touch etc) as different users. The problem I have is that using preexec_fn=os.setuid(userid)) is setting the userid of the parent p...
execute 'ls' command as a different User within python script
Folks, Here's what I am trying to do: my script will be running as root, I wish to execute various commands (say ls, rm, touch etc) as different users. The problem I have is that using preexec_fn=os.setuid(userid)) is setting the userid of the parent process as well. Suggestions please? Is preexec_fn the wrong way to ...
[ "Your problem is that you are accidentally calling the preexec_fn when you're only trying to pass a callback to Popen.\nTry this instead:\ndef my_preexec_fn():\n os.setuid(10033)\nprocess = subprocess.Popen(cmdstr,stdout=subprocess.PIPE, stderr=subprocess.STDOUT, preexec_fn=my_preexec_fn)\n\n", "rlibby's answe...
[ 5, 1 ]
[]
[]
[ "callback", "python" ]
stackoverflow_0005602199_callback_python.txt
Q: Python multiprocessing with MySQL I've Googled this topic a lot, but cannot find a solution which fits my needs :( I have a MySQL DB with a table containing e-mail adresses (10,000+). I would like to run a batch job on them every 5 minute. So I'll guess Python is a good choice for retrieving the resultset from MyS...
Python multiprocessing with MySQL
I've Googled this topic a lot, but cannot find a solution which fits my needs :( I have a MySQL DB with a table containing e-mail adresses (10,000+). I would like to run a batch job on them every 5 minute. So I'll guess Python is a good choice for retrieving the resultset from MySQL and then call a command-line with th...
[ "you could use the multiprocessing module like this : \nfrom multiprocessing import Pool\np = Pool() # let python choose the optimal number of processes (= number of CPU cores)\ndef treat_email(email_adress):\n # do the stuff you need with email address\n\nemail_addresses = grab_the_list_from_mysql() # somet...
[ 0, 0 ]
[]
[]
[ "multiprocessing", "mysql", "python" ]
stackoverflow_0005855170_multiprocessing_mysql_python.txt
Q: Editing a SPECIFIC word in a file in python, every 20 mins I want to change the value of omega in the file below at a specific interval, say every 30 minutes. This file is used by another program at runtime. I would like to ramp the RPM value (the last entry on the line) from 0-10 slowly. Essentially, the value "5...
Editing a SPECIFIC word in a file in python, every 20 mins
I want to change the value of omega in the file below at a specific interval, say every 30 minutes. This file is used by another program at runtime. I would like to ramp the RPM value (the last entry on the line) from 0-10 slowly. Essentially, the value "5" in the file below needs to change from 0-10 in increments of 1...
[ "You are not modifying data at all -- you are extracting line and word and modify those. In the end, you write back the original data to the file.\nI would not use Python for this, but rather a shell script (provided you are on a Unix-like OS):\nfor i in 0 1 2 3 4 5 6 7 8 9 10; do\n sleep 30\n sed -i \"26s/[0-...
[ 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005854941_python.txt
Q: List inside the object remembers it's members after creating a new one In root class I'm creating new object every time F3 keys is being pressed: class Browser(QtGui.QMainWindow): indexlist = None some code def keyPressEvent(self, keyEvent): if keyEvent.key() == QtCore.Qt.Key_F3: keyEvent.accept() self.indexl...
List inside the object remembers it's members after creating a new one
In root class I'm creating new object every time F3 keys is being pressed: class Browser(QtGui.QMainWindow): indexlist = None some code def keyPressEvent(self, keyEvent): if keyEvent.key() == QtCore.Qt.Key_F3: keyEvent.accept() self.indexlist = self.ui.treeView.selectedIndexes() compareWin = CompareBox(self.inde...
[ "the parameterlist you have delcared in the class is the same for each instance you create.\nYou should try something like this : \nclass CompareBox(QtGui.QDialog):\n def __init__(self, indexlist=None, parent=None):\n some code now then\n self.parameterlist = []\n self.parameterlist.append(s...
[ 3 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt" ]
stackoverflow_0005855979_pyqt_pyqt4_python_qt.txt
Q: Best practice to install dependencies? I am thinking of a good way to ship my application which is a python package. Installing my package is easy making use of pythons distutils package. The trouble comes with the dependencies my package relies on. If the dependencies are python packages I can deal with them eas...
Best practice to install dependencies?
I am thinking of a good way to ship my application which is a python package. Installing my package is easy making use of pythons distutils package. The trouble comes with the dependencies my package relies on. If the dependencies are python packages I can deal with them easily again using distutils, but non python pa...
[ "We have a project named Kivy ( http://kivy.org/ ), that have exactly the same issue. At the early stage, we've done a all-in-one package that include every setup of every dependencies. However the user was having a lot of \"Next >\" button to click... for every deps (Windows). So now, we have managed to take care ...
[ 5, 4 ]
[]
[]
[ "dependencies", "installation", "python" ]
stackoverflow_0005855543_dependencies_installation_python.txt
Q: Most useful Python modules from the standard library? I am teaching a graduate level Python class at the University of Paris, and the students need to be introduced to the standard library. I want to discuss with them about some of the most important standard modules. What modules do you think are absolute musts?...
Most useful Python modules from the standard library?
I am teaching a graduate level Python class at the University of Paris, and the students need to be introduced to the standard library. I want to discuss with them about some of the most important standard modules. What modules do you think are absolute musts? Even though responses probably vary depending on your fie...
[ "Modules to cover in a 1-2 hour slot entirely depend on your audience's interest or focus. What other classes are they taking? What are they prepared to make use of immediately?\nBe sure to mention math, decimal and datetime and time and re.\nFor IT-types who will be doing file-oriented work: glob, fnmatch, os, o...
[ 41, 33, 18, 7, 7, 6, 5, 5, 4, 3, 3, 2, 1, 1, 1, 1 ]
[]
[]
[ "module", "python", "standard_library" ]
stackoverflow_0001453952_module_python_standard_library.txt
Q: Measuring coverage of C library called in python process Let me start with the example - calling library code from python. This is the library code (compiled into library libfoolib): #include <stdio.h> void bar() { printf("bar\n"); } void foo() { printf("foo\n"); } And this is the python code calling i...
Measuring coverage of C library called in python process
Let me start with the example - calling library code from python. This is the library code (compiled into library libfoolib): #include <stdio.h> void bar() { printf("bar\n"); } void foo() { printf("foo\n"); } And this is the python code calling it: #!/usr/bin/python25 import sys import libfoolib import proc...
[ "The issue is that the processing library of python is exiting using os._exit. This is a problem since exiting in this way does not call the regular cleanup handlers of the process. It turns out that the instrumentation collects coverage data in buffers it and writes it only on process exit and it does that in the ...
[ 1 ]
[]
[]
[ "c", "gcov", "linux", "profiling", "python" ]
stackoverflow_0005847407_c_gcov_linux_profiling_python.txt
Q: Counter in HTML? I am using Google App engine, in the html file I want to show different screens to different users, ie, they are not logged in the show them a log in screen They are logged in and this is there first time to use the system They are a returning user So far the loops in my code is as follows {% i...
Counter in HTML?
I am using Google App engine, in the html file I want to show different screens to different users, ie, they are not logged in the show them a log in screen They are logged in and this is there first time to use the system They are a returning user So far the loops in my code is as follows {% ifequal access_token ...
[ "Firstly, it's not the greatest idea to loop through all your users in your template. It would be better to use a database filter query in your view to find the user, and set an appropriate variable to determine the action in your template. That being said, it is possible to get a forloop counter. Inside the forloo...
[ 3, 1, 1 ]
[]
[]
[ "django", "google_app_engine", "html", "if_statement", "python" ]
stackoverflow_0005855654_django_google_app_engine_html_if_statement_python.txt
Q: python doctest: expected result is the same as the "got" result but the test failed I am on a learning stage of using python as a tool for software QA. I wrote the next simple test in order to find the letter 'a' in a text file number matrix. problem is that the test fails even though the expect equals to what i g...
python doctest: expected result is the same as the "got" result but the test failed
I am on a learning stage of using python as a tool for software QA. I wrote the next simple test in order to find the letter 'a' in a text file number matrix. problem is that the test fails even though the expect equals to what i got. Why is that? Can you tell me what am I doing wrong? test script: fin = open("abc.txt...
[ "You've got an extra space after the 97 - if you remove it, your test should run fine.\n", "This:\nreturn;\n\nMakes your function return None.\nDid you mean return t?\n\nBesides that, IMHO doctest tests are meant to be self-contained. This is something the user should see in your documentation and understand with...
[ 14, 2 ]
[]
[]
[ "doctest", "python" ]
stackoverflow_0005856502_doctest_python.txt
Q: Bottle and GAE authentication using Google Accounts I'm currently developing a bottle app on GAE, and it's already got its own home-made authentication system. However, I would also like to permit access to some areas to application admins using Google Accounts. I'm looking at the documentation, but I'm not quite ...
Bottle and GAE authentication using Google Accounts
I'm currently developing a bottle app on GAE, and it's already got its own home-made authentication system. However, I would also like to permit access to some areas to application admins using Google Accounts. I'm looking at the documentation, but I'm not quite following it. On the development server, hiting any _ah l...
[ "_ah will work only on the development server. It's a part of appengine sdk which emulates the GAE. Coming to your point. If you want to use the google's account for admin functionalities. Then you should do something like this\nfrom google.appengine.api import users\n\nif users.is_current_user_admin():\n\nHere adm...
[ 0 ]
[]
[]
[ "bottle", "google_app_engine", "python" ]
stackoverflow_0005856941_bottle_google_app_engine_python.txt
Q: Revision Control script with python I am was reading this SO question https://stackoverflow.com/questions/38388/organization-wide-backup-strategy And i was interested in implementing this system Revision control is handled by a Python script that scans a file system and uploads changed files to a central s...
Revision Control script with python
I am was reading this SO question https://stackoverflow.com/questions/38388/organization-wide-backup-strategy And i was interested in implementing this system Revision control is handled by a Python script that scans a file system and uploads changed files to a central server. The file system on that server m...
[ "rsync + hard links.\nuse rsync to maintain a master backup directory.\nuse cp -al to take daily/weekly/whatever snapshots.\nUsing hard links means duplicated files will not take up additional space, i.e. each snapshot will only use up the space in the files that have changed. In addition each snapshot contains a ...
[ 1, 0 ]
[]
[]
[ "bash", "python", "sysadmin" ]
stackoverflow_0005855259_bash_python_sysadmin.txt
Q: Abstract methods in Python I need something like an abstract protected method in Python (3.2): class Abstract: def use_concrete_implementation(self): print(self._concrete_method()) def _concrete_method(self): raise NotImplementedError() class Concrete(Abstract): def _concrete_method(s...
Abstract methods in Python
I need something like an abstract protected method in Python (3.2): class Abstract: def use_concrete_implementation(self): print(self._concrete_method()) def _concrete_method(self): raise NotImplementedError() class Concrete(Abstract): def _concrete_method(self): return 2 * 3 Is ...
[ "In Python, you usually avoid having such abstract methods alltogether. You define an interface by the documentation, and simply assume the objects that are passed in fulfil that interface (\"duck typing\").\nIf you really want to define an abstract base class with abstract methods, this can be done using the abc ...
[ 43, 9, 0 ]
[]
[]
[ "abstract_class", "oop", "python", "python_3.x" ]
stackoverflow_0005856963_abstract_class_oop_python_python_3.x.txt
Q: Emacs 23 with python.el not able to keep up with typing and renders screen with a delay I am currently using python.el that by default gets shipped with Emacs 23. I can notice that when i am editing python files, the screen update happens in bursts. e.g. I hold a key, nothing happens in screen, and every 1 seco...
Emacs 23 with python.el not able to keep up with typing and renders screen with a delay
I am currently using python.el that by default gets shipped with Emacs 23. I can notice that when i am editing python files, the screen update happens in bursts. e.g. I hold a key, nothing happens in screen, and every 1 seconds or 2 they appear. Also the problem happens only with editing python files. other modes li...
[ "You'd probably do best to use the new python mode instead of those two you mention. I haven't used them, but I've used the new one and it's pretty decent. There is also the fact that its maintainer has stepped up to maintain the old python.el mode and will replace it internally by the new one anyways.(or at least ...
[ 0 ]
[]
[]
[ "emacs", "python" ]
stackoverflow_0005853274_emacs_python.txt
Q: Sending composite data type with XML-RPC using cPickle I am working on a distributed processing project. I need to send my composite data type to another peer, so i can use it in other peer to populate my TreeView structure. I have these two classes in my "tsk_composite" module, My composite data node : class CTs...
Sending composite data type with XML-RPC using cPickle
I am working on a distributed processing project. I need to send my composite data type to another peer, so i can use it in other peer to populate my TreeView structure. I have these two classes in my "tsk_composite" module, My composite data node : class CTskNode(object): def __init__(self, pData, pParent = N...
[ "When Pickle serialize an object, it serialize a ditionnary that stores the attributes names/values and class name (full name, with modules pathes) not the method definitions.\nWhen deserializing, it recreate an object with the same class and set the saved attributes to this object. \nTo re-create the object, pickl...
[ 4 ]
[]
[]
[ "composite", "importerror", "pickle", "python", "xml_rpc" ]
stackoverflow_0005857357_composite_importerror_pickle_python_xml_rpc.txt
Q: [Python]Encoding and execfile I am trying to do something like that using python 2.4: #!/usr/bin/python # -*- coding: utf-8 -*- afile = unicode('C:\\國立國語院.py', 'UTF-8') execfile(afile.encode("UTF-8",'replace')) And I receive this error: IOError: [Errno 2] No such file or directory: 'C:\\\xef\xbb\xbf\xe5\x9c\x8b\...
[Python]Encoding and execfile
I am trying to do something like that using python 2.4: #!/usr/bin/python # -*- coding: utf-8 -*- afile = unicode('C:\\國立國語院.py', 'UTF-8') execfile(afile.encode("UTF-8",'replace')) And I receive this error: IOError: [Errno 2] No such file or directory: 'C:\\\xef\xbb\xbf\xe5\x9c\x8b\xe7\xab\x8b\xe5\x9c\x8b\xe8\xaa\x9e...
[ "I think you should just be able to do execfile(afile) with a unicode argument on Windows, but I can't test it.\nIf not, get the file system encoding:\nimport sys\nfsenc = sys.getfilesystemencoding()\nexecfile(afile.encode(fsenc))\n\n", "@Thomas K's answer should work (it works on Linux and doesn't work in Wine o...
[ 2, 2 ]
[]
[]
[ "encoding", "execfile", "python", "unicode", "windows" ]
stackoverflow_0005855550_encoding_execfile_python_unicode_windows.txt
Q: Check if the integer in a list is not duplicated, and sequential testGroupList is a list of integer. I need to check the numbers in testGroupList is sequential and not duplicate numbers. Ignore the negative integer. For example, [1,2,-1,2,3,4] is an error as 2 is duplicated, but [-1,3,2,4,1,5] is OK. I implement...
Check if the integer in a list is not duplicated, and sequential
testGroupList is a list of integer. I need to check the numbers in testGroupList is sequential and not duplicate numbers. Ignore the negative integer. For example, [1,2,-1,2,3,4] is an error as 2 is duplicated, but [-1,3,2,4,1,5] is OK. I implemented it as follows, and it's pretty ugly. Is there any clever way to do ...
[ "For Python2.7 or 3.1 you can use Counter, although the print needs to be changed in the case of Python3\nfrom collections import Counter\ncounter = Counter(x for x in testGroupList if x>=0)\nminval = min(Counter) \nmaxval = max(Counter)\nmessages={0:\"(Test Group %(id)d missing)\",\n 1:\"%(id)d\",\n ...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002429073_python.txt
Q: How can I eliminate my custom __import__ hook from Python backtraces I'm the implementor of the Lazy Python Reloader, and it's all working wonderfully, except that once I overrode the builtin __import__ function, I started seeing my replacement in tracebacks whenever there was an error in a module being loaded. F...
How can I eliminate my custom __import__ hook from Python backtraces
I'm the implementor of the Lazy Python Reloader, and it's all working wonderfully, except that once I overrode the builtin __import__ function, I started seeing my replacement in tracebacks whenever there was an error in a module being loaded. For example, there are two instances of _real_import in the following, that...
[ "You can but you also shouldn't (even the standard library's runpy module leaves itself in the stack trace when the main module is executed via the -m switch). When an exception escapes all the way to the top level of a program, it's hard to know in advance exactly which components were at fault (and the fact that ...
[ 2, 1 ]
[]
[]
[ "built_in", "import", "python", "traceback" ]
stackoverflow_0005852148_built_in_import_python_traceback.txt
Q: Deploying matlab app on the web using python Hi I want to deploy a matlab application on the web using python. Is there a way to do it.I have converted my application into jar files (java classes) as per the documentation on math works site. Can someone point me in the right direction to go ahead A: The fact tha...
Deploying matlab app on the web using python
Hi I want to deploy a matlab application on the web using python. Is there a way to do it.I have converted my application into jar files (java classes) as per the documentation on math works site. Can someone point me in the right direction to go ahead
[ "The fact that your Matlab code is packaged up as Jars may not help that much here, at least not with pure Python. \nThere are a few ways you can take code written in Java and expose it to Python.\nJython\nIf you are willing to give Jython a shot this may be a really easy way to provide a Django interface to your ...
[ 6 ]
[]
[]
[ "django", "flask", "matlab", "python" ]
stackoverflow_0005831495_django_flask_matlab_python.txt
Q: App engine query retrieve data with index reference class Entry(Base): amount = db.IntegerProperty() entries = Entry.gql("WHERE amount > 0") Is there a way to refer to entries result with an index as an array, for example my_entry = entries[4] A: entries = [x for x in Entry.gql("WHERE amount > 0")] The di...
App engine query retrieve data with index reference
class Entry(Base): amount = db.IntegerProperty() entries = Entry.gql("WHERE amount > 0") Is there a way to refer to entries result with an index as an array, for example my_entry = entries[4]
[ "entries = [x for x in Entry.gql(\"WHERE amount > 0\")]\nThe distinction between this and previous answers is that it filters at the datastore rather than in the handler, and doesn't require you to guess the maximum number of entities that will be returned.\n", "You could use the fetch() method on the Query insta...
[ 3, 2, 1, 1 ]
[ "entries= [entry for entry from Entry.all() if entry.amount > 0]\nprint entries[4]\n\n" ]
[ -1 ]
[ "google_app_engine", "gql", "python" ]
stackoverflow_0005855488_google_app_engine_gql_python.txt
Q: Practical Django Projects - Pages 183 and 184 On pages 183 and 184 there is the following code : def edit_snippet(request, snippet_id): snippet = get_object_or_404(Snippet, pk=snippet_id) if request.user.id != snippet.author.id: return HttpResponseForbidden() if request.method == 'POST': ...
Practical Django Projects - Pages 183 and 184
On pages 183 and 184 there is the following code : def edit_snippet(request, snippet_id): snippet = get_object_or_404(Snippet, pk=snippet_id) if request.user.id != snippet.author.id: return HttpResponseForbidden() if request.method == 'POST': form = SnippetForm(instance=snippet, data=request...
[ "It is Django way of doing:\nthe same view is used to show the form for editing (GET) and then to validate it (POST).\nSee this example in docs:\n\nThe standard pattern for processing a\n form in a view looks like this:\ndef contact(request):\n if request.method == 'POST': # If the form has been submitted...\n ...
[ 2, 1 ]
[]
[]
[ "django", "projects", "python" ]
stackoverflow_0005857724_django_projects_python.txt