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:
catching NameError and Error Handling
I am writing a function which takes the user input:
def func(input):
I put in try and excepts to make sure the input is of the type I want. However, when I put in testInput, it throws a NameError vs "testInput".
I understand why as it is thinking testInput is a variable na... | catching NameError and Error Handling | I am writing a function which takes the user input:
def func(input):
I put in try and excepts to make sure the input is of the type I want. However, when I put in testInput, it throws a NameError vs "testInput".
I understand why as it is thinking testInput is a variable name while it knows "testInput" is a string.
... | [
"NameError is usually caused by undefined variable name. If you use testInput as a variable name, i.e., without the quotes, you have to define it first. Try something like this:\ntestInput = \"my_input_test\"\nfunc(testInput)\n\nOr you can just use the string itself as the argument:\nfunc(\"my_input_test\")\n\nSome... | [
5
] | [] | [] | [
"error_handling",
"nameerror",
"python"
] | stackoverflow_0005127717_error_handling_nameerror_python.txt |
Q:
Switching ListCtrl object to another one
In wxPython, If I have a frame and in it I have a sizer with a ListCtrl object; what is the easiest way that I can switch this listctrl object to another one.
example-code
self.list = wx.ListCtrl(panel, size=(-1, 530), style=wx.LC_REPORT|wx.BORDER_SUNKEN|wx.LC_HRULES )
self... | Switching ListCtrl object to another one | In wxPython, If I have a frame and in it I have a sizer with a ListCtrl object; what is the easiest way that I can switch this listctrl object to another one.
example-code
self.list = wx.ListCtrl(panel, size=(-1, 530), style=wx.LC_REPORT|wx.BORDER_SUNKEN|wx.LC_HRULES )
self.list.InsertColumn(0, 'Country' , width = 1... | [
"I'm not quite sure what you are trying to do but I am going to take a guess at it and say that you have two ListCtrl's within your gui and you want to be able to switch between them?\nIf so, I guess my first suggestion would be to just reuse s single ListCtrl for both purposes, there really is no need to have two ... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0005445067_python_wxpython.txt |
Q:
How can I send an email using python in google app engine
Possible Duplicate:
How to send an e-mail from a Python script that is being run on “Google App Engine”?
I'd like to be able to trigger an email when certain things occur in my python google-app-engine app. Is there a simple way to do this? Basically, the... | How can I send an email using python in google app engine |
Possible Duplicate:
How to send an e-mail from a Python script that is being run on “Google App Engine”?
I'd like to be able to trigger an email when certain things occur in my python google-app-engine app. Is there a simple way to do this? Basically, the idea is that when certain server messages are received, I'd l... | [
"message = mail.EmailMessage(sender=\"<emailid>\",subject=\"Output\",to=\"<emailid>\"))\nmessage.body = \"\"\nmessage.send()\n\n"
] | [
3
] | [] | [] | [
"email",
"google_app_engine",
"python"
] | stackoverflow_0005447256_email_google_app_engine_python.txt |
Q:
Python - question about hashes and `None`
Why does None hash to -1042159082 (which I found to be equal to number of bytes in a Gigabyte negated)?
I realize this doesn't really effect my code, but I'm curious.
Hashes are used for dictionary key look-ups, so I decided to experiment:
>>> D = {-1042159082: 'Hello', No... | Python - question about hashes and `None` | Why does None hash to -1042159082 (which I found to be equal to number of bytes in a Gigabyte negated)?
I realize this doesn't really effect my code, but I'm curious.
Hashes are used for dictionary key look-ups, so I decided to experiment:
>>> D = {-1042159082: 'Hello', None: 'Hi'}
>>> D[None]
'Hi'
>>> D[-1042159082]
'... | [
"About 2 values which may produce the same output when passed to the built-in hash() function (None and -1042159082 in the question asked):\nThis is called a collision (see this page on Wikipedia for more information about collisions).\nThe hashing algorithm which Python uses has a special way to figure out which v... | [
5,
4,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0005447559_python.txt |
Q:
Accessing a Dynamically Generated Nested Dictionary
The goal is to be able to compare words in a document to the words in a set of documents as fast as possible (create a term-document matrix). If possible can this be done (and will it be fast) by using Lucene?
My thought (if done by me) is to create a tree of ter... | Accessing a Dynamically Generated Nested Dictionary | The goal is to be able to compare words in a document to the words in a set of documents as fast as possible (create a term-document matrix). If possible can this be done (and will it be fast) by using Lucene?
My thought (if done by me) is to create a tree of terms in each document and then combine the trees together t... | [
"I can see a few problems with your current implementation. How do you mark if a node in the trie is a word? A better implementation would be to initialize tree to something like tree = [{}, None] where None indicates if the current node is the end of a word.\nYour addTerm method could then be something like:\nde... | [
1,
1
] | [] | [] | [
"dictionary",
"matrix",
"nested",
"python"
] | stackoverflow_0005447428_dictionary_matrix_nested_python.txt |
Q:
Tkinter string callbacks
Here is the situation:
I have an XML file with the menu hiearchy for my app in it. I can display the menu, but defining the callbacks in the XML file only returns strings.
The more defined problem:
I need a way to callback functions via a string. Yeah, there's the
lambda x: pass
deal, b... | Tkinter string callbacks | Here is the situation:
I have an XML file with the menu hiearchy for my app in it. I can display the menu, but defining the callbacks in the XML file only returns strings.
The more defined problem:
I need a way to callback functions via a string. Yeah, there's the
lambda x: pass
deal, but I'm not really sure that's ... | [
"\nI need a way to callback functions via a string.\n\nFrom the comments to your question I understand that you'd like to do something like:\n# ...\ncallback_str = getcallback_str() # e.g., 'self.logic.account_new'\ncallback = eval_dottedname(self, callback_str)`\n\nIn this case eval_dottedname() function could be ... | [
1
] | [] | [] | [
"function",
"menu",
"python",
"tkinter"
] | stackoverflow_0005446372_function_menu_python_tkinter.txt |
Q:
XML-RPC: best way to handle 64-bit values?
So the official XML-RPC standard doesn't support 64-bit values. But in these modern times, 64-bit values are increasingly common.
How do you handle these? What XML-RPC extensions are the most common? What language bindings are there? I'm especially interested in Pytho... | XML-RPC: best way to handle 64-bit values? | So the official XML-RPC standard doesn't support 64-bit values. But in these modern times, 64-bit values are increasingly common.
How do you handle these? What XML-RPC extensions are the most common? What language bindings are there? I'm especially interested in Python and C++, but all information is appreciated.
| [
"Some libraries support 64 bits extensions, indeed, but there doesn't seem to be a standard. xmlrpc-c, for example, has a so called i8 but it doesn't work with python (at least not by default).\nI would recommend to either:\n\nConvert the integer to string by hand and send it as such. XMLRPC will convert it to stri... | [
7,
1,
0,
0
] | [] | [] | [
"64_bit",
"c++",
"python",
"xml_rpc"
] | stackoverflow_0000107616_64_bit_c++_python_xml_rpc.txt |
Q:
oauth2 library for python2.3?
Does anyone know of an oauth2 library that works with python2.3? I know python2.3 is a little dated but we still haven't updated yet :/
Most auth2 libraries I see say something like "Most likely doesn't work anymore with python2.3".
A:
There is this paid for library: http://webscri... | oauth2 library for python2.3? | Does anyone know of an oauth2 library that works with python2.3? I know python2.3 is a little dated but we still haven't updated yet :/
Most auth2 libraries I see say something like "Most likely doesn't work anymore with python2.3".
| [
"There is this paid for library: http://webscripts.softpedia.com/script/Authentication/OAuth--Python-Library--65907.html\nDisclaimer: I've not ever used it.\n",
"Check out Mike Knapp's library on GitHub.\nNice and simple, no install needed. \n"
] | [
1,
0
] | [] | [] | [
"oauth",
"python"
] | stackoverflow_0005067850_oauth_python.txt |
Q:
Trees in Python
Please help me to understand trees in Python. This is an example of tree implementation I found in the Internet.
from collections import deque
class EmptyTree(object):
"""Represents an empty tree."""
# Supported methods
def isEmpty(self):
return True
def __str__(self):
... | Trees in Python | Please help me to understand trees in Python. This is an example of tree implementation I found in the Internet.
from collections import deque
class EmptyTree(object):
"""Represents an empty tree."""
# Supported methods
def isEmpty(self):
return True
def __str__(self):
return ""
def... | [
"It sounds like your problem isn't trees, which are a much more general (and simple) concept, but in how to properly populate and/or evaluate an expression tree.\nIf you have your operators specified in post-fix order, it becomes a lot easier.\nSee this wikipedia article on how to deal with infix notation when pars... | [
1,
0,
0
] | [] | [] | [
"python",
"tree"
] | stackoverflow_0005448015_python_tree.txt |
Q:
Scrapy CrawlSpider Post-processing: Finding an Average
Let's say I have a crawl spider similar to this example:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.item import... | Scrapy CrawlSpider Post-processing: Finding an Average | Let's say I have a crawl spider similar to this example:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.item import Item
class MySpider(CrawlSpider):
name = 'example.com'
... | [
"You could use Scrapy's stats collector to build this kind of information or gather the necessary data to do so as you go. For per-category stats, you could use a per-category stats key.\nFor a quick dump of all stats gathered during a crawl, you can add STATS_DUMP = True to your settings.py.\nRedis (via redis-py) ... | [
3
] | [] | [] | [
"python",
"scrapy",
"web_scraping"
] | stackoverflow_0005447727_python_scrapy_web_scraping.txt |
Q:
django: Optimal way to select manytomany object with a particular attribute
I have a model app which has many to many association with users. Here is the code.
class app(models.Model):
users = models.ManyToManyField(UserProfile)
Now I want to check if a Django user with particular 'id' exits in this app's use... | django: Optimal way to select manytomany object with a particular attribute | I have a model app which has many to many association with users. Here is the code.
class app(models.Model):
users = models.ManyToManyField(UserProfile)
Now I want to check if a Django user with particular 'id' exits in this app's user list. After some hits and trials, I got to a solution.
def user_exists(self,u... | [
"That is very inefficient: it gets all related users and iterates through.\nA ManyToManyField returns a queryset. So you can use the normal queryset filtering methods, to do all that in a single command:\nreturn self.app.users.filter(user=user_obj).exists()\n\nNote this uses the exists() method to return a bool dir... | [
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0005448330_django_django_models_python.txt |
Q:
python intra pc client-server - dbus alternative?
I need to estabilish client-server communications on a single pc (no network) and the only option I found so far is to use dbus.
The problem is that python-dbus seems to work bad on wondows so far (my app is cross platform), furthermore I read that python-dbus api ... | python intra pc client-server - dbus alternative? | I need to estabilish client-server communications on a single pc (no network) and the only option I found so far is to use dbus.
The problem is that python-dbus seems to work bad on wondows so far (my app is cross platform), furthermore I read that python-dbus api continues to change breaking code.
Is there an alternat... | [
"I think that use a socket is the best way to do that. You can use the port you want.\nIf you want to reduce the risk of port conflict, just put the port into a config file and load it to the start of the software.\nYou can also use a parameter when you call your software like (the best solution in my opinion) :\n.... | [
0
] | [] | [] | [
"client",
"python"
] | stackoverflow_0005448551_client_python.txt |
Q:
calculating the value of the expression in Python
Possible Duplicate:
python convert a string to an operator
Hello everyboby!
I just started learning Python and have a simple question.
Is it possible to get an answer (calculate) of this expression?
['10', '/', '5']
My problem: I convert '10' and '5' just to 10 ... | calculating the value of the expression in Python |
Possible Duplicate:
python convert a string to an operator
Hello everyboby!
I just started learning Python and have a simple question.
Is it possible to get an answer (calculate) of this expression?
['10', '/', '5']
My problem: I convert '10' and '5' just to 10 and 5. How can I convert '/' just to /? I am using Pyt... | [
"I think that the best way is :\nretrieve the first element of your list and cast it to int\nretrieve the third element of your list and cast it to int\nmap the second element to a function to compute the result\nimport sys\n\nelement = ['10', '/', '5']\n\noperators = {\n '/': lambda a, b: a / b,\n '+': lambd... | [
5,
3,
2,
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0005448297_list_python.txt |
Q:
Ignore exception/error in Python while using YouTube API
I am using Python YouTube API to retrieve information from a few video ids. I sometimes run into a
gdata.service.RequestError: {'status':
403, 'body': 'Private video',
'reason': 'Forbidden'}
However, I would like my program to ignore the error and con... | Ignore exception/error in Python while using YouTube API | I am using Python YouTube API to retrieve information from a few video ids. I sometimes run into a
gdata.service.RequestError: {'status':
403, 'body': 'Private video',
'reason': 'Forbidden'}
However, I would like my program to ignore the error and continue. PFB some code snippet:
@contextlib.contextmanager
def ... | [
"The exceptions were in the lines :\n\nentry = yt_service.GetYouTubeVideoEntry(video_id = entry_video_id)\n\n\nand \n\ncomment_feed = yt_service.GetYouTubeVideoCommentFeed(uri=url)\n\n\nI added the exception_ignore_handler and the program runs by ignoring the exception now.\n"
] | [
0
] | [] | [] | [
"exception_handling",
"python",
"youtube_api"
] | stackoverflow_0005438271_exception_handling_python_youtube_api.txt |
Q:
Trigger code on program termination
My script creates files to store data for the duration of its run time, I would like to delete these files on termination of my program. Is this possible?
I DO NOT want suggestions for a work around ... like 'don't create files'.
Much appreciated!
A:
What about the os module o... | Trigger code on program termination | My script creates files to store data for the duration of its run time, I would like to delete these files on termination of my program. Is this possible?
I DO NOT want suggestions for a work around ... like 'don't create files'.
Much appreciated!
| [
"What about the os module of Python ? There is a \"remove()\" method to do what you want.\nSee the documentation\nTo handle the exit of your program, you can use atexit module.\nExample:\nimport os\n\ndef delete_file(name):\n os.remove(name)\n\nimport atexit\natexit.register(delete_file, file_path)\n\nfile_path ... | [
7,
6,
1,
1
] | [] | [] | [
"delete_file",
"python",
"termination"
] | stackoverflow_0005448766_delete_file_python_termination.txt |
Q:
How to merge only the unique lines from file_a to file_b?
This question has been asked here in one form or another but not quite the thing I'm looking for. So, this is the situation I shall be having: I already have one file, named file_a and I'm creating another file - file_b. file_a is always bigger than file_b ... | How to merge only the unique lines from file_a to file_b? | This question has been asked here in one form or another but not quite the thing I'm looking for. So, this is the situation I shall be having: I already have one file, named file_a and I'm creating another file - file_b. file_a is always bigger than file_b in size. There will be a number of duplicate lines in file_b (h... | [
"Maybe something along these lines?\nfrom sets import Set as set\n\ndef yield_lines(fileobj):\n #I want to discard the headers\n for i in xrange(3):\n fileobj.readline()\n\n for line in fileobj:\n yield line\n\ndef app(path1, path2):\n file1 = set(yield_lines(open(path1)))\n file2 = set... | [
2,
2,
0,
0
] | [] | [] | [
"python",
"python_2.3"
] | stackoverflow_0005407233_python_python_2.3.txt |
Q:
Printing floating point number in python
How can I print the following lines of code but get a floating point number of of it instead of a rounded int?
print "Math Question: ", 100 - 25 * 3 % 4
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
A:
Division with / in 2.x results in a integer if both operands are integers. E... | Printing floating point number in python | How can I print the following lines of code but get a floating point number of of it instead of a rounded int?
print "Math Question: ", 100 - 25 * 3 % 4
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
| [
"Division with / in 2.x results in a integer if both operands are integers. Either cast one of the operands to a float first, or from __future__ import division.\n",
"from __future__ import divison\n\nor run Python with the -Qnew option\nPython3 has this behaviour by default\n",
"If you use integers, Python ass... | [
3,
3,
1
] | [] | [] | [
"floating_point",
"format",
"numbers",
"python",
"string"
] | stackoverflow_0005448867_floating_point_format_numbers_python_string.txt |
Q:
Creating a IPv4 packet header in python
For my larger project i need to start with creating a IPv4 network packet ( for simulation )
for the same I need to write a function that creates a header out of the passed data which has the source ip , dest ip and all the necessary fields
def convertIpv4( data ):
pas... | Creating a IPv4 packet header in python | For my larger project i need to start with creating a IPv4 network packet ( for simulation )
for the same I need to write a function that creates a header out of the passed data which has the source ip , dest ip and all the necessary fields
def convertIpv4( data ):
pass
For this I need you to guide me in the rig... | [
"Scapy can create IP headers easily.\nHere they have an example on creating IP header.\n",
"Have a look at the PyIP module.\n"
] | [
1,
0
] | [] | [] | [
"ipv4",
"python"
] | stackoverflow_0005448277_ipv4_python.txt |
Q:
How to Set Call Back For Enter key of GtkTextView?
how can I set call back on enter key of GtkTextView Widget and set TextView to work like gtk.entry (single-line)?
A:
import gtk
tv = gtk.TextView()
def keyPress(widget, event):
if gtk.gdk.keyval_name(event.keyval) == 'Return':
## do something
... | How to Set Call Back For Enter key of GtkTextView? | how can I set call back on enter key of GtkTextView Widget and set TextView to work like gtk.entry (single-line)?
| [
"import gtk\n\ntv = gtk.TextView()\n\ndef keyPress(widget, event):\n if gtk.gdk.keyval_name(event.keyval) == 'Return':\n ## do something\n return True\n return False\n\ntv.connect('key-press-event', keyPress)\n\nwin = gtk.Dialog()\nwin.vbox.pack_start(tv)\nwin.vbox.show_all()\nwin.run()\n\nBut a... | [
6
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003652877_pygtk_python.txt |
Q:
Python Backend Logic Adding MVC Framework (Django)
I have a Python CLI program, with SQL database models and want to add a frontend with a MVC framework (such as Django). What's the best way to interface my program with the framework, if I've already defined my models?
Do I either:
Rewrite the model so it's shar... | Python Backend Logic Adding MVC Framework (Django) | I have a Python CLI program, with SQL database models and want to add a frontend with a MVC framework (such as Django). What's the best way to interface my program with the framework, if I've already defined my models?
Do I either:
Rewrite the model so it's shared by both Django and my program
Write a layer that inte... | [
"I love Django but given this scenario, you could also take a look at Pylons too, since they support SQLAlchemy. Or you can still work with SQLAlchemy by importing it into your views. See this post on an example for doing that.\n",
"Let's start by making observation that frontend which modifies data bypassing bac... | [
3,
1,
0,
0
] | [] | [] | [
"backend",
"django",
"interaction",
"python"
] | stackoverflow_0004577514_backend_django_interaction_python.txt |
Q:
Python : sending mail through gmail issue
I am trying to send an email (through gmail) using python script that someone once wrote on this site, but I'm getting an error:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe8 in position 2: invalid continuation byte
the script:
import smtplib
from email.mime.tex... | Python : sending mail through gmail issue | I am trying to send an email (through gmail) using python script that someone once wrote on this site, but I'm getting an error:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe8 in position 2: invalid continuation byte
the script:
import smtplib
from email.mime.text import MIMEText
#mail setup
FROMMAIL = "xxx@... | [
"Use the 'email' module of Python in order to generate proper formatted emails.\nDealing yourself with encoding issues on the application level while composing emails directly through Python is not the way to go.\n"
] | [
0
] | [] | [] | [
"decode",
"email",
"gmail",
"python",
"unicode"
] | stackoverflow_0005449084_decode_email_gmail_python_unicode.txt |
Q:
vimrc mapping problem; execute python script mapping not working from vimrc
grr. I'm struggling with Vim's learning curve.
And trying to get a simple mapping in my vimrc to execute the current buffer's python script.
The mapping is well-formed and works after I enter it into the command line in Vim. This is the ... | vimrc mapping problem; execute python script mapping not working from vimrc | grr. I'm struggling with Vim's learning curve.
And trying to get a simple mapping in my vimrc to execute the current buffer's python script.
The mapping is well-formed and works after I enter it into the command line in Vim. This is the mapping:
map <buffer> <S-e> :w<CR>:!usr/bin/env python % <CR>
But it won't ... | [
"I suspect that you have something before map: <buffer> argument means that mapping is defined for current buffer only, so adding it to vimrc without something like autocmd FileType python before it is weird. Maybe it is the reason why it does not work: you somehow switch to another buffer before testing this mappi... | [
2,
0
] | [] | [] | [
"map",
"python",
"vim"
] | stackoverflow_0005449207_map_python_vim.txt |
Q:
Python's equivalent for Ruby's define_method?
Is there a Python equivalent for Ruby's define_method, which would allow dynamic generation of class methods?
(as can be seen in Wikipedia's Ruby example code)
A:
Functions are first-class objects in Python and can be assigned to attributes of a class or an instance.... | Python's equivalent for Ruby's define_method? | Is there a Python equivalent for Ruby's define_method, which would allow dynamic generation of class methods?
(as can be seen in Wikipedia's Ruby example code)
| [
"Functions are first-class objects in Python and can be assigned to attributes of a class or an instance. One way to do the same thing as in the Wikipedia example is:\ncolours = {\"black\": \"000\",\n \"red\": \"f00\",\n \"green\": \"0f0\",\n \"yellow\": \"ff0\",\n \"blue\":... | [
14,
2,
0
] | [
"Either look into abstract base classes:\nhttp://docs.python.org/library/abc.html\nor \ncheck the options that the 'new' (or the newer 'types') module provides to you.\n"
] | [
-2
] | [
"python",
"ruby"
] | stackoverflow_0005449244_python_ruby.txt |
Q:
How can I use Pika to send and receive RabbitMQ messages?
I'm having some issue getting Pika to work with routing keys or exchanges in a way that's consistent with it AMQP or RabbitMQ documentation. I understand that the RabbitMQ documentation uses an older version of Pika, so I have disregarded their example code... | How can I use Pika to send and receive RabbitMQ messages? | I'm having some issue getting Pika to work with routing keys or exchanges in a way that's consistent with it AMQP or RabbitMQ documentation. I understand that the RabbitMQ documentation uses an older version of Pika, so I have disregarded their example code.
What I'm trying to do is define a queue, "order" and have tw... | [
"As it turns out, my understanding of AMQP was incomplete. \nThe idea is as following:\nClient:\nThe client after getting the connection should not care about anything else but the name of the exchange and the routing key. That is we don't know which queue this will end up in.\nchannel.basic_publish(exchange='order... | [
12
] | [] | [] | [
"amqp",
"python",
"rabbitmq"
] | stackoverflow_0005448936_amqp_python_rabbitmq.txt |
Q:
How to turn a string of letters into 3 letter words in Python 2.7.1
I have a string of letters 'aaabbbcccdddeeefffggg' that i would like to read as 3 letter words. For example, 'aaa','bbb','ccc'...
Is there any code that you know of that can do this function?
My ultimate goal is to assign numbers to each word like... | How to turn a string of letters into 3 letter words in Python 2.7.1 | I have a string of letters 'aaabbbcccdddeeefffggg' that i would like to read as 3 letter words. For example, 'aaa','bbb','ccc'...
Is there any code that you know of that can do this function?
My ultimate goal is to assign numbers to each word like
aaa= 123
bbb= 234
ccc= 356 ...
and have the output be the position of t... | [
"Something like this?\ndata = 'aaabbbcccdddeeefffggg'\ntrans = {'aaa': 123, 'bbb': 234, 'ccc': 356, ...}\n[(x + 1, trans[y * 3]) for x, y in enumerate(data[::3])]\n\nOtherwise:\ndef trans(c):\n a = ord('a')\n return ord(c) - a + 3 + 10 * (ord(c) - a + 2) + 100 * (ord(c) - a + 1)\n\ndata = 'aaabbbcccdddeeefffg... | [
1,
0,
0,
0
] | [] | [] | [
"function",
"list",
"python",
"string",
"word"
] | stackoverflow_0005446837_function_list_python_string_word.txt |
Q:
how to have google apps engine send mail- not send a copy of the mail to the sender
I'm using GAE send mail- but I dont want the sender of the mail to get a coppy of the mail.
as for now, when a user is sending mail he gets a mail saying that he sent a mail to someone and the body of the sent mail, how do I disabl... | how to have google apps engine send mail- not send a copy of the mail to the sender | I'm using GAE send mail- but I dont want the sender of the mail to get a coppy of the mail.
as for now, when a user is sending mail he gets a mail saying that he sent a mail to someone and the body of the sent mail, how do I disable that?
| [
"You can't. Sending email from someone without their knowledge isn't permitted by App Engine.\nYou can send email from any administrator address; you could add a \"donotreply@yourapp.com\" type address as an administrator and send email from that address.\n"
] | [
6
] | [] | [] | [
"google_app_engine",
"python",
"sendmail"
] | stackoverflow_0005448698_google_app_engine_python_sendmail.txt |
Q:
Intelligent screen scraping using different proxies and user-agents randomly?
I want to download few HTML pages from http://abc.com/view_page.aspx?ID= The ID is from an array of different numbers.
I would be interested in visiting multiple instances of this URL and saving the file as [ID].HTML using different pro... | Intelligent screen scraping using different proxies and user-agents randomly? | I want to download few HTML pages from http://abc.com/view_page.aspx?ID= The ID is from an array of different numbers.
I would be interested in visiting multiple instances of this URL and saving the file as [ID].HTML using different proxy IP/ports.
I want to use different user-agents and I want to randomize the wait ... | [
"Use something like:\nimport urllib2\nimport time\nimport random\n\nMAX_WAIT = 5\nids = ...\nagents = ...\nproxies = ...\n\nfor id in ids:\n url = 'http://abc.com/view_page.aspx?ID=%d' % id\n opener = urllib2.build_opener(urllib2.ProxyHandler({'http' : proxies[0]}))\n html = opener.open(urllib2.Request(url... | [
5,
2,
2
] | [] | [] | [
"proxy",
"python",
"screen_scraping"
] | stackoverflow_0002803737_proxy_python_screen_scraping.txt |
Q:
what's the difference between matplotlib.pyplot and matplotlib.figure?
I'm just getting into matplotlib.
I see some examples of matplotlib.pyplot used, but when integrating matplotlib with wxpython i often see matplotlib.figure like
from matplotlib.figure import Figure
...
vboxFigure = wx.BoxSizer(wx.VERTICAL)
s... | what's the difference between matplotlib.pyplot and matplotlib.figure? | I'm just getting into matplotlib.
I see some examples of matplotlib.pyplot used, but when integrating matplotlib with wxpython i often see matplotlib.figure like
from matplotlib.figure import Figure
...
vboxFigure = wx.BoxSizer(wx.VERTICAL)
self.figure = Figure()
self.axes = self.figure.add_subplot(111)
t = [1,2,3,4... | [
"Pyplot is the Matlab-like state-machine API, matplotlib.figure.Figure is part of the object-oriented API. See e.g. this tutorial to get started with the object-oriented API. If you want to create a wx app, you will most likely need to learn the OO API.\n"
] | [
14
] | [] | [] | [
"matplotlib",
"python",
"wxpython"
] | stackoverflow_0005450207_matplotlib_python_wxpython.txt |
Q:
How can I improve my INSERT statement performance?
While Josh's answer here gave me a good head start on how to insert a 256x64x250 value array into a MySQL database. When I actually tried his INSERT statement on my data it turned out horribly slow (as in 6 minutes for a 16Mb file).
ny, nx, nz = np.shape(data)
que... | How can I improve my INSERT statement performance? | While Josh's answer here gave me a good head start on how to insert a 256x64x250 value array into a MySQL database. When I actually tried his INSERT statement on my data it turned out horribly slow (as in 6 minutes for a 16Mb file).
ny, nx, nz = np.shape(data)
query = """INSERT INTO `data` (frame, sensor_row, sensor_co... | [
"the fastest way to insert 4 million rows (16MB of data) would be to use load data infile - http://dev.mysql.com/doc/refman/5.0/en/load-data.html\nso if possible generate a csv file then use load data infile..\nhope this helps :)\nEDIT\nSo I took one of your original data files rolloff.dat and wrote a quick and dir... | [
6,
5,
1,
0,
0
] | [
"You could employ list comprehenshions instead of for loops:\nvalues = [(frames, rows, cols, data[rows,cols,frames]) \\\n for frames in range(nz) for rows in range(ny) \\\n for cols in range(nx) if data[rows,cols,frames] > 0.0] \n\nI'd estimate this could give you slight speed up such as 10-... | [
-1
] | [
"mysql",
"python"
] | stackoverflow_0005450055_mysql_python.txt |
Q:
wxPython: prevent taskbar menu from closing after clicking an item
I am using wxPython to create a taskbar menu. The menu contains some menu items (obviously).
Now I would like to update/change some of these items when a particular item is clicked, while still displaying the menu.
How can I prevent the taskbar m... | wxPython: prevent taskbar menu from closing after clicking an item | I am using wxPython to create a taskbar menu. The menu contains some menu items (obviously).
Now I would like to update/change some of these items when a particular item is clicked, while still displaying the menu.
How can I prevent the taskbar menu from disappearing after clicking an item?
The only method I've foun... | [
"Although I never got around to trying it myself, I remember attempting a similar effect with a popup menu & textctrl. You might want to consider trying wx.lib.agw.flatmenu.FlatMenuBar, it provides an event handler OnMenuDismissed(self, event), as well as a few others, which by name appear to be what you need. You ... | [
0
] | [] | [] | [
"python",
"taskbar",
"wxpython"
] | stackoverflow_0003150609_python_taskbar_wxpython.txt |
Q:
Attribute error using __builtin__ functions inside class method
I installed rdiff-backup on my arch linux box only to end up with the attribute error:
AttributeError: 'module' object has no attribute 'reduce'
The error exists in one of rdiff_backup classes, but I can not spot the error. The function reduce should... | Attribute error using __builtin__ functions inside class method | I installed rdiff-backup on my arch linux box only to end up with the attribute error:
AttributeError: 'module' object has no attribute 'reduce'
The error exists in one of rdiff_backup classes, but I can not spot the error. The function reduce should be builtin, and I can not get the code to find the function.
The cod... | [
"reduce(lambda x,y: x+y, l) is an equivalent of sum(l). Can you try whether sum(l) works? Also, which python version are you using (sum is available in version >= 2.3)\n"
] | [
0
] | [] | [] | [
"built_in",
"linux",
"namespaces",
"python"
] | stackoverflow_0005450510_built_in_linux_namespaces_python.txt |
Q:
Python, why can't i override Popen.stdout
Why is possibile to override sys.stdout but not subprocess.Popen.stdout, with my own class.
If it is possibile to override please show me how ...
I'm working on some GUI project, and i want to print output of some other program on text_view in "real_time", not when everyth... | Python, why can't i override Popen.stdout | Why is possibile to override sys.stdout but not subprocess.Popen.stdout, with my own class.
If it is possibile to override please show me how ...
I'm working on some GUI project, and i want to print output of some other program on text_view in "real_time", not when everything is done.
when i am overriding sys.stdout i ... | [
"You can achieve the same by using:\np = Popen(args, ..., stdout=subprocess.PIPE)\nfor line in p.stdout:\n print line\n\nwhere p.stdout behaves like PIPE, so you can read data from it as soon as it arrives. It is not strict realtime, because some buffering comes in play, but still this is a viable alternative.\n"... | [
2
] | [] | [] | [
"python",
"stdout"
] | stackoverflow_0005450741_python_stdout.txt |
Q:
Python inheritance problem
I'm making a game, and I have some problems... I have a function that loads a map (usually when the player collides with a gate). I have two gates and two maps (one gate on each map). When I walk to a gate the second map is loaded, when I walk through a gate on that map, the first map is... | Python inheritance problem | I'm making a game, and I have some problems... I have a function that loads a map (usually when the player collides with a gate). I have two gates and two maps (one gate on each map). When I walk to a gate the second map is loaded, when I walk through a gate on that map, the first map is loaded. I also have a tree on t... | [
"You have a global variable \"creature\" which is hiding your class.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0005450877_python.txt |
Q:
Why does python dict behave this way?
I have some code written like so:
class Invite(models.Model):
STATE_UNKNOWN = 0
STATE_WILL_PLAY = 1
STATE_WONT_PLAY = 2
STATE_READY = 3
STATE_CHOICES = ((STATE_UNKNOWN, _("Unknown")),
(STATE_WILL_PLAY, _("Yes, I'll play")),
... | Why does python dict behave this way? | I have some code written like so:
class Invite(models.Model):
STATE_UNKNOWN = 0
STATE_WILL_PLAY = 1
STATE_WONT_PLAY = 2
STATE_READY = 3
STATE_CHOICES = ((STATE_UNKNOWN, _("Unknown")),
(STATE_WILL_PLAY, _("Yes, I'll play")),
(STATE_WONT_PLAY, _("Sorry, can't... | [
"The constructor of dict accepts (among other things) a sequence of (key, value) tuples. Your second examples passes a list of tuples of length 3 instead of 2, and hence fails.\ndict([(1, (2, 3)), (2, (2, 3)), (3, (2, 3))])\n\nhowever will create the dictionary\n{1: (2, 3), 2: (2, 3), 3: (2, 3)}\n\n",
"I think i... | [
3,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0005451204_python.txt |
Q:
creating an iterator in Python from a dictionary in memory-efficient way
I'm iterating through a very large tab-delimited file (containing millions of lines) and pairing different lines of it based on the value of some field in that file, e.g.
mydict = defaultdict()
for line in myfile:
# Group all lines that hav... | creating an iterator in Python from a dictionary in memory-efficient way | I'm iterating through a very large tab-delimited file (containing millions of lines) and pairing different lines of it based on the value of some field in that file, e.g.
mydict = defaultdict()
for line in myfile:
# Group all lines that have the same field into a list
mydict[line.field].append(line)
Since "mydict"... | [
"It sounds like you might want a database. There's a variety of relational and non-relational databases you can pick from (some more efficient than others, depending on what you are trying to achieve), but sqlite (built into python) would be the easiest.\nOr, if there are only a small number of line.fields to proce... | [
2,
1
] | [] | [] | [
"loops",
"memory_efficient",
"python",
"scripting"
] | stackoverflow_0005451159_loops_memory_efficient_python_scripting.txt |
Q:
can web2py support RESTful api calls? if so any pointers on how to build one?I
I want to configure a simple webapplication to support an iphone app to connect with it in RESTFUL ways. Initially have a user login session enabled from the iphone to the web app. I'd like the iphone app to send a NSURL call to the web... | can web2py support RESTful api calls? if so any pointers on how to build one?I | I want to configure a simple webapplication to support an iphone app to connect with it in RESTFUL ways. Initially have a user login session enabled from the iphone to the web app. I'd like the iphone app to send a NSURL call to the webapp, with user and password and have the webapp respond if the suer exists or not. P... | [
"I think you should post it to web2py group on google groups.\nweb2py@googlegroups.com\n",
"I know this question is a bit old now, but Massimo recently posted a video demonstrating a new experimental RESTful API for web2py. See also the Google groups posting \"video about new RESTful APIs\" .\n"
] | [
2,
1
] | [] | [] | [
"cocoa",
"iphone",
"python",
"restful_authentication",
"web2py"
] | stackoverflow_0004801216_cocoa_iphone_python_restful_authentication_web2py.txt |
Q:
python function that creates HTML for a row containing two cells
I'm looking to write a function in python that accepts a dictionary and a single key as parameters in order to create HTML for a row containing two cells. I'd like the cells to contain a key/value pair from the dictionary.
the dictionary -
d = {'ye... | python function that creates HTML for a row containing two cells | I'm looking to write a function in python that accepts a dictionary and a single key as parameters in order to create HTML for a row containing two cells. I'd like the cells to contain a key/value pair from the dictionary.
the dictionary -
d = {'year':1999, 'director':'Mike Judge', 'title':'Office Space'}
my guess a... | [
"The code you written is OK, but you can make it more concise:\ndef makeHTMLRow(d, 'title'):\n s = \"<tr>\\n\\t\"\n s += \"<td>%(year)d</td>\\n\\t\"\n s += \"<td>%(director)s</td>\\n\"\n s += \"</tr><tr>\\n\\t\"\n s += \"<td>%(title)s></td>\\n\"\n s += \"</tr>\"\n return s % d\n\nThis sample u... | [
2,
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0005451427_html_python.txt |
Q:
Global variable problem - Python
I am having difficulties with global variables.
My code:
from Tkinter import *
import Tkinter as tk
import tkMessageBox
import time
import re
import string
from random import randint
class prgrm():
def start():
global bs
global bsrly
global bsrly2
... | Global variable problem - Python | I am having difficulties with global variables.
My code:
from Tkinter import *
import Tkinter as tk
import tkMessageBox
import time
import re
import string
from random import randint
class prgrm():
def start():
global bs
global bsrly
global bsrly2
global turns
global rec
... | [
"Best approach that will fix your issues: Eliminate the global variables and pass them as arguments either to the method at hand, or, to a previously called method (such as the constructor) and set them within the class.\nSo instead of:\nclass Foo:\n def test():\n global a\n global b\n globa... | [
3,
2,
1,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0005446889_python_tkinter.txt |
Q:
How to set the environment in which python snippet can run in c++ program?
I have created two files embed.py useEmbed.cppin my home directory.
embed.py
import os
print os.getcwd()
useEmbed.cpp
#include <iostream>
#include "Python.h"
using namespace std;
int main()
{
Py_Initialize();
PyRu... | How to set the environment in which python snippet can run in c++ program? | I have created two files embed.py useEmbed.cppin my home directory.
embed.py
import os
print os.getcwd()
useEmbed.cpp
#include <iostream>
#include "Python.h"
using namespace std;
int main()
{
Py_Initialize();
PyRun_SimpleFile("embed.py");
Py_Finalize();
return 0;
}
Command g+... | [
"Make sure you point the compiler to the directory where Python.h is located, i.e. use the -I<path> switch with gcc. Of course you need to have the Python development files installed.\n",
"On linux, you can use python-config to get the compiler flags (python-config --cflags) and linker flags (python-config --ldfl... | [
3,
3
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0005450928_c++_python.txt |
Q:
Example google app engine (python, Django) websites with open source
I am learning to create a website using google app engine with python and django. Does anyone have sample websites with open source that i can look at and learn from ?
thanks,
A:
A nice variety of example projects:
http://code.google.com/p/goog... | Example google app engine (python, Django) websites with open source | I am learning to create a website using google app engine with python and django. Does anyone have sample websites with open source that i can look at and learn from ?
thanks,
| [
"A nice variety of example projects:\nhttp://code.google.com/p/google-app-engine-samples/\n",
"Checkout rietveld, a code review web app along with its source code.\n"
] | [
5,
2
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0005451644_django_google_app_engine_python.txt |
Q:
pygtk's strange problem about set button's sensitive property
on one of my methods, I have the following code:
def fun():
self.button1.set_sensitive(False)
self.get_time()
However, self.button1 only becomes insensitive after get_time() return !!,use the time.sleep(n) replace the get_time() could get same re... | pygtk's strange problem about set button's sensitive property | on one of my methods, I have the following code:
def fun():
self.button1.set_sensitive(False)
self.get_time()
However, self.button1 only becomes insensitive after get_time() return !!,use the time.sleep(n) replace the get_time() could get same result
Any clue why?
| [
"I think programmic changes to widgets applies in the next lap of event loop (gtk.main()), that is probably after finishing fun function. Does that make a problem for you? How much time self.get_time()\n takes? If that takes a sensible time, you can update widgets before that:\ndef fun():\n self.button1.set_sensi... | [
4,
0
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0005448217_pygtk_python.txt |
Q:
django 1.3 wsgi input error using django-page-cms 1.4
Im trying to upgrade an old project made using django 1.2 / django-page-cms 1.2 to django 1.3 / django-page-cms 1.4
Everything works fine until I try to edit/add a page. That's when I receive the following error:
Exception Type: KeyError
Exception Value: ... | django 1.3 wsgi input error using django-page-cms 1.4 | Im trying to upgrade an old project made using django 1.2 / django-page-cms 1.2 to django 1.3 / django-page-cms 1.4
Everything works fine until I try to edit/add a page. That's when I receive the following error:
Exception Type: KeyError
Exception Value: 'wsgi.input'
Exception Location: C:\Python26\lib\site-... | [
"The problem was related specifically to the latest page cms when used with the latest version of django. It was fixed back in nov 2010.\nthe details and fix can be found here:\nhttps://github.com/batiste/django-page-cms/issues/closed/#issue/14\n"
] | [
0
] | [] | [] | [
"django",
"python",
"windows_xp"
] | stackoverflow_0005420934_django_python_windows_xp.txt |
Q:
Why won't this override of the Model.save() function in Django work?
I am new to SO and Python/Django, so please bear with me.
In my generic blog app based on the tutorial at http://www.djangoproject.com/, I am trying to create slugs for posts when they are saved to the database by using the slugify() method on th... | Why won't this override of the Model.save() function in Django work? | I am new to SO and Python/Django, so please bear with me.
In my generic blog app based on the tutorial at http://www.djangoproject.com/, I am trying to create slugs for posts when they are saved to the database by using the slugify() method on the post's title. Here is posts.models.py:
from django.db import models
from... | [
"modocache,\nWhat version of django are you using? What you have there listed should work, I use that same logic in many of my own models, and it works fine. \nAccording to this page: http://fosshelp.blogspot.com/2010/12/django-override-save-method-two-ways.html\nyou should be able to change the code to look like t... | [
4,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0005451724_django_django_models_python.txt |
Q:
How a framework development works without a debugger?
I am quite new with development. In some programming language such as python and PHP there is not a good debugger. How is the development going on without a debugger? just put the logs in the source code? Especially for the framework developers, how do they tes... | How a framework development works without a debugger? | I am quite new with development. In some programming language such as python and PHP there is not a good debugger. How is the development going on without a debugger? just put the logs in the source code? Especially for the framework developers, how do they test their codes?
Thank you very much.
-Stefan-
| [
"Your answer concerning the debugging in Python is truly nonsense. Python has a reasonable \"pdb\" debugger which is useful since years. Apart from that you can have a powerful IDE as WingIDE giving you all debugging and inspection power you need. Making such wild claims about Python is not appropriate. That's why ... | [
2,
1,
0,
0,
0
] | [] | [] | [
"debugging",
"php",
"python"
] | stackoverflow_0005447482_debugging_php_python.txt |
Q:
XML-RPC server logging
I found a recipe do log activities of an XML-RPC server at http://code.activestate.com/recipes/496700-logging-simplexmlrpcserver/
The problem that I'm having is I want to reuse the LoggingSimpleRPCRequestHandler (i.e import it) but I don't know how to correctly set the 'logger' variable. The... | XML-RPC server logging | I found a recipe do log activities of an XML-RPC server at http://code.activestate.com/recipes/496700-logging-simplexmlrpcserver/
The problem that I'm having is I want to reuse the LoggingSimpleRPCRequestHandler (i.e import it) but I don't know how to correctly set the 'logger' variable. The idea is that
This works (L... | [
"Ok, I haven't properly read you code. Now I see that in this structure it is impossible to do what I proposed. What I would do here is to prepare custom logger at the module level and retrieve it by name in LoggingSimpleXMLRPCRequestHandler.\nYour are doing part of it in \"main\": configuring the logger with name ... | [
2
] | [] | [] | [
"logging",
"python",
"xml_rpc"
] | stackoverflow_0005452284_logging_python_xml_rpc.txt |
Q:
Writing to file problems and displaying file contents
I am currently having problems displaying a file correctly once i have written a dictionary to the file. For this program the input file needs to have the format:
ID: Date: Dayskept: ProductName e.g. 1:12/12/2011:12:A
This is fine the first time I read the exam... | Writing to file problems and displaying file contents | I am currently having problems displaying a file correctly once i have written a dictionary to the file. For this program the input file needs to have the format:
ID: Date: Dayskept: ProductName e.g. 1:12/12/2011:12:A
This is fine the first time I read the example file into a dictionary, but once i save the dictionay i... | [
"Since you have a specific format you want, you're going to need to write code to emit that format. (I don't know what you're trying to do with pickle in there, that produces a binary format that doesn't bear any resemblance to what you say you're getting.)\nFor instance, you could redefine saveProduct like so:\nd... | [
1
] | [] | [] | [
"dictionary",
"file_handling",
"python"
] | stackoverflow_0005452437_dictionary_file_handling_python.txt |
Q:
wxpython, hidding and showing an object with its defined flags
If I add an item to a sizer, with a few flags; it works great. But if I hide it and then show it back again, it shows up but without using the flags!!! Why? How can I fix it?
ex:
sizer.Add(self.listb, 1, wx.ALL|wx.EXPAND, 5) # -> works great
.
.
self.... | wxpython, hidding and showing an object with its defined flags | If I add an item to a sizer, with a few flags; it works great. But if I hide it and then show it back again, it shows up but without using the flags!!! Why? How can I fix it?
ex:
sizer.Add(self.listb, 1, wx.ALL|wx.EXPAND, 5) # -> works great
.
.
self.listb.Hide()
self.listb.Show() # --> brings back the item without... | [
"Instead of using the controls Show/Hide functions, try using the BoxSizer's Show/Hide functions.\n.\n.\nsizer.Add(self.listb, 1, wx.ALL|wx.EXPAND, 5) # -> works great\nsizer.Show(self.listb, False)\nsizer.Show(self.listb, True)\n.\n.\n\nYou could also try adding sizer.Layout() to the end if it still does not solv... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0005449482_python_wxpython.txt |
Q:
Does disabling unused languages [Python ASP.net CGI Perl] in PLESK8 Speed Up PHP5 on Apache server?
Fellow Folks,
Inspecting om my PLESK 8.2 on APACHE2 with PHP 5.2.3 I saw this. Being a person who loves peed, would I gain anything by disabling all the stuff except PHP? which is the only thing I use really? I'll ... | Does disabling unused languages [Python ASP.net CGI Perl] in PLESK8 Speed Up PHP5 on Apache server? | Fellow Folks,
Inspecting om my PLESK 8.2 on APACHE2 with PHP 5.2.3 I saw this. Being a person who loves peed, would I gain anything by disabling all the stuff except PHP? which is the only thing I use really? I'll do anything to speed up my site. Advise in regards to the buttons in this picture is appreciated greatly.... | [
"No - disabling the other language's won't make PHP any faster, as the other options won't be using CPU time unless they're actively being used.\nIn theory, you might save some memory due to Apache modules not being loaded, but this is pretty marginal.\nThat said, if you're not going to use them it makes sense to d... | [
1
] | [] | [] | [
"apache",
"asp.net",
"php",
"plesk",
"python"
] | stackoverflow_0005452648_apache_asp.net_php_plesk_python.txt |
Q:
Lucene and Django with Limited Memory
I'm running a Django application on a shared web server with limited application memory. I want to incorporate Lucene for a search functionality. What are my options, given the limited amount memory?
I thought about using Solr via solrpy, but it looks like Solr is very memory ... | Lucene and Django with Limited Memory | I'm running a Django application on a shared web server with limited application memory. I want to incorporate Lucene for a search functionality. What are my options, given the limited amount memory?
I thought about using Solr via solrpy, but it looks like Solr is very memory hungry. Do you think it would be possible t... | [
"You're not going to get the JVM to even fit in 15MB. I wouldn't try to run Solr unless there's at least 200MB memory.\nYou could try Woosh, a pure Python search library, or Xapian, which is in C++. Haystack makes it easy to integrate either into Django.\n"
] | [
2
] | [] | [] | [
"django",
"lucene",
"python",
"solr"
] | stackoverflow_0005452116_django_lucene_python_solr.txt |
Q:
Read words from .txt, and count for each words
I wonder, how to read character string like fscanf. I need to read for word, in the all .txt . I need a count for each words.
collectwords = collections.defaultdict(int)
with open('DatoSO.txt', 'r') as filetxt:
for line in filetxt:
v=""
for char in line:
... | Read words from .txt, and count for each words | I wonder, how to read character string like fscanf. I need to read for word, in the all .txt . I need a count for each words.
collectwords = collections.defaultdict(int)
with open('DatoSO.txt', 'r') as filetxt:
for line in filetxt:
v=""
for char in line:
if str(char) != " ":
v=v+str(char)
... | [
"Uhm, like this?\nwith open('DatoSO.txt', 'r') as filetxt:\n for line in filetxt:\n for word in line.split():\n collectwords[word] += 1\n\n",
"You might also consider using collections.counter if you are using Python >=2.7\nhttp://docs.python.org/library/collections.html#collections.Counter\n... | [
3,
3,
1
] | [] | [] | [
"file",
"python"
] | stackoverflow_0005452550_file_python.txt |
Q:
Wxpython - setting background color of a listctrl of a CELL, not of the entire row
Is it possible to set the background color of a cell in a wxpython listctrl object? I have found SetItemTextColour() and the SetItemBackgroundColour() but both only change the colors for the entire row.
Any ideas? Thanks!
A:
You m... | Wxpython - setting background color of a listctrl of a CELL, not of the entire row | Is it possible to set the background color of a cell in a wxpython listctrl object? I have found SetItemTextColour() and the SetItemBackgroundColour() but both only change the colors for the entire row.
Any ideas? Thanks!
| [
"You might want to switch to an UltimateListCtrl to achieve your goals, take a look in the wxPython demo for an example of how to accomplish your goals their sample has single-celled background adjustments. You can also checkout the AGW home page for more information and updated version.\nfrom wx.lib.agw import ul... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0005449046_python_wxpython.txt |
Q:
Unscriptable Int Error for String Slice
I'm writing a webscraper and I have a table full of links to .pdf files that I want to download, save, and later analyze. I was using beautiful soup and I had soup find all the links. They are normally beautiful soup tag objects, but I've turned them into strings. The str... | Unscriptable Int Error for String Slice | I'm writing a webscraper and I have a table full of links to .pdf files that I want to download, save, and later analyze. I was using beautiful soup and I had soup find all the links. They are normally beautiful soup tag objects, but I've turned them into strings. The string is actually a bunch of junk with the link... | [
"just_the_link = end_of_link[9:end_of_link]\n\nThis is your problem, just like the error message says. end_of_link is an integer -- the index of \".pdf\" in pdf_link_string, which you calculated in the preceding line. So naturally you can't slice it. You want to slice pdf_link_string.\n",
"Sounds like a job for ... | [
1,
0
] | [] | [] | [
"python",
"slice",
"string"
] | stackoverflow_0005452464_python_slice_string.txt |
Q:
Remove certain consecutive duplicates in list
I have a list of strings like this:
['**', 'foo', '*', 'bar', 'bar', '**', '**', 'baz']
I want to replace the '**', '**' with a single '**', but leave 'bar', 'bar' intact. I.e. replace any consecutive number of '**' with a single one. My current code looks like this:
... | Remove certain consecutive duplicates in list | I have a list of strings like this:
['**', 'foo', '*', 'bar', 'bar', '**', '**', 'baz']
I want to replace the '**', '**' with a single '**', but leave 'bar', 'bar' intact. I.e. replace any consecutive number of '**' with a single one. My current code looks like this:
p = ['**', 'foo', '*', 'bar', 'bar', '**', '**', 'b... | [
"Not sure about pythonic, but this should work and is more terse:\nstar_list = ['**', 'foo', '*', 'bar', 'bar', '**', '**', 'baz']\nstar_list = [i for i, next_i in zip(star_list, star_list[1:] + [None]) \n if (i, next_i) != ('**', '**')]\n\nThe above copies the list twice; if you want to avoid that, con... | [
5,
3,
1,
1,
1,
1
] | [] | [] | [
"duplicates",
"list",
"python"
] | stackoverflow_0005443271_duplicates_list_python.txt |
Q:
Using Python on Dreamhost, return XML document (not HTML)
The Dreamhost Python documentation specifies that a Python script must print the HTML type declaration as the first line of output. However, I need to produce an XML response for a third-party API. Here's what I've tried:
Set type declaration to XML. Dream... | Using Python on Dreamhost, return XML document (not HTML) | The Dreamhost Python documentation specifies that a Python script must print the HTML type declaration as the first line of output. However, I need to produce an XML response for a third-party API. Here's what I've tried:
Set type declaration to XML. Dreamhost throws an error when I do this.
Set type declaration to HT... | [
"The relevant sentence in the page you linked to is:\n\nIf you want to view printed output\n from your Python code, you must print\n print \"Content-type: text/html\\n\\n\" as\n the first line of output.\n\nNote the first part - \"if you want to view printed output.\" That's only a requirement is you expect a we... | [
1
] | [] | [] | [
"dreamhost",
"html",
"python",
"type_declaration",
"xml"
] | stackoverflow_0005452533_dreamhost_html_python_type_declaration_xml.txt |
Q:
log into website (specifically netflix) with python
I am trying to log into netflix with python, would work perfectly but i cant get it to detect weather or not login failed, the code looks like this:
#this is not purely my code! Thanks to Ori for the code
import urllib
username = raw_input('Enter your email: ')
p... | log into website (specifically netflix) with python | I am trying to log into netflix with python, would work perfectly but i cant get it to detect weather or not login failed, the code looks like this:
#this is not purely my code! Thanks to Ori for the code
import urllib
username = raw_input('Enter your email: ')
password = raw_input('Enter your password: ')
params = url... | [
"First, I'll just share some verbiage I noticed on the Netflix site under Limitations on Use:\nAny unauthorized use of the Netflix service or its contents will terminate the limited license granted by us and will result in the cancellation of your membership.\nIn short, I'm not sure what your script does after this... | [
4
] | [] | [] | [
"automation",
"forms",
"python",
"tcp",
"urllib2"
] | stackoverflow_0005216128_automation_forms_python_tcp_urllib2.txt |
Q:
Searching for elements in a python list
Searching for elements in a python list and then accessing particular values
Mylist = [('A',3,['x','y','z']),('B',2,['m','n'])]
Variable = 'A'
i = Mylist.index(Variable)
print i
For example I would like to check if is Variable is present and access its elements li... | Searching for elements in a python list | Searching for elements in a python list and then accessing particular values
Mylist = [('A',3,['x','y','z']),('B',2,['m','n'])]
Variable = 'A'
i = Mylist.index(Variable)
print i
For example I would like to check if is Variable is present and access its elements like
is present then access each of sublist el... | [
"It looks like you haven't found the Python dict yet. Perhaps you mean:\nmydict = {}\nmydict['A'] = {'count': 3, 'letters': ['x','y','z']}\nmydict['B'] = {'count': 2, 'letters': ['m','n']}\n\nmydict is a dictionary that itself contains dictionaries.\nYou can then look them up with:\nval = mydict['A']\nprint val['l... | [
1,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0005452475_list_python.txt |
Q:
To split on the basis of space and special character in python
v=vi nod-u
i want to split this string to obtain
l=[vi],[nod],[u]
l.split(" ") splits on the basis of space.
And i dont know the usage of the regular expression import functions properly.
Could anyone explain how to do that?
A:
Are you trying to spli... | To split on the basis of space and special character in python | v=vi nod-u
i want to split this string to obtain
l=[vi],[nod],[u]
l.split(" ") splits on the basis of space.
And i dont know the usage of the regular expression import functions properly.
Could anyone explain how to do that?
| [
"Are you trying to split the string to get words? If so, try the following:\n>>> import re\n>>> pattern = re.compile(r'\\W+')\n>>> pattern.split('vi nod-u')\n['vi', 'nod', 'u']\n\n"
] | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005453509_python_regex.txt |
Q:
Is there a "short_description" method for variables in Django?
I have a long variable name in one of my models "xxxx_xxxx_xx_xxxxxxxx" is there an equivilent of:
xxxx_xxxx_xx_xxxxxxxx.short_description = 'xxxx'
for variables or do I have to make a method to display that? I would like to not have to use a method b... | Is there a "short_description" method for variables in Django? | I have a long variable name in one of my models "xxxx_xxxx_xx_xxxxxxxx" is there an equivilent of:
xxxx_xxxx_xx_xxxxxxxx.short_description = 'xxxx'
for variables or do I have to make a method to display that? I would like to not have to use a method because I want to be able to sort by this variable in the Django admi... | [
"Look at the verbose field name option. It allows you use whatever name you like in the admin. There is also the verbose_name_plural for model names that have unusual plural construxions.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005453456_django_python.txt |
Q:
Set global template variable in template tag
I know that there are context processors that can do this, but I want to set global template variable in template tag. So far I tried this:
class SetNode(template.Node):
def __init__(self, key, nodelist):
self.key = key
self.nodelist = nodelist
... | Set global template variable in template tag | I know that there are context processors that can do this, but I want to set global template variable in template tag. So far I tried this:
class SetNode(template.Node):
def __init__(self, key, nodelist):
self.key = key
self.nodelist = nodelist
def render(self, context):
value = self.no... | [
"Here is an oldie-but-a-goodie: the {% expr %} tag. The code is self-explanatory.\nNote that using it (possibly) moves some of your business logic into your template, but sometimes that is OK.\n"
] | [
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0005452800_django_django_templates_python.txt |
Q:
Flask redirects on GAE
Hi I am using Flask (http://flask.pocoo.org/) on Google app engine. I have a following code
@app.route("/edit.html", methods=['GET', 'POST'])
def create():
if request.method == 'GET':
form = ImageForm()
return render_template('edit.html', title=u'Add', form=form)
if request.method... | Flask redirects on GAE | Hi I am using Flask (http://flask.pocoo.org/) on Google app engine. I have a following code
@app.route("/edit.html", methods=['GET', 'POST'])
def create():
if request.method == 'GET':
form = ImageForm()
return render_template('edit.html', title=u'Add', form=form)
if request.method == 'POST':
image = Imag... | [
"Something in your code is outputting text to the response before the Flask framework outputs its response (it looks like whatever it is is printing 'image') - most likely you have a print statement somewhere in your code. As a result, the headers flask tries to output get interpreted as part of the body of the res... | [
7
] | [] | [] | [
"flask",
"google_app_engine",
"python",
"redirect"
] | stackoverflow_0005452106_flask_google_app_engine_python_redirect.txt |
Q:
Python regex to match text in single quotes, ignoring escaped quotes (and tabs/newlines)
Given a file of text, where the character I want to match are delimited by single-quotes, but might have zero or one escaped single-quote, as well as zero or more tabs and newline characters (not escaped) - I want to match the... | Python regex to match text in single quotes, ignoring escaped quotes (and tabs/newlines) | Given a file of text, where the character I want to match are delimited by single-quotes, but might have zero or one escaped single-quote, as well as zero or more tabs and newline characters (not escaped) - I want to match the text only. Example:
menu_item = 'casserole';
menu_item = 'meat
loaf';
menu_item ... | [
"This tested script should do the trick:\nimport re\nre_sq_long = r\"\"\"\n # Match single quoted string with escaped stuff.\n ' # Opening literal quote\n ( # $1: Capture string contents\n [^'\\\\]* # Zero or more non-', non-backslash\n (?: # \"unroll-the-loop\"!\n... | [
14,
4,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005452655_python_regex.txt |
Q:
How to check user online with django and GAE?
I'm using Django with Google App Engine and I want to build a module for checking online/offline user .
But GAE don't support session so it's hard for me to find way to do it.
how can i resolve this problem? Any ideas would be appreciated, thanks.
A:
A session librar... | How to check user online with django and GAE? | I'm using Django with Google App Engine and I want to build a module for checking online/offline user .
But GAE don't support session so it's hard for me to find way to do it.
how can i resolve this problem? Any ideas would be appreciated, thanks.
| [
"A session library won't solve this, because HTTP is stateless. Using sessions, you can determine when someone last made a request, but that doesn't tell you if they're \"online\" or not - they could have immediately closed their browser tab, or they could leave it open for a week.\nIf you really, really need to do... | [
3
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0005450359_django_google_app_engine_python.txt |
Q:
override builtin "and"
can the primitive "and" be overridden?
for instance If I try to do something like this
class foo():
def __and__(self,other):
return "bar"
this gets outputted
>> foo() and 4
4
>> foo().__and__(4)
'bar'
my intuition is that the built in and cannot be overridden and shouldn't be... | override builtin "and" | can the primitive "and" be overridden?
for instance If I try to do something like this
class foo():
def __and__(self,other):
return "bar"
this gets outputted
>> foo() and 4
4
>> foo().__and__(4)
'bar'
my intuition is that the built in and cannot be overridden and shouldn't be overridden to not cause con... | [
"__and__ overrides the bitwise operator &, not the logic operator.\nTo give your class boolean logic handling, define a __nonzero__ method: http://docs.python.org/reference/datamodel.html#object.__nonzero__\n",
"The and operator cannot be overridden, since it doesn't always evaluate both of its operands. There i... | [
7,
2,
1
] | [] | [] | [
"overriding",
"python"
] | stackoverflow_0005453546_overriding_python.txt |
Q:
why doesn't the Python property set the attribute value
Consider this following code:
class Class:
def __init__(self):
self._value = False
def GetValue(self):
return self._value
def SetValue(self, val):
self._value = val
Value = property(GetValue, SetValue)
c = Class()
prin... | why doesn't the Python property set the attribute value | Consider this following code:
class Class:
def __init__(self):
self._value = False
def GetValue(self):
return self._value
def SetValue(self, val):
self._value = val
Value = property(GetValue, SetValue)
c = Class()
print c._value, c.Value
False False
c.Value = True
print c._value... | [
"You need to use a new style class (inherit from object) for property to work\nclass Class(object):\n ...\n\n",
"If you only want to access your value as a property, it's much simpler to just use an attribute:\nclass Class(object):\n def __init__(self):\n self.value = False\n\nc = Class()\nc.value ... | [
9,
1
] | [] | [] | [
"properties",
"python",
"setter"
] | stackoverflow_0005451956_properties_python_setter.txt |
Q:
How to summarise data in Google AppEngine
I'm trying to implement a summary view on to a large(ish) data set using AppEngine.
My model looks something like:
def TxRecord(db.Model):
expense_type = db.StringProperty()
amount = db.IntegerProperty()
def ExpenseType(db.Model):
name = db.StringProperty()
... | How to summarise data in Google AppEngine | I'm trying to implement a summary view on to a large(ish) data set using AppEngine.
My model looks something like:
def TxRecord(db.Model):
expense_type = db.StringProperty()
amount = db.IntegerProperty()
def ExpenseType(db.Model):
name = db.StringProperty()
total = db.IntegerProperty()
My datastore co... | [
"Using the MapReduce framework is a good idea. You could use more than one shard if you utilize the counters provided by the MapReduce framework. So instead of modifying the datastore each time, you could do something like this:\nyield op.counters.Increment(\"total_<expense_type_name>\", rec.amount)\n\nAfter the ... | [
3,
3,
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"mapreduce",
"python"
] | stackoverflow_0005448221_google_app_engine_google_cloud_datastore_mapreduce_python.txt |
Q:
Create a tuple from a string and a list of strings
I need to combine a string along with a list of strings into a tuple so I can use it as a dictionary key. This is going to be in an inner loop so speed is important.
The list will be small (usually 1, but occasionally 2 or 3 items).
What is the fastest way to do ... | Create a tuple from a string and a list of strings | I need to combine a string along with a list of strings into a tuple so I can use it as a dictionary key. This is going to be in an inner loop so speed is important.
The list will be small (usually 1, but occasionally 2 or 3 items).
What is the fastest way to do this?
Before:
my_string == "foo"
my_list == ["bar", "baz... | [
"I can't speak for performance, but this is definitely the simplest I can think of:\nmy_tuple = tuple([my_string] + my_list)\n\n",
"The straightforward way is simply my_tuple = tuple( my_list + [my_string] ). I would certainly start with that and see if the performance is acceptable before trying to figure out an... | [
21,
1
] | [
"i think this way is better:\nmy_list = my_list.insert(0,my_string)\nmy_tuple = tuple(my_list)\n\n"
] | [
-3
] | [
"list",
"python",
"string",
"tuples"
] | stackoverflow_0005453979_list_python_string_tuples.txt |
Q:
Arbitrary length bytes to int builtin in Python
I'm looking for a function that takes an arbitrary length bytes object, and converts it to an int. Obviously endianness is a required parameter to this function.
I'm certain I encountered a builtin on either bytes or int, but can't find it anymore. There are plenty o... | Arbitrary length bytes to int builtin in Python | I'm looking for a function that takes an arbitrary length bytes object, and converts it to an int. Obviously endianness is a required parameter to this function.
I'm certain I encountered a builtin on either bytes or int, but can't find it anymore. There are plenty of answers on similar questions involving use of struc... | [
"Since 3.2:\n>>> int.from_bytes(b'\\xFF\\x00','little')\n255\n>>> int.from_bytes(b'\\xFF\\x00','big')\n65280\n\n"
] | [
17
] | [] | [] | [
"byte",
"endianness",
"int",
"python",
"python_3.x"
] | stackoverflow_0005454120_byte_endianness_int_python_python_3.x.txt |
Q:
html appengine redirect URL
I want to redirect a user to the next URL after authenticating on a third party web page. In the redirect URL I want it to contain some info about the user, i.e. session id. For example my redirect URL will be www.z.appspot.com/?session=x/ when the user returns to my page I want to pars... | html appengine redirect URL | I want to redirect a user to the next URL after authenticating on a third party web page. In the redirect URL I want it to contain some info about the user, i.e. session id. For example my redirect URL will be www.z.appspot.com/?session=x/ when the user returns to my page I want to parse some of their details from the ... | [
"You want a module called cgi, and a function called FieldStorage. Do it like this:\nimport cgi\n\nurl_parms = cgi.FieldStorage()\nsession = url_parms.getvalue(\"session\",\"default\")\n\nYou can do this for any of the URL parameters. Replace \"default\" with whatever you want the default value to be (like an emp... | [
1,
1,
0
] | [] | [] | [
"google_app_engine",
"html",
"python",
"redirect",
"url"
] | stackoverflow_0005444240_google_app_engine_html_python_redirect_url.txt |
Q:
Using response.out.write from within an included file in Google App Engine
I think this is quite an easy question to answer, I just haven't been able to find anywhere detailing how to do it.
I'm developing a GAE app.
In my main file I have a few request handlers, for example:
class Query(webapp.RequestHandler):
... | Using response.out.write from within an included file in Google App Engine | I think this is quite an easy question to answer, I just haven't been able to find anywhere detailing how to do it.
I'm developing a GAE app.
In my main file I have a few request handlers, for example:
class Query(webapp.RequestHandler):
def post(self):
queryDOI = cgi.escape(self.request.get('doiortitle'))
... | [
"A much better, more modular approach, is to have your queryCosine.cosine function throw an exception if something goes wrong. Then, your handler method can output the appropriate response depending on the return value or exception. This avoids unduly coupling the code that calculates whatever it is you're calculat... | [
2,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005444155_google_app_engine_python.txt |
Q:
Gql get all children of ancestor without the ancestor itself
I'm trying to build a forum like platform on GAE.
I must mention first: I'm a bit new to GAE.
I want to pull all replies to a specific post.
So far the structure looks like so:
- Forum
--- Post
----- Reply ( = Post with Post as a parent )
Replies are j... | Gql get all children of ancestor without the ancestor itself | I'm trying to build a forum like platform on GAE.
I must mention first: I'm a bit new to GAE.
I want to pull all replies to a specific post.
So far the structure looks like so:
- Forum
--- Post
----- Reply ( = Post with Post as a parent )
Replies are just posts with post as their parent(instead of the forum as a pare... | [
"If you have the parent key you do not have to fetch the parent post entity. If you have a string version of the parent post's key:\nparent_post = db.Key(string_version_of_the_key)\nreplies = Post.all().ancestor(parent_post).fetch(num_to_fetch)\n\nIf you have the parent post's key id or name:\nparent_post = db.Key... | [
2,
2,
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0005443499_google_app_engine_google_cloud_datastore_python.txt |
Q:
App engine model, get_or_insert question w.r.t primary key and composite keys
A] Summary of the problem:
I Have 1 to many hierarchical relationships between models
Country (1) --> City (Many)
City (1) --> Status (Many)
So, there can only be one unique country, a country can only have one unique city, and a city c... | App engine model, get_or_insert question w.r.t primary key and composite keys | A] Summary of the problem:
I Have 1 to many hierarchical relationships between models
Country (1) --> City (Many)
City (1) --> Status (Many)
So, there can only be one unique country, a country can only have one unique city, and a city could have many statuses
I am planning to use "get_or_insert" method to make sure th... | [
"To address your questions in order:\n\n1] From the google search, it appears\n \"get_or_insert\" requires a key, In my\n case in the \"UserReportedCountry\"\n model, i want the name of the country\n to be the primary key and in the\n \"UserReportedCity\" model, i want the\n combination of country name + city... | [
3,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005442464_google_app_engine_python.txt |
Q:
Writing a random-generating quiz, need to recall the object that was randomly generated
I'm very new to python, so I'm sure my code is prodigiously inefficient, etc, but I'm just feeling my way around and learning by doing at the moment, so excuse my general ignorance.
My quiz currently takes a series of quotes an... | Writing a random-generating quiz, need to recall the object that was randomly generated | I'm very new to python, so I'm sure my code is prodigiously inefficient, etc, but I'm just feeling my way around and learning by doing at the moment, so excuse my general ignorance.
My quiz currently takes a series of quotes and randomly prints the first 20 characters of them (via slice), the idea being that the quizee... | [
"You can use quote itself:\nwhile control:\n quote = random.choice([SonnetSeventeen,SonnetEighteen,JCIIiii34,JCIii101])\n print quote[:20]\n var = raw_input (\"\\n\")\n if var == \"exit\":\n control = False\n elif var == \"next\":\n print \"\\n\"\n control = True\n elif var ==... | [
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0005452797_python.txt |
Q:
why i cant login this site using python in a post method
this is my code to login a site using python :
import urllib2, cookielib
cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
content = urllib2.u... | why i cant login this site using python in a post method | this is my code to login a site using python :
import urllib2, cookielib
cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
content = urllib2.urlopen('http://192.168.1.200/order/index.php?op=Login&ac=login... | [
"You are making a GET request. To make a POST request, use:\ncontent = urllib2.urlopen(\n 'http://192.168.1.200/order/index.php\",\n 'op=Login&ac=login&userName=%E8%B5%B5%E6%B1%9F%E6%98%8E&userPwd=123').read()\n\nThe urlopen method sends a POST request if data (second argument) is passed to it.\n",
"Try usi... | [
3,
0
] | [] | [] | [
"authentication",
"cookielib",
"python",
"urllib2"
] | stackoverflow_0005453791_authentication_cookielib_python_urllib2.txt |
Q:
x/y axis graph tool [text file input]
Is there a free tool I can download that will display a graph given a set of x,y coordinates in a text file? Or is there a python module I could use that would give me a quick and dirty view of a graph? Excel is not an option because I do not have it. I would prefer somethi... | x/y axis graph tool [text file input] | Is there a free tool I can download that will display a graph given a set of x,y coordinates in a text file? Or is there a python module I could use that would give me a quick and dirty view of a graph? Excel is not an option because I do not have it. I would prefer something light weight.
| [
"You can try gnuplot.\nIf you want a python solution, use matplotlib. It is a bit heavy weight, but once setup, it is very simple to use.\n",
"If you want something very quick and dirty, you could try ascii-plotter:\nhttp://www.algorithm.co.il/blogs/ascii-plotter/\nOtherwise I would go with matplotlib\nhttp://mat... | [
2,
1
] | [] | [] | [
"graph",
"python"
] | stackoverflow_0005454699_graph_python.txt |
Q:
Opening file - Performing a function
I was wondering if someone could give me a direction on how to give functions to a file... This is a bit hard to explain, so I'll try my best.
Let's say I have an application (using wxPython) and let's say that I have a file. Now this file is assigned to open with the applicati... | Opening file - Performing a function | I was wondering if someone could give me a direction on how to give functions to a file... This is a bit hard to explain, so I'll try my best.
Let's say I have an application (using wxPython) and let's say that I have a file. Now this file is assigned to open with the application. So, I double-click the file and it ope... | [
"AFAIK most platforms just call the helper app with the file you clicked on as an argument, so your filepath will be in sys.argv[1]\n",
"I think what he wants to do is associate a file extension to his application so when he opens the file by double clicking it, it sends the contents of the file to his app; in th... | [
2,
1
] | [] | [] | [
"file",
"python",
"wxpython"
] | stackoverflow_0005453782_file_python_wxpython.txt |
Q:
SQLAlchemy pool.addListener Error
I'm creating a pylons app and I keep getting an error when trying to start the app with paster. I've searched for answers on google and keep coming up with nothing. Anyone have any ideas?
Traceback (most recent call last):
File "/opt/python2.7/bin/paster", line 8, in <module>
... | SQLAlchemy pool.addListener Error | I'm creating a pylons app and I keep getting an error when trying to start the app with paster. I've searched for answers on google and keep coming up with nothing. Anyone have any ideas?
Traceback (most recent call last):
File "/opt/python2.7/bin/paster", line 8, in <module>
load_entry_point('PasteScript==1.7.3', ... | [
"I figured it out, the book i was using said to use\n sqlalchemy.pool = 3600\nBut apparently it's supposed to be\n sqlalchemy.pool_recycle = 3600 \n"
] | [
0
] | [] | [] | [
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0005446111_pylons_python_sqlalchemy.txt |
Q:
How do I parse a file and substitute the environment variables with values in Python
I have a text file (lets call it file1.txt), it contains the following lines:
"read model $path_1"
How do I replace the value of path_1 variable in this text file and write it to another file (lets call it file2.txt) with same con... | How do I parse a file and substitute the environment variables with values in Python | I have a text file (lets call it file1.txt), it contains the following lines:
"read model $path_1"
How do I replace the value of path_1 variable in this text file and write it to another file (lets call it file2.txt) with same contents but $path_1 variable expanded. My file2.txt should contain something like the follow... | [
"os.path.expandvars()\n",
"string.Template \n>>> from string import Template\n>>> s = Template('$who likes $what')\n>>> s.substitute(who='tim', what='kung pao')\n'tim likes kung pao'\n\n"
] | [
4,
2
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0005455000_python_shell.txt |
Q:
What's the best facebook python-sdk fork?
It looks like development has stalled on the official python-sdk. There are 139 forks on github. What's the most mature or best for using with Django.
EDIT:
By "official" I meant http://github.com/facebook/python-sdk. I'm reluctant to use it because it has a number of p... | What's the best facebook python-sdk fork? | It looks like development has stalled on the official python-sdk. There are 139 forks on github. What's the most mature or best for using with Django.
EDIT:
By "official" I meant http://github.com/facebook/python-sdk. I'm reluctant to use it because it has a number of pull requests that have been open for quite a wh... | [
"Take a look at django-la-facebook. It was started to bridge the gap between all of the incomplete django facebook integration layers. It is also worked on by Jacob Burch of the ladjango meetup group fame, and Danny Greenfield of the django consultancy, Cartwheel Web (no I don't work for them).\n"
] | [
1
] | [
"https://github.com/facebook/python-sdk/ this is the one facebook recommends... but if I were you I would just use graph API for python, since there is no complete solution\n"
] | [
-2
] | [
"django",
"facebook",
"python"
] | stackoverflow_0005453518_django_facebook_python.txt |
Q:
Python integer testing
def isinteger(x):
while x > 0.0:
x = x - 1.0
if x < 0.0:
return 0.0
elif x == 0:
return 1.0
d = input('')
print isinteger(d)
The code is somewhat self explanatory. I'm using it for a fractran interpreter. Here is my problem: I input a fraction, such as 2... | Python integer testing | def isinteger(x):
while x > 0.0:
x = x - 1.0
if x < 0.0:
return 0.0
elif x == 0:
return 1.0
d = input('')
print isinteger(d)
The code is somewhat self explanatory. I'm using it for a fractran interpreter. Here is my problem: I input a fraction, such as 22/7, and I get a 1 as my out... | [
"The input function evaluates your 22/7 exactly the same way as if it had been entered into the python interpreter. Since both 22 and 7 are integers you get an integer division with a result of 3. If you want float division, enter either 22.0/7 or 22/7.0 both of which result in 3.146....\n",
"If you're using pyth... | [
5,
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005454677_python.txt |
Q:
Can modulus/modulo work on big numbers in python?
Using mod on a big number, such as 600851475143, does not give a correct answer, anyone know why?
print 600851475143 / 2.0
print 600851475143 % 2.0
print 4 / 2.0
print 4 % 2.0
600851475143 / 2.0 = 300425737572.0
600851475143 % 2.0 = 1.0
4 / 2.0 = 2.0
4 % ... | Can modulus/modulo work on big numbers in python? | Using mod on a big number, such as 600851475143, does not give a correct answer, anyone know why?
print 600851475143 / 2.0
print 600851475143 % 2.0
print 4 / 2.0
print 4 % 2.0
600851475143 / 2.0 = 300425737572.0
600851475143 % 2.0 = 1.0
4 / 2.0 = 2.0
4 % 2.0 = 0.0
I was working on creating my own prime n... | [
">>> print 600851475143 / 2\n300425737571\n>>> print 600851475143 % 2\n1\n>>> 4 / 2\n2\n>>> 4 % 2\n0\n\nApart from that: your issue has nothing to do with big numbers - it's only about integer operations in Python.\n"
] | [
0
] | [] | [] | [
"modulo",
"python"
] | stackoverflow_0005455355_modulo_python.txt |
Q:
Packaging javascript and css files in a django app for reuse, install via pip?
I'm building a django app that requires a javascript file for some ajaxy bits. I would like to package this app so that it can be installed by via easy_install or pip with as little fuss as possible.
But I'm not sure what where to put ... | Packaging javascript and css files in a django app for reuse, install via pip? | I'm building a django app that requires a javascript file for some ajaxy bits. I would like to package this app so that it can be installed by via easy_install or pip with as little fuss as possible.
But I'm not sure what where to put the static media, particularly the javascript file. On my machine, I have the stati... | [
"I think the staticfiles app is exactly what you're looking for, unfortunately it's new in Django 1.3. Are you able to upgrade?\nFrom the docs:\n\ndjango.contrib.staticfiles collects static files from each of your applications (and any other places you specify) into a single location that can easily be served in pr... | [
3
] | [] | [] | [
"django",
"javascript",
"pip",
"python"
] | stackoverflow_0005455053_django_javascript_pip_python.txt |
Q:
Python subprocess never exits and keeps giving empty strings in output
So, I have been facing a problem with using subprocess for a python app i am writing. To illustrate the problem, I wrote this small script that replicates my problem pretty well.
from __future__ import print_function
import subprocess as sp
fr... | Python subprocess never exits and keeps giving empty strings in output | So, I have been facing a problem with using subprocess for a python app i am writing. To illustrate the problem, I wrote this small script that replicates my problem pretty well.
from __future__ import print_function
import subprocess as sp
from select import select
p = sp.Popen(['ls'], stdout=sp.PIPE, stderr=sp.PIPE... | [
"while p.returncode is None or p.stdout.closed or p.stderr.closed:\n\nloops while any of the conditions is true. You probably meant to check just returncode (and poll in every iteration). \n"
] | [
1
] | [] | [] | [
"python",
"stderr",
"stdout",
"subprocess"
] | stackoverflow_0005455764_python_stderr_stdout_subprocess.txt |
Q:
How does the SAX parser process characters?
I wrote a little code to parse a XML file, and want to print it's characters, but each character seems invoke characters() callback function three times.
code:
def characters(self,chrs):
if self.flag==1:
self.outfile.write(chrs+'\n')
xml ... | How does the SAX parser process characters? | I wrote a little code to parse a XML file, and want to print it's characters, but each character seems invoke characters() callback function three times.
code:
def characters(self,chrs):
if self.flag==1:
self.outfile.write(chrs+'\n')
xml file:
<e1>9308</e1>
<e2>865</e2>
and the output ... | [
"The example XML you posted is obviously not the full XML, because that would be malformed (and the SAX parser would tell you that instead of producing your output). So I'll assume that there's more to the XML than you showed us.\nYou need to be aware that every whitespace between any XML elements is character data... | [
4,
0,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0005388626_python_xml.txt |
Q:
Exit code when python script has unhandled exception
I need a method to run a python script file, and if the script fails with an unhandled exception python should exit with a non-zero exit code. My first try was something like this:
import sys
if __name__ == '__main__':
try:
import <unknown script>
... | Exit code when python script has unhandled exception | I need a method to run a python script file, and if the script fails with an unhandled exception python should exit with a non-zero exit code. My first try was something like this:
import sys
if __name__ == '__main__':
try:
import <unknown script>
except:
sys.exit(-1)
But it breaks a lot of scr... | [
"Python already does what you're asking:\n$ python -c \"raise RuntimeError()\"\nTraceback (most recent call last):\n File \"<string>\", line 1, in <module>\nRuntimeError\n$ echo $?\n1\n\nAfter some edits from the OP, perhaps you want:\nimport subprocess\n\nproc = subprocess.Popen(['/usr/bin/python', 'script-name']... | [
18,
2
] | [] | [] | [
"exit_code",
"python"
] | stackoverflow_0005456157_exit_code_python.txt |
Q:
What is meant with a buffer in python
In the python documentation for struct, the word buffer is used without explanation:
http://docs.python.org/library/struct.html
struct.unpack_from(fmt, buffer[,offset=0])
Unpack the buffer
according to the given format. The
result is a tuple even if it contains
exactly ... | What is meant with a buffer in python | In the python documentation for struct, the word buffer is used without explanation:
http://docs.python.org/library/struct.html
struct.unpack_from(fmt, buffer[,offset=0])
Unpack the buffer
according to the given format. The
result is a tuple even if it contains
exactly one item. The buffer must
contain at leas... | [
"It's a memory buffer: in Python 2, a string (str), in Python 3, a binary string (bytes), or alternatively an object constructed with buffer.\n"
] | [
4
] | [] | [] | [
"buffer",
"io",
"python"
] | stackoverflow_0005456730_buffer_io_python.txt |
Q:
python wmv stream download
Given a wmv file that is streaming online. The file is around 10kb as it does not have any video. If i click on the file it opens windows media player which then connects to the net. Windows media player starts to cache the file and then play the video for me.
Instead I would like my py... | python wmv stream download | Given a wmv file that is streaming online. The file is around 10kb as it does not have any video. If i click on the file it opens windows media player which then connects to the net. Windows media player starts to cache the file and then play the video for me.
Instead I would like my python program to open the file. G... | [
"I was facing the same issue and looked into the Python VLC bindings but because I was pressed for time and there was a lack of examples using the bindings, I went for another approach.\nThe vlc command line is extremely powerful. Using subprocess.call i did direct calls to the vlc command line. \nThis is the forma... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004510859_python.txt |
Q:
How do I share a python script's imports with another script?
Let's say I have a script1.py with imports.
How can I share script1.py imports with script2.py? without copy and pasting.
A:
Your application should consist of many modules that are logically independent. It makes your program easier to read, debug et... | How do I share a python script's imports with another script? | Let's say I have a script1.py with imports.
How can I share script1.py imports with script2.py? without copy and pasting.
| [
"Your application should consist of many modules that are logically independent. It makes your program easier to read, debug etc. Just like Python's standard library is divided into many modules (as you said - you have to import things from many of them). \nThe more modules you have, the fewer imports you need to d... | [
2
] | [
"though I agree with the comments... you can have a module that defines the all attribute\nfrom crazyapp import all, my, imports\n\n__all__ =['all', 'my', 'imports']\n\nthen just call to import the modules.\nfrom allmyimports import *\nBut fix things if you have that many.... 200? Think of a module as something tha... | [
-1
] | [
"django",
"import",
"oop",
"python"
] | stackoverflow_0005456923_django_import_oop_python.txt |
Q:
Cherry Py - Return output as XML in Python
My intention is to deploy a web service in Google App Engine. I am using CherryPy as I found it very easy to understand.
import sys
sys.path.insert(0,'cherrypy.zip')
import cherrypy
from cherrypy import expose
class Converter:
@expose
def index(self):
re... | Cherry Py - Return output as XML in Python | My intention is to deploy a web service in Google App Engine. I am using CherryPy as I found it very easy to understand.
import sys
sys.path.insert(0,'cherrypy.zip')
import cherrypy
from cherrypy import expose
class Converter:
@expose
def index(self):
return "Hello World!"
@expose
def fahr_to... | [
"I had a similar issue. My solution was to use xml elementtree. It was something like\n....\n#elementtree is stored in weird places... This catches most of em\ntry:\n import xml.etree.ElementTree as ET # in python >=2.5\nexcept ImportError:\n try:\n import cElementTree as ET # effbot's C module\n ... | [
3
] | [] | [] | [
"cherrypy",
"python",
"web_services",
"xml"
] | stackoverflow_0005456195_cherrypy_python_web_services_xml.txt |
Q:
Better algorithm to riffle shuffle (or interleave) multiple lists of varying lengths
I like to watch my favorite TV shows on the go. I have all episodes of each show I'm following in my playlist. Not all shows consist of the same number of episodes. Unlike some who prefer marathons, I like to interleave episode... | Better algorithm to riffle shuffle (or interleave) multiple lists of varying lengths | I like to watch my favorite TV shows on the go. I have all episodes of each show I'm following in my playlist. Not all shows consist of the same number of episodes. Unlike some who prefer marathons, I like to interleave episodes of one show with those of another.
For example, if I have a show called ABC with 2 episo... | [
"A deterministic solution (ie not random)\nSort your shows by decreasing number of episodes. \nSelect the biggest and arrange a matrix with the number of columns corresponding to the number of episodes of this one, filled in the following way: \nA A A A A A <- First show consist of 6 episodes\nB B ... | [
5,
1,
0,
0
] | [] | [] | [
"algorithm",
"language_agnostic",
"python",
"shuffle"
] | stackoverflow_0005455693_algorithm_language_agnostic_python_shuffle.txt |
Q:
How to embed and listen data over icmp in order to tunnel connection with using python
i am trying to code one tunnel tool but i could not receive packet from icmp. I uses socket library, is there any one pylibnet or pynet library
A:
You might want to try scapy. On the other hand, have you seen the other impleme... | How to embed and listen data over icmp in order to tunnel connection with using python | i am trying to code one tunnel tool but i could not receive packet from icmp. I uses socket library, is there any one pylibnet or pynet library
| [
"You might want to try scapy. On the other hand, have you seen the other implementations?\n"
] | [
0
] | [] | [] | [
"icmp",
"libnet",
"python",
"sockets",
"tunneling"
] | stackoverflow_0005454229_icmp_libnet_python_sockets_tunneling.txt |
Q:
Dynamic column_property with SQLAlchemy
I've got some SA models and need some trick :
class Entry(Base):
__tablename__ = 'entry'
id = Column(Integer, primary_key=True)
title = Column(Unicode(255))
author_id = Column(Integer, ForeignKey('user.id'))
date = Column(DateTime)
content = Column(Te... | Dynamic column_property with SQLAlchemy | I've got some SA models and need some trick :
class Entry(Base):
__tablename__ = 'entry'
id = Column(Integer, primary_key=True)
title = Column(Unicode(255))
author_id = Column(Integer, ForeignKey('user.id'))
date = Column(DateTime)
content = Column(Text)
author = relationship('User', backref... | [
"Adding property is a good way to get some database state related to the object. But with external criterion parameter the count won't be just a state, but a function. Representing such data as object property won't be good. So query for additional data directly (counting antries newer than start_date in all exampl... | [
8
] | [] | [] | [
"count",
"python",
"sqlalchemy"
] | stackoverflow_0005443529_count_python_sqlalchemy.txt |
Q:
Internal Server Error - Python CGI
I am currently writing a CGI script that has an end goal of running a java program and then redirecting to a different page. However, the CGI causes a 500 internal server error when I call try to run the java program. I've tried os.system("[command]") and call(["command"]) and ... | Internal Server Error - Python CGI | I am currently writing a CGI script that has an end goal of running a java program and then redirecting to a different page. However, the CGI causes a 500 internal server error when I call try to run the java program. I've tried os.system("[command]") and call(["command"]) and subprocess.Popen("command") and all thre... | [
"Have you tried:\nimport cgitb\n\ncgitb.enable()\n\nto get a more meaningful error - python error message in your browser\nor\nrunning your script from the command line on your server to see if python is returning an error, and if so, if it helps to diagnose the problem?\nor\nprinting your java call as html output ... | [
1,
1
] | [] | [] | [
"cgi",
"internal_server_error",
"java",
"popen",
"python"
] | stackoverflow_0005456412_cgi_internal_server_error_java_popen_python.txt |
Q:
XML-RPC connection problem
I have a simple xml rpc server running on a localhost. The server has the following address:
servAddr = ("localhost", 8080). When I run the client on a different machine I get a connection refused error. However, when i change the line
servAddr = ("localhost", 8080)
to
servAddr = ("myho... | XML-RPC connection problem | I have a simple xml rpc server running on a localhost. The server has the following address:
servAddr = ("localhost", 8080). When I run the client on a different machine I get a connection refused error. However, when i change the line
servAddr = ("localhost", 8080)
to
servAddr = ("myhostname", 8080)
everything works... | [
"'localhost' refers to your local machine. It's an alias to 127.0.0.1 ip address. It only works when the server and the client are running on the same machine.\nWhen you try to put the client on an other machine, localhost refer to the machine of the client --> no the machine of the server !\nMore information about... | [
0,
0
] | [] | [] | [
"python",
"xml_rpc"
] | stackoverflow_0005457488_python_xml_rpc.txt |
Q:
Django i18n and python locales (and dates)
I've been playing with Django's i18n system and it seems to be mostly working. However, dates in model code seem to be causing a problem.
I use datetime.strftime to populate a few CHOICES tuples which are then used in forms.
From what I understood, django will set the lo... | Django i18n and python locales (and dates) | I've been playing with Django's i18n system and it seems to be mostly working. However, dates in model code seem to be causing a problem.
I use datetime.strftime to populate a few CHOICES tuples which are then used in forms.
From what I understood, django will set the locale to the user's choice so that datetime.strft... | [
"Django does not set locale for translation, just loads translation catalog. To get desired effect you have either set locale (which is not a good option since it works process-wide) or use specialized library. I recommend Babel which has nice Django integration.\n",
"I've recently faced similar problem but manag... | [
3,
1
] | [] | [] | [
"django",
"internationalization",
"python"
] | stackoverflow_0001318744_django_internationalization_python.txt |
Q:
What determines the applicative log file location in Apache/Django?
(Cross posted to Server Fault some time ago)
I have a django app running on Apache/ubuntu, and I have evidently misconfigured it.
When I start apache, I'm getting this error in the apache log:
...
IOError: [Errno 2] No such file or directory: '/... | What determines the applicative log file location in Apache/Django? | (Cross posted to Server Fault some time ago)
I have a django app running on Apache/ubuntu, and I have evidently misconfigured it.
When I start apache, I'm getting this error in the apache log:
...
IOError: [Errno 2] No such file or directory: '/home/osqa/sites/log/django.osqa.log'
Now, my site is supposed to be runn... | [
"My hunch is that it's something in your apache2 config. Go to sites-available/your-site.com.conf, and look in its file. Perhaps you'll find that it is logging things? \n",
"The following lines in your httpd.conf file is what is causing your problem:\nCustomLog ${APACHE_LOG_DIR}/beta-meta-d3c.access.log common\nE... | [
1,
1
] | [] | [] | [
"apache",
"django",
"python",
"ubuntu"
] | stackoverflow_0005452931_apache_django_python_ubuntu.txt |
Q:
django + orbited/stomp
I'm using django server together with orbited/stomp server to write something like chat. Assume that some users are connected to orbited. When one of them disconnects from orbited, how can I notify the rest? I mean I've tried the following code (javascript on the client side - maybe this is ... | django + orbited/stomp | I'm using django server together with orbited/stomp server to write something like chat. Assume that some users are connected to orbited. When one of them disconnects from orbited, how can I notify the rest? I mean I've tried the following code (javascript on the client side - maybe this is already wrong, server should... | [
"It seems that orbited is not suited for this kind of things (I talked with orbited creator). I switched to hookbox and it works fine. \n"
] | [
0
] | [] | [] | [
"chat",
"django",
"orbited",
"python",
"stomp"
] | stackoverflow_0005384734_chat_django_orbited_python_stomp.txt |
Q:
Temporal interpolation in NumPy/matplotlib
When creating animations in ParaView there is a function to temporally interpolate input files. When generating an animation via multiple contour plots in NumPy/matplotlib is there a similar function which can help make the animation smoother or do I have to temporal inte... | Temporal interpolation in NumPy/matplotlib | When creating animations in ParaView there is a function to temporally interpolate input files. When generating an animation via multiple contour plots in NumPy/matplotlib is there a similar function which can help make the animation smoother or do I have to temporal interpolate the data manually?
| [
"VTK's TemporalInterpolator is for interpolating data on unstructured spacial meshes between time steps. You have your data in two-dimensional NumPy arrays, and the task of interpolating it is far easier. For this reason, there is no dedicated function for this, and you'll have to do it manually.\nLet's assume a0... | [
2
] | [] | [] | [
"matplotlib",
"numpy",
"paraview",
"python"
] | stackoverflow_0005448322_matplotlib_numpy_paraview_python.txt |
Q:
Python IDE and gathering runtime statistics (variable types and other)
It occured to me after reading this blog post and watching related video: http://steve-yegge.blogspot.com/2008/05/dynamic-languages-strike-back.html
Is there any Python IDE that gathers Python program runtime statistics and uses it to provide b... | Python IDE and gathering runtime statistics (variable types and other) | It occured to me after reading this blog post and watching related video: http://steve-yegge.blogspot.com/2008/05/dynamic-languages-strike-back.html
Is there any Python IDE that gathers Python program runtime statistics and uses it to provide better code completion, variable type determining etc.?
Or, if not IDE, is th... | [
"AFAIK there is no tool that is able to do all this magic at once, but...\n\neclipse can do some inference about basic types, e.g. classes and instance members, functions, can do some autocompletion\nsemantic & emacs also does it\npywin, IDLE and pycrust introspect imported modules, also providing autocompletion\np... | [
0
] | [] | [] | [
"ide",
"python",
"runtime",
"statistics",
"variable_types"
] | stackoverflow_0005435463_ide_python_runtime_statistics_variable_types.txt |
Q:
how to switch into a single database among multiple databases at run time in django?
how to switch into a single database among multiple databases at run time in django?
A:
which version of Django are you using?
1.2 supports multiple databases..for further info you can go here
As for your question you can go her... | how to switch into a single database among multiple databases at run time in django? | how to switch into a single database among multiple databases at run time in django?
| [
"which version of Django are you using?\n1.2 supports multiple databases..for further info you can go here\nAs for your question you can go here\neg.\nAuthor.objects.using('db_name').all()\n\n"
] | [
5
] | [] | [] | [
"database",
"django",
"python"
] | stackoverflow_0005458386_database_django_python.txt |
Q:
Python concatenation of variable and string
for i in range (0,len(list4)):
ws.write(1, 0, datetime.now(), style1)
ws.write(2, 1, 1)
ws.write(2, 2, xlwt.Formula("A3+B3"))
wb.save('example.xls')
how do i generalize (A3+B3) ?
'"A" + i' + '"B" + i'
Is this correct???
A:
'A%(row)d+B%(row)d' % {'row': 3}
... | Python concatenation of variable and string | for i in range (0,len(list4)):
ws.write(1, 0, datetime.now(), style1)
ws.write(2, 1, 1)
ws.write(2, 2, xlwt.Formula("A3+B3"))
wb.save('example.xls')
how do i generalize (A3+B3) ?
'"A" + i' + '"B" + i'
Is this correct???
| [
"'A%(row)d+B%(row)d' % {'row': 3}\n\nor\n'A{0}+B{0}'.format(3)\n\n",
"You need:\nws.write(2, 2, xlwt.Formula(\"A\" + str(i) + \"+B\" + str(i)))\n\nOr more idiomatically:\nws.write(2, 2, xlwt.Formula(\"A%d+B%d\" % (i,i)))\n\n"
] | [
7,
3
] | [] | [] | [
"concatenation",
"python"
] | stackoverflow_0005458468_concatenation_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.