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:
What does '_' do in Django code?
Why does this Django code use _ in front of 'has favicon'
has_favicon = models.BooleanField(_('has favicon'))
A:
If you look in the import statements, you'll find that they tied _ to a function that turns stuff into unicode and localizes it by writing:
from django.utils.translati... | What does '_' do in Django code? | Why does this Django code use _ in front of 'has favicon'
has_favicon = models.BooleanField(_('has favicon'))
| [
"If you look in the import statements, you'll find that they tied _ to a function that turns stuff into unicode and localizes it by writing:\nfrom django.utils.translation import ugettext_lazy as _\n\n",
"_ in Django is a convention that is used for localizing texts. It is an alias for ugettext_lazy. Read Lazy tr... | [
34,
11,
9
] | [] | [] | [
"django",
"gettext",
"internationalization",
"python"
] | stackoverflow_0001962287_django_gettext_internationalization_python.txt |
Q:
Python: error while checking IE state
Please, help me with Python 2.6 and win32com.
I'm a newbie to Python and I got error
when I start the next program:
import pywintypes
from win32com.client import Dispatch
from time import sleep
ie = Dispatch("InternetExplorer.Application")
ie.visible=1
url='hotfile.com'
ie.... | Python: error while checking IE state | Please, help me with Python 2.6 and win32com.
I'm a newbie to Python and I got error
when I start the next program:
import pywintypes
from win32com.client import Dispatch
from time import sleep
ie = Dispatch("InternetExplorer.Application")
ie.visible=1
url='hotfile.com'
ie.navigate(url)
while ie.ReadyState !=4:
... | [
"The sleep trick won't work with IE. You actually need to pump messages while you wait. I don't think a thread will work, by the way, because IE hates to not be in the GUI thread.\nHere's a ctypes-based message pump, with which I was able to get a 4 ReadyState for \"hotfile.com\" and \"yahoo.com\". It pulls all the... | [
1
] | [] | [] | [
"python",
"win32com"
] | stackoverflow_0001965911_python_win32com.txt |
Q:
how can i determine if anything at the given url does exist
how can i determine if anything at the given url does exist in the web using python? it can be a html page or a pdf file, shouldnt be matter.
ive tried the solution written in this page http://code.activestate.com/recipes/101276/
but it just returns a 1 w... | how can i determine if anything at the given url does exist | how can i determine if anything at the given url does exist in the web using python? it can be a html page or a pdf file, shouldnt be matter.
ive tried the solution written in this page http://code.activestate.com/recipes/101276/
but it just returns a 1 when its a pdf file or anything.
| [
"You need to check HTTP response code. Python example:\nfrom urllib2 import urlopen\ncode = urlopen(\"http://example.com/\").code\n\n4xx and 5xx code probably mean that you cannot get anything from this URL. 4xx status codes describe client errors (like \"404 Not found\") and 5xx status codes describe server errors... | [
16,
9,
2,
0
] | [] | [] | [
"http",
"python",
"url"
] | stackoverflow_0001966086_http_python_url.txt |
Q:
Remove all nested blocks, whilst leaving non-nested blocks alone via python
Source:
[This] is some text with [some [blocks that are nested [in a [variety] of ways]]]
Resultant text:
[This] is some text with
I don't think you can do a regex for this, from looking at the threads at stack overflow.
Is there a simpl... | Remove all nested blocks, whilst leaving non-nested blocks alone via python | Source:
[This] is some text with [some [blocks that are nested [in a [variety] of ways]]]
Resultant text:
[This] is some text with
I don't think you can do a regex for this, from looking at the threads at stack overflow.
Is there a simple way to to do this -> or must one reach for pyparsing (or other parsing library)... | [
"Here's an easy way that doesn't require any dependencies: scan the text and keep a counter for the braces that you pass over. Increment the counter each time you see a \"[\"; decrement it each time you see a \"]\".\n\nAs long as the counter is at zero or one, put the text you see onto the output string.\nOtherwise... | [
5,
4,
3,
3
] | [] | [] | [
"brackets",
"nested",
"python",
"recursion",
"regex"
] | stackoverflow_0001965486_brackets_nested_python_recursion_regex.txt |
Q:
When is the formfield() method called in Django?
This is a question on making custom fields in Django. I'm making a field called EditAreaField, which inherits from TextField. Here's what my code looks like:
class EditAreaField(models.TextField):
description = "A field for editing the HTML of a page"
def fo... | When is the formfield() method called in Django? | This is a question on making custom fields in Django. I'm making a field called EditAreaField, which inherits from TextField. Here's what my code looks like:
class EditAreaField(models.TextField):
description = "A field for editing the HTML of a page"
def formfield(self, **kwargs):
defaults = {}
... | [
"It looks like the formfield method is called by the ModelForm helper. According to the docs, the formfield method should include only a form_class attribute to point to the formfield class for this custom model field. This is a custom (or default) form field class, which is where the default widget is defined\nfro... | [
2
] | [] | [] | [
"custom_field_type",
"django",
"python",
"widget"
] | stackoverflow_0001964545_custom_field_type_django_python_widget.txt |
Q:
Specify input() type in Python?
Is it possible to define input times, like time, date, currency or that should be verified manually? Like for example:
morning = input('Enter morning Time:')
evening = input('Enter evening Time:')
.. I need (only) time here, how do I make sure that user enters input in xx:xx format... | Specify input() type in Python? | Is it possible to define input times, like time, date, currency or that should be verified manually? Like for example:
morning = input('Enter morning Time:')
evening = input('Enter evening Time:')
.. I need (only) time here, how do I make sure that user enters input in xx:xx format where xx are integers only.
| [
"input (in Python 2.any) will return the type of whatever expression the user types in. Better (in Python 2.any) is to use raw_input, which returns a string, and do the conversion yourself, catching the TypeError if the conversion fails.\nPython 3.any's input works like 2.any's raw_input, i.e., it returns a string... | [
10,
1
] | [] | [] | [
"input",
"python",
"types"
] | stackoverflow_0001964996_input_python_types.txt |
Q:
frames per seconds
I want to limit the calculation-speed. There was a command for rate per second. Could anybody help me?
doesn't rate() work in the newer version of Python?
Thanks
A:
Like Ignacio said, you can measure the time since the last calculation, calculate the time until the next, and sleep until then.... | frames per seconds | I want to limit the calculation-speed. There was a command for rate per second. Could anybody help me?
doesn't rate() work in the newer version of Python?
Thanks
| [
"Like Ignacio said, you can measure the time since the last calculation, calculate the time until the next, and sleep until then. You can also do it without any other framework, for example, with these functions:\nfrom datetime import datetime\nimport time\n\nt = datetime.now()[5] # milliseconds\ndt = # do some cal... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001957237_python.txt |
Q:
python print statements fixes OverflowError
I'm hacking a security system DVR so I can add motion capture and other fun features in python (version 2.6). One of the functions I was able to decompile from java and convert to python was the following:
def ToInt(abyte0, i):
if(abyte0[i] >= 0):
j = abyte0[i]
... | python print statements fixes OverflowError | I'm hacking a security system DVR so I can add motion capture and other fun features in python (version 2.6). One of the functions I was able to decompile from java and convert to python was the following:
def ToInt(abyte0, i):
if(abyte0[i] >= 0):
j = abyte0[i]
print "A " + str(j)
else:
j = 256 +... | [
"If you pass socket.recv() a value larger than 2147483647 (hex 0x7fffffff) Python will attempt to use a long integer instead of a regular integer. Clearly your value for DATA_SIZE is considered to be larger than that.\nThe ToInt() code appears to be trying to build up an integer out of individual bytes, and likely... | [
4,
0
] | [] | [] | [
"casting",
"python"
] | stackoverflow_0001966456_casting_python.txt |
Q:
Converting arrays between NumPy and JPype?
Does a library or script exist to convert between NumPy and JPype arrays?
A:
Doesn't
JArray(float, 1)(numpyarray)
work?
At least
JArray(float, 1)(numpyarray.tolist())
should work.
| Converting arrays between NumPy and JPype? | Does a library or script exist to convert between NumPy and JPype arrays?
| [
"Doesn't \nJArray(float, 1)(numpyarray)\n\nwork?\nAt least\nJArray(float, 1)(numpyarray.tolist())\n\nshould work.\n"
] | [
3
] | [] | [] | [
"java",
"numpy",
"python"
] | stackoverflow_0001966253_java_numpy_python.txt |
Q:
Why I can't call packagename.modulename.foo()?
In my working python directory I create:
packagename/__init__.py
packagename/modulename.py
test.py
In modulename.py I create some empty class:
class Someclass(object):
pass
in test.py:
import packagename
packagename.modulename.Someclass()
Why I can't call packag... | Why I can't call packagename.modulename.foo()? | In my working python directory I create:
packagename/__init__.py
packagename/modulename.py
test.py
In modulename.py I create some empty class:
class Someclass(object):
pass
in test.py:
import packagename
packagename.modulename.Someclass()
Why I can't call packagename.modulename.someclass() in test.py ?
AttributeE... | [
"Python does not automatically recurse and import subpackages. When you say:\nimport packagename\n\nThat is all it imports. If you say:\nimport packagename.modulename\n\nThen it first imports packagename, then imports packagename.modulename and assignes a reference to it as an attribute of packagename. Therefore... | [
2,
1,
0
] | [] | [] | [
"import",
"package",
"python"
] | stackoverflow_0001966783_import_package_python.txt |
Q:
Python UDP socket port random, despite assignment
I have two simple Python files: client.py and server.py. The client simply sends the text you type to the server, via UDP socket.
The port assigned and listened to is 21567, BUT... the line reading:
print "\nReceived message '", data,"' from ", addr
in server.py ... | Python UDP socket port random, despite assignment | I have two simple Python files: client.py and server.py. The client simply sends the text you type to the server, via UDP socket.
The port assigned and listened to is 21567, BUT... the line reading:
print "\nReceived message '", data,"' from ", addr
in server.py outputs the addr to be something looking like this: ('1... | [
"60471 is the client's port and 21567 is the server's port. They can't be the same: Any IP traffic has to declare its source address and port, and its destination address and port. The client port is usually a random number in the range 32768 to 65535. addr is telling you the client's address.\nThis is done so y... | [
4,
2
] | [] | [] | [
"python",
"sockets",
"udp"
] | stackoverflow_0001967188_python_sockets_udp.txt |
Q:
Why is "def InvalidArgsSpecified:" a syntax error?
I'm just starting to learn python... so bear with me please
Why is it giving me a Invalid Syntax error with this block of code
def InvalidArgsSpecified:
print ("*** Simtho Usage ***\n")
print ("-i Installs Local App,, include full path")
print ("-u Uni... | Why is "def InvalidArgsSpecified:" a syntax error? | I'm just starting to learn python... so bear with me please
Why is it giving me a Invalid Syntax error with this block of code
def InvalidArgsSpecified:
print ("*** Simtho Usage ***\n")
print ("-i Installs Local App,, include full path")
print ("-u Uninstalls Installed App,include ID or Name")
print ("-... | [
"The syntax error is in the very first line, where you have:\ndef InvalidArgsSpecified:\n\nchange it to:\ndef InvalidArgsSpecified():\n\nThose parentheses are mandatory in a def, even when there's nothing between them (just as parentheses are always used to call a function -- empty parentheses, in that case, if you... | [
6,
2
] | [] | [] | [
"function",
"python",
"syntax_error"
] | stackoverflow_0001967336_function_python_syntax_error.txt |
Q:
Delete the \n and following letters in the end of words in a list
How can I delete the \n and the following letters? Thanks a lot.
wordlist = ['Schreiben\nEs', 'Schreiben', 'Schreiben\nEventuell', 'Schreiben\nHaruki']
for x in wordlist:
...?
A:
>>> import re
>>> wordlist = ['Schreiben\nEs', 'Schreiben', \
... | Delete the \n and following letters in the end of words in a list | How can I delete the \n and the following letters? Thanks a lot.
wordlist = ['Schreiben\nEs', 'Schreiben', 'Schreiben\nEventuell', 'Schreiben\nHaruki']
for x in wordlist:
...?
| [
">>> import re\n>>> wordlist = ['Schreiben\\nEs', 'Schreiben', \\\n 'Schreiben\\nEventuell', 'Schreiben\\nHaruki']\n>>> [ re.sub(\"\\n.*\", \"\", word) for word in wordlist ]\n['Schreiben', 'Schreiben', 'Schreiben', 'Schreiben']\n\nDone via re.sub:\n>>> help(re.sub)\n 1 Help on function sub in module re:\n 2 \... | [
4,
3,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001966495_python_string.txt |
Q:
cut off empty spaces
How can i cut off the last empty space?
a = ['Hello ','everybody ','! ']
for i in range(len(a)):
a[i,-1]=''
print a
A:
To cut off only last (right) empty spaces, use rstrip() method. strip() removes spaces from both ends:
>>> s = " abc "
>>> s.rstrip()
' abc'
>>> s.strip()
'abc'
In you... | cut off empty spaces | How can i cut off the last empty space?
a = ['Hello ','everybody ','! ']
for i in range(len(a)):
a[i,-1]=''
print a
| [
"To cut off only last (right) empty spaces, use rstrip() method. strip() removes spaces from both ends:\n>>> s = \" abc \"\n>>> s.rstrip()\n' abc'\n>>> s.strip()\n'abc'\n\nIn your example:\n>>> [s.rstrip() for s in ['Hello ','everybody ','! '] ]\n['Hello', 'everybody', '!']\n\n",
"Solution via list comprehension:... | [
10,
5,
1,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001966426_python_string.txt |
Q:
When are function local python variables created?
When are function-local variables are created? For example, in the following code is dictionary d1 created each time the function f1 is called or only once when it is compiled?
def f1():
d1 = {1: 2, 3: 4}
return id(d1)
d2 = {1: 2, 3: 4}
def f2():
retur... | When are function local python variables created? | When are function-local variables are created? For example, in the following code is dictionary d1 created each time the function f1 is called or only once when it is compiled?
def f1():
d1 = {1: 2, 3: 4}
return id(d1)
d2 = {1: 2, 3: 4}
def f2():
return id(d2)
Is it faster in general to define a dictionar... | [
"Local variables are created when assigned to, i.e., during the execution of the function.\nIf every execution of the function needs (and does not modify!-) the same dict, creating it once, before the function is ever called, is faster. As an alternative to a global variable, a fake argument with a default value i... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001967454_python.txt |
Q:
Google App Engine - How do I split code into multiple files? (webapp)
I have a question about splitting up a main.py file.
right now, I have everything in my main.py. I have no other .py files. And I always have to scroll long lines of code before reaching the section I wish to edit.
How do I split it up?
(i'm go... | Google App Engine - How do I split code into multiple files? (webapp) | I have a question about splitting up a main.py file.
right now, I have everything in my main.py. I have no other .py files. And I always have to scroll long lines of code before reaching the section I wish to edit.
How do I split it up?
(i'm going to have more than 20 pages, so that means the main.py will be HUGE if I... | [
"Splitting the code is no different than splitting code for any Python app - find a bunch of related code that you want to move to another file, move it to that file, and import it into the main handler file.\nFor example, you could move the Page2 code to page2.py, put\nimport page2\n\nat the top of your file, and ... | [
22,
2,
0
] | [] | [] | [
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0001966974_google_app_engine_python_web_applications.txt |
Q:
Return value of os.path in Python
For this code:
import os
a=os.path.join('dsa','wqqqq','ffff')
print a
print os.path.exists('dsa\wqqqq\ffff') #what situation this will be print True?
When will os.path.exists('what') print True?
A:
'dsa\wqqqq\ffff' does not mean what you probably think it does: \f, within a str... | Return value of os.path in Python | For this code:
import os
a=os.path.join('dsa','wqqqq','ffff')
print a
print os.path.exists('dsa\wqqqq\ffff') #what situation this will be print True?
When will os.path.exists('what') print True?
| [
"'dsa\\wqqqq\\ffff' does not mean what you probably think it does: \\f, within a string, is an escape sequence and expands to the same character as chr(12) (ASCII \"form feed\").\nSo print os.path.exists('dsa\\wqqqq\\ffff') will print True if:\n\non Windows, there's a subdirectory dsa in the current working directo... | [
8,
1,
0
] | [] | [] | [
"path",
"python"
] | stackoverflow_0001967643_path_python.txt |
Q:
Is there any Visual Studio-like tool for creating GUIs for Python?
My girlfriend asked me if there was a tool (actually, an IDE) that would let her create her GUI visually and edit functions associated with GUI-related events with little effort.
For example, she wants to double-click a button she just created and ... | Is there any Visual Studio-like tool for creating GUIs for Python? | My girlfriend asked me if there was a tool (actually, an IDE) that would let her create her GUI visually and edit functions associated with GUI-related events with little effort.
For example, she wants to double-click a button she just created and immediately see (and edit) the code associated with that button's on-cli... | [
"I would recommend based on your needs:\n\nQt Designer\nwxGlade\n\nCheck this out:\nhttp://wiki.python.org/moin/GuiProgramming\n",
"For GTK+ there is Glade. Python can load interface files created with Glade. There are some tutorials on the net.\n\nFor Qt there is QtDesigner. PyQt manual covers how to use PyQt wi... | [
8,
2,
2,
1,
0,
0
] | [] | [] | [
"gtk",
"python",
"qt",
"visual_studio",
"wxwidgets"
] | stackoverflow_0001967220_gtk_python_qt_visual_studio_wxwidgets.txt |
Q:
Accessing a file relatively in Python if you do not know your starting point?
Hey. I've got a project in Python, whose directory layout is the following:
root
|-bin
|-conf
|-[project]
Python files in [project] need to be able to read configuration data from the 'conf' directory, but I cannot guarantee the l... | Accessing a file relatively in Python if you do not know your starting point? | Hey. I've got a project in Python, whose directory layout is the following:
root
|-bin
|-conf
|-[project]
Python files in [project] need to be able to read configuration data from the 'conf' directory, but I cannot guarantee the location of root, plus it may be used on both Linux, Mac and Windows machines so I a... | [
"Instead of:\npath = os.path.abspath(__file__)[:-8]\n\nuse:\npath = os.path.dirname(os.path.abspath(__file__))\n\nSee the docs here.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0001967688_python.txt |
Q:
How can you use a font file in GTK
I'm writing an open source program (key-train) in Python and GTK (with Cairo) and I would like to use some more attractive fonts. I was hoping that it would be possible to load a ttf font from within the program and just use it (instead of installing it), but I haven't been able... | How can you use a font file in GTK | I'm writing an open source program (key-train) in Python and GTK (with Cairo) and I would like to use some more attractive fonts. I was hoping that it would be possible to load a ttf font from within the program and just use it (instead of installing it), but I haven't been able to figure out how to do this.
| [
"You might want to take a look at this feature request It shows a work-a-round if using cairo and freetype for the backend.\n",
"You could use pango to set the ttf font:\n#!/usr/bin/env python\nimport pango\nimport gtk\n\nwindow = gtk.Window(gtk.WINDOW_TOPLEVEL)\nmain_vbox = gtk.VBox(homogeneous=False,spacing=0)\... | [
4,
0
] | [] | [] | [
"fonts",
"gtk",
"linux",
"python"
] | stackoverflow_0001967257_fonts_gtk_linux_python.txt |
Q:
Why doesn't my code print `os.path`
For the code:
def a(x):
if x=='s':
__import__('os') #I think __import__ == import
print os.path
Why doesn't print a('os') print os.path?
My next question is: Why does the following code use __import__('some') instead of something like, a = __import__('os') ... | Why doesn't my code print `os.path` | For the code:
def a(x):
if x=='s':
__import__('os') #I think __import__ == import
print os.path
Why doesn't print a('os') print os.path?
My next question is: Why does the following code use __import__('some') instead of something like, a = __import__('os') ?
def import_module(name, package=None):
... | [
"__import__ returns a module. It doesn't actually add anything to the current namespace.\nYou probably want to just use import os:\ndef a(x):\n if x=='s':\n import os\n print os.path\na('s')\n\nAlternatively, if you want to import the module as a string, you can explicitly assign it:\ndef a(x):\n ... | [
11,
5
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0001967702_import_module_python.txt |
Q:
Python string concatenation Idiom. Need Clarification.
From http://jaynes.colorado.edu/PythonIdioms.html
"Build strings as a list and use
''.join at the end. join is a string
method called on the separator, not
the list. Calling it from the empty
string concatenates the pieces with no
separator, which is a Pytho... | Python string concatenation Idiom. Need Clarification. | From http://jaynes.colorado.edu/PythonIdioms.html
"Build strings as a list and use
''.join at the end. join is a string
method called on the separator, not
the list. Calling it from the empty
string concatenates the pieces with no
separator, which is a Python quirk and
rather surprising at first. This is
important: st... | [
"Yes. For the examples you chose the importance isn't clear because you only have two very short strings so the append would probably be faster.\nBut every time you do a + b with strings in Python it causes a new allocation and then copies all the bytes from a and b into the new string. If you do this in a loop wit... | [
14,
6,
4,
1,
0
] | [] | [] | [
"idioms",
"performance",
"python"
] | stackoverflow_0001967723_idioms_performance_python.txt |
Q:
Are there other Type in addition to the class to be called by hasattr
For code:
class a(object):
a='aaa'
b=a()
print hasattr(a,'a')
print hasattr(b,'a')
who can be called by hasattr except 'class somebody'?
Thanks!
A:
You can call hasattr with any object as the first argument (and any string as the second a... | Are there other Type in addition to the class to be called by hasattr | For code:
class a(object):
a='aaa'
b=a()
print hasattr(a,'a')
print hasattr(b,'a')
who can be called by hasattr except 'class somebody'?
Thanks!
| [
"You can call hasattr with any object as the first argument (and any string as the second argument): it just returns False if that object does not have an attribute by that name (\"having\" an attribute of course includes possibly inheriting or synthesizing it; hasattr(x,'y') is True if and only if accessing x.y wo... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001967730_python.txt |
Q:
Parse Facebook feed datetime in python?
I am reading a Facebook updates feed using the python library 'feedparser'.
I loop through the collection of entries in my Django templates, and display the results.
The updated field is returned in a big long string, of some format I am unfamiliar with.
Tue, 01 Dec 2009 23:... | Parse Facebook feed datetime in python? |
I am reading a Facebook updates feed using the python library 'feedparser'.
I loop through the collection of entries in my Django templates, and display the results.
The updated field is returned in a big long string, of some format I am unfamiliar with.
Tue, 01 Dec 2009 23:55:52 +0000
How can I...
A) Use a Django fi... | [
"Use entries[i].updated_parsed instead of entries[i].updated, and feedparser will return a parsed 9-tuple for you. (Documentation)\nThen build a datetime object and pass it to Django or format to a string by yourself.\nThere is a similar question here.\n",
"This worked but wasn't what my final solution ended up b... | [
4,
2
] | [] | [] | [
"datetime",
"django",
"facebook",
"feedparser",
"python"
] | stackoverflow_0001967801_datetime_django_facebook_feedparser_python.txt |
Q:
How to use C++ lib from python
I would like to know how to use python to make calls to a C++ library called libwpd to read word perfect files and build python objects from them, but I have no experience with C++ or calling C++ functions from python, and I don't understand how to figure out what the output of these... | How to use C++ lib from python | I would like to know how to use python to make calls to a C++ library called libwpd to read word perfect files and build python objects from them, but I have no experience with C++ or calling C++ functions from python, and I don't understand how to figure out what the output of these library functions would be. So that... | [
"Checkout ctypes. It's part of the standard Python library set. I can't speak to it's use with C++, but I suspect it will work nicely.\n",
"The Boost.Python library allows easy interoperability between C++ and Python.\nThe tutorial shows how to wrap C++ functions and classes to use them from Python.\n"
] | [
2,
2
] | [] | [] | [
"python",
"swig",
"wordperfect"
] | stackoverflow_0001967755_python_swig_wordperfect.txt |
Q:
Simulate mouse click/Detect color under cursor in Python
I am very new to python. I am trying to write a program that will click the mouse at (x, y), move it to (a, b), and then wait until the color under the mouse is a certain color, lets say #fff. When it is that color, it clicks again and then repeats.
I cannot... | Simulate mouse click/Detect color under cursor in Python | I am very new to python. I am trying to write a program that will click the mouse at (x, y), move it to (a, b), and then wait until the color under the mouse is a certain color, lets say #fff. When it is that color, it clicks again and then repeats.
I cannot find a good API for mouse related stuff for python.
| [
"The API for simulating mouse events depends on your platform. I don't know any cross-platform solution. \nOn Windows, you can access the Win32 API thanks to ctypes. see mouse_event on MSDN. You may also be interested by pywinauto\nFor getting the color under the mouse, you need the mouse position. See GetCursorPos... | [
9
] | [
"if you're on Windows, then, for this kind of thing, you really want to try autohotkey. It's not python, but it is extremely powerful for doing this kind of thing on a Windows machine. The user community is extremely helpful, also. Check out their \"ask for help\" forum.\n"
] | [
-1
] | [
"colors",
"mouse",
"python"
] | stackoverflow_0001967096_colors_mouse_python.txt |
Q:
i don't know why django do this,it is about os.stat
What is the benefits of doing so:
import os
ST_MODE = 0
ST_INO = 1
ST_DEV = 2
ST_NLINK = 3
ST_UID = 4
ST_GID = 5
ST_SIZE = 6
ST_ATIME = 7
ST_MTIME = 8
ST_CTIME = 9
# Extract bits from the mode
def S_IMODE(mode):
return mode & 07777
def S_IFMT(mod... | i don't know why django do this,it is about os.stat | What is the benefits of doing so:
import os
ST_MODE = 0
ST_INO = 1
ST_DEV = 2
ST_NLINK = 3
ST_UID = 4
ST_GID = 5
ST_SIZE = 6
ST_ATIME = 7
ST_MTIME = 8
ST_CTIME = 9
# Extract bits from the mode
def S_IMODE(mode):
return mode & 07777
def S_IFMT(mode):
return mode & 0170000
# Constants used as S_IFMT... | [
"The benefits? I imagine one of them (a 'negative' one) is to stop the code from trying to process directories as regular files. If you run code such as:\nmyprog *\n\nthe shell will change that * into a list of all files within the current directory (including subdirectories, pipes, device nodes and all sorts of ot... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0001968272_python.txt |
Q:
Can a standalone web application built with cherrypy be compiled?
I want to build a web application that stands completely by itself, apache not required. Is cherrypy a good solution, and can this be compiled with something like py2exe?
A:
Python is a scripting language and is not usually compiled. What you are ... | Can a standalone web application built with cherrypy be compiled? | I want to build a web application that stands completely by itself, apache not required. Is cherrypy a good solution, and can this be compiled with something like py2exe?
| [
"Python is a scripting language and is not usually compiled. What you are talking about is packaging your scripts into an exe (via p2exe), bundled with the relative modules and an interpreter.\nThis is possible with many scripts, including CherryPy, as p2exe basically sticks all your scripts together in one place, ... | [
1,
0
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0001967705_cherrypy_python.txt |
Q:
How can i create a melody? Is there any sound-module?
I am confused because there are a lot of programms. But i am looking something like this. I will type a melody like "a4 c3 h3 a2" etc. and then i want to hear this. Does anybody know what i am looking for?
thanks in advance
A:
computing frequencies from note ... | How can i create a melody? Is there any sound-module? | I am confused because there are a lot of programms. But i am looking something like this. I will type a melody like "a4 c3 h3 a2" etc. and then i want to hear this. Does anybody know what i am looking for?
thanks in advance
| [
"computing frequencies from note name is easy. each half-note is 2^(1/12) away from the preceding note, 440 Hz is A4. \nif by any chance you are on windows, you may try this piece of code, which plays a song through the PC speaker:\nimport math\nimport winsound\nimport time\n\nlabels = ['a','a#','b','c','c#','d','d... | [
8,
3,
2,
1
] | [] | [] | [
"audio",
"python"
] | stackoverflow_0001967040_audio_python.txt |
Q:
Python with MySQL on Windows: installation errors
I tried to run the following command, in the folder of my Django project:
$ python manage.py dbshell
It shows me this error:
$python manage.py dbshell
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File ... | Python with MySQL on Windows: installation errors | I tried to run the following command, in the folder of my Django project:
$ python manage.py dbshell
It shows me this error:
$python manage.py dbshell
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "C:\Python25\lib\site-packages\django\core\management\_... | [
"Did you try looking here: http://sourceforge.net/projects/mysql-python/files/\nThat is the download area of MySQLdb project, it has nothing to do with django, so your question is incorrect - django does not make switching database backends hard, you just change one line. And of course, your python installation sho... | [
4,
0,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0001964448_mysql_python.txt |
Q:
How does the Python conditional operator workaround work?
From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).
I found the following code as a substitute:
def val():
var = float(raw_input("Age:"))
status = ("Working","Retired")[var>65]
... | How does the Python conditional operator workaround work? | From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).
I found the following code as a substitute:
def val():
var = float(raw_input("Age:"))
status = ("Working","Retired")[var>65]
print "You should be:",status
I couldn't understand how this ... | [
"Python has a construct that is sort of like the ternary operator in C, et al. It works something like this:\nmy_var = \"Retired\" if age > 65 else \"Working\"\n\nand is equivalent to this C code:\nmy_var = age > 65 ? \"Retired\" : \"Working\";\n\nAs for how the code you posted works, let's step through it:\n(\"Wor... | [
51,
9,
8,
7,
2,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"boolean",
"conditional_operator",
"indexing",
"python"
] | stackoverflow_0001947030_boolean_conditional_operator_indexing_python.txt |
Q:
Cant get __import__() to dynamically import a module in python - I know this cause it doesn't show up in sys.modules
I wrote a small script. It's designed to search the python directory for all available modules (whether they are installed or not), then it is supposed to check what modules are currently loaded, th... | Cant get __import__() to dynamically import a module in python - I know this cause it doesn't show up in sys.modules | I wrote a small script. It's designed to search the python directory for all available modules (whether they are installed or not), then it is supposed to check what modules are currently loaded, then it offers an option to dynamically load a module of your choice. The latter using __import__() because I am passing a s... | [
"Nascent_Notes, nice script! \nI tried loading uu (command 3) and printing the list of loaded modules (command 2) and they both seem to work fine. \nHowever, if I try to \"browse the module\" (command 4), I get the following error:\nHlpWiz>>> 4\nWhat module do you want to look more into?: uu\n\n*An error occurred ... | [
1
] | [] | [] | [
"import",
"operating_system",
"python",
"sys"
] | stackoverflow_0001969097_import_operating_system_python_sys.txt |
Q:
free Website testing tool
I am eager to know about any website testing software which is good in usability and look and feel.
Here are the main areas that software should cover.
1. Find the image size.
2. To check broken links.
3. Loading time of website.
4. Test the load with many virtual users.
5. Check for usel... | free Website testing tool | I am eager to know about any website testing software which is good in usability and look and feel.
Here are the main areas that software should cover.
1. Find the image size.
2. To check broken links.
3. Loading time of website.
4. Test the load with many virtual users.
5. Check for useless codes placed in the source ... | [
"I recommend YSlow for frontend testing.\n",
"You certainly won't find these requirements wrapped in one app - although I'm sure you could build a test script for this.\nThat been said, take a look at JMeter for load testing (very flexible app once you've get the hang of it), Xenu for link checking. There are too... | [
3,
1,
1
] | [] | [] | [
"c#",
"python",
"ruby"
] | stackoverflow_0001346503_c#_python_ruby.txt |
Q:
pylint PyQt4 error
I write a program :
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def main():
app = QApplication([])
button = QPushButton("hello?")
button.show()
app.exec_()
if __name__=="__main__":
main()
the file name is t.py,
when I run:
pylint t.py
in ubuntu9.10, pyqt4,
I got... | pylint PyQt4 error | I write a program :
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def main():
app = QApplication([])
button = QPushButton("hello?")
button.show()
app.exec_()
if __name__=="__main__":
main()
the file name is t.py,
when I run:
pylint t.py
in ubuntu9.10, pyqt4,
I got this:
pylint t.py
No co... | [
"Looks like a bug in astng. They try to read the name of a function which does not publish it (native extension func). I'd report a bug to both astng and pyqt projects. The first one would be that they should handle a no-name situation better. The second one would be that every sane extension should publish at leas... | [
1,
0
] | [] | [] | [
"pylint",
"pyqt4",
"python"
] | stackoverflow_0001962500_pylint_pyqt4_python.txt |
Q:
Shortest way to find if a string matchs an object's attribute value in a list of objects of that type in Python
I have a list with objects of x type. Those objects have an attribute name.
I want to find if a string matchs any of those object names. If I would have a list with the object names I just would do if ... | Shortest way to find if a string matchs an object's attribute value in a list of objects of that type in Python | I have a list with objects of x type. Those objects have an attribute name.
I want to find if a string matchs any of those object names. If I would have a list with the object names I just would do if string in list, so I was wondering given the current situation if there is a way to do it without having to loop over... | [
"any(obj for obj in objs if obj.name==name)\n\nNote, that it will stop looping after first match found.\n",
"Here's another\ndict( (o.name,o) for o in obj_list )[name]\n\nThe trick, though, is avoid creating a list obj_list in the first place.\nSince you know that you're going to fetch objects by the string value... | [
5,
4,
4,
1,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0001969490_algorithm_python.txt |
Q:
Problem with python-proxy for mp3-streams
I am trying to make a proxy for internet-radio in mp3. It is working fine when accessing mp3-files, but not for mp3-streams.
I suppose I am missing some very basic difference but could not find a hint.
Best regards,
wolf
My test code:
#!/usr/local/bin/python2.5
import urll... | Problem with python-proxy for mp3-streams | I am trying to make a proxy for internet-radio in mp3. It is working fine when accessing mp3-files, but not for mp3-streams.
I suppose I am missing some very basic difference but could not find a hint.
Best regards,
wolf
My test code:
#!/usr/local/bin/python2.5
import urllib;
import SocketServer, BaseHTTPServer
imp... | [
"The problem is that you are reading not mp3 stream but M3U playlist file. This file doesn't contain any mp3 data itself.\nThe content of your file is simple text:\nhttp://zlz-stream10.streamserver.ch/1/drs3/mp3_128\nhttp://glb-stream12.streamserver.ch/1/drs3/mp3_128\nhttp://zlz-stream13.streamserver.ch/1/drs3/mp3_... | [
0
] | [] | [] | [
"audio",
"mp3",
"python",
"stream"
] | stackoverflow_0001969621_audio_mp3_python_stream.txt |
Q:
Iteration WAS working in my script, now I cant get python to iterate - what happened?
Did my python ide break or something?
import sys
i = 0
sample = ("this", "is", "Annoying!")
for line in sample:
print i, line
i + 1
Now gives me...
0 this
0 is
0 Annoying!
I THOUGHT, it would give me:
1 this
2 is... | Iteration WAS working in my script, now I cant get python to iterate - what happened? | Did my python ide break or something?
import sys
i = 0
sample = ("this", "is", "Annoying!")
for line in sample:
print i, line
i + 1
Now gives me...
0 this
0 is
0 Annoying!
I THOUGHT, it would give me:
1 this
2 is
3 Annoying
I had other scripts that I was working on and it they all just broke - they a... | [
"While the other answers are correct, this is how you usually do this in python:\nsample = (\"this\", \"is\", \"Annoying!\")\n\nfor i, line in enumerate(sample):\n print i, line\n\nThe enumerate function does exactly what you want: Iterating through your tuple, while at the same time giving you (line) numbers.\n... | [
10,
7,
4,
4,
3,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0001969937_python.txt |
Q:
Is it a bad idea to design and develop a python applications backend and then once finished try to apply a GUI to it?
Is it better to do it all at once? I'm very new to wxPython and I'm thinking it would be better to write the program in a way familiar to me, then apply the wxPython gui to it after I'm satisfied w... | Is it a bad idea to design and develop a python applications backend and then once finished try to apply a GUI to it? | Is it better to do it all at once? I'm very new to wxPython and I'm thinking it would be better to write the program in a way familiar to me, then apply the wxPython gui to it after I'm satisfied with the overall design of the app. Any advice?
| [
"This is a viable approach. In fact, some programmers use it for the advantages it brings:\n\nModular non-GUI code can then be tied in with different GUIs, not just a single library\nIt can also be used for a command-line application (or a batch interface to a GUI one)\nIt can be reused for a web application\nAnd m... | [
16,
2,
1,
0,
0
] | [
"What level of interactivity do you need? If you need rich feedback and interaction, then you need an OO program model, then you can ad the GUI on top of the objects.\nIf you just have filters and functions (no real feedback, or just a results window) than a library or component model would be better.\nEither way, ... | [
-1,
-1
] | [
"python",
"wxpython"
] | stackoverflow_0001967888_python_wxpython.txt |
Q:
Python regexp find two keywords in a line
I'm having a hard time understanding this regex stuff...
I have a string like this:
<wn20schema:NounSynset rdf:about="&dn;synset-56242" rdfs:label="{saddelmageri_1}">
I want to use findall() and groups to get this:
['56242','saddelmageri']
I can match the number with som... | Python regexp find two keywords in a line | I'm having a hard time understanding this regex stuff...
I have a string like this:
<wn20schema:NounSynset rdf:about="&dn;synset-56242" rdfs:label="{saddelmageri_1}">
I want to use findall() and groups to get this:
['56242','saddelmageri']
I can match the number with something like "synset-[0-9]" and the word with so... | [
"Please see the top answer to this question. It is generally a terrible idea to parse xml with regular expressions. XML parsers are built for this purpose.\nThe quickest way to do this would probably be python's built-in minidom\n",
"Since this appears to be xml data, you would be better off using an xml parser... | [
2,
1,
1,
1
] | [] | [] | [
"findall",
"python",
"regex"
] | stackoverflow_0001970028_findall_python_regex.txt |
Q:
Enumerations in python
Duplicate:
What’s the best way to implement an ‘enum’ in Python?
Whats the recognised way of doing enumerations in python?
For example, at the moment I'm writing a game and want to be able to move "up", "down", "left" and "right". I'm using strings because I haven't yet figured out how en... | Enumerations in python |
Duplicate:
What’s the best way to implement an ‘enum’ in Python?
Whats the recognised way of doing enumerations in python?
For example, at the moment I'm writing a game and want to be able to move "up", "down", "left" and "right". I'm using strings because I haven't yet figured out how enumerations work in python, ... | [
"UPDATE 1: Python 3.4 will have a built-in well designed enum library. The values always know their name and type; there is an integer-compatible mode but the recommended default for new uses are singletons, unequal to any other object.\nUPDATE 2: Since writing this I realized the critical test for enums is serial... | [
69,
48,
17,
14,
13,
7
] | [] | [] | [
"enums",
"python"
] | stackoverflow_0001969005_enums_python.txt |
Q:
django's UserCreationForm problem
I have got problem with django's UserCreationForm. It's very strange because ween I:
view:
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render_to_response
form = UserCreationForm()
context = {'form' : form}
render_to_response('something.ht... | django's UserCreationForm problem | I have got problem with django's UserCreationForm. It's very strange because ween I:
view:
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render_to_response
form = UserCreationForm()
context = {'form' : form}
render_to_response('something.html', context)
template:
...
{% block c... | [
"You should have missed something in the code.\nWhat must had lead you to this error is:\nform = UserCreationForm\n\n{% for field in form1 %}{{ field }}{% endfor %}\n\nHere the error is that you missed the parentheses after UserCreationForm\n",
"Could you post the code of the view you're actually trying? It seems... | [
2,
1
] | [] | [] | [
"authentication",
"django",
"django_forms",
"python"
] | stackoverflow_0001970218_authentication_django_django_forms_python.txt |
Q:
Imported functioning is not iterating "TypeError: 'NoneType' object > is not iterable"... how do I make this work?
This is a snip-it of python I am working on right now - I did not list all of this code, so I apologize if something you need is "missing" - I think I can explain it well enough without the rest of it... | Imported functioning is not iterating "TypeError: 'NoneType' object > is not iterable"... how do I make this work? | This is a snip-it of python I am working on right now - I did not list all of this code, so I apologize if something you need is "missing" - I think I can explain it well enough without the rest of it...
Below there is a function main() - this is not explicitly defined in my script - it is imported from another script ... | [
"The function main prints the lines to standard output; it doesn't return anything. More precisely it returns the None object, so all_mods is None. That's the cause for \"'NoneType' object is not iterable\", because you're trying to iterate over it with for x in all_mods.\nHere's a terribly hackish solution that wi... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001970317_python.txt |
Q:
Should I use Celery or Carrot for a Django project?
I'm a little confused as to which one I should use. I think either will work, but is one better or more appropriate than the other?
http://github.com/ask/carrot/tree/master
http://github.com/ask/celery/tree/master
A:
If you need to send/receive messages to/from... | Should I use Celery or Carrot for a Django project? | I'm a little confused as to which one I should use. I think either will work, but is one better or more appropriate than the other?
http://github.com/ask/carrot/tree/master
http://github.com/ask/celery/tree/master
| [
"If you need to send/receive messages to/from AMQP message queues, use carrot.\nIf you want to run scheduled tasks on a number of machines, use celery.\nIf you're making soup, use both ;-)\n",
"May you should see this http://www.slideshare.net/idangazit/an-introduction-to-celery\n"
] | [
70,
6
] | [] | [] | [
"amqp",
"django",
"message_queue",
"python",
"rabbitmq"
] | stackoverflow_0001102254_amqp_django_message_queue_python_rabbitmq.txt |
Q:
Measure time of a function with arguments in Python
I am trying to measure the time of raw_queries(...), unsuccessfully so far. I found that I should use the timeit module. The problem is that I can't (= I don't know how) pass the arguments to the function from the environment.
Important note: Before calling raw_q... | Measure time of a function with arguments in Python | I am trying to measure the time of raw_queries(...), unsuccessfully so far. I found that I should use the timeit module. The problem is that I can't (= I don't know how) pass the arguments to the function from the environment.
Important note: Before calling raw_queries, we have to execute phase2() (environment initiali... | [
"First, never use the time module to time functions. It can easily lead to wrong conclusions. See timeit versus timing decorator for an example.\nThe easiest way to time a function call is to use IPython's %timeit command.\nThere, you simply start an interactive IPython session, call phase2(), define queries,\nand ... | [
6,
2,
2,
1,
0
] | [] | [] | [
"arguments",
"performance",
"python",
"time",
"timeit"
] | stackoverflow_0001966750_arguments_performance_python_time_timeit.txt |
Q:
Crash reporting in Python
Is there a crash reporting framework that can be used for pure Python Tkinter applications? Ideally, it should work cross-platform.
Practically speaking, this is more of 'exception reporting' since the Python interpreter itself hardly crashes.
Here's a sample crash reporter:
A:
Rather t... | Crash reporting in Python | Is there a crash reporting framework that can be used for pure Python Tkinter applications? Ideally, it should work cross-platform.
Practically speaking, this is more of 'exception reporting' since the Python interpreter itself hardly crashes.
Here's a sample crash reporter:
| [
"Rather than polluting your code with try..except everywhere, you should just implement your own except hook by setting sys.excepthook. Here is an example:\nimport sys\nimport traceback\n\ndef install_excepthook():\n def my_excepthook(exctype, value, tb):\n s = ''.join(traceback.format_exception(exctype, ... | [
7,
2
] | [] | [] | [
"crash_reports",
"python",
"tkinter"
] | stackoverflow_0001964336_crash_reports_python_tkinter.txt |
Q:
Django specific sql query
how can I execute such query in django:
SELECT * FROM keywords_keyword WHERE id not in (SELECT keyword_id FROM sites_pagekeyword)
In the latest SVN release we can use:
keywords = Keyword.objects.raw('SELECT * FROM keywords_keyword WHERE id not in (SELECT keyword_id FROM sites_pagekeyword... | Django specific sql query | how can I execute such query in django:
SELECT * FROM keywords_keyword WHERE id not in (SELECT keyword_id FROM sites_pagekeyword)
In the latest SVN release we can use:
keywords = Keyword.objects.raw('SELECT * FROM keywords_keyword WHERE id not in (SELECT keyword_id FROM sites_pagekeyword)')
But RawQuerySet doesn't su... | [
"\nKeyword.objects.exclude(id__in=PageKeyword.objects.all()\n\nKeyword.objects.exclude(id__in=PageKeyword.objects.values('keyword_id'))\n\nFor future reference, exclude is documented here.\n\nEdit: Yes, you are right; I corrected my answer. See above.\n\nEdit: Even more readable:\nKeyword.objects.exclude(pagekeywor... | [
8,
1
] | [] | [] | [
"django",
"django_models",
"python",
"sql"
] | stackoverflow_0001970718_django_django_models_python_sql.txt |
Q:
Open a new browser window from a Python script in Google App Engine
A Python script at Google App Engine fetches data into a HTML page.
What is the best way to open a new browser window from the script or HTML page?
JavaScript doesn't work.
A:
The only way to automatically open a new window in a browser is Java... | Open a new browser window from a Python script in Google App Engine | A Python script at Google App Engine fetches data into a HTML page.
What is the best way to open a new browser window from the script or HTML page?
JavaScript doesn't work.
| [
"The only way to automatically open a new window in a browser is JavaScript (using window.open()).\nIf you can't use JavaScript, you can simply add a link to your html page with a _blank target that will open a new window (or sometimes a new tab if the user has configured this browser to do so) :\n<a href=\"newPage... | [
3,
0,
0,
-1
] | [] | [] | [
"google_app_engine",
"javascript",
"open_source",
"python"
] | stackoverflow_0001930511_google_app_engine_javascript_open_source_python.txt |
Q:
How do I sudo the current process?
Is it possible to use a sudo frontend (like gksudo) to elevate the privileges of the current process? I know I can do the following:
sudo cat /etc/passwd-
But I'm interested in doing this:
sudo-become-root # magic function/command
cat /etc/passwd-
I'm writing in Python. My us... | How do I sudo the current process? | Is it possible to use a sudo frontend (like gksudo) to elevate the privileges of the current process? I know I can do the following:
sudo cat /etc/passwd-
But I'm interested in doing this:
sudo-become-root # magic function/command
cat /etc/passwd-
I'm writing in Python. My usecase is that I have a program that runs... | [
"Aptitude has a \"become root\" option. You may wish to see what the author did there.\n",
"If you want to deal cleanly with administrative rights inside a program, you might want to use PolicyKit rather than sudo, depending on the OS you plan to run your program on.\nFor PolicyKit for Python, see python-slip.\nO... | [
3,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"gksudo",
"linux",
"python",
"root"
] | stackoverflow_0001970329_gksudo_linux_python_root.txt |
Q:
how to "export CFLAGS='my -flags -here' from python script
I'm writing a python program that needs to set the environment CFLAGS as needed.
I'm using the subprocess module to perform some operations, but, I'm not sure this is the correct way of doing this.
The script will first set the CFLAGS and then compile some... | how to "export CFLAGS='my -flags -here' from python script | I'm writing a python program that needs to set the environment CFLAGS as needed.
I'm using the subprocess module to perform some operations, but, I'm not sure this is the correct way of doing this.
The script will first set the CFLAGS and then compile some code, so the cflags need to stay put while the code is compiled... | [
"You can do this without modifying the python process's environment.\n# Make a copy of the environment and modify that.\nmyenv = dict(os.environ)\nmyenv[\"CXXFLAGS\"] = \"-DFOO\"\n\n# Pass the modified environment to the subprocess.\nsubprocess.check_call([\"make\", \"install\"], env=myenv)\n\nSee the documentation... | [
1,
0
] | [] | [] | [
"compiler_flags",
"python"
] | stackoverflow_0001971344_compiler_flags_python.txt |
Q:
convert byte array to string without interpreting the bytes?
I have a GSM date/time stamp from a PDU encoded SMS it is formatted as so
\x90,\x21,\x51,\x91,\x40,\x33
format yy,mm,dd,hh,mm,ss
I have read them from a binary file into a byte array. I want to convert them to a string but without doing any decoding I wa... | convert byte array to string without interpreting the bytes? | I have a GSM date/time stamp from a PDU encoded SMS it is formatted as so
\x90,\x21,\x51,\x91,\x40,\x33
format yy,mm,dd,hh,mm,ss
I have read them from a binary file into a byte array. I want to convert them to a string but without doing any decoding I want to end up with a string that contains 902151914033. I then need... | [
"This should get you started:\n>>> s = b'\\x90\\x21\\x51\\x91\\x40\\x33'\n>>> lst = [hex(z)[2:] for z in s]\n>>> lst\n['90', '21', '51', '91', '40', '33']\n\n>>> string = ''.join(hex(z)[3:1:-1] for z in s)\n>>> string\n'091215190433'\n\n",
"To convert to hex:\nhexdata = ''.join('%02x' % ord(byte) for byte in bind... | [
5,
5,
1,
0,
0
] | [] | [] | [
"bytearray",
"decode",
"python"
] | stackoverflow_0001916928_bytearray_decode_python.txt |
Q:
Python, Huge Iteration Performance Problem
I'm doing an iteration through 3 words, each about 5 million characters long, and I want to find sequences of 20 characters that identifies each word. That is, I want to find all sequences of length 20 in one word that is unique for that word. My problem is that the code ... | Python, Huge Iteration Performance Problem | I'm doing an iteration through 3 words, each about 5 million characters long, and I want to find sequences of 20 characters that identifies each word. That is, I want to find all sequences of length 20 in one word that is unique for that word. My problem is that the code I've written takes an extremely long time to run... | [
"def slices(seq, length, prefer_last=False):\n unique = {}\n if prefer_last: # this doesn't have to be a parameter, just choose one\n for start in xrange(len(seq) - length + 1):\n unique[seq[start:start+length]] = start\n else: # prefer first\n for start in xrange(len(seq) - length, -1, -1):\n un... | [
10,
0,
0,
0
] | [] | [] | [
"bioinformatics",
"iteration",
"python"
] | stackoverflow_0001941712_bioinformatics_iteration_python.txt |
Q:
In python is there any way I can obtain the arguments passed to a function as object?
I don't want to use *args or **kwargs since I can't change function declaration.
For example:
def foo( a, b, c ) """Lets say values passed to a, b and c are 1,2 and 3 respectively"""
...
...
""" I would like to generate ... | In python is there any way I can obtain the arguments passed to a function as object? | I don't want to use *args or **kwargs since I can't change function declaration.
For example:
def foo( a, b, c ) """Lets say values passed to a, b and c are 1,2 and 3 respectively"""
...
...
""" I would like to generate an object preferably a dictionary such as {'a':1, 'b':2, 'c':3} """
...
...
Can anyo... | [
"If you can't change the function \"declaration\" (why not?) but you can change the contents of the function, then just create the dictionary as you want it:\ndef foo(a, b, c):\n mydict = {'a': a, 'b': b, 'c': c}\n\nIf that doesn't work, I think you need a better explanation of what you want and what the constra... | [
5,
1,
1,
0
] | [] | [] | [
"arguments",
"function",
"object",
"python"
] | stackoverflow_0001966715_arguments_function_object_python.txt |
Q:
Start and capture GUI's output from same Python script and transfer variables?
I have to start a GUI from an existing Python application. The GUI is actually separate Python GUI that can run alone. Right now, I am starting the GUI using something like:
res=Popen(['c:\python26\pythonw.exe',
... | Start and capture GUI's output from same Python script and transfer variables? | I have to start a GUI from an existing Python application. The GUI is actually separate Python GUI that can run alone. Right now, I am starting the GUI using something like:
res=Popen(['c:\python26\pythonw.exe',
full_filename,
str(RESULTs),
str(context... | [
"From the sounds of it, unless Nazarius' excellent suggestion for a first step is infeasible, a program like pyWinAuto would do what you need. We use it to control our own wxPython-based application for use in automated testing, with a Python script controlling the program by entering text into GUI fields, clickin... | [
1,
0
] | [] | [] | [
"automation",
"python",
"subprocess",
"user_interface"
] | stackoverflow_0001972176_automation_python_subprocess_user_interface.txt |
Q:
MySQLdb connection issue
I am writing a server which provide a service by query MySQL database.
Everything goes fine, except when run one or two days the connection will go away.
The error code is (2600, MySQL has gone away)
I try to wrap the cursor object by:
def cursor(self):
try:
return self.con... | MySQLdb connection issue | I am writing a server which provide a service by query MySQL database.
Everything goes fine, except when run one or two days the connection will go away.
The error code is (2600, MySQL has gone away)
I try to wrap the cursor object by:
def cursor(self):
try:
return self.connection.cursor()
except:
... | [
"@duffymo's idea about not keeping connections open too long is viable, but so is your original idea about catching the exception and retrying (I'm not so sure about which one is better).\nSince the exception is raised by cursor.execute, that's where you must catch and remedy it (by renewing the connection and curs... | [
2,
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0001972562_mysql_python.txt |
Q:
Python-Challenge Level 3
The questions is: One small letter, surrounded by EXACTLY three big bodyguards on each of its sides.
I wrote this code and get an answer. I thougt it would be correct, but it doesn't work. Can anybody help me? My answer: KWGtIDC
import urllib, sys, string
from string import maketrans
bbb ... | Python-Challenge Level 3 | The questions is: One small letter, surrounded by EXACTLY three big bodyguards on each of its sides.
I wrote this code and get an answer. I thougt it would be correct, but it doesn't work. Can anybody help me? My answer: KWGtIDC
import urllib, sys, string
from string import maketrans
bbb = 0
f = urllib.urlopen("http:... | [
"A couple of points:\n\nYou need to operate on the comment block in the source of the html page, not the entire page itself. I'm not sure if the rest of the page makes a difference, but still. I'd copy the comment block to another file locally, and go from there.\nThe title of the page is \"re\". Does that ring any... | [
8,
4
] | [] | [] | [
"python"
] | stackoverflow_0001972693_python.txt |
Q:
python permission error
I have a file a.txt in Mac OS, which has write perms to everybody:
sh-3.2# ls -hal a.txt
-rw-rw-rw- 1 root wheel 0B Dec 8 11:34 a.txt
sh-3.2# pwd
/var/root
however in python it gives me an error:
>>> fob=open("/var/root/a.txt","w")
Traceback (most recent call last):
File "<pyshe... | python permission error | I have a file a.txt in Mac OS, which has write perms to everybody:
sh-3.2# ls -hal a.txt
-rw-rw-rw- 1 root wheel 0B Dec 8 11:34 a.txt
sh-3.2# pwd
/var/root
however in python it gives me an error:
>>> fob=open("/var/root/a.txt","w")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
... | [
"I'm going to guess that the permissions on the /var/root directory are too strict for the user you are running as.\n",
"It's likely that you don't have write permission on the directory that the file is in.\n",
"Just a wild guess: since the file already exists there, is it possible that opening with mode \"w+\... | [
2,
1,
0
] | [] | [] | [
"permissions",
"python"
] | stackoverflow_0001868213_permissions_python.txt |
Q:
Get the position of the windows start menu
I'm writing an app in Python that automatically moves stuff around. How do I get the position of the windows start menu bar, so I can account for it in my calculations?
A:
When you ask for the work area, the taskbar area is automatically excluded.
System.Parameters.... | Get the position of the windows start menu | I'm writing an app in Python that automatically moves stuff around. How do I get the position of the windows start menu bar, so I can account for it in my calculations?
| [
"When you ask for the work area, the taskbar area is automatically excluded. \nSystem.Parameters.WorkArea\n\nor Use interop to \nSystemParametersInfo(SPI_GETWORKAREA, ...)` \n\nand you are done.\n",
"Ah, found it. GetMonitorInfo: http://msdn.microsoft.com/en-us/library/dd144901(VS.85).aspx . Here is an example... | [
1,
0,
0
] | [] | [] | [
"python",
"pywin32",
"winapi"
] | stackoverflow_0001972709_python_pywin32_winapi.txt |
Q:
delete a line based on logic
I have a file where i have multiple records with such data
F00DY4302B8JRQ rank=0000030 x=800.0 y=1412.0 length=89
now i want to search for the line where if i find length<=50 then delete this line and the next line in the file and write to another file.
Thanks everyone
A:
From... | delete a line based on logic | I have a file where i have multiple records with such data
F00DY4302B8JRQ rank=0000030 x=800.0 y=1412.0 length=89
now i want to search for the line where if i find length<=50 then delete this line and the next line in the file and write to another file.
Thanks everyone
| [
"From the top of my head:\nfor every line in file\nsplit by spaces\nget last token\nsplit by equal\nverify length\nwrite line to another file\ndelete line and the next\n\nHope this is what you need to start working.\n",
"Assuming Python 2.6 (let us know if it's another version you need!), and that you want to ski... | [
1,
1,
0
] | [] | [] | [
"python",
"text_processing"
] | stackoverflow_0001972817_python_text_processing.txt |
Q:
Apache: Download files getting a CR inserted before every LF (even spreadsheets)
I am using Apache 2.2.14 and Python 2.6 for CGI on Windows XP. Files sent through CGI get corrupted. A CR gets inserted before every LF. Firefox, IE, and Curl clients give the same result. The file is the correct size, but CR's are... | Apache: Download files getting a CR inserted before every LF (even spreadsheets) | I am using Apache 2.2.14 and Python 2.6 for CGI on Windows XP. Files sent through CGI get corrupted. A CR gets inserted before every LF. Firefox, IE, and Curl clients give the same result. The file is the correct size, but CR's are inserted throughout, and the data is shifted down and truncated. I can look at the f... | [
"Use msvcrt.setmode(1, os.O_BINARY) (after you write the headers and sys.stdout.flush them) to set standard output to binary mode -- poor Apache is innocent, it's a Windows thing;-).\n"
] | [
4
] | [] | [] | [
"apache",
"cgi",
"python"
] | stackoverflow_0001972849_apache_cgi_python.txt |
Q:
How to use pyparsing to parse and hash strings enclosed by special characters?
The majority of pyparsing examples that I have seen have dealt with linear expressions.
a = 1 + 2
I'd like to parse mediawiki headlines, and hash them to their sections.
e.g.
Introduction goes here
==Hello==
foo
foo
===World===
bar
bar
... | How to use pyparsing to parse and hash strings enclosed by special characters? | The majority of pyparsing examples that I have seen have dealt with linear expressions.
a = 1 + 2
I'd like to parse mediawiki headlines, and hash them to their sections.
e.g.
Introduction goes here
==Hello==
foo
foo
===World===
bar
bar
Dict would look like:
{'Introduction':'Whoot introduction goes here', 'Hello':"foo\... | [
"Did you miss this wiki-like language parser in the pyParsing web site examples?\nh2 = QuotedString(\"==\")\n\n",
"Also, this format is not unlike a .INI file:\n[section1]\na = 1\nb = 3\n[section2]\nblah=a\n\nWhich can be parsed into a nested dictionary using this example code.\n"
] | [
3,
1
] | [] | [] | [
"dictionary",
"mediawiki",
"parsing",
"pyparsing",
"python"
] | stackoverflow_0001972781_dictionary_mediawiki_parsing_pyparsing_python.txt |
Q:
Python code optimization
I'm building a online font previewer, with following architecture. I wrapped preview creation function in a standalone .py file and making system calls to it in a Django view in order to run them in parallel and maximum performance on multi-core CPU system.
preview.py
....
def make_preview... | Python code optimization | I'm building a online font previewer, with following architecture. I wrapped preview creation function in a standalone .py file and making system calls to it in a Django view in order to run them in parallel and maximum performance on multi-core CPU system.
preview.py
....
def make_preview(text, fontfile, imagefile, fo... | [
"You should look into the multiprocessing module. You could create a pool of workers equal to your number of CPU cores and then send jobs to your make_preview function.\n",
"If this is a font chooser, where you can reasonably display the same text every time you show it, you can pre-render the font samples and s... | [
2,
0
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0001972699_optimization_python.txt |
Q:
Interpolating a scalar field in a 3D space
I have a 3D space (x, y, z) with an additional parameter at each point (energy), giving 4 dimensions of data in total.
I would like to find a set of x, y, z points which correspond to an iso-energy surface found by interpolating between the known points.
The spacial mesh ... | Interpolating a scalar field in a 3D space | I have a 3D space (x, y, z) with an additional parameter at each point (energy), giving 4 dimensions of data in total.
I would like to find a set of x, y, z points which correspond to an iso-energy surface found by interpolating between the known points.
The spacial mesh has constant spacing and surrounds the iso-energ... | [
"There are quite a few options here...\nIn order to get your energy into your mesh, you'll need to use some form of interpolation. Shepard's method is a common, and reasonably simple, method to implement, and tends to work well if your data distribution is reasonable.\nOnce you have that done, you'll need to do so... | [
8,
2,
1
] | [] | [] | [
"algorithm",
"interpolation",
"python"
] | stackoverflow_0001972172_algorithm_interpolation_python.txt |
Q:
Why does this happen with Python's list.sort?
Given the code:
a=['a','b','c','d']
b=a[::-1]
print b
c=zip(a,b)
print c
c.sort(key=lambda x:x[1])#
print c
It prints:
['d', 'c', 'b', 'a']
[('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')]
[('d', 'a'), ('c', 'b'), ('b', 'c'), ('a', 'd')]
Why does [('a', 'd'), ('b', '... | Why does this happen with Python's list.sort? | Given the code:
a=['a','b','c','d']
b=a[::-1]
print b
c=zip(a,b)
print c
c.sort(key=lambda x:x[1])#
print c
It prints:
['d', 'c', 'b', 'a']
[('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')]
[('d', 'a'), ('c', 'b'), ('b', 'c'), ('a', 'd')]
Why does [('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')] change to [('d', 'a')... | [
"because x[1] means second\nuse\nc.sort(key=lambda x:x[0])\n\n",
"You've sorted c using the second item as the key, and the second item does indeed go up, just as you asked for it to go up. What's so surprising?!\n",
"from operator import itemgetter \nc.sort(key=itemgetter(0))\n\n",
"As the others have sa... | [
7,
3,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001973164_python.txt |
Q:
Why does it do this ? if - __name__ == '__main__'
Duplicate of:
What does if __name__== "__main__" do?
Consider this code:
if __name__ == '__main__':
import pdb
pdb.run("interact()\n")
What does the following line mean?
if(__name__=='__main__')
I fainted.
A:
__name__ is a variable automatically set i... | Why does it do this ? if - __name__ == '__main__' |
Duplicate of:
What does if __name__== "__main__" do?
Consider this code:
if __name__ == '__main__':
import pdb
pdb.run("interact()\n")
What does the following line mean?
if(__name__=='__main__')
I fainted.
| [
"__name__ is a variable automatically set in an executing python program. If you import your module from another program, __name__ will be set to the name of the module. If you run your program directly, __name__ will be set to __main__. \nTherefore, if you want some things to happen only if you're running your pro... | [
14,
10,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0001973373_python.txt |
Q:
How can I insert a new Event for non primary Calendar? Using python gdata
def addEvent(calendar_service):
event = gdata.calendar.CalendarEventEntry()
event.content = atom.Content(text='Tennis with John 30.12.2009 15:00-16:00')
event.quick_add = gdata.calendar.QuickAdd(value='true')
new_event = cale... | How can I insert a new Event for non primary Calendar? Using python gdata | def addEvent(calendar_service):
event = gdata.calendar.CalendarEventEntry()
event.content = atom.Content(text='Tennis with John 30.12.2009 15:00-16:00')
event.quick_add = gdata.calendar.QuickAdd(value='true')
new_event = calendar_service.InsertEvent(event, '/calendar/feeds/default/private/full')
This w... | [
"Ok, i found the url in a_calendar.content.src it show like \"http://www.google.com/calendar/feeds/\"+id+\"/private/full\"\ndef addEvent(calendar_service):\n event = gdata.calendar.CalendarEventEntry()\n event.content = atom.Content(text='Tennis with John 30.12.2009 15:00-16:00')\n event.quick_add = gdata.... | [
3,
0
] | [] | [] | [
"django",
"gdata",
"gdata_api",
"python"
] | stackoverflow_0001972096_django_gdata_gdata_api_python.txt |
Q:
django:error with the custom inclusiong_tag, error info:Invalid block tag
I'm trying to write a custom inclusion_tag in django.
Following the example on http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
I'm just writing
from django import template
from libmas import models
register = template.Libr... | django:error with the custom inclusiong_tag, error info:Invalid block tag | I'm trying to write a custom inclusion_tag in django.
Following the example on http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
I'm just writing
from django import template
from libmas import models
register = template.Library()
@register.inclusion_tag('records.html')
def display_records(book_id):
... | [
"The problem lies in your template. Its calling {% libmas_tags %}. Have you created template tags called libmas_tags? If so you might need to change it to \n{% load libmas_tags %}\n\n",
"What is libmas_tags? The tag you have defined is called display_records, and that's what you should be calling in your template... | [
3,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001972844_django_python.txt |
Q:
What arguments does Python sort() function have?
Is there any other argument than key, for example: value?
A:
Arguments of sort and sorted
Both sort and sorted have three keyword arguments: cmp, key and reverse.
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
sorted(it... | What arguments does Python sort() function have? | Is there any other argument than key, for example: value?
| [
"Arguments of sort and sorted\nBoth sort and sorted have three keyword arguments: cmp, key and reverse.\nL.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\ncmp(x, y) -> -1, 0, 1\n\nsorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list\n\nUsing key and reverse is preferred, becau... | [
41,
3,
1
] | [] | [] | [
"key",
"python",
"python_2.x",
"python_3.x",
"sorting"
] | stackoverflow_0001972672_key_python_python_2.x_python_3.x_sorting.txt |
Q:
Infinite loop error in python code
I am learning how to code through this book called "Headfirst Programming", which I am really enjoying so far.
One of the projects in the book uses the following code:
def save_transaction(price, credit_card, description):
file = open("transactions.txt", "a")
file.write("%s%07d%... | Infinite loop error in python code | I am learning how to code through this book called "Headfirst Programming", which I am really enjoying so far.
One of the projects in the book uses the following code:
def save_transaction(price, credit_card, description):
file = open("transactions.txt", "a")
file.write("%s%07d%s\n" % (credit_card, price * 100, descri... | [
"As you've probably read, Python uses indentation to identify blocks of code.\nSo...\nwhile running:\n option = 1\n for choice in items:\n print(str(option) + \". \" + choice)\n option = option + 1\n\nwill run forever, and\nprint(str(option) + \". Quit\"))\nchoice = int(input(\"choose an o... | [
8,
0,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0001973822_loops_python.txt |
Q:
Image library with advanced text effects?
What would be the best Python library to use when producing text-based images requiring things such as leading, kerning, outlines, drop-shadows, etc?
I've worked with PIL before for resizing images, but the methods for working with text seem rather limited. Is there a bett... | Image library with advanced text effects? | What would be the best Python library to use when producing text-based images requiring things such as leading, kerning, outlines, drop-shadows, etc?
I've worked with PIL before for resizing images, but the methods for working with text seem rather limited. Is there a better alternative?
| [
"What you seem to want to do is exactly what LaTeX was designed for. With plasTeX, you can convert LaTeX markup to an image. Here's an example of what you can do with this (from the plasTeX documentation) \n(source: sourceforge.net)\n. \nNotice the shadows and text effects.\n",
"Cairo is very capable, and there a... | [
1,
0
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0001972044_python_python_imaging_library.txt |
Q:
python - problem int/string and hash/array
f = open('transaction.log','r')
ClerkHash = dict()
arr = [0,0]
for line in f:
Tdate = line[0:12]
AccountKey = line[12:50]
TransType = line[22:2]
ClerkKey = line[24:10]
CurrencyCode = line[34:2]
Amount = line[36:45]
pri... | python - problem int/string and hash/array | f = open('transaction.log','r')
ClerkHash = dict()
arr = [0,0]
for line in f:
Tdate = line[0:12]
AccountKey = line[12:50]
TransType = line[22:2]
ClerkKey = line[24:10]
CurrencyCode = line[34:2]
Amount = line[36:45]
print line
print '\n'
print AccountKey
... | [
"Here is few issue I seen so far\nAmount = line[36:45]\n\nshould be\nAmount = int(line[36:45])\n\nand \nClerkHash[ClerkKey+AccountKey] = arr[0,0]\n\nshould be\nClerkHash[ClerkKey+AccountKey] = [0,0]\n\n",
"Check your slice intervals! The second argument is another index, NOT the number of steps to tak... | [
2,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001974434_python_string.txt |
Q:
Python sched alternative to cancel all events
I'm looking for an alternative to the sched module which would allow me to cancel all events at any time. sched only allows to cancel single events by id (which is returned from the scheduler when an event is scheduled).
Any pointers to Python alternatives to sched wou... | Python sched alternative to cancel all events | I'm looking for an alternative to the sched module which would allow me to cancel all events at any time. sched only allows to cancel single events by id (which is returned from the scheduler when an event is scheduled).
Any pointers to Python alternatives to sched would be appreciated.
Thanks
Toni p
| [
"In python 2.6, there is a read-only attribute called queue returning a list of upcoming events. So this will cancel all events:\ns = sched.scheduler(time.time, time.sleep)\nmap(s.cancel, s.queue)\n\nUpdate for Python 3:\nPython 3 map() returns the iterator. Therefore, the object must be converted to the list.\ns =... | [
12
] | [] | [] | [
"events",
"python"
] | stackoverflow_0001974571_events_python.txt |
Q:
django double "extends", problem with login
Hi:) I have got a small problem with template double extends system. I have got a scheme:
base.html ---> index.html ---> something.html
When I log in to the site I have got access to all invisible blocks (invisible blocks for anonymous users) like:
{% if user.is_superus... | django double "extends", problem with login | Hi:) I have got a small problem with template double extends system. I have got a scheme:
base.html ---> index.html ---> something.html
When I log in to the site I have got access to all invisible blocks (invisible blocks for anonymous users) like:
{% if user.is_superuser %}
blabla
{% endif %}
So "blabla" is visib... | [
"Are you passing the request context to render_to_response (or HttpResponse)?\nInformation about logged in user must be stored in the context (see documentation), and you have to do it explicitly.\nGeneric views automatically do it, but if you are using your own view for something.html, with a direct call to render... | [
1
] | [] | [] | [
"authentication",
"django",
"python"
] | stackoverflow_0001974478_authentication_django_python.txt |
Q:
Is there a python-equivalent of the unix "file" utility?
I want to have different behavior in a python script, depending on the type of file. I cannot use the filename extension as it may not be present or misleading. I could call the file utility and parse the output, but I would rather use a python builtin for p... | Is there a python-equivalent of the unix "file" utility? | I want to have different behavior in a python script, depending on the type of file. I cannot use the filename extension as it may not be present or misleading. I could call the file utility and parse the output, but I would rather use a python builtin for portability.
So is there anything in python that uses heuristic... | [
"\npython-magic\npymagic\n\nProbably others as well. \"magic\" is the magic keyword to search for. ;-)\n"
] | [
18
] | [] | [] | [
"python",
"unix"
] | stackoverflow_0001974724_python_unix.txt |
Q:
how to distribute python app with glade GUI?
I'm trying to distribute this app that I wrote in python. The application consists of 2 python scripts. 2 .glade files and 1 .png file.
Here is my dir structure on this project
vasm/
vasmcc.py
src/
vasm.py
gui/
vasm.glade
vasmset.glade
... | how to distribute python app with glade GUI? | I'm trying to distribute this app that I wrote in python. The application consists of 2 python scripts. 2 .glade files and 1 .png file.
Here is my dir structure on this project
vasm/
vasmcc.py
src/
vasm.py
gui/
vasm.glade
vasmset.glade
logo.png
vasmcc is just the python script f... | [
"You should take a look at distutils. You can tell it to install all kinds of files, not just the source code itself. For the user, installing your program then comes down to\n$ python setup.py install\n\nand it's even pretty easy to, say, create RPM packages with distutils.\n"
] | [
2
] | [] | [] | [
"distutils",
"glade",
"python",
"user_interface"
] | stackoverflow_0001974733_distutils_glade_python_user_interface.txt |
Q:
Debug history of variable changing in python
I need magic tool, that helps me to understand where one my problem variable is changed in the code.
I know about perfect tool:
pdb.set_trace()
and I need something similar format, but about only one variable changing history.
For example, my current problem is strang... | Debug history of variable changing in python | I need magic tool, that helps me to understand where one my problem variable is changed in the code.
I know about perfect tool:
pdb.set_trace()
and I need something similar format, but about only one variable changing history.
For example, my current problem is strange value of context['request'] variable inside Djan... | [
"I'm not really familiar with django, so your mileage may vary. In general, you can override the __setitem__ method on objects to capture item assignment. However, this doesn't work on dictionaries, only on user-created classes, so first of all it depends on what this context object is.\nAs I get from a short look ... | [
2
] | [] | [] | [
"debugging",
"django",
"python"
] | stackoverflow_0001974997_debugging_django_python.txt |
Q:
epoch timestamp converter with millennia range, python
is there an epoch time converter that can deal with millennia?
time.gmtime(1000 * 365 * 24 * 60 * 60)
throws
ValueError: timestamp out of range for platform time_t
A:
Yes, at least on Windows (using Windows 7 here). What platform are you using?
Python 2.6... | epoch timestamp converter with millennia range, python | is there an epoch time converter that can deal with millennia?
time.gmtime(1000 * 365 * 24 * 60 * 60)
throws
ValueError: timestamp out of range for platform time_t
| [
"Yes, at least on Windows (using Windows 7 here). What platform are you using?\nPython 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32\n>>> time.gmtime(1000*365*24*60*60)\ntime.struct_time(tm_year=2969, tm_mon=5, tm_mday=3, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=123, tm_is... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0001975524_python.txt |
Q:
Is there a platform agnostic implementation of time.gmtime?
on google appengine (http://shell.appspot.com/):
>>> time.gmtime(1000*365*24*60*60)
(2969, 5, 3, 0, 0, 0, 2, 123, 0)
on macosx:
>>> time.gmtime(1000*365*24*60*60)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: timest... | Is there a platform agnostic implementation of time.gmtime? | on google appengine (http://shell.appspot.com/):
>>> time.gmtime(1000*365*24*60*60)
(2969, 5, 3, 0, 0, 0, 2, 123, 0)
on macosx:
>>> time.gmtime(1000*365*24*60*60)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: timestamp out of range for platform time_t
is there a platform agnosti... | [
"The time module is defined to be platform-specific.\n\nThe functions in this module do not handle dates and times before the epoch or far in the future. The cut-off point in the future is determined by the C library; for Unix, it is typically in 2038.\n\nYou can use the datetime type without timezone info (\"naive... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0001975693_python.txt |
Q:
django, runserver_plus - admin media files served from wrong path
The configuration below works fine on my remote host (same dir structure, same django), all admin media are served properly
settings
MEDIA_ROOT = '%s/static/' % FS_ROOT
STATIC_DOC_ROOT = '%s/static/' % FS_ROOT
MEDIA_URL = '/static/'
ADMIN_MEDIA_PREF... | django, runserver_plus - admin media files served from wrong path | The configuration below works fine on my remote host (same dir structure, same django), all admin media are served properly
settings
MEDIA_ROOT = '%s/static/' % FS_ROOT
STATIC_DOC_ROOT = '%s/static/' % FS_ROOT
MEDIA_URL = '/static/'
ADMIN_MEDIA_PREFIX = '%smedia/' % MEDIA_URL
urls
(r'^admin/', include(admin.site.urls)... | [
"There are two solutions:\n\nYou can either set a hostname in ADMIN_MEDIA_PREFIX as suggested in this answer.\nOr you can start the development server with the --adminmedia parameter as described in the django documentation.\n\n"
] | [
1
] | [] | [] | [
"django",
"django_admin",
"file",
"media",
"python"
] | stackoverflow_0001974697_django_django_admin_file_media_python.txt |
Q:
Does Google Webapp framework for Google App Engine maintain a link to the database?
1) When a script gets data from the database using the db.Model.get_element_by_id("id") method, what id does it refer to, and how can you get it from the database.
2) If you get a result using this method, does that result maintain... | Does Google Webapp framework for Google App Engine maintain a link to the database? | 1) When a script gets data from the database using the db.Model.get_element_by_id("id") method, what id does it refer to, and how can you get it from the database.
2) If you get a result using this method, does that result maintain a link to the database so that any changes to the result are reflected on the database? ... | [
"As Jonathan Feinberg suggested, this is answered in the Google App Engine tutorial. The relevant piece of the tutorial is found here: http://code.google.com/appengine/docs/python/gettingstarted/usingdatastore.html\nOn that page, this text specifically answers your question about \"how would you update an entry in... | [
2,
1
] | [] | [] | [
"database",
"google_app_engine",
"python",
"reference",
"web_applications"
] | stackoverflow_0001976254_database_google_app_engine_python_reference_web_applications.txt |
Q:
TypeError: can't multiply sequence by non-int of type 'float'
I am a noob to Python and have not had any luck figuring this out. I want to be able to keep the tax variable in the code so it would be easily updated should it change. I have experimented with different means but was only able to get it to skip the pr... | TypeError: can't multiply sequence by non-int of type 'float' | I am a noob to Python and have not had any luck figuring this out. I want to be able to keep the tax variable in the code so it would be easily updated should it change. I have experimented with different means but was only able to get it to skip the print tax line and print the same values for the total and subtotal. ... | [
"It would help if you provide the back-trace for the error. I ran your code, and got this back-trace:\nTraceback (most recent call last):\n File \"t.py\", line 13, in <module>\n print 'The amount of sales tax is: ' '$%.2f' % sum(items_count) * tax\nTypeError: can't multiply sequence by non-int of type 'float'\... | [
5,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001976467_python.txt |
Q:
semantic markup for Python's difflib.HtmlDiff
It appears Python's difflib.HtmlDiff, rather than using INS and DEL, uses SPAN elements with custom classes:
python -c 'import difflib; txt1 = "lorem ipsum\ndolor sit amet".splitlines(); txt2 = "lorem foo isum\ndolor amet".splitlines(); d = difflib.HtmlDiff(); print d.... | semantic markup for Python's difflib.HtmlDiff | It appears Python's difflib.HtmlDiff, rather than using INS and DEL, uses SPAN elements with custom classes:
python -c 'import difflib; txt1 = "lorem ipsum\ndolor sit amet".splitlines(); txt2 = "lorem foo isum\ndolor amet".splitlines(); d = difflib.HtmlDiff(); print d.make_table(txt1, txt2)'
Before I go about fixing t... | [
"This script by Aaron Swartz uses difflib to output ins/del.\n",
"The python bug tracker is here: http://bugs.python.org/\nThere's no open bug on this issue, which I guess is because most people would not care what sort of html it is as long as it works. If it's important to you, file a bug and submit a patch.\n"... | [
3,
2
] | [] | [] | [
"diff",
"python",
"semantics"
] | stackoverflow_0000745600_diff_python_semantics.txt |
Q:
Piecing together Django views
Is it good practice to treat individual app views as a blocks of HTML that can be pieced together to form a larger site? If not, what is the best way to reuse app views from project to project, assuming each one uses a different set of templates?
A:
A general good practice to define... | Piecing together Django views | Is it good practice to treat individual app views as a blocks of HTML that can be pieced together to form a larger site? If not, what is the best way to reuse app views from project to project, assuming each one uses a different set of templates?
| [
"A general good practice to define views with a template_name kwarg. This allows a the default template to be overridden. This is common in generic views.\n#my reusable view\ndef list_items(request, template_name=\"items.html\"):\n items=Item.objects.all()\n return render_to_response(template_name,\n {'items':... | [
2,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001975769_django_python.txt |
Q:
Retrieving ORM properties with SQLAlchemy
I have three tables (users, articles, and tags) defined in SQLAlchemy and mapped with orm.mapper(). As you can see below, I'm adding a property "author" to each article which ties that article to the user that created it.
orm.mapper(User, t_users)
orm.mapper(Tag, t_tags)
... | Retrieving ORM properties with SQLAlchemy | I have three tables (users, articles, and tags) defined in SQLAlchemy and mapped with orm.mapper(). As you can see below, I'm adding a property "author" to each article which ties that article to the user that created it.
orm.mapper(User, t_users)
orm.mapper(Tag, t_tags)
orm.mapper(Article, t_articles, properties={
... | [
"Considered eagerloading, as covered in Working with Related Objects?\nYour join is also funky. You're mixing the ORM with the SQL-toolkit, so you're getting row-objects and not mapped objects back. See Querying with Joins\n"
] | [
3
] | [] | [] | [
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0001977008_orm_python_sqlalchemy.txt |
Q:
security question: Changing system password via python
I'm working on a project aimed at system administration for a linux installation.
I need to perform some tasks like change the user password...
I was planning to use the subprocess module for this.
I'm concerned about security so, what are the 'best practices'... | security question: Changing system password via python | I'm working on a project aimed at system administration for a linux installation.
I need to perform some tasks like change the user password...
I was planning to use the subprocess module for this.
I'm concerned about security so, what are the 'best practices' when doing this via python?
is subprocess sufficient, or is... | [
"I believe the pexpect module would be the easiest way to go about this.\nhttp://pexpect.sourceforge.net/pexpect.html\nSomething along these lines should work pretty well:\nimport pexpect\nimport time\n\ndef ChangePassword(user, pass):\n passwd = pexpect.spawn(\"/usr/bin/passwd %s\" % user)\n\n for x in xrang... | [
3
] | [] | [] | [
"python",
"security",
"system"
] | stackoverflow_0001977022_python_security_system.txt |
Q:
How to make read-only data accessible by diff requests while the server is running (apache, mod_python)
I am using Apache/2.2.8 (Ubuntu) mod_python/3.3.1 Python/2.5.2 and I would like to preload the data I work with.
Currently I read the data from a file on disk every time I get a request, then parse it and store... | How to make read-only data accessible by diff requests while the server is running (apache, mod_python) | I am using Apache/2.2.8 (Ubuntu) mod_python/3.3.1 Python/2.5.2 and I would like to preload the data I work with.
Currently I read the data from a file on disk every time I get a request, then parse it and store it in an object. The data file is relatively large and I would like to parse/preload it ahead of time.
I was... | [
"You could set a tmpfs (or ramfs) mount with the data and it will stay in RAM (tmpfs may send data to swap).\n",
"You don't say what form your data is in, but if a keystore will suffice then you can use shelve along with OS caching in order to hold the data in a preparsed format.\n",
"Another option is to use p... | [
1,
0,
0
] | [] | [] | [
"apache",
"mod_python",
"python"
] | stackoverflow_0001957148_apache_mod_python_python.txt |
Q:
sqlalchemy lookup tables
Hi I have a table in 3NF form
ftype_table = Table(
'FTYPE',
Column('ftypeid', Integer, primary_key=True),
Column('typename', String(50)),
base.metadata,
schema='TEMP')
file_table = Table(
'FILE',
base.metadata,
Column('fileid', Integer, primary_key=True),
... | sqlalchemy lookup tables | Hi I have a table in 3NF form
ftype_table = Table(
'FTYPE',
Column('ftypeid', Integer, primary_key=True),
Column('typename', String(50)),
base.metadata,
schema='TEMP')
file_table = Table(
'FILE',
base.metadata,
Column('fileid', Integer, primary_key=True),
Column('datatypeid', Integer... | [
"the UniqueObject recipe is the standard answer here: http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject . The idea is to override the creation of File using either __metaclass__.call() or File.__new__() to return the already-existing object, from the DB or from cache (the initial DB lookup, if the o... | [
2,
0,
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0001964784_python_sqlalchemy.txt |
Q:
In memory database with socket capability
Python --> SQLite --> ASP.NET C#
I am looking for an in memory database application that does not have to write the data it receives to disc. Basically, I'll be having a Python server which receives gaming UDP data and translates the data and stores it in the memory databa... | In memory database with socket capability | Python --> SQLite --> ASP.NET C#
I am looking for an in memory database application that does not have to write the data it receives to disc. Basically, I'll be having a Python server which receives gaming UDP data and translates the data and stores it in the memory database engine.
I want to stay away from writing to ... | [
"Totally not my field, but I think Redis is along these lines.\n",
"This sounds like a premature optimization (apologizes if you've already done the profiling). What I would suggest is go ahead and write the system in the simplest, cleanest way, but put a bit of abstraction around the database bits so they can e... | [
1,
1,
0,
0,
0
] | [] | [] | [
"asp.net",
"networking",
"python",
"sqlite",
"udp"
] | stackoverflow_0001962130_asp.net_networking_python_sqlite_udp.txt |
Q:
Is RLock a sensible default over Lock?
the threading module in Python provides two kinds of locks: A common lock and a reentrant lock. It seems to me, that if I need a lock, I should always prefer the RLock over the Lock; mainly to prevent deadlock situations.
Besides that, I see two points, when to prefer a Lock ... | Is RLock a sensible default over Lock? | the threading module in Python provides two kinds of locks: A common lock and a reentrant lock. It seems to me, that if I need a lock, I should always prefer the RLock over the Lock; mainly to prevent deadlock situations.
Besides that, I see two points, when to prefer a Lock over a RLock:
RLock has a more complicated ... | [
"Two points:\n\nIn officially released Python versions (2.4, 2.5... up to 3.1), an RLock is much slower than a Lock, because Locks are implemented in C and RLocks in Python (this will change in 3.2)\nA Lock can be released from any thread (not necessarily the thread which acquire()d it), while an RLock has to be re... | [
10,
3
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0001822541_multithreading_python.txt |
Q:
Python performance characteristics
I'm in the process of tuning a pet project of mine to improve its performance. I've already busted out the profiler to identify hotspots but I'm thinking understanding Pythons performance characteristics a little better would be quite useful going forward.
There are a few things ... | Python performance characteristics | I'm in the process of tuning a pet project of mine to improve its performance. I've already busted out the profiler to identify hotspots but I'm thinking understanding Pythons performance characteristics a little better would be quite useful going forward.
There are a few things I'd like to know:
How smart is its optim... | [
"Python's compiler is deliberately dirt-simple -- this makes it fast and highly predictable. Apart from some constant folding, it basically generates bytecode that faithfully mimics your sources. Somebody else already suggested dis, and it's indeed a good way to look at the bytecode you're getting -- for example, ... | [
24,
6,
6,
4,
4,
4
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0001913906_performance_python.txt |
Q:
Separate logger name for each application instance
My python application consists of main program and several modules. Each module contains
import logging
log = logging.getLogger('myapp.mymodule')
on global level. Handlers and other stuff initialized in main program, and typically all messages forwarded to syslog... | Separate logger name for each application instance | My python application consists of main program and several modules. Each module contains
import logging
log = logging.getLogger('myapp.mymodule')
on global level. Handlers and other stuff initialized in main program, and typically all messages forwarded to syslog.
Now I want to launch multiple instances of application... | [
"Here is a solution I can think of:\nIn the main program, set the formatter of logger named myapp\nimport logging\nlogger = logging.getLogger(\"myapp\")\nformatter = logging.Formatter(\"%(asctime)s - instance_name - %(levelname)s - %(message)s\")\nch = logging.SysLogHandler()\nch.setFormatter(formatter)\nlogger.add... | [
2,
0,
0
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0001975823_logging_python.txt |
Q:
2 dimensional interpolation problem
I have DATA on x and y axes and the output is on z
for example
y = 10
x = [1,2,3,4,5,6]
z = [2.3,3.4,5.6,7.8,9.6,11.2]
y = 20
x = [1,2,3,4,5,6]
z = [4.3,5.4,7.6,9.8,11.6,13.2]
y = 30
x = [1,2,3,4,5,6]
z = [6.3,7.4,8.6,10.8,13.6,15.2]
how can i find the value of z when y = ... | 2 dimensional interpolation problem | I have DATA on x and y axes and the output is on z
for example
y = 10
x = [1,2,3,4,5,6]
z = [2.3,3.4,5.6,7.8,9.6,11.2]
y = 20
x = [1,2,3,4,5,6]
z = [4.3,5.4,7.6,9.8,11.6,13.2]
y = 30
x = [1,2,3,4,5,6]
z = [6.3,7.4,8.6,10.8,13.6,15.2]
how can i find the value of z when y = 15 x = 3.5
I was trying to use scipy but... | [
"scipy.interpolate.bisplrep\nReference:\nhttp://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.bisplrep.html\nimport scipy\nimport math\nimport numpy\nfrom scipy import interpolate\n\n\nx= [1,2,3,4,5,6]\ny= [10,20,30]\n\nY = numpy.array([[i]*len(x) for i in y])\nX = numpy.array([x for i in y])\nZ = ... | [
4,
1,
0
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0001977467_python_scipy.txt |
Q:
Does Paramiko support non-secure telnet and ftp instead of just SSH and SFTP?
I'm looking at existing python code that heavily uses Paramiko to do SSH and FTP. I need to allow the same code to work with some hosts that do not support a secure connection and over which I have no control.
Is there a quick and easy ... | Does Paramiko support non-secure telnet and ftp instead of just SSH and SFTP? | I'm looking at existing python code that heavily uses Paramiko to do SSH and FTP. I need to allow the same code to work with some hosts that do not support a secure connection and over which I have no control.
Is there a quick and easy way to do it via Paramiko, or do I need to step back, create some abstraction that ... | [
"No, paramiko has no support for telnet or ftp -- you're indeed better off using a higher-level abstraction and implementing it twice, with paramiko and without it (with the ftplib and telnetlib modules of the Python standard library).\n"
] | [
7
] | [] | [] | [
"paramiko",
"python"
] | stackoverflow_0001977571_paramiko_python.txt |
Q:
Why doesn't my Django site return a 404 when checked with this URL parser?
Here's a simple python function that checks if a given url is valid:
from httplib import HTTP
from urlparse import urlparse
def checkURL(url):
p = urlparse(url)
h = HTTP(p[1])
h.putrequest('HEAD', p[2])
h.endheaders()
i... | Why doesn't my Django site return a 404 when checked with this URL parser? | Here's a simple python function that checks if a given url is valid:
from httplib import HTTP
from urlparse import urlparse
def checkURL(url):
p = urlparse(url)
h = HTTP(p[1])
h.putrequest('HEAD', p[2])
h.endheaders()
if h.getreply()[0] == 200:
return 1
else: return 0
This works for mo... | [
"Although the content says 404, the site is returning 200 OK in the headers:\nHTTP/1.1 200 OK\nServer: nginx\nDate: Wed, 30 Dec 2009 01:38:24 GMT\nContent-Type: text/html; charset=utf-8\nConnection: close\n\nMake sure your response is using HttpResponseNotFound. e.g.:\n return HttpResponseNotFound('<h1>Page not ... | [
1,
0,
0
] | [] | [] | [
"django",
"python",
"web_applications"
] | stackoverflow_0001977938_django_python_web_applications.txt |
Q:
what does '__getnewargs__' do in this code
class NavigableString(unicode, PageElement):
def __new__(cls, value):
if isinstance(value, unicode):
return unicode.__new__(cls, value)
return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
def __getnewargs__(self):#this line
... | what does '__getnewargs__' do in this code | class NavigableString(unicode, PageElement):
def __new__(cls, value):
if isinstance(value, unicode):
return unicode.__new__(cls, value)
return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
def __getnewargs__(self):#this line
return (NavigableString.__str__(self),)
| [
"Try this:\nx = NavigableString('foop')\ny = pickle.dumps(x)\nz = pickle.loads(y)\nprint x, z\n\nI.e.: __getnewargs__ tells pickle.dumps to pickle x in such a way that a pickle.loads back from that string will use NavigableString.__new__ with the proper argument.\n"
] | [
15
] | [] | [] | [
"python"
] | stackoverflow_0001978264_python.txt |
Q:
pip equivalent to "easy_install ."
Simple Question ;)
Is there a way to simply install the package using pip once you build it. Using easy_install I would simply build my package it (python setup.py build), then if I was happy do a easy_install . and this would dump the resulting egg into the right place. How do... | pip equivalent to "easy_install ." | Simple Question ;)
Is there a way to simply install the package using pip once you build it. Using easy_install I would simply build my package it (python setup.py build), then if I was happy do a easy_install . and this would dump the resulting egg into the right place. How do I do this using pip?
| [
"pip install -e . will install from a local source like easy_install . would.\nMost of pip's commands and functionality are designed around installing from source repositories or PyPI package listings, or maintaining consistently versioned dependencies though.\nIf you are going through the steps of building the pac... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0001978220_python.txt |
Q:
Transforming DTD's with Python
I'm looking for a library to help me parse and transform DTDs using Python. The only thing I have found so far is xmlproc, but that seems ancient and doesn't seem to support serialization of DTDs. There's this for Java but I'd prefer a Python solution.
Edit: by "serialization" of DTD... | Transforming DTD's with Python | I'm looking for a library to help me parse and transform DTDs using Python. The only thing I have found so far is xmlproc, but that seems ancient and doesn't seem to support serialization of DTDs. There's this for Java but I'd prefer a Python solution.
Edit: by "serialization" of DTDs I mean that ideally I'd like to be... | [
"I don't know of an end-to-end processor for DTDs, but then again I so rarely use DTDs at all so that's not surprising.\nAmara can parse DTDs, but I don't know what level of access you can have to them or if the results can be serialized. I assume they can, but that's not based in reality. libxml2, which is availab... | [
0,
0
] | [] | [] | [
"dtd",
"dtd_parsing",
"python"
] | stackoverflow_0001975316_dtd_dtd_parsing_python.txt |
Q:
Is this essential functional programming feature missing from python?
I have a class in python that allows me to save a function (in a database) for later use. Now I need to have a method in the class that allows me to call this function on some arguments. Since I don't know how many arguments the function has ahe... | Is this essential functional programming feature missing from python? | I have a class in python that allows me to save a function (in a database) for later use. Now I need to have a method in the class that allows me to call this function on some arguments. Since I don't know how many arguments the function has ahead of time, I have to pass them in as list. This is where things fall apart... | [
"Python uses * for argument expansion. If you want keyword arguments, expand a dict using **. So the macro you showed would be:\ndef call(function, args):\n return function(*args)\n\nBut usually the Pythonic way is to just do the call inline. There actually is a function called apply() that does exactly this, bu... | [
12,
4
] | [] | [] | [
"python"
] | stackoverflow_0001979003_python.txt |
Q:
Hooking into a wave-out on different platforms
I am going to apologize in advance for being extremely vague, but my knowledge in this area is somewhat limited so I don't know the neccessary "keywords" to make my point/question clear. Sorry.
What I want to do is to find a way to obtain access to raw audio data as i... | Hooking into a wave-out on different platforms | I am going to apologize in advance for being extremely vague, but my knowledge in this area is somewhat limited so I don't know the neccessary "keywords" to make my point/question clear. Sorry.
What I want to do is to find a way to obtain access to raw audio data as it is being output, say, when some external applicati... | [
"Whether you can access the \"wave out\" or \"loopback\" depends on your sound card and drivers.\nThe native sound API on Linux is called ALSA. Search for the ALSA docs and sample code and you should be able to get some code to record from your sound card, then hopefully set up your mixer so that you're recording ... | [
4
] | [] | [] | [
"audio",
"language_agnostic",
"linux",
"python",
"windows"
] | stackoverflow_0001978990_audio_language_agnostic_linux_python_windows.txt |
Q:
What is the difference between isinstance('aaa', basestring) and isinstance('aaa', str)?
a='aaaa'
print isinstance(a, basestring)#true
print isinstance(a, str)#true
A:
In Python versions prior to 3.0 there are two kinds of strings "plain strings" and "unicode strings". Plain strings (str) cannot represent charac... | What is the difference between isinstance('aaa', basestring) and isinstance('aaa', str)? | a='aaaa'
print isinstance(a, basestring)#true
print isinstance(a, str)#true
| [
"In Python versions prior to 3.0 there are two kinds of strings \"plain strings\" and \"unicode strings\". Plain strings (str) cannot represent characters outside of the Latin alphabet (ignoring details of code pages for simplicity). Unicode strings (unicode) can represent characters from any alphabet including som... | [
398,
8,
4,
1
] | [] | [] | [
"built_in_types",
"python",
"python_2.x"
] | stackoverflow_0001979004_built_in_types_python_python_2.x.txt |
Q:
What causes subprocess.call to output blank file when attempting db export with mysqldump?
I am having some problems using subprocess.call to export a database using mysqldump. I'm using Python 3.1 installed on Windows 7.
from time import gmtime, strftime
import subprocess
DumpDir = "c:/apps/sqlbackup/";
DumpFile... | What causes subprocess.call to output blank file when attempting db export with mysqldump? | I am having some problems using subprocess.call to export a database using mysqldump. I'm using Python 3.1 installed on Windows 7.
from time import gmtime, strftime
import subprocess
DumpDir = "c:/apps/sqlbackup/";
DumpFile = "mysqldump-" + strftime("%Y-%m-%d-%H-%M-%S", gmtime()) + ".sql";
params = [r"mysqldump --use... | [
"I'm uncertain of what exactly caused the problem but the above code now works after:\n\nI reset the PATH environment setting\nin Windows to be sure the path to\nmysqldump is added everytime the PC\nboots.\nI restarted the PC (to ensure\nPython/MySQL were restarted and PATH\nenvironment settings were definitely\nco... | [
1
] | [] | [] | [
"mysqldump",
"python",
"subprocess"
] | stackoverflow_0001978944_mysqldump_python_subprocess.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.