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: Python video converter packages Any Packages out there on python which takes a input of a particular video format and convert it to another format A: PyFFmpeg. It's a wrapper around FFmpeg. Or use subprocess and call your favourite video format conversion program. >>> import subprocess >>> command = ['ffmpeg']...
Python video converter packages
Any Packages out there on python which takes a input of a particular video format and convert it to another format
[ "PyFFmpeg. It's a wrapper around FFmpeg. \nOr use subprocess and call your favourite video format conversion program.\n>>> import subprocess\n>>> command = ['ffmpeg']\n>>> subprocess.call(command)\n\nTo call ffmpeg with your own command which includes the details required, just extend the command list. \n", "Perh...
[ 4, 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0004365058_linux_python.txt
Q: how to implement unittest.skip from python 3.1 in python 2.6? do you know of any implementation of unittest.skip of python 3.1 in python 2.6/2.7? http://docs.python.org/dev/library/unittest.html#skipping-tests-and-expected-failures thanks A: Try installing the unittest2 package, "a backport of the new features a...
how to implement unittest.skip from python 3.1 in python 2.6?
do you know of any implementation of unittest.skip of python 3.1 in python 2.6/2.7? http://docs.python.org/dev/library/unittest.html#skipping-tests-and-expected-failures thanks
[ "Try installing the unittest2 package, \"a backport of the new features added to the unittest testing framework\" in Python 2.7 and 3.2.\n" ]
[ 8 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0004364500_python_unit_testing.txt
Q: Is there a good AJAX/JQuery way of validating forms that works well with Django's form models? Especially validating forms "live"...when the user goes on to the next field, and telling the user that his previous one was not valid. What options are available, and what would you use in conjunction? A: Ajax Validat...
Is there a good AJAX/JQuery way of validating forms that works well with Django's form models?
Especially validating forms "live"...when the user goes on to the next field, and telling the user that his previous one was not valid. What options are available, and what would you use in conjunction?
[ "Ajax Validation package by django core developer Alex Gaynor is pretty awesome and probably what you want.\nThe best part is that you define only the standard django forms and the validation happens even after the submit.\n" ]
[ 2 ]
[]
[]
[ "django", "html", "javascript", "jquery", "python" ]
stackoverflow_0004365347_django_html_javascript_jquery_python.txt
Q: How to change the main window widgets with Python/Glade? I am more or less new to GUI programming (just some tiny bit of Perl/Tk experience); I am new to Python, and I am new to Glade, both of which I would like to learn how to use. I have a program in mind which would require one single window, but this window's...
How to change the main window widgets with Python/Glade?
I am more or less new to GUI programming (just some tiny bit of Perl/Tk experience); I am new to Python, and I am new to Glade, both of which I would like to learn how to use. I have a program in mind which would require one single window, but this window's contents (widgets and all) would have to change with each ste...
[ "Glade allows you to create partial windows. Example: You can create many GtkVBox'es with the contents you want, and then in runtime swap between them.\nIn fact, glade already includes GtkAssistant, \"a widget used to guide users through multi-step operations. It includes tools to ease implementing the \"next-next-...
[ 3 ]
[]
[]
[ "glade", "python", "user_interface" ]
stackoverflow_0004361364_glade_python_user_interface.txt
Q: Python convert mixed ASCII code to String I am retrieving a value that is set by another application from memcached using python-memcached library. But unfortunately this is the value that I am getting: >>> mc.get("key") '\x04\x08"\nHello' Is it possible to parse this mixed ASCII code into plain string using pyt...
Python convert mixed ASCII code to String
I am retrieving a value that is set by another application from memcached using python-memcached library. But unfortunately this is the value that I am getting: >>> mc.get("key") '\x04\x08"\nHello' Is it possible to parse this mixed ASCII code into plain string using python function? Thanks heaps for your help
[ "It is a \"plain string\", to the extent that such a thing exists. I have no idea what kind of output you're expecting, but:\nThere ain't no such thing as plain text.\nThe Python (in 2.x, anyway) str type is really a container for bytes, not characters. So it isn't really text in the first place :) It displays the ...
[ 7, 1 ]
[]
[]
[ "ascii", "memcached", "python" ]
stackoverflow_0004365456_ascii_memcached_python.txt
Q: pyCurl WRITEFUNCTION callback with parameters I am using pyCurl with the following line to call a function with the data of the connection: conn.setopt(pycurl.WRITEFUNCTION, on_receive) Is there anyway I can pass more parameters to on_receive function, such as: conn.setopt(pycurl.WRITEFUNCTION, on_receive, parame...
pyCurl WRITEFUNCTION callback with parameters
I am using pyCurl with the following line to call a function with the data of the connection: conn.setopt(pycurl.WRITEFUNCTION, on_receive) Is there anyway I can pass more parameters to on_receive function, such as: conn.setopt(pycurl.WRITEFUNCTION, on_receive, parameter_1, parameter_2) Thanks, Joel
[ "The only straight-forward way I know would be to have a separate springboard function to call your actual function with the additional parameters. A lambda function or function pointer in other words, if the parameters are ok to be constant. \nconnn.setopt(pycurl.WRITEFUNCTION, lambda data: real_impl(data, param1,...
[ 3 ]
[]
[]
[ "pycurl", "python" ]
stackoverflow_0004365550_pycurl_python.txt
Q: Form validations in a template if using a readymade module for registration I just wanted to know that I am using the predefined registration module and it I am not able to validate the registration form. my registration_form.html look like this {% extends "registration_base.html" %} 2 {% block title %} Registra...
Form validations in a template if using a readymade module for registration
I just wanted to know that I am using the predefined registration module and it I am not able to validate the registration form. my registration_form.html look like this {% extends "registration_base.html" %} 2 {% block title %} Registration Form {% endblock %} 3 {% block external %} 4 5 .error{ ...
[ "I worked out and got my answer that if we want to put any extra validations, then they should be inserted before the save method of the form. Its the correct place to perform the task.\nHope this would help a beginner like me.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004224661_django_python.txt
Q: Which abbreviations should we use for python variable names? In generally I'm using the standard naming stated in PEP-8 for variables. Like: delete_projects connect_server However sometimes I can't find any good name and the name just extend to a long one: project_name_to_be_deleted I could use pr_nm_del , but ...
Which abbreviations should we use for python variable names?
In generally I'm using the standard naming stated in PEP-8 for variables. Like: delete_projects connect_server However sometimes I can't find any good name and the name just extend to a long one: project_name_to_be_deleted I could use pr_nm_del , but this makes the code unreadable. I'm really suffering finding good ...
[ "pr_nm_del? You might as well let a cat name it. I believe abbreviations should be avoided at all cost, except well-known/obvious ones (like del, as mentioned in the comments - that one's even a language keyword!) that save a whole lot of typing.\nBut that doesn't mean overly verbose identifiers. Just as context is...
[ 6, 1, 1, 0, 0 ]
[]
[]
[ "formatting", "naming_conventions", "python", "syntax" ]
stackoverflow_0004358840_formatting_naming_conventions_python_syntax.txt
Q: Which revision of html5lib is stable? html5lib notes that it's latest release (0.11) is somewhat old. Using the Python portion, I have recursion problems as noted in Issue 70 and Issue 59 but can't find a recent Mercurial revision that is stable. The latest tip is no good, I got the following error from python set...
Which revision of html5lib is stable?
html5lib notes that it's latest release (0.11) is somewhat old. Using the Python portion, I have recursion problems as noted in Issue 70 and Issue 59 but can't find a recent Mercurial revision that is stable. The latest tip is no good, I got the following error from python setup.py install: byte-compiling build/bdist.l...
[ "As of January 2010, it looks like version 0.90 is what you want:\nhttp://code.google.com/p/html5lib/downloads/list\n" ]
[ 1 ]
[]
[]
[ "html5lib", "python" ]
stackoverflow_0001122494_html5lib_python.txt
Q: How to programmatically exit pdb started in eval() or exec() without showing output In my python code I have this line: try: result = eval(command, self.globals, self.locals) except SyntaxError: exec(command, self.globals, self.locals) The command variable can be any string. Hence the python debugger pdb ...
How to programmatically exit pdb started in eval() or exec() without showing output
In my python code I have this line: try: result = eval(command, self.globals, self.locals) except SyntaxError: exec(command, self.globals, self.locals) The command variable can be any string. Hence the python debugger pdb may be started in eval/exec and still be active when eval/exec is returning. What I want ...
[ "While I'm somewhat concerned that you are eval/exec'ing a string that you don't control, I'll assume you've thought that bit through.\nI think the simplest thing would be to persuade pdb to check the stack frame on each step and resume automatically when you return to the desired level. You can do that with a simp...
[ 3 ]
[]
[]
[ "debugging", "ipython", "pdb", "python" ]
stackoverflow_0003959418_debugging_ipython_pdb_python.txt
Q: Question about python construction A friend of mine that is a programmer told me that "Python is written in Python" or something like that. He meant that Python interpreter is written in Python (I think). I've read in some websites that Python interpret in real time ANY programming language (even C++ and ASM). Is ...
Question about python construction
A friend of mine that is a programmer told me that "Python is written in Python" or something like that. He meant that Python interpreter is written in Python (I think). I've read in some websites that Python interpret in real time ANY programming language (even C++ and ASM). Is this true? Could someone explain me HOW ...
[ "It's not true. The standard implementation of Python - CPython - is written in C, although much of the standard library is written in Python. There are other implementations in Java (Jython) and .NET (IronPython).\nThere is a project called PyPy which, among other things, is rewriting the C parts of Python into Py...
[ 5, 2, 0, 0 ]
[]
[]
[ "compiler_construction", "interpreter", "programming_languages", "python" ]
stackoverflow_0004364507_compiler_construction_interpreter_programming_languages_python.txt
Q: Using FormWizard and saving the forms data in between before the completion of the whole process? I am using FormWizard to complete a set of operation in my app, I have two models Employee and Person, Employee class inherits Person, and all the fields of Person are available for Employee object. Now I am creating ...
Using FormWizard and saving the forms data in between before the completion of the whole process?
I am using FormWizard to complete a set of operation in my app, I have two models Employee and Person, Employee class inherits Person, and all the fields of Person are available for Employee object. Now I am creating a set of forms using FormWizard, I just wanted to know that. If a user starts entering the data in the ...
[ "what you can do is every step, save out the form state to some serialised object in db ForeignKeyed to the user.\nthen when hooking up the formwizard, wrap the formwizard view in a custom view which checks if the user has a saved form and if so deserialises and redirects to the appropriate step.\nEdit: seems formw...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004365859_django_python.txt
Q: application automation software/tool I am looking for an automation software which should be configurable to handle any other software for repetitive tasks on Windows. Push button x if ... Does anybody know such a software. If not would it be possible to program such a robot in python? Are there existing python-mo...
application automation software/tool
I am looking for an automation software which should be configurable to handle any other software for repetitive tasks on Windows. Push button x if ... Does anybody know such a software. If not would it be possible to program such a robot in python? Are there existing python-modules for this?
[ "PowerShell. http://en.wikipedia.org/wiki/Windows_PowerShell\nhttp://technet.microsoft.com/en-us/scriptcenter/powershell.aspx\n\nwould it be possible to program such a robot in python? \n\nThe answer to all \"is it possible\" question is always \"Yes.\" As long as the question doesn't involve time travel, anti-gr...
[ 1, 1 ]
[]
[]
[ "automation", "python" ]
stackoverflow_0004366293_automation_python.txt
Q: Problem with mail flood when connecting to database When I'm connecting to a database I'm sending mails on connection errors. The problem is that Python tries so often to connect to the database that I'm getting flooded by mails (hundreds per minute) in the case of errors. To clarify: try: #connect to db excep...
Problem with mail flood when connecting to database
When I'm connecting to a database I'm sending mails on connection errors. The problem is that Python tries so often to connect to the database that I'm getting flooded by mails (hundreds per minute) in the case of errors. To clarify: try: #connect to db except psycopg2.Error, msg: # write error mail Now I want...
[ "Use a file lock to make sure only one session of you test runs, and add a sleep() to make sure you only test every, say, 5 minutes.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004366423_python.txt
Q: How to detect if USB keyboard is plugged and unplugged Is there any daemon/tool which will trigger some signal/event when USB keyboard is plugged and unplugged from pc? I need to know in my program when USB keyboard is plugged and unplugged. Any ideas on how to do this? A: udev (Linux device manager) is the one ...
How to detect if USB keyboard is plugged and unplugged
Is there any daemon/tool which will trigger some signal/event when USB keyboard is plugged and unplugged from pc? I need to know in my program when USB keyboard is plugged and unplugged. Any ideas on how to do this?
[ "udev (Linux device manager) is the one that polls hardware. When it detects some changes about devices, it executes the rule associated.\nYou should add a rule to udev, in order to inform your program about insertion of removal of USB keyboard. You can find documentation about udev rules here, or Look at files in ...
[ 4, 2 ]
[ "If HAL daemon is running (which is true for most modern linux desktops), you can listen to its DBus Signals. Here is an example how to detect if a USB mouse is plugged in (I don't have a USB keyboard at hand):\nimport gobject\nimport dbus\nfrom dbus.mainloop.glib import DBusGMainLoop\n\nDBusGMainLoop(set_as_defaul...
[ -2 ]
[ "dbus", "keyboard", "linux", "python" ]
stackoverflow_0004224796_dbus_keyboard_linux_python.txt
Q: A simple framework for Google App Engine (like Sinatra)? Is there a simple 'wrapper' framework for appengine? Something like Sinatra or Juno? So that one can write code like the following: from juno import * @route('/') def index(web): return 'Juno says hi' run() UPDATE: I want to use the Python API (not Ja...
A simple framework for Google App Engine (like Sinatra)?
Is there a simple 'wrapper' framework for appengine? Something like Sinatra or Juno? So that one can write code like the following: from juno import * @route('/') def index(web): return 'Juno says hi' run() UPDATE: I want to use the Python API (not Java) in GAE.
[ "There are several frameworks either specifically for App Engine, or well suited to it:\n\nweb.py - Not specifically for App Engine, but well suited.\nGoogle App Engine Oil\nweb2py - Also not specifically for App Engine\npyxer\nkay\ntipfy\n\n", "No such framework has been released at this time, to the best of my ...
[ 7, 2, 2, 1, 1, 0 ]
[]
[]
[ "google_app_engine", "python", "web_frameworks" ]
stackoverflow_0001592088_google_app_engine_python_web_frameworks.txt
Q: simplejson + GAE serialize objects with fields names I use this code to define my class in GAE Python: class Pair(db.Model): find = db.StringProperty() replace = db.StringProperty() rule = db.StringProperty() tags = db.StringListProperty() created = db.DateTimeProperty() updated = db.DateTi...
simplejson + GAE serialize objects with fields names
I use this code to define my class in GAE Python: class Pair(db.Model): find = db.StringProperty() replace = db.StringProperty() rule = db.StringProperty() tags = db.StringListProperty() created = db.DateTimeProperty() updated = db.DateTimeProperty(auto_now=True) Then I use this code to seriali...
[ "class PairEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, Pair):\n return {\"created\": str(obj.created), \"updated:\": str(obj.updated), \"find\": obj.find, \"replace\": obj.replace, \"tags\": obj.tags, \"rule\": obj.rule}\n return json.JSONEncoder.default(sel...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "json", "python" ]
stackoverflow_0004366541_google_app_engine_json_python.txt
Q: address already in use with multithreaded server in twisted I'm trying to write a multithreaded server in python using twisted. callInThread(self.task) is to create a new thread to run task() every time a client requests sth from the server. When the client sends requests one by one(all through port 53), everythin...
address already in use with multithreaded server in twisted
I'm trying to write a multithreaded server in python using twisted. callInThread(self.task) is to create a new thread to run task() every time a client requests sth from the server. When the client sends requests one by one(all through port 53), everything works but when there are multiple requests at the same time, it...
[ "You don't need threads. This is horribly buggy. Twisted is already calling recv for you: and it is the result of that which is passed to datagramReceived. Don't call it again yourself. You don't need a thread.\nHowever, that probably has nothing to do with your problem. 53 is the default DNS port: the problem...
[ 2 ]
[]
[]
[ "multithreading", "python", "twisted" ]
stackoverflow_0004366723_multithreading_python_twisted.txt
Q: how to get edges from networkx to color differently I've built a tree image, see question. Now I've some major groups. One group has nodes with color green and brown, and has a 'B' and a 'A'. The second group has only pink nodes and 'T' and the last group has yellow, orange and blue, and the letters 'L', 'X' and '...
how to get edges from networkx to color differently
I've built a tree image, see question. Now I've some major groups. One group has nodes with color green and brown, and has a 'B' and a 'A'. The second group has only pink nodes and 'T' and the last group has yellow, orange and blue, and the letters 'L', 'X' and 'H'. the colors refer to the colors of the nodes and the l...
[ "I'm guessing (since I don't know how that snippet fits in to the rest of the code) that you're iterating over the nodes, and adding one colour to the list for each node. Like the error message suggests, you need to work out the colour required for each edge. That's going to be trickier.\nAlright, got it! The code ...
[ 4 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0004366842_networkx_python.txt
Q: Why is this variable now cross-module global in python? I shall simplify the code slightly in the hopes that someone can shed some light on this and maybe give me a more pythonic approach if what im doing is wrong. Inside dbcontrollers.py import autosettings import aerialcontroller import controller import gobject...
Why is this variable now cross-module global in python?
I shall simplify the code slightly in the hopes that someone can shed some light on this and maybe give me a more pythonic approach if what im doing is wrong. Inside dbcontrollers.py import autosettings import aerialcontroller import controller import gobject import gtk import utils # Create the settings object so we ...
[ "Python doesn't have a way to share a name across modules. If there's something you want access to from multiple modules, you declare it in a separate module (e.g. \"settings\"), and then import it wherever you want it.\nsettings.py:\nSETTINGS = autosettings.autoSettings()\nCONTROLLERS = {}\n\naerialcontroller.py\n...
[ 3, 1 ]
[]
[]
[ "global_variables", "module", "object", "python", "scope" ]
stackoverflow_0004366987_global_variables_module_object_python_scope.txt
Q: Creating scoreboard with complicated rules I need to make a scoreboard creating by such list of rules: Teams' places at the first stage of the Championship are determined by the most amount of points. For the victory in a match the team charges 3 points, for draw - 1 point and for loss - 0 points. In case of equal...
Creating scoreboard with complicated rules
I need to make a scoreboard creating by such list of rules: Teams' places at the first stage of the Championship are determined by the most amount of points. For the victory in a match the team charges 3 points, for draw - 1 point and for loss - 0 points. In case of equal results of two or more teams, their places are ...
[ "seems like what you want to do is use sort(). python's sort sorts tuples lexicographically, i.e. if the first item is the same it checks the second (etc...)\ndef rank_teams():\n rank = []\n # iterate through teams and create a tuple with most important to least important \n # sort params. team bust be the...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004365280_django_python.txt
Q: Screen Capture Under Win7 of JOGL Applet I'm trying to take a screen shot of an applet running inside a browser. The applet is using JOGL (OpenGL for Java) to display 3D models. (1) The screen shots always come out either black or white.The current solution uses the usual GDI calls. Screen shots of applets not run...
Screen Capture Under Win7 of JOGL Applet
I'm trying to take a screen shot of an applet running inside a browser. The applet is using JOGL (OpenGL for Java) to display 3D models. (1) The screen shots always come out either black or white.The current solution uses the usual GDI calls. Screen shots of applets not running OpenGL are fine. A few examples of JOGL a...
[ "Unless you are trying to automate it, I would just use a Firefox extension for this. There are a number of them returned from a search for \"screenshot\" that can take a screenshot of the entire browser page including the scrollable area:\n\nFireShot\nScreengrab\nSnapper (for older Firefox versions)\n\nHowever, I ...
[ 0, 0, 0, 0 ]
[]
[]
[ "gdi", "jogl", "python" ]
stackoverflow_0002154448_gdi_jogl_python.txt
Q: Splitting an expression I have to split a string into a list of substrings according to the criteria that all the parenthesis strings should be split . Lets say I have (9+2-(3*(4+2))) then I should get (4+2), (3*6) and (9+2-18). The basic objective is that I learn which of the inner parenthesis is going to be exec...
Splitting an expression
I have to split a string into a list of substrings according to the criteria that all the parenthesis strings should be split . Lets say I have (9+2-(3*(4+2))) then I should get (4+2), (3*6) and (9+2-18). The basic objective is that I learn which of the inner parenthesis is going to be executed first and then execute i...
[ "The eval is insecure, so you have to check input string for dangerous things.\n>>> import re\n>>> e = \"(9+2-(3*(4+2)))\"\n>>> while '(' in e:\n... inner = re.search('(\\([^\\(\\)]+\\))', e).group(1)\n... e = re.sub(re.escape(inner), eval('str'+inner), e)\n... print inner,\n... \n(4+2) (3*6) (9+2-18)\n...
[ 4, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004367414_python.txt
Q: HTTP POST, curl and mod_python - How to handle POST request without HTML FORM element? I am running a mod_python server, where the index.py is designed to handle the incoming requests. In the index.py, if I design something like this to handle form and get the details in the form: <form enctype="multipart/form-dat...
HTTP POST, curl and mod_python - How to handle POST request without HTML FORM element?
I am running a mod_python server, where the index.py is designed to handle the incoming requests. In the index.py, if I design something like this to handle form and get the details in the form: <form enctype="multipart/form-data" action="func" method="post"> <p>Input file:<input type="file" name="request"></p> <p><inp...
[ "First a few notes:\n\nIt looks like you're using the Publisher Handler of mod_python. This does a lot under the covers to map URL's to Python functions.\nThe server doesn't really know or care where its getting its data. In your case the curl command is simply simulating a form POST request.\nTherefore you can ha...
[ 4 ]
[]
[]
[ "http_post", "mod_python", "python" ]
stackoverflow_0004364572_http_post_mod_python_python.txt
Q: Pythonic way of doing 'for these except myself' Basically, wondering what the best / most python-y way of doing this is; class thing(collectionclass): for onething in super(collectionclass,listofthings): if onething != self: do something This is obviously a very contrived example but hopef...
Pythonic way of doing 'for these except myself'
Basically, wondering what the best / most python-y way of doing this is; class thing(collectionclass): for onething in super(collectionclass,listofthings): if onething != self: do something This is obviously a very contrived example but hopefully the point is clear! I was thinking of folding th...
[ "Personally I'd use\nfor onething in listofthings:\n if onething is self:\n continue\n # ...\n\nto avoid one level of nesting. You could also use a generator expression:\nfor onething in (x for x in listofthings if x is not self):\n # ...\n\nAlso, S.Lott's comment.\nEdit: Changed == to is as per @gr...
[ 2, 2, 1, 0 ]
[]
[]
[ "list", "oop", "python" ]
stackoverflow_0004367816_list_oop_python.txt
Q: teamplayer and pyhook interacting strangely I'm using teamplayer, which lets you connect more mice to your computer to be used simultaneously. I'm also using pyHook to capture mouse events, with the following code: import pyHook import pythoncom def onclick(event): # called when mouse events are received prin...
teamplayer and pyhook interacting strangely
I'm using teamplayer, which lets you connect more mice to your computer to be used simultaneously. I'm also using pyHook to capture mouse events, with the following code: import pyHook import pythoncom def onclick(event): # called when mouse events are received print 'MessageName:',event.MessageName print 'Messa...
[ "Multiple ideas:\n\nDetect duplicate clicks from the same timestamp, and ignore the first of them. This would require delaying the processing until one time tick later which does complicate matters slightly in your code...\nYou could alter the pyhook source to handle the duplicates instead; debugging inside their s...
[ 1 ]
[]
[]
[ "mouse", "python", "pywin32", "winapi" ]
stackoverflow_0003358355_mouse_python_pywin32_winapi.txt
Q: Difference between "import cv" and "import opencv.cv" using Python + OpenCV? I'm trying to use OpenCV with Python and converting some C++ code. Anyway, if I do: import cv img = cv.LoadImage('image.jpg') It's ok. Or: import opencv.cv as opcv size = opcv.cvSize(40, 50) But anyway, the cv module doesn't have the cv...
Difference between "import cv" and "import opencv.cv" using Python + OpenCV?
I'm trying to use OpenCV with Python and converting some C++ code. Anyway, if I do: import cv img = cv.LoadImage('image.jpg') It's ok. Or: import opencv.cv as opcv size = opcv.cvSize(40, 50) But anyway, the cv module doesn't have the cvSize data structure and the opencv.cv doesn't have the LoadImage. So, what exactly...
[ "The real answer is :) that both \"import opencv.cv\" or \"from opencv import cv\" are the old-style wrapping imports.\nSince OpenCV 2.0, the new-style Python wrapping is used, and the style you should use looks like this:\n# import only cv, no opencv\n# this also brings in sub modules such as highgui\nimport cv\n#...
[ 2, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0004351777_opencv_python.txt
Q: Insert record of utf-8 character (Chinese, Arabic, Japanese.. etc) into GAE datastore programatically with python I just want to build simple UI translation built in GAE (using python SDK). def add_translation(self, pid=None): trans = Translation() trans.tlang = db.Key("agtwaW1kZXNpZ25lcnITCxILQXBwTGFuZ3Vh...
Insert record of utf-8 character (Chinese, Arabic, Japanese.. etc) into GAE datastore programatically with python
I just want to build simple UI translation built in GAE (using python SDK). def add_translation(self, pid=None): trans = Translation() trans.tlang = db.Key("agtwaW1kZXNpZ25lcnITCxILQXBwTGFuZ3VhZ2UY8aIEDA") trans.ttype = "UI" trans.transid = "ui-about" trans.content = "关于我们" trans.put() this is ...
[ "using the u notation:\n>>> s=u\"关于我们\"\n>>> print s\n关于我们\n\nOr explicitly, stating the encoding:\n>>> s=unicode('אדם מתן', 'utf8')\n>>> print s\nאדם מתן \n\nRead more at the Unicode HOWTO page in the python documentation site.\n" ]
[ 6 ]
[]
[]
[ "character_encoding", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004368300_character_encoding_google_app_engine_google_cloud_datastore_python.txt
Q: Need some help on Cookie Handling and session in python I want to set some value to cookie when user visits the homepage so that when he hits some url I'll get that value and compare it with what I've stored in db. Now do I have to set the same cookie value again to handle the next request(in order to maintain ses...
Need some help on Cookie Handling and session in python
I want to set some value to cookie when user visits the homepage so that when he hits some url I'll get that value and compare it with what I've stored in db. Now do I have to set the same cookie value again to handle the next request(in order to maintain session). I'm using python on GAE and I couldn't find any sessio...
[ "Look at gaeutilities. It contains session management stuff.\n", "As mentioned above gaeutilties provides sessions support. If that's what you're looking for overall you may want to check it out. \nHowever, also to answer your question. Cookies set persist between requests, you don't need to keep resetting it unl...
[ 1, 1 ]
[]
[]
[ "cookies", "google_app_engine", "python" ]
stackoverflow_0004353491_cookies_google_app_engine_python.txt
Q: How to provide data from PySide QAbstractItemModel subclass to QML ListView? I have an app I'm writing in PySide that has a QML UI. I have subclassed QAbstractListModel in Python: class MyModel(QtCore.QAbstractListModel): def __init__(self, parent=None): QtCore.QAbstractListModel.__init__(self, parent)...
How to provide data from PySide QAbstractItemModel subclass to QML ListView?
I have an app I'm writing in PySide that has a QML UI. I have subclassed QAbstractListModel in Python: class MyModel(QtCore.QAbstractListModel): def __init__(self, parent=None): QtCore.QAbstractListModel.__init__(self, parent) self._things = ["foo", "bar", "baz"] def rowCount(self, parent=QtCor...
[ "You need to set the role names for the model to be able to access the data in QML;\nhttp://doc.qt.io/archives/qt-4.7/qabstractitemmodel.html#setRoleNames\n" ]
[ 0 ]
[]
[]
[ "pyside", "python", "qml", "qt" ]
stackoverflow_0004013615_pyside_python_qml_qt.txt
Q: How to get started with Sessions in Google App Engine / Django? I'm new to Python / GAE / Django. I get that with GAE there are no in-memory sessions per se... but I think I want something equivalent. I read that Django sessions can be backed by BigTable or MemCache, but I never got them working. I guess what I'm ...
How to get started with Sessions in Google App Engine / Django?
I'm new to Python / GAE / Django. I get that with GAE there are no in-memory sessions per se... but I think I want something equivalent. I read that Django sessions can be backed by BigTable or MemCache, but I never got them working. I guess what I'm asking is "Should I..." Persist with getting Django sessions working...
[ "The reason django sessions are not supported by App engine out of the box is because django uses database table (model) based sessions, and the django ORM is not supported on appengine.\nA solution to this is to make django models work out of the box on appengine. And it has been done by patching django code, in t...
[ 3, 1, 1, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0001271892_django_google_app_engine_python.txt
Q: python sleekxmpp & gchat sending "invisible" presence I am using the python sleekxmpp library to do some work with gchat, my question is: how do I send a presence stanza so that other people see me as invisible (but still be logged on and able to send/receive presencce/messages? So far I have tried self.sendPresen...
python sleekxmpp & gchat sending "invisible" presence
I am using the python sleekxmpp library to do some work with gchat, my question is: how do I send a presence stanza so that other people see me as invisible (but still be logged on and able to send/receive presencce/messages? So far I have tried self.sendPresence(ppriority = "0", ptype="unavailable") but that seems to ...
[ "You're stopping a bit short of properly setting up invisibility. After you send \"unavailable\" you need to send more data in jabber:iq:privacy stanzas, as described in XEP-0126 Invisibility. Once upon a time most clients used XEP-0018 Invisible Presence, but as XMPP became more defined it was realized that that...
[ 1 ]
[]
[]
[ "google_talk", "python", "xmpp" ]
stackoverflow_0004248006_google_talk_python_xmpp.txt
Q: How to organise the structure of a 3D game? This is a bit of a vague question but bear with me. I am in the process of writing a game using Python/Pyglet and openGL. I currently have it structured so that there is an object called 'world', in this are other objects with other objects inside them etc. I did it this...
How to organise the structure of a 3D game?
This is a bit of a vague question but bear with me. I am in the process of writing a game using Python/Pyglet and openGL. I currently have it structured so that there is an object called 'world', in this are other objects with other objects inside them etc. I did it this way because for instance one part of the game is...
[ "Not probably a full answer, but i think a full one would take a whole book...\nWhat you are doing with your representation of the world in a hierarchy is very similar to what is usually known as \"scene-graph\", and it is a good idea in many cases. A good example of a library to do precisly this is Open Scene Grap...
[ 1, 0 ]
[]
[]
[ "3d", "architecture", "pyglet", "python" ]
stackoverflow_0004291566_3d_architecture_pyglet_python.txt
Q: List and files in python I'm using readlines method from python to get list of all data lines. Now I wan't to access some index from that list: file = open('article.txt', 'r') data = file.readlines() print data.index(1) Error: data isn't a list What's wrong? A: I think you mean (if your goal is to print the sec...
List and files in python
I'm using readlines method from python to get list of all data lines. Now I wan't to access some index from that list: file = open('article.txt', 'r') data = file.readlines() print data.index(1) Error: data isn't a list What's wrong?
[ "I think you mean (if your goal is to print the second element of the list):\n print data[1]\n\ndata.index(value) returns the list position of value:\n>>> data = [\"a\",\"b\",\"c\"]\n>>> data[1] # Which is the second element of data?\nb\n>>> data.index(\"a\") # Which is the position of the element \"a\"?\...
[ 5, 1 ]
[]
[]
[ "file", "list", "python" ]
stackoverflow_0004368812_file_list_python.txt
Q: how to use Content_type, video/mp2t in http response? I am preparing response to a http request to send video and receiving error: Broken Pipe if self.path.endswith(".ts"): f = open("filename.ts", 'r') self.send_response(200) self.send_header('Content-Type', "video/mp2t") self.end_headers()...
how to use Content_type, video/mp2t in http response?
I am preparing response to a http request to send video and receiving error: Broken Pipe if self.path.endswith(".ts"): f = open("filename.ts", 'r') self.send_response(200) self.send_header('Content-Type', "video/mp2t") self.end_headers() self.wfile.write(f.read()) return Same response...
[ "Alright, I'll give it a try. \"Broken pipe\" on the server side usually means that the client closes the connection while the server is still sending data. From your previous question, I assume your client is a browser (using the <video> tag). That most probably means that the browser does not support playback of ...
[ 1, 0 ]
[]
[]
[ "http", "http_headers", "mime_types", "python" ]
stackoverflow_0004354649_http_http_headers_mime_types_python.txt
Q: Issue with timezone with time.strftime I've been using blockhosts for some time now, and it's been great so far. I recently updated Ubuntu to 10.10, and I started to see some erratic behaviour. Upon a closer inspection, I noticed a bunch of errors in /var/log/blockhosts.log: ERROR: failed to parse date for ip 188...
Issue with timezone with time.strftime
I've been using blockhosts for some time now, and it's been great so far. I recently updated Ubuntu to 10.10, and I started to see some erratic behaviour. Upon a closer inspection, I noticed a bunch of errors in /var/log/blockhosts.log: ERROR: failed to parse date for ip 188.17.155.25, using now value: time data '2...
[ "The time module doesn't do much than call the unix C API calls, so I would suspect your configuration first of all.\nThat said, time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime()) and time.strftime('%Y-%m-%d %H:%M:%S %Z') should be equivalent, as time.localtime() is the default for the argument, so how those a...
[ 0 ]
[]
[]
[ "python", "time", "timezone", "ubuntu" ]
stackoverflow_0004367896_python_time_timezone_ubuntu.txt
Q: python writing to a file I keep getting this "writing to a closed file error" while trying to compile the following code: fout = open('markov_output.txt', 'w') for i in range( MAXGEN ) : # get our hands on the list key = (w1,w2) sufList = table[key] # choose a suffix from the lis...
python writing to a file
I keep getting this "writing to a closed file error" while trying to compile the following code: fout = open('markov_output.txt', 'w') for i in range( MAXGEN ) : # get our hands on the list key = (w1,w2) sufList = table[key] # choose a suffix from the list suf = random.choice( suf...
[ "You're closing fout each time through the loop. Un-indent fout.close() and it should work as expected.\n", "Don't you want the fout.close() outside the loop??\nYou might want to consider using with if you have Python 2.5 or newer:\nwith open('markov_output.txt', 'w') as fout:\n # Your code to write to the fi...
[ 5, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004369611_python.txt
Q: Displaying a local gstreamer stream in a browser I have a camera feed coming into a linux machine using a V4l2 interface as the source for a gstreamer pipeline. I'm building an interface to control the camera, and I would like to do so in HTML/javascript, communicating to a local server. The problem is getting a f...
Displaying a local gstreamer stream in a browser
I have a camera feed coming into a linux machine using a V4l2 interface as the source for a gstreamer pipeline. I'm building an interface to control the camera, and I would like to do so in HTML/javascript, communicating to a local server. The problem is getting a feed from the gst pipeline into the browser. The option...
[ "You already thought about multiple solutions. You could also stream in ogg/vorbis/theora or vp8 to an icecast server, see the OLPC GStreamer wiki for examples.\nSince you are looking for a python solution as well (according to your tags), have you considered using Flumotion? It's a streaming server written on top ...
[ 1, 0 ]
[]
[]
[ "gstreamer", "javascript", "python" ]
stackoverflow_0003692874_gstreamer_javascript_python.txt
Q: WxPython, change Frame style class Window (wx.MiniFrame): def __init__ ( self ): wx.MiniFrame.__init__(self, None, -1, 'Mini') self.panel = wx.Panel(self) (...) Can I/How to edit MiniFrame style f.e. in my method ChangeStyle(), I want to make a MiniFrame with new parameter (style = wx.NO_BORDER) Do ...
WxPython, change Frame style
class Window (wx.MiniFrame): def __init__ ( self ): wx.MiniFrame.__init__(self, None, -1, 'Mini') self.panel = wx.Panel(self) (...) Can I/How to edit MiniFrame style f.e. in my method ChangeStyle(), I want to make a MiniFrame with new parameter (style = wx.NO_BORDER) Do I have to kill the window and run ...
[ "You can try the frame's SetWindowStyle or SetWindowStyleFlag methods and see if they work. If not, then you'll probably have to close the frame and recreate it with the styles you want.\n" ]
[ 0 ]
[]
[]
[ "coding_style", "python", "wxpython" ]
stackoverflow_0004369833_coding_style_python_wxpython.txt
Q: Button command being called automatically For some reason, this Button is automatically calling bot_analysis_frame without the button being pressed. I'm guessing it's because the command is a function with arguments. Is there a way to have the button only call this function and pass the required variables only up...
Button command being called automatically
For some reason, this Button is automatically calling bot_analysis_frame without the button being pressed. I'm guessing it's because the command is a function with arguments. Is there a way to have the button only call this function and pass the required variables only upon being pressed? Button(topAnalysisFrame, text...
[ "Read the section here on passing callbacks.\nYou are storing the result of that function to the command argument and not the function itself.\nI believe this:\ncommand = lambda: bot_analysis_frame(eventConditionL,eventBreakL)\n\nmight work for you.\n", "I'm pretty sure this has been answered before. Instead of t...
[ 14, 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004370160_python_tkinter.txt
Q: html select option into a list Is there any way I could select all the <option>s in the following HTML form <select> into a python list, like so, ['a','b','c','d']? <select name="sel"> <option value="a">a</option> <option value="b">b</option> <option value="c">c</option> <option value="d">d</option> </...
html select option into a list
Is there any way I could select all the <option>s in the following HTML form <select> into a python list, like so, ['a','b','c','d']? <select name="sel"> <option value="a">a</option> <option value="b">b</option> <option value="c">c</option> <option value="d">d</option> </select> Many thanks in advance.
[ "import re\ntext = '''<select name=\"sel\">\n <option value=\"a\">a</option>\n <option value=\"b\">b</option>\n <option value=\"c\">c</option>\n <option value=\"d\">d</option>\n</select>'''\npattern = re.compile(r'<option value=\"(?P<val>.*?)\">(?P=val)</option>')\nhandy_list = pattern.findall(text)\nprint ...
[ 5, 3 ]
[]
[]
[ "html", "python", "text_processing" ]
stackoverflow_0004369983_html_python_text_processing.txt
Q: Get user's screen_name with twitter API I've started working with the twitter API, and I'd like to know the fastest way to get the authenticated user screen_name. A: The fastest way is to grab the python-twitter library ( which provides an object and method for just about everything - also note - use the latest ...
Get user's screen_name with twitter API
I've started working with the twitter API, and I'd like to know the fastest way to get the authenticated user screen_name.
[ "The fastest way is to grab the python-twitter library ( which provides an object and method for just about everything - also note - use the latest sources, don't fetch the zipped files) and use the GetUser method\n>>> import twitter\n>>> api = twitter.Api(consumer_key=conskey, consumer_secret=conssec, access_token...
[ 2, -2 ]
[]
[]
[ "api", "python", "twitter" ]
stackoverflow_0004367381_api_python_twitter.txt
Q: Add new field to access table using python I have an access table that I am trying to add fields programmatically using Python. It is not a personal geodatabase. Just a standard Access database with some tables in it. I have been able to access the table and get the list of field names and data types. How do I ad...
Add new field to access table using python
I have an access table that I am trying to add fields programmatically using Python. It is not a personal geodatabase. Just a standard Access database with some tables in it. I have been able to access the table and get the list of field names and data types. How do I add a new field and assign the data type to this A...
[ "Using the pyodbc module:\nimport pyodbc\n\nMDB = 'c:/path/to/my.mdb'\nDRV = '{Microsoft Access Driver (*.mdb)}'\nPWD = 'my_password'\n\nconn = pyodbc.connect('DRIVER=%s;DBQ=%s;PWD=%s' % (DRV,MDB,PWD))\nc = conn.cursor()\nc.execute(\"ALTER TABLE my_table ADD COLUMN my_column INTEGER;\")\nconn.commit()\nc.close()\nc...
[ 1 ]
[]
[]
[ "add", "field", "ms_access", "python" ]
stackoverflow_0004370274_add_field_ms_access_python.txt
Q: Does PyODE support composite objects? I'm trying to create a composite object with PyODE, but I can't find any documentation regarding this. Here is some info I found: this is for ODE, the engine that PyODE is a wrapper for, and seems to be the most recent source of information: http://opende.sourceforge.net/wiki...
Does PyODE support composite objects?
I'm trying to create a composite object with PyODE, but I can't find any documentation regarding this. Here is some info I found: this is for ODE, the engine that PyODE is a wrapper for, and seems to be the most recent source of information: http://opende.sourceforge.net/wiki/index.php/Manual_%28Collision_Detection%29...
[ "Bit of a late Answer, but I thought id post it for others.\nYou need to call setOffsetPosition() on the other geoms after the have been attached to the same body\n" ]
[ 0 ]
[]
[]
[ "ode_library", "pyode", "python" ]
stackoverflow_0004272451_ode_library_pyode_python.txt
Q: XML processing in Python So I'm trying to do roughly the following: Take the following snippet of XML: <?xml version="1.0" standalone="no"?> <!DOCTYPE labels SYSTEM "label.dtd"> <labels _FORMAT="E:BARCODE2.ZPL" _QUANTITY="1" _DEVICENAME="ZBR3666875" _JOBNAME="BARC101"> <label> <variable name="x">A-0000000</v...
XML processing in Python
So I'm trying to do roughly the following: Take the following snippet of XML: <?xml version="1.0" standalone="no"?> <!DOCTYPE labels SYSTEM "label.dtd"> <labels _FORMAT="E:BARCODE2.ZPL" _QUANTITY="1" _DEVICENAME="ZBR3666875" _JOBNAME="BARC101"> <label> <variable name="x">A-0000000</variable> </label> </labels> ...
[ "Unless you're dealing with truly gigantic XML files, ElementTree is generally the easiest thing to use. There's the built-in implementations in Python and also lxml.etree which is mostly API-compatible but faster and more flexible.\n" ]
[ 7 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0004370438_python_xml.txt
Q: Class variables of same type as the class Messing around with the typical Point class example when learning Python, I noticed that for some reason I can't have a class level (static variable) of the same type as that of the class. E.g. class Point: ORIGIN = Point() # doesn't work def __init__(self, x=0, y=0)...
Class variables of same type as the class
Messing around with the typical Point class example when learning Python, I noticed that for some reason I can't have a class level (static variable) of the same type as that of the class. E.g. class Point: ORIGIN = Point() # doesn't work def __init__(self, x=0, y=0): self.x = x self.y = y while the same...
[ "class Point(object):\n pass\n\nPoint.ORIGIN = Point()\n\n", "Assign it after the fact:\nclass Point:\n def __init__(self, x=0, y=0):\n self.x = x\n self.y = y\n\n\nPoint.ORIGIN = Point()\n\n", "You can't create an instance of a class, until that class is actually created, which is after the class body ...
[ 13, 7, 5, 4 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0004369814_oop_python.txt
Q: Modifying nested lists How to handle nested lists in Python? I am having problem figuring out the syntax. Like example: >>> l = [[1, 2, 3], [5, 6, 7]] I want to square all the elements in this list. I tried: [m*m for m in l] But that doesn't work and throws up: TypeError: can't multiply sequence by non-int of...
Modifying nested lists
How to handle nested lists in Python? I am having problem figuring out the syntax. Like example: >>> l = [[1, 2, 3], [5, 6, 7]] I want to square all the elements in this list. I tried: [m*m for m in l] But that doesn't work and throws up: TypeError: can't multiply sequence by non-int of type 'list' because of th...
[ ">>> l = [[1, 2, 3], [5, 6, 7]]\n>>> [[e*e for e in m] for m in l]\n |-nested list-|\n |---- complete list ---|\n[[1, 4, 9], [25, 36, 49]]\n\n", "[[1,2,3],[4,5,6]] != [1,2,3,4,5,6] \n\n[map(lambda x: x *x,sl) for sl in l] #List comprhension\n\n", "Assuming you wanted the answer to look like th...
[ 9, 1, 1, 0 ]
[]
[]
[ "nested_lists", "python" ]
stackoverflow_0004370641_nested_lists_python.txt
Q: django-debug-toolbar blows up when saving binary object in db. Is there a workaround? I'm using the django-debug-toolbar, and when I try to save something in a blob field I get: DjangoUnicodeDecodeError looking through the stack trace it come from: django_debug_toolbar-0.8.4-py2.6.egg/debug_toolbar/panels/sql.py i...
django-debug-toolbar blows up when saving binary object in db. Is there a workaround?
I'm using the django-debug-toolbar, and when I try to save something in a blob field I get: DjangoUnicodeDecodeError looking through the stack trace it come from: django_debug_toolbar-0.8.4-py2.6.egg/debug_toolbar/panels/sql.py in execute 98. _params = simplejson.dumps([force_unicode(x, strings_only=True) for x in para...
[ "My thought would be to break out that list comprehension into a traditional for loop, and wrap a try/except around it so it doesn't throw an exception. In the except clause, simply add something like \"Non-unicode object\" for the output.\nThere is nothing currently built-in to work around this, sorry.\n" ]
[ 0 ]
[]
[]
[ "django", "django_debug_toolbar", "python" ]
stackoverflow_0004350028_django_django_debug_toolbar_python.txt
Q: Is there any way to set options without any prefix in Argparser? I'm using Argparser to handle arguments for my CLI prog. But as the time passed I think that It's not a good Idea to use it. Here comes the problem. I want to use options without any prefix character. Like git commit or svn move. I've searched a litt...
Is there any way to set options without any prefix in Argparser?
I'm using Argparser to handle arguments for my CLI prog. But as the time passed I think that It's not a good Idea to use it. Here comes the problem. I want to use options without any prefix character. Like git commit or svn move. I've searched a little and found that Argparse has a add_subparser() method. Let us popula...
[ "Edit: Apparently the default for default is None, which means we don't have one, so you'll have to use True and False (which is the right way anyhow).\nYou need to add the default when you add your argument to the parser:\nparser_a.add_argument('-ap', '--add-project',\n nargs = '*',\n ...
[ 0, 0 ]
[]
[]
[ "argparse", "arguments", "python" ]
stackoverflow_0004370834_argparse_arguments_python.txt
Q: Trouble using lxml from a .py file. It works with the interpreter I have python.org v2.7 installed on my Snow Leopard. There's also a Apple 2.6 Python onboard. I pip installed lxml with the 'sudo pip install lxml' command. I made sure I was doing this from within the bin directory of my python.org 2.7 version. Whe...
Trouble using lxml from a .py file. It works with the interpreter
I have python.org v2.7 installed on my Snow Leopard. There's also a Apple 2.6 Python onboard. I pip installed lxml with the 'sudo pip install lxml' command. I made sure I was doing this from within the bin directory of my python.org 2.7 version. When I give the command: from lxml import etree within the IDLE interpret...
[ "Finally figured this out. There was a file named lxml.py in the PATH which wasn't the lxml module. Actually, I created that file when I started playing with the lxml tutorial a couple days ago and didn't pay attention to the filename match. I totally forgot about it. Dumb me.\n", "Which interpreter are they runn...
[ 2, 1 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0004361676_lxml_python.txt
Q: How do I create a view onto a NumPy array? I have a 2D numpy array. Is there a way to create a view onto it that would include the first k rows and all columns? The point is to avoid copying the underlying data (the array is so large that making partial copies is not feasible.) A: Sure, just index it as you norm...
How do I create a view onto a NumPy array?
I have a 2D numpy array. Is there a way to create a view onto it that would include the first k rows and all columns? The point is to avoid copying the underlying data (the array is so large that making partial copies is not feasible.)
[ "Sure, just index it as you normally would. E.g. y = x[:k, :] This will return a view into the original array. No data will be copied, and any updates made to y will be reflected in x and vice versa.\n\nEdit: \nI commonly work with >10GB 3D arrays of uint8's, so I worry about this a lot... Numpy can be very effic...
[ 253 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0004370745_numpy_python.txt
Q: CDATA Directive missing from SAX Parser output I am using the following code to read an XML file and write it to an XML output file using the SAX Parser. However, the output file is missing the CDATA directives. The contents of the CDATA section are there all right, but the starting <![CDATA[ and the closing ]]> a...
CDATA Directive missing from SAX Parser output
I am using the following code to read an XML file and write it to an XML output file using the SAX Parser. However, the output file is missing the CDATA directives. The contents of the CDATA section are there all right, but the starting <![CDATA[ and the closing ]]> are not present in the output file! from xml.sax imp...
[ "CDATA is a convenience annotation used to include text containing markup. The fact that a text node was enclosed in CDATA in a particular serialization may be preserved by the parser or may be discarded. If your SAX parser has events for CDATA sections, you have to handle them and then re-wrap the text node in C...
[ 0 ]
[]
[]
[ "python", "sax", "xml" ]
stackoverflow_0004370081_python_sax_xml.txt
Q: Parsing HTML: lxml error in Python I am writing a simple script to fetch the big grey table from here. The code I have is the following: import urllib2 from lxml import etree html = urllib2.urlopen("http://www.afi.com/100years/movies10.aspx").read() root = etree.XML(html) But I am getting an error on the last s...
Parsing HTML: lxml error in Python
I am writing a simple script to fetch the big grey table from here. The code I have is the following: import urllib2 from lxml import etree html = urllib2.urlopen("http://www.afi.com/100years/movies10.aspx").read() root = etree.XML(html) But I am getting an error on the last statement. Traceback (most recent call la...
[ "You're trying to parse HTML with the XML parser, you should use the lxml HTML parser.\nimport urllib2\nfrom StringIO import StringIO\nfrom lxml import etree\n\nufile = urllib2.urlopen(\"http://www.afi.com/100years/movies10.aspx\")\n\nroot = etree.parse(ufile, etree.HTMLParser())\n\nprint etree.tostring(root)\n\n",...
[ 9, 1 ]
[]
[]
[ "html_parsing", "lxml", "python" ]
stackoverflow_0004371004_html_parsing_lxml_python.txt
Q: from log with regex extracted values fail correct insertion into sqlite table Problem with storing extracted values in SQLite - How to adress or index list of values for proper insertion into table. The Regex works fine: input logging data looks like: 0.0.0(06026104) 1.6.1(0.1501)(1011111000) 1.6.1*32(0.1446)(1010...
from log with regex extracted values fail correct insertion into sqlite table
Problem with storing extracted values in SQLite - How to adress or index list of values for proper insertion into table. The Regex works fine: input logging data looks like: 0.0.0(06026104) 1.6.1(0.1501)(1011111000) 1.6.1*32(0.1446)(1010190800) 1.8.1(02484.825) 1.8.1*32(02449.574) correct regex output: 06026104 0.150...
[ "for line in fp:\n match = re.search(r'(0\\.0\\.0|1\\.6\\.1|1\\.8\\.1)\\(([0-9\\.]+)', line)\n if match: \n version,value = match.groups() \n extrakt.append(value)\ncursor.execute('INSERT INTO energielog (sernr, peak, kwh) values (?, ?, ?)', extrakt)\n\nthat works out\n" ]
[ 0 ]
[]
[]
[ "iteration", "python", "regex", "sqlite" ]
stackoverflow_0004369243_iteration_python_regex_sqlite.txt
Q: Can't add new line to text file with all other lines being removed I need to be able to add a new line to the end of a simple text file, but I can't. I have a for loop, and on each loop I want to add a new line of text to the end of the file in question, but every time it adds a new line, it removes all the other ...
Can't add new line to text file with all other lines being removed
I need to be able to add a new line to the end of a simple text file, but I can't. I have a for loop, and on each loop I want to add a new line of text to the end of the file in question, but every time it adds a new line, it removes all the other text, leaving just that line. This is the code: for item in items: ...
[ "Use 'a' (append) mode to, well, append anything you write to the end of the file instead of truncating it.\nAlso, you propably want to open the file outside of the loop and close it afterwards (with open(...) as f: ... would be even better).\n", "Try to open the file in \"append\" mode:\nfor item in items: \ndoc...
[ 3, 3 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0004371216_file_io_python.txt
Q: How to for-loop three columns per row in Django/python? I would like to display data, three columns per row during my for. I would like my result to look like the following: <table> <tr><td>VALUE1</td><td>VALUE2</td><td>VALUE3</td></tr> <tr><td>VALUE4</td><<td>VALUE5</td><td>VALUE6</td></tr> </table> Anyone know ...
How to for-loop three columns per row in Django/python?
I would like to display data, three columns per row during my for. I would like my result to look like the following: <table> <tr><td>VALUE1</td><td>VALUE2</td><td>VALUE3</td></tr> <tr><td>VALUE4</td><<td>VALUE5</td><td>VALUE6</td></tr> </table> Anyone know how to do it? Syntax Error TemplateSyntaxError at / 'for' st...
[ "There's a divisibleby tag.\nSo you can do something (ugly) like:\n<table><tr>\n{% for field in form %}\n <td>{{ field }}</td>\n {% if forloop.last %}\n </tr>\n {% else %}\n {% if forloop.counter|divisibleby:\"3\" %}\n </tr><tr>\n {% endif %}\n {% endif %}\n{% endfor %}\n</table>\n\nAltern...
[ 23 ]
[ "<table>\n{% for i in range(0, len(stuff), 3) %}\n <tr>\n {% for j in range(3) %}\n <td>{{ stuff[i+j] }}</td>\n {% endfor %} \n </tr>\n{% endfor %}\n</table>\n\nSorry misunderstood question.\n" ]
[ -2 ]
[ "django", "for_loop", "python" ]
stackoverflow_0004371338_django_for_loop_python.txt
Q: What is a good framework for a soap service? I'm looking for a good framework to use for a soap service. I'd prefer to use a pythonic framework, but after looking at soaplib/rpclib (too unstable), SOAPy (doesn't work with 2.7) and ZSI (too...confusing), I'm not sure that's possible. I'm fine with it being in anot...
What is a good framework for a soap service?
I'm looking for a good framework to use for a soap service. I'd prefer to use a pythonic framework, but after looking at soaplib/rpclib (too unstable), SOAPy (doesn't work with 2.7) and ZSI (too...confusing), I'm not sure that's possible. I'm fine with it being in another language, though I'm hesitant to use php's soa...
[ "Checkout Twisted, great framework for building network services. And soap is basically an extension of xmlrpc. \n\nhttp://twistedmatrix.com/trac/\nhttp://twistedmatrix.com/documents/10.1.0/web/howto/xmlrpc.html#auto4\nhttp://twistedmatrix.com/documents/10.1.0/api/twisted.web.soap.Proxy.html\n\n", "I have used Sp...
[ 4, 1 ]
[]
[]
[ "python", "silverlight", "soap", "web_services" ]
stackoverflow_0004371139_python_silverlight_soap_web_services.txt
Q: take a char and print out from char to 'a' and reverse it should be recursive this is what Ii wrote so far but it is not the correct output def characters(char): numb=ord(char) while numb>ord('a'): print chr(numb), numb=numb-1 return I want the this output: characters('h') g f e d c...
take a char and print out from char to 'a' and reverse it should be recursive
this is what Ii wrote so far but it is not the correct output def characters(char): numb=ord(char) while numb>ord('a'): print chr(numb), numb=numb-1 return I want the this output: characters('h') g f e d c b a
[ "Your function should be designed to call itself if it has to be recursive:\ndef recurse_chars_down(char):\n if char <= 'a':\n print char\n else:\n print char,\n recurse_chars_down(chr(ord(char) - 1))\n\n>>> recurse_chars_down('h')\nh g f e d c b a\n\n", "Whenever you design a recursive...
[ 3, 3, 0, 0 ]
[]
[]
[ "char", "python", "recursion" ]
stackoverflow_0004371744_char_python_recursion.txt
Q: Designing a web based game that would run in a browser - Where should I start? I would like to design a web based game preferably in Python ( using Django maybe) though I'm open to any language other than Java/Flash/ActionScript. The idea I have in mind is more about data models than graphics and will leverage soc...
Designing a web based game that would run in a browser - Where should I start?
I would like to design a web based game preferably in Python ( using Django maybe) though I'm open to any language other than Java/Flash/ActionScript. The idea I have in mind is more about data models than graphics and will leverage social networking sites. I would like to extend it with a mobile web interface in the f...
[ "Step 1. Design a good game.\nStep 2. Be sure that it fits the HTTP model of simple request/reply GET/POST processing. Be sure that the game is still good. Some people try to do \"real time\" or \"push\" or other things that don't fit the model well and require lots of sophisticated GUI on the desktop.\nStep 3....
[ 9, 6 ]
[]
[]
[ "python", "web_applications" ]
stackoverflow_0004369314_python_web_applications.txt
Q: In Django, how can I keep the value of the File input after it is returned to it through an error? Let's say someone submits a form. (I'm using Django's form framework completely) The form goes through my models.py and doesn't validate well. I redirect them back to the page, and display the form errors. All of the...
In Django, how can I keep the value of the File input after it is returned to it through an error?
Let's say someone submits a form. (I'm using Django's form framework completely) The form goes through my models.py and doesn't validate well. I redirect them back to the page, and display the form errors. All of the text boxes have their initial value in them, so the user doesn't have to retype them. But my "Choose ...
[ "If you validate the file separately you could store it before returning the error and provide an indication to the user that their upload has been saved (optionally allow them to choose between uploading yet another file or use the one from a previous submittal). This is a lot of extra housekeeping which could be...
[ 2 ]
[]
[]
[ "django", "forms", "html", "javascript", "python" ]
stackoverflow_0004371947_django_forms_html_javascript_python.txt
Q: Adding transparency to PNGCanvas images I've been playing around with PNGCanvas, and the one thing I can't figure out is how to add transparency to images. I've been trying to vary the alpha channel values, but it only adjusts the intensity of the color. Am I barking up the wrong tree using this library, or is the...
Adding transparency to PNGCanvas images
I've been playing around with PNGCanvas, and the one thing I can't figure out is how to add transparency to images. I've been trying to vary the alpha channel values, but it only adjusts the intensity of the color. Am I barking up the wrong tree using this library, or is there hope?
[ "You're barking up the wrong tree. Here's a quote from PNGCanvas.dump:\n# 8-bit image represented as RGB tuples\n# simple transparency, alpha is pure white\n\nLooking further through its code, when you provide alpha it's just blending it with the background, and the final background is just white.\n" ]
[ 1 ]
[]
[]
[ "alpha_transparency", "png", "python" ]
stackoverflow_0004371846_alpha_transparency_png_python.txt
Q: Socket Connection: Python So I'm trying to send several iterations of a barcode file to a device. This is the relevant part of the code: # Start is the first barcode start = 1234567 # Number is the quantity number = 3 with open('barcode2.xml', 'rt') as f: tree = ElementTree.parse(f) # Iterate over all elem...
Socket Connection: Python
So I'm trying to send several iterations of a barcode file to a device. This is the relevant part of the code: # Start is the first barcode start = 1234567 # Number is the quantity number = 3 with open('barcode2.xml', 'rt') as f: tree = ElementTree.parse(f) # Iterate over all elements in a tree for the root ele...
[ "target_file = open(\"barcode2.xml\") \nbarc_file_text = target_file.read() \nsock.sendall(barc_file_text) \nsock.close()\n\nThe socket gets closed, but the file doesn't. The next time through the loop, there is already a lock on the file when you get to the with open... part.\nSolution: Use with open......
[ 4 ]
[]
[]
[ "python", "sockets", "xml" ]
stackoverflow_0004372088_python_sockets_xml.txt
Q: Upgrading Django from 1.1 to 1.2 I've an Ubuntu server with Nginx and Django 1.1 installed. On the developer's local he had 1.2 and it has some features (smart if) that are breaking now on my dev server. I need to upgrade to 1.2. This is pretty much my first proper django/python project I'm involved in so I'm fe...
Upgrading Django from 1.1 to 1.2
I've an Ubuntu server with Nginx and Django 1.1 installed. On the developer's local he had 1.2 and it has some features (smart if) that are breaking now on my dev server. I need to upgrade to 1.2. This is pretty much my first proper django/python project I'm involved in so I'm feeling my way into it. What I want to d...
[ "pip -E /var/www/env/example.com install --upgrade django will work properly and upgrade the django installation, however you may want to read the release notes for django 1.2 and be aware of any backwards incompatible changes that may break your code. Also, you may want to do this on a dev server first and run any...
[ 3 ]
[]
[]
[ "django", "python", "virtualenv" ]
stackoverflow_0004368419_django_python_virtualenv.txt
Q: Hide window from taskbar I'm trying to minimize a window to the tray, but it seems it refuses to hide from the taskbar. I've spent a little time and distilled the problem code down to this. It's not mcuh so I'm wondering if I need something else to hide my app to tray in Windows 7. import sys, os from PyQt4 import...
Hide window from taskbar
I'm trying to minimize a window to the tray, but it seems it refuses to hide from the taskbar. I've spent a little time and distilled the problem code down to this. It's not mcuh so I'm wondering if I need something else to hide my app to tray in Windows 7. import sys, os from PyQt4 import uic from PyQt4.QtGui import ...
[ "It took a quite ugly hack to get it working but here's the final code if anybody is interested, ph is my platform-specific module, you can use platform.name or similar function instead:\ndef hideEvent(self, event):\n self.hide()\n if ph.is_windows():\n self.hidden = True\n self.setWindowFlags(Q...
[ 3, 1 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0004331802_pyqt_python_qt.txt
Q: Uses of combining **kwargs and key word arguments in a method signature Is there a use for combining **kwargs and keyword arguments in a method signature? >>> def f(arg, kw=[123], *args, **kwargs): ... print arg ... print kw ... print args ... print kwargs ... >>> f(5, 'a', 'b', 'c', kw=['abc'], kw2='def') T...
Uses of combining **kwargs and key word arguments in a method signature
Is there a use for combining **kwargs and keyword arguments in a method signature? >>> def f(arg, kw=[123], *args, **kwargs): ... print arg ... print kw ... print args ... print kwargs ... >>> f(5, 'a', 'b', 'c', kw=['abc'], kw2='def') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeE...
[ "In Python 3 you can have keyword-only arguments (PEP 3102). With these, your function would look like this:\n>>> def f(arg, *args, kw=[123], **kwargs): \n... print(arg)\n... print(kw)\n... print(args)\n... print(kwargs)\n>>> f(5, 'a', 'b', 'c', kw=['abc'], kw2='def')\n5\n('a', 'b', 'c')\n['abc']\n{'kw2': 'def...
[ 14, 9 ]
[]
[]
[ "python" ]
stackoverflow_0004372346_python.txt
Q: Python tkInter Entry fun Playing around with Python - tkInter - Entry widget - when I use validatecommand (below), the check happens the first time the string > Max, but when I continue to enter text the check steps - there's no delete or insert after the first time? Any advice? (outside of not building a desktop...
Python tkInter Entry fun
Playing around with Python - tkInter - Entry widget - when I use validatecommand (below), the check happens the first time the string > Max, but when I continue to enter text the check steps - there's no delete or insert after the first time? Any advice? (outside of not building a desktop app via python) #!/usr/bin/e...
[ "From the Tk man:\n\nThe validate option will also set itself to none when you edit the entry widget from within either the validateCommand or the invalidCommand. Such editions will override the one that was being validated. If you wish to edit the entry widget (for example set it to {}) during validation and still...
[ 3, 3, 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0001019782_python_tkinter.txt
Q: Traversing and modifying a tree-like list of dict structure I have a structure that looks like this: [ {'id': 4, 'children': None}, {'id': 2, 'children': [ {'id': 1, 'children': [ {'id': 6, 'children': None}, {'id': 5, 'children': None} ] }, {'id': 7, 'children': [ {'id...
Traversing and modifying a tree-like list of dict structure
I have a structure that looks like this: [ {'id': 4, 'children': None}, {'id': 2, 'children': [ {'id': 1, 'children': [ {'id': 6, 'children': None}, {'id': 5, 'children': None} ] }, {'id': 7, 'children': [ {'id': 3, 'children': None} ] } ] } ] I also have a list...
[ "Recursion is perfectly elegant. List comprehensions don't apply as you're altering the structure in place, rather than producing a new sequence. As for generators, you could write a DFS or BFS traverser.\ndef dfs(nodes):\n if nodes is not None:\n for node in nodes:\n yield node\n yi...
[ 9, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004372073_python.txt
Q: Getting the widget that triggered an Event? In Tkinter, I have a multiple widgets bound to the left-mouse button. They all trigger the same event when clicked. How do I recover which widget was clicked? I want it so when say Label2 was pressed, I'd be able to recover that Label2 was the widget that was pressed w...
Getting the widget that triggered an Event?
In Tkinter, I have a multiple widgets bound to the left-mouse button. They all trigger the same event when clicked. How do I recover which widget was clicked? I want it so when say Label2 was pressed, I'd be able to recover that Label2 was the widget that was pressed within the event it triggered.
[ "def f(event):\n caller = event.widget\n\n", "You have a couple options. One way is to access the widget attribute of the event object. Another way is to pass an object reference in to your function. Here's an example that uses one of each. \nimport Tkinter as tk\n\ndef onClickA(event):\n print \"you clicke...
[ 22, 15, 4 ]
[]
[]
[ "events", "python", "tkinter", "widget" ]
stackoverflow_0004299145_events_python_tkinter_widget.txt
Q: In Python, how to sort a dict inside a dict by a key within the inner dict I have a data set in key/value form: setlist = {{'135350258120342034': {'title':'The Matrix'} {'235350258120342034': {'title':'The Godfather'} {'335350258120342034': {'title':'Atonement'} } How can I sort setl...
In Python, how to sort a dict inside a dict by a key within the inner dict
I have a data set in key/value form: setlist = {{'135350258120342034': {'title':'The Matrix'} {'235350258120342034': {'title':'The Godfather'} {'335350258120342034': {'title':'Atonement'} } How can I sort setlist by the value of 'key' which is a dict within a dict?
[ ">>> sorted(setlist.items(),key=lambda x:x[1]['title'])\n[('335350258120342034', {'title': 'Atonement'}), ('235350258120342034', {'title': 'The Godfather'}), ('135350258120342034', {'title': 'The Matrix'})]\n\n", "You can't, dicts can't be sorted.\nWhat you can do is move your key for the outer dict into the inne...
[ 5, 2, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0004373351_dictionary_python.txt
Q: splitting a string->list to be checked I've been lurking for a few weeks, and decided to join in order to be more hands-on with my learning of Python. What I'm trying to do is take a single string, containing several web addresses, and come up with a list containing all the addresses with a domain name of 2-4 char...
splitting a string->list to be checked
I've been lurking for a few weeks, and decided to join in order to be more hands-on with my learning of Python. What I'm trying to do is take a single string, containing several web addresses, and come up with a list containing all the addresses with a domain name of 2-4 characters. The hypothetical addresses are not a...
[ "Assuming you only care about the length of the TLD:\n[url for url in urlstring.split(',') if 2 <= len(url.split('.')[-2]) <= 4]\n\n", "Or if you want to get all the urls that have at least one desired, or length-correct, domain name, you could try the following code:\ndef len_is_valid(url, min_len, max_len):\n ...
[ 1, 0, 0 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0004373002_python_split_string.txt
Q: can more than one thread use the same port i'm trying to write a multithreaded server in python which can recieve multiple client requests then send the answer in a UDP packet (port 53). I was wondering if all these threads can use 53 at the same time. thanks a lot (this question might seem silly, i'm a beginner) ...
can more than one thread use the same port
i'm trying to write a multithreaded server in python which can recieve multiple client requests then send the answer in a UDP packet (port 53). I was wondering if all these threads can use 53 at the same time. thanks a lot (this question might seem silly, i'm a beginner)
[ "If you specify the 'reuse port' option, then yes you can bind multiple listening sockets to the same port. But in my experience even when doing that, only one of the sockets will receive any given packet (unless you're receiving multicast packets).\nmySocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)\n\...
[ 3 ]
[ "Please don't. Use Twisted instead. It's already got all that sort of stuff done.\n" ]
[ -1 ]
[ "multithreading", "python" ]
stackoverflow_0004373728_multithreading_python.txt
Q: In Django, how do I keep a running list of notifications for the user? When the user clicks the "My Notifications" tab, I want him to see a list of new and old notifications and the time that the action happened. That means, the notifications must be stored, and must even have a cursor to be paged through. Does th...
In Django, how do I keep a running list of notifications for the user?
When the user clicks the "My Notifications" tab, I want him to see a list of new and old notifications and the time that the action happened. That means, the notifications must be stored, and must even have a cursor to be paged through. Does the Django message framework do this?
[ "Adjusting Django messages framework to fit with your requirement would be a big deviation from the way the framework works.\nI would strongly recommend not to use the framework for this particular use-case since creating a simple Django model (User FK, Notification, created datetimestamp) would be a better approac...
[ 5, 2 ]
[]
[]
[ "database", "django", "messages", "notifications", "python" ]
stackoverflow_0004372688_database_django_messages_notifications_python.txt
Q: Getting session information from a xmmppy connection for jsjac I am trying to make xwchat and xmpppy work together following this blog post , http://codingcromulence.blogspot.com/2009/01/chat-hacking-part-ii.html But unable to get session id and other information from xmpppy connection. Does anyone has prior exper...
Getting session information from a xmmppy connection for jsjac
I am trying to make xwchat and xmpppy work together following this blog post , http://codingcromulence.blogspot.com/2009/01/chat-hacking-part-ii.html But unable to get session id and other information from xmpppy connection. Does anyone has prior experience with this ?
[ "Got the solution, need to use a BOSH Client on server side, BOSH client creates a session and gives sid, rid which can be used in view.\n" ]
[ 0 ]
[]
[]
[ "python", "xmpppy" ]
stackoverflow_0004130591_python_xmpppy.txt
Q: How do I find where Python is located on Unix? I'm working on a new server for a new workplace, and I'm trying to reuse a CGI script I wrote in Python earlier this year. My CGI script starts off with #!/local/usr/bin/python But when I run this on the new server, it complains that there's no such folder. Obviously...
How do I find where Python is located on Unix?
I'm working on a new server for a new workplace, and I'm trying to reuse a CGI script I wrote in Python earlier this year. My CGI script starts off with #!/local/usr/bin/python But when I run this on the new server, it complains that there's no such folder. Obviously Python's kept in a different place on this box, but...
[ "Try:\nwhich python\n\nin a terminal.\n", "For this very reason it is recommend that you change your shebang line to be more path agnostic:\n#!/usr/bin/env python\n\nSee this mailing list message for more information:\n\nConsider the possiblities that in a different machine, python may be installed at /usr/bin/py...
[ 27, 9, 4, 4, 3, 1 ]
[]
[]
[ "directory", "python", "shebang", "shell", "unix" ]
stackoverflow_0004373428_directory_python_shebang_shell_unix.txt
Q: list checking in python Hello there i've written a small functions that takes two lists and compares them for duplicating pairs, and returns a boolean value. For instance ([1,2,3],[2,1,4]) returns false and ([1,2,3],[3,4,5]) returns true But i would like the argument to take any given amount of lists, instead of j...
list checking in python
Hello there i've written a small functions that takes two lists and compares them for duplicating pairs, and returns a boolean value. For instance ([1,2,3],[2,1,4]) returns false and ([1,2,3],[3,4,5]) returns true But i would like the argument to take any given amount of lists, instead of just two. Here's my program so...
[ "import itertools\n\ndef check(*args):\n r = None\n for l in args:\n s = set(frozenset(x) for x in itertools.combinations(l, 2))\n if r is None:\n r = s\n else:\n r &= s\n if not r:\n return True\n return False\n\nprint check([1, 2, 3], [3, 4, 5])\nprint check([1, 2, 3], [2, 1, 4])\n\n...
[ 3, 3, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004374426_list_python.txt
Q: how can i make the server listen for TCP and UDP? i'm using python twisted and i have two separate servers working, one that recieves TCP, one that receives UDP and they each use reactor.listenTCP(PORT, factory) reactor.run() and reactor.listenUDP(PORT, BaseThreadedUDPServer()) reactor.run() They both work but n...
how can i make the server listen for TCP and UDP?
i'm using python twisted and i have two separate servers working, one that recieves TCP, one that receives UDP and they each use reactor.listenTCP(PORT, factory) reactor.run() and reactor.listenUDP(PORT, BaseThreadedUDPServer()) reactor.run() They both work but now I want to combine them into one server that recieves...
[ "This is just a rephrasing of MarkR's answer, which is right, but I thought it might be a bit clearer to spell out exactly how this works:\nInstead of what you propose, your program should look like this:\nreactor.listenTCP(PORT, factory)\nreactor.listenUDP(PORT, BaseThreadedUDPServer())\nreactor.run()\n\nIt's help...
[ 5, 4 ]
[]
[]
[ "python", "tcp", "twisted", "udp" ]
stackoverflow_0004374399_python_tcp_twisted_udp.txt
Q: Python: Call all methods of an object with a given set of arguments I'd like to call all methods of a python object instance with a given set of arguments, i.e. for an object like class Test(): def a(input): print "a: " + input def b(input): print "b: " + input def c(input): pri...
Python: Call all methods of an object with a given set of arguments
I'd like to call all methods of a python object instance with a given set of arguments, i.e. for an object like class Test(): def a(input): print "a: " + input def b(input): print "b: " + input def c(input): print "c: " + input I would like to write a dynamic method allowing me to r...
[ "Not exactly sure why you want to do this. Normally in something like unittest you would provide an input on your class then reference it inside each test method.\nUsing inspect and dir.\nfrom inspect import ismethod\n\ndef call_all(obj, *args, **kwargs):\n for name in dir(obj):\n attribute = getattr(obj...
[ 12, 1 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0004374563_design_patterns_python.txt
Q: should i use a decorator to provide a subclass to multiple classes in python I have a subclass baz, which needs to be included in both foo and bar, class foo(): def __init__() pass class baz: pass class bar(): def __init__() pass class baz: pass I imagine in this situation a de...
should i use a decorator to provide a subclass to multiple classes in python
I have a subclass baz, which needs to be included in both foo and bar, class foo(): def __init__() pass class baz: pass class bar(): def __init__() pass class baz: pass I imagine in this situation a decorator could wrap around both foo and bar, providing baz to each, but i can't se...
[ "To reiterate the comments, don't use this method to create Admin objects for Django, upgrade to a later, greater version of Django :) \nFWIW a decorator to do what you asked would look something like:\ndef add_baz(klass):\n def adder():\n instance = klass()\n\n class Baz:\n bazvar='This...
[ 0 ]
[]
[]
[ "decorator", "django", "python" ]
stackoverflow_0004372129_decorator_django_python.txt
Q: Asynchronous getNext errors out when going out of table I am using one of the examples for GetNext operation for an SNMPWalk of the tree. I am using the asynchronous variant to collect the OIDs - # GETNEXT Command Generator from pysnmp.entity.rfc3413.oneliner import cmdgen from pysnmp.proto import rfc1902 # ( ( ...
Asynchronous getNext errors out when going out of table
I am using one of the examples for GetNext operation for an SNMPWalk of the tree. I am using the asynchronous variant to collect the OIDs - # GETNEXT Command Generator from pysnmp.entity.rfc3413.oneliner import cmdgen from pysnmp.proto import rfc1902 # ( ( authData, transportTarget, varNames ), ... ) targets = ( ...
[ "changing CommunityData string did the trick (I don't know why)\nBEFORE\ncmdgen.CommunityData('test-agent-1', 'public'), \n\nAFTER \ncmdgen.CommunityData('test-agent', 'public'),\n\n", "That seems to happen on request retry. So it may not be relevant to going out of table.\nI'd suggest upgrading your pysnmp insta...
[ 1, 0 ]
[]
[]
[ "pysnmp", "python", "snmp" ]
stackoverflow_0004370540_pysnmp_python_snmp.txt
Q: how do I share configuration data between Javascript, Python, and CSS in my Django app? I have Javascript, Django templates, Python code, and CSS which all work with the same configuration data. Where's the best place to configure it? Specifically, I have a browser-side entry widget in Javascript which controls an...
how do I share configuration data between Javascript, Python, and CSS in my Django app?
I have Javascript, Django templates, Python code, and CSS which all work with the same configuration data. Where's the best place to configure it? Specifically, I have a browser-side entry widget in Javascript which controls an embedded Java app. When the user is done, the Javascript asks the Java applet for an image o...
[ "Use JSON. Generate the CSS dynamically, using caching to reduce load.\n", "I think an really good approach would be to effectively have a DSL expressed indirectly via JSON data structures laid out using some sort of coding convention, coupled with a separate build step that used that to create the configuration ...
[ 4, 0 ]
[]
[]
[ "css", "data_sharing", "django", "javascript", "python" ]
stackoverflow_0004375838_css_data_sharing_django_javascript_python.txt
Q: How come I can't get the file from my POST request? @csrf_exempt def document_ajax_upload(request): print request.POST['qqfile'] return HttpResponse('{"success":true}') I'm following this tutorial: http://valums.com/ajax-upload/ I'm supposed to be able to get the picture, once it's uploaded via ajax. Th...
How come I can't get the file from my POST request?
@csrf_exempt def document_ajax_upload(request): print request.POST['qqfile'] return HttpResponse('{"success":true}') I'm following this tutorial: http://valums.com/ajax-upload/ I'm supposed to be able to get the picture, once it's uploaded via ajax. This is my HTML code: var uploader = new qq.Fil...
[ "Files aren't stored in request.POST, they're stored in request.FILES.\n", "It looks like the request actually just contains the image data (request has content-type \"application/octetstream\"). So I would try the following:\nfrom django.core.files.uploadedfile import SimpleUploadedFile\n\ndef document_ajax_uplo...
[ 1, 1 ]
[]
[]
[ "ajax", "django", "javascript", "jquery", "python" ]
stackoverflow_0004375574_ajax_django_javascript_jquery_python.txt
Q: How to get the expression which has the maxium result in a string list? For example, I have a list a = ['3*4', '2*3', '4*6'], I want to print the string in the list whose result will be the largest, '4*6' in this case. A: >>> a = ['3*4', '2*3', '4*6'] >>> max(a, key=eval) '4*6' with the usual caveats about usi...
How to get the expression which has the maxium result in a string list?
For example, I have a list a = ['3*4', '2*3', '4*6'], I want to print the string in the list whose result will be the largest, '4*6' in this case.
[ ">>> a = ['3*4', '2*3', '4*6']\n>>> max(a, key=eval)\n'4*6'\n\nwith the usual caveats about using eval of course\n" ]
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0004376285_python.txt
Q: Ternary (and more!) overload of __add__ in Python Context: As a personal learning project I've been working on a simple computer algebra system. I have a univariate polynomial class where the coefficents to the terms are stored as a dictionary. Operator overloading the sum of two polynomials A and B involves findi...
Ternary (and more!) overload of __add__ in Python
Context: As a personal learning project I've been working on a simple computer algebra system. I have a univariate polynomial class where the coefficents to the terms are stored as a dictionary. Operator overloading the sum of two polynomials A and B involves finding the like terms, adding them and making a new term fo...
[ "\nCould I write a special overload of\n the add function that would be called\n when there are multiple summations?\n\nIn short: No\nHere's the list of all the operators and the parameters: http://docs.python.org/reference/datamodel.html#emulating-numeric-types\nUsing a custom function is your only option\n", ...
[ 3, 2, 2, 1 ]
[]
[]
[ "lazy_evaluation", "python", "ternary_operator" ]
stackoverflow_0004372963_lazy_evaluation_python_ternary_operator.txt
Q: Getting AttributeError after invoking class function in Python Very simple class(source below) written in Python. After constructing obj1 = myClass(12) and calling class function obj1.printInfo(), I am getting an error - AttributeError: type object 'myClass' has no attribute 'arg1' What might be the source of the ...
Getting AttributeError after invoking class function in Python
Very simple class(source below) written in Python. After constructing obj1 = myClass(12) and calling class function obj1.printInfo(), I am getting an error - AttributeError: type object 'myClass' has no attribute 'arg1' What might be the source of the problem ?? class myClass(object): def __init__(self, arg1, arg...
[ "You want to use replace the body of printInfo(self) with:\ndef printInfo(self):\n print self.arg1, self.arg2\n\nThe use of self here is not to specify the scope, as it is sometimes used in Java (MyClass.this) or in PHP. In this function, self is actcually the object that contains arg1 and arg2. Python is very e...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004372920_python.txt
Q: Send alert (mail) if a process (python code) takes more than specified time to execute I need to send an alert (mail) if a process (python code) takes more than 5 minutes to execute, and also process should continue to run after sending alert !! I am using time.time() for timer, How can it be implemented ? A: I ...
Send alert (mail) if a process (python code) takes more than specified time to execute
I need to send an alert (mail) if a process (python code) takes more than 5 minutes to execute, and also process should continue to run after sending alert !! I am using time.time() for timer, How can it be implemented ?
[ "I don't know how to implement it using time.time(), but I suggest that you look at the signal module. First thing you need to do is to set up the handler via signal.signal(signal.SIGALRM, your_signal_handler_function), and then schedule the SIGALARM to be sent to your process in 300 seconds via signal.alarm(300).\...
[ 2 ]
[]
[]
[ "python", "python_datetime" ]
stackoverflow_0004376532_python_python_datetime.txt
Q: Python frustrated install library won't install I am on Windows XP. I have downloaded Python 2.7 as per the recommendations here. I clicked the .msi link and it installed fine. Now, I want to use beautifulsoup. I have downloaded version 3.2.0. I have no idea where to put it or how to install it. I put it i...
Python frustrated install library won't install
I am on Windows XP. I have downloaded Python 2.7 as per the recommendations here. I clicked the .msi link and it installed fine. Now, I want to use beautifulsoup. I have downloaded version 3.2.0. I have no idea where to put it or how to install it. I put it into a c:\temp folder and double clicked on setup.py a...
[ "Don't double click on setup.py . Open command and then navigate to the folder where setup.py is. Then run:\npython setup.py install\n\nAfter that, try import BeautifulSoup. If it works, all is well. \n", "The problem with Python is not about programming complexity, but distribution complexity.\nBetter if you use...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "installation", "python" ]
stackoverflow_0004376352_beautifulsoup_installation_python.txt
Q: How can I monitor Tkinter buttons when Python is busy? I am developing a Python 2.7.1 / Tkinter 8.4 app on Windows XP that checks several lines of input from a RS-232 port. However, if no input arrives it will sit in a loop for ever. I am trying to implement an ‘Abandon Test’ button on the GUI but because the mai...
How can I monitor Tkinter buttons when Python is busy?
I am developing a Python 2.7.1 / Tkinter 8.4 app on Windows XP that checks several lines of input from a RS-232 port. However, if no input arrives it will sit in a loop for ever. I am trying to implement an ‘Abandon Test’ button on the GUI but because the main thread is busy waiting for input it doesn’t appear to eve...
[ "Tk is single-threaded, so if the main thread is busy the GUI will freeze. One solution is to use a separate thread to do the reading, so when the read blocks your main thread can continue. When you get a line of input you can push it on a queue which is monitored by the main thread. \nThe other way is to figure ou...
[ 5 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004376870_python_tkinter.txt
Q: CGI/Python server push Is it possible to write a simple python script which handles real-time server pushing of data back to the client when data is available? A: "Yes, but": You can keep the connection between the client and server live; but this can take significantly more server resources. Edit: If you want t...
CGI/Python server push
Is it possible to write a simple python script which handles real-time server pushing of data back to the client when data is available?
[ "\"Yes, but\":\nYou can keep the connection between the client and server live; but this can take significantly more server resources.\nEdit: If you want to do this, see\n\nPython Comet Server\nHow to implement Comet server side with Python?\nThe latest recommendation for Comet in Python?\n\nYou can have the client...
[ 2 ]
[]
[]
[ "apache", "cgi", "javascript", "jquery", "python" ]
stackoverflow_0004377038_apache_cgi_javascript_jquery_python.txt
Q: Dynamic function building in Python I need to create a function for an arbitrary number of peaks to pass to a least square fitting routine. For each peak there is an extra term in the function, i.e. One term with a value at 50 returns a function: f(p, x) = p[0]*50 Two terms with values at 50, 60 returns a function...
Dynamic function building in Python
I need to create a function for an arbitrary number of peaks to pass to a least square fitting routine. For each peak there is an extra term in the function, i.e. One term with a value at 50 returns a function: f(p, x) = p[0]*50 Two terms with values at 50, 60 returns a function: f(p, x) = p[0]*50 + p[1]*60*x Three ter...
[ "How about:\ndef foo(vals):\n def f(p,x):\n result=0\n for i,(av,ap) in enumerate(zip(vals,p)):\n result+=av*ap*(x**i)\n return result\n return f\n\nprint(foo([50])([2],3))\n# f(p,x)=50*2\n# 100\nprint(foo([50,60])([2,3],4))\n# f(p,x)=50*2+60*3*x\n# 820\n\n", "Closures don't ...
[ 2, 1, 1, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0004376943_function_python.txt
Q: Encoding error while deserializing a json object from Google As an exercise I built a little script that query Google Suggest JSON API. The code is quite simple: query = 'a' url = "http://clients1.google.co.jp/complete/search?hl=ja&q=%s&json=t" %query response = urllib.urlopen(url) result = json.load(response) Uni...
Encoding error while deserializing a json object from Google
As an exercise I built a little script that query Google Suggest JSON API. The code is quite simple: query = 'a' url = "http://clients1.google.co.jp/complete/search?hl=ja&q=%s&json=t" %query response = urllib.urlopen(url) result = json.load(response) UnicodeDecodeError: 'utf8' codec can't decode byte 0x83 in position 0...
[ "The response header (print response.header) contains the following information:\nContent-Type: text/javascript; charset=Shift_JIS\n\nNote the charset.\nIf you specify this encoding in json.load it will work:\nresult = json.load(response, encoding='shift_jis')\n\n", "Regardless of what the spec says, the string \...
[ 3, 0 ]
[]
[]
[ "encoding", "json", "python" ]
stackoverflow_0004377260_encoding_json_python.txt
Q: What should C return to Python call()? Continuing on my previous question at Executing a C program in python?; what returns one from C to get usable data in Python?? Currently my program returns this: int main (int argc, char *argv[]) { spa_data spa; //declare the SPA structure int result; float min, ...
What should C return to Python call()?
Continuing on my previous question at Executing a C program in python?; what returns one from C to get usable data in Python?? Currently my program returns this: int main (int argc, char *argv[]) { spa_data spa; //declare the SPA structure int result; float min, sec; //enter required input values into...
[ "The simplest way to return data to Python would be to print it out in some sensible format. The one you've got there decent, but a simple CSV would be a bit easier.\nThen you'll use subprocess.Popen:\np = subprocess.Popen([\"./spa\", \"args\", \"to\", \"spa\"], stdout=subprocess.PIPE)\n(stdout, stderr) = p.communi...
[ 2 ]
[]
[]
[ "c", "python" ]
stackoverflow_0004378077_c_python.txt
Q: How to remove the 1px border under a toolbar? I have a toolbar, which is next to a slider (screenshot: http://i54.tinypic.com/w2n6ag.jpg) and wxPython automatically puts a tiny 1px border under the [Play/Pause/Stop | Previous/Next] buttons. This does not look nice at all so is it possible to remove it/set it to 0...
How to remove the 1px border under a toolbar?
I have a toolbar, which is next to a slider (screenshot: http://i54.tinypic.com/w2n6ag.jpg) and wxPython automatically puts a tiny 1px border under the [Play/Pause/Stop | Previous/Next] buttons. This does not look nice at all so is it possible to remove it/set it to 0px? Thank you very much. Here is part of the my co...
[ "Just in case anyone else stumbles their way here looking to fix the same problem: try adding wx.TB_NODIVIDER to your style, e.g. \nstyle=wx.TB_HORIZONTAL | wx.NO_BORDER | wx.TB_FLAT | wx.TB_NODIVIDER \nRemoved the ugly line for me in XP at any rate.\n", "I didn't know toolbars added lines. It must be platform s...
[ 4, 1 ]
[]
[]
[ "border", "python", "toolbar", "wxpython" ]
stackoverflow_0003756351_border_python_toolbar_wxpython.txt
Q: What to do with "The input line is too long" error message? I am trying to use os.system() to call another program that takes an input and an output file. The command I use is ~250 characters due to the long folder names. When I try to call the command, I'm getting an error: The input line is too long. I'm guessi...
What to do with "The input line is too long" error message?
I am trying to use os.system() to call another program that takes an input and an output file. The command I use is ~250 characters due to the long folder names. When I try to call the command, I'm getting an error: The input line is too long. I'm guessing there's a 255 character limit (its built using a C system call...
[ "Even it's a good idea to use subprocess.Popen(), this does not solve the issue.\nYour problem is not the 255 characters limit, this was true on DOS times, later increased to 2048 for Windows NT/2000, and increased again to 8192 for Windows XP+.\nThe real solution is to workaround a very old bug in Windows APIs: _p...
[ 20, 6, 2, 1, 1, 1 ]
[]
[]
[ "command_line", "python", "windows_console" ]
stackoverflow_0000682799_command_line_python_windows_console.txt
Q: twisted ssh -X option (x11 forwarding) is it possible to use Twisted with a ssh -X like option, that is, passing the x11 option to the ssh protocol ? Thanks, Regards, A: Nope.
twisted ssh -X option (x11 forwarding)
is it possible to use Twisted with a ssh -X like option, that is, passing the x11 option to the ssh protocol ? Thanks, Regards,
[ "Nope.\n" ]
[ 3 ]
[]
[]
[ "python", "ssh", "twisted", "x11" ]
stackoverflow_0004377250_python_ssh_twisted_x11.txt
Q: Python, how to sort dictionary by keys, when keys are floating point numbers in scientific format? I need to sort a Python dictionary by keys, when keys are floating point numbers in scientific format. Example: a={'1.12e+3':1,'1.10e+3':5,'1.19e+3':7,...} I need to maintain key-value links unchanged. What is the...
Python, how to sort dictionary by keys, when keys are floating point numbers in scientific format?
I need to sort a Python dictionary by keys, when keys are floating point numbers in scientific format. Example: a={'1.12e+3':1,'1.10e+3':5,'1.19e+3':7,...} I need to maintain key-value links unchanged. What is the simplest way to do this?
[ "Probably by simply converting back to a number:\nsorted(a, key = lambda x: float(x))\n['1.10e+3', '1.12e+3', '1.19e+3']\n\nThis just gives you a sorted copy of the keys. I'm not sure if you can write to a dictionary and change its list of keys (the list returned by keys() on the dictionary) in-place. Sounds a bit ...
[ 8, 3 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0004378428_dictionary_python_sorting.txt
Q: File buffer flushing and closing in Python with variable re-assign Had an interesting experience with Python's file buffering and wanted to know that I understand it correctly. Given [Python 2.7 shell] ... model = (really big Numpy model) f = open('file.out','w') pickle.dump(model, f) (pickle.dump() finishes while...
File buffer flushing and closing in Python with variable re-assign
Had an interesting experience with Python's file buffering and wanted to know that I understand it correctly. Given [Python 2.7 shell] ... model = (really big Numpy model) f = open('file.out','w') pickle.dump(model, f) (pickle.dump() finishes while I'm doing other things) [Bash shell] $ ls -l -rw-r--r-- 1 john staff...
[ "As long as your computer does not crash, you won't lose data by not closing a file. Python does indeed close files if the corresponding file objects are garbage collected. In the case you described, the name f was the only reference to the file, so it was closed when you used the name for something else.\nNote t...
[ 2, 0 ]
[]
[]
[ "buffer", "garbage_collection", "python" ]
stackoverflow_0004378464_buffer_garbage_collection_python.txt
Q: Python is not existing when ran from System Scheduler I have made a batch script which runs a Python application. This batch script is triggered by a program called System Scheduler, but when the program runs the batch script, it says that Python is not exisiting. When I run my batch script manually, I get no erro...
Python is not existing when ran from System Scheduler
I have made a batch script which runs a Python application. This batch script is triggered by a program called System Scheduler, but when the program runs the batch script, it says that Python is not exisiting. When I run my batch script manually, I get no error. Can anyone explain this or come up with a solution?
[ "Probably the $PATH is not set properly when called from scheduler. Try changing the command called from \npython yourscript.py\n\nto\n/usr/bin/python yourscript.py\n\n(Substitute the actual path to python on your system, which you can find with:\n$ which python\n\n", "Check the user context that System Scheduler...
[ 2, 1 ]
[]
[]
[ "python", "scheduler", "system" ]
stackoverflow_0004378653_python_scheduler_system.txt
Q: How can I profile a multithreaded program? I have a program that is performing waaaay under par, and I would like to profile it. However, it is multithreaded, so I can't seem to find a good way to profile this thing. Any advice? I've tried yappi, but it segfaults on OS X :( EDIT: This is in python, sorry for putt...
How can I profile a multithreaded program?
I have a program that is performing waaaay under par, and I would like to profile it. However, it is multithreaded, so I can't seem to find a good way to profile this thing. Any advice? I've tried yappi, but it segfaults on OS X :( EDIT: This is in python, sorry for putting it under profiling...
[ "Depending on how far you've come in your troubleshooting, there are some tools that might point you in the right direction. \n\n\"top\" is a helpful start to show you if your problem is burning CPU time or simply waiting for stuff.\n\"dtruss -c\" can show you where you spend time and what system calls takes most o...
[ 2, 2 ]
[]
[]
[ "multithreading", "performance", "profile", "python" ]
stackoverflow_0004373585_multithreading_performance_profile_python.txt
Q: Setting a default value for a field in a formset in Django In a formset in Django, how do we set a default value for a field which needs a value from the http session? Since a session is required to get the value, we cannot set a default value in the model class itself. And I am not able to understand how to expli...
Setting a default value for a field in a formset in Django
In a formset in Django, how do we set a default value for a field which needs a value from the http session? Since a session is required to get the value, we cannot set a default value in the model class itself. And I am not able to understand how to explicitly set the value in each form in the formset before saving in...
[ "The idiom to instance a formset with initial data is:\ndata = {\n 'form-TOTAL_FORMS': u'2',\n 'form-INITIAL_FORMS': u'0',\n 'form-MAX_NUM_FORMS': u'',\n 'form-0-updated_by': u'user',\n 'form-1-updated_by': u'user',\n}\n\nformset = LineItemsInlineFormSet(data)\n\nUpdate:\nAs Jonny Buchanan noted...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004378667_django_python.txt
Q: Download Manager: How to re-construct chunks fetched by multiple connections so i am developing my own download manager for educational purpose. I have multiple connections/threads downloading a file, each connection works on a particular range of the file. Now after they have all fetched their chunks, i dont exac...
Download Manager: How to re-construct chunks fetched by multiple connections
so i am developing my own download manager for educational purpose. I have multiple connections/threads downloading a file, each connection works on a particular range of the file. Now after they have all fetched their chunks, i dont exact know how to i bring this chunks together to re-make the original file. What i ...
[ "You need to write chunks it different temporary files and then join them in the original order. If you open one file for all the threads, you should make the access to it sequential to preserve to correct order of data, which discards thread usage since a thread should wait for the previous one. BTW, you should op...
[ 2, 1 ]
[]
[]
[ "chunks", "connection", "python", "urllib2" ]
stackoverflow_0004379160_chunks_connection_python_urllib2.txt