content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How do I send/get a JSON Object with Django?
I know how to use the JQuery ajax feature to call the "url view" of Django.
import simplejson as json
def the_view(request):
fruits = {'color':5, 'type': 22}
jfruit = json.dump(fruits)
return render_to_response( THE JSON OBJECT!!! ...how? )
A:
return HttpResp... | How do I send/get a JSON Object with Django? | I know how to use the JQuery ajax feature to call the "url view" of Django.
import simplejson as json
def the_view(request):
fruits = {'color':5, 'type': 22}
jfruit = json.dump(fruits)
return render_to_response( THE JSON OBJECT!!! ...how? )
| [
"return HttpResponse(simplejson.dumps(mydictionary), mimetype=\"application/json\")\nsee b-list\n",
"Or shorter: \ndownload http://bitbucket.org/offline/django-annoying/ and write:\n@ajax_request \ndef the_view(request):\n return {'color':5, 'type': 22}\n\nThere are a few such nice tiny things in django-annoyi... | [
5,
3
] | [] | [] | [
"django",
"json",
"python"
] | stackoverflow_0002023577_django_json_python.txt |
Q:
wrapping cmd.exe with subprocess
I try to wrap cmd.exe under windows with the following program but it doesn't work , it seems to wait for something and doesn't display anything. Any idea what is wrong here ?
import subprocess
process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE,stdout=subproc... | wrapping cmd.exe with subprocess | I try to wrap cmd.exe under windows with the following program but it doesn't work , it seems to wait for something and doesn't display anything. Any idea what is wrong here ?
import subprocess
process = subprocess.Popen('cmd.exe', shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)
process.stdin.... | [
"Usually when trying to call command prompt with an actual command, it is simpler to just call it with the \"/k\" parameter rather than passing commands in via stdin. That is, just call \"cmd.exe /k dir\". For example, \nfrom os import *\na = popen(\"cmd /k dir\")\nprint (a.read())\n\nThe code below does the same... | [
5,
5,
2
] | [] | [] | [
"python",
"subprocess",
"windows"
] | stackoverflow_0002028207_python_subprocess_windows.txt |
Q:
Running Different Django Versions But Sharing Authentication
Brand new to django. We have a legacy django project using django 0.96x that does authentication, ldap, etc., and it's pretty involved so we don't want to rewrite that code.
We want to add a forum solution (off the shelf) but all of the ones I've seen so... | Running Different Django Versions But Sharing Authentication | Brand new to django. We have a legacy django project using django 0.96x that does authentication, ldap, etc., and it's pretty involved so we don't want to rewrite that code.
We want to add a forum solution (off the shelf) but all of the ones I've seen so far require django 1.x
I'm trying to figure out how to get this ... | [
"It's possible, but it may be pretty painful to do option #3.\nHow about Option 4: bite the bullet and upgrade to Django 1.1.1. I did this with a couple of 0.97pre sites and it took less time than I thought it would. The biggest pain was dealing with admin stuff. Instead of going with separate admin.py files, we si... | [
1,
0,
0
] | [] | [] | [
"django",
"mod_python",
"python"
] | stackoverflow_0002022178_django_mod_python_python.txt |
Q:
adding lighting effects to an image in python
I want to specify a light source at a particular location in an image using Python.
PIL's ImageEnhance module does provide a way to briten an image. but I want to have a control over light source placement to acheieve special effects. Does anyone know how to do this?
... | adding lighting effects to an image in python | I want to specify a light source at a particular location in an image using Python.
PIL's ImageEnhance module does provide a way to briten an image. but I want to have a control over light source placement to acheieve special effects. Does anyone know how to do this?
thank you!
| [
"So, the bad news is that PIL can't do that. I trhow a couple of ideas bellow, unfortunatelly none of which is straightforward.\nGIMP (GNU Image Manipulation Program) does have an awesome \"ligthning effects\" plug-in,\nGIMP is scriptable in Python, and it is possible to call teh plug-in paramtrically. \nThe drawba... | [
1
] | [] | [] | [
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0002028809_image_processing_python_python_imaging_library.txt |
Q:
Creating an image editing application in Python
I need a tile/sprite editor kind of like Pixen, but I couldn't find one for Windows so I thought it might be a good exercise for me to try and put one together. I use Python, so are there any libraries out there that are suited to the task of putting together a simpl... | Creating an image editing application in Python | I need a tile/sprite editor kind of like Pixen, but I couldn't find one for Windows so I thought it might be a good exercise for me to try and put one together. I use Python, so are there any libraries out there that are suited to the task of putting together a simple tile/sprite editor?
| [
"You just need a gui toolkit (gtk, qt, wx) a image library (PIL) and 500 hours of free time ...\n",
"Have you looked at the Python Imaging Library (PIL)? \n",
"So, the fact is that creating a complex app with a nice UI takes time - I am just expanding a little bit on the answer by THC4k. \nPIL, at least PIL al... | [
6,
3,
2,
1
] | [] | [] | [
"image_editor",
"python"
] | stackoverflow_0002028025_image_editor_python.txt |
Q:
Drag and drop ordering of formset with extra entries
I have been looking for a way to allow the user to easily change the order of entries in a formset. I found a StackOverflow question that addresses this subject, with the accepted answer referencing a Django Snippet that uses a JQuery tool to allow drag 'n drop... | Drag and drop ordering of formset with extra entries | I have been looking for a way to allow the user to easily change the order of entries in a formset. I found a StackOverflow question that addresses this subject, with the accepted answer referencing a Django Snippet that uses a JQuery tool to allow drag 'n drop of the entries. This is nifty and cool, but I have a pro... | [
"I found my own solution. The snippet was setting the order for every row that had a non-empty primary key value. But the extra rows have an empty primary key, and I believe they have to stay empty for Django to know that they are to be inserted instead of updated. I modified the function to check for the other ... | [
3,
1
] | [] | [] | [
"django",
"javascript",
"jquery",
"python"
] | stackoverflow_0001993826_django_javascript_jquery_python.txt |
Q:
How do I search through regex matches in Python?
I need to try a string against multiple (exclusive - meaning a string that matches one of them can't match any of the other) regexes, and execute a different piece of code depending on which one it matches. What I have currently is:
m = firstre.match(str)
if m:
... | How do I search through regex matches in Python? | I need to try a string against multiple (exclusive - meaning a string that matches one of them can't match any of the other) regexes, and execute a different piece of code depending on which one it matches. What I have currently is:
m = firstre.match(str)
if m:
# Do something
m = secondre.match(str)
if m:
# Do... | [
"def doit( s ):\n\n # with some side-effect on a\n a = [] \n\n def f1( s, m ):\n a.append( 1 )\n print 'f1', a, s, m\n\n def f2( s, m ):\n a.append( 2 )\n print 'f2', a, s, m\n\n def f3( s, m ):\n a.append( 3 )\n print 'f3', a, s, m\n\n re1 = re.compile( '... | [
4,
3,
3,
1,
1,
0,
0
] | [] | [] | [
"python",
"regex",
"switch_statement"
] | stackoverflow_0002028164_python_regex_switch_statement.txt |
Q:
Python data structures, dictionary?
I hope somebody can help. I am using Python and I would like to be able to do the following.
I have a set of objects (shapes for example) and a series of commands to act on these objects. The commands have the a format of a command string followed by a variable number of paramet... | Python data structures, dictionary? | I hope somebody can help. I am using Python and I would like to be able to do the following.
I have a set of objects (shapes for example) and a series of commands to act on these objects. The commands have the a format of a command string followed by a variable number of parameters which can be strings or integers
For ... | [
"You might be better off creating your own class:\nclass Shape(object):\n def __init__(self):\n self.shape = \"rectangle\"\n self.color = \"green\"\n self.fillstyle = \"hatch\"\n # etc\n\n def ChangeColor(self, color):\n self.color = color\n\n # etc\n\n",
"dicts are for... | [
3,
2,
1,
0,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0002028723_dictionary_python.txt |
Q:
Writing a LaTeX document with Python code snippets
I am using LaTeX to write a document about Python. This document will contain code snippets (examples).
I could use the verbatim environment, but before I embark onto it, I'd like to know if you are aware of any LaTeX style file which provides an environment for P... | Writing a LaTeX document with Python code snippets | I am using LaTeX to write a document about Python. This document will contain code snippets (examples).
I could use the verbatim environment, but before I embark onto it, I'd like to know if you are aware of any LaTeX style file which provides an environment for Python code. Syntax highlight would be a plus.
Thanks.
Ed... | [
"Take a look at this question Source code highlighting in LaTeX for more information.\nYou should also look at the pygments program for source code highlighting. \nI personally use Emacs org-mode with #+BEGIN_SRC python and let htmlize.el take care of the highlighting during export. You can see a sample here (This ... | [
5,
2,
2
] | [] | [] | [
"latex",
"python"
] | stackoverflow_0002029957_latex_python.txt |
Q:
python - good places to check out example prog / code online?
there is a year old, similar question - but in case there have been changes afoot:
i'm an intermediate c++ programmer just starting out on python, post some online tuts etc i can do some basic pythoneering, but was wondering if there are good places i c... | python - good places to check out example prog / code online? | there is a year old, similar question - but in case there have been changes afoot:
i'm an intermediate c++ programmer just starting out on python, post some online tuts etc i can do some basic pythoneering, but was wondering if there are good places i can look online for simple(ish) --pref console based-- code that i c... | [
"The standard library is an excellent place to the start. It's maintained by the core python team and is of high quality with a lot of interesting idioms. I'd recommend the newer modules since they don't have much backward compatibility cruft and are more representative of the language as it is now. The older ones ... | [
4,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002029606_python.txt |
Q:
Project Euler #101 - how to work around numpy polynomial overflow?
Project Euler #101
I just started learning Numpy and it so far looks pretty straightforward to me.
One thing I ran into is that when I evaluate the polynomial, the result is a int32, so an overflow would occur.
u = numpy.poly1d([1, -1, 1, -1, 1, -1... | Project Euler #101 - how to work around numpy polynomial overflow? | Project Euler #101
I just started learning Numpy and it so far looks pretty straightforward to me.
One thing I ran into is that when I evaluate the polynomial, the result is a int32, so an overflow would occur.
u = numpy.poly1d([1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1])
for i in xrange(1, 11):
print(i, u(i))
The resu... | [
"It wasn't the scaling by 100 that helped, but the fact that the numbers given were floats instead of ints, and thus had a higher range. Due to the floating-point calculations, there are some inaccuracies introduced to the calculations as you have seen.\nYou can specify the type manually like this:\nu = numpy.poly1... | [
4,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0002030422_numpy_python.txt |
Q:
How do I get Sphinx to test code embedded in documentation?
If this code is a blockquote in my documentation, what do I need to do to make Sphinx run it when the documentation is generated? I tried adding
.. testcode::
import datetime
def today():
return datetime.datetime.now().date()
if True:... | How do I get Sphinx to test code embedded in documentation? | If this code is a blockquote in my documentation, what do I need to do to make Sphinx run it when the documentation is generated? I tried adding
.. testcode::
import datetime
def today():
return datetime.datetime.now().date()
if True:
today()
to one of the .rst sources and the Sphinx docte... | [
"The testcode directive needs a matching testoutput directive.\nHere's the example from the documentation.\n.. testcode::\n\n print 'Output text.'\n\n.. testoutput::\n :hide:\n :options: -ELLIPSIS, +NORMALIZE_WHITESPACE\n\n Output text.\n\n"
] | [
4
] | [] | [] | [
"python",
"python_sphinx"
] | stackoverflow_0002021671_python_python_sphinx.txt |
Q:
Bazaar VCS under IronPython?
Has anyone successfully executed the source control system Bazaar in IronPython?
A:
Yes, Bazaar is pure-python with optional extensions and will run on IronPython. There are a few caveats though. Firstly some changes are needed to Bazaar that haven't yet been merged with the main bra... | Bazaar VCS under IronPython? | Has anyone successfully executed the source control system Bazaar in IronPython?
| [
"Yes, Bazaar is pure-python with optional extensions and will run on IronPython. There are a few caveats though. Firstly some changes are needed to Bazaar that haven't yet been merged with the main branch. Secondly, IronPython's slow startup time makes it unsuitable for general bzr usage, and there are are some out... | [
2,
1
] | [] | [] | [
"bazaar",
"dynamic_language_runtime",
"ironpython",
"python"
] | stackoverflow_0001909057_bazaar_dynamic_language_runtime_ironpython_python.txt |
Q:
Python - automating MySQL index: passing parameter
I have a function with a new improved version of the code for automatic table indexing:
def update_tableIndex(self,tableName):
getIndexMySQLQuery = """SELECT numberID
FROM %s;""" % (tableName,)
updateIndexMySQLQuery = """UPDATE %s
SET numberID=%s... | Python - automating MySQL index: passing parameter | I have a function with a new improved version of the code for automatic table indexing:
def update_tableIndex(self,tableName):
getIndexMySQLQuery = """SELECT numberID
FROM %s;""" % (tableName,)
updateIndexMySQLQuery = """UPDATE %s
SET numberID=%s WHERE numberID=%s;""" % (tableName,)
updateIndex=1... | [
"Second one doesn't work, because you are using three placeholders inside the query string and provide only one variable for interpolation.\nupdateIndexMySQLQuery = \"\"\"UPDATE %s \nSET numberID=%%s WHERE numberID=%%s;\"\"\" % (tableName,)\n\nThis way the string formatting mechanism doesn't expect you to provide 3... | [
2,
0,
0
] | [] | [] | [
"automation",
"mysql",
"parameters",
"python"
] | stackoverflow_0002031401_automation_mysql_parameters_python.txt |
Q:
Python logging over multiple files
I've read through the logging module documentation and whilst I may have missed something obvious, the code I've got doesn't appear to be working as intended. I'm using Python 2.6.4.
My program consists of several different python files, from which I want to send logging messages... | Python logging over multiple files | I've read through the logging module documentation and whilst I may have missed something obvious, the code I've got doesn't appear to be working as intended. I'm using Python 2.6.4.
My program consists of several different python files, from which I want to send logging messages to a text file and, potentially, the sc... | [
"Are you sure no other logging setup is being done in anything you import.\nThe incorrect output in your console logs look like the default configuration for a logger, so something else may be setting that up. \nRunning this quick test script:\nimport logging\nfrom logging.handlers import RotatingFileHandler\nimpor... | [
12
] | [] | [] | [
"error_logging",
"logging",
"python"
] | stackoverflow_0002031394_error_logging_logging_python.txt |
Q:
Optimize Game-of-Life iteration over 80x60 RGB pixel array
Okay, so I've got a piece of Python code which really needs optimizing.
It's a Game-of-Life iteration over a small (80x60-pixel) image and extracts the RGB values from it.
currently using nested for-loops; I'd rather swap out those for loops for the faste... | Optimize Game-of-Life iteration over 80x60 RGB pixel array | Okay, so I've got a piece of Python code which really needs optimizing.
It's a Game-of-Life iteration over a small (80x60-pixel) image and extracts the RGB values from it.
currently using nested for-loops; I'd rather swap out those for loops for the faster map() c function, but if I do that I can't figure out how I ca... | [
"What's making your code slow is probably not the loops, they are incredibly fast.\nWhat slows done your code are the number of function calls. For example\npixelR = get_at((x,y))[0]\npixelG = get_at((x,y))[1]\npixelB = get_at((x,y))[2]\n\nis a lot slower than (about 3 times I guess)\nr, g, b, a = get_at((x,y))\n\n... | [
3,
2,
1
] | [] | [] | [
"arrays",
"conways_game_of_life",
"optimization",
"pixels",
"python"
] | stackoverflow_0002031216_arrays_conways_game_of_life_optimization_pixels_python.txt |
Q:
Debugging Django Forms validation errors
One of my forms fails on form.is_valid()
First time I debug a Django form so I am not too sure where to look
forms.py
class ImageForm(forms.ModelForm):
def __init__(self,user,*args,**kwargs):
super(ImageForm,self ).__init__(*args,**kwargs) # populates the form
class Me... | Debugging Django Forms validation errors | One of my forms fails on form.is_valid()
First time I debug a Django form so I am not too sure where to look
forms.py
class ImageForm(forms.ModelForm):
def __init__(self,user,*args,**kwargs):
super(ImageForm,self ).__init__(*args,**kwargs) # populates the form
class Meta:
model = KMSImageP
fields = ('name'... | [
"You really should learn how to use debugger with Django and it's built in server- it has saved me lot's of print/dir expressions and endless edit-run-observe output-edit iterations.\nThe most basic way to debug python applications is by using pdb\nIt's as easy as dropping in these two lines of code:\nimport pdb\np... | [
5
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0002030896_django_django_forms_python.txt |
Q:
Any way to set request headers when doing a request using urllib in Python 2.x?
I am trying to make an HTTP request in Python 2.6.4, using the urllib module. Is there any way to set the request headers?
I am sure that this is possible using urllib2, but I would prefer to use urllib since it seems simpler.
A:
The... | Any way to set request headers when doing a request using urllib in Python 2.x? | I am trying to make an HTTP request in Python 2.6.4, using the urllib module. Is there any way to set the request headers?
I am sure that this is possible using urllib2, but I would prefer to use urllib since it seems simpler.
| [
"There isn't any way to do that, which is precisely the reason urllib is deprecated in favour of urllib2. So just use urllib2 rather than writing new code to a deprecated interface.\n",
"I don't think so, but urllib2 can. Check out the documentation of urllib2.Request.\n",
"You could actually overwrite methods... | [
2,
1,
1
] | [] | [] | [
"http",
"python",
"python_2.6",
"python_2.x",
"urllib"
] | stackoverflow_0002031745_http_python_python_2.6_python_2.x_urllib.txt |
Q:
how can i use django.utils.safestring.py
from django.utils.safestring import *
print SafeString('\u3042')
print '\u3042'
\u3042
\u3042
who can give me a better example.
thanks
A:
An instance of django.utils.safestring.SafeString is a string which has already been vetted or escaped, so it contains no character... | how can i use django.utils.safestring.py | from django.utils.safestring import *
print SafeString('\u3042')
print '\u3042'
\u3042
\u3042
who can give me a better example.
thanks
| [
"An instance of django.utils.safestring.SafeString is a string which has already been vetted or escaped, so it contains no characters that could give HTML a parsing problem ('<', '>', '&'). See the docs.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002031788_django_python.txt |
Q:
How do I sort this list?
I have a list of lists.
List<List<T>> li = {
{a1,a2,a3 ... aN},
{b1,b2,b3 ... bN},
...
};
double foo(List<T> list)
{
// do something
// e.g {1,2,3}
// it = 1 + 2 + 3
return it;
}
Now I want to sort li in such a way that higher the foo(x) for a x higher it shou... | How do I sort this list? | I have a list of lists.
List<List<T>> li = {
{a1,a2,a3 ... aN},
{b1,b2,b3 ... bN},
...
};
double foo(List<T> list)
{
// do something
// e.g {1,2,3}
// it = 1 + 2 + 3
return it;
}
Now I want to sort li in such a way that higher the foo(x) for a x higher it should appear in a sorted list.
Wh... | [
"With a little bit of LINQ:\nvar q = from el in li\n orderby foo(el)\n select el;\nli = q.ToList();\n\n",
"The Haskell solution is particularly elegant with the on combinator from Data.Function.\nimport Data.Function (on)\nimport Data.List (sortBy)\n\nlists = [ [ 5, 6, 8 ]\n , [ 1, 2, 3 ]\n ... | [
10,
10,
5,
2,
2,
1,
1,
1,
1,
0,
0
] | [] | [] | [
"c#",
"haskell",
"python",
"ruby",
"sorting"
] | stackoverflow_0002019951_c#_haskell_python_ruby_sorting.txt |
Q:
Is there a python hamcrest matcher library for performing XML document matching?
I'm interested in both xpath matching and full document comparisons:
assert_that(mydoc, hasTextAtXPath('/foo/bar', 'text'))
assert_that(mydoc, matchesStructurally('<some_xml/>'))
Does any matcher library exist for this? If not, wha... | Is there a python hamcrest matcher library for performing XML document matching? | I'm interested in both xpath matching and full document comparisons:
assert_that(mydoc, hasTextAtXPath('/foo/bar', 'text'))
assert_that(mydoc, matchesStructurally('<some_xml/>'))
Does any matcher library exist for this? If not, what is the best place to start with for this type of comparison, so that I can write one... | [
"lxml has XPath matching: http://codespeak.net/lxml/\n",
"There is a Python version of Hamcrest. It does not currently provide XML matchers. I'd be happy to work on some if you define what you need.\n"
] | [
0,
0
] | [] | [] | [
"hamcrest",
"python",
"unit_testing",
"xml",
"xpath"
] | stackoverflow_0001941431_hamcrest_python_unit_testing_xml_xpath.txt |
Q:
Scripting Python for Linux commands
I have a question. I have been really trying to learn Python. For a project, I want to make an ncurses GUI for my backup server. My backup server runs rdiff-backup, and I want to have the ncurses take in variable names and plug them into my script. I have been trying to do ... | Scripting Python for Linux commands | I have a question. I have been really trying to learn Python. For a project, I want to make an ncurses GUI for my backup server. My backup server runs rdiff-backup, and I want to have the ncurses take in variable names and plug them into my script. I have been trying to do a lot of reading so I don't ask dumb ques... | [
"you can use format specifiers\ndef runScript():\n script = \"%s %s %s@%s %s::%s %s\" %(rdiff,rdiffVerbosity,rdiffStatistics,clientName,clientHost,clientDir,serverDir) \n os.system(script)\n\nor say your rdiffArgs is already in a list\nrdiffArgs = [rdiffVerbosity,rdiffStatistics,clientName,clientHost,clien... | [
5,
5,
3
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0002032228_linux_python.txt |
Q:
Detect if a process is already running and collaborate with it
I'm trying to create a program that starts a process pool of, say, 5 processes, performs some operation, and then quits, but leaves the 5 processes open. Later the user can run the program again, and instead of it starting new processes it uses the ex... | Detect if a process is already running and collaborate with it | I'm trying to create a program that starts a process pool of, say, 5 processes, performs some operation, and then quits, but leaves the 5 processes open. Later the user can run the program again, and instead of it starting new processes it uses the existing 5. Basically it's a producer-consumer model where:
The numb... | [
"There are a couple of common ways to do your item #1 (detecting running processes), but to use them would first require that you slightly tweak your mental picture of how these background processes are started by the first invocation of the program.\nThink of the first program not as starting the five processes an... | [
2,
1,
1
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0002031121_multiprocessing_python.txt |
Q:
is something wrong with Python Shell (Google App)?
Python Shell - shell.appspot.com is acting weird? or am I missing something?
Google App Engine/1.3.0
Python 2.5.2 (r252:60911, Apr 7 2009, 17:42:26)
[GCC 4.1.0]
>>> mycolors = ['red','green','blue']
>>> mycolors.append('black')
>>> print mycolors
['red', 'green... | is something wrong with Python Shell (Google App)? | Python Shell - shell.appspot.com is acting weird? or am I missing something?
Google App Engine/1.3.0
Python 2.5.2 (r252:60911, Apr 7 2009, 17:42:26)
[GCC 4.1.0]
>>> mycolors = ['red','green','blue']
>>> mycolors.append('black')
>>> print mycolors
['red', 'green', 'blue']
But the below result is expected
['red', 'gr... | [
"Short Answer\nThat is a known bug. Short answer:\n\nInclude everything on one line: mycolors.append('black'); print mycolors\nUse my free software tool, App Engine Console. My code is derived from the shell and I have fixed this bug.\n\nLong answer\nThe bug involves the way that state is stored in between every co... | [
4,
1
] | [] | [] | [
"google_app_engine",
"python",
"shell"
] | stackoverflow_0002027658_google_app_engine_python_shell.txt |
Q:
Interactive Python GUI
Python have been really bumpy for me, because the last time I created a GUI client, the client seems to hang when spawning a process, calling a shell script, and calling outside application.
This have been my major problem with Python since then, and now I'm in a new project, can someone giv... | Interactive Python GUI | Python have been really bumpy for me, because the last time I created a GUI client, the client seems to hang when spawning a process, calling a shell script, and calling outside application.
This have been my major problem with Python since then, and now I'm in a new project, can someone give me pointers, and a word of... | [
"Simplest (not necessarily \"best\" in an abstract sense): spawn the subprocess in a separate thread, communicating results back to the main thread via a Queue.Queue instance -- the main thread must periodically check that queue to see if the results have arrived yet, but periodic polling isn't hard to arrange in a... | [
4,
2
] | [] | [] | [
"interactive",
"pygtk",
"python",
"spawn",
"user_interface"
] | stackoverflow_0002032617_interactive_pygtk_python_spawn_user_interface.txt |
Q:
Porting python app to silverlight or flash
I guess that title is self-explanatory. Is there any such effort been made?
Some more info:
it's client application (gui intensive)
By porting I was thinking of cross-compiling.
A:
i havent done this but it shouldnt be to difficult to port python o silverlight because ... | Porting python app to silverlight or flash | I guess that title is self-explanatory. Is there any such effort been made?
Some more info:
it's client application (gui intensive)
By porting I was thinking of cross-compiling.
| [
"i havent done this but it shouldnt be to difficult to port python o silverlight because you should be able to use IronPython and add clr references to your python code to start using the silverlight assemblies.\n",
"Between the two, porting to Silverlight is going to be much easier. You can target IronPython an... | [
2,
2
] | [] | [] | [
"flash",
"python",
"silverlight"
] | stackoverflow_0002032845_flash_python_silverlight.txt |
Q:
Concatenation Operator + or ,
var1 = 'abc'
var2 = 'xyz'
print('literal' + var1 + var2) # literalabcxyz
print('literal', var1, var2) # literal abc xyz
... except for automatic spaces with ',' whats the difference between the two? Which to use normally, also which is the fastest?
Thanks
A:
(You're using Python 3... | Concatenation Operator + or , | var1 = 'abc'
var2 = 'xyz'
print('literal' + var1 + var2) # literalabcxyz
print('literal', var1, var2) # literal abc xyz
... except for automatic spaces with ',' whats the difference between the two? Which to use normally, also which is the fastest?
Thanks
| [
"(You're using Python 3.x, where print is a function—in 2.x, print is a statement. It's a good idea to mention the major Python version—2.x or 3.x—especially when asking for help, because currently most people reasonably assume 2.x unless it's stated.)\nThe first, print('literal' + var1 + var2), evaluates an expre... | [
26,
6,
1
] | [] | [] | [
"concatenation",
"python",
"python_3.x"
] | stackoverflow_0002033242_concatenation_python_python_3.x.txt |
Q:
In what circumstances should you serialize data? When should you not?
I'm aware that serializing is used to
convert data types into a storable
format, for purposes such as caching.
What I'm more specifically asking is, what are the circumstances in which you should actually decide to store data ( using serial... | In what circumstances should you serialize data? When should you not? |
I'm aware that serializing is used to
convert data types into a storable
format, for purposes such as caching.
What I'm more specifically asking is, what are the circumstances in which you should actually decide to store data ( using serialize() in PHP, pickle module in Python, et cetera )?
Let's say we had a hig... | [
"Example 1\nProfile.\n\nIs it prohibitively costly to generate your content pages?\nIs it significantly less costly to deserialize your generated content?\n\nIf both answers are yes, consider it.\nExample 2\nProfile.\n\nIs it prohibitively costly to generate your content pages?\nIs it significantly less costly to d... | [
6,
3
] | [] | [] | [
"php",
"python",
"serialization"
] | stackoverflow_0002032644_php_python_serialization.txt |
Q:
running a system command in a python script
I have been going through "A byte of Python" to learn the syntax and methods etc...
I have just started with a simple backup script (straight from the book):
#!/usr/bin/python
# Filename: backup_ver1.py
import os
import time
# 1. The files and directories to be back... | running a system command in a python script | I have been going through "A byte of Python" to learn the syntax and methods etc...
I have just started with a simple backup script (straight from the book):
#!/usr/bin/python
# Filename: backup_ver1.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['"C:\\My... | [
"It would help us if you could format your code as code; select the code parts, and click on the \"Code Sample\" button in the editor toolbar. The icon looks like \"101/010\" and if you hold the mouse pointer over it, the yellow \"tool tip\" box says \"Code Sample <pre></pre> Ctrl+K\"\nI just tried it, and if you ... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001710967_python.txt |
Q:
What do I use, CherryPy or Pylons?
Hi I'm planning on building a site with social networking features. Which Python framework do you think is more appropriate or you would suggest over the other, CherryPy or Pylons?
A:
That's a subjective question. I suggest you read carefully each framework's description and ch... | What do I use, CherryPy or Pylons? | Hi I'm planning on building a site with social networking features. Which Python framework do you think is more appropriate or you would suggest over the other, CherryPy or Pylons?
| [
"That's a subjective question. I suggest you read carefully each framework's description and choose the one that has the most features fitting your project.\nHere's an extensive overview of the two frameworks. This should help you choose the right tool for your project.\n",
"As S.Lott said it is vague, so best wa... | [
3,
2
] | [] | [] | [
"cherrypy",
"pylons",
"python"
] | stackoverflow_0002033195_cherrypy_pylons_python.txt |
Q:
_functools module
How does this import work, what file does it use?
import _functools
In python 2.5:
import _functools
print _functools.__file__
Gives:
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <module>
print _functools.__file__
AttributeError: 'module' object h... | _functools module | How does this import work, what file does it use?
import _functools
In python 2.5:
import _functools
print _functools.__file__
Gives:
Traceback (most recent call last):
File "D:\zjm_code\mysite\zjmbooks\a.py", line 5, in <module>
print _functools.__file__
AttributeError: 'module' object has no attribute '__file... | [
"C-coded modules can be built-in (lacking __file__) or live in a .so or .pyd dynamic library (which their __file__ will indicate) -- that's an implementation detail that you should not care about.\nIf you want to understand how a Python-callable, C-coded function works by studying code, learning to read C is genera... | [
3,
0,
0,
0,
0
] | [] | [] | [
"extension_modules",
"python"
] | stackoverflow_0002032677_extension_modules_python.txt |
Q:
How to access elements of matrices from mat file in python?
When load matrices from mat file in python using scipy.io, it makes dictionary where key is name of matrix,and value is 2D array of that matrix.
How can i access elements in this array?
A:
Suppose you have
mat = sio.loadmat('a.mat')
Then you can see ... | How to access elements of matrices from mat file in python? | When load matrices from mat file in python using scipy.io, it makes dictionary where key is name of matrix,and value is 2D array of that matrix.
How can i access elements in this array?
| [
"Suppose you have\nmat = sio.loadmat('a.mat')\n\nThen you can see which matrices were loaded by\nprint mat\n\nFor each key key in the dictionary, you can retrieve the corresponding matrix by\nmy_matrix = mat[key]\n\nmy_matrix is a 2d array representing the matrix. So to get row 0 of the matrix, you would use my_ma... | [
2,
0,
0
] | [] | [] | [
"matlab",
"python"
] | stackoverflow_0002034053_matlab_python.txt |
Q:
How to use Python tkSimpleDialog.askstring
I want to use the response from an askstring prompt to set a variable. Unfortunately,
I have the dilemma that I'm trapped in the loop asking the question or the window refuses to draw because the variable (urltoopen) has no value.
The code as it stands:
urltoopen = tkSim... | How to use Python tkSimpleDialog.askstring | I want to use the response from an askstring prompt to set a variable. Unfortunately,
I have the dilemma that I'm trapped in the loop asking the question or the window refuses to draw because the variable (urltoopen) has no value.
The code as it stands:
urltoopen = tkSimpleDialog.askstring('Address', 'Where do we get ... | [
"tkSimpleDialog.askstring returns None if the user clicks Cancel or closes the window (instead of clicking Ok or using the Enter key); you should check for that (what do you want to do if the user chooses to cancel? surely not call urlopen anyway...).\nApart from that, you're using the function correctly; I imagine... | [
4,
0
] | [] | [] | [
"python",
"tkinter",
"user_input"
] | stackoverflow_0002003504_python_tkinter_user_input.txt |
Q:
Text in tables?
I like to organize a lot of information from literature reviews in "tables" (information not unlike product comparisons, but for scientific research), but often the information I enter can contain lines or paragraphs of text and becomes unwieldy in a spreadsheet. I've heard SQL relational tables ar... | Text in tables? | I like to organize a lot of information from literature reviews in "tables" (information not unlike product comparisons, but for scientific research), but often the information I enter can contain lines or paragraphs of text and becomes unwieldy in a spreadsheet. I've heard SQL relational tables are often used for this... | [
"The way you store and retrieve data would depend on what you plan to do with it.\nText files have problems with manageability. You can't really take care of a directory tree with thousands and thousands of files. It would be a nightmare to search through them. If you're concurrently updating, you'll have to deal w... | [
4
] | [] | [] | [
"database",
"datatable",
"python",
"sql"
] | stackoverflow_0002034330_database_datatable_python_sql.txt |
Q:
Is there any way to load data dynamically into a python datastructure without recreating
I have a process that builds a list from a database table and runs real time. Every now and then new data gets added to the database table. Querying data from the table every now and then is cumbersome, and time consuming, and... | Is there any way to load data dynamically into a python datastructure without recreating | I have a process that builds a list from a database table and runs real time. Every now and then new data gets added to the database table. Querying data from the table every now and then is cumbersome, and time consuming, and this need to be as real time as possible.What is the right way to approach the problem?
The p... | [
"Wouldn't it make sense to just query the database again for all the new data that has come since you last queried? Something like key > highest_key_in_list or date > highest_date_in_list rather than loading up the whole thing again.\n",
"This feels a big hackish, but on your initial query create a temp table to ... | [
0,
0,
0,
0
] | [] | [] | [
"dynamic_data",
"python",
"real_time"
] | stackoverflow_0002034338_dynamic_data_python_real_time.txt |
Q:
Python CLI to edit Firefox bookmarks?
Has anyone done a Python CLI to edit Firefox bookmarks ?
My worldview is that of Unix file trees; I want
find /re/ in given or all fields in given or all subtrees
cd
ls with context
mv this ../there/
Whether it uses bookamrks.html or places.sqlite is secondary -- whatever's ... | Python CLI to edit Firefox bookmarks? | Has anyone done a Python CLI to edit Firefox bookmarks ?
My worldview is that of Unix file trees; I want
find /re/ in given or all fields in given or all subtrees
cd
ls with context
mv this ../there/
Whether it uses bookamrks.html or places.sqlite is secondary -- whatever's easier.
Clarification added: I'd be happy t... | [
"Assuming we're talking about Firefox 3 or better, the bookmarks are kept in a SQLite file, places.sqlite in the profile folder. So you need a routine to find the profile folder (depending on your platform) and then you can load the SQLite file.\nThe schema's rich and a bit complicated, but well documented, and of... | [
3,
0
] | [] | [] | [
"bookmarks",
"command_line_interface",
"firefox",
"python"
] | stackoverflow_0002034373_bookmarks_command_line_interface_firefox_python.txt |
Q:
ttk.Button returns None
I am trying to use the invoke method of a ttk.Button, as shown at TkDocs (look at "The Command Callback"), but I keep getting this error:
AttributeError: 'NoneType' object has no attribute 'invoke'
So, I tried this in the Interactive Shell:
ActivePython 3.1.1.2 (ActiveState Software Inc.)... | ttk.Button returns None | I am trying to use the invoke method of a ttk.Button, as shown at TkDocs (look at "The Command Callback"), but I keep getting this error:
AttributeError: 'NoneType' object has no attribute 'invoke'
So, I tried this in the Interactive Shell:
ActivePython 3.1.1.2 (ActiveState Software Inc.) based on
Python 3.1.1 (r311:... | [
"No, you're entirely wrong: your code does not show that ttk.Button returns None -- it shows that the grid method on the button object returns None! Don't you see that you're calling .grid on whatever it is that ttk.Button returns (the button object), and it's the result of that grid call that you're assigning to ... | [
14
] | [] | [] | [
"python",
"tkinter",
"ttk"
] | stackoverflow_0002034576_python_tkinter_ttk.txt |
Q:
Python: Very confused about decorators
I thought I understood decorators but not anymore. Do decorators only work when the function is created?
I wanted to create a series of functions that all have a required argument called 'ticket_params' that is a dictionary. and then decorate them with something like @param_c... | Python: Very confused about decorators | I thought I understood decorators but not anymore. Do decorators only work when the function is created?
I wanted to create a series of functions that all have a required argument called 'ticket_params' that is a dictionary. and then decorate them with something like @param_checker(['req_param_1', 'req_param_2']) and t... | [
"A decorator is applied immediately after the def statement; the equivalence is:\n@param_checker(['req_param_1', 'req_param_2'])\ndef my_decorated_function(params):\n # do stuff\n\nis exactly the same thing as:\ndef my_decorated_function(params):\n # do stuff\nmy_decorated_function = param_checker(['req_param... | [
11,
5,
3,
2,
0
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0002031559_decorator_python.txt |
Q:
cookielib and form authentication woes in Python
InstaMapper is a GPS tracking service that updates the device's position more frequently when the device is being tracked live on the InstaMapper webpage. I'd like to have this happen all the time so I thought I'd write a python script to login to my account and ac... | cookielib and form authentication woes in Python | InstaMapper is a GPS tracking service that updates the device's position more frequently when the device is being tracked live on the InstaMapper webpage. I'd like to have this happen all the time so I thought I'd write a python script to login to my account and access the page periodically.
import urllib2, urllib, co... | [
"action=login is part of the parameters, and should be treated accordingly:\nparams = urllib.urlencode(dict(action='login', username_hb='user', password_hb='hunter2')) \nopener.open('http://www.instamapper.com/fe', params)\n\n(Also, this particular username/password combination is invalid, I assume, that you actual... | [
0,
0
] | [] | [] | [
"cookielib",
"cookies",
"gps",
"python"
] | stackoverflow_0002033814_cookielib_cookies_gps_python.txt |
Q:
Optimize function to sort a list of tuples
I need to sort a list of tuples by first item in descending order, and then by second item in ascending order.
To do this, I have implemented the following function, but I think it could be faster.
>>> compare = lambda a, b: -cmp(b[1], a[1]) if b[0] == a[0] else cmp(b[0],... | Optimize function to sort a list of tuples | I need to sort a list of tuples by first item in descending order, and then by second item in ascending order.
To do this, I have implemented the following function, but I think it could be faster.
>>> compare = lambda a, b: -cmp(b[1], a[1]) if b[0] == a[0] else cmp(b[0], a[0])
>>> sorted([(0, 2), (0, 1), (1, 0), (1, 2... | [
"For me, it is a little faster to use a key instead of a comparison function, and arguably also easier to read:\nsorted([(0, 2), (0, 1), (1, 0), (1, 2)], key = lambda x:(-x[0], x[1]))\n\nThis requires Python 2.4 or newer.\n",
"How does this stack up for you?\ncompare = lambda a, b: cmp(b[0], a[0]) and cmp(a[1],b[... | [
8,
0
] | [] | [] | [
"optimization",
"python",
"sorting"
] | stackoverflow_0002034629_optimization_python_sorting.txt |
Q:
diff for single lines
All diff tools I've found are just comparing line by line instead of char by char. Is there any library that gives details on single line strings? Maybe also a percentage difference, though I guess there are separate functions for that?
A:
This algorithm diffs word-by-word:
http://github.c... | diff for single lines | All diff tools I've found are just comparing line by line instead of char by char. Is there any library that gives details on single line strings? Maybe also a percentage difference, though I guess there are separate functions for that?
| [
"This algorithm diffs word-by-word: \nhttp://github.com/paulgb/simplediff\navailable in Python and PHP. It can even spit out HTML formatted output using the <ins> and <del> tags.\n",
"I was looking for something similar recently, and came across wdiff. It operates on words, not characters, but is this close to wh... | [
5,
4,
3,
3
] | [] | [] | [
"diff",
"python"
] | stackoverflow_0002034727_diff_python.txt |
Q:
Distributing a python application
I have a simple python application where my directory structure is as follows:
project/
main.py
config.py
plugins/
plugin1
plugin2
...
Config.py only loads configuration files, it does not contain any configuration info in itself.
I now want to distribute this program, and I t... | Distributing a python application | I have a simple python application where my directory structure is as follows:
project/
main.py
config.py
plugins/
plugin1
plugin2
...
Config.py only loads configuration files, it does not contain any configuration info in itself.
I now want to distribute this program, and I thought I'd use setuptools to do it.... | [
"setuptools install your package in a location which is reachable from python i.e. you can import it:\nimport project\n\nthe problem raise when you do relative imports instead of absolute imports. if your main.py imports config.py it works because they live in the same directory. when you move your main.py to anoth... | [
11
] | [] | [] | [
"python",
"setuptools"
] | stackoverflow_0002034787_python_setuptools.txt |
Q:
Datastore Design Inquiry
I'm creating a Trivia app, and need some help designing my model relationships. This question may get fairly complicated, but I'll try to be concise.
Trivia questions will all be part of a particular category. Categories may be a category within another category. If a trivia question is... | Datastore Design Inquiry | I'm creating a Trivia app, and need some help designing my model relationships. This question may get fairly complicated, but I'll try to be concise.
Trivia questions will all be part of a particular category. Categories may be a category within another category. If a trivia question is created/removed, I need to ma... | [
"I'm not that familiar with Google App Engine, but here are some thoughts. First is to consider if \"tags\" are more appropriate than category & sub categories. Will their be a rigid 2 level category scheme? Will all items have a main and subcategory assignment? \nRather than having a class for each category, ha... | [
0,
0
] | [] | [] | [
"database_design",
"google_app_engine",
"python"
] | stackoverflow_0002034584_database_design_google_app_engine_python.txt |
Q:
Download a webpage and media
I need to download a webpage and all its media (like css javascript and images) to make a sort of backup (like firefox does when you click on File -> Save) with python.
Is there any library to do that or I shall create my own one?
A:
It's not exactly Python, but there's a pretty stan... | Download a webpage and media | I need to download a webpage and all its media (like css javascript and images) to make a sort of backup (like firefox does when you click on File -> Save) with python.
Is there any library to do that or I shall create my own one?
| [
"It's not exactly Python, but there's a pretty standard *nix utility called wget which you can call from a Python script that will do this.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0002035324_python.txt |
Q:
Python: Why does this doc test fail?
This code that's in the doctest works when run by itself, but in this doctest it fails in 10 places. I can't figure out why it does though. The following is the entire module:
class requireparams(object):
"""
>>> @requireparams(['name', 'pass', 'code'])
>>> def comp... | Python: Why does this doc test fail? | This code that's in the doctest works when run by itself, but in this doctest it fails in 10 places. I can't figure out why it does though. The following is the entire module:
class requireparams(object):
"""
>>> @requireparams(['name', 'pass', 'code'])
>>> def complex_function(params):
>>> print(pa... | [
"doctest requires that you use ... for continuation lines:\n>>> @requireparams(['name', 'pass', 'code'])\n... def complex_function(params):\n... print(params['name'])\n... print(params['pass'])\n... print(params['code'])\n...\n>>> params = {\n... 'name': 'John Doe',\n... 'pass': 'OpenSesame',\n.... | [
7,
1,
0
] | [] | [] | [
"docstring",
"doctest",
"python"
] | stackoverflow_0002035406_docstring_doctest_python.txt |
Q:
Python UDP socket options for multiple & concurrent clients
Let me explain a bit the app i'm doing.
I'm creating a central UDP (needs to be UDP) server for multiple and concurrent clients that also "talk" between them.
I do a check into a dict of known clients addresses and create a client handler thread if "i don... | Python UDP socket options for multiple & concurrent clients | Let me explain a bit the app i'm doing.
I'm creating a central UDP (needs to be UDP) server for multiple and concurrent clients that also "talk" between them.
I do a check into a dict of known clients addresses and create a client handler thread if "i dont know" the client. Else, the thread receives the data ad does it... | [
"The 'socket reset' happens because the client sent an ICMP port-unreachable in response to the datagram sent to a socket that wasn't there any more. Perfectly reasonable way to express that in the API, so you're just going to have to handle it. But if you just ignore the exception, the socket should still be wor... | [
1
] | [] | [] | [
"clients",
"concurrency",
"python",
"sockets"
] | stackoverflow_0002035542_clients_concurrency_python_sockets.txt |
Q:
Python synchronised reading of sorted files
I have two groups of files that contain data in CSV format with a common key (Timestamp) - I need to walk through all the records chronologically.
Group A: 'Environmental Data'
Filenames are in format A_0001.csv, A_0002.csv, etc.
Pre-sorted ascending
Key is Timestamp,... | Python synchronised reading of sorted files | I have two groups of files that contain data in CSV format with a common key (Timestamp) - I need to walk through all the records chronologically.
Group A: 'Environmental Data'
Filenames are in format A_0001.csv, A_0002.csv, etc.
Pre-sorted ascending
Key is Timestamp, i.e.YYYY-MM-DD HH:MM:SS
Contains environmental d... | [
"im thinking importing it into a db (mysql, sqlite, etc) will give better performance than merging it in script. the db typically has optimized routines for loading csv and the join will be probably be as fast or much faster than merging 2 dicts (one being very large) in python.\n",
"\"YYYY-MM-DD HH:MM:SS\" can b... | [
2,
2,
1,
0,
0
] | [] | [] | [
"file",
"merge",
"python",
"sorting"
] | stackoverflow_0002035285_file_merge_python_sorting.txt |
Q:
Coming from a Visual C# Express IDE/C# programming background, is there a tutorial for creating python applications?
It's very overwhelming coming from something that helps you create applications straight forward to something with somewhat convoluted documentation.
Can someone please share a tutorial on how to cr... | Coming from a Visual C# Express IDE/C# programming background, is there a tutorial for creating python applications? | It's very overwhelming coming from something that helps you create applications straight forward to something with somewhat convoluted documentation.
Can someone please share a tutorial on how to create a simple Hello World application using Python. No, I don't mean command line. I mean a physical window.
I'm trying to... | [
"Here's a great tutorial for wxPython (my GUI API of choice: extremely powerful, good community/mailing list, and cross-platform (it wraps the native platform's widgets))\nhttp://wiki.wxpython.org/Getting%20Started\nInstalling wxpython can be done through a simple setup.exe :\nhttp://downloads.sourceforge.net/wxpyt... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0002035599_python.txt |
Q:
purpose of '"sss".decode("base64").decode("zlib")'
ACTIVATE_THIS = """
eJx1UsGOnDAMvecrIlYriDRlKvU20h5aaY+teuilGo1QALO4CwlKAjP8fe1QGGalRoLEefbzs+Mk
Sb7NcvRo3iTcoGqwgyy06As+HWSNVciKaBTFywYoJWc7yit2ndBVwEkHkIzKCV0YdQdmkvShs6YH
E3IhfjFaaSNLoHxQy2sLJrL0ow98JQmEG/rAYn7OobVGogngBgf0P0hjgwgt7HOUaI5DdBVJkggR
3HwSktaqWcCtg... | purpose of '"sss".decode("base64").decode("zlib")' | ACTIVATE_THIS = """
eJx1UsGOnDAMvecrIlYriDRlKvU20h5aaY+teuilGo1QALO4CwlKAjP8fe1QGGalRoLEefbzs+Mk
Sb7NcvRo3iTcoGqwgyy06As+HWSNVciKaBTFywYoJWc7yit2ndBVwEkHkIzKCV0YdQdmkvShs6YH
E3IhfjFaaSNLoHxQy2sLJrL0ow98JQmEG/rAYn7OobVGogngBgf0P0hjgwgt7HOUaI5DdBVJkggR
3HwSktaqWcCtgiHIH7qHV+esW2CnkRJ+9R5cQGsikkWEV/J7leVGs9TV4TvcO5QOOrTHY... | [
"The data in the strings is encoded and compressed binary data. The .decode(\"base64\").decode(\"zlib\") unencodes and decompresses it.\nThe error you got was because 'dsss' decoded from base64 is not valid zlib compressed data.\n",
"What is the purpose of x.decode(”base64”).decode(”zlib”) for x in (\"sss\", \"d... | [
4,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002035727_python.txt |
Q:
Good interview questions for a Python/TurboGears web developer?
If you were looking to hire a web developer who would primarily be working with TurboGears/Python - what sort of questions should you ask them?
A:
In addition to the good suggestions in the other answers, something I always like to ask (from anybody... | Good interview questions for a Python/TurboGears web developer? | If you were looking to hire a web developer who would primarily be working with TurboGears/Python - what sort of questions should you ask them?
| [
"In addition to the good suggestions in the other answers, something I always like to ask (from anybody who's a candidate to develop anything at all that's related to the web) is: \"when a user types www.foo.com on their browser's address bar and hits return, what happens then? Please describe in as much or as litt... | [
15,
2,
1,
1
] | [] | [] | [
"python",
"turbogears"
] | stackoverflow_0002034128_python_turbogears.txt |
Q:
Python: Decorators: How does the following code work?
Are the comments in the following code correct? Particularly the "instance =..." one?
# This does nothing.
class donothing(object):
def __init__(self, func):
"""
The 'func' argument is the function being decorated because in this
ca... | Python: Decorators: How does the following code work? | Are the comments in the following code correct? Particularly the "instance =..." one?
# This does nothing.
class donothing(object):
def __init__(self, func):
"""
The 'func' argument is the function being decorated because in this
case, we're not instantiating the decorator class. Instead we... | [
"Yes perfect description, decorator donothing decorates the function printer and returns a object of class donothing, so yes decorator simply boils down to this \nx = donothing(func) # donothing is a class not function\n\nand you can use it like this, if you wish to avoid @deco syntax.\nso now x is an object, when ... | [
2
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0002036288_decorator_python.txt |
Q:
Model sys's python implementation
pypy
has many built-in function use python implementation.example:link
but,i can't find model 'sys' implementation.
how can i get it.
import sys
print help(sys)
A:
The sys module is implemented in C: http://svn.python.org/view/python/trunk/Python/sysmodule.c?view=markup
There ... | Model sys's python implementation | pypy
has many built-in function use python implementation.example:link
but,i can't find model 'sys' implementation.
how can i get it.
import sys
print help(sys)
| [
"The sys module is implemented in C: http://svn.python.org/view/python/trunk/Python/sysmodule.c?view=markup\nThere is no Python source for it, because it's entirely operating system interfaces that cannot be implemented in pure Python.\n",
"Abstraction can only be taken so far, Python strives to be a system/platf... | [
2,
0
] | [] | [] | [
"model",
"pypy",
"python"
] | stackoverflow_0002036392_model_pypy_python.txt |
Q:
Resource scheduling application
I'm trying to implement an application that coordinates multiple users who are scheduling exclusive resources. The schedule data must maintain strong consistency over a network with a single master node. The scheduled resources could be anything from a conference room to a worker on... | Resource scheduling application | I'm trying to implement an application that coordinates multiple users who are scheduling exclusive resources. The schedule data must maintain strong consistency over a network with a single master node. The scheduled resources could be anything from a conference room to a worker on a job site.
We assume the conference... | [
"You'll want to track just start and end times for each exclusionary resource. The data storage in your problem is actually the easy part - the hard(er) part is crafting queries to look for conflicts in time intervals.\nIf my logic is correct after being up for 21 hours, the following psuedo-code should check for ... | [
3,
1
] | [] | [] | [
"google_app_engine",
"python",
"resources",
"schedule",
"scheduling"
] | stackoverflow_0001535391_google_app_engine_python_resources_schedule_scheduling.txt |
Q:
I just installed QT for Windows but I can't find the control toolbox anywhere. Where do I drag controls to a form?
I opened a starter application to see how it works but I only see C++ files, nothing in Python. How can I configure QT to work for Python? :S
Also, where can I find the visual form?
A:
For python su... | I just installed QT for Windows but I can't find the control toolbox anywhere. Where do I drag controls to a form? | I opened a starter application to see how it works but I only see C++ files, nothing in Python. How can I configure QT to work for Python? :S
Also, where can I find the visual form?
| [
"For python support see PyQt.\nI'm not quite sure what you mean by \"visual form\". If you want a GUI editor try qtcreator \n",
"Qt comes with Qt Designer which you can use to create forms visually (like in Visual Studio). Designer creates XML \".ui\" files that are then fed into Qt's UIC tool. That tool then gen... | [
2,
1
] | [] | [] | [
"python",
"qt",
"qt4"
] | stackoverflow_0002035459_python_qt_qt4.txt |
Q:
How to get started building a Mac application
I am a Python/web programmer.
Now, I would like to transition to building applications for the Mac.
Please tell me--what do I have to learn to get started?
What books would you recommend?
A:
Assuming that you included the "python" tag after considering that it will ... | How to get started building a Mac application | I am a Python/web programmer.
Now, I would like to transition to building applications for the Mac.
Please tell me--what do I have to learn to get started?
What books would you recommend?
| [
"Assuming that you included the \"python\" tag after considering that it will be interpreted as applying to the question and not the questioner, you must be interested in writing Python applications for the Mac, right? After all, you didn't include \"web\" as one of the tags too.\nIf that's true, I'm not sure what... | [
3,
2
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0002036844_macos_python.txt |
Q:
What are the tradeoffs of reusing a cursor vs. creating a new cursor?
In cx_Oracle (or Oracle in general), is it possible to allocate a cursor for each query, or to reuse a cursor across several queries.
def getSomeData(curs): # case 1: pass in a cursor, which is generally
curs.execute('select ...') # ... | What are the tradeoffs of reusing a cursor vs. creating a new cursor? | In cx_Oracle (or Oracle in general), is it possible to allocate a cursor for each query, or to reuse a cursor across several queries.
def getSomeData(curs): # case 1: pass in a cursor, which is generally
curs.execute('select ...') # reused across queries
return curs.fetchall()
def getSomeData(c... | [
"You can re-use a cx_Oracle cursor as much as you like, no problem. If you're executing thousands of small queries in a small space of time, you might see a slight performance improvement by re-using the cursor, but I doubt it.\nI will sometimes create new cursors, and other times re-use an existing one, depending ... | [
11
] | [] | [] | [
"cx_oracle",
"database",
"oracle",
"python",
"sql"
] | stackoverflow_0002035212_cx_oracle_database_oracle_python_sql.txt |
Q:
PIP complains when I try to install a module into another virtualenv
I have a module installed in the main python install, however, I'd like to install this module into my virtualenv and I'd like it to be portable, how can I do that?
I'm getting this error:
(v_env)[nubela@nubela-desktop zine-ified]$ pip -E v_env i... | PIP complains when I try to install a module into another virtualenv | I have a module installed in the main python install, however, I'd like to install this module into my virtualenv and I'd like it to be portable, how can I do that?
I'm getting this error:
(v_env)[nubela@nubela-desktop zine-ified]$ pip -E v_env install pyfacebook
Requirement already satisfied (use --upgrade to upgrade)... | [
"To force pip installing a package when it's already been detected, you need to use the -I or --ignore-installed flag. In your case, the command would be:\npip -E v_env install -I pyfacebook\n\npip will then install it into your virtualenv.\n"
] | [
6
] | [] | [] | [
"python"
] | stackoverflow_0002036462_python.txt |
Q:
How to do related questions autopopulate
I want to get a related [things/questions] in my app, similar to what StackOverflow does, when you tab out of the Title field.
I can think of only one way to do it, which i think might be fast enough
Do a search for the title in corpus of titles of all [things], and return... | How to do related questions autopopulate | I want to get a related [things/questions] in my app, similar to what StackOverflow does, when you tab out of the Title field.
I can think of only one way to do it, which i think might be fast enough
Do a search for the title in corpus of titles of all [things], and return first x matches. We can use whatever search i... | [
"You're looking at a content-based recommendation algorithm. AFAICT StackOverflow's looks at the tags and the words in the title, and finds questions that share some of these. It can be implemented as a nearest neighbour search in a space where documents are represented as TF-IDF vectors.\nImplementation-wise, go w... | [
1
] | [] | [] | [
"algorithm",
"django",
"information_retrieval",
"python"
] | stackoverflow_0002036688_algorithm_django_information_retrieval_python.txt |
Q:
Different results from yield vs return
I don't really understand how yield statement works in this situation. The problem says that given an expression without parentheses, write a function to generate all possible fully parenthesized (FP) expressions. Say, the input is '1+2+3+4' which should be generated to 5 FP ... | Different results from yield vs return | I don't really understand how yield statement works in this situation. The problem says that given an expression without parentheses, write a function to generate all possible fully parenthesized (FP) expressions. Say, the input is '1+2+3+4' which should be generated to 5 FP expressions:
(1+(2+(3+4)))
(1+((2+3)+4))
((... | [
"The problem is you're iterating over generators instead of lists in the yield version, specifically secondG which is exhausted after one loop. Change the line to this and it works:\nfirstG, secondG = f(first), list(f(second))\n\nOr, you can change your loop:\nfor e in (\"(%s%s%s)\" % (e1, op, e2) for e1 in f(firs... | [
4
] | [] | [] | [
"python",
"recursion",
"yield"
] | stackoverflow_0002037267_python_recursion_yield.txt |
Q:
Translating function for finding all partitions of a set from Python to Ruby
I have the following python function to recursively find all partitions of a set:
def partitions(set_):
if not set_:
yield []
return
for i in xrange(2**len(set_)/2):
parts = [set(), set()]
for item ... | Translating function for finding all partitions of a set from Python to Ruby | I have the following python function to recursively find all partitions of a set:
def partitions(set_):
if not set_:
yield []
return
for i in xrange(2**len(set_)/2):
parts = [set(), set()]
for item in set_:
parts[i&1].add(item)
i >>= 1
for b in par... | [
"#!/usr/bin/ruby1.8\n\ndef partitions(set)\n yield [] if set.empty?\n (0 ... 2 ** set.size / 2).each do |i|\n parts = [[], []]\n set.each do |item|\n parts[i & 1] << item\n i >>= 1\n end\n partitions(parts[1]) do |b|\n result = [parts[0]] + b\n result = result.reject do |e|\n ... | [
4,
0
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0002037327_python_ruby.txt |
Q:
Problem with sqlalchemy, reflected table and defaults for string fields
hmm, is there any reason why sa tries to add Nones to for varchar columns that have defaults set in in database schema ?, it doesnt do that for floats or ints (im using reflection).
so when i try to add new row :
like
u = User()
u.foo = 'a'
u.... | Problem with sqlalchemy, reflected table and defaults for string fields | hmm, is there any reason why sa tries to add Nones to for varchar columns that have defaults set in in database schema ?, it doesnt do that for floats or ints (im using reflection).
so when i try to add new row :
like
u = User()
u.foo = 'a'
u.bar = 'b'
sa issues a query that has a lot more cols with None values assigne... | [
"What version do you use and what is actual code? Below is a sample code showing that server_default parameter works fine for string fields:\nfrom sqlalchemy import *\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nmetadata = MetaData()\nBase = declarative_base(m... | [
2,
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0002036996_python_sqlalchemy.txt |
Q:
How to create Form from a Model which has a ListProperty
I am currently using Django forms with the Google App Engine and I have a model which is as follows:
class Menu(db.Model):
name = db.StringProperty(required=True)
is_special = db.BooleanProperty()
menu_items = db.ListProperty(MenuItem)
I have a... | How to create Form from a Model which has a ListProperty | I am currently using Django forms with the Google App Engine and I have a model which is as follows:
class Menu(db.Model):
name = db.StringProperty(required=True)
is_special = db.BooleanProperty()
menu_items = db.ListProperty(MenuItem)
I have a MenuForm which is the following:
class MenuForm(djangoforms.M... | [
"Your problem comes well before the \"create a form\" task begins: ListProperty does not allow a list of model entities (although I can't find this clearly documented in the app engine docs, I'm still looking in the docs for a good, clear, unambiguous statement about that). Try changing it into (say) a list of str... | [
5
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0002037591_django_google_app_engine_python.txt |
Q:
jquery.autocomplete.js - how does autocomplete work?
I call the autocomplete jquery with the result of a GET request.
The autocomplete function call looks like this:
$('#id_project_owner_externally').autocomplete('/pm/contact_autocomplete');
The url /pm/contact_autocomplete returns a list of tuples. The first pa... | jquery.autocomplete.js - how does autocomplete work? | I call the autocomplete jquery with the result of a GET request.
The autocomplete function call looks like this:
$('#id_project_owner_externally').autocomplete('/pm/contact_autocomplete');
The url /pm/contact_autocomplete returns a list of tuples. The first part of the tuple is the name of the contact and the second ... | [
"The plugin docs have this example:\nvar data = [ {text:'Link A', url:'/page1'}, {text:'Link B', url: '/page2'} ];\n$(\"...\").autocomplete(data, {\n formatItem: function(item) {\n return item.text;\n }\n}).result(function(event, item) {\n location.href = item.url;\n});\n\nSo you basically can have a .result(... | [
3,
2
] | [] | [] | [
"django",
"jquery",
"python"
] | stackoverflow_0002038031_django_jquery_python.txt |
Q:
Getting output from server side python script
Hey, I'm doing this project where we are supposed to connect a javascript client side application/web page on server A with a python server side script on server B.
I need to get the output from the python script and store it into a variable but am running into some pr... | Getting output from server side python script | Hey, I'm doing this project where we are supposed to connect a javascript client side application/web page on server A with a python server side script on server B.
I need to get the output from the python script and store it into a variable but am running into some problems. I was trying to use XMLHttpRequest for this... | [
"It sounds like your XMLHttpRequest is failing because you're trying to do a cross-domain request. You could use a cross-domain solution like JSONP instead.\nIn general, tools like Firebug net panel are really useful for debugging these types of problems--you can use them to tell whether the client is sending a req... | [
4
] | [] | [] | [
"javascript",
"python",
"scripting",
"xmlhttprequest"
] | stackoverflow_0002038085_javascript_python_scripting_xmlhttprequest.txt |
Q:
How to get module variable in function from another module?
I'd like to define a helper function that has the ability to modify a module-level variable (with known name) from surrounding context without explicitly passing it, e.g.
# mod1.py
mod_var = 1
modify_var()
# mod_var modified
print mod_var
The problem is ... | How to get module variable in function from another module? | I'd like to define a helper function that has the ability to modify a module-level variable (with known name) from surrounding context without explicitly passing it, e.g.
# mod1.py
mod_var = 1
modify_var()
# mod_var modified
print mod_var
The problem is - I can't reference variable by mod1.mod_var, because I want to u... | [
"What you want to do sounds like too much magic. Pass in urlpatterns and be done with it. Explicit is better than implicit.\n",
"It's a truly bad, horrible, and awful idea, which will lead to future maintenance nightmares. However, Python does offer \"enough rope to shoot yourself in the foot\", if you truly ins... | [
4,
4,
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002038160_django_python.txt |
Q:
Integration of Python console into a GUI C++ application
I'm going to add a python console widget (into a C++ GUI) below some other controls:
Many classes are going to be exposed to the python code, including some access to GUI (maybe I'll consider PyQt).
Should I run the Python code in a separate thread?
I thi... | Integration of Python console into a GUI C++ application | I'm going to add a python console widget (into a C++ GUI) below some other controls:
Many classes are going to be exposed to the python code, including some access to GUI (maybe I'll consider PyQt).
Should I run the Python code in a separate thread?
I think it's a good approach, because GUI won't be frozen while exe... | [
"Since you're apparently wanting to embed a Python interpreter to use Python as a scripting language in a what seems to be a Qt application, I suggest you have a look at PythonQt.\nWith the PythonQt module, Python scripts will be able to interact with the GUI of your host application.\n\nUnlike PyQt and Qt Jambi, P... | [
14
] | [] | [] | [
"c++",
"integration",
"multithreading",
"python",
"user_interface"
] | stackoverflow_0002038247_c++_integration_multithreading_python_user_interface.txt |
Q:
Sets of instances
I'm trying to build a set of instances of an object, however adding instances of certain objects results in a TypeError: unhashable instance. Here is a minimal example:
from sets import Set
import random
from UserDict import DictMixin
class Item1(object):
pass
class Item2(DictMixin):
pa... | Sets of instances | I'm trying to build a set of instances of an object, however adding instances of certain objects results in a TypeError: unhashable instance. Here is a minimal example:
from sets import Set
import random
from UserDict import DictMixin
class Item1(object):
pass
class Item2(DictMixin):
pass
item_collection = S... | [
"In order to put things into a set, they should be hashable. Tuples for example are hashable whereas lists are not. You can make your object hashable by giving it a __hash__ method that will generate a hash key (a unique identifier for that instance of the class dependent on the data it's holding) for it. \nHere is... | [
5,
5
] | [] | [] | [
"python"
] | stackoverflow_0002038010_python.txt |
Q:
Difficulty getting flup fcgi script to work
I'm building a site for a client using django. It's been hosted on shared hosting and mod_wsgi can't be used. In the old year, I got it working using fcgi, but when I got back, it was broken.
I have replaced the fcgi script with a simple hello world script:
#!/usr/bin/py... | Difficulty getting flup fcgi script to work | I'm building a site for a client using django. It's been hosted on shared hosting and mod_wsgi can't be used. In the old year, I got it working using fcgi, but when I got back, it was broken.
I have replaced the fcgi script with a simple hello world script:
#!/usr/bin/python
def myapp(environ, start_response):
star... | [
"The exit status 116 and 118 were coming from suexec. By reading the source code, I found that these errors are caused by the file/dir being writable by group or others, which suexec considers as a security issue. Removing write access from group fixed the problem.\n"
] | [
2
] | [] | [] | [
"django",
"fastcgi",
"flup",
"python"
] | stackoverflow_0002013936_django_fastcgi_flup_python.txt |
Q:
Implementing tridiagonal matrix algorithm (TDMA) with NumPy
I'm implementing TDMA in Python using NumPy. The tridiagonal matrix is stored in three arrays:
a = array([...])
b = array([...])
c = array([...])
I'd like to calculate alpha-coefficients efficiently. The algorithm is as follows:
# n = size of the given m... | Implementing tridiagonal matrix algorithm (TDMA) with NumPy | I'm implementing TDMA in Python using NumPy. The tridiagonal matrix is stored in three arrays:
a = array([...])
b = array([...])
c = array([...])
I'd like to calculate alpha-coefficients efficiently. The algorithm is as follows:
# n = size of the given matrix - 1
alpha = zeros(n)
alpha[0] = b[0] / c[0]
for i in range(... | [
"If its tridiagonal systems you want to solve there is solve_banded() in numpy.linalg. Not sure if that's what you're looking for.\n",
"Apparently, there is no way to do this in Python without using C or its pythonic variations.\n"
] | [
2,
2
] | [] | [] | [
"numerical_methods",
"numpy",
"python"
] | stackoverflow_0001929045_numerical_methods_numpy_python.txt |
Q:
Access scanner from Java or Python (or something else if it's technically motivated) in Linux (but Windows would be nice)
I want to write a system for handling important documents in my home. This is the user story for getting a new document:
I "Add new document" and am prompted to scan it using my combined print... | Access scanner from Java or Python (or something else if it's technically motivated) in Linux (but Windows would be nice) | I want to write a system for handling important documents in my home. This is the user story for getting a new document:
I "Add new document" and am prompted to scan it using my combined printer/scanner.
I view the scanned copy to see it's of good enough quality. Which it has.
The system tells me to mark it with numbe... | [
"Under Linux, the common interface to scanners is SANE.\n",
"The standard interface for scanners is TWAIN. If you google for \"java twain\" or \"python twain\", you get plenty of useful-looking stuff, e.g.\n\nhttp://www.programmersheaven.com/2/Java-Twain-image-acquisition\nhttp://twainmodule.sourceforge.net/\n\n"... | [
3,
1
] | [] | [] | [
"image_scanner",
"java",
"python"
] | stackoverflow_0002038700_image_scanner_java_python.txt |
Q:
Listing buildout configuration variables
I'd like to find out, exactly what variables are available when using zc.buildout. I can always look at the source, but ideally I'd find a list somewhere, or be able to query buildout to find out what it thinks are the variables available at any one time. Is this possible... | Listing buildout configuration variables | I'd like to find out, exactly what variables are available when using zc.buildout. I can always look at the source, but ideally I'd find a list somewhere, or be able to query buildout to find out what it thinks are the variables available at any one time. Is this possible?
| [
"I found from the buildout docs that \nbin/buildout annotate \nwas what I was looking for.\n",
"It is not the prettiest list, but you can look at .installed.cfg in your buildout's directory.\nFor every part, it shows which options it knows about. (For some reason several parts are often shown multiple times).\n"... | [
14,
1
] | [] | [] | [
"buildout",
"python"
] | stackoverflow_0002037290_buildout_python.txt |
Q:
Python ctypes addressof CFuncType
Related to my other question
How can I get the address (acctual function pointer) to a CFuncType object? addressof() does not report the correct address.
C code:
extern "C" _declspec(dllexport)
int addr(int (*func)())
{
int r = (int)func;
return r;
}
Python code:
def test... | Python ctypes addressof CFuncType | Related to my other question
How can I get the address (acctual function pointer) to a CFuncType object? addressof() does not report the correct address.
C code:
extern "C" _declspec(dllexport)
int addr(int (*func)())
{
int r = (int)func;
return r;
}
Python code:
def test():
return 42
t = CFUNCTYPE(c_int)
f... | [
"cast(f, c_void_p) gets the correct address from within python\n"
] | [
7
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0002038839_ctypes_python.txt |
Q:
How should I convert this long and complex PHP style URL query string to a Django url?
I'm converting a small PHP application to Django.
One section has a long query string, indicating how a widget is to be displayed. There are a few required parameters and several optional ones.
The current urls read like:
app.ph... | How should I convert this long and complex PHP style URL query string to a Django url? | I'm converting a small PHP application to Django.
One section has a long query string, indicating how a widget is to be displayed. There are a few required parameters and several optional ones.
The current urls read like:
app.php?id=102030&size=large&auto=0&bw=1&extra=1
The id and size are required, but auto, bw and e... | [
"If you consider that \"URL\" stands for Uniform Resource Locator, the URL should only indicate the resource being displayed, and any 'configuration' options should be passed as parameters. So, I think your first idea is fine.\n"
] | [
8
] | [] | [] | [
"django",
"python",
"url",
"url_routing"
] | stackoverflow_0002039054_django_python_url_url_routing.txt |
Q:
Handling an "Inventory" (complex associations) with django + appengine
I'm writing a web application to manage a "game".
Here are the models:
class Character(db.Model):
# Bio
name = db.StringProperty()
player = db.StringProperty()
level = db.IntegerProperty()
class Item(db.Model):
name = db.St... | Handling an "Inventory" (complex associations) with django + appengine | I'm writing a web application to manage a "game".
Here are the models:
class Character(db.Model):
# Bio
name = db.StringProperty()
player = db.StringProperty()
level = db.IntegerProperty()
class Item(db.Model):
name = db.StringProperty()
description = db.StringProperty()
value = db.StringPr... | [
"Not sure if I understand you correctly, but if you want to show the Inventory of a Character in a form and place the form of the Character at the same page, you should check out inline formsets the doc\nUsing inline formsets you can do something like this:\ncharacter= get_object_or_404(Character, pk=character_id)\... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002038290_django_python.txt |
Q:
Fractions with decimal precision
Is there a pure python implementation of fractions.Fraction that supports longs as numerator and denominator? Unfortunately, exponentiation appears to be coded in to return a float (ack!!!), which should at least support using decimal.Decimal.
If there isn't, I suppose I can probab... | Fractions with decimal precision | Is there a pure python implementation of fractions.Fraction that supports longs as numerator and denominator? Unfortunately, exponentiation appears to be coded in to return a float (ack!!!), which should at least support using decimal.Decimal.
If there isn't, I suppose I can probably make a copy of the library and try ... | [
"\"Raise to a power\" is not a closed operation over the rationals (differently from the usual four arithmetic operations): there is no rational number r such that r == 2 ** 0.5. Legend has it that Pythagoras (from whose theorem this fact so simply follows) had his disciple Hippasus killed for the horrible crime o... | [
7,
0
] | [] | [] | [
"arbitrary_precision",
"decimal",
"long_integer",
"python"
] | stackoverflow_0002039154_arbitrary_precision_decimal_long_integer_python.txt |
Q:
PyQt + shortcut to trigger a button
How do I configure keyboard shortcuts to click specific buttons in a PyQT app? Eg: Ctrl + 1 to click one button while Ctrl + 2 to click the other?
A:
Use QtGui.QShortcut: you build it with a QKeySequence, and it emits the activated() signal when that key sequence is typed whil... | PyQt + shortcut to trigger a button | How do I configure keyboard shortcuts to click specific buttons in a PyQT app? Eg: Ctrl + 1 to click one button while Ctrl + 2 to click the other?
| [
"Use QtGui.QShortcut: you build it with a QKeySequence, and it emits the activated() signal when that key sequence is typed while the shortcut's parent widget has focus (of course, you connect those signals to slots of your choosing, including buttons').\n"
] | [
7
] | [] | [] | [
"button",
"keyboard_shortcuts",
"pyqt",
"python"
] | stackoverflow_0002039241_button_keyboard_shortcuts_pyqt_python.txt |
Q:
why 'setprofile' print this
import sys
def a():
print 'aaa'
def profiler(frame, event, arg):
print event, frame.f_code.co_name, frame.f_lineno, "->", arg
# profiler is activated on the next call, return, or exception
sys.setprofile(profiler)
a()
print
call a 5 -> None#what is it
aaa
return a 6 -> None#w... | why 'setprofile' print this | import sys
def a():
print 'aaa'
def profiler(frame, event, arg):
print event, frame.f_code.co_name, frame.f_lineno, "->", arg
# profiler is activated on the next call, return, or exception
sys.setprofile(profiler)
a()
print
call a 5 -> None#what is it
aaa
return a 6 -> None#what is it
return <module> 12 -> ... | [
"The profiler function gets called at each profiling event because you called sys.setprofile on it.\nEach time it's called, it prints a line, because you put an unconditional print statement as its body. Why you did that, is hard for us to tell you, making your \"why\" questions really, truly peculiar.\nProfiling ... | [
3,
0
] | [] | [] | [
"python",
"sys"
] | stackoverflow_0002039336_python_sys.txt |
Q:
How to upload images using an API Key that gives you permission to upload? [Python source code included]
The documentation of the API shows source code on how to accomplish this in Python:
#!/usr/bin/python
import pycurl
c = pycurl.Curl()
values = [
("key", "YOUR_API_KEY"),
("image", (c.FORM_... | How to upload images using an API Key that gives you permission to upload? [Python source code included] | The documentation of the API shows source code on how to accomplish this in Python:
#!/usr/bin/python
import pycurl
c = pycurl.Curl()
values = [
("key", "YOUR_API_KEY"),
("image", (c.FORM_FILE, "file.png"))]
# OR: ("image", "http://example.com/example.jpg"))]
c.setopt(c.URL, "http://imgur.com... | [
"You just need to perform an HTTP POST, e.g. this code with a \"parameters\" string of key=YOUR_API_KEY&image=http://example.com/example.jpg or the like.\n"
] | [
1
] | [] | [] | [
"api",
"c#",
"imgur",
"python"
] | stackoverflow_0002039602_api_c#_imgur_python.txt |
Q:
How do I regex search for weird non-ASCII characters in Python?
I'm using the following regular expression basically to search for and delete these characters.
invalid_unicode = re.compile(ur'(Û|²|°|±|É|¹|Í)')
My source code in ASCII encoded, and whenever I try to run the script it spits out:
SyntaxError: Non-AS... | How do I regex search for weird non-ASCII characters in Python? | I'm using the following regular expression basically to search for and delete these characters.
invalid_unicode = re.compile(ur'(Û|²|°|±|É|¹|Í)')
My source code in ASCII encoded, and whenever I try to run the script it spits out:
SyntaxError: Non-ASCII character '\xdb' in file ./release.py on line 273, but no encodin... | [
"You need to find out what encoding your editor is using, and set that per PEP263; or, make things more stable and portable (though alas perhaps a bit less readable) and use escape sequences in your string literal, i.e., use u'(\\xdb|\\xb2|\\xb0|\\xb1|\\xc9|\\xb9|\\xcd)' as the parameter to the re.compile call.\n",... | [
3,
1,
0
] | [] | [] | [
"ascii",
"python",
"regex",
"unicode"
] | stackoverflow_0002039650_ascii_python_regex_unicode.txt |
Q:
Django instance start under Google App Engine
After thinking quite a while about how to make a fast and scalable web application, I am almost decided to go for a combination of Google App Engine, Python+Django, and app-engine-patch. But I came across a comment in the app-engine-patch FAQ that made me think that pe... | Django instance start under Google App Engine | After thinking quite a while about how to make a fast and scalable web application, I am almost decided to go for a combination of Google App Engine, Python+Django, and app-engine-patch. But I came across a comment in the app-engine-patch FAQ that made me think that perhaps the combination is not quite as mature as I t... | [
"Yes, long startup times are a caveat of using a framework with a lot of code. There's no way around them, currently, other than using a framework that is lighter-weight (such as the built in webapp framework).\nPolling your app isn't recommended: It'll use up quota, and doesn't actually guarantee that the real use... | [
3,
1,
1,
0,
0
] | [] | [] | [
"app_engine_patch",
"django",
"google_app_engine",
"google_app_engine_patch",
"python"
] | stackoverflow_0001481942_app_engine_patch_django_google_app_engine_google_app_engine_patch_python.txt |
Q:
How do I make these Perl regexs Python compatible?
I have these two lines in an old Perl script. When I write the Python equivalent I get all sorts of errors like valueerror: invalid \x escape, and stuff about encoding.
$line =~ s/[^\x{8}-\x{7B}]/ /ig;
$line =~ s/(Û|²|°|±|É|¹|Í)/ /g;
What do I need to do to get t... | How do I make these Perl regexs Python compatible? | I have these two lines in an old Perl script. When I write the Python equivalent I get all sorts of errors like valueerror: invalid \x escape, and stuff about encoding.
$line =~ s/[^\x{8}-\x{7B}]/ /ig;
$line =~ s/(Û|²|°|±|É|¹|Í)/ /g;
What do I need to do to get them working in Python?
| [
"I'm not too great with Perl regex but I think I may have solved it:\ninvalid_range = re.compile(r'[^\\x08-\\x7B]', re.I)\ninvalid_unicode = re.compile(ur'(Û|²|°|±|É|¹|Í)')\nline = re.sub(invalid_range , '', line)\nline = re.sub(invalid_unicode, '', line)\n\n",
"For encoding issues, if you want to put Unicode cha... | [
1,
0
] | [] | [] | [
"perl",
"python",
"regex"
] | stackoverflow_0002039100_perl_python_regex.txt |
Q:
media conversion library
I am building a mobile website were users can upload/download videos, and I need a library that can convert the media files from mpeg, 3gp, mov depending on what the user wants to download.
Do you happen to know a a library that can do this?
A:
You should not only search for Library to... | media conversion library | I am building a mobile website were users can upload/download videos, and I need a library that can convert the media files from mpeg, 3gp, mov depending on what the user wants to download.
Do you happen to know a a library that can do this?
| [
"You should not only search for Library to do this, if you are using linux you can find an application that do this for you with CLI support,then using that application cli you can change your format;\n$result=shell_exec('application_name [parameters] input-file output-file')\n\nfor example you can use ffmpeg\n$res... | [
2,
1,
1,
0
] | [
"Take a look at FFmpeg. You could use as a command line tool.\n",
"In the past, I ran VLC from the command-line and used it to do my conversions (it's free, supports nearly all audio and video formats, and works on many different platforms). If you have VLC installed on the server, you can access it this way usi... | [
-1,
-1
] | [
".net",
"java",
"php",
"python",
"ruby"
] | stackoverflow_0001999641_.net_java_php_python_ruby.txt |
Q:
Python: Why can't I get my decorator to work?
This works now for those new to this question:
class ensureparams(object):
"""
Used as a decorator with an iterable passed in, this will look for each item
in the iterable given as a key in the params argument of the function being
decorated. It was bu... | Python: Why can't I get my decorator to work? | This works now for those new to this question:
class ensureparams(object):
"""
Used as a decorator with an iterable passed in, this will look for each item
in the iterable given as a key in the params argument of the function being
decorated. It was built for a series of PayPal methods that require
... | [
"def wrapper(params): means you're only going to accept one argument -- and so of course calls with (self, params) just won't work. You need to be able to accept either one or two arguments, e.g., at the very least (if you don't need to support calls w/named args):\ndef wrapper(one, two=None):\n if two is None: p... | [
2,
2,
0
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0002039699_decorator_python.txt |
Q:
Django One-To-Many Models
The following models describe a vulnerability and the URLs out on the internet that reference that vulnerability. Assume that each URL only ever talks about 1 vulnerability, and that many URLs will discuss that vulnerability. Is this the correct way to lay out the model?
class Vuln(models... | Django One-To-Many Models | The following models describe a vulnerability and the URLs out on the internet that reference that vulnerability. Assume that each URL only ever talks about 1 vulnerability, and that many URLs will discuss that vulnerability. Is this the correct way to lay out the model?
class Vuln(models.Model):
pub_date = models.Da... | [
"It should be more like this:\nclass Vuln(models.Model): \n pub_date = models.DateTimeField(\"Publication Date\") \n short_description = models.CharField(\"Description\", max_length=70)\n vendor = models.ForeignKey(Vendor, verbose_name=\"Vendor\") \n\nclass Url(models.Model): \n url = models.URLField(\"URL\", m... | [
23
] | [] | [] | [
"django",
"model",
"one_to_many",
"python"
] | stackoverflow_0002039958_django_model_one_to_many_python.txt |
Q:
Model form is crashing on a foreign key in django
So I'm trying to create a new feed within the Admin page and its
crashing with the error IntegrityError: lifestream_feed.lifestream_id
may not be NULL, form['lifestream'] is set but
form.instance.lifestream is not.
form.fields even shows that lifestream is a djan... | Model form is crashing on a foreign key in django | So I'm trying to create a new feed within the Admin page and its
crashing with the error IntegrityError: lifestream_feed.lifestream_id
may not be NULL, form['lifestream'] is set but
form.instance.lifestream is not.
form.fields even shows that lifestream is a django.forms.models.ModelChoiceField
Here is the code:
clas... | [
"I believe the problem is in your clean() method.\nThe general clean() method (as opposed to field specific clean methods like clean_domain()) must return the cleaned_data dictionary (minus any fields which do not validate), and you have at least 3 returns in your clean method that do not return anything.\nSee here... | [
0,
0
] | [] | [] | [
"django",
"django_forms",
"django_models",
"python"
] | stackoverflow_0002038621_django_django_forms_django_models_python.txt |
Q:
Sorting datetime objects while ignoring the year?
I have a list of birthdays stored in datetime objects. How would one go about sorting these in Python using only the month and day arguments?
For example,
[
datetime.datetime(1983, 1, 1, 0, 0)
datetime.datetime(1996, 1, 13, 0 ,0)
datetime.datetime(1976,... | Sorting datetime objects while ignoring the year? | I have a list of birthdays stored in datetime objects. How would one go about sorting these in Python using only the month and day arguments?
For example,
[
datetime.datetime(1983, 1, 1, 0, 0)
datetime.datetime(1996, 1, 13, 0 ,0)
datetime.datetime(1976, 2, 6, 0, 0)
...
]
Thanks! :)
| [
"You can use month and day to create a value that can be used for sorting:\nbirthdays.sort(key = lambda d: (d.month, d.day))\n\n",
"l.sort(key = lambda x: x.timetuple()[1:3])\n\n",
"If the dates are stored as strings—you say they aren't, although it looks like they are—you might use dateutil's parser:\n>>> from... | [
13,
7,
3
] | [] | [] | [
"datetime",
"python",
"sorting"
] | stackoverflow_0002040038_datetime_python_sorting.txt |
Q:
Python JPype integration
I am using JPype The following is the code i am trying to use
from jpype import *
startJVM("C:\Program Files\Java\jdk1.6.0_14\jre\bin\client\jvm.dll","-ea")
java.lang.System.out.println("hai")
shutdownJVM()
It is giving error in the execution of the println statement
java.lang.System.o... | Python JPype integration | I am using JPype The following is the code i am trying to use
from jpype import *
startJVM("C:\Program Files\Java\jdk1.6.0_14\jre\bin\client\jvm.dll","-ea")
java.lang.System.out.println("hai")
shutdownJVM()
It is giving error in the execution of the println statement
java.lang.System.out.println("hai")
File "<stdin... | [] | [] | [
"Firstly, are all the dependencies setup correctly? Java, Python, JPype etc?\nYou are trying to execute one of the first examples in the documentation.\nThe sample they provide in the docs are:\nfrom jpype import * \nstartJVM(\"d:/tools/j2sdk/jre/bin/client/jvm.dll\", \"-ea\") \njava.lang.System.out.println(\"hello... | [
-1,
-2
] | [
"java",
"jpype",
"python"
] | stackoverflow_0002040104_java_jpype_python.txt |
Q:
Install Plone egg as a Python module on Windows
I have a Plone site (Plone version 3.1.2) that I need to install a product called GrufSpaces on - (http://plone.org/products/grufspaces). However, it is a production site and so I can't easily take it down to upgrade Plone to 3.2+ in order to use buildout; using buil... | Install Plone egg as a Python module on Windows | I have a Plone site (Plone version 3.1.2) that I need to install a product called GrufSpaces on - (http://plone.org/products/grufspaces). However, it is a production site and so I can't easily take it down to upgrade Plone to 3.2+ in order to use buildout; using buildout would allow me to easily add Grufspaces (collect... | [
"Did you check GrufSpaces' INSTALL.TXT? From there:\n\nUnpack it into your Zope Products Folder\n\nFor Plone, the easiest way is probably to unpack it the top level products folder.\nSee also http://plone.org/documentation/kb/third-party-products/installing, section \"Installing Zope 2-style Products Without Buildo... | [
1,
1,
1
] | [] | [] | [
"plone",
"plone_3.x",
"python",
"zope"
] | stackoverflow_0002029826_plone_plone_3.x_python_zope.txt |
Q:
Implementing USZipCodeField and USStateField in django
I'm looking to implement a zipcode field in django using the form objects from localflavor, but not quite getting them to work. I want to have a zipcode field in a form (or ModelForm in my case), but the fields never validate as a zipcode when calling _get_er... | Implementing USZipCodeField and USStateField in django | I'm looking to implement a zipcode field in django using the form objects from localflavor, but not quite getting them to work. I want to have a zipcode field in a form (or ModelForm in my case), but the fields never validate as a zipcode when calling _get_errors() on the form object. The way I'm implementing it seems... | [
"Using widgets declaratively has literally only just been added to the trunk SVN version in the last day or so. If you're using an older checkout, or a released version, it won't work - you'll need to go back to the old way of doing it, by overriding the field declarations at the top level of the form.\n"
] | [
1
] | [] | [] | [
"django",
"django_forms",
"django_models",
"localization",
"python"
] | stackoverflow_0002039762_django_django_forms_django_models_localization_python.txt |
Q:
If I use QT For Windows, will my application run great on Linux/Mac/Windows?
I'm under the impressions that Python runs in the Triforce smoothly. A program that runs in Windows will run in Linux. Is this sentiment correct?
Having said that, if I create my application in QT For Windows, will it run flawlessly in Li... | If I use QT For Windows, will my application run great on Linux/Mac/Windows? | I'm under the impressions that Python runs in the Triforce smoothly. A program that runs in Windows will run in Linux. Is this sentiment correct?
Having said that, if I create my application in QT For Windows, will it run flawlessly in Linux/Mac as well?
Thanks.
| [
"Yes. No. Maybe. See also: Java and \"write once, run anywhere\".\nFilesystem layout, external utilities, anything you might do with things like dock icons, character encoding behaviors, these and more are areas you might run into some trouble.\nUsing Qt and Python, and strenuously avoiding anything that seems tied... | [
8,
5,
2,
1,
0,
0
] | [] | [] | [
"cross_platform",
"python",
"qt"
] | stackoverflow_0002035249_cross_platform_python_qt.txt |
Q:
Why is Ruby more suitable for Rails than Python?
Python and Ruby are usually considered to be close cousins (though with quite different historical baggage) with similar expressiveness and power. But some have argued that the immense success of the Rails framework really has a great deal to do with the language it... | Why is Ruby more suitable for Rails than Python? | Python and Ruby are usually considered to be close cousins (though with quite different historical baggage) with similar expressiveness and power. But some have argued that the immense success of the Rails framework really has a great deal to do with the language it is built on: Ruby itself. So why would Ruby be more s... | [
"There are probably two major differences:\nRuby has elegant, anonymous closures.\nRails uses them to good effect. Here's an example:\nclass WeblogController < ActionController::Base\n def index\n @posts = Post.find :all\n respond_to do |format|\n format.html\n format.xml { render :xml => @posts.to... | [
172,
58,
54,
26,
26,
15,
11,
8,
4,
1,
1
] | [
"Two answers : \na. Because rails was written for ruby. \nb. For the same reason C more suitable for Linux than Ruby\n",
"All of this is TOTALLY \"IMHO\"\nIn Ruby there is ONE web-application framework, so it is the only framework that is advertised for that language.\nPython has had several since inception, just... | [
-2,
-6
] | [
"python",
"ruby",
"ruby_on_rails",
"web_frameworks"
] | stackoverflow_0001099305_python_ruby_ruby_on_rails_web_frameworks.txt |
Q:
How does one do async ajax calls using cherrypy?
I'm using cherrypy's standalone server (cherrypy.quickstart()) and sqlite3 for a database.
I was wondering how one would do ajax/jquery asynchronous calls to the database while using cherrypy?
A:
If you are using CherryPy 3.2.0-rc1 then you can use the decorators ... | How does one do async ajax calls using cherrypy? | I'm using cherrypy's standalone server (cherrypy.quickstart()) and sqlite3 for a database.
I was wondering how one would do ajax/jquery asynchronous calls to the database while using cherrypy?
| [
"If you are using CherryPy 3.2.0-rc1 then you can use the decorators @json_in and @json_out (see here).\nThus:\n@cherrypy.expose\n@tools.json_in(on = True)\n@tools.json_out(on = True)\ndef json_test(self):\n return { 'message':'Hello, world!' }\n\nwill return JSON to the browser, e.g.\n$(document).ready(function... | [
9,
2
] | [] | [] | [
"ajax",
"asynchronous",
"cherrypy",
"jquery",
"python"
] | stackoverflow_0002015065_ajax_asynchronous_cherrypy_jquery_python.txt |
Q:
Index of item in list when only part of the item is known
This is a follow-up on a previous question of mine regarding searching in lists of lists
I have a list with pairs of values as lists in it.
[['a',5], ['b',3], ['c',2] ]
I know the first element of each pair but I don't know the second (it's the result of... | Index of item in list when only part of the item is known | This is a follow-up on a previous question of mine regarding searching in lists of lists
I have a list with pairs of values as lists in it.
[['a',5], ['b',3], ['c',2] ]
I know the first element of each pair but I don't know the second (it's the result of a calculation and stored in the list with the first element. I... | [
"[x[0] for x in list].index('a')\n\nBut if you are running this code several times, you might want to save the list of x[0]'s.\n",
"There's a similar solution to that of Ofris\nD = dict([ [x[1][0], x[0] ] for x in list(enumerate(L)) ])\nD['a']\n#returns 0\n\nBut another nice feature is that if you tweak this a l... | [
5,
4,
2,
2,
1
] | [] | [] | [
"indexing",
"list",
"python",
"search"
] | stackoverflow_0002040298_indexing_list_python_search.txt |
Q:
OS/X mimetype handler
I'd like to write a small script that implements RFC4709 for OS/X.
I started off by creating an application bundle that registers the application/xml+davmount mimetype and launches a simple python script.
It doesn't make a lot of sense to me to make this a .app bundle, because the application... | OS/X mimetype handler | I'd like to write a small script that implements RFC4709 for OS/X.
I started off by creating an application bundle that registers the application/xml+davmount mimetype and launches a simple python script.
It doesn't make a lot of sense to me to make this a .app bundle, because the application is very short-lived, and i... | [
"Make it a .app bundle, installed in Applications/Utilities (or really, anywhere). Bundles are the right thing on OS X. But if you really don't want to install it in Applications, how about somewhere under /Library or ~/Library, using a package rather than a drop in app. But I know I'd prefer the .app version...... | [
1
] | [] | [] | [
"macos",
"mime_types",
"python",
"webdav"
] | stackoverflow_0002040633_macos_mime_types_python_webdav.txt |
Q:
Using object id as a hash for objects in Python
Is it wise to use the object id as a hash key (via. the __hash__) to be able to hash an otherwise mutable object for a single instance of a program? Using the object attributes would be nicer but they're all mutable and can change.
This occurred to me while looking ... | Using object id as a hash for objects in Python | Is it wise to use the object id as a hash key (via. the __hash__) to be able to hash an otherwise mutable object for a single instance of a program? Using the object attributes would be nicer but they're all mutable and can change.
This occurred to me while looking at Sets of instances and I'm wondering if it's wise.
| [
"Yes, as long as you also define __eq__ (and presumably __ne__!-) consistently with that. IOW, it's fine, as long as you're fine with a==b meaning exactly the same as a is b!-)\n",
"For most Python classes this is the default behaviour. The unhashable ones are unhashable for a good reason: they are mutable collec... | [
14,
7
] | [] | [] | [
"hash",
"python"
] | stackoverflow_0002040101_hash_python.txt |
Q:
Best way to start, stop and send parameters to separate Python script from C++ application?
I try to explain the situation:
I have a QT application written in C++ and QT.
This QT application starts a separate console C++ application that runs in the background.
These two communicate using perhaps sockets, don't k... | Best way to start, stop and send parameters to separate Python script from C++ application? | I try to explain the situation:
I have a QT application written in C++ and QT.
This QT application starts a separate console C++ application that runs in the background.
These two communicate using perhaps sockets, don't know yet.
Console C++ application needs to start and stop my gnuradio python script. Also it needs... | [
"Sockets, or you could use DBUS python, and DBUS c++, if you want to be all free-desktopy :D\n",
"Spawn python script as a new process using fork() and execv(). execv() (or any other function of the exec family) lets you pass arguments to the Python script. Use the child process ID to send a kill signal when you ... | [
2,
2,
0
] | [] | [] | [
"c++",
"gnuradio",
"python",
"qt"
] | stackoverflow_0002040769_c++_gnuradio_python_qt.txt |
Q:
AppEngine/Python, query database and send multiple images to the client as a response to a single get request
I am working on a social-network type of application on App Engine, and would like to send multiple images to the client based on a single get request. In particular, when a client loads a page, they shoul... | AppEngine/Python, query database and send multiple images to the client as a response to a single get request | I am working on a social-network type of application on App Engine, and would like to send multiple images to the client based on a single get request. In particular, when a client loads a page, they should see all images that are associated with their account.
I am using python on the server side, and would like to u... | [
"The App Engine part isn't much of a problem (as long as the number of images and total size doesn't exceed GAE's limits), but the user's browser is unlikely to know what to do in order to receive multiple payloads per GET request -- that's just not how the web works. I guess you could concatenate all the blobs/by... | [
2,
1,
0,
0
] | [] | [] | [
"ajax",
"google_app_engine",
"image",
"python"
] | stackoverflow_0002003630_ajax_google_app_engine_image_python.txt |
Q:
How do I get PyFacebook working with the Google App Engine Patch?
I've tried to follow the advice of this question: Facebook, Django, and Google App Engine, however I've run into a number of problems. The first is that from facebook.djangofb import facebook doesn't work because when I try to use the decorator @fa... | How do I get PyFacebook working with the Google App Engine Patch? | I've tried to follow the advice of this question: Facebook, Django, and Google App Engine, however I've run into a number of problems. The first is that from facebook.djangofb import facebook doesn't work because when I try to use the decorator @facebook.require_login(), it complains that the facebook module doesn't h... | [
"For your first question:\n\nfrom facebook.djangofb import facebook doesn't work because when I try to use the decorator @facebook.require_login(), it complains that the facebook module doesn't have that method. If I change it to import facebook.djangofb and @facebook.djangofb.require_login(), it works.\n\nWell, se... | [
4
] | [] | [] | [
"app_engine_patch",
"django",
"facebook",
"google_app_engine",
"python"
] | stackoverflow_0002039653_app_engine_patch_django_facebook_google_app_engine_python.txt |
Q:
How to make phone calls using Python?
I'm writting a small python program to send voice file to other telephone. The phone is connected to pc over usb. How to make phone calls using Python?
A:
I think the smart way is to leave it a professional Voice/IP app such as ribbit or Twilio. I would personally recommend ... | How to make phone calls using Python? | I'm writting a small python program to send voice file to other telephone. The phone is connected to pc over usb. How to make phone calls using Python?
| [
"I think the smart way is to leave it a professional Voice/IP app such as ribbit or Twilio. I would personally recommend twilio which has Python libraries\n",
"Micromedia Jericho is a commercial product running on Ms Windows which has this capability. It manages several types of modems and make possible to send w... | [
2,
1,
0
] | [] | [] | [
"python",
"usb",
"voice"
] | stackoverflow_0002041352_python_usb_voice.txt |
Q:
What is The Pythonic Way for writing matching algorithm
I have this piece of code (should be self-explanatory; if not, just ask):
for tr in completed_taskrevs:
found = False
for nr in completion_noterevs:
if tr.description in nr.body:
completion_noterevs.remove(nr)
found = T... | What is The Pythonic Way for writing matching algorithm | I have this piece of code (should be self-explanatory; if not, just ask):
for tr in completed_taskrevs:
found = False
for nr in completion_noterevs:
if tr.description in nr.body:
completion_noterevs.remove(nr)
found = True
break
assert found
How can I make it mor... | [
"Try this:\nfor tr in compleded_taskrevs:\n try:\n nrs = (nr for nr in completion_noterevs if tr.description in nr.body)\n completion_noterevs.remove(nrs.next())\n except StopIteration:\n raise ValueError('Some error')\n\nEDIT:\nDevin is right. Assertion is not the way to go, better to us... | [
8,
6,
3
] | [] | [] | [
"python"
] | stackoverflow_0002041378_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.