content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python: Help with UnboundLocalError: local variable referenced before assignment
I keep getting this error for a portion of my code.
Traceback (most recent call last):
File "./mang.py", line 1688, in <module>
files, tsize = logger()
File "./mang.py", line 1466, in logger
nl = sshfile(list, "nl")
UnboundLocalError:... | Python: Help with UnboundLocalError: local variable referenced before assignment | I keep getting this error for a portion of my code.
Traceback (most recent call last):
File "./mang.py", line 1688, in <module>
files, tsize = logger()
File "./mang.py", line 1466, in logger
nl = sshfile(list, "nl")
UnboundLocalError: local variable 'sshfile' referenced before assignment
I haven't put the code up caus... | [
"You probably haven't imported the file which contains the definition of sshfile, or you need to qualify the class name with the package name. It depends on how you imported it.\nWhat package does it come from? Where is it defined?\n\nUpdate\nFor anyone else reading this, after a discussion in the comments it turne... | [
1
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0002256056_multithreading_python.txt |
Q:
Why is there an error when dividing 2/5.0 in Python?
Possible Duplicate:
Python float - str - float weirdness
In python, 2/5.0 or 2/float(5) returns 0.40000000000000002
Why do I get that error at the end and how can I get the right value to use in additional calculations?
A:
Welcome to IEEE754, enjoy your stay... | Why is there an error when dividing 2/5.0 in Python? |
Possible Duplicate:
Python float - str - float weirdness
In python, 2/5.0 or 2/float(5) returns 0.40000000000000002
Why do I get that error at the end and how can I get the right value to use in additional calculations?
| [
"Welcome to IEEE754, enjoy your stay.\nUse decimal instead.\n",
"Because floating point arithmetic is not exact. You should use this value in your additional calculations, and round off the result when you're finished. If you need it to be exact, use another data type.\n",
"Ignacio above has the right answer. ... | [
22,
3,
2,
2,
1
] | [] | [] | [
"division",
"python"
] | stackoverflow_0002250828_division_python.txt |
Q:
SQLAlchemy Basic Question
To anyone with experience of SQLAlchemy, this will be basic I am sure; But I don't find the docs that helpful and I am sick of scratching my head.
Given two classes:
class User(Base):
__tablename__='users'
id = Column(Integer, primary_key=True)
name = Column(String(32))
..... | SQLAlchemy Basic Question | To anyone with experience of SQLAlchemy, this will be basic I am sure; But I don't find the docs that helpful and I am sick of scratching my head.
Given two classes:
class User(Base):
__tablename__='users'
id = Column(Integer, primary_key=True)
name = Column(String(32))
...
class UserPost(Base):
__... | [
"I think you just have the relation definition backwards.\nTry:\nclass User(Base):\n __tablename__='users'\n id = Column(Integer, primary_key=True)\n name = Column(String(32))\n posts = relation(\"UserPost\", backref=\"poster\")\n\nclass UserPost(Base):\n __tablename__='posts'\n id = Column(Intege... | [
2,
1,
0
] | [] | [] | [
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0002211070_orm_python_sqlalchemy.txt |
Q:
python Client hangs when no data to receive from server and hangs in that thread w/o letting client send
I am trying to figure out how to get my client to send and receive data 'simultaneously' and am using threads. My problem is that, depending on the way I set it up, the way here it waits for data from the serv... | python Client hangs when no data to receive from server and hangs in that thread w/o letting client send | I am trying to figure out how to get my client to send and receive data 'simultaneously' and am using threads. My problem is that, depending on the way I set it up, the way here it waits for data from the server in the recieveFromServer function which is in its own thread and cannot stop it when nothing will be sent. ... | [
"I think you want to try and set the socket to non-blocking mode:\nhttp://docs.python.org/library/socket.html#socket.socket.setblocking\n\nSet blocking or non-blocking mode of\n the socket: if flag is 0, the socket\n is set to non-blocking, else to\n blocking mode. Initially all sockets\n are in blocking mode. ... | [
2
] | [] | [] | [
"client",
"locking",
"multithreading",
"python"
] | stackoverflow_0002256113_client_locking_multithreading_python.txt |
Q:
What backing storage engine should I use for my Python library?
I'm writing a data processing library in Python that reads data from a variety of sources into memory, manipulates it, then exports it into a variety of different formats. I was loading this data into memory, but some of the datasets I'm processing c... | What backing storage engine should I use for my Python library? | I'm writing a data processing library in Python that reads data from a variety of sources into memory, manipulates it, then exports it into a variety of different formats. I was loading this data into memory, but some of the datasets I'm processing can be particularly large (over 4 Gig).
I need an open source library ... | [
"A document-oriented database should cope fine with that kind of workload as long as you do not have complex joins.\nCommon representatives would be CouchDB or MongoDB.\nThey are both well suited for MapReduce like algorithms (this includes iterating over all datasets). If you want to merge rows with new data, you ... | [
3,
1,
1,
0
] | [] | [] | [
"python",
"storage"
] | stackoverflow_0002254694_python_storage.txt |
Q:
Equivalent of Beautiful Soup's renderContents() method in lxml?
Is there an equivalent of Beautiful Soup's tag.renderContents() method in lxml?
I've tried using element.text, but that doesn't render child tags, as well as ''.join(etree.tostring(child) for child in element), but that doesn't render child text. The ... | Equivalent of Beautiful Soup's renderContents() method in lxml? | Is there an equivalent of Beautiful Soup's tag.renderContents() method in lxml?
I've tried using element.text, but that doesn't render child tags, as well as ''.join(etree.tostring(child) for child in element), but that doesn't render child text. The closest I've been able to find is etree.tostring(element), but that r... | [
"You're most of the way there with your original idea. element.text gives you the first text child of the element, and your list comprehension gives you everything else. If you concatenate the two strings together, you get what you're looking for:\n>>> xmlstr = \"<sec>header <p>para 0</p> text <p>para 1</p> footer<... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"lxml",
"python",
"rendering",
"xml"
] | stackoverflow_0002028270_beautifulsoup_lxml_python_rendering_xml.txt |
Q:
Running a PHP script inside a Python WSGI enviroment
I have a simple PHP script that outputs a dir listing in XML format. I use it to let a flash slideshow know what files are available to show.
I've just added the flash to a website that's powered by Django and the PHP file is now served up as it is, not parsed.
... | Running a PHP script inside a Python WSGI enviroment | I have a simple PHP script that outputs a dir listing in XML format. I use it to let a flash slideshow know what files are available to show.
I've just added the flash to a website that's powered by Django and the PHP file is now served up as it is, not parsed.
It's in the directory with the images under my media direc... | [
"Maybe read this thread, and port your PHP script to Python:\nos.walk() python: xml representation of a directory structure, recursion\n",
"So it turns out the problem was two things, making it hard to find.\nThanks Ignacio Vazquez-Abrams, I had my lines the wrong way around.\nOnce that was solved, PHP would not ... | [
3,
2,
1,
1
] | [] | [] | [
"apache",
"django",
"php",
"python",
"wsgi"
] | stackoverflow_0002159637_apache_django_php_python_wsgi.txt |
Q:
Options for read-only binary flat-file storage using Python
I have been tasked with setting up a flat-file SKU database for use on embedded devices with limited storage and processor speed.
Basically the data I need to store consists of the following:
SKU
Description
Location
Price
Qty
The file will consist of sev... | Options for read-only binary flat-file storage using Python | I have been tasked with setting up a flat-file SKU database for use on embedded devices with limited storage and processor speed.
Basically the data I need to store consists of the following:
SKU
Description
Location
Price
Qty
The file will consist of several million records.
The most important considerations are stora... | [
"How about SQLite with Python bindings? It has a little more than you need, but it's standard software and well-tested.\n",
"The old way would be to use a simple key/value data table like gdbm module. Python comes with support for that, but it's not built into the default Python installation on my machine.\nIn ge... | [
4,
4,
1,
1,
0,
0
] | [] | [] | [
"data_structures",
"flat_file",
"minimum_size",
"python"
] | stackoverflow_0002256256_data_structures_flat_file_minimum_size_python.txt |
Q:
Python IRC Client
import socket
from time import strftime
time = strftime("%H:%M:%S")
irc = 'irc.tormented-box.net'
port = 6667
channel = '#test'
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
print sck.recv(4096)
sck.send('NICK supaBOT\r\n')
sck.send('USER supaBOT supaBOT supaB... | Python IRC Client | import socket
from time import strftime
time = strftime("%H:%M:%S")
irc = 'irc.tormented-box.net'
port = 6667
channel = '#test'
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
print sck.recv(4096)
sck.send('NICK supaBOT\r\n')
sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n'... | [
"You really need to rethink how you're trying to parse messages; as-is I can say \"haha !opwned PRIVMSG\" to get ops. (For everyone else: PRIVMSG is part of the IRC protocol, not normally said by users.)\nHowever, I don't see the error in your current code, but you've changed what you're really running when you po... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0002215448_python.txt |
Q:
Options for storing metadata about CUPS print jobs?
I'm writing a print system that puts a simplified interface on top of CUPS. Users drop jobs into one queue, the system processes them in various ways (statistics, page quotas, etc.), and then offers the user a web interface to dispatch the job to one of multiple ... | Options for storing metadata about CUPS print jobs? | I'm writing a print system that puts a simplified interface on top of CUPS. Users drop jobs into one queue, the system processes them in various ways (statistics, page quotas, etc.), and then offers the user a web interface to dispatch the job to one of multiple printers.
Since there may be several user kiosks, an ad... | [
"Have you considered sqlite or redis? Both of those are low overhead and easy to spin up, especially when you're not really dealing with complex datasets.\n"
] | [
0
] | [] | [] | [
"concurrency",
"cups",
"ipp_protocol",
"python"
] | stackoverflow_0002254693_concurrency_cups_ipp_protocol_python.txt |
Q:
What does `**` mean in the expression `dict(d1, **d2)`?
I am intrigued by the following python expression:
d3 = dict(d1, **d2)
The task is to merge 2 dictionaries into a third one, and the above expression accomplishes the task just fine. I am interested in the ** operator and what exactly is it doing to the expr... | What does `**` mean in the expression `dict(d1, **d2)`? | I am intrigued by the following python expression:
d3 = dict(d1, **d2)
The task is to merge 2 dictionaries into a third one, and the above expression accomplishes the task just fine. I am interested in the ** operator and what exactly is it doing to the expression. I thought that ** was the power operator and haven't ... | [
"** in argument lists has a special meaning, as covered in section 4.7 of the tutorial. The dictionary (or dictionary-like) object passed with **kwargs is expanded into keyword arguments to the callable, much like *args is expanded into separate positional arguments.\n",
"The ** turns the dictionary into keyword ... | [
50,
17,
11,
3,
2,
1
] | [] | [] | [
"dictionary",
"operators",
"python",
"set_operations",
"syntax"
] | stackoverflow_0002255878_dictionary_operators_python_set_operations_syntax.txt |
Q:
Is there a Term::ANSIScreen equivalent for Python?
Perl has the excellent module Term::ANSIScreen for doing all sorts of fancy cursor movement and terminal color control. I'd like to reimplement a program that's currently in Perl in Python instead, but the terminal ANSI colors are key to its function. Is anyone aw... | Is there a Term::ANSIScreen equivalent for Python? | Perl has the excellent module Term::ANSIScreen for doing all sorts of fancy cursor movement and terminal color control. I'd like to reimplement a program that's currently in Perl in Python instead, but the terminal ANSI colors are key to its function. Is anyone aware of an equivalent?
| [
"If you only need colors You may want to borrow the implementation from pygments. IMO it's much cleaner than the one from ActiveState\nhttp://dev.pocoo.org/hg/pygments-main/file/b2deea5b5030/pygments/console.py\n",
"Here's a cookbook recipe on ActiveState to get you started. It covers colors and positioning.\n[E... | [
8,
3,
3,
2
] | [] | [] | [
"ansi",
"perl",
"python"
] | stackoverflow_0000471463_ansi_perl_python.txt |
Q:
Sorting dictionary keys by values in a list?
I have a dictionary and a list. The values of the keys match those of the list, I'm just trying to find out how to sort the values in the dictionary by the values in the list.
>>> l = [1, 2, 37, 32, 4, 3]
>>> d = {
32: 'Megumi',
1: 'Ai',
2: 'Risa',
3: '... | Sorting dictionary keys by values in a list? | I have a dictionary and a list. The values of the keys match those of the list, I'm just trying to find out how to sort the values in the dictionary by the values in the list.
>>> l = [1, 2, 37, 32, 4, 3]
>>> d = {
32: 'Megumi',
1: 'Ai',
2: 'Risa',
3: 'Eri',
4: 'Sayumi',
37: 'Mai'
}
I've tri... | [
"Don't shadow the builtins dict and list\n>>> L = [1, 2, 37, 32, 4, 3]\n>>> D = {\n... 32: 'Megumi',\n... 1: 'Ai',\n... 2: 'Risa',\n... 3: 'Eri',\n... 4: 'Sayumi',\n... 37: 'Mai'\n... }\n\n# Seems roundabout to use sorted here\n# This causes an index error for keys in D that are not listed i... | [
6,
4,
1,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python",
"sorting"
] | stackoverflow_0002257101_dictionary_list_python_sorting.txt |
Q:
How can I count words in complex documents (.rtf, .doc, .odt, etc)?
I'm trying to write a Python function that, given the path to a document file, returns the number of words in that document. This is fairly easy to do with .txt files, and there are tools that allow me to hack support for a few more complex docume... | How can I count words in complex documents (.rtf, .doc, .odt, etc)? | I'm trying to write a Python function that, given the path to a document file, returns the number of words in that document. This is fairly easy to do with .txt files, and there are tools that allow me to hack support for a few more complex document formats together, but I want a really comprehensive solution.
Looking ... | [
"load the documents in a headless OOo\nand call its word-count function\nPyODConverter is a recent (11-2009) script to use OOo to convert multiple file types. Looking at the script, it has basic loading of all the OOo supported documents. \nThis is how you start OOo as a headless service:\nsoffice -headless -accept... | [
3,
2
] | [] | [] | [
"document",
"openoffice.org",
"python",
"word_count"
] | stackoverflow_0002256881_document_openoffice.org_python_word_count.txt |
Q:
How to organize Python source code files?
I am developing a Python App Engine app, where I want to split the content of a source code file Models.py into separate files for each model, but I want to put it all in a folder called Models. The problem is that when I do that, my app can't find the classes anymore. Wha... | How to organize Python source code files? | I am developing a Python App Engine app, where I want to split the content of a source code file Models.py into separate files for each model, but I want to put it all in a folder called Models. The problem is that when I do that, my app can't find the classes anymore. What should I do?
This question is not about MVC b... | [
"Put an empty __init__.py file in the Models directory.\nThen, in your app; presumably one level up, you reference modules in the Models directory like this:\nimport Models\n\nand do something with it like this:\nModels.my_model.MyClassName\n\nYou can also use the from keyword like this:\nfrom Models import my_mode... | [
12,
4,
1
] | [] | [] | [
"code_formatting",
"code_structure",
"google_app_engine",
"project_structure",
"python"
] | stackoverflow_0002256126_code_formatting_code_structure_google_app_engine_project_structure_python.txt |
Q:
Testing python methods that call class methods
I have a very simple method:
Class Team(models.Model):
def sides(self):
return SideNames.objects.filter(team=self)
SideNames is another model defined in the same file as Team,
Which when I try and test:
self.assertEquals(len(t.sides()), 2)
I get the follo... | Testing python methods that call class methods | I have a very simple method:
Class Team(models.Model):
def sides(self):
return SideNames.objects.filter(team=self)
SideNames is another model defined in the same file as Team,
Which when I try and test:
self.assertEquals(len(t.sides()), 2)
I get the following error:
return SideNames.objects.filter(team=se... | [
"In the module that defines the test, you're importing the name SideNames from some other module. In the module where that sides method is defined, the name SideNames is not defined or imported.\n",
"By any chance, does your test do something like this:\nfrom myapp import models\n\n...\n\nmodels.SideNames = None\... | [
1,
1
] | [] | [] | [
"python",
"python_unittest",
"unit_testing"
] | stackoverflow_0002256063_python_python_unittest_unit_testing.txt |
Q:
How do I do os.getpid() in C++?
newb here. I am trying to make a c++ program that will read from a named pipe created by python. My problem is, the named pipe created by python uses os.getpid() as part of the pipe name. when i try calling the pipe from c++, i use getpid(). i am not getting the same value from c++.... | How do I do os.getpid() in C++? | newb here. I am trying to make a c++ program that will read from a named pipe created by python. My problem is, the named pipe created by python uses os.getpid() as part of the pipe name. when i try calling the pipe from c++, i use getpid(). i am not getting the same value from c++. is there a method equivalent in c++ ... | [
"You don't get same proccess IDs because your python program and c++ programs are run in different proccesses thus having different process IDs. So generally use a different logic to name your fifo files.\n",
"You won't get the same value if you're running as a separate process as each process has their own proce... | [
4,
2,
0,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0002257415_c++_python.txt |
Q:
Django version selection
Greetings,
I am currently working on a long term project that uses Django 1.1.1, and we are planning to release it around march of 2010.
Now while surfing I came upon to this article which says the planned release date of Django 1.2.0 is March 9, 2010.
Now I am a bit confused. If I should ... | Django version selection | Greetings,
I am currently working on a long term project that uses Django 1.1.1, and we are planning to release it around march of 2010.
Now while surfing I came upon to this article which says the planned release date of Django 1.2.0 is March 9, 2010.
Now I am a bit confused. If I should continue developing under 1.1.... | [
"I'd say only develop for the latest version if there is a specific feature you need/like. Read up on it so you know of course what is in store. \n1.0 onwards. I've found swapping django versions to be relatively trouble free. At any stage all you need to do is swap symlinks on a source tree on your test server. an... | [
4,
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002251696_django_python.txt |
Q:
How to parse a file line by line, char by char in Python?
How do you read a character by character from a source file in python until end of line and how do you check for end of line in python so that you can then start reading from the next line and finally how do we check for the end of file condition to finish ... | How to parse a file line by line, char by char in Python? | How do you read a character by character from a source file in python until end of line and how do you check for end of line in python so that you can then start reading from the next line and finally how do we check for the end of file condition to finish the read in the entire file.
Thank You:).
| [
"You can simply iterate over each line in Python. Use the universal end-of-line mode if you want Python to care about Windows/UNIX/Mac line ends automatically:\nwith open(\"mytextfile.txt\", \"rtU\") as f:\n for line in f:\n # Now you have one line of text in the variable \"line\" and can\n # iterate over it... | [
8,
1
] | [] | [] | [
"python"
] | stackoverflow_0002257665_python.txt |
Q:
Executing server-side Unix scripts asynchronously
We have a collection of Unix scripts (and/or Python modules) that each perform a long running task. I would like to provide a web interface for them that does the following:
Asks for relevant data to pass into scripts.
Allows for starting/stopping/killing them.
Al... | Executing server-side Unix scripts asynchronously | We have a collection of Unix scripts (and/or Python modules) that each perform a long running task. I would like to provide a web interface for them that does the following:
Asks for relevant data to pass into scripts.
Allows for starting/stopping/killing them.
Allows for monitoring the progress and/or other informati... | [
"Django is great for writing web applications, and the subprocess module (subprocess.Popen en .communicate()) is great for executing shell scripts. You can give it a stdin,stdout and stderr stream for communication if you want.\n",
"Answering my own question, I recently saw the announcement of Celery 1.0, which s... | [
1,
1,
0
] | [] | [] | [
"asynchronous",
"http",
"python",
"unix"
] | stackoverflow_0001897748_asynchronous_http_python_unix.txt |
Q:
Review Website In Python. Is django right for this?
Basically, I misread this but would still really appreciate some assurance. I recently came across the django tutorial (http://djangotutorial.com) and have fell in love with the framework. I have a website that is simply ran on wordpress and a simple plugin at th... | Review Website In Python. Is django right for this? | Basically, I misread this but would still really appreciate some assurance. I recently came across the django tutorial (http://djangotutorial.com) and have fell in love with the framework. I have a website that is simply ran on wordpress and a simple plugin at the moment at http://runningshoesreview.org.
I've been wan... | [
"The Django admin is for administrator use only.\nYou could use this for moderation and general admin tasks.\nYou would create a different interface using django for your users.\nDjango would be a great framework for your app. I'm developing a service with it now.\nThere are other great frameworks out there too. Ca... | [
3,
1,
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002256892_django_python.txt |
Q:
Python Shell, Logging Commands for Easy Re-Execution
Say I do something like this in a python shell for my Django app:
>>>from myapp.models import User
>>>user = User.objects.get(pk=5)
>>>groups = user.groups.all()
What I'd like to do is stash these 3 commands somehow without leaving the shell. The goal being I c... | Python Shell, Logging Commands for Easy Re-Execution | Say I do something like this in a python shell for my Django app:
>>>from myapp.models import User
>>>user = User.objects.get(pk=5)
>>>groups = user.groups.all()
What I'd like to do is stash these 3 commands somehow without leaving the shell. The goal being I can quickly restore a similar environment if I restart the ... | [
"The Django shell will use IPython if available, which supports a persistent history.\nAlso, writing throwaway scripts is not difficult.\n",
"So thanks to Ignacio, with IPython installed:\n>>>from myapp.models import User\n>>>user = User.objects.get(pk=5)\n>>>groups = user.groups.all()\n>>>#Ipython Tricks Follow\... | [
2,
1,
1
] | [] | [] | [
"django",
"python",
"shell"
] | stackoverflow_0002242288_django_python_shell.txt |
Q:
Script access to WebGoat urls?
I've been solving a couple of the WebGoat exampels for a uni-lab thing. In one of the exercises I tried to use a python script with urllib2 to do automated "tests" so I didnt manually have to used ascii(substr(first_name,3,1)) > 97 etc.
But I seem to get the same page eventhough I tr... | Script access to WebGoat urls? | I've been solving a couple of the WebGoat exampels for a uni-lab thing. In one of the exercises I tried to use a python script with urllib2 to do automated "tests" so I didnt manually have to used ascii(substr(first_name,3,1)) > 97 etc.
But I seem to get the same page eventhough I try different urls when using an urlli... | [
"Is the user agent being checked? I've had to specify a user agent for a typical browser before to get past checks like that. You have one listed in your \"data\" variable but it looks like you don't actually apply it in any way.\n",
"Woohoo! \nFound out\nThe ID of the page I'm trying to find is regenerated on ev... | [
2,
1
] | [] | [] | [
"python",
"security"
] | stackoverflow_0002255721_python_security.txt |
Q:
How to copy data from one Tkinter Text widget to another?
from Tkinter import *
root = Tk()
root.title("Whois Tool")
text = Text()
text1 = Text()
text1.config(width=15, height=1)
text1.pack()
def button1():
text.insert(END, text1)
b = Button(root, text="Enter", width=10, height=2, command=button1)
b.pack(... | How to copy data from one Tkinter Text widget to another? | from Tkinter import *
root = Tk()
root.title("Whois Tool")
text = Text()
text1 = Text()
text1.config(width=15, height=1)
text1.pack()
def button1():
text.insert(END, text1)
b = Button(root, text="Enter", width=10, height=2, command=button1)
b.pack()
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=... | [
"You are trying to insert a Text reference at the end of another Text widget (does not make much sense), but what you actually want to do is to copy the contents of a Text widget to another:\ndef button1():\n text.insert(INSERT, text1.get(\"1.0\", \"end-1c\"))\n\nNot an intuitive way to do it in my opinion. \"1.... | [
5
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0002258097_python_tkinter.txt |
Q:
Why do I get "expected an indented block" when I try to run my Python script?
I have an error which says "expected an indented block"
Could you please guide me on how to deal with this error. Thank you:)
Code example:
for ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (tr... | Why do I get "expected an indented block" when I try to run my Python script? | I have an error which says "expected an indented block"
Could you please guide me on how to deal with this error. Thank you:)
Code example:
for ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch)
| [
"Editing answer to match the code example.\nfor ch in f: ( translatedToken = english_hindi_dict[ch] ) if (ch in english_hindi_dict) else (translatedToken = ch) \n\nis just not valid Python.\nFirst, readability count. Your code is hard to read and so, is hard to debug. What's \"ch\" and \"f\" ? What's more, you can... | [
14,
13,
11,
3,
2,
1
] | [] | [] | [
"indentation",
"python"
] | stackoverflow_0002257947_indentation_python.txt |
Q:
Search and replace characters in a file with Python
I am trying to do transliteration where I need to replace every source character in English from a file with its equivalent from a dictionary I am using in the source code corresponding to another language in Unicode format. I am now able to read character by cha... | Search and replace characters in a file with Python | I am trying to do transliteration where I need to replace every source character in English from a file with its equivalent from a dictionary I am using in the source code corresponding to another language in Unicode format. I am now able to read character by character from a file in English how do I search for its equ... | [
"The translate method of Unicode objects is the simplest and fastest way to perform the transliteration you require. (I assume you're using Unicode, not plain byte strings which would make it impossible to have characters such as 'पत्र'!).\nAll you have to do is layout your transliteration dictionary in a precise ... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0002257731_python.txt |
Q:
Grid lines in parasitic axes in matplotlib
Can you draw the grid lines in a plot with parasitic axes in matplotlib?
I try this, based on the samples for grids and for parasitic axes, but grid drawing is not performed:
from mpl_toolkits.axes_grid.parasite_axes import SubplotHost
import matplotlib.pyplot as plt
fig... | Grid lines in parasitic axes in matplotlib | Can you draw the grid lines in a plot with parasitic axes in matplotlib?
I try this, based on the samples for grids and for parasitic axes, but grid drawing is not performed:
from mpl_toolkits.axes_grid.parasite_axes import SubplotHost
import matplotlib.pyplot as plt
fig = plt.figure(1)
host = SubplotHost(fig, 111)
f... | [
"From the discussion here it looks like this is a bug in the .99 release. \n(I'm not sure why it works for doug but no combination of rcParams works for me on version 0.99.1.1-r1.)\nFrom that link the answer is to make a call to:\nhost.toggle_axisline(False)\n\n\nWhat the toggle_axisline does is simply to make the... | [
5,
3
] | [] | [] | [
"grid",
"matplotlib",
"python"
] | stackoverflow_0002248118_grid_matplotlib_python.txt |
Q:
Python - to check if a char is in dictionary and if not to deal with it
I am going about transliteration from one source language(input file) to a target language(target file) so I am checking for equivalent mappings in a dictionary in my source code, certain characters in the source code don't have an equivalent ... | Python - to check if a char is in dictionary and if not to deal with it | I am going about transliteration from one source language(input file) to a target language(target file) so I am checking for equivalent mappings in a dictionary in my source code, certain characters in the source code don't have an equivalent mapping like comma(,) and all other such special symbols. How do I check if t... | [
"My recommendation, given that rules is a mapping of the characters to their transliterated equivalents:\nresults = []\nfor char in source_text:\n results.append(rules.get(char, char))\nreturn ''.join(results) # turns the list back into a string\n\nA dict's get method will return either the value for a key or... | [
3,
3,
1,
0,
0
] | [] | [] | [
"python",
"transliteration"
] | stackoverflow_0002257799_python_transliteration.txt |
Q:
Modify entity data either transactionally or not (depending on the need)
What is the best way to keep code modular and decoupled but avoid entering a transaction twice?
Entities often have class methods to load, modify, and store data. Often, this must be transactional to be consistent with child/sibling/cousin en... | Modify entity data either transactionally or not (depending on the need) | What is the best way to keep code modular and decoupled but avoid entering a transaction twice?
Entities often have class methods to load, modify, and store data. Often, this must be transactional to be consistent with child/sibling/cousin entities. Here is the pattern:
class MyEntity(db.Model):
# ... some properties... | [
"The pattern I use is to have a parameter indicating whether transactional behavior is required.\nclass OtherEntity(db.Model):\n# ... some properties\n\n@classmethod\ndef update_descendants(cls, ancestor, with_transaction=True):\n if with_transaction:\n return db.run_in_transaction(cls.update_descendants, ances... | [
2,
1
] | [] | [] | [
"google_app_engine",
"python",
"transactions"
] | stackoverflow_0002257946_google_app_engine_python_transactions.txt |
Q:
Disable cache in Pylons app under development mode
I'm using @beaker_cache() decorator in my Pylons application.
How can I disable the cache under development mode?
A:
You could write your own decorator which looks at pylons.config["debug"], and depending on that either returns function unchanged or decorated wi... | Disable cache in Pylons app under development mode | I'm using @beaker_cache() decorator in my Pylons application.
How can I disable the cache under development mode?
| [
"You could write your own decorator which looks at pylons.config[\"debug\"], and depending on that either returns function unchanged or decorated with beaker_cache. Something along these lines (completely untested!):\nfrom pylons import config\n\ndef my_cache(*args, **kwargs):\n if config[\"debug\"]:\n de... | [
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0002243470_pylons_python.txt |
Q:
Pylons and Flex 3
Has anyone used Python/Pylons as the server backend for a Flex 3 application? Does anyone have any thoughts on how well this would work? I read Bruce Eckel's article about tying Flex 3 to Twisted, and I've done Twisted programming, but for just a web service I think Pylons is simpler to use.
Than... | Pylons and Flex 3 | Has anyone used Python/Pylons as the server backend for a Flex 3 application? Does anyone have any thoughts on how well this would work? I read Bruce Eckel's article about tying Flex 3 to Twisted, and I've done Twisted programming, but for just a web service I think Pylons is simpler to use.
Thanks in advance,
Doug
| [
"I'm working on webapp which has client-side UI coded in Flex 3 and backend is Pylons app. Our client communicates with backend using HTTP GET and POST requests, POST request bodies and all response bodies carry data in JSON format. Works well, just few gotchas:\n\nFlex apps cannot do PUT and DELETE requests. We wo... | [
0
] | [] | [] | [
"apache_flex",
"pylons",
"python",
"twisted"
] | stackoverflow_0002185329_apache_flex_pylons_python_twisted.txt |
Q:
How do I handle Python XML-RPC output and exceptions?
I have created a simple Python XML-RPC implementation, largely based on the examples.
However, it sends output like this:
foo.bar.com - - [13/Feb/2010 17:55:47] "POST /RPC2 HTTP/1.0" 200 -
... to the terminal, even if I redirect standard out and standard error... | How do I handle Python XML-RPC output and exceptions? | I have created a simple Python XML-RPC implementation, largely based on the examples.
However, it sends output like this:
foo.bar.com - - [13/Feb/2010 17:55:47] "POST /RPC2 HTTP/1.0" 200 -
... to the terminal, even if I redirect standard out and standard error to a file using >> or >. I'm doing this with the following... | [
"I guess you're using the SimpleXMLRPCServer class from the examples. In that case, simply provide the parameter logRequests when creating it:\nserver = SimpleXMLRPCServer((\"localhost\", 8000), logRequests = False)\n\nThat will suppress request logging.\nAs for the exceptions, they're logged in BaseServer (cf. sou... | [
5,
0
] | [] | [] | [
"python",
"xml_rpc"
] | stackoverflow_0002258514_python_xml_rpc.txt |
Q:
Using TinyMCE for sites with a dark background
I'm using django-tinymce in my Django website. Through the admin interface one can edit a SimplePage object which has a tinymce.models.HTMLField. The website visitor will then see the html rendered in the content area of the page.
Problem is, the website itself has a ... | Using TinyMCE for sites with a dark background | I'm using django-tinymce in my Django website. Through the admin interface one can edit a SimplePage object which has a tinymce.models.HTMLField. The website visitor will then see the html rendered in the content area of the page.
Problem is, the website itself has a dark background, and the TinyMCE textarea has a whit... | [
"You can customize the CSS of the editable area with the content_css setting, see: http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/content_css\nThis also works with django-tinymce, simply adjust TINYMCE_DEFAULT_CONFIG in your django settings:\nTINYMCE_DEFAULT_CONFIG = {\n # your other settings\n 'co... | [
1,
0
] | [] | [] | [
"django",
"django_tinymce",
"html",
"python",
"tinymce"
] | stackoverflow_0002258678_django_django_tinymce_html_python_tinymce.txt |
Q:
More than 1 docstrings for a single module/function etc.?
I'm using python 3.1.
Is it possible to create more than 1 docstring for a single module or function?
I'm creating a program, and I'm intending to have multiple docstrings with a category for each. I intend to give other people the program so they can use i... | More than 1 docstrings for a single module/function etc.? | I'm using python 3.1.
Is it possible to create more than 1 docstring for a single module or function?
I'm creating a program, and I'm intending to have multiple docstrings with a category for each. I intend to give other people the program so they can use it, and to make things easy for programmers and non-programmers ... | [
"I don't recommend trying to do something complicated with the docstrings. Best to keep the docstrings simple, and do something else if you want to make a bunch of different documentation options available.\nIf you really want to do what you described, I suggest you use tags to delimit sections within docstrings. ... | [
5,
4,
3,
1,
1
] | [] | [] | [
"docstring",
"python"
] | stackoverflow_0002258696_docstring_python.txt |
Q:
How to force an ImportError on development machine? (pwd module)
I'm trying to use a third-party lib (docutils) on Google App Engine and have a problem with this code (in docutils):
try:
import pwd
do stuff
except ImportError:
do other stuff
I want the import to fail, as it will on the actual GAE serv... | How to force an ImportError on development machine? (pwd module) | I'm trying to use a third-party lib (docutils) on Google App Engine and have a problem with this code (in docutils):
try:
import pwd
do stuff
except ImportError:
do other stuff
I want the import to fail, as it will on the actual GAE server, but the problem is that it doesn't fail on my development box (ubu... | [
"Even easier than messing with __import__ is just inserting None in the sys.modules dict:\n>>> import sys\n>>> sys.modules['pwd'] = None\n>>> import pwd\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nImportError: No module named pwd\n\n",
"In your testing framework, before you cause... | [
12,
4
] | [] | [] | [
"google_app_engine",
"import",
"pwd",
"python",
"ubuntu"
] | stackoverflow_0002258100_google_app_engine_import_pwd_python_ubuntu.txt |
Q:
Extending a PIL decoder
I have a file which contains a single image of a specific format at a
specific offset. I can already get a file-like for the embedded image
which supports read(), seek(), and tell(). I want to take advantage
of an existing PIL decoder to handle the embedded image, but be able to
treat the e... | Extending a PIL decoder | I have a file which contains a single image of a specific format at a
specific offset. I can already get a file-like for the embedded image
which supports read(), seek(), and tell(). I want to take advantage
of an existing PIL decoder to handle the embedded image, but be able to
treat the entire file as an "image file"... | [
"The relevant chapter of the docs is this one and I think it's fairly clear: if for example you want to decode image files in the new .zap-format, you write a ZapImagePlugin.py module which must perform a couple things:\n\nhave a class ZapImageFile(ImageFile.ImageFile): with string attributes format and format_desc... | [
9,
4
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0002257318_python_python_imaging_library.txt |
Q:
How to execute some code when a file is modified using python?
I want to execute one function each time a file gets written with new data (gets modified) and I'm using Python.
How can I do it?
A:
If you want to monitor for changes in the file system using Python, see this article for pointers to libraries which ... | How to execute some code when a file is modified using python? | I want to execute one function each time a file gets written with new data (gets modified) and I'm using Python.
How can I do it?
| [
"If you want to monitor for changes in the file system using Python, see this article for pointers to libraries which can help you achieve this on different platforms.\nShort summary of available libraries for different platforms:\n\nWindows: pywin32\nOS X: pyKQueue\nLinux: Gamin\n\nRemember that your program needs... | [
5,
2
] | [] | [] | [
"execute",
"file",
"function",
"python"
] | stackoverflow_0002259336_execute_file_function_python.txt |
Q:
How can I know the path of the running script in Python?
My script.py creates a temporary file using a relative path.
When running it as:
python script.py
it works as expected.
But it doesn't work when you run it like:
python /path/to/script.py
The problem is that I don't know which path it will be running in. H... | How can I know the path of the running script in Python? | My script.py creates a temporary file using a relative path.
When running it as:
python script.py
it works as expected.
But it doesn't work when you run it like:
python /path/to/script.py
The problem is that I don't know which path it will be running in. How can I get the absolute path to the script folder (the "/pat... | [
"Per the great Dive Into Python:\nimport sys, os\n\nprint 'sys.argv[0] =', sys.argv[0] 1\npathname = os.path.dirname(sys.argv[0]) 2\nprint 'path =', pathname\nprint 'full path =', os.path.abspath(pathname)\n\n",
"The two current answers reflect the ambiguity of your question.\nWhen you've run p... | [
12,
8,
0
] | [] | [] | [
"path",
"python"
] | stackoverflow_0002259503_path_python.txt |
Q:
Problem using cPickle
Could you helpme to make this exmaple work?
I'd like to load a serialized dict if it exists, modify it and dump it again. I think I have a problem with the mode I'm using to open the file but I don't know the correct way.
import os
import cPickle as pickle
if os.path.isfile('file.txt'):
... | Problem using cPickle | Could you helpme to make this exmaple work?
I'd like to load a serialized dict if it exists, modify it and dump it again. I think I have a problem with the mode I'm using to open the file but I don't know the correct way.
import os
import cPickle as pickle
if os.path.isfile('file.txt'):
cache_file = open('file.txt... | [
"'rwb' is not correct file open mode for open(). Try 'r+b'.\nAnd after you have read from file, you have cursor positioned at the end of file, so pickle.dump(cache, cache_file) will append to the file (which is probably not what you want). Try cache_file.seek(0) after pickle.load(cache_file).\n",
"For each load, ... | [
5,
4,
1
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0002259636_pickle_python.txt |
Q:
Tool to convert python indentation from spaces to tabs?
I have a some .py files that use spaces for indentation, and I'd like to convert them to tabs.
I could easily hack together something using regexes, but I can think of several edge cases where this approach could fail. Is there a tool that does this by parsi... | Tool to convert python indentation from spaces to tabs? | I have a some .py files that use spaces for indentation, and I'd like to convert them to tabs.
I could easily hack together something using regexes, but I can think of several edge cases where this approach could fail. Is there a tool that does this by parsing the file and determining the indentation level the same wa... | [
"If there are not many files to convert, you can open them in vim, and use the :retab command.\nSee the vim documentation for more information.\n",
"Python includes a script for the opposite (tabs to spaces). It's C:\\Python24\\Tools\\Scripts\\reindent.py for me\n",
":retab will swap tab with spaces, and :reta... | [
17,
16,
12,
4,
3
] | [] | [] | [
"indentation",
"python"
] | stackoverflow_0000338767_indentation_python.txt |
Q:
Request-Aware Code in Google App Engine -- os.environ?
In GAE, you can say users.get_current_user() to get the currently logged-in user implicit to the current request. This works even if multiple requests are being processed simultaneously -- the users module is somehow aware of which request the get_current_user... | Request-Aware Code in Google App Engine -- os.environ? | In GAE, you can say users.get_current_user() to get the currently logged-in user implicit to the current request. This works even if multiple requests are being processed simultaneously -- the users module is somehow aware of which request the get_current_user function is being called on behalf of. I took a look into t... | [
"As the docs say, \n\nA Python web app interacts with the\n App Engine web server using the CGI\n protocol.\n\nThis basically means exactly one request is being served at one time within any given process (although, differently from real CGI, one process can be serially reused for multiple requests, one after the... | [
3
] | [] | [] | [
"google_app_engine",
"python",
"request"
] | stackoverflow_0002259727_google_app_engine_python_request.txt |
Q:
Should I use the same url to login admins and other registred users in Django?
I am quite new to Django, so it may be a stupid question, but, nevertheless:
I need Django admin part to edit contents on the site, and also I want to have authentification, that will allow registred users to leave comments.
I have the ... | Should I use the same url to login admins and other registred users in Django? | I am quite new to Django, so it may be a stupid question, but, nevertheless:
I need Django admin part to edit contents on the site, and also I want to have authentification, that will allow registred users to leave comments.
I have the following idea of implementation it: have 2 different tables(admins and other regist... | [
"\"have 2 different tables(admins and other registred users)\"\nBad idea. Django auth module has one user table. You can easily assign users to groups. Some groups have admin access to anything. Other groups can only leave comments. Read up on the auth module before you do anything more.\nhttp://docs.djangopr... | [
4
] | [] | [] | [
"admin",
"architecture",
"authentication",
"django",
"python"
] | stackoverflow_0002259747_admin_architecture_authentication_django_python.txt |
Q:
Recommended Django Deployment
Short version: How do you deploy your Django servers? What application server, front-end (if any, and by front-end I mean reverse proxy), and OS do you run it on? Any input would be greatly appreciated, I'm quite a novice when it comes to Python and even more as a server administrator... | Recommended Django Deployment | Short version: How do you deploy your Django servers? What application server, front-end (if any, and by front-end I mean reverse proxy), and OS do you run it on? Any input would be greatly appreciated, I'm quite a novice when it comes to Python and even more as a server administrator.
Long version:
I'm migrating betwe... | [
"\nUpdate your question to remove the choices that don't work. If it has Python 2.4, and an installation is a headache, just take it off the list, and update the question to list the real candidates. Only list the ones that actually fit your requirements. (You don't say what your requirements are, but minimal up... | [
4,
3,
3,
0
] | [] | [] | [
"deployment",
"django",
"linux",
"python",
"webserver"
] | stackoverflow_0002256987_deployment_django_linux_python_webserver.txt |
Q:
How should I display a constantly updating timer using PyGTK?
I am writing a timer program in Python using PyGTK. It is precise to the hundredths place. Right now, I am using a constantly updated label. This is a problem, because if I resize the window while the timer is running, Pango more often than not throws s... | How should I display a constantly updating timer using PyGTK? | I am writing a timer program in Python using PyGTK. It is precise to the hundredths place. Right now, I am using a constantly updated label. This is a problem, because if I resize the window while the timer is running, Pango more often than not throws some crazy error and my program terminates. It's not always the same... | [
"Updating a label should work perfectly reliably, so I suspect you're doing something else wrong. Are you using threads? What does your code look like? How small can you condense your program (by removing functionality, not by obfuscating the code), without making the problem go away?\n",
"I figured out the probl... | [
2,
2
] | [] | [] | [
"gtk",
"pango",
"pygtk",
"python"
] | stackoverflow_0002259386_gtk_pango_pygtk_python.txt |
Q:
sqlalchemy backref slow
Hi have have the following tables
nfiletable = Table(
'NFILE', base.metadata,
Column('fileid', Integer, primary_key=True),
Column('path', String(300)),
Column('filename', String(50)),
Column('filesize', Integer),
schema='NATIVEFILES')#,autoload=True,autoload_with=en... | sqlalchemy backref slow | Hi have have the following tables
nfiletable = Table(
'NFILE', base.metadata,
Column('fileid', Integer, primary_key=True),
Column('path', String(300)),
Column('filename', String(50)),
Column('filesize', Integer),
schema='NATIVEFILES')#,autoload=True,autoload_with=engine)
sheetnames_table=Table... | [
"if NFile.sheets references a huge collection, put \"lazy='dynamic'\" on the backref:\nmapper(Sheet, sheetnames_table, properties={\n 'files': relation(\n Nfile, secondary=nfile_sheet_table,\n backref=backref('sheets', lazy='dynamic'))\n})\n\nAll the primaryjoin/secondaryjoin/foreign_keys stuff is ... | [
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0002231324_python_sqlalchemy.txt |
Q:
SQLAlchemy getting column data types of query results
from sqlalchemy import create_engine, MetaData, ForeignKey
engine = create_engine("mysql://user:passwd@localhost/shema", echo=False)
meta = MetaData(engine, True)
conn = engine.connect()
tb_list = meta.tables["tb_list"]
tb_data = meta.tables["tb_data"]
tb_li... | SQLAlchemy getting column data types of query results | from sqlalchemy import create_engine, MetaData, ForeignKey
engine = create_engine("mysql://user:passwd@localhost/shema", echo=False)
meta = MetaData(engine, True)
conn = engine.connect()
tb_list = meta.tables["tb_list"]
tb_data = meta.tables["tb_data"]
tb_list.c.i_data.append_foreign_key( ForeignKey(tb_data.c.i_id) ... | [
"you'd say:\ntypes = [col.type for col in q.columns]\n\nthe (compiled) statement is on the result too if you feel like digging:\ntypes = [col.type for col in res.context.compiled.statement.columns]\n\nif you want the DBAPI version of the types, which is a little more varied based on DBAPI:\ntypes = [elem[1] for ele... | [
17
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0002258072_python_sqlalchemy.txt |
Q:
Issue with links Embedding the app engine's shell app within my own app, for help coding
In my own App Engine App, at the browser, I wanted to mess around with new code by simulating having access to the python interpretor's >> within a browser window by embedding this app --> http://shell.appspot.com/ .
One can g... | Issue with links Embedding the app engine's shell app within my own app, for help coding | In my own App Engine App, at the browser, I wanted to mess around with new code by simulating having access to the python interpretor's >> within a browser window by embedding this app --> http://shell.appspot.com/ .
One can get shell_20091112.tar.gz at http://code.google.com/p/google-app-engine-samples/downloads/deta... | [
"The answer to my own question is to install the following shell console, very easy, and looks very helpful:\nhttp://con.appspot.com/console/help/about\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"httphandler",
"python"
] | stackoverflow_0002235080_google_app_engine_httphandler_python.txt |
Q:
How can I preserve or identify a caller's stack frame?
My brain feels slow today.
I'm writing pre/post/invariants in Python using decorators. Currently, I need each call to specify the locals and globals for context, and this feels ugly. Is there a way to get the locals and globals from the decorator applic... | How can I preserve or identify a caller's stack frame? | My brain feels slow today.
I'm writing pre/post/invariants in Python using decorators. Currently, I need each call to specify the locals and globals for context, and this feels ugly. Is there a way to get the locals and globals from the decorator application level even though it's an arbitrary depth.
That is, I'... | [
"If you can access self.total_sold, you can access self.tax_rate (which is the same thing as Item.tax_rate unless you stomp on it -- so you just don't stomp of it, keep the tax rate as a pristine class variable, and access it through self.!-). That would be much more solid than mucking through the stack, especiall... | [
2
] | [] | [] | [
"decorator",
"python",
"stack"
] | stackoverflow_0002260029_decorator_python_stack.txt |
Q:
Simple Python Regex Find pattern
I have a sentence. I want to find all occurrences of a word that start with a specific character in that sentence. I am very new to programming and Python, but from the little I know, this sounds like a Regex question.
What is the pattern match code that will let me find all word... | Simple Python Regex Find pattern | I have a sentence. I want to find all occurrences of a word that start with a specific character in that sentence. I am very new to programming and Python, but from the little I know, this sounds like a Regex question.
What is the pattern match code that will let me find all words that match my pattern?
Many thanks i... | [
"import re\nprint re.findall(r'\\bv\\w+', thesentence)\n\nwill print every word in the sentence that starts with 'v', for example.\nUsing the split method of strings, as another answer suggests, would not identify words, but space-separated chunks that may include punctuation. This re-based solution does identify ... | [
21,
3,
2,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002260105_python_regex.txt |
Q:
python mapping with strings
I implemented a version of the str_replace function available in php using python. Here is my original code that didn't work
def replacer(items,str,repl):
return "".join(map(lambda x:repl if x in items else x,str))
test = "hello world"
print test
test = replacer(test,['e','l','o'],... | python mapping with strings | I implemented a version of the str_replace function available in php using python. Here is my original code that didn't work
def replacer(items,str,repl):
return "".join(map(lambda x:repl if x in items else x,str))
test = "hello world"
print test
test = replacer(test,['e','l','o'],'?')
print test
but this prints ... | [
"The ordering of the arguments to replacer is what makes the difference between the two. If you changed the argument ordering in the first version it'd behave like the second version.\n",
"Don't use built-in names such as str for your own identifiers, that's just asking for trouble and has no benefit whatsoever.... | [
4,
3,
1
] | [] | [] | [
"lambda",
"map",
"python",
"string"
] | stackoverflow_0002260148_lambda_map_python_string.txt |
Q:
wxPython - PaintDC not refreshing
import wx
class TestDraw(wx.Panel):
def __init__(self,parent=None,id=-1):
wx.Panel.__init__(self,parent,id)
self.SetBackgroundColour("#FFFFFF")
self.Bind(wx.EVT_PAINT,self.onPaint)
def onPaint(self, event):
event.Skip()
dc=wx.Paint... | wxPython - PaintDC not refreshing |
import wx
class TestDraw(wx.Panel):
def __init__(self,parent=None,id=-1):
wx.Panel.__init__(self,parent,id)
self.SetBackgroundColour("#FFFFFF")
self.Bind(wx.EVT_PAINT,self.onPaint)
def onPaint(self, event):
event.Skip()
dc=wx.PaintDC(self)
dc.BeginDrawing()
... | [
"You can bind a method to handle wx.EVT_SIZE or the panel and invalidate it there. Alternatively simply use the wx.FULL_REPAINT_ON_RESIZE for the panel. \n",
"The documentation for a SizeEvent claims that there may be some complications when drawing depends on the dimensions of the window. I do not know exactly w... | [
2,
0
] | [] | [] | [
"graphics",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0002260142_graphics_python_user_interface_wxpython.txt |
Q:
Django/Python: < comes up as < when I import it from the model object
Revised question:
In my dbms, I'm storing the literal <<<firefox-image>>>, I confirmed in Navicat and Mysql CLI that its <<<firefox-image>>>. When I use the Python shell and try to grab the same article entry, the outer <>'s get converted to <... | Django/Python: < comes up as < when I import it from the model object | Revised question:
In my dbms, I'm storing the literal <<<firefox-image>>>, I confirmed in Navicat and Mysql CLI that its <<<firefox-image>>>. When I use the Python shell and try to grab the same article entry, the outer <>'s get converted to < and <, respectively.
Snippet of me testing:
>>> entry = Entry.objects... | [
"I'm a dumbass - I forgot to invoke render_uploads before storing it.\nreturn markdown(render_uploads(markup))\n\n",
"I can't duplicate that symptom; the fact that you have only two less-than and greater-thans on each side makes me wonder if your inline syntax is wrong? Are there definitely three on either side i... | [
2,
1
] | [] | [] | [
"django",
"python",
"unicode"
] | stackoverflow_0002259844_django_python_unicode.txt |
Q:
Regex try and match until hitting end tag in python
I'm looking for a bit of help with a regex in python and google is failing me. Basically I'm searching some html and there is a certain type of table I'm searching for, specifically any table that includes a background tag in it (i.e. BGCOLOR). Some tables have... | Regex try and match until hitting end tag in python | I'm looking for a bit of help with a regex in python and google is failing me. Basically I'm searching some html and there is a certain type of table I'm searching for, specifically any table that includes a background tag in it (i.e. BGCOLOR). Some tables have this tag and some do not. Could someone help me out wit... | [
"Don't use a regular expression to parse HTML. Use lxml or BeautifulSoup.\n",
"Don't use regular expressions to parse HTML -- use an HTML parser, such as BeautifulSoup.\nSpecifically, your situation is basically one of having to deal with \"nested parentheses\" (where an open \"parens\" is an opening <table> tag ... | [
4,
3,
0,
0
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0002259694_parsing_python_regex.txt |
Q:
Deleting the most recently received email via Python script?
I use Gmail and an application that notifies me if I've received a new email, containing its title in a tooltip. (GmailNotifier with Miranda-IM) Most of the emails I receive are ones I don't want to read, and it's annoying having to login to Gmail on a s... | Deleting the most recently received email via Python script? | I use Gmail and an application that notifies me if I've received a new email, containing its title in a tooltip. (GmailNotifier with Miranda-IM) Most of the emails I receive are ones I don't want to read, and it's annoying having to login to Gmail on a slow connection just to delete said email. I believe plugin is clos... | [
"import poplib\n\n#connect to server\nmailserver = poplib.POP3_SSL('pop.gmail.com')\nmailserver.user('recent:YOURUSERNAME') #use 'recent mode'\nmailserver.pass_('YOURPASSWORD') #consider not storing in plaintext!\n\n#newest email has the highest message number\nnumMessages = len(mailserver.list()[1])\n\n#confirm th... | [
4
] | [] | [] | [
"email",
"imap",
"pop3",
"python"
] | stackoverflow_0002260316_email_imap_pop3_python.txt |
Q:
How can I write a Nokia application with pyqt?
I have seen questions on my Facebook group about 'Can I write Nokia apps with pyqt', but no one has answered. I am curious, can it be done?
A:
The short answer is yes.
You might like to look at http://wiki.forum.nokia.com/index.php/Getting_started_with_PyQt_for_Maem... | How can I write a Nokia application with pyqt? | I have seen questions on my Facebook group about 'Can I write Nokia apps with pyqt', but no one has answered. I am curious, can it be done?
| [
"The short answer is yes.\nYou might like to look at http://wiki.forum.nokia.com/index.php/Getting_started_with_PyQt_for_Maemo, \nBecause of issues with PyQT being available only for GPL applications without money, Nokia released their own Python/QT bindings: http://developers.slashdot.org/story/09/08/30/0823206/N... | [
3
] | [] | [] | [
"nokia",
"pyqt",
"python"
] | stackoverflow_0002260434_nokia_pyqt_python.txt |
Q:
How to approach Google groups discussions crawler
as an exercise in RSS I would like to be able to search through pretty much all Unix discussions on this group.
comp.unix.shell
I know enough Python and understand basic RSS, but I am stuck on ... how do I grab all messages between particular dates, or at least all... | How to approach Google groups discussions crawler | as an exercise in RSS I would like to be able to search through pretty much all Unix discussions on this group.
comp.unix.shell
I know enough Python and understand basic RSS, but I am stuck on ... how do I grab all messages between particular dates, or at least all messages between Nth recent and Mth recent?
High level... | [
"Crawling google groups violates the Google's Terms of Service, specifically the phrase:\n\nuse any robot, spider, site search/retrieval application, or other device to retrieve or index any portion of the Service or collect information about users for any unauthorized purpose\n\nAre you sure you want to announce t... | [
4,
3,
1,
1
] | [] | [] | [
"google_groups",
"python",
"web_crawler"
] | stackoverflow_0002211887_google_groups_python_web_crawler.txt |
Q:
SCons - convert all images in a directory
I'd like to write an SConstruct file that will convert (e.g.) all the JPEG files in a directory into PNGs.
I think I have the Builder alright:
ConvToPNG = Builder(action = 'convert $SOURCE $TARGET',
suffix = '.png',
src_suffix = '.jpg')
env['BUILDERS']['Con... | SCons - convert all images in a directory | I'd like to write an SConstruct file that will convert (e.g.) all the JPEG files in a directory into PNGs.
I think I have the Builder alright:
ConvToPNG = Builder(action = 'convert $SOURCE $TARGET',
suffix = '.png',
src_suffix = '.jpg')
env['BUILDERS']['ConvToPNG'] = ConvToPNG
But then I'm not sure how... | [
"Your steps seems fine, but Alias node you need to pass to the AlwaysBuild function:\nenv.AlwaysBuild(env.Alias('convert_all', pix_conversions))\n\nSo the end result would be:\nConvToPNG = Builder(action = 'convert $SOURCE $TARGET',\n suffix = '.png',\n src_suffix = '.jpg')\nenv['BUILDERS']['ConvToPNG... | [
2,
1
] | [] | [] | [
"python",
"scons"
] | stackoverflow_0002254707_python_scons.txt |
Q:
In PyObjC how do you get a sheet to end after using runModalForWindow_?
I have a secondary window (a sheet) for a dialog controlled by a secondard WindowController. For some reason, the actions never get called in NSObject subclass after the sheet is displayed. I have confirmed and re-linked the actions. The code ... | In PyObjC how do you get a sheet to end after using runModalForWindow_? | I have a secondary window (a sheet) for a dialog controlled by a secondard WindowController. For some reason, the actions never get called in NSObject subclass after the sheet is displayed. I have confirmed and re-linked the actions. The code runs to runModalForWindow_ but then never receives the ok or cancel actions. ... | [
"Your lines \n @objc.IBAction\n def okSelected(self, sender):\n\nshould be\n @objc.IBAction\n def okSelected_(self, sender):\n\netc. Remember, every colon in an Objective-C selector becomes an _ in Python!\n"
] | [
2
] | [] | [] | [
"cocoa",
"pyobjc",
"python"
] | stackoverflow_0002259377_cocoa_pyobjc_python.txt |
Q:
GAE datastore viewer - editing lists
Is it possible to somehow enable editing lists in GAE datastore viewer?
I'm using Python version of SDK.
Basically I want to avoid, as much as possible, writing own CRUD as it
wouldn't be necessary if only I could edit lists in datastore viewer..
A:
That's not built in to th... | GAE datastore viewer - editing lists | Is it possible to somehow enable editing lists in GAE datastore viewer?
I'm using Python version of SDK.
Basically I want to avoid, as much as possible, writing own CRUD as it
wouldn't be necessary if only I could edit lists in datastore viewer..
| [
"That's not built in to the datastore viewer, no. With the 1.3.1 release of the SDK, it is possible to add custom pages to the Admin console, but that wouldn't really save you from having to write the list editing page yourself.\nAppEnngine Custom Pages Documentation\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0002260804_google_app_engine_google_cloud_datastore_python.txt |
Q:
How can I resize the root window in Tkinter?
from Tkinter import *
import socket, sys
from PIL import Image, ImageTk
root = Tk()
root.title("Whois Tool")
root.resizable(0, 0)
text = Text()
text1 = Text()
image = Image.open("hacker2.png")
photo = ImageTk.PhotoImage(image)
label = Label(root, image=photo)
label.... | How can I resize the root window in Tkinter? | from Tkinter import *
import socket, sys
from PIL import Image, ImageTk
root = Tk()
root.title("Whois Tool")
root.resizable(0, 0)
text = Text()
text1 = Text()
image = Image.open("hacker2.png")
photo = ImageTk.PhotoImage(image)
label = Label(root, image=photo)
label.pack()
text1.config(width=15, height=1)
text1.pa... | [
"For a 500x500 window you would use\nroot.geometry(\"500x500\")\n\nAs for image resizing, I do not believe Tkinter supports it. You would have to use a library such as PIL to resize the image to the window resolution. -example resize code-\n"
] | [
35
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0002261011_python_tkinter.txt |
Q:
Google Wave gadget configure / set properties
How can you configure or mutate a Google Wave gadget after creating one in Python? The following code will load the gadget via XML:
from waveapi import document
gadget = document.Gadget('http://domain.com/gadget.xml')
The API reference says you can pass a dictionary o... | Google Wave gadget configure / set properties | How can you configure or mutate a Google Wave gadget after creating one in Python? The following code will load the gadget via XML:
from waveapi import document
gadget = document.Gadget('http://domain.com/gadget.xml')
The API reference says you can pass a dictionary of initial properties, but I can't find any informat... | [
"Gadget is derived from Element which states:\n\nAlthough a Robot can query the properties of an element it can only interact with the specific types that the element represents.\n\nThe API does mention SubmitDelta() and get() , which seem like wrappers for setattr and getattr. \nDiscussion of (similar) issue here\... | [
1
] | [] | [] | [
"google_wave",
"python"
] | stackoverflow_0002258985_google_wave_python.txt |
Q:
Prevent a console app from closing when not invoked from an existing terminal?
There are many variants on this kind of question. However I am specifically after a way to prevent a console application in Python from closing when it is not invoked from a terminal (or other console, as it may be called on Windows). A... | Prevent a console app from closing when not invoked from an existing terminal? | There are many variants on this kind of question. However I am specifically after a way to prevent a console application in Python from closing when it is not invoked from a terminal (or other console, as it may be called on Windows). An example where this could occur is double clicking a .py file from the Windows expl... | [
"First, an attempt to disuade you from clever hacks. It's perfectly appropriate to have a seperate shortcut designed to be run from Explorer that does slightly different things (like holding the console open) from the script to be used from the commandline. As Alex has already pointed out, this is not an issue on n... | [
6,
3
] | [] | [] | [
"console",
"console_application",
"persistence",
"python",
"terminal"
] | stackoverflow_0002258771_console_console_application_persistence_python_terminal.txt |
Q:
Python: How to make multiple HTTP POST queries in one moment?
How to make multiple HTTP POST queries in one moment using Python?
Using an external library with an example can be a good solution.
A:
External lib? Maybe an internal one would do the trick...
http://docs.python.org/library/httplib.html#examples
spe... | Python: How to make multiple HTTP POST queries in one moment? | How to make multiple HTTP POST queries in one moment using Python?
Using an external library with an example can be a good solution.
| [
"External lib? Maybe an internal one would do the trick...\nhttp://docs.python.org/library/httplib.html#examples\nspecifically: \nparams = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})\n\nIf you wanted to process multiple HTTP POST queries (asynchronous) you could cycle through them in a loop, opening subpro... | [
1,
0
] | [] | [] | [
"concurrency",
"http",
"python"
] | stackoverflow_0002261035_concurrency_http_python.txt |
Q:
How can I put 2 buttons next to each other?
b = Button(root, text="Enter", width=10, height=2, command=button1)
b.config()
b.pack(side=LEFT)
c = Button(root, text="Clear", width=10, height=2, command=clear)
c.pack(side=LEFT)
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text.config(width=35, hei... | How can I put 2 buttons next to each other? | b = Button(root, text="Enter", width=10, height=2, command=button1)
b.config()
b.pack(side=LEFT)
c = Button(root, text="Clear", width=10, height=2, command=clear)
c.pack(side=LEFT)
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text.config(width=35, height=15)
text.pack(side=RIGHT, fill=Y)
scrollbar.... | [
"There are typically two solutions to this type of problem. Neither is better than the other in all circumstances, or in this particular example. Both solutions are perfectly acceptable.\nSolution 1: use two containers (typically, frames). One to hold horizontal items, one to hold vertical items. In this case the r... | [
33
] | [] | [] | [
"button",
"python",
"tkinter"
] | stackoverflow_0002261191_button_python_tkinter.txt |
Q:
PyRo and python
I use PyRo in my python programm. And I have a problem. class B: In callFromProxy print 0, but in callfun print right value = 10. Why? How to fix?
class A(Pyro.core.ObjBase):
# set link to item class B
def set(self, real_B):
self.item_B = real_B
# call function callfun in item_B
def callfun(... | PyRo and python | I use PyRo in my python programm. And I have a problem. class B: In callFromProxy print 0, but in callfun print right value = 10. Why? How to fix?
class A(Pyro.core.ObjBase):
# set link to item class B
def set(self, real_B):
self.item_B = real_B
# call function callfun in item_B
def callfun(self):
self.item_B.... | [
"I believe (and correct me if I'm wrong) PyRo uses asynchronous calls, at least by default.\nSo when you call callFromProxy, printvalue might get executed before callfun on itemB, because it takes time to call A.callfun and B.callfun. If/when this happens, elements[\"name\"] will still be 0 when printvalue is calle... | [
1
] | [] | [] | [
"pyro",
"python"
] | stackoverflow_0002261317_pyro_python.txt |
Q:
Python repr function problem
I'm dealing with some text parsing in Python and for that purpose, it's good for me to apply repr() function on each string I'm gonna parse, but after the parsing, I need to convert some parsed substring back to the previous representation, because I want to print them and I'm not able... | Python repr function problem | I'm dealing with some text parsing in Python and for that purpose, it's good for me to apply repr() function on each string I'm gonna parse, but after the parsing, I need to convert some parsed substring back to the previous representation, because I want to print them and I'm not able to do this. I thought that str() ... | [
"str() has no effect on objects that are already strings. You need to use eval() to undo a repr() where possible. Try using ast.literal_eval() instead though.\n"
] | [
3
] | [] | [] | [
"format",
"python",
"text"
] | stackoverflow_0002261593_format_python_text.txt |
Q:
Runing bcdedit from python in Windows 2008 SP2
I do not know windows well, so that may explain my dilemma ...
I am trying to run bcdedit in Windows 2008R2 from Python 2.6.
My Python routine to run a command looks like this:
def run_program(cmd_str):
"""Run the specified command, returning its output as an arra... | Runing bcdedit from python in Windows 2008 SP2 | I do not know windows well, so that may explain my dilemma ...
I am trying to run bcdedit in Windows 2008R2 from Python 2.6.
My Python routine to run a command looks like this:
def run_program(cmd_str):
"""Run the specified command, returning its output as an array of lines"""
dprint("run_program(%s): entering"... | [
"Windows 2008 R2 is 64-bit-only, yes? Python's a 32-bit process. When a 32-bit app runs something from C:\\Windows\\System32, Windows actually looks in C:\\Windows\\SysWOW64. Use C:\\Windows\\SysNative.\n",
"Perhaps the path to bcdedit.exe isn't in your system path when Python is running for some reason (a differ... | [
1,
0,
0,
0
] | [] | [] | [
"python",
"windows_vista"
] | stackoverflow_0002017557_python_windows_vista.txt |
Q:
Python: Simulate search algorithms in network models
I am using networkx package to draw power law graphs. I want to simulate a search algorithm on this graph and want to visually see the algorithm move from one node to another on the graph. How do I do that?
A:
On a mac you could use NodeBox: http://nodebox.net... | Python: Simulate search algorithms in network models | I am using networkx package to draw power law graphs. I want to simulate a search algorithm on this graph and want to visually see the algorithm move from one node to another on the graph. How do I do that?
| [
"On a mac you could use NodeBox: http://nodebox.net/. \n",
"NetworkX supports drawing using Graphviz and matplotlib. Did you read the drawing-chapter in its documentation?\n"
] | [
1,
1
] | [] | [] | [
"graph_drawing",
"networkx",
"python"
] | stackoverflow_0002146395_graph_drawing_networkx_python.txt |
Q:
Possible to use Mathematica from other programming languages (python/C#)?
Is it possible to use Mathematica's computing capabilities from other languages? I need to do some complex operations (not necessarily symbolic, btw), and it'd be pretty sweet to be able to just call Mathematica's functions or running Mathem... | Possible to use Mathematica from other programming languages (python/C#)? | Is it possible to use Mathematica's computing capabilities from other languages? I need to do some complex operations (not necessarily symbolic, btw), and it'd be pretty sweet to be able to just call Mathematica's functions or running Mathematica's code right from my python/c#'s program.
Is it possible?
| [
"Looks like there is a MathLink API you can use from C#, c or Java, have you checked this out?\nhttp://reference.wolfram.com/mathematica/guide/MathLinkAPI.html\n",
"To links about usage of python and .Net (for C#)\n",
"Perhaps the easiest way is to make the Mathematica program its own self-contained script and ... | [
5,
4,
4,
1,
1
] | [] | [] | [
"c#",
"mathlink",
"python",
"wolfram_mathematica"
] | stackoverflow_0001783564_c#_mathlink_python_wolfram_mathematica.txt |
Q:
List comprehension and functions
I'm a little confusing when try something like this
b = [lambda x:x**i for i in range(11)]
When I then try b[1](2) I have 1024 as a result that is wrong. But when I write so
b = [(lambda i: lambda x:x**i)(i) for i in range(11)]
all is OK
>>> b[1](2)
2
>>> b[5](2)
32
It works fin... | List comprehension and functions | I'm a little confusing when try something like this
b = [lambda x:x**i for i in range(11)]
When I then try b[1](2) I have 1024 as a result that is wrong. But when I write so
b = [(lambda i: lambda x:x**i)(i) for i in range(11)]
all is OK
>>> b[1](2)
2
>>> b[5](2)
32
It works fine but what's wrong in first code?
| [
"This is due to how closures in Python work.\nThe loop changes the value in the scope that all the functions share. Move generation of the function into a separate scope, i.e. function.\n",
"It's a game of scopes.\nIn the first code, the \"i\" name in the lambda is only a reference. The value behind that referenc... | [
3,
1
] | [] | [] | [
"function",
"list",
"list_comprehension",
"python"
] | stackoverflow_0002261826_function_list_list_comprehension_python.txt |
Q:
BMP2avi in python
I am looking for a python code that takes series of BMP file and merges them into Avi file (and get the parameter frames per second from the user)
does anyone has an idea where to begin?
Ariel
A:
I'd begin by using the GStreamer Python bindings; at a minimum, that'll take the AVI encoding (or a... | BMP2avi in python | I am looking for a python code that takes series of BMP file and merges them into Avi file (and get the parameter frames per second from the user)
does anyone has an idea where to begin?
Ariel
| [
"I'd begin by using the GStreamer Python bindings; at a minimum, that'll take the AVI encoding (or a great many other codecs, if you prefer) off your plate.\nIt won't help with BMP input, though; either you can convert them to PNG or another natively-supported input format or use a different library such as PIL to ... | [
0
] | [] | [] | [
"avi",
"bmp",
"python"
] | stackoverflow_0002261928_avi_bmp_python.txt |
Q:
URL redirection problem
i have the below url
http://bit.ly/cDdh1c
When you place the above url in a browser and hit enter it will redirect to the below url
http://www.kennystopproducts.info/Top/?hop=arnishad
But where as when i try to find the base url (after eliminating all the redirect urls) for the same abov... | URL redirection problem | i have the below url
http://bit.ly/cDdh1c
When you place the above url in a browser and hit enter it will redirect to the below url
http://www.kennystopproducts.info/Top/?hop=arnishad
But where as when i try to find the base url (after eliminating all the redirect urls) for the same above url http://bit.ly/cDdh1c vi... | [
"Your problem is that when you call urlsplit, your path variable only contains the path and is missing the query.\nSo, instead try:\nimport httplib\nimport urlparse\n\ndef getUrl(url):\n maxattempts = 10\n turl = url\n while (maxattempts > 0) : \n host,path,query = urlparse.urlsplit(... | [
1,
1
] | [] | [] | [
"bit.ly",
"python",
"redirect",
"url"
] | stackoverflow_0002261823_bit.ly_python_redirect_url.txt |
Q:
Displaying a cvMatrix containing complex numbers (CV_64FC2)
I'm new to OpenCV, and I would like to compare the results of a python program with my calculations in OpenCV. My matrix contains complex numbers since its the result of a cvDFT. Python handles complex numbers well and displays it with scientific notation... | Displaying a cvMatrix containing complex numbers (CV_64FC2) | I'm new to OpenCV, and I would like to compare the results of a python program with my calculations in OpenCV. My matrix contains complex numbers since its the result of a cvDFT. Python handles complex numbers well and displays it with scientific notation. My C++ program is not effective when trying to use std::cout.
I... | [
"There is a dft example in OpenCV 2.0 code, which I am also studying right now. Here is a copy paste for you that might give you an idea. As you can see, it uses cvSplit to spilit to real and imaginary components. Hope that helps:\nim = cvLoadImage( filename, CV_LOAD_IMAGE_GRAYSCALE );\nif( !im )\n return -1;\n\... | [
4,
0
] | [] | [] | [
"c++",
"numpy",
"opencv",
"python"
] | stackoverflow_0002048577_c++_numpy_opencv_python.txt |
Q:
Entry with suggestions
I'm building a small PyGTK application and I have an text input field (currently a ComboBoxEntry) which is populated with a few values that the user should be able to choose from.
I think what I want to do is to filter out the matching fields and only show those ones so the user using the ke... | Entry with suggestions | I'm building a small PyGTK application and I have an text input field (currently a ComboBoxEntry) which is populated with a few values that the user should be able to choose from.
I think what I want to do is to filter out the matching fields and only show those ones so the user using the keyboard arrows can choose one... | [
"An Entry with an EntryCompletion seems more appropriate than a ComboBoxEntry. As always, the tutorial is a good start.\nIt's very easy to set up when the predefined URLs list is small and fixed.\nYou just need to populate a ListStore:\n# simplified example from the tutorial\nimport gtk\n\nurls = [\n 'http://ww... | [
8,
0,
0
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0002250477_pygtk_python.txt |
Q:
What's the difference between "while 1" and "while True"?
I've seen two ways to create an infinite loop in Python:
while 1:
do_something()
while True:
do_something()
Is there any difference between these? Is one more pythonic than the other?
A:
Fundamentally it doesn't matter, such minutiae doesn't re... | What's the difference between "while 1" and "while True"? | I've seen two ways to create an infinite loop in Python:
while 1:
do_something()
while True:
do_something()
Is there any difference between these? Is one more pythonic than the other?
| [
"Fundamentally it doesn't matter, such minutiae doesn't really affect whether something is 'pythonic' or not.\nIf you're interested in trivia however, there are some differences.\n\nThe builtin boolean type didn't exist till Python 2.3 so code that was intended to run on ancient versions tends to use the while 1: f... | [
47,
11,
5,
4,
3,
2,
2,
2,
1,
0,
0
] | [] | [] | [
"infinite_loop",
"python",
"while_loop"
] | stackoverflow_0002261987_infinite_loop_python_while_loop.txt |
Q:
How to parse just the text from a Word Doc using Python?
When you try opening a MS Word document or for that matter most Windows file formats, you will see gibberish as given below broken intermittently by the actual text. I need to extract the text that goes in and want to ignore the gibberish -- which is somethi... | How to parse just the text from a Word Doc using Python? | When you try opening a MS Word document or for that matter most Windows file formats, you will see gibberish as given below broken intermittently by the actual text. I need to extract the text that goes in and want to ignore the gibberish -- which is something like given below. How do I extract only the text that matte... | [
"The tool that seems the most viable, particularly if you need an all python solution is OleFileIO.\n",
"doc is a binary format, it's not a markup language or something.\nSpecs: http://www.microsoft.com/interop/docs/OfficeBinaryFormats.mspx\n",
"\nThere is no generic why to extract\n information from every fil... | [
3,
1,
0,
0,
0
] | [] | [] | [
"ms_word",
"python",
"regex",
"screen_scraping"
] | stackoverflow_0002261650_ms_word_python_regex_screen_scraping.txt |
Q:
How can I detect what other copy of Python script is already running
I have a script. It uses GTK. And I need to know if another copy of scrip starts. If it starts window will extend.
Please, tell me the way I can detect it.
A:
You could use a D-Bus service. Your script would start a new service if none is found... | How can I detect what other copy of Python script is already running | I have a script. It uses GTK. And I need to know if another copy of scrip starts. If it starts window will extend.
Please, tell me the way I can detect it.
| [
"You could use a D-Bus service. Your script would start a new service if none is found running in the current session, and otherwise send a D-Bus message to the running instace (that can send \"anything\", including strings, lists, dicts).\nThe GTK-based library libunique (missing Python bindings?) uses this approa... | [
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002261997_python.txt |
Q:
How can I get the text between tags using python SAX parser?
What I need is just get the text of the corresponding tag and persist it into database. Since the xml file is big (4.5GB) I'm using sax. I used the characters method to get the text and put it in a dictionary. However when I'm printing the text at the en... | How can I get the text between tags using python SAX parser? | What I need is just get the text of the corresponding tag and persist it into database. Since the xml file is big (4.5GB) I'm using sax. I used the characters method to get the text and put it in a dictionary. However when I'm printing the text at the endElement method I'm getting a new line instead of the text.
Here i... | [
"The text in the tag is chunked by the SAX processor. characters might be called multiple times.\nYou need to do something like:\ndef startElement(self, name, attrs):\n self.map[name] = ''\n self.tag = name\n\ndef characters(self, content):\n self.map[self.tag] += content\n\ndef endElement(self, name):\n ... | [
8
] | [] | [] | [
"python",
"sax",
"xml"
] | stackoverflow_0002262577_python_sax_xml.txt |
Q:
unexpected list appearing in python loop
I am new to python and have the following piece of test code featuring a nested loop and I'm getting some unexpected lists generated:
import pybel
import math
import openbabel
search = ["CCC","CCCC"]
matches = []
#n = 0
#b = 0
print search
for n in search: ... | unexpected list appearing in python loop | I am new to python and have the following piece of test code featuring a nested loop and I'm getting some unexpected lists generated:
import pybel
import math
import openbabel
search = ["CCC","CCCC"]
matches = []
#n = 0
#b = 0
print search
for n in search:
print "n=",n
smarts = pybel.Smarts(... | [
"allmol has 2 items and so you're looping twice with matches being an empty list the second time.\nNotice how the newline is printed after each; changing that \"\\n\" to \"<-- matches\" may clear things up for you:\nprint matches, \"<-- matches\"\n# or, more commonly:\nprint \"matches:\", matches\n\n"
] | [
2
] | [
"Perhaps it is supposed to end like this\nfor b in allmol: \n matches.append(smarts.findall(b)) \nprint matches, \"\\n\"\n\notherwise I'm not sure why you'd initialise matches to an empty list\nIf that is the case, you can instead write\nmatches = [smarts.findall(b) for b in allmol]\nprint matches\n\nanother p... | [
-1
] | [
"for_loop",
"list",
"openbabel",
"python"
] | stackoverflow_0002262509_for_loop_list_openbabel_python.txt |
Q:
How to make my Python unit tests to import the tested modules if they are in sister folders?
I am still getting my head around the import statement. If I have 2 folders in the same level:
src
test
How to make the py files in test import the modules in src?
Is there a better solution (like put a folder inside ano... | How to make my Python unit tests to import the tested modules if they are in sister folders? | I am still getting my head around the import statement. If I have 2 folders in the same level:
src
test
How to make the py files in test import the modules in src?
Is there a better solution (like put a folder inside another?)
| [
"The code you want is for using src/module_name.py\nfrom src import module_name \n\nand the root directory is on your PYTHONPATH e.g. you run from the root directory\nYour directory structure is what I use but with the model name instead from src. I got this structure from J Calderone's blog and\n",
"Try this out... | [
10,
6,
0
] | [] | [] | [
"code_organization",
"directory",
"import",
"python",
"python_unittest"
] | stackoverflow_0002262546_code_organization_directory_import_python_python_unittest.txt |
Q:
Python equivalent of C code from Bit Twiddling Hacks?
I have a bit counting method that I am trying to make as fast as possible. I want to try the algorithm below from Bit Twiddling Hacks, but I don't know C. What is 'type T' and what is the python equivalent of (T)~(T)0/3?
A generalization of the best bit
coun... | Python equivalent of C code from Bit Twiddling Hacks? | I have a bit counting method that I am trying to make as fast as possible. I want to try the algorithm below from Bit Twiddling Hacks, but I don't know C. What is 'type T' and what is the python equivalent of (T)~(T)0/3?
A generalization of the best bit
counting method to integers of
bit-widths upto 128 (parameter... | [
"T is a integer type, which I'm assuming is unsigned. Since this is C, it'll be fixed width, probably (but not necessarily) one of 8, 16, 32, 64 or 128. The fragment (T)~(T)0 that appears repeatedly in that code sample just gives the value 2**N-1, where N is the width of the type T. I suspect that the code may r... | [
7,
2
] | [] | [] | [
"bit_manipulation",
"c",
"python"
] | stackoverflow_0002261671_bit_manipulation_c_python.txt |
Q:
mod_python not detecting files when using open()
I am trying to open a file I have in my /var/www/ directory named cardlist.xml.
this is the code I am using.
import cgi
import os
open("./cardlist.xml", "r")
def crawlXml():
return 0
My error is
MOD_PYTHON ERROR
ProcessId: 11361 Interpreter:
'127.0.1.1'... | mod_python not detecting files when using open() | I am trying to open a file I have in my /var/www/ directory named cardlist.xml.
this is the code I am using.
import cgi
import os
open("./cardlist.xml", "r")
def crawlXml():
return 0
My error is
MOD_PYTHON ERROR
ProcessId: 11361 Interpreter:
'127.0.1.1'
ServerName: '127.0.1.1'
DocumentRoot: '/var/w... | [
"The working directory might not be the directory of the file. Try using an absolute path, or an explicitly relative path:\nimport os.path\nopen(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cardlist.xml'))\n\n"
] | [
3
] | [] | [] | [
"apache2",
"mod_python",
"python"
] | stackoverflow_0002263005_apache2_mod_python_python.txt |
Q:
How can I send data to a base template in Django?
Let's say I have a django site, and a base template for all pages with a footer that I want to display a list of the top 5 products on my site. How would I go about sending that list to the base template to render? Does every view need to send that data to the rend... | How can I send data to a base template in Django? | Let's say I have a django site, and a base template for all pages with a footer that I want to display a list of the top 5 products on my site. How would I go about sending that list to the base template to render? Does every view need to send that data to the render_to_response? Should I use a template_tag? How would ... | [
"You should use a custom context processor. With this you can set a variable e.g. top_products that will be available in all your templates.\nE.g.\n# in project/app/context_processors.py\nfrom app.models import Product\n\ndef top_products(request):\n return {'top_products': Products.objects.all()} # of course so... | [
11
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0002263258_django_django_templates_python.txt |
Q:
Generating & Merging PDF Files in Python
I want to automatically generate booking confirmation PDF files in Python. Most of the content will be static (i.e. logos, booking terms, phone numbers), with a few dynamic bits (dates, costs, etc).
From the user side, the simplest way to do this would be to start with a P... | Generating & Merging PDF Files in Python | I want to automatically generate booking confirmation PDF files in Python. Most of the content will be static (i.e. logos, booking terms, phone numbers), with a few dynamic bits (dates, costs, etc).
From the user side, the simplest way to do this would be to start with a PDF file with the static content, and then usin... | [
"\nFrom the user side, the simplest way to do this would be to start with a PDF file with the static content, and then using python to just add the dynamic parts. Is this a simple process?\n\nUnfortunately no. There are several tools that are good at producing PDFs from scratch (most commonly for Python, ReportLab)... | [
8,
2,
1
] | [] | [] | [
"merge",
"pdf",
"pypdf",
"python",
"reportlab"
] | stackoverflow_0002263263_merge_pdf_pypdf_python_reportlab.txt |
Q:
Converting from ascii to utf-8 with Python
I have xmpp bot written in python. One of it's plugins is able to execute OS commands and send output to the user. As far as I know output should be unicode-like to send it over xmpp protocol. So I tried to handle it this way:
output = os.popen(cmd).read()
if not isinsta... | Converting from ascii to utf-8 with Python | I have xmpp bot written in python. One of it's plugins is able to execute OS commands and send output to the user. As far as I know output should be unicode-like to send it over xmpp protocol. So I tried to handle it this way:
output = os.popen(cmd).read()
if not isinstance(output, unicode):
output = unicode(output... | [
"sys.getdefaultencoding() returns python's default encoding - which is ASCII unless you have changed it. ASCII doesn't support Russian characters.\nYou need to work out what encoding the actual text is, either manually, or using the locale module.\nTypically something like:\nimport locale\nencoding = locale.getpref... | [
3,
2,
1,
0
] | [] | [] | [
"ascii",
"command_prompt",
"python",
"utf_8"
] | stackoverflow_0002262879_ascii_command_prompt_python_utf_8.txt |
Q:
Control 2 separate Excel instances by COM independently... can it be done?
I've got a legacy application which is implemented in a number of Excel workbooks. It's not something that I have the authority to re-implement, however another application that I do maintain does need to be able to call functions in the Ex... | Control 2 separate Excel instances by COM independently... can it be done? | I've got a legacy application which is implemented in a number of Excel workbooks. It's not something that I have the authority to re-implement, however another application that I do maintain does need to be able to call functions in the Excel workbook.
It's been given a python interface using the Win32Com library. Ot... | [
"See \"Starting a new instance of a COM application\" by Tim Golden, also referenced here, which give the hint to use\nxl_app = DispatchEx(\"Excel.Application\")\n\nrather than\nxl_app = Dispatch(\"Excel.Application\")\n\nto start a separate process. So you should be able to do:\nxl_app_1 = DispatchEx(\"Excel.Appli... | [
9,
2,
0
] | [] | [] | [
"com",
"excel",
"python",
"windows"
] | stackoverflow_0000516946_com_excel_python_windows.txt |
Q:
How to calculate positions of holes in a game board?
I'm making a game with Python->PyGame->Albow and ran into a problem with board generation. However I'll try to explain the problem in a language agnostic way. I believe it's not related to python.
I've split the game board generation into several parts.
Part one... | How to calculate positions of holes in a game board? | I'm making a game with Python->PyGame->Albow and ran into a problem with board generation. However I'll try to explain the problem in a language agnostic way. I believe it's not related to python.
I've split the game board generation into several parts.
Part one generates the board holes.
Holes are contained in a list/... | [
"If hole positions are stored as integers, I don't doubt rounding error accumulates quickly enough to kill you. If hole positions are stored as floating point, and if you have an error of one unit in the last place (ULP) at each computation, I'm not quite sure how quickly error accumulates—but if error doubles at ... | [
1,
0,
0
] | [] | [] | [
"language_agnostic",
"precision",
"python",
"rounding"
] | stackoverflow_0002263121_language_agnostic_precision_python_rounding.txt |
Q:
OAuth with Twitter script in Python is not working
I'm writing a script of OAuth in Python.
For testing this, I use Twitter API. But it is not working well.
def test():
params = {
"oauth_consumer_key": TWITTER_OAUTH_CONSUMER_KEY,
"oauth_nonce": "".join(random.choice(string.digits + stri... | OAuth with Twitter script in Python is not working | I'm writing a script of OAuth in Python.
For testing this, I use Twitter API. But it is not working well.
def test():
params = {
"oauth_consumer_key": TWITTER_OAUTH_CONSUMER_KEY,
"oauth_nonce": "".join(random.choice(string.digits + string.letters) for i in xrange(7)),
"oauth_sign... | [
"I got the same problem in OAuth with FaceBook a while ago. The problem is that the signature validation on server side fails. See your signature generation code here:\nmsg = \"&\".join([\"POST\", urllib.quote(url,\"\"),\n urllib.quote(\"&\".join([k+\"=\"+params[k] for k in sorted(params)]), \"-._~\"... | [
1,
0
] | [] | [] | [
"oauth",
"python",
"twitter"
] | stackoverflow_0002244608_oauth_python_twitter.txt |
Q:
Detect the location of an image within a larger image
How do you detect the location of an image within a larger image? I have an unmodified copy of the image. This image is then changed to an arbitrary resolution and placed randomly within a much larger image which is of an arbitrary size. No other transformat... | Detect the location of an image within a larger image | How do you detect the location of an image within a larger image? I have an unmodified copy of the image. This image is then changed to an arbitrary resolution and placed randomly within a much larger image which is of an arbitrary size. No other transformations are conducted on the resulting image. Python code wou... | [
"There is a quick and dirty solution, and that's simply sliding a window over the target image and computing some measure of similarity at each location, then picking the location with the highest similarity. Then you compare the similarity to a threshold, if the score is above the threshold, you conclude the image... | [
7,
3,
2,
2
] | [] | [] | [
"gdlib",
"image",
"image_processing",
"python"
] | stackoverflow_0002262832_gdlib_image_image_processing_python.txt |
Q:
How do I get the google username and email when someone logins to my site?
the next is mysite1\django_openid\registration.py:
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.conf import settings
from django_openid.auth import AuthConsumer
from django_openid.utils im... | How do I get the google username and email when someone logins to my site? | the next is mysite1\django_openid\registration.py:
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.conf import settings
from django_openid.auth import AuthConsumer
from django_openid.utils import OpenID, int_to_hex, hex_to_int
from django_openid import signed
from django... | [
"You ask the user. OpenID is inherently designed to not require providing anything except a user-unique identifier for authenticated users; any information beyond that is in the realm of application-specific.\n"
] | [
2
] | [] | [] | [
"django",
"openid",
"pinax",
"python"
] | stackoverflow_0002264193_django_openid_pinax_python.txt |
Q:
twisted.web2 and spawining threads for synchronous code?
So, I'm writing a python web application using the twisted web2 framework. There's a library that I need to use (SQLAlchemy, to be specific) that doesn't have asynchronous code. Would it be bad to spawn a thread to handle the request, fetch any data from the... | twisted.web2 and spawining threads for synchronous code? | So, I'm writing a python web application using the twisted web2 framework. There's a library that I need to use (SQLAlchemy, to be specific) that doesn't have asynchronous code. Would it be bad to spawn a thread to handle the request, fetch any data from the DB, and then return a response? I'm afraid that if there was ... | [
"See the docs, and specifically the thread pool which lets you control how many threads are active at most. Spawning one new thread per request would definitely be an inferior idea!\n"
] | [
0
] | [] | [] | [
"multithreading",
"python",
"twisted"
] | stackoverflow_0002264135_multithreading_python_twisted.txt |
Q:
Unwind a function call
This is a difficult problem to describe so please let me know if anything is unclear.
I am trying to solve a possible deadlock situation in my C++ app and I am having trouble visualizing an appropriate solution. The restrictions placed on me by the two libraries I am trying to connect make ... | Unwind a function call | This is a difficult problem to describe so please let me know if anything is unclear.
I am trying to solve a possible deadlock situation in my C++ app and I am having trouble visualizing an appropriate solution. The restrictions placed on me by the two libraries I am trying to connect make my problem very complex and ... | [
"If you're destroying the timer handler, I figure you're exiting the program. Before you try to exit and begin killing the timers, can you set a flag to prevent Action 1 and have Thread 1 terminate itself? I hope I'm reading your diagram right, because it doesn't exactly match with the text...\n"
] | [
0
] | [] | [] | [
"boost_python",
"c++",
"multithreading",
"python"
] | stackoverflow_0002264137_boost_python_c++_multithreading_python.txt |
Q:
How to check if a page is displaying a specific tag
What is the best way to determine if a page on a website is REALLY displaying a specific img tag like this <img src=http://domain.com/img.jpg>? A simple string comparison is easy to fool using http comments <!-- -->. Even if the html tag exists it could be de... | How to check if a page is displaying a specific tag | What is the best way to determine if a page on a website is REALLY displaying a specific img tag like this <img src=http://domain.com/img.jpg>? A simple string comparison is easy to fool using http comments <!-- -->. Even if the html tag exists it could be deleted with JavaScript. It could also be obscured by placi... | [
"The only surefire way I can think of is to render the page and check. It is simple to strip comments etc. But if scripts are involved, it is not possible to have a general solution that will not amount to executing them (I believe this is the first time I ever invoked Church's theorem...).\n",
"I don't think you... | [
1,
1,
0
] | [] | [] | [
"browser",
"python",
"security",
"web_crawler"
] | stackoverflow_0002262724_browser_python_security_web_crawler.txt |
Q:
how to work with strings and integers as bit strings in python?
I'm developing a Genetic Algorithm in python were chromosomes are composed of strings and integers. To apply the genetic operations, I want to convert these groups of integers and strings into bit strings.
For example, if one chromosome is:
["Hello", ... | how to work with strings and integers as bit strings in python? | I'm developing a Genetic Algorithm in python were chromosomes are composed of strings and integers. To apply the genetic operations, I want to convert these groups of integers and strings into bit strings.
For example, if one chromosome is:
["Hello", 4, "anotherString"]
I'd like it to become something like:
0100100100... | [
"You can turn strings and integers into bytestrings (and back) with the struct module, and that's exactly 8 bits to a byte. If for some reason you want these binary bytestrings as text strings made up of 0 and 1 characters, you can print them in binary form, of course.\nEdit: forgot to remind you how to format a b... | [
3,
3,
0
] | [] | [] | [
"artificial_intelligence",
"bit_manipulation",
"data_conversion",
"genetic_algorithm",
"python"
] | stackoverflow_0002264130_artificial_intelligence_bit_manipulation_data_conversion_genetic_algorithm_python.txt |
Q:
Creating a GUI Calculator in python similar to MS Calculator
I need to write a code that runs similar to normal calculators in such a way that it displays the first number I type in, when i press the operand, the entry widget still displays the first number, but when i press the numbers for my second number, the f... | Creating a GUI Calculator in python similar to MS Calculator | I need to write a code that runs similar to normal calculators in such a way that it displays the first number I type in, when i press the operand, the entry widget still displays the first number, but when i press the numbers for my second number, the first one gets replaced. I'm not to the point in writing the whole ... | [
"What you need here is a concept of state. Each time a key is pressed, you check the state and determine what action to take.\nIn the initial state, you take input of numbers.\nWhen an operand button is pressed, you store the operand, and change the state.\nWhen another number is pressed, you store the number, clea... | [
2
] | [] | [] | [
"calculator",
"python",
"user_interface"
] | stackoverflow_0002264371_calculator_python_user_interface.txt |
Q:
Python csv tags
I have a csv file with different headers.
name,city
john doe,chicago
Have headers as
reader = csv.DictReader(open(PATH_FILE),skipinitialspace=True)
headers = reader.fieldnames
How will you run a regex that whenever a tag [name] was to be proceesed it will show "john doe"
A:
You could use re.s... | Python csv tags | I have a csv file with different headers.
name,city
john doe,chicago
Have headers as
reader = csv.DictReader(open(PATH_FILE),skipinitialspace=True)
headers = reader.fieldnames
How will you run a regex that whenever a tag [name] was to be proceesed it will show "john doe"
| [
"You could use re.sub() with a function passed as repl, or you could just use string interpolation with a mapping:\nprint 'My name is %(name)s' % rowdict\n\n"
] | [
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0002264567_csv_python.txt |
Q:
if i have the key of google openid when someone who login my site,how do i get the username
if the key is https://www.google.com/accounts/o8/id?id=AItOawmqS0V2RR5FihojGdC90vXJpjcukoZ
how do i get the username who login my site ?
thanks
A:
I am afraid, that with OpenID, the URL really is the closest thing to a us... | if i have the key of google openid when someone who login my site,how do i get the username | if the key is https://www.google.com/accounts/o8/id?id=AItOawmqS0V2RR5FihojGdC90vXJpjcukoZ
how do i get the username who login my site ?
thanks
| [
"I am afraid, that with OpenID, the URL really is the closest thing to a user name. According to Wikipedia:\n\nUnlike a typical login form with fields for the user name and password, the OpenID login form has only one field—for the OpenID identifier, typically along with a small OpenID logo.\n\nIf you go to your ow... | [
1,
0
] | [] | [] | [
"django",
"openid",
"python"
] | stackoverflow_0002264833_django_openid_python.txt |
Q:
Where can I find some "hello world"-simple Beautiful Soup examples?
I'd like to do a very simple replacement using Beautiful Soup. Let's say I want to visit all A tags in a page and append "?foo" to their href. Can someone post or link to an example of how to do something simple like that?
A:
from BeautifulSoup ... | Where can I find some "hello world"-simple Beautiful Soup examples? | I'd like to do a very simple replacement using Beautiful Soup. Let's say I want to visit all A tags in a page and append "?foo" to their href. Can someone post or link to an example of how to do something simple like that?
| [
"from BeautifulSoup import BeautifulSoup\n\nsoup = BeautifulSoup('''\n<html>\n <head><title>Testing</title></head>\n <body>\n <a href=\"http://foo.com/\">foo</a>\n <a href=\"http://bar.com/bar\">Bar</a>\n </body>\n</html>''')\n\nfor link in soup.findAll('a'): # find all links\n link['href'] = link[... | [
15,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0000821173_beautifulsoup_python.txt |
Q:
How can I install django-stdimage in my django project, rather than as a module (jailed shell, no path access)
The question about covers it. I'm using dreamhost, and need to utilize the stdimagefield rather than image field so I can do this:
image3 = StdImageField(upload_to='path/to/img', size=(640, 480))
If the... | How can I install django-stdimage in my django project, rather than as a module (jailed shell, no path access) | The question about covers it. I'm using dreamhost, and need to utilize the stdimagefield rather than image field so I can do this:
image3 = StdImageField(upload_to='path/to/img', size=(640, 480))
If there is a better way to do this, please let me know.
Edit: Trying it like this, everything is working with the "python... | [
"Just put the django-stdimage folder into your project folder (it should already be a package).\n",
"Just copy the module contents into your project, making it a package if necessary. I put \"external\" modules in an external package.\n"
] | [
0,
0
] | [] | [] | [
"django",
"dreamhost",
"module",
"python"
] | stackoverflow_0002264959_django_dreamhost_module_python.txt |
Q:
How can I write a Python list to persistent storage?
I am currently trying to solve this problem in MySQL. I have MySQLdb installed. What is the best way to write a list in Python, e.g.
[1, 2, -1, -2]
to a column of a MySQL database table? I would like each consecutive entry of the list to be put into consecutive... | How can I write a Python list to persistent storage? | I am currently trying to solve this problem in MySQL. I have MySQLdb installed. What is the best way to write a list in Python, e.g.
[1, 2, -1, -2]
to a column of a MySQL database table? I would like each consecutive entry of the list to be put into consecutive rows of a MySQL column. I can obviously run individual qu... | [
"You're looking for executemany().\n",
"Caution: There is no notion of consecutive rows in SQL.\nThe order of input is not recorded in the SQL database unless you also have an auto increment column that is automatically updated as you insert data or some other way to order the data on input, and the order of outp... | [
2,
2
] | [] | [] | [
"mysql",
"python",
"storage"
] | stackoverflow_0002265016_mysql_python_storage.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.