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:
mutagen: how to detect and embed album art in mp3, flac and mp4
I'd like to be able to detect whether an audio file has embedded album art and, if not, add album art to that file. I'm using mutagen
1) Detecting album art. Is there a simpler method than this pseudo code:
from mutagen import File
audio = File('musi... | mutagen: how to detect and embed album art in mp3, flac and mp4 | I'd like to be able to detect whether an audio file has embedded album art and, if not, add album art to that file. I'm using mutagen
1) Detecting album art. Is there a simpler method than this pseudo code:
from mutagen import File
audio = File('music.ext')
test each of audio.pictures, audio['covr'] and audio['APIC:']... | [
"Embed flac:\nfrom mutagen import File\nfrom mutagen.flac import Picture, FLAC\n\ndef add_flac_cover(filename, albumart):\n audio = File(filename)\n \n image = Picture()\n image.type = 3\n if albumart.endswith('png'):\n mime = 'image/png'\n else:\n mime = 'image/jpeg'\n image.... | [
4
] | [] | [] | [
"albumart",
"metadata",
"mutagen",
"python"
] | stackoverflow_0007275710_albumart_metadata_mutagen_python.txt |
Q:
Does converting json to dict with eval a good choice?
I am getting a json object from a remote server, and converting it to a python string like this:
a = eval(response)
Is this stupid in any way, or do I have a better option?
A:
Using eval is not a good way to process JSON:
JSON isn't even valid Python, becau... | Does converting json to dict with eval a good choice? | I am getting a json object from a remote server, and converting it to a python string like this:
a = eval(response)
Is this stupid in any way, or do I have a better option?
| [
"Using eval is not a good way to process JSON:\n\nJSON isn't even valid Python, because of true, false, and null.\neval will execute arbitrary Python code, so you are at the mercy of malicious injection of code.\n\nUse the json module available in the standard library instead:\nimport json\ndata = json.loads(\"[1, ... | [
18,
2
] | [] | [] | [
"dictionary",
"eval",
"json",
"python"
] | stackoverflow_0007282905_dictionary_eval_json_python.txt |
Q:
Python readline module: Set 2 character delimiter
I'm using the readline module to autocomplete names (firstname lastname).
I want to set a 2 character delimiter, but by setting readline.set_completer_delims(', ') it accepts both the comma and the whitespace as a delimiter. But I only want the combination.
The pro... | Python readline module: Set 2 character delimiter | I'm using the readline module to autocomplete names (firstname lastname).
I want to set a 2 character delimiter, but by setting readline.set_completer_delims(', ') it accepts both the comma and the whitespace as a delimiter. But I only want the combination.
The problem is, now I enter a first name that exists several t... | [
"You probably will have to use your own function for this, with\nreadline.set_completer([function])\n\nFrom python doc : \n\"The completer function is called as function(text, state), for state in 0, 1, 2, ..., until it returns a non-string value. It should return the next possible completion starting with text.\"\... | [
0
] | [] | [] | [
"autocomplete",
"python",
"readline"
] | stackoverflow_0007282757_autocomplete_python_readline.txt |
Q:
perform multiple for loops simultaneously
Is it possible to perform multiple loops simultaneously in python.
Like(syntax error, of course):
for a,b in list_of_a,list_of_b:
//do some thing
By simultaneously, I am not meaning the thread or process sense.
I mean, they share the same index or cursor during the ... | perform multiple for loops simultaneously | Is it possible to perform multiple loops simultaneously in python.
Like(syntax error, of course):
for a,b in list_of_a,list_of_b:
//do some thing
By simultaneously, I am not meaning the thread or process sense.
I mean, they share the same index or cursor during the iteration.
What I can think of achieving that i... | [
"for a,b in zip(list_of_a, list_of_b):\n # Do some thing\n\nIf you're using Python 2.x, are worried about performance, and/or using iterators instead of lists, consider itertools.izip instead of zip.\nIn Python 3.x, zip replaces itertools.izip; use list(zip(..)) to get the old (2.x) behavior of zip returning a lis... | [
9,
2
] | [] | [] | [
"for_loop",
"python",
"simultaneous"
] | stackoverflow_0007283110_for_loop_python_simultaneous.txt |
Q:
Python: class static member pointing to itself?
Possible Duplicate:
Can I get a reference to the 'owner' class during the init method of a descriptor?
Code is worth a thousand words:
>>> class ShortRib(object):
>>> def __init__(self, owner):
>>> self.owner = owner
>>>
>>> ... some more methods a... | Python: class static member pointing to itself? |
Possible Duplicate:
Can I get a reference to the 'owner' class during the init method of a descriptor?
Code is worth a thousand words:
>>> class ShortRib(object):
>>> def __init__(self, owner):
>>> self.owner = owner
>>>
>>> ... some more methods and stuff ...
>>>
>>>
>>> class Cow(object):
>>> ... | [
"You can easily do this in __new__:\nclass ShortRib(object):\n def __init__(self, owner):\n self.owner = owner\n\nclass Cow(object):\n shortRib = None\n def __new__(cls, *args, **kwargs):\n if cls.shortRib == None:\n cls.shortRib = ShortRib(cls)\n return super(Cow, cls).__ne... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007282729_python.txt |
Q:
Django logging not showing argument
I have this line in a custom django-admin command:
logger.info("%d records updated", records_updated)
When I run the command, the log file and console output show what I would expect:
[2011-09-02 03:49:31,405] INFO::(27041 140698227433576)::update_records - 5 records updated
... | Django logging not showing argument | I have this line in a custom django-admin command:
logger.info("%d records updated", records_updated)
When I run the command, the log file and console output show what I would expect:
[2011-09-02 03:49:31,405] INFO::(27041 140698227433576)::update_records - 5 records updated
However, the email to the admin shows
INF... | [
"logger.info(\"%d records updated\" % records_updated)\nMaybe u should write like this?\n"
] | [
-1
] | [] | [] | [
"django",
"django_admin",
"logging",
"python"
] | stackoverflow_0007281306_django_django_admin_logging_python.txt |
Q:
create instance of a class in the same class's definition in python
I am trying to create a new MyClass instance in MyClass's definition.
Why does this code fail and how can achieve it?
class MyClass:
def __init__(self):
self.child=MyClass()
mc=MyClass()
A:
Well, it fails because it has ... | create instance of a class in the same class's definition in python | I am trying to create a new MyClass instance in MyClass's definition.
Why does this code fail and how can achieve it?
class MyClass:
def __init__(self):
self.child=MyClass()
mc=MyClass()
| [
"Well, it fails because it has infinite recursion. Think about it, if every MyClass has a child which is a MyClass, it will go on for infinity!\nYou can resolve this a couple of ways. First, you can have a parameter to the constructor:\nclass MyClass:\n def __init__(self, create = True):\n if create:\n ... | [
7,
5,
1,
1
] | [] | [] | [
"class",
"instance",
"python"
] | stackoverflow_0007283473_class_instance_python.txt |
Q:
python stdout carriage return
i am running a for loop on a given set of files..and for monitoring purpose it writes output on which files are being currently processed..
sys.stdout.write("\rProcessing.... "+ j)
sys.stdout.flush()
where j is filenames
output of script...
Processing.... /etc/sysconfig/rhn/sources0.... | python stdout carriage return | i am running a for loop on a given set of files..and for monitoring purpose it writes output on which files are being currently processed..
sys.stdout.write("\rProcessing.... "+ j)
sys.stdout.flush()
where j is filenames
output of script...
Processing.... /etc/sysconfig/rhn/sources0.examplewn-slepcsbals-ipv6f
problem... | [
"Remember the written string, and write spaces first.\nsys.stdout.write('\\r' + (' ' * len(old_string)))\nsys.stdout.write('\\rProcessing... ' + new_string)\n\n"
] | [
7
] | [] | [] | [
"python"
] | stackoverflow_0007283684_python.txt |
Q:
save Python script with formatting - special characters
I use pygmentize to save my Python script as rtf file (with propoer colors depends on keywords in syntax).
Unfortunatelly program substitute special characters (ą,ę,ź,ć,ó) with strange symbols.
Is there any option to set proper code page?
Alternatively - is ... | save Python script with formatting - special characters | I use pygmentize to save my Python script as rtf file (with propoer colors depends on keywords in syntax).
Unfortunatelly program substitute special characters (ą,ę,ź,ć,ó) with strange symbols.
Is there any option to set proper code page?
Alternatively - is there any other tool which can proceed this operation properl... | [
"Did you use the encoding option so pygmentize will use the actual encoding of your source file? If you don't, it defaults to latin-1 which doesn't contain the characters you quoted.\n"
] | [
2
] | [] | [] | [
"pygments",
"python"
] | stackoverflow_0007283756_pygments_python.txt |
Q:
dividing sequence in a file into 3s and numbering them
I have a file containing the sequence: ATGAAGCTAGGCATATTC. I want a simple python code that
will divide this sequence into 3s: ATG AAG GCT.... and then divide their indices to 3s too:
123 456 789........
The final print output should look like this:
ATG 123
... | dividing sequence in a file into 3s and numbering them | I have a file containing the sequence: ATGAAGCTAGGCATATTC. I want a simple python code that
will divide this sequence into 3s: ATG AAG GCT.... and then divide their indices to 3s too:
123 456 789........
The final print output should look like this:
ATG 123
AAG 456
CTA 789
GGC 101112
ATA 131415
TTC 161718
This is wh... | [
"You can tell the read instruction to get three chars at a time:\ni=1\nwhile True :\n v = o.read(3)\n print v, \" \", i, i+1, i+2\n i+=3\n if len(v) < 3:\n break\n\n",
"Instead of \nprint I[i:i+3], i+1; \n\nDo\nprint I[i:i+3], i+1, i+2, i+3; \n\n"
] | [
1,
0
] | [] | [] | [
"indexing",
"python"
] | stackoverflow_0006298456_indexing_python.txt |
Q:
Embedding Python into C - importing modules
I am having problems using the Embedded Python for C as per the Documentation - Whenever I try using imported modules I get an :
Unhandled exception at 0x1e089e85 in PythonIncl.exe: 0xC0000005:
Access violation reading location 0x00000004.
The error occurs in the PyO... | Embedding Python into C - importing modules | I am having problems using the Embedded Python for C as per the Documentation - Whenever I try using imported modules I get an :
Unhandled exception at 0x1e089e85 in PythonIncl.exe: 0xC0000005:
Access violation reading location 0x00000004.
The error occurs in the PyObject_GetAttrString() method and the documentatio... | [
"Check the result of the PyImport_ImportModule call: It fails and returns NULL. That is because by default, the current directory is not in the search path. Add\nPySys_SetPath(\".\"); // before ..\nmymod = PyImport_ImportModule(\"reverse\");\n\nto add the current directory to the module search path and make your ex... | [
16,
2
] | [] | [] | [
"c",
"python",
"python_c_api",
"python_embedding"
] | stackoverflow_0007283964_c_python_python_c_api_python_embedding.txt |
Q:
How do I make an ubuntu/debian package for a twistd/twisted plugin?
As a follow-up to How do I write a setup.py for a twistd/twisted plugin that works with setuptools, distribute, etc?, how does one make a debian package for a twisted plugin?
Assuming the setup.py is properly written, using cdbs/python-central/dh_... | How do I make an ubuntu/debian package for a twistd/twisted plugin? | As a follow-up to How do I write a setup.py for a twistd/twisted plugin that works with setuptools, distribute, etc?, how does one make a debian package for a twisted plugin?
Assuming the setup.py is properly written, using cdbs/python-central/dh_python2 should just work, but I haven't had much luck so far.
The trick w... | [
"Apparently the issue is with 'python-support', which is plain broken when it comes to twisted plugins.\nThis message from Ubuntu's Matthias Klose explains the issue and offers a solution:\n\npackaging of twisted plugins with python-support is broken by design.\n Even python policy mentions explicitly that you sh... | [
3,
1
] | [] | [] | [
"debian",
"packaging",
"python",
"twisted",
"ubuntu"
] | stackoverflow_0007275759_debian_packaging_python_twisted_ubuntu.txt |
Q:
Can you tell when i can see a good example of "drag and drop" a cell of wx.Grid?
Can you tell when i can see a good example of "drag and drop" a cell of wx.Grid. I have a two wx.Grid's. I want to move the content (or another data) from cell of first Grid to cell of second Grid.
A:
Can this help you ?
http://wiki... | Can you tell when i can see a good example of "drag and drop" a cell of wx.Grid? | Can you tell when i can see a good example of "drag and drop" a cell of wx.Grid. I have a two wx.Grid's. I want to move the content (or another data) from cell of first Grid to cell of second Grid.
| [
"Can this help you ?\nhttp://wiki.wxpython.org/DragAndDrop\n\n"
] | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0007283956_python_wxpython.txt |
Q:
Getting selected value from drop down box in a html form without submit
How to get the text of selected item from a drop down box element in html forms? (using python)
How can I store the value to a variable, when I select one item from the drop down box using mouse? (ie. without using a submit button)
This is for... | Getting selected value from drop down box in a html form without submit | How to get the text of selected item from a drop down box element in html forms? (using python)
How can I store the value to a variable, when I select one item from the drop down box using mouse? (ie. without using a submit button)
This is for a application which I am doing in app engine which only supports Python.
| [
"Your question shows some misunderstanding on how web applications work.\nThe user has to type an address in a browser to get to the application. That sends a request to the server. The server code (written in python) receives this request and has the opportunity to send an answer. The answer is a document usually ... | [
19,
3,
1,
0
] | [] | [] | [
"drop_down_menu",
"google_app_engine",
"html",
"javascript",
"python"
] | stackoverflow_0000419908_drop_down_menu_google_app_engine_html_javascript_python.txt |
Q:
python multithreading synchronization
I am having a synchronization problem while threading with cPython. I have two files, I parse them and return the desired result. However, the code below acts strangely and returns three times instead of two plus doesn't return in the order I put them into queue. Here's the co... | python multithreading synchronization | I am having a synchronization problem while threading with cPython. I have two files, I parse them and return the desired result. However, the code below acts strangely and returns three times instead of two plus doesn't return in the order I put them into queue. Here's the code:
import Queue
import threading
from Html... | [
"\nI am threading because actually I will have to connect more than 10 places at a time and retrieve its results. I believe that threading is the most appropriate way to accomplish such a task\n\nThreading is actually one of the most error-prone ways to manage multiple concurrent connections. A more powerful, more ... | [
2,
1,
0
] | [] | [] | [
"multithreading",
"python",
"synchronization"
] | stackoverflow_0007283197_multithreading_python_synchronization.txt |
Q:
Extracting elements inside and between brackets
I have the following string and I would like to extract the elements (xx="yy") and what's between the brackets. Here's an example:
[caption id="get this" align="and this" width="and this" caption="and
this"]this too please[/caption]
I've tried the following code ... | Extracting elements inside and between brackets | I have the following string and I would like to extract the elements (xx="yy") and what's between the brackets. Here's an example:
[caption id="get this" align="and this" width="and this" caption="and
this"]this too please[/caption]
I've tried the following code but I'm quite a noob with regex.
re.sub(r'\[caption ... | [
"It's probably not working for you because .* is greedy. Try [^\"]* in its place. [^\"] means the set of all characters except the quote character. Also, as you've pointed out in the comments, the token syntax, is \\\\n, not %n. Try this:\nre.sub(r'\\[caption id=\"([^\"]*)\" align=\"([^\"]*)\" width=\"([^\"]*)\" ca... | [
3,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007284570_python_regex.txt |
Q:
Getting Memory Error when trying to plot large array with matplotlib
I would like to plot an array of 20 millions object, I have 8GB RAM and still I get the following error when I run the following lines:
import matplotlib.pyplot as plt
import numpy as np
d = np.arange(200000000)
plt.plot(d)
plt.show()
Error:
Tr... | Getting Memory Error when trying to plot large array with matplotlib | I would like to plot an array of 20 millions object, I have 8GB RAM and still I get the following error when I run the following lines:
import matplotlib.pyplot as plt
import numpy as np
d = np.arange(200000000)
plt.plot(d)
plt.show()
Error:
Traceback (most recent call last):
...
File "C:\Python27\lib\site-packages... | [
"Due to physical limitations of displays and plotters, you won't be able to plot 20,000,000 points anyway. So you could reduce your array by sampling it or by using means of slices:\n>>> m = 20000000\n>>> a = np.arange(m)\n>>> n = 100 # <- reducing to 100 points\n>>> s = m/n # <- size of slices to compress\n>>> red... | [
6,
2
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0007284538_matplotlib_numpy_python.txt |
Q:
Check sum in list comprehension
Is it possible to also check the sum of the digits in the list in the same comprehension and make another except if the sum exceeds 50?
k = input("input digits separated by spaces:")
try:
[int(i) for i in k.split()]
except ValueError:
... | Check sum in list comprehension | Is it possible to also check the sum of the digits in the list in the same comprehension and make another except if the sum exceeds 50?
k = input("input digits separated by spaces:")
try:
[int(i) for i in k.split()]
except ValueError:
print("input only digits")
The main ... | [
" k = input(\"Input integers separated by spaces:\")\n try:\n the_list = [int(i) for i in k.split()]\n if sum(the_list) > 50:\n raise ValueError(\"The user's numbers' summation is too large.\")\n except ValueError:\n print(\"Input only integers separated by spaces with sum n... | [
3,
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0007282538_python_python_3.x.txt |
Q:
How to optionally import/construct class to member variable that will support IDE autocomplete
I have a Python library design that I'm trying to clean up, but I noticed that one piece isn't auto-completing in Eclipse/PyDev. I'm familiar enough for this not to be a problem for me, but its a library that others will... | How to optionally import/construct class to member variable that will support IDE autocomplete | I have a Python library design that I'm trying to clean up, but I noticed that one piece isn't auto-completing in Eclipse/PyDev. I'm familiar enough for this not to be a problem for me, but its a library that others will end up using and auto-complete that doesn't work for a feature chunk won't do.
I'll just explain qu... | [
"First, Simple is better than complex -- your design appears to be complicated for no good reason. Maybe you should provide some details about your actual library.\nSecond, with Python as a dynamically typed language, it's just natural that there are cases when your IDE fails to auto-complete because your IDE has a... | [
0
] | [] | [] | [
"class",
"eclipse",
"pydev",
"python"
] | stackoverflow_0007285319_class_eclipse_pydev_python.txt |
Q:
Using python to filter files on disk
I am using below to remove files from disk.
def match_files(dir, pattern):
for dirname, subdirs, files in os.walk(dir):
for f in files:
if f.endswith(pattern):
yield os.path.join(dirname, f)
# Remove all files in the curren... | Using python to filter files on disk | I am using below to remove files from disk.
def match_files(dir, pattern):
for dirname, subdirs, files in os.walk(dir):
for f in files:
if f.endswith(pattern):
yield os.path.join(dirname, f)
# Remove all files in the current dir matching *.txt
for f in match_fi... | [
"Besides os.stat you could use os.path.getmtime or os.path.getctime, the pro's / con's of which are discussed on this question. You can use datetime.datetime.fromtimestamp to convert the timestamp returned into a datetime object, and then you can do whatever you want. In this example I'll remove files not modified ... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0007285402_python.txt |
Q:
Make running python script more responsive to ctrl c?
We are running a very large framework of python scripts for test automation and I do really miss the opportunity to kill a running python script with ctrl + c in some situations on Windows.
When the script might be doing some socket communications with long tim... | Make running python script more responsive to ctrl c? | We are running a very large framework of python scripts for test automation and I do really miss the opportunity to kill a running python script with ctrl + c in some situations on Windows.
When the script might be doing some socket communications with long time-outs the only options sometimes is to kill the DOS window... | [
"Rather than using blocking calls with long timeouts, use event-driven networking. This will allow you never to have long periods of time doing uninterruptable operations.\n",
"Look for instances of:\ntry:\n some code\nexcept:\n # catches all exceptions, including ^C\n\nChange to:\ntry:\n some code\nexce... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007285874_python.txt |
Q:
How to delete entities not found in feed on GAE
I am updating and adding items from a feed(which can have about 40000 items) to the datastore 200 items at a time, the problem is that the feed can change and some items might be deleted from the feed.
I have this code:
class FeedEntry(db.Model):
name = db.String... | How to delete entities not found in feed on GAE | I am updating and adding items from a feed(which can have about 40000 items) to the datastore 200 items at a time, the problem is that the feed can change and some items might be deleted from the feed.
I have this code:
class FeedEntry(db.Model):
name = db.StringProperty(required=True)
def updateFeed(offset, numbe... | [
"If you add a DateTimeProperty with auto_now=True, it will record the last modified time of each entity. Since you update every item in the feed, by the time you've finished they will all have times after the moment you started, so anything with a date before then isn't in the feed any more.\nXavier's generation co... | [
2,
1
] | [] | [] | [
"feed",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007283368_feed_google_app_engine_google_cloud_datastore_python.txt |
Q:
HTMLParser and weird behavior
I have to extract an information from the following web page with Python 3: http://www.homefinance.nl/english/international-interest-rates/libor/libor-interest-rates-gbp.asp
The download using urllib.request seems ok, but surprisingly, when I parse the html file with my HTMLParser cla... | HTMLParser and weird behavior | I have to extract an information from the following web page with Python 3: http://www.homefinance.nl/english/international-interest-rates/libor/libor-interest-rates-gbp.asp
The download using urllib.request seems ok, but surprisingly, when I parse the html file with my HTMLParser class the parsing seems to stop in the... | [
"BTW, I noticed that you forgot to do a parser.close() after the parser.feed(). It might be buffering something, and the close will force it to finish.\n",
"Not sure what you are actually trying to do but using BeautifulSoup for parsing HTML is much nicer and easier and less error-prone.\n"
] | [
2,
0
] | [] | [] | [
"html",
"html_parsing",
"python"
] | stackoverflow_0005488751_html_html_parsing_python.txt |
Q:
Python: Faster regex replace
I have a large set of large files and a set of "phrases" that need to be replaced in each file.
The "business logic" imposes several restrictions:
Matching must be case-insensitive
The whitespace, tabs and new lines in the regex cannot be ignored
My solution (see below) is a bit on... | Python: Faster regex replace | I have a large set of large files and a set of "phrases" that need to be replaced in each file.
The "business logic" imposes several restrictions:
Matching must be case-insensitive
The whitespace, tabs and new lines in the regex cannot be ignored
My solution (see below) is a bit on the slow side. How could it be op... | [
"you could avoid recompiling your regexp for every file:\nprecompiled = []\nfor phrase in phrases:\n b1, b2 = str(phrase).strip().split(\" \")\n precompiled.append(b1+\"_\"+b2, re.compile(r\"%s\\ *\\t*\\n*%s\"%(b1,b2), re.IGNORECASE))\n\nfor (input, output) in ...:\n with open(output,\"w\") as o:\n ... | [
5,
2
] | [] | [] | [
"python",
"regex",
"replace"
] | stackoverflow_0007285980_python_regex_replace.txt |
Q:
How to convert an associative array in python?
I am really new to python and I can't find any information about this. I have an associative array item,
item['id'] = 0
item['title'] = 'python'
I want to validate the contents of item but I dont want to use the index name like 'title' but just have a for loop and i... | How to convert an associative array in python? | I am really new to python and I can't find any information about this. I have an associative array item,
item['id'] = 0
item['title'] = 'python'
I want to validate the contents of item but I dont want to use the index name like 'title' but just have a for loop and iterate over all entries in item regardless of their ... | [
"In Python, associative arrays are called dictionaries.\nA good way to iterate through a dict is to use .iteritems():\nfor key, value in item.iteritems():\n print key, value \n\nIf you only need the values, use .itervalues():\nfor value in item.itervalues():\n print value \n\nAs you learn more about Python an... | [
21,
6
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0007286111_for_loop_python.txt |
Q:
Using Python to break a continuous string into components?
This is similar to what I want to do: breaking a 32-bit number into individual fields
This is my typical "string" 00000000110000000000011000000000
I need to break it up into four equal parts:
00000000
11000000
00000110
00000000
I need to append the list to... | Using Python to break a continuous string into components? | This is similar to what I want to do: breaking a 32-bit number into individual fields
This is my typical "string" 00000000110000000000011000000000
I need to break it up into four equal parts:
00000000
11000000
00000110
00000000
I need to append the list to a new text file with the original string as a header.
I know ho... | [
"This should do what you want. See comprehensions for more details.\n>>> s = \"00000000110000000000011000000000\"\n>>> [s[i:i+8] for i in xrange(0, len(s), 8)]\n['00000000', '11000000', '00000110', '00000000']\n\n",
"+1 for Robert's answer. As for 'I need to append the list to a new text file with the original s... | [
9,
3,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007286139_python.txt |
Q:
macos standalone python
Well I'm quite sure this is quite a stupid question but everything else seems to have failed so far(py2app and cx_freeze). So my question is basically:
On MacOS, from you python framework, is it possible to "select" some required files, that will
then allow you to use "your" python elsewhe... | macos standalone python | Well I'm quite sure this is quite a stupid question but everything else seems to have failed so far(py2app and cx_freeze). So my question is basically:
On MacOS, from you python framework, is it possible to "select" some required files, that will
then allow you to use "your" python elsewhere?
So shortly kind of an "e... | [
"Yes you can. Check out PyInstaller.\nYou give it the path to your python script and it analyzes all of your package imports, extracting any binary files that are needed and placing them into an archive. You can then just unzip the archive onto another OS X and it runs.\nI've used it for a fairly complex python pro... | [
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0007282955_macos_python.txt |
Q:
Python+Tornado vs Scala+Lift?
I'm looking to start a Google Maps based web application.
My initial thoughts are that in the first phase the focus should be on the front-end, and the backend should be easy to write and to prototype, and should aid as much as possible the development of the frontend.
There will be ... | Python+Tornado vs Scala+Lift? | I'm looking to start a Google Maps based web application.
My initial thoughts are that in the first phase the focus should be on the front-end, and the backend should be easy to write and to prototype, and should aid as much as possible the development of the frontend.
There will be no 'classic' pages, just a meebo.co... | [
"I think Python and Tornado are a great team, for the following reasons\n\nTornado is really an IOLoop that happens to come with an HTTP implementation that runs on it (and a few helpers). \n\nThis means that it comes with everything you need to do web development with it.\nIt also means that if you find, down the ... | [
14,
6,
3
] | [] | [] | [
"comet",
"lift",
"python",
"scala",
"tornado"
] | stackoverflow_0007227850_comet_lift_python_scala_tornado.txt |
Q:
Can I iterate objects from my Django model over a modified HTMLCalendar()?
This code will only retrieve a single object from the database, rather than iterate them throughout the calendar on their applicable date.
cal.py
from www.wednesday.models import Event
import calendar
class EventCal(calendar.HTMLCalendar):... | Can I iterate objects from my Django model over a modified HTMLCalendar()? | This code will only retrieve a single object from the database, rather than iterate them throughout the calendar on their applicable date.
cal.py
from www.wednesday.models import Event
import calendar
class EventCal(calendar.HTMLCalendar):
def formatday(self, day, weekday):
if day == 0:
... | [
"Most of your question is murky.\n\nAnd, it's printing the django tag {{ event.restaurant }} rather than the data from the model. \n\nThat's because formatday() returns the string \"{{ event.restaurant }}\".\nThe template rendering inserts that string into the template.\nThe template rendering doesn't look at the d... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007285950_django_python.txt |
Q:
splitting unicode string into words
I am trying to split a Unicode string into words (simplistic), like this:
print re.findall(r'(?u)\w+', "раз два три")
What I expect to see is:
['раз','два','три']
But what I really get is:
['\xd1', '\xd0', '\xd0', '\xd0', '\xd0\xb2\xd0', '\xd1', '\xd1', '\xd0']
What am I doin... | splitting unicode string into words | I am trying to split a Unicode string into words (simplistic), like this:
print re.findall(r'(?u)\w+', "раз два три")
What I expect to see is:
['раз','два','три']
But what I really get is:
['\xd1', '\xd0', '\xd0', '\xd0', '\xd0\xb2\xd0', '\xd1', '\xd1', '\xd0']
What am I doing wrong?
Edit:
If I use u in front of the... | [
"You're actually getting the stuff you expect in the unicode case. You only think you are not because of the weird escaping due to the fact that you're looking at the reprs of the strings, not not printing their unescaped values. (This is just how lists are displayed.)\n>>> words = [u'\\u0440\\u0430\\u0437', u'\\u0... | [
6
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0007286879_python_unicode.txt |
Q:
Python: UnicodeEncodeError: 'latin-1' codec can't encode characters in position
I am getting this error:
File "run.py", line 37, in <module>
print str1
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 24-29: ordinal not in range(256)
When trying to simply print some Japanese text. Actually... | Python: UnicodeEncodeError: 'latin-1' codec can't encode characters in position | I am getting this error:
File "run.py", line 37, in <module>
print str1
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 24-29: ordinal not in range(256)
When trying to simply print some Japanese text. Actually it seems the string looks like this:
\u5149\u66dc\u65e5\u3067\u30e9\u30c6 \u30d4\u3... | [
"The error that you see is because you terminal use latin-1 as encoding, as a side note you can check the encoding of your terminal (assuming that it's your stdout) by doing in your shell:\n$ python -c \"import sys; print sys.stdout.encoding\"\n\nAnd now for printing in UTF-8 you should encode your string to utf-8 ... | [
4
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0007286968_python_unicode.txt |
Q:
is there any drand48() equivalent in python or a wrapper to it?
I am converting some c code to python. I am wondering that is there any drand48() equivalent in python(exactly the same!) or a wrapper to it?
Thanks a lot
A:
You are looking for random.random.
>>> import random
>>> help(random)
>>> random.random()
0... | is there any drand48() equivalent in python or a wrapper to it? | I am converting some c code to python. I am wondering that is there any drand48() equivalent in python(exactly the same!) or a wrapper to it?
Thanks a lot
| [
"You are looking for random.random.\n>>> import random\n>>> help(random)\n>>> random.random()\n0.8423026866867628\n\nIt does not use the same generator as drand48. The drand48 family uses a 48-bit linear congruential generator, whereas the Python random module uses the superior Mersenne Twister algorithm.\nIf you ... | [
8
] | [] | [] | [
"python",
"random"
] | stackoverflow_0007287014_python_random.txt |
Q:
Why python makes the difference between expressions and statements?
What are the reasons for putting the border between expressions and statements in python? Are there any limitations that require that distinction?
What is the benefit for the python programmers?
A:
One benefit is that Python programmers don't ha... | Why python makes the difference between expressions and statements? |
What are the reasons for putting the border between expressions and statements in python? Are there any limitations that require that distinction?
What is the benefit for the python programmers?
| [
"One benefit is that Python programmers don't have to maintain code such as:\nwhile((x = foo()) != value)\n\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0007287074_python.txt |
Q:
How do you get the IP address of a given network interface?
In Python is there a function to get the IP address of a given network interface?
Is there a command line programme that get do this?
I want to get the IP address of en1.
This is the result of ifconfig on my machine.
$ ifconfig
lo0: flags=8049<UP,LOOPBA... | How do you get the IP address of a given network interface? | In Python is there a function to get the IP address of a given network interface?
Is there a command line programme that get do this?
I want to get the IP address of en1.
This is the result of ifconfig on my machine.
$ ifconfig
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
inet6 ::1 prefixlen 128
... | [
"$ sudo pip install netifaces\n$ python\nPython 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) \n[GCC 4.2.1 (Apple Inc. build 5646)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n\n\n\nimport netifaces\nnetifaces.ifaddresses('en0')\n\n\n\n{18: [{'addr': '10:9a:dd:52:89:dc'}],... | [
2
] | [] | [] | [
"network_interface",
"networking",
"python"
] | stackoverflow_0007286998_network_interface_networking_python.txt |
Q:
Why doesn't my Python 2.6 auto-unzip egg files on import?
I'm under the impression that Python import is supposed to automatically
unzip egg files in site-packages.
My installation doesn't seem to want to auto-unzip the egg. What I tried:
(1) I used easy_install to install the suds module, which copied the
egg fil... | Why doesn't my Python 2.6 auto-unzip egg files on import? | I'm under the impression that Python import is supposed to automatically
unzip egg files in site-packages.
My installation doesn't seem to want to auto-unzip the egg. What I tried:
(1) I used easy_install to install the suds module, which copied the
egg file into site-packages. Python couldn't import it. (import suds)... | [
"By default (if you haven't specified multi-version mode), easy_installing an egg will add an entry to the easy-install.pth file in site-packages. Check there to see if there's a reference to the suds egg. You can also check the Python import path (which is the list of places Python will search for modules) like th... | [
2
] | [] | [] | [
"easy_install",
"egg",
"import",
"python"
] | stackoverflow_0007286115_easy_install_egg_import_python.txt |
Q:
django 1.3 forms validation using clean method to retrieve getlist
I have a form with checkboxes, the form functioning well, in my view i can use request.POST.getlist('list') to retrieve the list of values.
At the moment am trying to do some form validation inside the clean method and when i try to use self.clean... | django 1.3 forms validation using clean method to retrieve getlist | I have a form with checkboxes, the form functioning well, in my view i can use request.POST.getlist('list') to retrieve the list of values.
At the moment am trying to do some form validation inside the clean method and when i try to use self.cleaned_data['list'] I get the last value. I cannot retrieve the list of item... | [
"First, there are a number of basic Python errors here. There is almost never a need to access the double-underscore functions - they are internal implementation details. Always use the normal len() function instead. And, never use is for comparisons: it's for identity, so should only be used with things you know h... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007286241_django_python.txt |
Q:
How to make from var_str import var_str in python
Let me explain..
I want to do this:
a = "somedir.somefile"
b = "someclass"
from a import b
Well, I want to do this to import automatic all classes inside a directory, and I don't know how many classes are there.
A:
a = "somedir.somefile"
b = "someclass"
module ... | How to make from var_str import var_str in python | Let me explain..
I want to do this:
a = "somedir.somefile"
b = "someclass"
from a import b
Well, I want to do this to import automatic all classes inside a directory, and I don't know how many classes are there.
| [
"a = \"somedir.somefile\"\nb = \"someclass\"\n\nmodule = __import__(a, globals(), locals(), [b], -1)\nclazz = getattr(module, b)\n\nnow you can do this:\ninstance = clazz()\ninstance.method()\n\n",
"You need the __import__ built-in function. It's a bit fiddly to use, though, because it returns the top-level modul... | [
2,
2,
0
] | [] | [] | [
"dynamic",
"import",
"python"
] | stackoverflow_0007287361_dynamic_import_python.txt |
Q:
Google Chrome Remote Debugging - Loading Page
I have been reading through Google Chrome Remote Debugging documentation (http://code.google.com/chrome/devtools/docs/remote-debugging.html), but I still don't understand how do I open a new web page in Google Chrome. I am using Python and after launching Google Chrome... | Google Chrome Remote Debugging - Loading Page | I have been reading through Google Chrome Remote Debugging documentation (http://code.google.com/chrome/devtools/docs/remote-debugging.html), but I still don't understand how do I open a new web page in Google Chrome. I am using Python and after launching Google Chrome with --remote-debugging-port, I can only communica... | [
"\nyou can ask your further questions in https://groups.google.com/forum/#!forum/google/chrome-developer-tools if you like. (I just got your question about DevTools with help of Google Alert's rss feed);\nyou can sniff the messages between DevTools and Chrome (Open DevTools in detached mode, open DevTools for DevTo... | [
1
] | [] | [] | [
"google_chrome",
"google_chrome_devtools",
"python"
] | stackoverflow_0007204282_google_chrome_google_chrome_devtools_python.txt |
Q:
Python: Comment out a block heading without dedenting all the code inside
Sometimes I need to temporarily comment out block headings for testing purpose, e.g.:
i = 2
s = { 'a', 'b', 'c' }
#while i > 0:
s.pop()
i -= 1
print(s)
but, since indentation is part of python's syntax, if I run the code above I got:
... | Python: Comment out a block heading without dedenting all the code inside | Sometimes I need to temporarily comment out block headings for testing purpose, e.g.:
i = 2
s = { 'a', 'b', 'c' }
#while i > 0:
s.pop()
i -= 1
print(s)
but, since indentation is part of python's syntax, if I run the code above I got:
s.pop()
^
IndentationError: unexpected indent
I know that dedenting th... | [
"What about if True: as the alternate? Then just exchange the '#' between the while and if to get your desired effect.\n",
"Either use an editor that auto-indent for you or replace the while by something like if True: temporarily.\n"
] | [
7,
0
] | [] | [] | [
"comments",
"indentation",
"python"
] | stackoverflow_0007287608_comments_indentation_python.txt |
Q:
Getting the dtype of a result array in numpy
I want to preallocate memory for the output of an array operation, and I need to know what dtype to make it. Below I have a function that does what I want it to do, but is terribly ugly.
import numpy as np
def array_operation(arr1, arr2):
out_shape = arr1.shape
... | Getting the dtype of a result array in numpy | I want to preallocate memory for the output of an array operation, and I need to know what dtype to make it. Below I have a function that does what I want it to do, but is terribly ugly.
import numpy as np
def array_operation(arr1, arr2):
out_shape = arr1.shape
# Get the dtype of the output, these lines are t... | [
"You are looking for numpy.result_type.\n(As an aside, do you realize that you can access all multi-dimensional arrays as 1d arrays? You don't need to access x[0, 0, 0, 0, 0] -- you can access x.flat[0].)\n",
"For those using numpy version < 1.6, you could use:\ndef result_type(arr1, arr2):\n x1 = arr1.flat[0]... | [
7,
1
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0007285612_numpy_python_scipy.txt |
Q:
Creating a matplotlib interactive plotting window for an existing figure
I am writing a program that fits curves to large sets of xy coordinate data. It is often helpful to watch the progress of the algorithm by plotting and displaying each iteration as the fitting progresses. I'm using matplotlib for plotting.
Wh... | Creating a matplotlib interactive plotting window for an existing figure | I am writing a program that fits curves to large sets of xy coordinate data. It is often helpful to watch the progress of the algorithm by plotting and displaying each iteration as the fitting progresses. I'm using matplotlib for plotting.
What I'd like to do is create the figure in the main thread, then pass it into a... | [
"I think I got it:\nimport Tkinter\nimport threading\nimport matplotlib.backends.backend_tkagg\n\nroot = Tkinter.Tk()\n\nclass Plotter():\n def __init__(self,fig):\n t = threading.Thread(target=self.PlottingThread,args=(fig,))\n t.start() \n\n def PlottingThread(self,fig): \n ... | [
2
] | [] | [] | [
"matplotlib",
"multithreading",
"oop",
"python"
] | stackoverflow_0007275646_matplotlib_multithreading_oop_python.txt |
Q:
Is there a way to interactively program a Python curses application?
Is there a way to create a second terminal so that all calls to curses functions operate on that, rather than in the existing terminal? I work much faster when I can try things out interactively, so I'd like to be able to run an interactive pyth... | Is there a way to interactively program a Python curses application? | Is there a way to create a second terminal so that all calls to curses functions operate on that, rather than in the existing terminal? I work much faster when I can try things out interactively, so I'd like to be able to run an interactive python interpreter in one terminal and see the curses output in another.
As it... | [
"You could use code.InteractiveConsole and SocketServer to attach a python interactive shell to a socket and do your development through that. A simple example looks like:\nimport sys\nimport SocketServer\nfrom code import InteractiveConsole\n\nclass InteractiveServer(SocketServer.BaseRequestHandler):\n def handl... | [
4,
3,
0
] | [] | [] | [
"curses",
"python"
] | stackoverflow_0007209285_curses_python.txt |
Q:
sorting a dictionary of lists based on keys
Possible Duplicate:
Sorting a dictionary having keys as string of numbers in python
I want to sort the dictionary of list based on value of keys. This is how it looks now
{'217': ['109'],
'214': ['111', '156', '159'],
'215': ['111'],
'219': ['111', '114', '212', ... | sorting a dictionary of lists based on keys |
Possible Duplicate:
Sorting a dictionary having keys as string of numbers in python
I want to sort the dictionary of list based on value of keys. This is how it looks now
{'217': ['109'],
'214': ['111', '156', '159'],
'215': ['111'],
'219': ['111', '114', '212', '214’]}
But I want something like
{'214': ['111... | [
"Dictionaries do not sort their keys in any particular order, because they are implemented as hash tables. You can get the keys and values in sorted order, but not as a dict, using something like:\n>>> mydict = {'217': ['109'], '214': ['111', '156', '159'], '215': ['111'], '219': ['111', '114', '212', '214']}\n>>>... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0007287900_python.txt |
Q:
How to get the next obj when looping in the django model
This is the code:
{% for o in page_obj.object_list %}
<tr style="color:#4A3C8C;background-color:{% cycle '#E7E7FF' '#F7F7F7' %};">
<td align="center"> {{o.terminal_id}}</td>
<td align="center"> {{o.time_st... | How to get the next obj when looping in the django model | This is the code:
{% for o in page_obj.object_list %}
<tr style="color:#4A3C8C;background-color:{% cycle '#E7E7FF' '#F7F7F7' %};">
<td align="center"> {{o.terminal_id}}</td>
<td align="center"> {{o.time_stamp}}</td>
<td align="center" class="lat"> ... | [
"If you want to access multiple objects within a forloop, (although this is not a good design idea, but that is a separate discussion entirely.) you don't loop on the objects, but a counter and access the respective objects' counters moved around.\n#In your view\nobj_count = range(page_obj.object_list.count())\n\n{... | [
0,
0
] | [] | [] | [
"django",
"html",
"javascript",
"jquery",
"python"
] | stackoverflow_0005012973_django_html_javascript_jquery_python.txt |
Q:
How to double buffering a WebKit page using QWebView and PySide?
I am playing with PySide and QWebView to provide a WebKit version of a webapp on Windows.
Simple and easy to install in a complex working Windows environment where only Internet Explorer exists.
More over using QWebKit it is quite simple :
#!/usr/bin... | How to double buffering a WebKit page using QWebView and PySide? | I am playing with PySide and QWebView to provide a WebKit version of a webapp on Windows.
Simple and easy to install in a complex working Windows environment where only Internet Explorer exists.
More over using QWebKit it is quite simple :
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# hellowebkit.py
# Co... | [
"You can use a QStackedWidget and a QSignalMapper to do that:\nimport sys\nfrom PySide.QtCore import *\nfrom PySide.QtGui import *\nfrom PySide.QtWebKit import *\n\napp = QApplication(sys.argv)\n\n# Create a stack with 2 webviews\nstack = QStackedWidget()\nmapper = QSignalMapper(stack)\nmapper.mapped[int].connect(s... | [
3
] | [] | [] | [
"pyqt",
"pyside",
"python",
"qt4",
"webkit"
] | stackoverflow_0007285976_pyqt_pyside_python_qt4_webkit.txt |
Q:
Implement SMPP in Python
Have you ever heard of really working python-libraries for the realization of the SMPP client and the SMPP server?
A:
I didn't try any of these but it seems there are a couple of SMPP libraries for Python. Of course, most of the projects are dead. Two may be worth looking into though:
... | Implement SMPP in Python | Have you ever heard of really working python-libraries for the realization of the SMPP client and the SMPP server?
| [
"I didn't try any of these but it seems there are a couple of SMPP libraries for Python. Of course, most of the projects are dead. Two may be worth looking into though:\nPythomnik3k\nThe name suggests that this is Python 3 only, but there has been a Python 2 version, too. You may need to ask the author to send y... | [
4,
4,
1
] | [] | [] | [
"python",
"smpp",
"sms"
] | stackoverflow_0003970169_python_smpp_sms.txt |
Q:
basic Python(ic) inheritance question
Quick question about Python(ic) inheritence: what is the difference between the idiom posted here (super(ChildClass,self).method(args)) vs. the one on the Python docs site (ParentClass.method(self,[args]))? Is one more Pythonic than the other?
A:
Using super(ChildClass, self... | basic Python(ic) inheritance question | Quick question about Python(ic) inheritence: what is the difference between the idiom posted here (super(ChildClass,self).method(args)) vs. the one on the Python docs site (ParentClass.method(self,[args]))? Is one more Pythonic than the other?
| [
"Using super(ChildClass, self).method(args) allows you to walk the method resolution order and -- if everyone but the last parent uses super -- call every class in the hierarchy exactly once. (Not that super only works with new-style classes.)\nUsing ParentClass.method(self, args) calls one specific class. It does ... | [
4
] | [] | [] | [
"inheritance",
"oop",
"python"
] | stackoverflow_0007288686_inheritance_oop_python.txt |
Q:
Check if element are in same paragraph (Beautiful soup)
How to check if elements of the BeautifulSoup parse tree are in the same <p> tag?
A:
If you know both nodes are directly underneath a <p> tag, check equality of the nodes nodea.getParent() == nodeb.getParent(); more generally, search (recursively) upwards u... | Check if element are in same paragraph (Beautiful soup) | How to check if elements of the BeautifulSoup parse tree are in the same <p> tag?
| [
"\nIf you know both nodes are directly underneath a <p> tag, check equality of the nodes nodea.getParent() == nodeb.getParent(); more generally, search (recursively) upwards until you hit a <p> tag. Do this separately for each node, then compare the results for equality:\ngetContainingPara(nodea) == getContainingPa... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"text_processing"
] | stackoverflow_0007282988_beautifulsoup_python_text_processing.txt |
Q:
referencing a variable in another function?
I'm an experienced TCL developer and write my own procedures to help myself along. i.e.
a proc i call putsVar, it prints out the value of the variable in a definitave format, so I know which variable it is and what the value is "set foo 1 ; putsVar foo" Result 'foo="1"'
... | referencing a variable in another function? | I'm an experienced TCL developer and write my own procedures to help myself along. i.e.
a proc i call putsVar, it prints out the value of the variable in a definitave format, so I know which variable it is and what the value is "set foo 1 ; putsVar foo" Result 'foo="1"'
I'd like to do the same kind of thing in python, ... | [
"You can, but you shouldn't. If your code downright needs it, then something is wrong with your design, and you probably should be using explicitly passed dictionaries or objects with proper attributes.\nBut, to answer the question directly: you can use sys._getframe. Just be aware that this might not be portable a... | [
1,
0
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0007288713_python_variables.txt |
Q:
Problem importing latest Pyside version
I get:
ImportError: /usr/lib/pymodules/python2.6/PySide/QtCore.so: undefined symbol: _ZN8Shiboken4Enum16createGlobalEnumEP7_objectPKcS4_S4_P11_typeobject
when I do
import PySide
After installing the new version of PySide, version 1.0.6 isolino
Is there a work around?
A:
T... | Problem importing latest Pyside version | I get:
ImportError: /usr/lib/pymodules/python2.6/PySide/QtCore.so: undefined symbol: _ZN8Shiboken4Enum16createGlobalEnumEP7_objectPKcS4_S4_P11_typeobject
when I do
import PySide
After installing the new version of PySide, version 1.0.6 isolino
Is there a work around?
| [
"This could be an old shiboken running with a new PySide version. Could you confirm that you're using the latest version (shiboken 1.0.6)? If you're using Ubuntu, the python-pyside package should ensure that all the modules are properly updated - see http://bugs.pyside.org/show_bug.cgi?id=999\n",
"I get this erro... | [
1,
0
] | [] | [] | [
"pyside",
"python",
"qt"
] | stackoverflow_0007285746_pyside_python_qt.txt |
Q:
SCons if/then statement
I have a single SConscript file in a top level directory and I have many subdirectories with JSON files containing different key/value pair. I have one env.Command() in my SConscript file that I want to be called based on the value of a particular key. What is the best way to do this in S... | SCons if/then statement | I have a single SConscript file in a top level directory and I have many subdirectories with JSON files containing different key/value pair. I have one env.Command() in my SConscript file that I want to be called based on the value of a particular key. What is the best way to do this in Scons?
I was thinking somethin... | [
"This is Python, you cannot put an if/else inside something else like that. However, you can pass arguments to env.Command using a dictionary.\nif Value(params['json_key']) == \"True\":\n kw = {\n 'target': 'out.txt',\n 'source': 'in.txt',\n 'action': 'function $SOURCE $TARGET',\n }\nels... | [
2
] | [] | [] | [
"json",
"python",
"scons"
] | stackoverflow_0007289418_json_python_scons.txt |
Q:
boost.python expose function that returns vector
I'm writing an extension module for Python in C++ and I am using boost.python. I want to expose a function that returns a vector<MyClass>. I'm not exactly sure how to do this and how it will interact with Python WRT memory management.
My first thought was to wrap My... | boost.python expose function that returns vector | I'm writing an extension module for Python in C++ and I am using boost.python. I want to expose a function that returns a vector<MyClass>. I'm not exactly sure how to do this and how it will interact with Python WRT memory management.
My first thought was to wrap MyClass in shared_ptr, thus the function would return ve... | [
"Take a look at Boost.Python's indexing suite.\n",
"If you use vector<MyClass> those instances in the vector are obviously (kind of, since the vector internally uses dynamically allocated memory) stack allocated. It would be different to vector<MyClass*> which is essentially a vector of dynamically allocated MyCl... | [
2,
2,
0
] | [] | [] | [
"boost",
"c++",
"python",
"shared_ptr",
"vector"
] | stackoverflow_0007268496_boost_c++_python_shared_ptr_vector.txt |
Q:
Why do my subprocess calls require a page reload to execute?
I have two separate subprocess calls in a django app, each in a different view. The first calls the dcraw image conversion tool to take an uploaded raw image and convert it into a tiff. (The .tiff output is usually nine times larger than the input, e.g. ... | Why do my subprocess calls require a page reload to execute? | I have two separate subprocess calls in a django app, each in a different view. The first calls the dcraw image conversion tool to take an uploaded raw image and convert it into a tiff. (The .tiff output is usually nine times larger than the input, e.g. 8mb image yields 72mb tiff.)
pdcraw = subprocess.Popen(dcraw_args,... | [
"because the whole idea of a subprocess is being asynchronous, it won't be ready when your view is parsed to the browser.\nPerhaps you make an Ajax request to check the status of the progress, and as soon as files are available, they can then be send by the server.\nOr you work with WebSockets, which can send any d... | [
0
] | [] | [] | [
"django",
"firefox",
"python",
"subprocess"
] | stackoverflow_0007289741_django_firefox_python_subprocess.txt |
Q:
modifying the contents of the sqlilte database
I have the following sqlite3 database:
name : sampledb
table : main
fields : id, name description and gender
sample elements are:
"1" "John" "Fat-Head" "M"
I have around 2000 rows, and want to remove the quotes from each of the field values, so that my db elem... | modifying the contents of the sqlilte database | I have the following sqlite3 database:
name : sampledb
table : main
fields : id, name description and gender
sample elements are:
"1" "John" "Fat-Head" "M"
I have around 2000 rows, and want to remove the quotes from each of the field values, so that my db elements look like:
1 John Fat-Head M
What would be a... | [
"I'm not sure this will be one hundred percent there, or very efficient but try this:\nimport sqlite3\n\ndb = sqlite3.connect('sampledb')\nc = db.cursor()\n\nnew_set = []\n\nc.execute('select * from main')\n\ntemp_value = []\nfor row in c:\n for item in row:\n temp_value.append(item[1:-1])\n new_se... | [
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0007287913_python_sqlite.txt |
Q:
How can I find additional files installed with my python package from an included script?
I've built a python package that installs with a number of external files. I need to be able to read those files from a script that gets installed with the package. I can see that I can use __file__ inside my script, and it r... | How can I find additional files installed with my python package from an included script? | I've built a python package that installs with a number of external files. I need to be able to read those files from a script that gets installed with the package. I can see that I can use __file__ inside my script, and it returns something like this:
/Library/Python/2.6/site-packages/M5-0.3.0-py2.6.egg/EGG-INFO/scrip... | [
"You might want something like the \npkgutil.get_data function. \nIt will read in resources relative to __file__ if your package lives as a standard python package directory structure on the disk, and I think it will read resources out of a zipped egg as well (though I've not used it for that myself).\n",
"does ... | [
2,
1
] | [] | [] | [
"distutils",
"python",
"setuptools"
] | stackoverflow_0007289520_distutils_python_setuptools.txt |
Q:
Control automatically imported modules
Basically, I am cramming python into an embedded environment where I can't compile/configure it on the system itself. I am not surprised that the site module refuses to load; but that's okay, I don't need it. How do I control which modules python automatically imports?
Notes... | Control automatically imported modules | Basically, I am cramming python into an embedded environment where I can't compile/configure it on the system itself. I am not surprised that the site module refuses to load; but that's okay, I don't need it. How do I control which modules python automatically imports?
Notes, this is a static build, and the only thing... | [
"Starting Python with the -S flag suppresses the automatic importing of the site module. Others, such as signal and readline, are actually built in. So you can just use the -S flag and then in your main script import what you need. Make sure you at least call sys.setdefaultencoding(\"ascii\") (or \"utf-8\") early.... | [
2
] | [] | [] | [
"configuration",
"python"
] | stackoverflow_0007289489_configuration_python.txt |
Q:
Using beaker sessions for checking if user is authenticated in Pyramid
I'm creating a webapp using Pyramid with Beaker sessions.
I would like to store user id in request.session['user_id'] and some other info after successful signing in and then use it for checking if user already signed in:
if 'user_id' in requ... | Using beaker sessions for checking if user is authenticated in Pyramid | I'm creating a webapp using Pyramid with Beaker sessions.
I would like to store user id in request.session['user_id'] and some other info after successful signing in and then use it for checking if user already signed in:
if 'user_id' in request.session:
# user signed in
else:
# user not signed in or session ... | [
"Use pyramid_beaker and the SessionAuthenticationPolicy, then use pyramid.authentication.authenticated_userid() to check if they're logged in or not. If it returns None, they're not.\n"
] | [
11
] | [] | [] | [
"authentication",
"pyramid",
"python",
"session"
] | stackoverflow_0007281884_authentication_pyramid_python_session.txt |
Q:
Add SSL support to Python for existing Plone 3.3.4 install
I have an existing Plone 3.3.4 installation that was created using the Unified Installer. The python packaged with the Unified Installer does not include SSL support. How would I go about adding SSL support to an existing installation? Do i need to rebu... | Add SSL support to Python for existing Plone 3.3.4 install | I have an existing Plone 3.3.4 installation that was created using the Unified Installer. The python packaged with the Unified Installer does not include SSL support. How would I go about adding SSL support to an existing installation? Do i need to rebuild python, then run bootstrap and buildout to get have it enabl... | [
"Easiest path: re-run the unified installer, specifying a different target. If it finds libssl this time, you're set. If not, try again, and use --with-python to pick your python2.4.6 that has ssl support. And, you might as well update to 3.3.6 while you're at it.\nAlternatively, install distribute for your new Pyt... | [
4,
1
] | [] | [] | [
"bootstrapping",
"buildout",
"plone",
"python",
"ssl"
] | stackoverflow_0007287360_bootstrapping_buildout_plone_python_ssl.txt |
Q:
Access class instance from one file in another file?
I have two files, both are in the same project (part of a web scraping framework). File1 processes items that are generated by File2. In File2 I have a function that prints out some basic stats about the processes (counts of how many items have been generated,... | Access class instance from one file in another file? | I have two files, both are in the same project (part of a web scraping framework). File1 processes items that are generated by File2. In File2 I have a function that prints out some basic stats about the processes (counts of how many items have been generated, etc). I have counts in File1 that I would like to print ... | [
"This is not working because you never instantiate Class1.\n__init__ is called when the Class1 is instantiated so Class1.stats is set.\nYou have 2 options here.\n\ninstantiate Class1 in file 2 somehow.\ndeclare a static method in Class1 that returns the count property.\n\n",
"Your terminology is a little mixed up... | [
8,
4,
3
] | [] | [] | [
"class",
"instance",
"python"
] | stackoverflow_0007290164_class_instance_python.txt |
Q:
python tkinter: displays only a portion of an image
This only displays the bottom right corner of my image. What am I doing wrong?
from Tkinter import *
from PIL import Image, ImageTk
class Application(Frame):
def __init__(self, titl, master=None):
Frame.__init__(self, master)
self.grid()
... | python tkinter: displays only a portion of an image | This only displays the bottom right corner of my image. What am I doing wrong?
from Tkinter import *
from PIL import Image, ImageTk
class Application(Frame):
def __init__(self, titl, master=None):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
self.master.title(tit... | [
"You have to set the anchor to NW (NorthWest) because its value is CENTER by default, which as the name suggests centers the image on the given coordinates:\nself.canvas.create_image(0,0, image=image1, anchor=NW)\n\nOr you can change that later if you keep the image id:\nself.idImage = self.canvas.create_image(0,0,... | [
8
] | [] | [] | [
"image",
"python",
"tkinter"
] | stackoverflow_0007288732_image_python_tkinter.txt |
Q:
How to get 'command-line intellisense' (TAB TAB) to work with a Python script?
My Python script accepts a number of options such as the following:
python ./Controller.py create 1
python ./Controller.py destroy
Is there anyways I can get intellisense to work in the command-line? For instance, typing the following:... | How to get 'command-line intellisense' (TAB TAB) to work with a Python script? | My Python script accepts a number of options such as the following:
python ./Controller.py create 1
python ./Controller.py destroy
Is there anyways I can get intellisense to work in the command-line? For instance, typing the following:
python ./Controller.py <TAB><TAB>
should give the following:
create - <description... | [
"AFAIK, the only way to do something along these lines is to provide help when the user enters something like python ./Controller.py -h. Take a look at the argparse module for hints on how to incorporate it into your script.\n",
"For bash, this feature is known as Bash Completion. Other shells may have similar fu... | [
1,
1
] | [] | [] | [
"command_line",
"intellisense",
"python",
"shell"
] | stackoverflow_0007290513_command_line_intellisense_python_shell.txt |
Q:
Pass variables after form submitted
I have a post form that calls Amazon's S3 service. I am doing a direct from browser upload to amazon, and thus have to pass some additional information to Amazon, that I will not know until the file is uploaded (file-type, name, 'signature' which references both). http://aws.ama... | Pass variables after form submitted | I have a post form that calls Amazon's S3 service. I am doing a direct from browser upload to amazon, and thus have to pass some additional information to Amazon, that I will not know until the file is uploaded (file-type, name, 'signature' which references both). http://aws.amazon.com/articles/1434
It is a large video... | [
"You're probably looking for Query String Request Authentication Alternative.\n\nYou can authenticate certain types of requests by passing the required\n information as query-string parameters instead of using the\n Authorization HTTP header. This is useful for enabling direct\n third-party browser access to you... | [
1
] | [] | [] | [
"amazon_s3",
"post",
"python"
] | stackoverflow_0007290457_amazon_s3_post_python.txt |
Q:
How to convert algorithm to python
new to python and I'm having trouble converting a script to a more effective algorithm I was given.
Here's the python code:
#!/usr/bin/env python
import itertools
target_sum = 10
a = 1
b = 2
c = 4
a_range = range(0, target_sum + 1, a)
b_range = range(0, target_sum + 1, b)
c_rang... | How to convert algorithm to python | new to python and I'm having trouble converting a script to a more effective algorithm I was given.
Here's the python code:
#!/usr/bin/env python
import itertools
target_sum = 10
a = 1
b = 2
c = 4
a_range = range(0, target_sum + 1, a)
b_range = range(0, target_sum + 1, b)
c_range = range(0, target_sum + 1, c)
for i, j... | [
"You can get that block which creates the table for dynamic programming with this:\nfrom collections import defaultdict\n\n# T[x, i] is True if 'x' can be solved\n# by a linear combination of data[:i+1]\nT = defaultdict(bool) # all values are False by default\nT[0, 0] = True # base case\n\n... | [
2,
1
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0007279641_algorithm_python.txt |
Q:
Getting every child widget of a Tkinter window
Is it possible to get all of the children of a Tkinter widget, then get the children's children etc.?
Basically I want all of the widgets within one entire window.
Edit :
I found a solution utilizing Bryan's line :
def all_children (wid) :
_list = wid.winfo_child... | Getting every child widget of a Tkinter window | Is it possible to get all of the children of a Tkinter widget, then get the children's children etc.?
Basically I want all of the widgets within one entire window.
Edit :
I found a solution utilizing Bryan's line :
def all_children (wid) :
_list = wid.winfo_children()
for item in _list :
if item.winfo... | [
"The method you are looking for is winfo_children.\n"
] | [
35
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007290071_python_tkinter.txt |
Q:
Alternative to zc.buildout that runs on Python3
My project uses buildout to do primarily two things: automatically fetch dependencies and create scripts; and setup cron jobs (on deployment machines) using the usercrontab buildout recipe.
But buildout is not yet available for Python 3.
So I would like to consider a... | Alternative to zc.buildout that runs on Python3 | My project uses buildout to do primarily two things: automatically fetch dependencies and create scripts; and setup cron jobs (on deployment machines) using the usercrontab buildout recipe.
But buildout is not yet available for Python 3.
So I would like to consider alternatives for buildout. I know that both virtualenv... | [
"Buildout 2 is in alpha at the time of this writing. It supports Python 3.\n",
"I wrote my own toolset on top of Fabric that does the core of what zc.buildout does. See https://github.com/srid/fablib\n"
] | [
3,
1
] | [] | [] | [
"buildout",
"packaging",
"python",
"python_3.x",
"virtualenv"
] | stackoverflow_0002837763_buildout_packaging_python_python_3.x_virtualenv.txt |
Q:
What is the easiest way to display a JPG using wxPython?
All the examples I've seen seem very complicated.
Thanks!
A:
The wx demo has an image example, under Using Images|Image. It shows how to convert and display a jpg, and other types as well. If you don't already have the demo, you can get it from the main ... | What is the easiest way to display a JPG using wxPython? | All the examples I've seen seem very complicated.
Thanks!
| [
"The wx demo has an image example, under Using Images|Image. It shows how to convert and display a jpg, and other types as well. If you don't already have the demo, you can get it from the main wx download page.\n"
] | [
3
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0007288543_python_wxpython.txt |
Q:
urlparse.urlparse returning 3 '/' instead of 2 after scheme
I'd like to add the 'http' scheme name in front of a given url string if it's missing. Otherwise, leave the url alone so I thought urlparse was the right way to do this. But whenever there's no scheme and I use get url, I get /// instead of '//' between t... | urlparse.urlparse returning 3 '/' instead of 2 after scheme | I'd like to add the 'http' scheme name in front of a given url string if it's missing. Otherwise, leave the url alone so I thought urlparse was the right way to do this. But whenever there's no scheme and I use get url, I get /// instead of '//' between the scheme and domain.
>>> t = urlparse.urlparse('www.example.com'... | [
"Short answer (but it's a bit tautological):\n>>> urlparse.urlparse(\"http://www.example.com\").geturl()\n'http://www.example.com'\n\nIn your example code, the hostname is parsed as a path not a network location:\n>>> urlparse.urlparse(\"www.example.com/go\")\nParseResult(scheme='', netloc='', path='www.example.com... | [
6,
2
] | [] | [] | [
"python",
"urlparse"
] | stackoverflow_0007289481_python_urlparse.txt |
Q:
python-twitter streaming api support/example
I was working with python-twitter and realized that twitter provides streaming api to consume tweets in realtime. I found one example that uses pyCurl here
Have anyone tried or know how to use that with python-twitter library? please let me know
Thank you
A:
Tweepy... | python-twitter streaming api support/example | I was working with python-twitter and realized that twitter provides streaming api to consume tweets in realtime. I found one example that uses pyCurl here
Have anyone tried or know how to use that with python-twitter library? please let me know
Thank you
| [
"Tweepy has good modules for streaming. You can see examples here. \n",
"Check out tweetstream for a nice high-level library to access twitter's streaming API.\n",
"python-twitter doesn't support twitter's real time API.\nYou will have to use Twisted, Tornado or Eventlet to consume such a real time API.\nI know... | [
8,
6,
1
] | [] | [] | [
"python",
"streaming",
"twitter"
] | stackoverflow_0004243038_python_streaming_twitter.txt |
Q:
Safe and lazy method invocations in PySide/PyQt
I'm using PySide to manage some hardware and perform some relatively simple operations depending on (e.g.) button clicks in the interface. The code for running each of these pieces of hardware resides in another thread. For convenience, to all of those hardware drive... | Safe and lazy method invocations in PySide/PyQt | I'm using PySide to manage some hardware and perform some relatively simple operations depending on (e.g.) button clicks in the interface. The code for running each of these pieces of hardware resides in another thread. For convenience, to all of those hardware drivers I've added a generic invoke_method signal, such th... | [
"I'd recommend reading this post for a general approach to interface threads with a PyQt GUI. The post discusses a thread that does socket I/O, but this really is applicable to any thread. Specifically, hardware-interface threads usually also use I/O, so this may be a good fit.\nThe approach discussed is very gener... | [
4
] | [] | [] | [
"pyqt",
"pyside",
"python",
"thread_safety"
] | stackoverflow_0007290714_pyqt_pyside_python_thread_safety.txt |
Q:
Show Python variables as children of function in Tagbar (gVim, with exuberant ctags)
I am trying to show variables inside functions in Tagbar for gVim. Currently, functions are shown inside classes, and variables are shown inside classes, but variables are not shown inside functions. I would like to be able to see... | Show Python variables as children of function in Tagbar (gVim, with exuberant ctags) | I am trying to show variables inside functions in Tagbar for gVim. Currently, functions are shown inside classes, and variables are shown inside classes, but variables are not shown inside functions. I would like to be able to see which variables are used inside each function.
I have tried messing around with 'kind2sco... | [
"This is a (maybe intentional) limitation of Exuberant Ctags to not show local variables in any language. If that got implemented in ctags it would be trivial to adjust Tagbar to make use of it -- depending on the exact implementation Tagbar would potentially not need any changes at all. But it would definitely nee... | [
0
] | [] | [] | [
"ctags",
"python",
"tagbar",
"vim"
] | stackoverflow_0007097525_ctags_python_tagbar_vim.txt |
Q:
How to access HttpRequest from urls.py in Django 1.2
I need to do the same thing asked in How to access HttpRequest from urls.py in Django but using version 1.2. Sorry, is what I have. I don't want to clutter the urls.py, so the two solutions given are not valid for me :)
Thank you very much for your time.
A:
fr... | How to access HttpRequest from urls.py in Django 1.2 | I need to do the same thing asked in How to access HttpRequest from urls.py in Django but using version 1.2. Sorry, is what I have. I don't want to clutter the urls.py, so the two solutions given are not valid for me :)
Thank you very much for your time.
| [
"from django.views.generic.list_detail import object_list\n\nurl('^URL_HERE/(?P<object_id>\\d+)$', lambda request, *a, **k: object_detail(request, *a,\n queryset=MyModel.objects.filter(user=request.user),\n template=\"myapp/mytmplate.html\", **k) )\n\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007273296_django_python.txt |
Q:
Write a string of 1's and 0's to a binary file?
I want to take a string of 1's and 0's and convert it into an actual binary file(simply writing the string of 1's and 0's to a file would just make it either ascii file containing "00110001"s and "00110000"s ). I would prefer to do this in python or directly from a ... | Write a string of 1's and 0's to a binary file? | I want to take a string of 1's and 0's and convert it into an actual binary file(simply writing the string of 1's and 0's to a file would just make it either ascii file containing "00110001"s and "00110000"s ). I would prefer to do this in python or directly from a bash shell, but java or C is fine too. this is probab... | [
"In Python, use the int built-in function to convert the string of 0s and 1s to a number:\n>>> int(\"00100101\", 2)\n37\n\nThen use the chr built-in to convert a 8-bit integer (that is, in the inclusive range 0-255) to a character.\n>>> chr(_)\n'%'\n\nThe result of chr can be simply written to a file (opened in bin... | [
19,
9,
3,
1,
1
] | [] | [] | [
"bash",
"c",
"java",
"python"
] | stackoverflow_0007290943_bash_c_java_python.txt |
Q:
Problems With Aptana Studio (and/or Python) under Lion
After installing Lion, Aptana has stopped working -- I can no longer run any Python code, despite me failing to find any other problems with Python my system. I've tried restoring defaults in Aptana, re-installing and looking for any missing references in Apt... | Problems With Aptana Studio (and/or Python) under Lion | After installing Lion, Aptana has stopped working -- I can no longer run any Python code, despite me failing to find any other problems with Python my system. I've tried restoring defaults in Aptana, re-installing and looking for any missing references in Aptana to python components.
Running a simple "hello world" .py... | [
"Have you tried removing your interpreter and adding it again (that way PyDev would update your PYTHONPATH? \nIt seems like the problem is that the math.so is not compatible with the latest changes in Lion (so, maybe in the update for Lion it got to 2.7 and you're still with 2.6 in the PYTHONPATH configure in Eclip... | [
1
] | [] | [] | [
"aptana",
"python"
] | stackoverflow_0007262025_aptana_python.txt |
Q:
Python string manipulation -- performance problems
I have the following piece of code that I execute around 2 million times in my application to parse that many records. This part seems to be the bottleneck and I was wondering if anyone could help me by suggesting some nifty tricks that could make these simple str... | Python string manipulation -- performance problems | I have the following piece of code that I execute around 2 million times in my application to parse that many records. This part seems to be the bottleneck and I was wondering if anyone could help me by suggesting some nifty tricks that could make these simple string manipulations faster.
try:
data = []
start =... | [
"def fubarise(data):\n try:\n if nasty(data):\n raise ValueError(\"Look, Ma, I'm doing a big fat GOTO ...\") # sheesh #1\n more_of_the_same()\n parsed_line = data\n except ValueError:\n parsed_line = False\n # so it can be a \"data\" or False -- sheesh #2\n ret... | [
3,
2,
1,
1,
1,
0
] | [] | [] | [
"performance",
"python",
"string"
] | stackoverflow_0007287654_performance_python_string.txt |
Q:
Splitting a HTML document using lxml.html
I have a HTML document containing multiple chapters of text where the H1 tag is the chapter separator. How can I split such a document into html snippets where each snippet starts with the h1 tag of the corresponding "chapter". I though of prettifying the HTML and then ite... | Splitting a HTML document using lxml.html | I have a HTML document containing multiple chapters of text where the H1 tag is the chapter separator. How can I split such a document into html snippets where each snippet starts with the h1 tag of the corresponding "chapter". I though of prettifying the HTML and then iterating of the content line by line...but that's... | [
"tree = lxml.html.document_fromstring(htmltext)\nfor element in tree.iter():\n if element.tag == 'h1':\n for subelement in element:\n // do stuff\n\nThat'll find the elements that are h1 tags and then you can iterate through all its subelements. You could also just take all the text inside the element as a... | [
6
] | [] | [] | [
"html",
"lxml",
"python"
] | stackoverflow_0007293141_html_lxml_python.txt |
Q:
Creation of StringToSign
I am reading the documentation of passing a querystring to Amazon's S3 for authentication, and can't seem to grok how exactly the StringToSign is created and used. I am looking for a concrete example to illustrate (1) how to construct the StringToSign, and (2) once I have the signature, ho... | Creation of StringToSign | I am reading the documentation of passing a querystring to Amazon's S3 for authentication, and can't seem to grok how exactly the StringToSign is created and used. I am looking for a concrete example to illustrate (1) how to construct the StringToSign, and (2) once I have the signature, how to call the form.
For exampl... | [
"Based on what you described, it seems like you want to support browser-based uploads using POST. There is a section of the AWS documentation which talks about this.\nAs an overview keep in mind you'll either have to make your bucket publically writeable or include a policy document. I'll assume you'll be including... | [
2
] | [] | [] | [
"amazon_s3",
"python"
] | stackoverflow_0007290684_amazon_s3_python.txt |
Q:
Converting a list of integers into a single value
If I had list of integers say,
x = [1,2,3,4,5]
Is there an in-built function that can convert this into a single number like 12345? If not, what's the easiest way?
A:
>>> listvar = [1,2,3,4,5]
>>> reduce(lambda x,y:x*10+y, listvar, 0)
12345
A:
If they're digi... | Converting a list of integers into a single value | If I had list of integers say,
x = [1,2,3,4,5]
Is there an in-built function that can convert this into a single number like 12345? If not, what's the easiest way?
| [
">>> listvar = [1,2,3,4,5]\n>>> reduce(lambda x,y:x*10+y, listvar, 0)\n12345\n\n",
"If they're digits like this, \nsum(digit * 10 ** place for place, digit in enumerate(reversed(x)))\n\n",
"int(\"\".join(str(X) for X in x))\n\nYou have not told us what the result for x = [1, 23, 4] should be by the way...\nMy a... | [
5,
4,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007293388_python.txt |
Q:
Python: script's directory
I was looking for a solution, but have not found what I need.
Script path: /dir/to/script/script.py or C:\dir\script.py
Excepted result:
$ ./script.py
output: /dir/to/script
$ cd .. && ./script/script.py
output: /dir/to/script
Is there any function in os module or something?
I mixed so... | Python: script's directory | I was looking for a solution, but have not found what I need.
Script path: /dir/to/script/script.py or C:\dir\script.py
Excepted result:
$ ./script.py
output: /dir/to/script
$ cd .. && ./script/script.py
output: /dir/to/script
Is there any function in os module or something?
I mixed solutions and write:
print os.path... | [
"os.path.realpath will give you the result:\nos.path.dirname(os.path.realpath(__file__))\n\n"
] | [
15
] | [] | [] | [
"directory",
"python"
] | stackoverflow_0007293601_directory_python.txt |
Q:
Python Module Installation Problems
I'm having a ton of trouble installing modules. At first I thought I had messed with my python installation on mac os x but I installed a virtual machine and ubuntu 11.04 and have similar troubles. Why are both os x and ubuntu failing with the same error?
For example I can't ins... | Python Module Installation Problems | I'm having a ton of trouble installing modules. At first I thought I had messed with my python installation on mac os x but I installed a virtual machine and ubuntu 11.04 and have similar troubles. Why are both os x and ubuntu failing with the same error?
For example I can't install tkinter with it failing:
Installing ... | [
"I encountered exactly the same problem when trying to install tkinter-pypy on Ubuntu 11.04. The error message shows that it's looking for tcl.h file in /usr/include/tcl, but it's not there. I have to install the dev version of the tcl library (I installed tcl8.4-dev). \nsudo apt-get install tcl8.4-dev\nThis instal... | [
5,
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006644371_python_tkinter.txt |
Q:
Python regex: how to replace each instance of an occurrence with a different value?
Suppose I have this string:
s = "blah blah blah"
Using Python regex, how can I replace each instance of "blah" with a different value (e.g. I have a list of values v = ("1", "2", "3")
A:
You could use a re.sub callback:
import re... | Python regex: how to replace each instance of an occurrence with a different value? | Suppose I have this string:
s = "blah blah blah"
Using Python regex, how can I replace each instance of "blah" with a different value (e.g. I have a list of values v = ("1", "2", "3")
| [
"You could use a re.sub callback:\nimport re\ndef callback(match):\n return next(callback.v)\ncallback.v=iter(('1','2','3'))\n\ns = \"blah blah blah\"\nprint(re.sub(r'blah',callback,s))\n\nyields\n1 2 3\n\n",
"You could use re.sub, which takes a string or function and applies it to each match:\n>>> re.sub('bla... | [
22,
13,
2,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007293750_python_regex.txt |
Q:
Accessing Java API information with Python
I'm looking for a very simple way, from Python, to get information about Java classes:
name of the class
what it extends and implements
methods with returns types and parameters
attributes with type information
Basically all of the information you'd need to generate a j... | Accessing Java API information with Python | I'm looking for a very simple way, from Python, to get information about Java classes:
name of the class
what it extends and implements
methods with returns types and parameters
attributes with type information
Basically all of the information you'd need to generate a javadoc.
Is there an existing Python library that... | [
"If your Python code does not make much use of C based libraries you could run the code in Jython which is Python run on the Java VM.\nOtherwise you could write a small Java/jython executable that gets the information and writes it to stdout to be read by a CPython program calling it.\n"
] | [
1
] | [] | [] | [
"java",
"python"
] | stackoverflow_0007293618_java_python.txt |
Q:
repeat an iteration of for loop
if for some reason i want to repeat the same iteration how i can do it in python?
for eachId in listOfIds:
#assume here that eachId conatins 10
response = makeRequest(eachId) #assume that makeRequest function request to a url by using this id
if response == 'market is cl... | repeat an iteration of for loop | if for some reason i want to repeat the same iteration how i can do it in python?
for eachId in listOfIds:
#assume here that eachId conatins 10
response = makeRequest(eachId) #assume that makeRequest function request to a url by using this id
if response == 'market is closed':
time.sleep(24*60*60) #s... | [
"Do it like this:\nfor eachId in listOfIds:\n successful = False\n while not successful: \n response = makeRequest(eachId)\n if response == 'market is closed':\n time.sleep(24*60*60) #sleep for one day\n else:\n successful = True\n\nThe title of your question ... | [
41,
8,
1,
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0007293978_for_loop_python.txt |
Q:
Python cross-module logging
I've googled and looked at the default documentation, but I can't figure out why this doesn't produce three lines of logging:
# main.py
import logging
import apple
import banana
log = logging.getLogger('main')
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(loggin... | Python cross-module logging | I've googled and looked at the default documentation, but I can't figure out why this doesn't produce three lines of logging:
# main.py
import logging
import apple
import banana
log = logging.getLogger('main')
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.For... | [
"The handler (StreamHandler) was not setup until after the imports. So the logging commands in the imported modules do not produce any output. Some handlers print to files, others communicate over a network, and some print to a console. There's no way the logging statements inside the imported modules could know wh... | [
9
] | [] | [] | [
"logging",
"module",
"python"
] | stackoverflow_0007294127_logging_module_python.txt |
Q:
Override shouldInterruptJavaScript in QWebPage with PySide
I would like to override PySide.QtWebKit.QWebPage.shouldInterruptJavaScript() slot to silently ignore JavaScript interrupt requests. I have my own timeout timer setup and I do not need a default message dialog.
Quoting PySide documentation:
Because of bin... | Override shouldInterruptJavaScript in QWebPage with PySide | I would like to override PySide.QtWebKit.QWebPage.shouldInterruptJavaScript() slot to silently ignore JavaScript interrupt requests. I have my own timeout timer setup and I do not need a default message dialog.
Quoting PySide documentation:
Because of binary compatibility constraints, this function is not virtual. If ... | [
"This is now fixed on PySide git master after the release 1.0.6.\n"
] | [
0
] | [] | [] | [
"pyside",
"python",
"qt",
"qtwebkit",
"qwebpage"
] | stackoverflow_0006868286_pyside_python_qt_qtwebkit_qwebpage.txt |
Q:
Programming Novice-Slickdeals.net, level of programming knowledge
I am interested in creating a website for gardeners but in similar format to slickdeals.net, in terms of having a login page, front page, and up/down votes for comments in forum.
If I plan on using python, what how long and how difficult will it ta... | Programming Novice-Slickdeals.net, level of programming knowledge | I am interested in creating a website for gardeners but in similar format to slickdeals.net, in terms of having a login page, front page, and up/down votes for comments in forum.
If I plan on using python, what how long and how difficult will it take me to build something like this? I have never programmed before, exc... | [
"For such a complicated site, I'd estimate at least 6 man-months for experienced developers (don't forget you need to set up servers, databases, create a design etc.).\nAs you're apparently not experienced in website creation, you have two options:\n\nIf it's a big project, hire one or more experienced developers (... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007294403_python.txt |
Q:
Django localeURL when WSGIScriptAlias is /PREFIX
Introduction
I Got a question about localeURL usage.
Everything works great for me with url like this :
http://www.example.com/
If I type http://www.example.com/ in address bar, it turns correctly in http://www.example.com/en/ for example.
If I use the view chang... | Django localeURL when WSGIScriptAlias is /PREFIX | Introduction
I Got a question about localeURL usage.
Everything works great for me with url like this :
http://www.example.com/
If I type http://www.example.com/ in address bar, it turns correctly in http://www.example.com/en/ for example.
If I use the view change_locale, it's also all right (ie change www.example.c... | [
"You should not be hard wiring SERVER_PREFIX in settings. The mount prefix for the site is available as SCRIPT_NAME in the WSGI environ dictionary. Thus from memory is available as request.META.get('SCRIPT_NAME').\n",
"try this (I am not sure whether it will work though):\n\nWSGIScriptAliasMatch ^/MY_PREFIX(/.*)?... | [
3,
0
] | [] | [] | [
"django",
"django_urls",
"django_wsgi",
"mod_wsgi",
"python"
] | stackoverflow_0002988394_django_django_urls_django_wsgi_mod_wsgi_python.txt |
Q:
Can you reference a class inside of itself in Python?
If I have classes A and B, I basically want to do something like this:
class A:
myDict = {A: 3, B: 2}
Since my reference isn't in a function, the class hasn't fully loaded by the time I try to use it. How can I get around this?
A:
The proper solution i... | Can you reference a class inside of itself in Python? | If I have classes A and B, I basically want to do something like this:
class A:
myDict = {A: 3, B: 2}
Since my reference isn't in a function, the class hasn't fully loaded by the time I try to use it. How can I get around this?
| [
"The proper solution is to move the dict outside the class\nclass A:\n pass\n\nA.mydict = {A: 3, B: 2}\n\nwhich will result in exactly the values you would get if you could do what you ask for.\n"
] | [
5
] | [] | [] | [
"class",
"python",
"recursion"
] | stackoverflow_0007294371_class_python_recursion.txt |
Q:
Strange thing about tabbar.. Help me to solve
I just started learning pyqt.. When i'm experimenting with the tabbar i encountered this.. As a minimal example i want to show a button in tab1 and a label in tab2.. Here's what i did
from PyQt4 import QtGui
class Ui_TabWidget(QtGui.QTabWidget):
def __i... | Strange thing about tabbar.. Help me to solve | I just started learning pyqt.. When i'm experimenting with the tabbar i encountered this.. As a minimal example i want to show a button in tab1 and a label in tab2.. Here's what i did
from PyQt4 import QtGui
class Ui_TabWidget(QtGui.QTabWidget):
def __init__(self,parent=None):
QtGui.QTabWidget._... | [
"I know it's been a while since this question was asked, but I notice your response to the previous answer was that you needed to be able to customize the tabs using stylesheets. This is also possible when using QTabWidget! Since all QWidgets have setStyleSheet(), and QTabWidget uses a QTabBar under the hood, you c... | [
2,
1
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0001926863_pyqt_python.txt |
Q:
How can I keep a list of recently seen users without running out of RAM/crashing my DB?
Here's some code that should demonstrate what I'm trying to do:
current_time = datetime.datetime.now()
recently_seen = []
user_id = 10
while True:
if user_id not in recently_seen:
recently_seen[user_id] = current... | How can I keep a list of recently seen users without running out of RAM/crashing my DB? | Here's some code that should demonstrate what I'm trying to do:
current_time = datetime.datetime.now()
recently_seen = []
user_id = 10
while True:
if user_id not in recently_seen:
recently_seen[user_id] = current_time
print 'seen {0}'.format(user_id)
else:
if current_time - recently_... | [
"How about removing the user from your dictionary once you log them to the database?\n",
"Why aren't you using a DBM?\nIt will work like a dictionary but will be stored on the disk.\n"
] | [
0,
0
] | [] | [] | [
"authentication",
"dictionary",
"list",
"python",
"time"
] | stackoverflow_0004989049_authentication_dictionary_list_python_time.txt |
Q:
Python Emailing - Use of colon causes no output
Really odd experience with this which took me over an hour to figure out. I have a cgi script written in python which takes form data and forwards it to an email, the problem was, if there was a colon in the string it would cause python to output nothing to the email... | Python Emailing - Use of colon causes no output | Really odd experience with this which took me over an hour to figure out. I have a cgi script written in python which takes form data and forwards it to an email, the problem was, if there was a colon in the string it would cause python to output nothing to the email.
Does anyone know why this is?
For example:
output =... | [
"Colon isn't a special character in python string output, but it is special to email headers. Try inserting a blank line in the output:\noutput = \"\\nPrint: Customer\"\n\n",
"Allow me to make a few guesses:\n\nThe mail is actually being sent, but the body appears to be empty (You question doesn't say this).\nYou... | [
6,
2
] | [] | [] | [
"email",
"python"
] | stackoverflow_0007294885_email_python.txt |
Q:
Memory model for apache/modwsgi application in python?
In a regular application (like on Windows), when objects/variables are created on a global level it is available to the entire program during the entire duration the program is running.
In a web application written in PHP for instance, all variables/objects ar... | Memory model for apache/modwsgi application in python? | In a regular application (like on Windows), when objects/variables are created on a global level it is available to the entire program during the entire duration the program is running.
In a web application written in PHP for instance, all variables/objects are destroyed at the end of the script so everything has to be... | [
"Go read the following from the official mod_wsgi documentation:\nhttp://code.google.com/p/modwsgi/wiki/ProcessesAndThreading\nIt explains the various modes things can be run in and gives some general guidelines about data scope and sharing.\n",
"All Python globals are created when the module is imported. When mo... | [
1,
0
] | [] | [] | [
"apache",
"memory_management",
"mod_wsgi",
"python"
] | stackoverflow_0007293290_apache_memory_management_mod_wsgi_python.txt |
Q:
psycopg installation problem
I've recently installed django and psycop2. However python is refusing to use it below is the error. Can someone please help?
>>> import psycopg2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7... | psycopg installation problem | I've recently installed django and psycop2. However python is refusing to use it below is the error. Can someone please help?
>>> import psycopg2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/psycopg2/__init__.p... | [
"macports is terrible for python/django development, everything seems to be out of data.\nI have my team doing the following for postgres:\n\nDownload and install postgresql 9.0 but read the README before\ninstalling !!!\nDownload psycopg2 source from http://initd.org/pub/software/psycopg/\nEdit the setup.cfg to se... | [
1
] | [] | [] | [
"django",
"psycopg2",
"python"
] | stackoverflow_0007290747_django_psycopg2_python.txt |
Q:
Cascade on update and delete wih django
I cannot find an option to cascade update or delete in the model api. Am wondering if there is a manual out there that can help me pass this db option when sycning the db.
any idea's?
A:
Look at the ForeignKey docs. It says:
When an object referenced by a ForeignKey is ... | Cascade on update and delete wih django | I cannot find an option to cascade update or delete in the model api. Am wondering if there is a manual out there that can help me pass this db option when sycning the db.
any idea's?
| [
"Look at the ForeignKey docs. It says: \n\nWhen an object referenced by a ForeignKey is deleted, Django by default emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey. This behavior can be overridden by specifying the on_delete argument.\n\nSo the defa... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007295417_django_python.txt |
Q:
Python: Formatting text to specific column
I would like to format some text to the protein data bank file format. Basically what I need to do is start the text in specific columns. Right now I'm doing the formatting using ljust and rjust but I feel like there should be some magic function that I could use give a... | Python: Formatting text to specific column | I would like to format some text to the protein data bank file format. Basically what I need to do is start the text in specific columns. Right now I'm doing the formatting using ljust and rjust but I feel like there should be some magic function that I could use give a word and in what column it should start.
Any he... | [
"Here is an example of how one might format a \"Coordinate Record Description\" using str.format:\nCRD='{r:<6}{a:>9.3f}{b:>9.3f}{c:>9.3f}{alpha:7.2f}{beta:7.2f}{gamma:7.2f} {sp:<11}{z:>4}'\n\ndata=dict(r='CRYST1',a=117,b=15.0,c=39,alpha=90,beta=90,gamma=90,sp='P 21 21 21',z=8)\nprint(CRD.format(**data))\n\n# CRYST1... | [
1,
0
] | [] | [] | [
"python",
"string_formatting"
] | stackoverflow_0007295639_python_string_formatting.txt |
Q:
Identify class module from a class function
I want to code the apply_method function:
class A:
def calc(self, num):
return num
def apply_method(class_method, *args, **kwargs):
# Identify class module A from class_method: Is this possible?
# Import class module A
# Create an instance of the ... | Identify class module from a class function | I want to code the apply_method function:
class A:
def calc(self, num):
return num
def apply_method(class_method, *args, **kwargs):
# Identify class module A from class_method: Is this possible?
# Import class module A
# Create an instance of the class A, say obj
# return obj.class_method(*a... | [
"Play around with some of the __ methods in the interpreter. Everything you need should be available in one form or another:\nIn [6]: class_method = A.calc\nIn [7]: class_method.__class__\nOut[7]: <type 'instancemethod'>\n\nIn [8]: class_method.__func__\nOut[8]: <function calc at 0x101625938>\n\nIn [9]: class_meth... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007295867_python.txt |
Q:
print redirected to file SOMETIMES results in incomplete printout in python
I want to save list to a file so I cycle through it and write it to file. Everything's fine. But SOMETIMES(!?!?) the list is not written entirely, it stops rendering in the middle of the item. No error is raised, it silently continues exec... | print redirected to file SOMETIMES results in incomplete printout in python | I want to save list to a file so I cycle through it and write it to file. Everything's fine. But SOMETIMES(!?!?) the list is not written entirely, it stops rendering in the middle of the item. No error is raised, it silently continues executing rest of the code.
I've tried several ways to write it out, several versions... | [
"Close the file when done with all the writes to ensure any write-caching is flushed to the drive with:\nwritewtsi.close()\n\n",
"Does the problem persist if you use:\nwith open(\"c:/files/wtsi.txt\", \"w\") as writewtsi:\n for i in range(net.ni):\n print>>writewtsi, net.wi[i] \n\n",
"use\n... | [
2,
0,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0007295530_file_python.txt |
Q:
Django Custom ChangeUserForm setting is_active, is_staff, and is_superuser to False
I have a custom ChangeUserForm (ModelForm on User) that allows a user to update their account information.
However, when I save the form, user.is_active, user.is_staff and user.is_superuser all get set to False.
Any thoughts on wha... | Django Custom ChangeUserForm setting is_active, is_staff, and is_superuser to False | I have a custom ChangeUserForm (ModelForm on User) that allows a user to update their account information.
However, when I save the form, user.is_active, user.is_staff and user.is_superuser all get set to False.
Any thoughts on what's going on here?
forms.py
class UserChangeForm(forms.ModelForm):
username = forms.R... | [
"Just a guess: they aren't on the exclusion list in the Meta class so they're being set to false (boolean fields like those use a checkbox, which doesn't show up in POST data when unchecked). The form can't tell the difference between a boolean form field set to false and one that isn't on the page in the first pla... | [
2
] | [] | [] | [
"django",
"django_forms",
"django_views",
"python"
] | stackoverflow_0007295395_django_django_forms_django_views_python.txt |
Q:
Python Serialization (to JSON) issue
I'm a bit of a newbie in Python, so go easy on me. I'm writing an AJAX handler in Django. Everything's been pretty straight-forward on this until now. I've been banging my head against this bit for the better part of a day. I'd like to return a JSON string that contains a d... | Python Serialization (to JSON) issue | I'm a bit of a newbie in Python, so go easy on me. I'm writing an AJAX handler in Django. Everything's been pretty straight-forward on this until now. I've been banging my head against this bit for the better part of a day. I'd like to return a JSON string that contains a dict that contains a queryset:
#
# models.p... | [
"You can't serialize a python object like that. There is a section in the django documentation on what to do.\nhttps://docs.djangoproject.com/en/dev/topics/serialization/#id2\nHere is the key part to look at:\njson_serializer.serialize(queryset, ensure_ascii=False, stream=response)\n\n"
] | [
1
] | [] | [] | [
"json",
"python",
"serialization"
] | stackoverflow_0007296326_json_python_serialization.txt |
Q:
Python Mechanize : Page not loading fully
The code snippet i am using ::
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
response = br.open('http://www.facebook.com')
br.select_form(nr=0)
br['email'] = USERNAME
br['pass'] = ... | Python Mechanize : Page not loading fully | The code snippet i am using ::
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
response = br.open('http://www.facebook.com')
br.select_form(nr=0)
br['email'] = USERNAME
br['pass'] = PASSWORD
response2 = br.submit()
assert br.vie... | [
"You shouldn't be scraping www.facebook.com.\nThe right way to get what you are after is to use Facebook Platform as @infrared notes.\n",
"Are you sure you're passing the correct login?\nI've run your code with my login and it works fine for me.\nThe only thing I'll add is that you don't need the time.sleep(50) i... | [
0,
0
] | [] | [] | [
"facebook",
"mechanize",
"python"
] | stackoverflow_0006565013_facebook_mechanize_python.txt |
Q:
Help with logic within generator function
I'm trying to create a generator function:
def combinations(iterable, r, maxGapSize):
maxGapSizePlusOne = maxGapSize+1
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = list(range(r))
while True:
for i in reversed(ran... | Help with logic within generator function | I'm trying to create a generator function:
def combinations(iterable, r, maxGapSize):
maxGapSizePlusOne = maxGapSize+1
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = list(range(r))
while True:
for i in reversed(range(r)):
if indices[i] != i ... | [
"Much of your code looks exactly like the Python code for itertools.combination. The CPython implementation of itertools.combination is written in C. The documentation linked to above shows Python-equivalent code.\nYou can speed up the function by simply using itertools.combination instead of using the Python-equiv... | [
3
] | [] | [] | [
"generator",
"performance",
"python",
"python_3.x"
] | stackoverflow_0007296495_generator_performance_python_python_3.x.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.