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: How to write a Python 2.6+ script that gracefully fails with older Python? I'm using the new print from Python 3.x and I observed that the following code does not compile due to the end=' '. from __future__ import print_function import sys if sys.hexversion < 0x02060000: raise Exception("py too old") ... pri...
How to write a Python 2.6+ script that gracefully fails with older Python?
I'm using the new print from Python 3.x and I observed that the following code does not compile due to the end=' '. from __future__ import print_function import sys if sys.hexversion < 0x02060000: raise Exception("py too old") ... print("x",end=" ") # fails to compile with py24 How can I continue using the new s...
[ "The easy method for Python 2.6 is just to add a line like:\nb'You need Python 2.6 or later.'\n\nat the start of the file. This exploits the fact that byte literals were introduced in 2.6 and so any earlier versions will raise a SyntaxError with whatever message you write given as the stack trace.\n", "There are ...
[ 8, 2, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003035749_python_python_3.x.txt
Q: monitor keyboard events with python in windows 7 Is there any way to monitor keyboard events in windows 7 with python without the python program having focus? I would like to run the python script as a background process that monitors certain keyboard events and does certain things on various keyboard input combin...
monitor keyboard events with python in windows 7
Is there any way to monitor keyboard events in windows 7 with python without the python program having focus? I would like to run the python script as a background process that monitors certain keyboard events and does certain things on various keyboard input combinations.
[ "Ok, I got pyHook working after installing the 32bit version of python 2.7 and compiling pyHook from the source with MinGW. Thanks for the pointers everyone.\n" ]
[ 2 ]
[]
[]
[ "event_handling", "events", "python", "windows_7" ]
stackoverflow_0003476183_event_handling_events_python_windows_7.txt
Q: wxPython SetBackgroundColour not working on OS X I haven't had to do any GUI programming in a long time, so I might be being obtuse here, so please bear with me if this is a stupid question. I decided to use wxPython for a small hobby project, and I'm having trouble changing the background colour of the main windo...
wxPython SetBackgroundColour not working on OS X
I haven't had to do any GUI programming in a long time, so I might be being obtuse here, so please bear with me if this is a stupid question. I decided to use wxPython for a small hobby project, and I'm having trouble changing the background colour of the main window. I'm using Python 2.6.2 and wxPython 2.8.11.0 on Sno...
[ "Your call to self.SetBackgroundStyle(BG_STYLE_CUSTOM) seems to be causing trouble on my system, and also you don't need the line for self.cdatabase = ColourDatabase() at all in my tests. This code works on my side of things:\nfrom wx import * \n\nclass MainFrame(Frame):\n def __init__(self, parent, title):\n ...
[ 1, 1 ]
[]
[]
[ "macos", "python", "wxpython" ]
stackoverflow_0003472609_macos_python_wxpython.txt
Q: Converting to Twisted Asynchronous Design Ok I have had a problem expressing my problems with the code I am working on without dumping a ton of code; so here is what it would be synchronously (instead of asking it from the view of it being async). Also for classes when should a variable be accessed through a meth...
Converting to Twisted Asynchronous Design
Ok I have had a problem expressing my problems with the code I am working on without dumping a ton of code; so here is what it would be synchronously (instead of asking it from the view of it being async). Also for classes when should a variable be accessed through a method argument and when should it be accessed thro...
[ "Given the circumstances, this just a skeleton of a solution which much implied. It seems to go against instinct to provide a solution with code where much is implied and untested...\nHowever, if I was coding what I think you're trying to achieve, I might go about it something like this:\nfrom twisted.internet impo...
[ 5 ]
[]
[]
[ "asynchronous", "python", "twisted" ]
stackoverflow_0003463496_asynchronous_python_twisted.txt
Q: How to avoid writing the name of the module all the time when importing a module in python? I use the math module a lot lately. I don't want to write math.sqrt(x) and math.sin(x) all the time. I would like to shorten it and write sqrt(x) and sin(x). How? A: For longer module names it is common to shorten them, e...
How to avoid writing the name of the module all the time when importing a module in python?
I use the math module a lot lately. I don't want to write math.sqrt(x) and math.sin(x) all the time. I would like to shorten it and write sqrt(x) and sin(x). How?
[ "For longer module names it is common to shorten them, e.g.\nimport numpy as np\n\nThen you can use the short name. Or you can import the specific stuff that you need, as shown in the other anwsers:\nfrom math import sin, sqrt\n\nThis is often used inside packages, for code that is more closely coupled. For librari...
[ 7, 5, 5, 1 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0003476509_import_module_python.txt
Q: C++ methods overload in python suppose a C++ class has several constructors which are overloaded according the number and type and sequences of their respective parameters, for example, constructor(int x, int y) and constructor(float x, float y, float z), I think these two are overloaded methods, which one to use ...
C++ methods overload in python
suppose a C++ class has several constructors which are overloaded according the number and type and sequences of their respective parameters, for example, constructor(int x, int y) and constructor(float x, float y, float z), I think these two are overloaded methods, which one to use depends on the parameters, right? So...
[ "Usually, you're fine with any combination of\n\nslightly altered design\ndefault arguments (def __init__(self, x = 0.0, y = 0.0, z = 0.0))\nuse of polymorphism (in a duck-typed language, you don't need an overload for SomeThing vs SomeSlightlyDifferentThing if neither inherits from the other one, as long as their ...
[ 3, 1, 0 ]
[ "This article talks about how a multimethod decorator can be created in Python. I haven't tried out the code that they give, but the syntax that it defines looks quite nice. Here's an example from the article:\nfrom mm import multimethod\n\n@multimethod(int, int)\ndef foo(a, b):\n ...code for two ints...\n\n@mul...
[ -2 ]
[ "c++", "constructor", "overloading", "python" ]
stackoverflow_0003476387_c++_constructor_overloading_python.txt
Q: Is there a lib to generate data according to a regexp? (Python or other) Given a regexp, I would like to generate random data x number of time to test something. e.g. >>> print generate_date('\d{2,3}') 13 >>> print generate_date('\d{2,3}') 422 Of course the objective is to do something a bit more complicated than...
Is there a lib to generate data according to a regexp? (Python or other)
Given a regexp, I would like to generate random data x number of time to test something. e.g. >>> print generate_date('\d{2,3}') 13 >>> print generate_date('\d{2,3}') 422 Of course the objective is to do something a bit more complicated than that such as phone numbers and email addresses. Does something like this exis...
[ "Pyparsing includes this regex inverter, which returns a generator of all permutations for simple regexes. Here are some of the test cases from that module:\n[A-C]{2}\\d{2}\n@|TH[12]\n@(@|TH[12])?\n@(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9]))?\n@(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9])|OH(1[0-9]?|2[0-9]?...
[ 8, 2, 1 ]
[]
[]
[ "data_generation", "python", "regex" ]
stackoverflow_0003477300_data_generation_python_regex.txt
Q: "pythonic" method to parse a string of comma-separated integers into a list of integers? I am reading in a string of integers such as "3 ,2 ,6 " and want them in the list [3,2,6] as integers. This is easy to hack about, but what is the "pythonic" way of doing it? A: mylist = [int(x) for x in '3 ,2 ,6 '.split(',...
"pythonic" method to parse a string of comma-separated integers into a list of integers?
I am reading in a string of integers such as "3 ,2 ,6 " and want them in the list [3,2,6] as integers. This is easy to hack about, but what is the "pythonic" way of doing it?
[ "mylist = [int(x) for x in '3 ,2 ,6 '.split(',')]\n\nAnd if you're not sure you'll only have digits (or want to discard the others):\nmylist = [int(x) for x in '3 ,2 ,6 '.split(',') if x.strip().isdigit()]\n\n", "map( int, myString.split(',') )\n\n", "While a custom solution will teach you about Python, for pro...
[ 31, 25, 9 ]
[]
[]
[ "python" ]
stackoverflow_0003477502_python.txt
Q: replace empty datasets Sorry, I agree that was really poorly written: Take 2: I have many columns of data (up to 63) in over 50 datasets. I am extracting only 3 columns of data that I need and writing it into a new .csv file. There are a few of my datasets that do not have the third desired column of data. But ...
replace empty datasets
Sorry, I agree that was really poorly written: Take 2: I have many columns of data (up to 63) in over 50 datasets. I am extracting only 3 columns of data that I need and writing it into a new .csv file. There are a few of my datasets that do not have the third desired column of data. But that's okay I can leave it b...
[ "Based on the error message, I'm guessing you have a list of lists that looks something like this (a gross simplification):\n[[0,1,2,3],\n[1,2,3,4,5],\n[1,2,3],\n[1,2,3]]\n\nAnd you are trying to do the following:\nfor row in xrange(4):\n for col in xrange(4):\n #something else?\n print data[row][col]...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003477058_python.txt
Q: How to assign a value to a variable when writing the value takes multiple lines (python) I have a variable x to which I want to assign a very long string. Since the string is pretty long I split it into 10 substrings. I would like to do something like this: x = 'a very long string - part 1'+ 'a very long str...
How to assign a value to a variable when writing the value takes multiple lines (python)
I have a variable x to which I want to assign a very long string. Since the string is pretty long I split it into 10 substrings. I would like to do something like this: x = 'a very long string - part 1'+ 'a very long string - part 2'+ 'a very long string - part 3'+ ... 'a very long string - ...
[ "If you want a string with no line-feeds, you could\n>>> x = (\n... 'a very long string - part 1' +\n... 'a very long string - part 2' +\n... 'a very long string - part 3' )\n>>> x\n'a very long string - part 1a very long string - part 2a very long string - part 3'\n>>> \n\nThe + operator is not necessary with stri...
[ 5, 4 ]
[]
[]
[ "python", "string", "variable_assignment" ]
stackoverflow_0003477592_python_string_variable_assignment.txt
Q: Making python like system calls in java Is there an equivalent to Python's popen2 in Java? A: I believe the Process object is what you're looking for. Javadoc here. You use it something like Process myProcess = System.getRuntime().exec("cmd here")); It allows you to get the standard and error output streams. A:...
Making python like system calls in java
Is there an equivalent to Python's popen2 in Java?
[ "I believe the Process object is what you're looking for. Javadoc here. You use it something like Process myProcess = System.getRuntime().exec(\"cmd here\")); It allows you to get the standard and error output streams.\n", "System.getRuntime().exec(...)\nSystem.getRuntime() yields the Runtime object, from which y...
[ 4, 3 ]
[]
[]
[ "java", "python", "runtime.exec", "shell", "unix" ]
stackoverflow_0003478033_java_python_runtime.exec_shell_unix.txt
Q: is fftshift broken in scipy? I use the latest version of numpy/scipy. The following script does not work: import numpy as np import matplotlib.pyplot as plt from scipy.fftpack import fft, fftshift, fftfreq hn= np.ones(10) hF = fft(hn,1024) shifted = fftshift(hF) It gives the following error message:...
is fftshift broken in scipy?
I use the latest version of numpy/scipy. The following script does not work: import numpy as np import matplotlib.pyplot as plt from scipy.fftpack import fft, fftshift, fftfreq hn= np.ones(10) hF = fft(hn,1024) shifted = fftshift(hF) It gives the following error message: Traceback (most recent call las...
[ "You should fill in a bug report on http://www.scipy.org/BugReport\n", "Works fine with my setup, if it's a bug in the current version try installing an older copy and filling out a report.\n>>> import numpy as np\n>>> import matplotlib.pyplot as plt\n>>> from scipy.fftpack import fft, fftshift, fftfreq\n>>> hn= ...
[ 1, 0 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0003477649_numpy_python_scipy.txt
Q: repeat y axis scale along grid line of graph ( matplotlib) I am new to matplotlib and I am trying to figure out if I can repeat the y axis scale values along the grid lines of the line graph. The graph has 2 axis, x-axis has hourly values and y-axis has temperature values. I need to show the graph for 48 hours,...
repeat y axis scale along grid line of graph ( matplotlib)
I am new to matplotlib and I am trying to figure out if I can repeat the y axis scale values along the grid lines of the line graph. The graph has 2 axis, x-axis has hourly values and y-axis has temperature values. I need to show the graph for 48 hours, so it results in a long horizontal graph. when user scrolls thr...
[ "You might take a look at the colorbar from this example:\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.collections import EllipseCollection\n\nx = np.arange(10)\ny = np.arange(15)\nX, Y = np.meshgrid(x, y)\n\nXY = np.hstack((X.ravel()[:,np.newaxis], Y.ravel()[:,np.newaxis]))\n\nww = X/10.0\...
[ 1 ]
[]
[]
[ "graph", "matplotlib", "python" ]
stackoverflow_0003478320_graph_matplotlib_python.txt
Q: django orm and 3 relations I have a problem to transpose my sql request in the orm. Well, this my sql request : SELECT DISTINCT accommodation.id from accommodation LEFT JOIN product on product.accommodation_id=accommodation.id LEFT JOIN date on date.product_id = product.id WHERE date.begin> '2010-08-13'; So i wa...
django orm and 3 relations
I have a problem to transpose my sql request in the orm. Well, this my sql request : SELECT DISTINCT accommodation.id from accommodation LEFT JOIN product on product.accommodation_id=accommodation.id LEFT JOIN date on date.product_id = product.id WHERE date.begin> '2010-08-13'; So i want all the accommodations for a ...
[ "This should do what you want:\n Accommodation.objects.filter(product__date__begin__gte=values['start_day'])\n\n" ]
[ 3 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0003478346_django_orm_python.txt
Q: subprocess.Popen() has inconsistent behavior between Eclipse/PyCharm and terminal execution The problem I'm having is with Eclipse/PyCharm interpreting the results of subprocess's Popen() differently from a standard terminal. All are using python2.6.1 on OSX. Here's a simple example script: import subprocess args...
subprocess.Popen() has inconsistent behavior between Eclipse/PyCharm and terminal execution
The problem I'm having is with Eclipse/PyCharm interpreting the results of subprocess's Popen() differently from a standard terminal. All are using python2.6.1 on OSX. Here's a simple example script: import subprocess args = ["/usr/bin/which", "git"] print "Will execute %s" % " ".join(args) try: p = subprocess.Popen...
[ "Ok, found the problem, and it's an important thing to keep in mind when using an IDE in a Unix-type environment. IDE's operate under a different environment context than the terminal user (duh, right?!). I was not considering that the subprocess was using a different environment than the context that I have for my...
[ 15 ]
[]
[]
[ "eclipse", "popen", "pycharm", "python", "subprocess" ]
stackoverflow_0003460130_eclipse_popen_pycharm_python_subprocess.txt
Q: How do I dynamically add an attribute to a module from within that module? Say in a module I want to define: a = 'a' b = 'b' ... z = 'z' For some set (in this case I chose letters). How do I dynamically set attributes on the current module? Something like: for letter in ['a', ..., 'z']: setattr(globals(), l...
How do I dynamically add an attribute to a module from within that module?
Say in a module I want to define: a = 'a' b = 'b' ... z = 'z' For some set (in this case I chose letters). How do I dynamically set attributes on the current module? Something like: for letter in ['a', ..., 'z']: setattr(globals(), letter, letter) This doesn't work, but what would? (Also my understanding is th...
[ "globals() returns the dictionary of the current module, so you add items to it as you would to any other dictionary. Try:\nfor letter in ['a', ..., 'z']:\n globals()[letter] = letter\n\nor to eliminate the repeated call to globals():\nglobal_dict = globals()\nfor letter in ['a', ..., 'z']:\n global_dict[let...
[ 10 ]
[]
[]
[ "python" ]
stackoverflow_0003478716_python.txt
Q: Inspecting urllib2.Request attributes when using OpenerDirector with handlers Is it possible to inspect the attributes of an Python urllib2.Request (url, data, headers etc) when using an urllib2.OpenerDirector: cookie_jar = cookielib.CookieJar() opener = urllib2.OpenerDirector() opener.add_handler(urllib2.Prox...
Inspecting urllib2.Request attributes when using OpenerDirector with handlers
Is it possible to inspect the attributes of an Python urllib2.Request (url, data, headers etc) when using an urllib2.OpenerDirector: cookie_jar = cookielib.CookieJar() opener = urllib2.OpenerDirector() opener.add_handler(urllib2.ProxyHandler()) opener.add_handler(urllib2.UnknownHandler()) opener.add_handler(urllib2...
[ "I'm not sure which attributes you're looking for exactly, but hopefully this answers your question. All of those attributes are in the Request class. To inspect the ones you listed, you can use these:\nurl = request.get_full_url()\ndata = request.get_data()\nheaders = request.headers\n\nThere are also functions to...
[ 2 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0003478293_python_urllib2.txt
Q: Help Creating Python Class with Tkinter How do I create a class called rectangle that I can pass it the coordinates and a color and have it fill those one? from Tkinter import * master = Tk() w = Canvas(master, width=300, height=300) w.pack() class rectangle(): def make(self, ulx, uly, lrx, lry, color): ...
Help Creating Python Class with Tkinter
How do I create a class called rectangle that I can pass it the coordinates and a color and have it fill those one? from Tkinter import * master = Tk() w = Canvas(master, width=300, height=300) w.pack() class rectangle(): def make(self, ulx, uly, lrx, lry, color): self.create_rectangle(ulx, uly, lrx, lry...
[ "Here is one way of doing it. First, to draw the rectangle on the Tk Canvas you need to call the create_rectangle method of the Canvas. I also use the __init__ method to store the attributes of the rectangle so that you only need to pass the Canvas object as a parameter to the rectangle's draw() method.\nfrom Tkint...
[ 3 ]
[]
[]
[ "class", "python", "tkinter" ]
stackoverflow_0003479265_class_python_tkinter.txt
Q: Renaming OS files I am trying to rename files based on their extensions. Below is my code, Somehow my os.rename isn't working. There aren't any errors though. I got no idea what is wrong. Hope you guys could help. Thanks. import os import glob directory = raw_input("directory? ") ext = raw_input("file extension? "...
Renaming OS files
I am trying to rename files based on their extensions. Below is my code, Somehow my os.rename isn't working. There aren't any errors though. I got no idea what is wrong. Hope you guys could help. Thanks. import os import glob directory = raw_input("directory? ") ext = raw_input("file extension? ") r = raw_input("replac...
[ "I get an error: \ndirectory? c:\\breakup\nfile extension? .txt\nreplace name? test\nTraceback (most recent call last):\n File \"foo.py\", line 25, in <module>\n new_name = os.rename(path, newpathext)\nWindowsError: [Error 2] The system cannot find the file specified\nshell returned 1\n\nAnyhow, it looks like y...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003478237_python.txt
Q: How do I dynamically create a function with the same signature as another function? I'm busy creating a metaclass that replaces a stub function on a class with a new one with a proper implementation. The original function could use any signature. My problem is that I can't figure out how to create a new function w...
How do I dynamically create a function with the same signature as another function?
I'm busy creating a metaclass that replaces a stub function on a class with a new one with a proper implementation. The original function could use any signature. My problem is that I can't figure out how to create a new function with the same signature as the old one. How would I do this? Update This has nothing to do...
[ "I believe functools.wraps does not reproduce the original call signature. However, Michele Simionato's decorator module does:\nimport decorator\n\nclass FooType(type):\n def __init__(cls,name,bases,clsdict):\n @decorator.decorator \n def modify_stub(func, *args,**kw):\n return fu...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003479412_python.txt
Q: Accessing the same function from two different classes I have two classes, suppose A and B. Within B, I instantiate A. I have a function func() that is required by both the classes. How should I go about it? I had thought of this approach: class A: func() class B: x = A() func() def func(): And then I...
Accessing the same function from two different classes
I have two classes, suppose A and B. Within B, I instantiate A. I have a function func() that is required by both the classes. How should I go about it? I had thought of this approach: class A: func() class B: x = A() func() def func(): And then I can access func() from within A or B. Is this approach OK o...
[ "Define func before you define either class, and it will be available to both.\n", "func here can me a method of common base class\nclass Base(object):\n def func():\n #...\nclass A(Base):\n #...\nclass B(Base):\n #...\n\n" ]
[ 1, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003479514_oop_python.txt
Q: Importing module with context I have a module named module.py, which checks a global variable in context. module.py: ---------- if 'FOO' in globals(): print 'FOO in globals' else: print 'nah' in python shell: ---------------- In [1]: FOO = True In [2]: import module nah how can I import modules with e...
Importing module with context
I have a module named module.py, which checks a global variable in context. module.py: ---------- if 'FOO' in globals(): print 'FOO in globals' else: print 'nah' in python shell: ---------------- In [1]: FOO = True In [2]: import module nah how can I import modules with existing context?
[ "This is rather hackish -- don't rely on this for production code since not all implementations of Python have a inspect.getouterframes function. However, this works in CPython:\nimport inspect\nrecord=inspect.getouterframes(inspect.currentframe())[1]\nframe=record[0]\n\nif 'FOO' in frame.f_globals:\n print 'FOO...
[ 2, 0 ]
[]
[]
[ "global", "import", "python", "scope" ]
stackoverflow_0003479934_global_import_python_scope.txt
Q: need help optimizing a geo algorithm using a map() operation, lists, floats and some validation Im doing som route(geo) calculations. I need to sort out some routes going in the "wrong" direction... all rides have "routes" and all routes consist of a lot of steps on the route.... each step has a lat. and a lng. ...
need help optimizing a geo algorithm using a map() operation, lists, floats and some validation
Im doing som route(geo) calculations. I need to sort out some routes going in the "wrong" direction... all rides have "routes" and all routes consist of a lot of steps on the route.... each step has a lat. and a lng. pair. I hope this makes sense? This is the way i do it now, and it works... however... im performin...
[ "To speed this up you should probably be using a better algorithm instead of trying all possible solutions. A* is a classic heuristic that could work on your problem.\nYou can try a comprehension like \napproved_rides = [ride for ride in initial_rides if any(\n (lat_min < step.latitude< lat_max and \\\n ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003479989_python.txt
Q: How to setup web2py fixtures I'm trying to find a way to create fixtures for my web2py application. I came across http://thadeusb.com/weblog/2010/4/21/using_fixtures_in_web2py that suggests creating a x_fixtures.py file to place all the fixtures in. The problem is that after a while, the file gets huge and a pain...
How to setup web2py fixtures
I'm trying to find a way to create fixtures for my web2py application. I came across http://thadeusb.com/weblog/2010/4/21/using_fixtures_in_web2py that suggests creating a x_fixtures.py file to place all the fixtures in. The problem is that after a while, the file gets huge and a pain to navigate through. What I want ...
[ "Well, I couldn't figure out how to get the fixtures to work while in the directory I created web2py/applications/MyApp/tests/fixtures, but I did get fixtures to work how I wanted by simply creating a web2py/applications/MyApp/models/fixtures directory and placing a separate file for each table I want fixtures for ...
[ 1 ]
[]
[]
[ "fixtures", "python", "web2py" ]
stackoverflow_0003477424_fixtures_python_web2py.txt
Q: A simple Python HTTP proxy What is the simplest way to create a HTTP proxy with Python? As far as I can understand, it should be possible to create the proxy relatively easily with a couple lines of code using the standard library HTTP server features and urlopen or Requests. A: One incredibly simple one is pyth...
A simple Python HTTP proxy
What is the simplest way to create a HTTP proxy with Python? As far as I can understand, it should be possible to create the proxy relatively easily with a couple lines of code using the standard library HTTP server features and urlopen or Requests.
[ "One incredibly simple one is python-proxy. I found it on the list of python proxies at xhaus, which was the top result when I googled \"python proxy server\" (sans quotes).\n", "Twisted lets you build simple ones, if you don't mind the complexity that is twisted.\n" ]
[ 7, 4 ]
[]
[]
[ "proxy", "python" ]
stackoverflow_0003480147_proxy_python.txt
Q: How to close stdout/stderr window in python? In my python app, I print some stuff during a cycle. After the cycle, I want to close the stdout/stderr window that the prints produced using python code. A: import sys sys.stdout.close() sys.stderr.close() Might be what you want. This will certainly close stdout/s...
How to close stdout/stderr window in python?
In my python app, I print some stuff during a cycle. After the cycle, I want to close the stdout/stderr window that the prints produced using python code.
[ "import sys\n\nsys.stdout.close()\nsys.stderr.close()\n\nMight be what you want. This will certainly close stdout/stderr at any rate.\n", "If you mean the prompt window that opens when you run a Python script on MS Windows, try specifying the executable pythonw instead of python, on the first line of your script...
[ 7, 0 ]
[]
[]
[ "printing", "python", "window" ]
stackoverflow_0003480371_printing_python_window.txt
Q: Twisted vs Google App Engine in serving mobile clients So far I have been using Twisted to simultaneously serve a lot of mobile clients (Android, iPhone) with their HTTP requests exchanging JSON messages. For my next project I'd like to try out Google App Engine, but I'm wondering if it is capable of doing the sam...
Twisted vs Google App Engine in serving mobile clients
So far I have been using Twisted to simultaneously serve a lot of mobile clients (Android, iPhone) with their HTTP requests exchanging JSON messages. For my next project I'd like to try out Google App Engine, but I'm wondering if it is capable of doing the same or if I should rather go with a custom built solution agai...
[ "Certainly. App Engine will scale your application up as the load increases automatically and will be spread over many machines. The web api they have is pretty nice too. You don't have to worry about deferreds either because it scales by bringing more instances up instead of making things asynchronous.\nBTW: I hav...
[ 6 ]
[]
[]
[ "google_app_engine", "python", "twisted" ]
stackoverflow_0003480524_google_app_engine_python_twisted.txt
Q: Is it good style to call bash commands within a Python script using os.system("bash code")? I was wondering whether or not it is considered a good style to call bash commands within a Python script using os.system(). I was also wondering whether or not it is safe to do so as well. I know how to implement some of t...
Is it good style to call bash commands within a Python script using os.system("bash code")?
I was wondering whether or not it is considered a good style to call bash commands within a Python script using os.system(). I was also wondering whether or not it is safe to do so as well. I know how to implement some of the functionality I need in Bash and in Python, but it is much simpler and more intuitive to imple...
[ "First of all, your example uses mv, which is a program in coreutils, not bash.\nUsing os.system() calls to external programs is considered poor style because:\n\nYou are creating platform-specific dependencies\nYou are creating version-specific dependencies (Yes, even coreutils change sometimes!)\nYou need to chec...
[ 18, 6, 3, 2, 1, 1, 0 ]
[]
[]
[ "bash", "embedding", "python", "scripting", "security" ]
stackoverflow_0003479728_bash_embedding_python_scripting_security.txt
Q: Algorithm Help: Building game board, but need to know when square is locked in I have built a gameboard that consists of a grid, the grid is then randomly assigned, "Walls" to a cell. Once the cells are built, how can I check to see if a certain cell is 'locked in' so that I don't place a player there. I have t...
Algorithm Help: Building game board, but need to know when square is locked in
I have built a gameboard that consists of a grid, the grid is then randomly assigned, "Walls" to a cell. Once the cells are built, how can I check to see if a certain cell is 'locked in' so that I don't place a player there. I have thought about this and the first ago I came up with check all sides for four walls, b...
[ "You basically want a floodfill algorithm.\nhttp://en.wikipedia.org/wiki/Floodfill\nedit\nI think I misunderstood your definitions of 'locked' and 'escape'.\nIf you have limited game board, every cell there is locked in some space. If I understand you correctly, you just want that space to be big enough. Well, you ...
[ 2, 1, 1, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0003480515_algorithm_python.txt
Q: VCS checkout based on a file I want to checkout a bunch of files from a CVS server. Is there a way I can pass cvs command a file name which contains files I want to checkout Is there another way of accomplishing that? A: You might want to take a look at the docs for the CVSROOT/modules file and then define a reg...
VCS checkout based on a file
I want to checkout a bunch of files from a CVS server. Is there a way I can pass cvs command a file name which contains files I want to checkout Is there another way of accomplishing that?
[ "You might want to take a look at the docs for the CVSROOT/modules file and then define a regular module like this:\nMyModule folder file1 file2 file3 [...]\n\nYou would then be able to do:\ncvs co MyModule\n\n", "Assuming you are using a bash-style shell:\ncvs co $(< myfile)\n\nWhere myfile contains the list of ...
[ 1, 1 ]
[]
[]
[ "cvs", "python", "scripting", "vcs_checkout" ]
stackoverflow_0003423666_cvs_python_scripting_vcs_checkout.txt
Q: Sorting scheduled events python So I have list of events that are sort of like alarms. They're defined by their start and end time (in hours and minutes), a range of days (ie 1-3 which is sunday through wed.), and a range of months (ie 1-3, january through march). The format of that data is largely unchangeable. I...
Sorting scheduled events python
So I have list of events that are sort of like alarms. They're defined by their start and end time (in hours and minutes), a range of days (ie 1-3 which is sunday through wed.), and a range of months (ie 1-3, january through march). The format of that data is largely unchangeable. I need to, not necessarily sort the li...
[ "Convert the items from the schedule into datetime objects. Then you can simply sort them\nfrom datetime import datetime\nevents = sorted(datetime(s.year, s.month, s.day, s.hour, s.minute) for s in schedule)\n\n", "Since your resolution is in minutes, and assuming that you don't have many events, then I'd simply ...
[ 1, 1, 1, 0 ]
[]
[]
[ "calendar", "date", "python", "sorting" ]
stackoverflow_0003471923_calendar_date_python_sorting.txt
Q: Union-within-structure syntax in ctypes Quick question about ctypes syntax, as documentation for Unions isn't clear for a beginner like me. Say I want to implement an INPUT structure (see here): typedef struct tagINPUT { DWORD type; union { MOUSEINPUT mi; KEYBDINPUT ki; HARDWAREINPUT hi; } ...
Union-within-structure syntax in ctypes
Quick question about ctypes syntax, as documentation for Unions isn't clear for a beginner like me. Say I want to implement an INPUT structure (see here): typedef struct tagINPUT { DWORD type; union { MOUSEINPUT mi; KEYBDINPUT ki; HARDWAREINPUT hi; } ; } INPUT, *PINPUT; Should I or do I need to...
[ "Your Structure syntax isn't valid:\nAttributeError: '_fields_' must be a sequence of pairs\n\nI believe you want to use the anonymous attribute in your ctypes.Structure. It looks like the ctypes documentation creates a TYPEDESC structure (which is very similar in construction to the tagINPUT).\nAlso note that you...
[ 11 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0003480240_ctypes_python.txt
Q: Python csv: UnicodeDecodeError I'm reading in a file with Python's csv module, and have Yet Another Encoding Question (sorry, there are so many on here). In the CSV file, there are £ signs. After reading the row in and printing it, they have become \xa3. Trying to encode them as Unicode produces a UnicodeDecodeE...
Python csv: UnicodeDecodeError
I'm reading in a file with Python's csv module, and have Yet Another Encoding Question (sorry, there are so many on here). In the CSV file, there are £ signs. After reading the row in and printing it, they have become \xa3. Trying to encode them as Unicode produces a UnicodeDecodeError: row = [unicode(x.strip()) for ...
[ "Try using the \"ISO-8859-1\" for your encoding. It seems like you are dealing with extended ASCII, not Unicode.\nEdit:\nHere's some simple code that deals with extended ASCII:\n>>> s = \"La Pe\\xf1a\"\n>>> print s\nLa Pe±a\n>>> print s.decode(\"latin-1\")\nLa Peña\n>>>\n\nEven better, dealing with the exact charac...
[ 7, 0 ]
[]
[]
[ "csv", "encoding", "python" ]
stackoverflow_0003479961_csv_encoding_python.txt
Q: Analyse data using time and date objects I have a rather unique problem I'm trying to solve: Based on this sample data (actual data is very many records, and at least 4 per card per day): serial, card, rec_date, rec_time, retrieved_on 2976 00040 2010-07-29 18:57 2010-07-31 13:37:31 2977 00040 2010-07-30 09:58 2...
Analyse data using time and date objects
I have a rather unique problem I'm trying to solve: Based on this sample data (actual data is very many records, and at least 4 per card per day): serial, card, rec_date, rec_time, retrieved_on 2976 00040 2010-07-29 18:57 2010-07-31 13:37:31 2977 00040 2010-07-30 09:58 2010-07-31 13:37:31 2978 00040 2010-07-30 15:3...
[ "Clearly, class TimeClock -- by itself -- is inadequate for what you're doing.\nYou need to summarize TimeClock to create WorkIntervals, which you can work with. These are pairs of TimeClock rows that show the (theoretical) start and end of a work span.\nIf someone fails to clock in, you're completely unable to re...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003479693_django_python.txt
Q: Problem with encode decode. Python. Django. BeautifulSoup In this code: soup=BeautifulSoup(program.Description.encode('utf-8')) name=soup.find('div',{'class':'head'}) print name.string.decode('utf-8') error happening when i'm trying to print or save to database. dosnt metter what i'm doing: print name.st...
Problem with encode decode. Python. Django. BeautifulSoup
In this code: soup=BeautifulSoup(program.Description.encode('utf-8')) name=soup.find('div',{'class':'head'}) print name.string.decode('utf-8') error happening when i'm trying to print or save to database. dosnt metter what i'm doing: print name.string.encode('utf-8') or just print name.string Traceback (m...
[ "I don't know what you are trying to do with name.string.decode('utf-8'). As the BeautifulSoup documentation eloquently points out, \"BeautifulSoup gives you Unicode, dammit\". So name.string is already decoded - it is in unicode. You can encode it back to utf-8 if you want to, but you can't decode it any further.\...
[ 5, 4, 0 ]
[ "try\ntext = text.decode(\"utf-8\", \"replace\")\n\n" ]
[ -1 ]
[ "beautifulsoup", "encoding", "python", "utf_8" ]
stackoverflow_0003480639_beautifulsoup_encoding_python_utf_8.txt
Q: python confusion: dict.pop I am really confused as to why Python acts in a particular way. Here is an example: I have a dictionary called "copy". (It is a copy of an HttpRequest.POST in django.) Here is a debug session (with added line numbers): 1 (Pdb) copy 2 <QueryDict: {u'text': [u'test'], u'otherId': [u'60002'...
python confusion: dict.pop
I am really confused as to why Python acts in a particular way. Here is an example: I have a dictionary called "copy". (It is a copy of an HttpRequest.POST in django.) Here is a debug session (with added line numbers): 1 (Pdb) copy 2 <QueryDict: {u'text': [u'test'], u'otherId': [u'60002'], u'cmd': [u'cA'], u'id': 3 [u...
[ "Have a look at the docs for QueryDicts. The short answer that it is a subclass of dict that modifies the way you get items, so that copy['text'] will return the last value in the list of values associated with 'text'. Since they haven't overridden pop, it will return the entire list.\nYou can use .getlist to get t...
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003481131_django_python.txt
Q: SQLAlchemy, self-referential secondary table association I'm trying to create a "Product" object in SQLAlchemy and so far I have gotten everything working accept the Product's "accessories". What I have is a Product with a list of field/value pairs (ie. Capacity : 12 L etc.), and integer ID and a catalog number. I...
SQLAlchemy, self-referential secondary table association
I'm trying to create a "Product" object in SQLAlchemy and so far I have gotten everything working accept the Product's "accessories". What I have is a Product with a list of field/value pairs (ie. Capacity : 12 L etc.), and integer ID and a catalog number. I would like to be able to associate certain "accessories" with...
[ "import sqlalchemy as sa\nfrom sqlalchemy import orm\n\nproducts_table = sa.Table('products', metadata,\n sa.Column('id', sa.Integer(), primary_key=True),\n sa.Column('catalog_number', sa.String(20)),\n)\n\naccessories_table = sa.Table('product_accessories', metadata,\n sa.Column('product_id', sa.ForeignKe...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003480602_python_sqlalchemy.txt
Q: Want all links that have 2 attributes, how do you pass 2 attributes? I know how to pass 1 attribute, but how do I pass 2? e.g. somerows = soup.findAll('a', target="blank") what if I want all links that have target="blank" and class="blah" ? A: You can use a dictionary to avoid having problems with some attribut...
Want all links that have 2 attributes, how do you pass 2 attributes?
I know how to pass 1 attribute, but how do I pass 2? e.g. somerows = soup.findAll('a', target="blank") what if I want all links that have target="blank" and class="blah" ?
[ "You can use a dictionary to avoid having problems with some attribute names such as 'class':\nsoup.findAll('a', {\n \"target\" : \"blank\",\n \"class\" : \"blah\",\n \"href\" : re.compile(...)\n})\n\nThis is mentioned in the documentation.\n", "soup.findAll('a', 'blah', target='blank', href=re.compile(....
[ 2, 1, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003481360_beautifulsoup_python.txt
Q: in a loop, only add to a dictionary or list or tuple if doesn't contains the key I am looping in python and want to add a key to a dictionary only if it isn't already in the collection. How can I do this? mydic = {} for x in range(100): ?? A: For a dict, it's easy and fast: for x in range(100): if x not i...
in a loop, only add to a dictionary or list or tuple if doesn't contains the key
I am looping in python and want to add a key to a dictionary only if it isn't already in the collection. How can I do this? mydic = {} for x in range(100): ??
[ "For a dict, it's easy and fast:\nfor x in range(100):\n if x not in mydic:\n mydic[x] = x # or whatever value you want\n\nthat is, just check with not in instead of in.\nThis is great for a dict. For a list, it's going to be extremely slow (quadratic); for speed, you need to add an auxiliary set (hopefully a...
[ 5 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003481414_dictionary_python.txt
Q: regex that matches a string that contains some text I need a regex that matches re.compile('userpage') href="www.example.com?u=userpage&as=233&p=1" href="www.example.com?u=userpage&as=233&p=2" I want to get all urls that have u=userpage and p=1 How can I modify the regex above to find both u=userpage and p=1? A...
regex that matches a string that contains some text
I need a regex that matches re.compile('userpage') href="www.example.com?u=userpage&as=233&p=1" href="www.example.com?u=userpage&as=233&p=2" I want to get all urls that have u=userpage and p=1 How can I modify the regex above to find both u=userpage and p=1?
[ "if you want to use, in my opinion, something more proper approach, than regexp:\nfrom urlparse import *\nurlparsed = urlparse('www.example.com?u=userpage&as=233&p=1')\n# -> ParseResult(scheme='', netloc='', path='www.example.com', params='', query='u=userpage&as=233&p=1', fragment='')\nqdict = dict(parse_qsl(urlpa...
[ 5, 4, 2, 0, 0 ]
[ "It is possible to do this with string hacking, but you shouldn't. It's already in the standard library:\n>>> import urllib.parse\n>>> urllib.parse.parse_qs(\"u=userpage&as=233&p=1\")\n{'u': ['userpage'], 'as': ['233'], 'p': ['1']}\n\nand hence\nimport urllib.parse\ndef filtered_urls( urls ):\n for url in urls:\...
[ -1 ]
[ "python", "regex" ]
stackoverflow_0003481378_python_regex.txt
Q: Python ctypes not loading dynamic library on Mac OS X I have a C++ library repeater.so that I can load from Python in Linux the following way: import numpy as np repeater = np.ctypeslib.load_library('librepeater.so', '.') However, when I compile the same library on Mac OS X (Sn...
Python ctypes not loading dynamic library on Mac OS X
I have a C++ library repeater.so that I can load from Python in Linux the following way: import numpy as np repeater = np.ctypeslib.load_library('librepeater.so', '.') However, when I compile the same library on Mac OS X (Snow Leopard, 32 bit) and get repeater.dylib, and then run th...
[ "It's not just a question of what architectures are available in the dylib; it's also a matter of which architecture the Python interpreter is running in. If you are using the Apple-supplied Python 2.6.1 in OS X 10.6, by default it runs in 64-bit mode if possible. Since you say your library was compiled as 32-bit...
[ 11, 4 ]
[]
[]
[ "ctypes", "dynamic_linking", "linux", "macos", "python" ]
stackoverflow_0003481508_ctypes_dynamic_linking_linux_macos_python.txt
Q: How should I configure Amazon EC2 to perform parallelizable data-intensive calculations? I have a computational intensive project that is highly parallelizable: basically, I have a function that I need to run on each observation in a large table (Postgresql). The function itself is a stored python procedure. A...
How should I configure Amazon EC2 to perform parallelizable data-intensive calculations?
I have a computational intensive project that is highly parallelizable: basically, I have a function that I need to run on each observation in a large table (Postgresql). The function itself is a stored python procedure. Amazon EC2 seems like an excellent fit for the project. My question is this: Should I make a c...
[ "you will definitely want to keep the data and the server instance separate in order for changes in your data to be persisted when you are done with the instance. your best bet will be to start with a basic image that has the OS & database platform you want to use, customize it to suit your needs, and then mount o...
[ 1, 1 ]
[]
[]
[ "amazon_ec2", "postgresql", "python" ]
stackoverflow_0003481285_amazon_ec2_postgresql_python.txt
Q: Python MySQL and Django problem I am having problems getting python/django to connect to a MySQL database. The error message is basically "Error Loading MySQLDb module: No module named MySQLDb". This is a fresh install right off python.org, so I assumed that it would have the MySQLDb module included, but it does n...
Python MySQL and Django problem
I am having problems getting python/django to connect to a MySQL database. The error message is basically "Error Loading MySQLDb module: No module named MySQLDb". This is a fresh install right off python.org, so I assumed that it would have the MySQLDb module included, but it does not seem to. I also can't seem to find...
[ "I believe http://pypi.python.org/pypi/MySQL-python/ is the Python module you need. In general, when looking for Python modules, http://pypi.python.org/ is where you should start (people will refer to it as either PyPI or \"the cheese shop.\" If setuptools is installed (it may be already) then you can run easy_inst...
[ 2, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0003432600_django_mysql_python.txt
Q: "x not in" vs. "not x in" I've noticed that both of these work the same: if x not in list and if not x in list. Is there some sort of difference between the two in certain cases? Is there a reason for having both, or is it just because it's more natural for some people to write one or the other? Which one am I mor...
"x not in" vs. "not x in"
I've noticed that both of these work the same: if x not in list and if not x in list. Is there some sort of difference between the two in certain cases? Is there a reason for having both, or is it just because it's more natural for some people to write one or the other? Which one am I more likely to see in other people...
[ "The two forms make identical bytecode, as you can clearly verify:\n>>> import dis\n>>> dis.dis(compile('if x not in d: pass', '', 'exec'))\n 1 0 LOAD_NAME 0 (x)\n 3 LOAD_NAME 1 (d)\n 6 COMPARE_OP 7 (not in)\n 9 JUMP_IF_FA...
[ 92, 7, 3, 3, 0 ]
[]
[]
[ "operators", "python" ]
stackoverflow_0003481554_operators_python.txt
Q: Python using doctest on the mainline Hello i was wondering if it is possible and if so how? to do doctests or something similar from the mainline, instead of testing a function as is described in the doctest docs i.e. """ >>> Hello World """ if __name__ == "__main__": print "Hello" import doctest doc...
Python using doctest on the mainline
Hello i was wondering if it is possible and if so how? to do doctests or something similar from the mainline, instead of testing a function as is described in the doctest docs i.e. """ >>> Hello World """ if __name__ == "__main__": print "Hello" import doctest doctest.testmod() This is part of being able...
[ "doctest is not limited to testing functions. For example, if dt.py is:\n'''\n >>> foo\n 23\n'''\n\nfoo = 23\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n\nthen, e.g.:\n$ py26 dt.py -v\nTrying:\n foo\nExpecting:\n 23\nok\n1 items passed all tests:\n 1 tests in __main__\n1 tes...
[ 2 ]
[]
[]
[ "doctest", "python", "string" ]
stackoverflow_0003481561_doctest_python_string.txt
Q: Why is this variable being changed? tokens_raw = {"foo": "bar"} tokens_raw_old = { } while not tokens_raw == tokens_raw_old: tokens_raw_old = tokens_raw # while loop that modifies tokens_raw goes here; # tokens_raw_old is never referenced print tokens_raw_old == tokens_raw This outputs True after ...
Why is this variable being changed?
tokens_raw = {"foo": "bar"} tokens_raw_old = { } while not tokens_raw == tokens_raw_old: tokens_raw_old = tokens_raw # while loop that modifies tokens_raw goes here; # tokens_raw_old is never referenced print tokens_raw_old == tokens_raw This outputs True after the first time for some reason. tokens_ra...
[ "tokens_raw_old = tokens_raw means: make a new reference called token_raw_old to the same object to which name tokens_raw refers at this time. It's the same object, not a copy of the object! So, changes to this one and only object made through one of the references obviously also affect the very same object when ...
[ 7 ]
[]
[]
[ "equality", "python", "while_loop" ]
stackoverflow_0003481863_equality_python_while_loop.txt
Q: How to open a file with the standard application? My application prints a PDF to a temporary file. How can I open that file with the default application in Python? I need a solution for Windows Linux (Ubuntu with Xfce if there's nothing more general.) Related Open document with default application in Python A:...
How to open a file with the standard application?
My application prints a PDF to a temporary file. How can I open that file with the default application in Python? I need a solution for Windows Linux (Ubuntu with Xfce if there's nothing more general.) Related Open document with default application in Python
[ "os.startfile is only available for windows for now, but xdg-open will be available on any unix client running X.\nif sys.platform == 'linux2':\n subprocess.call([\"xdg-open\", file])\nelse:\n os.startfile(file)\n\n", "on windows it works with os.system('start <myFile>'). On Mac (I know you didn't ask...) i...
[ 36, 10, 8, 4, 4, 0 ]
[]
[]
[ "linux", "python", "windows" ]
stackoverflow_0001679798_linux_python_windows.txt
Q: __decorated__ for python decorators As of 2.4 (2.6 for classes), python allows you to decorate a function with another function: def d(func): return func @d def test(first): pass It's a convenient syntactic sugar. You can do all sorts of neat stuff with decorators without making a mess. However, if you want to...
__decorated__ for python decorators
As of 2.4 (2.6 for classes), python allows you to decorate a function with another function: def d(func): return func @d def test(first): pass It's a convenient syntactic sugar. You can do all sorts of neat stuff with decorators without making a mess. However, if you want to find out the original function that got ...
[ "Well, independent of any discussion over whether this is a good idea, I'd go for option #3 because it's the most consistent: it always shows that the function has been decorated by the presence of the attribute, and accessing the value of the attribute always returns a function, so you don't have to test it agains...
[ 2, 1 ]
[]
[]
[ "c", "compiler_construction", "decorator", "parsing", "python" ]
stackoverflow_0003481872_c_compiler_construction_decorator_parsing_python.txt
Q: pure python socket module The socket module in python wraps the _socket module which is the C implementation stuff. As well, socket.socket will take a _sock parameter that must implement the _socket interface. In some regards _sock must be an actual instance of the underlying socket type from _socket since the C...
pure python socket module
The socket module in python wraps the _socket module which is the C implementation stuff. As well, socket.socket will take a _sock parameter that must implement the _socket interface. In some regards _sock must be an actual instance of the underlying socket type from _socket since the C code does type checking (unlik...
[ "It's already been done. Twisted uses this extensively for unit tests of its protocol implementations. A good starting place would be looking at some of Twisted's unit tests.\nIn essence, you'd just call makeConnection on your protocol with a transport that isn't connected to a real socket. Super easy!\n" ]
[ 3 ]
[]
[]
[ "emulation", "python", "sockets" ]
stackoverflow_0003481779_emulation_python_sockets.txt
Q: I'm looking for a Python multiplayer game server project I'm looking for a python multiplayer game server project. I'm just trying to learn more. A: Well I started on something simple here. It's written with pygame and Python's socket module. You could fork/learn from that. Presently multiple players can login, ...
I'm looking for a Python multiplayer game server project
I'm looking for a python multiplayer game server project. I'm just trying to learn more.
[ "Well I started on something simple here. It's written with pygame and Python's socket module. You could fork/learn from that.\nPresently multiple players can login, move around, and do basic chat communication. There's also a goblin that chases the nearest player.\n" ]
[ 5 ]
[]
[]
[ "mmo", "multiplayer", "python" ]
stackoverflow_0003481883_mmo_multiplayer_python.txt
Q: How to extract a given frame from a .gif animation in Python I'm trying to figure out how to extract a given frame from an animated-gif, possibly in PIL, in Python. I'm not able to easily dig this up, and I'm guessing it would take some knowledge of the gif format, something that is not readily understandable to m...
How to extract a given frame from a .gif animation in Python
I'm trying to figure out how to extract a given frame from an animated-gif, possibly in PIL, in Python. I'm not able to easily dig this up, and I'm guessing it would take some knowledge of the gif format, something that is not readily understandable to me. Is there any straightforward way to accomplish this? Do I need ...
[ "\nReading Sequences\nThe GIF loader supports the seek and\n tell methods. You can seek to the next\n frame (im.seek(im.tell()+1), or rewind\n the file by seeking to the first\n frame. Random access is not supported.\n\nhttp://effbot.org/imagingbook/format-gif.htm\nhttp://effbot.org/imagingbook/image.htm \n" ]
[ 5 ]
[]
[]
[ "animated_gif", "python", "python_imaging_library" ]
stackoverflow_0003482193_animated_gif_python_python_imaging_library.txt
Q: Using xterm to open a new console: How to while the current console is printing, to print on the new console also I'm using python right now. I have a thread that represents my entire program. I want to open another console window using os.system(xterm&) as a thread which works. The only thing is, is it possible t...
Using xterm to open a new console: How to while the current console is printing, to print on the new console also
I'm using python right now. I have a thread that represents my entire program. I want to open another console window using os.system(xterm&) as a thread which works. The only thing is, is it possible to print to the new window while the other thread is printing to the older window? import sys import os def my_fork(): ...
[ "You could probably create a named pipe, have your new thread write to that, then spawn a new terminal that runs tail -f on the pipe.\n", "Use subprocess.Popen() for creation of the children process. In that case you can specify PIPE and write to stdin of the children.\nimport subprocess\np = subprocess.Popen([\"...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "console", "linux", "multithreading", "python" ]
stackoverflow_0003481838_console_linux_multithreading_python.txt
Q: Shed some light on working with pipes and subprocesses in Python? I'm wrestling with the concepts behind subprocesses and pipes, and working with them in a Python context. If anybody could shed some light on these questions it would really help me out. Say I have a pipeline set up as follows createText.py | proc...
Shed some light on working with pipes and subprocesses in Python?
I'm wrestling with the concepts behind subprocesses and pipes, and working with them in a Python context. If anybody could shed some light on these questions it would really help me out. Say I have a pipeline set up as follows createText.py | processText.py | cat processText.py is receiving data through stdin, but ho...
[ "This assumes a UNIXish/POSIXish environment.\nEOF in a pipeline is signaled by no more data to read, that is, read() returns a length of 0. This normally occurs when the left-hand process exits and closes its stdout. Since you can't read from a pipe whose other end is closed the read in processText indicates EOF.\...
[ 1 ]
[]
[]
[ "pipe", "process", "python", "shell" ]
stackoverflow_0003482266_pipe_process_python_shell.txt
Q: Komodo Edit auto-complete won't find a Python module I am using Komodo edit on a Python file on Windows. When I type import s it successfully lists all the importable files starting with s, including one of my modules in one of my directories. When I type import t it lists all the importable files starting with t,...
Komodo Edit auto-complete won't find a Python module
I am using Komodo edit on a Python file on Windows. When I type import s it successfully lists all the importable files starting with s, including one of my modules in one of my directories. When I type import t it lists all the importable files starting with t, EXCLUDING one of my modules in the same directory. Even t...
[ "Problem solved itself when I closed Komodo, saving the project, and reopened it.\nSounds like Komodo's internal representation was out-of-date or corrupted.\nI'll leave the question here for the next person who stumbles over it.\n" ]
[ 2 ]
[]
[]
[ "komodo", "komodoedit", "python" ]
stackoverflow_0003481949_komodo_komodoedit_python.txt
Q: querying a array in django idarr = [1,2,3,4,5] for i in range(len(idarr)): upload.objects.filter(idarr[i]) Cant we pass the idarr at one shot to the query A: I am assuming that you are trying to filter all instances of Upload whose id is in the list idarr. If that is the case then you can...
querying a array in django
idarr = [1,2,3,4,5] for i in range(len(idarr)): upload.objects.filter(idarr[i]) Cant we pass the idarr at one shot to the query
[ "I am assuming that you are trying to filter all instances of Upload whose id is in the list idarr. If that is the case then you can go about it like this:\nUpload.objects.filter(id__in = idarr)\n\nRead the documentation for more details.\n", "So much wrong in so few lines...\n\nIn Python, never loop through rang...
[ 7, 7 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0003482637_django_django_models_django_views_python.txt
Q: Passing an array in django urls Can we pass an array to a django url <script> function save() { window.location = "/display/xlsdisplay/" + objarr ; } var objarr = new Array(); </script> Urls.py (r'^xlsdisplay/(?P<qid>\d+)$', 'xlsdisplay'), There is an error saying ...
Passing an array in django urls
Can we pass an array to a django url <script> function save() { window.location = "/display/xlsdisplay/" + objarr ; } var objarr = new Array(); </script> Urls.py (r'^xlsdisplay/(?P<qid>\d+)$', 'xlsdisplay'), There is an error saying http://192.168.1.11/dis...
[ "\nThe regular expression used in your URL will only match a sequence of digits. The comma will require a different expression. \nI don't know your specific need but you ought to look at naming URLs rather than hard cording them. \n\n" ]
[ 2 ]
[]
[]
[ "django", "django_urls", "django_views", "python" ]
stackoverflow_0003482481_django_django_urls_django_views_python.txt
Q: Is Python's seek() on OS X broken? I'm trying to implement a simple method to read new lines from a log file each time the method is called. I've looked at the various suggestions both on stackoverflow (e.g. here) and elsewhere for simulating "tail" functionality; most involve using readline() to read in new lines...
Is Python's seek() on OS X broken?
I'm trying to implement a simple method to read new lines from a log file each time the method is called. I've looked at the various suggestions both on stackoverflow (e.g. here) and elsewhere for simulating "tail" functionality; most involve using readline() to read in new lines as they're appended to the file. It sho...
[ "How are you adding two more lines to the file?\nMost text editors will go through operations a lot like this:\nfd = open(filename, read)\nfile_data = read(fd)\nclose(fd)\n/* you edit your file, and save it */\nunlink(filename)\nfd = open(filename, write, create)\nwrite(fd, file_data)\n\nThe file is different. (Che...
[ 3, 2 ]
[]
[]
[ "macos", "python", "seek" ]
stackoverflow_0003483007_macos_python_seek.txt
Q: How to control/call another python script within one python script? (Communicate between scripts) I'm working on one GUI program, and was gonna add a long running task into one event, but I found this would make the whole program freeze a lot, so considering other people's advice I would make the GUI only responsi...
How to control/call another python script within one python script? (Communicate between scripts)
I'm working on one GUI program, and was gonna add a long running task into one event, but I found this would make the whole program freeze a lot, so considering other people's advice I would make the GUI only responsible for starting, stopping and monitoring and make the long running task run as a separate script. The ...
[ "I suggest you look at the threading module. By subclassing the Thread class you can create new threads for time intensive jobs. \nThen for communication between the the threads you can use either pubsub or pydispatcher, I haven't tried the latter so I can't comment on it but I would recommend pubsub for its ease...
[ 5, 1, 1 ]
[]
[]
[ "event_handling", "python", "wxpython" ]
stackoverflow_0003482112_event_handling_python_wxpython.txt
Q: How to generate hebrew strings in python 3? I'm trying to create hebrew strings but get syntax errors. It works in the IDLE shell but not in Pydev. Here's what I've tried so far: s = 'מחרוזת בעברית' #works in the shell only s = u'מחרוזת בעברית' #doesn't work at all s = unicode("מחרוזת בעברית", "UTF-8") #also doesn...
How to generate hebrew strings in python 3?
I'm trying to create hebrew strings but get syntax errors. It works in the IDLE shell but not in Pydev. Here's what I've tried so far: s = 'מחרוזת בעברית' #works in the shell only s = u'מחרוזת בעברית' #doesn't work at all s = unicode("מחרוזת בעברית", "UTF-8") #also doesn't work at all I get a syntax error: Non-UTF-8 c...
[ "Does your source file start with a # -*- coding: utf-8 -*- line? Is your file actually encoded as utf-8 (and not some other encoding)?\nIt's supposed to work (the first line, other lines are not valid Python 3).\n" ]
[ 6 ]
[]
[]
[ "hebrew", "pydev", "python", "string", "unicode" ]
stackoverflow_0003483167_hebrew_pydev_python_string_unicode.txt
Q: How should I read the input data? For example, I have the following input data: (( 12 3 ) 42 ) I want to treat each integer value of the input data. This is an example of the general input data presentation. Just for additional information: Such presentation is corresponding to the binary tree with marked leaves: ...
How should I read the input data?
For example, I have the following input data: (( 12 3 ) 42 ) I want to treat each integer value of the input data. This is an example of the general input data presentation. Just for additional information: Such presentation is corresponding to the binary tree with marked leaves: /\ /\ 42 12 3
[ "I recommend pyparsing for this parsing task -- here, for example, is a pyparsing-based parsers for S-expressions... probably much richer and more powerful than what you need, but with a really limited understanding of Python and pyparsing you can simplify it down as much as you require (if at all -- it's quite abl...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003481971_python.txt
Q: Two classes: one for the django model and one for representing the data outside of django Is there a reasonable pattern for handling an object that exists as a Django model within the context of a particular Django application and as a non-Django class outside of that particular application? For example, let's say...
Two classes: one for the django model and one for representing the data outside of django
Is there a reasonable pattern for handling an object that exists as a Django model within the context of a particular Django application and as a non-Django class outside of that particular application? For example, let's say that I have a Post model within Django application Blog. I want to be able to interact with a ...
[ "You can use Django code outside of the normal server environment (as the test cases do). If you need to write Python scripts that play with your Django models, you can just access/modify your models as usual, using the ORM, there's just a short magic incantation you have to use first:\nfrom django.core.management ...
[ 2, 2, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003479982_django_django_models_python.txt
Q: Help With Printing a single item from list inside list in python I first create my grid: grid = [] for x in range(1,collength + 1): for y in range(1,collength + 1): grid.append([x,y,'e']) Then I make que for my grid and I want to manipulate the que based on the 0, 1, and 2 position of the lists inside...
Help With Printing a single item from list inside list in python
I first create my grid: grid = [] for x in range(1,collength + 1): for y in range(1,collength + 1): grid.append([x,y,'e']) Then I make que for my grid and I want to manipulate the que based on the 0, 1, and 2 position of the lists inside the lists: floodfillque = [] grid = floodfillque for each in floodf...
[ "As you have written it, your code iterates over an empty list. I think you mean:\nfor each in grid:\n\nor perhaps:\nfloodfillque = grid\n\nThis code works fine:\ncollength = 3\n\ngrid = []\nfor x in range(1,collength + 1):\n for y in range(1,collength + 1):\n grid.append([x,y,'e'])\n\nfor each in grid:\n...
[ 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003483807_list_python.txt
Q: When to inline definitions of metaclass in Python? Today I have come across a surprising definition of a metaclass in Python here, with the metaclass definition effectively inlined. The relevant part is class Plugin(object): class __metaclass__(type): def __init__(cls, name, bases, dict): t...
When to inline definitions of metaclass in Python?
Today I have come across a surprising definition of a metaclass in Python here, with the metaclass definition effectively inlined. The relevant part is class Plugin(object): class __metaclass__(type): def __init__(cls, name, bases, dict): type.__init__(name, bases, dict) registry.app...
[ "Like every other form of nested class definition, a nested metaclass may be more \"compact and convenient\" (as long as you're OK with not reusing that metaclass except by inheritance) for many kinds of \"production use\", but can be somewhat inconvenient for debugging and introspection.\nBasically, instead of giv...
[ 20 ]
[]
[]
[ "metaclass", "python" ]
stackoverflow_0003483718_metaclass_python.txt
Q: wxPython GridSizer.Add() not working for custom control I'm trying to create a custom control based on wx.richtext.RichTextCtrl and I'm running into a problem. Whenever I attempt to add the custom control to a sizer, wxPython chokes with the error Traceback (most recent call last): File "pyebook.py", line 46, in...
wxPython GridSizer.Add() not working for custom control
I'm trying to create a custom control based on wx.richtext.RichTextCtrl and I'm running into a problem. Whenever I attempt to add the custom control to a sizer, wxPython chokes with the error Traceback (most recent call last): File "pyebook.py", line 46, in <module> frame = MainFrame(None, 'pyebook') File "pyeb...
[ "I think you need to call __ init __ explicitly, so you can pass in 'self'. Otherwise, you are just creating a new instance of RichTextCtrl, not initialising your subclass properly.\nIOW:\nclass ReaderControl(wx.richtext.RichTextCtrl):\n def __init__(self, parent, id=-1, value=''):\n wx.richtext.RichText...
[ 3 ]
[]
[]
[ "custom_controls", "python", "wxpython" ]
stackoverflow_0003483613_custom_controls_python_wxpython.txt
Q: Django query select distinct by field pairs I have the field 'submission' which has a user and a problem. How can I get an SQL search result which will give a list of only one result per user-problem pair? Models are like this: class Problem(models.Model): title = models.CharField('Title', max_length = 100) ...
Django query select distinct by field pairs
I have the field 'submission' which has a user and a problem. How can I get an SQL search result which will give a list of only one result per user-problem pair? Models are like this: class Problem(models.Model): title = models.CharField('Title', max_length = 100) question = models.TextField('Question') class ...
[ "Try this:\ndistinct_users_problems = Submission.objects.all().values(\"user\", \"problem\").distinct()\n\nIt will give you a list of dicts like this one:\n[{'problem': 1, 'user': 1}, {'problem': 2, 'user': 1}, {'problem': 3, 'user': 1}]\n\ncontaining all the distinct pairs.\nIt actually results in your usual SELEC...
[ 19, 3 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0003483307_django_django_queryset_python.txt
Q: python first web application - where I am rookie in python - have experience in PHP my service provider (Bluehost) say that python 2.6 is available, however I am not able to run any script (basic hello word) on it - probably because I try do it PHP way. create a script.php file and place the link to it in browser....
python first web application - where
I am rookie in python - have experience in PHP my service provider (Bluehost) say that python 2.6 is available, however I am not able to run any script (basic hello word) on it - probably because I try do it PHP way. create a script.php file and place the link to it in browser... :) Where I can find explanation for du...
[ "If you're using Apache, this simple tutorial will show you how to configure it and run a python \"hello world\" script (in the simplest, old-fashioned way: as a CGI script).\nThis system-administration/configuration part will of course be different with other web servers, or other and better way of running Python ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003483981_python.txt
Q: Converting a Python Float to a String without losing precision I am maintaining a Python script that uses xlrd to retrieve values from Excel spreadsheets, and then do various things with them. Some of the cells in the spreadsheet are high-precision numbers, and they must remain as such. When retrieving the values ...
Converting a Python Float to a String without losing precision
I am maintaining a Python script that uses xlrd to retrieve values from Excel spreadsheets, and then do various things with them. Some of the cells in the spreadsheet are high-precision numbers, and they must remain as such. When retrieving the values of one of these cells, xlrd gives me a float such as 0.3828874611549...
[ "I'm the author of xlrd. There is so much confusion in other answers and comments to rebut in comments so I'm doing it in an answer.\n@katriealex: \"\"\"precision being lost in the guts of xlrd\"\"\" --- entirely unfounded and untrue. xlrd reproduces exactly the 64-bit float that's stored in the XLS file.\n@katriea...
[ 56, 3, 1, 0, 0 ]
[]
[]
[ "excel", "floating_point", "python", "xlrd" ]
stackoverflow_0003481289_excel_floating_point_python_xlrd.txt
Q: Distribute points on a circle as evenly as possible Problem statement I have the following problem: I have a circle with a certain number (zero or more) of points on it. These positions are fixed. Now I have to position another set of points on the circle, such as all points together are as evenly distributed arou...
Distribute points on a circle as evenly as possible
Problem statement I have the following problem: I have a circle with a certain number (zero or more) of points on it. These positions are fixed. Now I have to position another set of points on the circle, such as all points together are as evenly distributed around the circle as possible. Goal My goal is now to develop...
[ "Suppose you have M points already given, and N more need to be added. If all points were evenly spaced, then you would have gaps of 2*pi/(N+M) between them. So, if you cut at your M points to give M segments of angle, you can certainly place points into a segment (evenly spaced from each other) until the space i...
[ 10, 5, 4, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "algorithm", "geometry", "python" ]
stackoverflow_0003479736_algorithm_geometry_python.txt
Q: python reorganize codes Sorry I dont know how to add a comment with the format, so I post another question with code here, as I am new to python, seems that there are many better ways to reorgnize the codes to make it better: def min_qvalue(self): s = 0 q = 1 for i in range(len(self.results)): ...
python reorganize codes
Sorry I dont know how to add a comment with the format, so I post another question with code here, as I am new to python, seems that there are many better ways to reorgnize the codes to make it better: def min_qvalue(self): s = 0 q = 1 for i in range(len(self.results)): if self.results[i].score > s:...
[ "This is the same code:\nmax_score_qvalue = max( (result.score, result.qvalue) for result in self.results)[1]\n\nIt makes pairs of the score and qvalue, finds the pair with the highest score (with max) and then gets the qvalue from it.\nActually, I wrote the above just because I keep forgetting that max takes a key...
[ 4, 1 ]
[]
[]
[ "python", "refactoring" ]
stackoverflow_0003484181_python_refactoring.txt
Q: Is there a description of how __cmp__ works for dict objects in Python 2? I've been trying to make a dict subclass inheriting from UserDict.DictMixin that supports non-hashable keys. Performance isn't a concern. Unfortunately, Python implements some of the functions in DictMixin by trying to create a dict object...
Is there a description of how __cmp__ works for dict objects in Python 2?
I've been trying to make a dict subclass inheriting from UserDict.DictMixin that supports non-hashable keys. Performance isn't a concern. Unfortunately, Python implements some of the functions in DictMixin by trying to create a dict object from the subclass. I can implement these myself, but I am stuck on __cmp__. I...
[ "If you are asking how comparing dictionaries works, it is this:\n\nTo compare dicts A and B, first compare their lengths. If they are unequal, then return cmp(len(A), len(B)).\nNext, find the key adiff in A that is the smallest key for which adiff not in B or A[adiff] != B[adiff]. (If there is no such key, the d...
[ 34, 2, 0 ]
[]
[]
[ "python", "python_2.x" ]
stackoverflow_0003484293_python_python_2.x.txt
Q: Resizing a wxPython wx.Panel? I'm trying to place an image panel on a form such that when a button is clicked the 64x64 image that's put on the panel at program start is replaced with a bigger 320x224 image - the pixel sizes aren't so much important as they are being different sizes. I've ALMOST got it - right now...
Resizing a wxPython wx.Panel?
I'm trying to place an image panel on a form such that when a button is clicked the 64x64 image that's put on the panel at program start is replaced with a bigger 320x224 image - the pixel sizes aren't so much important as they are being different sizes. I've ALMOST got it - right now the images both load and it does i...
[ "Try calling self.v_sizer.Fit(self) at the end of your onOpenFileDialog() method\n" ]
[ 3 ]
[]
[]
[ "panel", "python", "wxpython" ]
stackoverflow_0003484326_panel_python_wxpython.txt
Q: Any suggestion on package for drawing 'random intervals' charts? I need to create a chart with the system load over a period of time. The main issue is that the data extraction is happening at random intervals so I need to be able to specify the X axis time position for the value. Any suggestion on a package/modul...
Any suggestion on package for drawing 'random intervals' charts?
I need to create a chart with the system load over a period of time. The main issue is that the data extraction is happening at random intervals so I need to be able to specify the X axis time position for the value. Any suggestion on a package/module with such functionality ? Sample Data: data = { '10:20' : 5, '10:28'...
[ "I'm not sure I understand the problem; any graphing library will let you specify x coordinates for the points that you plot. Try e.g. matplotlib.\n", "biggles is a decent Python graphing library. You can use SciPy to interpolate if you need to fill in empty spots on your graph.\n" ]
[ 1, 0 ]
[]
[]
[ "charts", "python" ]
stackoverflow_0003484605_charts_python.txt
Q: Django: Proxy Meta-class ignoring verbose_name_plural Django-admin is pluralizing a model that I have running as a proxy class. The normal case here works fine: class Triviatheme(models.Model): [ ... elided ... ] class Meta: db_table = u'TriviaTheme' verbose_name_plural='trivia themes' Bu...
Django: Proxy Meta-class ignoring verbose_name_plural
Django-admin is pluralizing a model that I have running as a proxy class. The normal case here works fine: class Triviatheme(models.Model): [ ... elided ... ] class Meta: db_table = u'TriviaTheme' verbose_name_plural='trivia themes' But for a main content table, I have a parent model called 'C...
[ "FWIW I tested this with Django 1.1.1 and Django 1.2.1 and it worked as expected in both cases.\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "python", "reverse_engineering" ]
stackoverflow_0003472395_django_django_admin_python_reverse_engineering.txt
Q: Phone Number Regular Expression (Regex) in Python Dive into python gives an amazing little tutorial on creating a regular expression for phone numbers: http://diveintopython3.ep.io/regular-expressions.html#phonenumbers The final version comes out to look like: phone_re = re.compile(r'(\d{3})\D*(\d{3})\D*(\d{4})\D*...
Phone Number Regular Expression (Regex) in Python
Dive into python gives an amazing little tutorial on creating a regular expression for phone numbers: http://diveintopython3.ep.io/regular-expressions.html#phonenumbers The final version comes out to look like: phone_re = re.compile(r'(\d{3})\D*(\d{3})\D*(\d{4})\D*(\d*)$', re.VERBOSE) This works fine for almost all ex...
[ "The (\\d*)$ requires that the string you're matching against end with digit characters (the $ signifies \"end of line\"). Try removing the $ if you're matching against a larger string where the phone number may not be at the end of the line.\n", "Here's your original, with some spaces (use re.VERBOSE, or remove ...
[ 2, 0 ]
[]
[]
[ "phone_number", "python", "regex" ]
stackoverflow_0003484721_phone_number_python_regex.txt
Q: Pass instance as function argument I wrote a nice little app that gets Yahoo weather info and posts it to Twitter. It worked flawlessly and now I want to rearrange the code into differently named files so it makes more sense. And that's when I hit some issues. Previously, I had a Class in libtweather.py. It was ...
Pass instance as function argument
I wrote a nice little app that gets Yahoo weather info and posts it to Twitter. It worked flawlessly and now I want to rearrange the code into differently named files so it makes more sense. And that's when I hit some issues. Previously, I had a Class in libtweather.py. It was my account. It allowed me to do accountN...
[ "You should be using an explicit dict for storing these items. eval, exec, globals, locals, and vars are all horribly silly ways to do this poorly. Remember from the Zen of Python: \"explicit is better than implicit.\"\nfeeds = {}\nfor item in whatever:\n feeds[item[0]] = lw.twitterWeather(*item[1:])\n\ndef getW...
[ 5 ]
[]
[]
[ "function", "instance", "oop", "python" ]
stackoverflow_0003484715_function_instance_oop_python.txt
Q: return as list from box with python (mechanize/twill) If I were to get something like this with showforms(), how would I get the Values out of the SOME_CODE input box? Form name=ttform (#2) ## ## __Name__________________ __Type___ __ID________ __Value__________________ 1 NUMBER select (...
return as list from box with python (mechanize/twill)
If I were to get something like this with showforms(), how would I get the Values out of the SOME_CODE input box? Form name=ttform (#2) ## ## __Name__________________ __Type___ __ID________ __Value__________________ 1 NUMBER select (None) ['0'] of ['0', '10', '2', '3', '4', ... 2 S...
[ "This does what you want. Tested on a website I found with the type of select control you have above:\n>>> import twill.commands\n>>> import BeautifulSoup\n>>> import re\n>>> \n>>> a=twill.commands\n>>> a.config(\"readonly_controls_writeable\", 1)\n>>> b = a.get_browser()\n>>> b.set_agent_string(\"Mozilla/5.0 (Wind...
[ 1, 0 ]
[]
[]
[ "mechanize", "python", "twill" ]
stackoverflow_0003199258_mechanize_python_twill.txt
Q: Reading fixed amount of bytes from socket with python asyncore I use asyncore to communicate with remote servers using "length:message"-type protocol. Can someone recommend me a way to read exact amount of bytes from socket? I was trying to use handle_read to fill internal buffer and call my function every time, c...
Reading fixed amount of bytes from socket with python asyncore
I use asyncore to communicate with remote servers using "length:message"-type protocol. Can someone recommend me a way to read exact amount of bytes from socket? I was trying to use handle_read to fill internal buffer and call my function every time, checking for size of buffer, but it looked too ugly(Check if buffer i...
[ "No. Sleeping would defeat the entire purpose of asynchronous IO. \nHowever, this is remarkably simple to do with twisted.\nfrom twisted.protocols.basic import Int32StringReceiver\n\nclass YourProtocol(Int32StringReceiver):\n def connectionMade(self):\n self.sendString('This string will automatically have...
[ 1 ]
[]
[]
[ "asyncore", "python", "sockets" ]
stackoverflow_0003484988_asyncore_python_sockets.txt
Q: Appengine forms Option Select from db.Model My application does not write all data in the database. In the example below just type in the DB name. All fields select dropdown are not recorded in the database. Help please I have a models Docente ESCOLHA_SEXO = (u'masculino', u'feminino') CHOICES_UNIDADE = ('Escola ...
Appengine forms Option Select from db.Model
My application does not write all data in the database. In the example below just type in the DB name. All fields select dropdown are not recorded in the database. Help please I have a models Docente ESCOLHA_SEXO = (u'masculino', u'feminino') CHOICES_UNIDADE = ('Escola Superior de Tecnologia', 'Escola Superior de Gest...
[ "Change these:\n<select name=\"categoria\">\n\n...\n<select name=\"regime\">\n\nTo this:\n<select name=\"docente_categoria\">\n\n...\n<select name=\"docente_regime\">\n\n" ]
[ 1 ]
[]
[]
[ "django_templates", "google_app_engine", "python" ]
stackoverflow_0003485299_django_templates_google_app_engine_python.txt
Q: Why can't I import pg.py? >>> import pg Traceback (most recent call last): File "<pyshell#40>", line 1, in <module> import pg File "C:\EPD\lib\site-packages\pg.py", line 21, in <module> from _pg import * ImportError: DLL load failed: The specified module could not be found. I downloaded PyGreSQL 4.0 ...
Why can't I import pg.py?
>>> import pg Traceback (most recent call last): File "<pyshell#40>", line 1, in <module> import pg File "C:\EPD\lib\site-packages\pg.py", line 21, in <module> from _pg import * ImportError: DLL load failed: The specified module could not be found. I downloaded PyGreSQL 4.0 for Windows, and installed it i...
[ "Looks like it's unable to find libpq.dll. Make sure that the directory which contains libpq.dll from your PostgreSQL installation is in your Windows path.\n", "Have you looked in the C:\\EPD\\lib\\site-packages\\ directory? Perhaps you did not install to the right site-packages directory?\n" ]
[ 1, 0 ]
[]
[]
[ "pygresql", "python", "sqlite" ]
stackoverflow_0003485483_pygresql_python_sqlite.txt
Q: Python, hard-code it time for filename manipulation I know how to append date to the end of the file name, but I m not sure how can I later in script put that filename as a link to FTP server. For instance: import datetime now = datetime.datetime.now() suffix = now.strftime(""%d-%m-%Y, %H:%M"") filename = 'My his...
Python, hard-code it time for filename manipulation
I know how to append date to the end of the file name, but I m not sure how can I later in script put that filename as a link to FTP server. For instance: import datetime now = datetime.datetime.now() suffix = now.strftime(""%d-%m-%Y, %H:%M"") filename = 'My history(%s).txt'%suffix How can I hard code it NOW variable...
[ "There is no need to 'hard code' the now variable so that it always references the same point of time. The now() function from the datetime library returns a datetime object; the values of the returned object will not change over time.\n>>> import datetime\n>>> import time\n>>> x = datetime.datetime.now()\n>>> x\nd...
[ 4 ]
[]
[]
[ "python", "time" ]
stackoverflow_0003485502_python_time.txt
Q: Pythonic way of repeating a method call on different finite arguments I was staring at a piece of Python code I produced, which, though correct, is ugly. Is there a more pythonic way of doing this? r = self.get_pixel(x,y, RED) g = self.get_pixel(x,y, GREEN) b = self.get_pixel(x,y, BLUE) t = functio...
Pythonic way of repeating a method call on different finite arguments
I was staring at a piece of Python code I produced, which, though correct, is ugly. Is there a more pythonic way of doing this? r = self.get_pixel(x,y, RED) g = self.get_pixel(x,y, GREEN) b = self.get_pixel(x,y, BLUE) t = function(r,g,b) if t: r2, g2, b2 = t self.set_pixel(x,y,RED...
[ "As you are using self, it appears that get_pixel etc are methods of your class. Instead of list comprehensions and zip() and other workarounds, look at the APIs and fix them. Two suggestions:\n\nWrite another method get_pixel_colors(x, y) which returns a 3-tuple. Then you can write r, g, b = self.get_pixel_colors(...
[ 5, 4, 1, 1 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0003485403_coding_style_python.txt
Q: Porting old apps from Python 2.4 I have a bunch of apps written in Python 2.4. I'd like to port them onto more recent version of the interpreter. Let's say I have no need of syntax features, but I am very concerned about performance. So which of the upper python versions is the fastest (the most optimized) - 2.4 o...
Porting old apps from Python 2.4
I have a bunch of apps written in Python 2.4. I'd like to port them onto more recent version of the interpreter. Let's say I have no need of syntax features, but I am very concerned about performance. So which of the upper python versions is the fastest (the most optimized) - 2.4 or 2.5 or 2.6 or 2.7 ? Performance com...
[ "In general, each successive version along the 2.* line becomes a bit faster than the previous one -- because optimization and fine-tuning is a high priority for many contributors.\nI don't know of any articles on performance configuration: my advice is to identify the \"hot spots\" of your specific application by ...
[ 4 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0003485886_performance_python.txt
Q: Using fuzzing lib (python) I'm trying to use this library : http://pastebin.com/xgPXpGtw (an example of use: http://pastebin.com/fNFAW3Fh) I have some issues since I dont want to split in an array all the byte as he does. My test script looks like this: import random from random import * def onerand(packet): ...
Using fuzzing lib (python)
I'm trying to use this library : http://pastebin.com/xgPXpGtw (an example of use: http://pastebin.com/fNFAW3Fh) I have some issues since I dont want to split in an array all the byte as he does. My test script looks like this: import random from random import * def onerand(packet): pack = packet[:] byte = str...
[ "In Python, strings are immutable. You pass to function onerand a string, argument name packet, copy it giving a local name pack (still a string, still therefore immutable), then you try to do \npack[whatever] = byte\n\nthe index doesn't matter: you're trying to modify the immutable string. That's what the error ...
[ 3, 2 ]
[]
[]
[ "fuzzing", "python", "string" ]
stackoverflow_0003485989_fuzzing_python_string.txt
Q: Should I be comparing bytes using struct? I'm trying to compare the data within two files, and retrieve a list of offsets of where the differences are. I tried it on some text files and it worked quite well.. However on non-text files (that still contain ascii text), I call them binary data files. (executables, so...
Should I be comparing bytes using struct?
I'm trying to compare the data within two files, and retrieve a list of offsets of where the differences are. I tried it on some text files and it worked quite well.. However on non-text files (that still contain ascii text), I call them binary data files. (executables, so on..) It seems to think some bytes are the sam...
[ "Did you try difflib and filecmp modules?\n\nThis module provides classes and\n functions for comparing sequences. It\n can be used for example, for comparing\n files, and can produce difference\n information in various formats,\n including HTML and context and unified\n diffs. For comparing directories and\n...
[ 4, 0 ]
[]
[]
[ "byte", "comparison", "file", "python" ]
stackoverflow_0003484460_byte_comparison_file_python.txt
Q: How to 'package' a simple, one-file python script for a person that wants to pay for it? A person (a senior citizen who is learning the very basics of computers) asked me to make a program that will save him LOTS of time with a grunt work type of task. I made the script in Python, it's simple, command line, takes ...
How to 'package' a simple, one-file python script for a person that wants to pay for it?
A person (a senior citizen who is learning the very basics of computers) asked me to make a program that will save him LOTS of time with a grunt work type of task. I made the script in Python, it's simple, command line, takes input from the user and saves the output to a file and that's it. My first question is related...
[ "There's a good PyInstaller tutorial here. However, PyInstaller does not (yet) support Python 2.7 (indeed, on Windows, I believe there are problems with 2.6 also).\nIn your use case I would recommend PortablePython -- Python configured to run (on Windows) from a USB key. You could easily put on the USB key Python...
[ 6 ]
[]
[]
[ "executable", "python" ]
stackoverflow_0003486137_executable_python.txt
Q: Help retrieving product code from HTML using Beautiful Soup A webpage has a product code I need to retrive, and it is in the following HTML section: <table...> <tr> <td> <font size="2">Product Code#</font> <br> <font size="1">2342343</font> </td> </tr> </table> So I guess the best way to do this would be fi...
Help retrieving product code from HTML using Beautiful Soup
A webpage has a product code I need to retrive, and it is in the following HTML section: <table...> <tr> <td> <font size="2">Product Code#</font> <br> <font size="1">2342343</font> </td> </tr> </table> So I guess the best way to do this would be first to reference the html element with the text value 'Product Co...
[ "Assuming soup is your BeautifulSoup instance:\nint(''.join(soup(\"font\", size=\"1\")[0](text=True)))\n\nOr, if you need to get multiple product codes:\n[int(''.join(font(text=True))) for font in soup(\"font\", size=\"1\")]\n\n", "My strategy is:\n\nFind text nodes matching the string \"Product Code#\"\nFor each...
[ 1, 1, 0, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003486204_beautifulsoup_python.txt
Q: PyQt's Signal / SLOT different classes can i connect two objects that are in different classes ? lets say i want button1's clicked() signal to clear line2 class A(QGroupBox): def __init__(self, parent=None): super(A, self).__init__(parent) self.button1= QPushButton('bt1') self.button1....
PyQt's Signal / SLOT different classes
can i connect two objects that are in different classes ? lets say i want button1's clicked() signal to clear line2 class A(QGroupBox): def __init__(self, parent=None): super(A, self).__init__(parent) self.button1= QPushButton('bt1') self.button1.show() class B(QGroupBox): def __init__...
[ "Yes, create a method in object B that's tied to a signal in object A. Note how connect is called (this is just an example):\n self.connect(self.okButton, QtCore.SIGNAL(\"clicked()\"),\n self, QtCore.SLOT(\"accept()\"))\n\nThe third argument is the object with the slot, and the fourth the slot n...
[ 3 ]
[]
[]
[ "pyqt", "python", "signals", "slot" ]
stackoverflow_0003486265_pyqt_python_signals_slot.txt
Q: Using BeautifulSoup, Can I quickly traverse to a specific parent element? Say I reference an element inside of a table in a HTML page like this: someEl = soup.findAll(text = "some text") I know for sure this element is embedded inside a table, is there a way to find the parent table without having to call .parent...
Using BeautifulSoup, Can I quickly traverse to a specific parent element?
Say I reference an element inside of a table in a HTML page like this: someEl = soup.findAll(text = "some text") I know for sure this element is embedded inside a table, is there a way to find the parent table without having to call .parent so many times? <table...> .. .. <tr>....<td><center><font..><b>some text</b><...
[ "Check out findParents, it has a similar form to findAll:\nsoup = BeautifulSoup(\"<table>...</table>\")\n\nfor text in soup.findAll(text='some text')\n table = text.findParents('table')[0]\n # table is your now your most recent `<table>` parent\n\nHere are the docs for findAllPrevious and also findParents.\n", ...
[ 6, 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003486331_beautifulsoup_python.txt
Q: Wxpython app exiting abnormally I have a wxpython app designed using XRC which has a multiline textctrl inside nested boxlayouts. I'm adding some text(retrieved from the web) to the text control using SetValue(), inside the longtask method from a separate thread using the following code thread.start_new_thread(s...
Wxpython app exiting abnormally
I have a wxpython app designed using XRC which has a multiline textctrl inside nested boxlayouts. I'm adding some text(retrieved from the web) to the text control using SetValue(), inside the longtask method from a separate thread using the following code thread.start_new_thread(self.longtask, ()) The app runs fine ...
[ "Directly calling methods of GUI elements from a different thread is dangerous. Without getting too much into your code, I'd recommend you to consider a robust multi-threaded design. For example, you can use Queue objects to pass data between threads. Alternatively, use wx's events.\nHere's a nice article on this i...
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003486536_python_wxpython.txt
Q: How to get an upload progress bar for urllib2? I currently use the following code to upload one file to a remote server: import MultipartPostHandler, urllib2, sys cookies = cookielib.CookieJar() opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler) params = {"data" : open("foo.bar") } request=op...
How to get an upload progress bar for urllib2?
I currently use the following code to upload one file to a remote server: import MultipartPostHandler, urllib2, sys cookies = cookielib.CookieJar() opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler) params = {"data" : open("foo.bar") } request=opener.open("http://127.0.0.1/api.php", params) respon...
[ "Here's a snippet from our python dependency script that Chris Phillips and I worked on @ Cogi (though he did this particular portion of it). Complete script is here. \n try:\n tmpfilehandle, tmpfilename = tempfile.mkstemp()\n with os.fdopen(tmpfilehandle, 'w+b') as tmpfile:\n print ' ...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003241986_python.txt
Q: cant install libgmail in python i'm a newbie in python , and trying to install libgmail .. this is what i get : C:\libgmail-0.1.11>setup.py Traceback (most recent call last): File "C:\libgmail-0.1.11\setup.py", line 7, in <module> import libgmail File "C:\libgmail-0.1.11\libgmail.py", line 96 exec data...
cant install libgmail in python
i'm a newbie in python , and trying to install libgmail .. this is what i get : C:\libgmail-0.1.11>setup.py Traceback (most recent call last): File "C:\libgmail-0.1.11\setup.py", line 7, in <module> import libgmail File "C:\libgmail-0.1.11\libgmail.py", line 96 exec data in {'__builtins__': None}, {'D': lam...
[ "Which version of Python are you using? It's possible it's 3.x which doesn't understand exec as a statement (in Python 3, exec, like print became a function and is no longer a special keyword/statement).\nThe solution is to either find a port of libgmail to Python 3, or install Python 2.7 for yourself instead.\n", ...
[ 1, 0 ]
[]
[]
[ "libgmail", "python" ]
stackoverflow_0003486920_libgmail_python.txt
Q: cron job and Long process problem Via django iam launching a thread (via middle ware the moment the first request comes) which continously fetches the twitter public steam and puts it down into the database.Assume the thread name is twitterthread. I also have have several cron jobs which periodically interacts wit...
cron job and Long process problem
Via django iam launching a thread (via middle ware the moment the first request comes) which continously fetches the twitter public steam and puts it down into the database.Assume the thread name is twitterthread. I also have have several cron jobs which periodically interacts with other third party api services. Obser...
[ "I'd advice to avoid launching threads inside the django application. Most of the times you can run the thread as a separate application.\nIf you deploy the app in a Apache server and you don't control it properly each Apache process will assume that a request is the first one and you could end up with more than on...
[ 0 ]
[]
[]
[ "cron", "django", "python" ]
stackoverflow_0002253714_cron_django_python.txt
Q: how to use python to run a google search and print out the results I wonder if you can help. I want to write a script in python that will run a query on google and output the results of the query as Thanks adaptive A: This should do what you want: >>> import twill.commands >>> import BeautifulSoup >>> >>> cla...
how to use python to run a google search and print out the results
I wonder if you can help. I want to write a script in python that will run a query on google and output the results of the query as Thanks adaptive
[ "This should do what you want:\n>>> import twill.commands\n>>> import BeautifulSoup\n>>> \n>>> class browser:\n... def __init__(self, url=\"http://www.google.com\",log = None):\n... self.a=twill.commands\n... self.a.config(\"readonly_controls_writeable\", 1)\n... self.b = self.a.get_browser()\n...
[ 3, 2 ]
[]
[]
[ "python", "web" ]
stackoverflow_0003487395_python_web.txt
Q: cant send SMS vla libgmail - python i'm new to python , and trying to write a script in order to send SMS's , after quick googling i found this lib: libgmail, and successfully installed it , this is the code i use to send SMS: !/usr/bin/env python import libgmail ga = libgmail.GmailAccount("username@gmail.com", "...
cant send SMS vla libgmail - python
i'm new to python , and trying to write a script in order to send SMS's , after quick googling i found this lib: libgmail, and successfully installed it , this is the code i use to send SMS: !/usr/bin/env python import libgmail ga = libgmail.GmailAccount("username@gmail.com", "password") myCellEmail = "phonenumber@mes...
[ "As far as I know libgmail is not compatible with the current Gmail interface. If I am not mistaken libgmail is not actively maintained either. You might want to look at alternative options. \n" ]
[ 0 ]
[]
[]
[ "libgmail", "python", "scripting", "sms" ]
stackoverflow_0003487447_libgmail_python_scripting_sms.txt
Q: django Queryset with year(date) = '2010' I'm trying to build this query select * from m_orders where year(order_date) = '2010' the field order_date is a DateTime field. I just don't want to use raw sql queries here. Is it even possible to use e.g. MySQL functions in django quersets? A: You can achieve this wit...
django Queryset with year(date) = '2010'
I'm trying to build this query select * from m_orders where year(order_date) = '2010' the field order_date is a DateTime field. I just don't want to use raw sql queries here. Is it even possible to use e.g. MySQL functions in django quersets?
[ "You can achieve this without using raw SQL. Use the built in __ mechanism instead (see the documentation for more details). Something like this:\nMyOrder.objects.filter(order_date__year = 2010)\n\n", "you can use django's builtin query API for this. no need for any vendor specific code or raw SQL.\nit would prob...
[ 26, 6 ]
[]
[]
[ "django", "django_queryset", "python", "sql" ]
stackoverflow_0003487484_django_django_queryset_python_sql.txt
Q: Python .format - error I'm trying to get the following to work in a Python interpreter, however it gives me an error and I cannot seem to find where my mistake is? (I'm a python newbie) >>> print 'THe value of PI is approx {}.'.format(math.pi) Traceback (most recent call last): File "<stdin>", line 1, in <modul...
Python .format - error
I'm trying to get the following to work in a Python interpreter, however it gives me an error and I cannot seem to find where my mistake is? (I'm a python newbie) >>> print 'THe value of PI is approx {}.'.format(math.pi) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' obj...
[ "You may use Python version < 2.6, version >= 2.6 support {0}, version >= 2.7 support {} format.\n", "You're using a too old version of python that does not support this string formatting method. On Python 2.6 this is the result (with a small correction):\n>>> print 'THe value of PI is approx {0}.'.format(math.pi...
[ 3, 1 ]
[ "This works: \n>>> print \"The value of PI is approx {'%s'}.\" % format(math.pi)\nThe value of PI is approx {'3.14159265359'}.\n\nSo does this: \n>>> print \"The value of PI is approx '%f'\" % math.pi\nThe value of PI is approx '3.141593'\n\n" ]
[ -1 ]
[ "format", "python" ]
stackoverflow_0003487770_format_python.txt
Q: How to plot data against specific dates on the x-axis using matplotlib I have a dataset consisting of date-value pairs. I want to plot them in a bar graph with the specific dates in the x-axis. My problem is that matplotlib distributes the xticks over the entire date range; and also plots the data using points. Th...
How to plot data against specific dates on the x-axis using matplotlib
I have a dataset consisting of date-value pairs. I want to plot them in a bar graph with the specific dates in the x-axis. My problem is that matplotlib distributes the xticks over the entire date range; and also plots the data using points. The dates are all datetime objects. Here's a sample of the dataset: data = [(D...
[ "What you're doing is simple enough that it's easiest to just using plot, rather than plot_date. plot_date is great for more complex cases, but setting up what you need can be easily accomplished without it.\ne.g., Based on your example above:\nimport datetime as DT\nfrom matplotlib import pyplot as plt\nfrom matpl...
[ 31 ]
[]
[]
[ "date", "matplotlib", "python" ]
stackoverflow_0003486121_date_matplotlib_python.txt
Q: Grab product code from a url, do I need regex for this? A url looks like: http://www.example.com/cgi-bin/blahblah?&PC=abd23423&uy=020 I need to extract the value: abc23423 I tried this regex but its not working: rx = re.compile(r'PC=(\w*)&uy=') I then I did: pc = rx.search(url).groups() but I get an error: att...
Grab product code from a url, do I need regex for this?
A url looks like: http://www.example.com/cgi-bin/blahblah?&PC=abd23423&uy=020 I need to extract the value: abc23423 I tried this regex but its not working: rx = re.compile(r'PC=(\w*)&uy=') I then I did: pc = rx.search(url).groups() but I get an error: attribute error: nonetype object has no attribute groups.
[ "Try urlparse.\n", "Update\nSheesh. What was I thinking?\nimport urlparse\nu = 'http://www.example.com/cgi-bin/blahblah?&PC=abd23423&uy=020'\nquery = urlparse.urlparse(u).query\nurlparse.parse_qs(query) # {'PC': ['abd23423'], 'uy': ['020']}\n\nOriginal Answer\nThis code snippet worked for me. Take a look:\nimport...
[ 4, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003486313_python_regex.txt
Q: What tricks do you use to avoid being tripped up by python whitespace syntax? I'm an experienced programmer, but still a little green at python. I just got caught by an error in indentation, which cost me a significant amount of debugging time. I was wondering what experienced python programmers do to avoid creati...
What tricks do you use to avoid being tripped up by python whitespace syntax?
I'm an experienced programmer, but still a little green at python. I just got caught by an error in indentation, which cost me a significant amount of debugging time. I was wondering what experienced python programmers do to avoid creating such problems in the first place. Here's the code (Part of a much larger program...
[ "Put all the class attributes (e.g. value) up at the top, right under the class Wizvar declaration (below the doc string, but above all method definitions). If you always place class attributes in the same place, you may not run into this particular error as often.\nNotice that if you follow the above convention an...
[ 8, 1, 1 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0003488231_python_syntax.txt
Q: Python ctypes - dll function accepting structures crashes I have to access a POS terminal under ms windows xp. I am using python 2.7. The crucial function in the DLL I load that does the payment accepts two pointer to structures, but it crashes returning 1 (Communication error) but without further messages. Please...
Python ctypes - dll function accepting structures crashes
I have to access a POS terminal under ms windows xp. I am using python 2.7. The crucial function in the DLL I load that does the payment accepts two pointer to structures, but it crashes returning 1 (Communication error) but without further messages. Please note that when the payment function is called, not all the ele...
[ "c_char_p is a direct translation of a C's char *. So, it seems to me that while your C structure is\ntypedef struct\n{\n char TerminalId[8+1];\n char AcquirerId[11+1];\n char TransactionType[3+1];\n\n&c\n\nthe allegedly-corresponding one you're making in ctypes is, instead, equivalent to\ntypedef struct\n{\n ...
[ 5 ]
[]
[]
[ "ctypes", "pointers", "python", "structure" ]
stackoverflow_0003488173_ctypes_pointers_python_structure.txt