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:
trying to implement sudoku solver brute foce algorithm
I've been trying to implement the brute force part of this http://www.garshol.priv.no/blog/178.html in my program here: http://paste.pound-python.org/show/7107/, but I'm relatively inexperience and I've hit a wall. I understand generally whats going on in the ... | trying to implement sudoku solver brute foce algorithm | I've been trying to implement the brute force part of this http://www.garshol.priv.no/blog/178.html in my program here: http://paste.pound-python.org/show/7107/, but I'm relatively inexperience and I've hit a wall. I understand generally whats going on in the algorithm but I can't figure out where I'm going wrong.
| [
"Check out Peter Norvig's python sudoku solution. It's both more elegant and clearer imho.\nhttp://norvig.com/sudoku.html\n",
"maybe you want to try implimenting Dancing Links algorithm\nmore information about Dancing Links\n"
] | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0006110585_python.txt |
Q:
How to access DirectSound device info from Python?
I've found this information on SO about how to enumerate the sound device info on with .NET, but I don't really know how to use this information with Python. As you can probably tell, I have almost zero experience with Windows API programming.
I can figure out ho... | How to access DirectSound device info from Python? | I've found this information on SO about how to enumerate the sound device info on with .NET, but I don't really know how to use this information with Python. As you can probably tell, I have almost zero experience with Windows API programming.
I can figure out how to get basic information via WMI, but I need more info... | [
"For a \"poor man's\" .NET library access, take a look at \"Python for .NET\".\nHowever, it is potentially easier to access DirectSound devices with IronPython due to its .NET bindings via its clr library.\nTips from IronPython cookbook:\nPlaying an MP3 song with DirectX:\nimport clr\nclr.AddReference('Microsoft.Di... | [
1
] | [] | [] | [
"ctypes",
"directx",
"python"
] | stackoverflow_0006119587_ctypes_directx_python.txt |
Q:
A better code to see if python.email.message.Message part is an attachment
I have an instance of a python.email.message.Message
with 3 parts, but only one is an attachment
assuming msg is the Message, the following code:
for part in msg.walk():
print part.get_param('attachment', 'noattachment', 'Content-Dispos... | A better code to see if python.email.message.Message part is an attachment | I have an instance of a python.email.message.Message
with 3 parts, but only one is an attachment
assuming msg is the Message, the following code:
for part in msg.walk():
print part.get_param('attachment', 'noattachment', 'Content-Disposition')
will print '' or noattachment since the header is:
Content-Dispositio... | [
"matching_parts = filter(lambda part: \\\n part.get_all('Content-Disposition', [None])[0] == 'attachment', msg.walk())\nprint len(matching_parts)\n\n"
] | [
0
] | [] | [] | [
"email",
"python"
] | stackoverflow_0006118564_email_python.txt |
Q:
Anchors in Regex
In a Python Regex, must ^ or $
appear just once?
I tried to match two lines with
^(.*\|.*)$^.*$
It does not work. How do you match
several lines?
Note: I am not programming in Python, but using Python-style Regex in my editor gedit.
Thanks and regards!
A:
As other answers have said, you are lo... | Anchors in Regex |
In a Python Regex, must ^ or $
appear just once?
I tried to match two lines with
^(.*\|.*)$^.*$
It does not work. How do you match
several lines?
Note: I am not programming in Python, but using Python-style Regex in my editor gedit.
Thanks and regards!
| [
"As other answers have said, you are looking for re.MULTILINE, but even with that your regex won't work.\n$ matches the position before the line break, and ^ matches the start of a line, so $^ in the middle of a regex will never match. For example:\n>>> re.search(\"^(.*)$^.*$\", multiline_string, re.M) # won't ... | [
6,
3,
2,
2,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006127317_python_regex.txt |
Q:
Using JavaCV in Jython
Has anyone successfully imported into Jython the JavaCV implementation of OpenCV? I have a project that needs to be written in Python and needs heavy GUI development. The standard GUI tools in native Python are not adequate and neither are many of the additional modules for GUIs. I know that... | Using JavaCV in Jython | Has anyone successfully imported into Jython the JavaCV implementation of OpenCV? I have a project that needs to be written in Python and needs heavy GUI development. The standard GUI tools in native Python are not adequate and neither are many of the additional modules for GUIs. I know that Java Swing and SWT will wor... | [
"I don't answer on the quality of JavaCV, but I can point you out on a project that may contain answers to your question as it uses Java, Jython and OpenCV multi platform. this is project Sikuli\n"
] | [
0
] | [] | [] | [
"jython",
"opencv",
"python",
"user_interface"
] | stackoverflow_0006127383_jython_opencv_python_user_interface.txt |
Q:
Is there a Python data structure which is sortable and searchable?
I'm using python to manage a queue of strings to process. It has a couple of requirments:
Each string is matched to a priority and is processed based solely on that value.
Strings can be added to this queue dynamically but no duplicate Strings ar... | Is there a Python data structure which is sortable and searchable? | I'm using python to manage a queue of strings to process. It has a couple of requirments:
Each string is matched to a priority and is processed based solely on that value.
Strings can be added to this queue dynamically but no duplicate Strings are allowed in the queue. If a duplicate is submitted then it must be iden... | [
"That sounds like a reasonable approach. I would use a set instead of a list since it has more efficient membership checking and you don't need to maintain order (since you do it in the heapq)\n",
"An ordered dictionary may be of help.\nSee this page (an ordered dictionary) where it states:\n\nThe ordered diction... | [
5,
2
] | [] | [] | [
"data_structures",
"list",
"priority_queue",
"python"
] | stackoverflow_0006127501_data_structures_list_priority_queue_python.txt |
Q:
Opencv... getting at the data in an IPLImage or CvMat
I am doing some simple programs with opencv in python. I want to write a few algorithms myself, so need to get at the 'raw' image data inside an image. I can't just do image[i,j] for example, how can I get at the numbers?
Thanks
A:
Quick example of using Lo... | Opencv... getting at the data in an IPLImage or CvMat | I am doing some simple programs with opencv in python. I want to write a few algorithms myself, so need to get at the 'raw' image data inside an image. I can't just do image[i,j] for example, how can I get at the numbers?
Thanks
| [
"Quick example of using LoadImageM to load an image file directly into a cvmat:\nimport cv\n\npath = 'stack.png'\nmat = cv.LoadImageM(path, cv.CV_LOAD_IMAGE_UNCHANGED)\nx, y = 42, 6\nprint type(mat)\nprint mat[y, x]\n\nOutput:\n<type 'cv.cvmat'>\n(21.0, 122.0, 254.0)\n\n\nQuick example showing how to multiple one o... | [
5,
1,
0
] | [] | [] | [
"iplimage",
"opencv",
"python"
] | stackoverflow_0006127314_iplimage_opencv_python.txt |
Q:
A solution to remove the duplicates?
My code is below. Basically, I've got a CSV file and a text file "input.txt". I'm trying to create a Python application which will take the input from "input.txt" and search through the CSV file for a match and if a match is found, then it should return the first column of the ... | A solution to remove the duplicates? | My code is below. Basically, I've got a CSV file and a text file "input.txt". I'm trying to create a Python application which will take the input from "input.txt" and search through the CSV file for a match and if a match is found, then it should return the first column of the CSV file.
import csv
csv_file = csv.reader... | [
"If original order does not matter, then stick the results into a set first, and then print them out at the end. But, your example is small enough where speed does not matter that much.\n",
"Stick the results in a set (which is like a list but only contains unique elements), and print at the end.\nSomething like;... | [
4,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0006127666_python.txt |
Q:
Basic django model question on ManyToMany
I need to create a model Class with three columns: network, graduation, and position(s).
class UserProfile(models.Model):
network = models.ForeignKey(Network)
graduation = models.IntegerField(blank=True, null=True, choices=choices)
# position = ?
How would I e... | Basic django model question on ManyToMany | I need to create a model Class with three columns: network, graduation, and position(s).
class UserProfile(models.Model):
network = models.ForeignKey(Network)
graduation = models.IntegerField(blank=True, null=True, choices=choices)
# position = ?
How would I enter in the position column to allow for multip... | [
"Probably the best way is to go ahead and have a Position model (likely using fixtures to populate the rows):\nclass Position(models.Model):\n label = models.CharField(max_length=100)\n\n def __unicode__(self):\n return self.label\n\nclass UserProfile(models.Model):\n [...]\n positions = models.M... | [
4
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0006127751_django_django_models_python.txt |
Q:
Match the last number in a string
I was trying to match the last number in a string, such as "34" in
3.1 General definitions 34
I am using Python-style regex, and I have tried:
(.*?)(\d)
so that later I can use \1 to refer "3.1 General definitions " and \2 to refer "34".
But \2 matches "4" instead of "34". So h... | Match the last number in a string | I was trying to match the last number in a string, such as "34" in
3.1 General definitions 34
I am using Python-style regex, and I have tried:
(.*?)(\d)
so that later I can use \1 to refer "3.1 General definitions " and \2 to refer "34".
But \2 matches "4" instead of "34". So how shall I do?
Thanks and regards!
| [
"You're currently only matching a single digit. Try\n(.*?)(\\d+)\n\nto match at least one digit. This should be all you need, as you've already made the first part of the match reluctant (non-greedy).\nDepending on how you're performing the match, you may need an \"end of string\" anchor ($) at the end, to make sur... | [
12,
4,
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006127771_python_regex.txt |
Q:
Python Convert an IP address encoded in Base64 to a Decimal IP address
I am very new to programming and Python so please bear with me. I have a string that is Base64 and I want to convert it to decimal. The string can come in to the script as any value, for example zAvIAQ. This value represents an IP address whic... | Python Convert an IP address encoded in Base64 to a Decimal IP address | I am very new to programming and Python so please bear with me. I have a string that is Base64 and I want to convert it to decimal. The string can come in to the script as any value, for example zAvIAQ. This value represents an IP address which is 204.11.200.1 when converted to decimal. What I want to do is convert th... | [
"First decode the base64-encoded string using decode('base64') and then decode the resulting number into an IP quartet by using socket.inet_ntoa. Like this:\n>>> socket.inet_ntoa('zAvIAQ=='.decode('base64'))\n'204.11.200.1'\n\n",
">>> address=[ord(c) for c in base64.b64decode('zAvIAQ==')]\n>>> address\n[204, 11, ... | [
6,
3,
1
] | [] | [] | [
"base64",
"decimal",
"python"
] | stackoverflow_0006127688_base64_decimal_python.txt |
Q:
BlueBream framework and multi connections to databases
I put the first steps in BlueBream framework. In my project I must get data from RDBMS - MySQL, PostgreSQL and MS Server. For now, I made a simple tutorial helloworld :) I know how to write Interfaces and Implementations, etc.
My question is: How to set up a c... | BlueBream framework and multi connections to databases | I put the first steps in BlueBream framework. In my project I must get data from RDBMS - MySQL, PostgreSQL and MS Server. For now, I made a simple tutorial helloworld :) I know how to write Interfaces and Implementations, etc.
My question is: How to set up a connections to RDBMS and multiple connections? Could you giv... | [
"Take a look at zope.sqlalchemy; it integrates SQLAlchemy into the Zope transaction manager. SQLAlchemy in turn lets you access many different databases, including MySQL, PostgreSQL and MS Server.\nThe zope.sqlalchemy package explains how to obtain a SQLAlchemy session. From there on out you use bog-standard SQLAlc... | [
0
] | [] | [] | [
"python",
"zope3"
] | stackoverflow_0006127963_python_zope3.txt |
Q:
Zope 3 and current Products
On this page http://www.zope.org/Products at the bottom is a full list of Zope products but most of them are available for Zope 2 not for Zope 3 e.g. ZMySQLDA.
Where I can find list of all Products only for Zope 3? Or maybe I am wrong and this list is for Zope2 and Zope3?
A:
Zope3 (o... | Zope 3 and current Products | On this page http://www.zope.org/Products at the bottom is a full list of Zope products but most of them are available for Zope 2 not for Zope 3 e.g. ZMySQLDA.
Where I can find list of all Products only for Zope 3? Or maybe I am wrong and this list is for Zope2 and Zope3?
| [
"Zope3 (or Zope Toolkit, ZTK) is a collection of Python libraries, used by various projects, with BlueBream being one of them, classic Zope2 another. As such, there is no need to provide specialized \"Products\" for these anymore.\nYou use the libraries like you would use other Python libraries; e.g. you write inte... | [
1,
0
] | [] | [] | [
"python",
"zope3"
] | stackoverflow_0006125410_python_zope3.txt |
Q:
Off by one error in imshow?
I'm plotting a PGM image:
Here's the data I'm using.
The problem is some of the shown pixels are wrong. For example:
the three grey boxes near the top of the image are of value 11 (so they should be red, not red)
the two yellow pixels in the top row -- they are of value 8, so they sh... | Off by one error in imshow? | I'm plotting a PGM image:
Here's the data I'm using.
The problem is some of the shown pixels are wrong. For example:
the three grey boxes near the top of the image are of value 11 (so they should be red, not red)
the two yellow pixels in the top row -- they are of value 8, so they should be yellow-green, not yellow
... | [
"The solution is to set im.set_clim(vmin, vmax). Basically the values in the image were being translated to cover the entire color range. For example if 3 was the largest value in your data, it would be assigned the maximum color value. \nInstead you need to tell it that max_nodes is the highest value (13 in you... | [
5,
3
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0006127282_matplotlib_python.txt |
Q:
Flexible parsing of text with regular expressions in Java or Python
I am working on some code to parse text into XML. I am currently using java and jaxb to handle the XML and the in-program representation of my data. I need to setup an easily expandable and adaptable method to parse the info from my text files int... | Flexible parsing of text with regular expressions in Java or Python | I am working on some code to parse text into XML. I am currently using java and jaxb to handle the XML and the in-program representation of my data. I need to setup an easily expandable and adaptable method to parse the info from my text files into my java classes. The data will for the most part stay the same, but I n... | [
"Those look like fixed-width fields, which are probably a good choice for simple string splitting. The only thing it looks like you could use regular expressions for is to determine what type of record you are looking at, although it looks like the indentation level is also useful for determining that.\n",
"You ... | [
2,
0,
0
] | [] | [] | [
"java",
"python",
"regex"
] | stackoverflow_0006074884_java_python_regex.txt |
Q:
Stop a Python program until a user performs an action
My original program used input, like this:
n = input("Enter your favorite number: ")
# do stuff with number
Now, I have switched to a GTK GUI, but still want the accomplish the same thing. Now look at this very similar piece of code:
n = myWindow.getNumber()
#... | Stop a Python program until a user performs an action | My original program used input, like this:
n = input("Enter your favorite number: ")
# do stuff with number
Now, I have switched to a GTK GUI, but still want the accomplish the same thing. Now look at this very similar piece of code:
n = myWindow.getNumber()
# do stuff with number
Would it be possible to write a getN... | [
"What you need is a modal dialog. I don't know GTK (or PyGTK) at all, but there appears to be an example in the documentation.\n"
] | [
3
] | [] | [] | [
"gtk",
"python"
] | stackoverflow_0006128721_gtk_python.txt |
Q:
is python multiprocessing.Process start() doing the same job as subprocess.Popen
I am a newbie in Python. I recently tried to use Python script to call an console exe which is a process need long time. I will allow the exe being called as many times as the CPU can permit. And when the exe has finish its job. The C... | is python multiprocessing.Process start() doing the same job as subprocess.Popen | I am a newbie in Python. I recently tried to use Python script to call an console exe which is a process need long time. I will allow the exe being called as many times as the CPU can permit. And when the exe has finish its job. The CPU can be allocated to other new jobs. So I think I may need the multiple process cont... | [
"Use subprocess.Popen to run other executables in a subprocess.\nUse multiprocessing.Process to run Python callables (e.g. functions) in a subprocess.\nThe two are not interchangeable.\n"
] | [
5
] | [] | [] | [
"multiprocessing",
"python",
"subprocess"
] | stackoverflow_0006128569_multiprocessing_python_subprocess.txt |
Q:
Launch ipython shell from python script that uses command line option parsing
I've been looking around for quite some time to find a way to optimally do this but haven't been successful. My problem setting is as follows:
I want to be able to launch an ipython shell for debugging purposes from within a python scri... | Launch ipython shell from python script that uses command line option parsing | I've been looking around for quite some time to find a way to optimally do this but haven't been successful. My problem setting is as follows:
I want to be able to launch an ipython shell for debugging purposes from within a python script that uses command line option parsing (optparse), in a non-programmatic fashion.... | [
"[Reposting as an answer since it worked]\nTry specifying argv, like so: IPShellEmbed(argv=[])(). That should stop IPython from looking at the arguments you gave to your script.\n"
] | [
4
] | [] | [] | [
"debugging",
"ipython",
"python"
] | stackoverflow_0006118531_debugging_ipython_python.txt |
Q:
How to get __radd__ to work with numpy arrays
Consider the following python code:
class MyClass:
def __radd__(self, a):
print "foo", a
return a
p = MyClass()
To evoke radd the following can be run:
>>> print "bar"+p
foo bar
bar
This is the expected behavior. __add__ is run and fails, therefore __... | How to get __radd__ to work with numpy arrays | Consider the following python code:
class MyClass:
def __radd__(self, a):
print "foo", a
return a
p = MyClass()
To evoke radd the following can be run:
>>> print "bar"+p
foo bar
bar
This is the expected behavior. __add__ is run and fails, therefore __radd__ takes over and handles the situation.
But wi... | [
"When you do a+b, a normally gets first crack at defining what that means: b.__radd__ will only be used if a.__add__ isn't implemented. So, in the general case, if you want to control addition, you have to make sure you put your object first: b+a.\nAccording to the docs, though, there's an exception to that. If yo... | [
2
] | [] | [] | [
"arrays",
"math",
"numpy",
"python"
] | stackoverflow_0006127550_arrays_math_numpy_python.txt |
Q:
Generating an "efficent" encoding from a list of numbers
I was thinking about this the other day. Say you have the list of numbers:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 19, 21, 22, 23, 999, 1000, 1001
is there any library or code snipped that will turn the following into something like:
1-13, 19, 21-23, 999... | Generating an "efficent" encoding from a list of numbers | I was thinking about this the other day. Say you have the list of numbers:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 19, 21, 22, 23, 999, 1000, 1001
is there any library or code snipped that will turn the following into something like:
1-13, 19, 21-23, 999-1001
In other words, reduce a full list of numbers to a bunc... | [
"def get_groups(lst):\n slices = [i+1 for i, v in enumerate(zip(lst, l[1:])) if v[0] != v[1]-1] \n slices = [0] + slices + [len(lst)]\n for start, end in zip(slices, slices[1:]):\n yield lst[start:end]\n\n>>> list(get_groups([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 19, 21, 22, 23, 999, 1000, 1001... | [
1,
0,
0
] | [] | [] | [
"python",
"range",
"sequence"
] | stackoverflow_0006128895_python_range_sequence.txt |
Q:
Python time.time() -> IOError
I've just installed a base gentoo stage 3 and I get the following error when i try and call time.time():
sbx / # python
import time
Python 2.7.1 (r271:86832, May 22 2011, 14:53:09)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import... | Python time.time() -> IOError | I've just installed a base gentoo stage 3 and I get the following error when i try and call time.time():
sbx / # python
import time
Python 2.7.1 (r271:86832, May 22 2011, 14:53:09)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> time.time()
Traceback (mo... | [
"Did it work before your custom kernel? Boot into a rescue CD, chroot into your gentoo env, and run your script. If it works, it's your kernel. That's about as specific as I can be.\n",
"Prehaps this is your issue ?\nhttp://bugs.gentoo.org/show_bug.cgi?id=330937\nedit C test code \n#include <stdio.h>\n#include <s... | [
3,
0
] | [] | [] | [
"gentoo",
"linux",
"python"
] | stackoverflow_0006129054_gentoo_linux_python.txt |
Q:
High Perfomance: Do call C++ methods directly from a python backend?
My Python backend (Django) has to request to a C++ library to get a result (with help of ctypes module).
Is it normal to call a C++ method directly? Or may be I need an intermediate thread manager that starts a new thread when python script wants... | High Perfomance: Do call C++ methods directly from a python backend? | My Python backend (Django) has to request to a C++ library to get a result (with help of ctypes module).
Is it normal to call a C++ method directly? Or may be I need an intermediate thread manager that starts a new thread when python script wants a result?
| [
"Basically you have to decide what kind of operation flow you want. If you prefer synchronous processing you can call you method directly, if you favor asynchronous processing you will need an intermediate solution.\nHowever, you have to be aware, that when you call the C++ routine directly form your Django app the... | [
2
] | [] | [] | [
"backend",
"c++",
"ctypes",
"django",
"python"
] | stackoverflow_0006129383_backend_c++_ctypes_django_python.txt |
Q:
Is Ruby or Python not suitable for iPhone or Mac app development because of speed, and any compiler that can help boost the speed?
I am reading a little bit on Objective-C, and since it comes from Smalltalk, like Ruby does, so I wonder, is it true that if using Ruby, (if Apple change XCode to support it), to devel... | Is Ruby or Python not suitable for iPhone or Mac app development because of speed, and any compiler that can help boost the speed? | I am reading a little bit on Objective-C, and since it comes from Smalltalk, like Ruby does, so I wonder, is it true that if using Ruby, (if Apple change XCode to support it), to develop iPhone or Mac app, it is not suitable really because of the speed? For example, Angry Birds probably isn't as smooth as it is now i... | [
"On desktop those are fine languages to use, and for Python you could use py2app to deploy your app. You wouldn't want to write low-level graphics routines in an interpreted language, but that's what libraries like PyGame are for.\n(Not that this is a particular advantage, but note that one of the most popular 2D g... | [
4,
3,
1
] | [] | [] | [
"ios",
"objective_c",
"python",
"ruby"
] | stackoverflow_0006129086_ios_objective_c_python_ruby.txt |
Q:
Simplest Python user registration system?
I am building in Python on django framework. Having done some tutorials, I now want to build a very simple lightweight application.
The first part of my application is that I need a user system. i.e. a way for people to sign up and a way for me to keep their information pr... | Simplest Python user registration system? | I am building in Python on django framework. Having done some tutorials, I now want to build a very simple lightweight application.
The first part of my application is that I need a user system. i.e. a way for people to sign up and a way for me to keep their information private.
What is the easiest way for me to set th... | [
"django-registration should get you started.\n"
] | [
3
] | [] | [] | [
"authentication",
"django",
"python",
"registration"
] | stackoverflow_0006129527_authentication_django_python_registration.txt |
Q:
Python: differences between tempfile.mkdtemp and tempfile.TemporaryDirectory
I need to create a temp directory that will house another named directory and subfiles. In the end the named directory and subfiles will be appended to a tarball and the temp directory can be removed. Was initially going to use mkdtemp() ... | Python: differences between tempfile.mkdtemp and tempfile.TemporaryDirectory | I need to create a temp directory that will house another named directory and subfiles. In the end the named directory and subfiles will be appended to a tarball and the temp directory can be removed. Was initially going to use mkdtemp() but it looks like the TemporaryDirectory() method removes itself? Can someone expl... | [
"You are correct in that the only real difference is that TemporaryDirectory will delete itself when it is done. It will let you do something like:\nwith tempfile.TemporaryDirectory() as dir:\n do_stuff_with(dir)\n\nwhen you leave the scope of the with, the temporary directory will be deleted. With mkdtemp, you w... | [
11,
6
] | [] | [] | [
"python",
"temporary_files"
] | stackoverflow_0006128621_python_temporary_files.txt |
Q:
How do I implement the OS-Rank() function for my binary tree in Python?
I'm trying to implement the OS-Rank() function for my binary tree that I've built. OS-Rank tags a node with a count of smaller nodes from the tree, and stores it in node.size. This allows OS-Select to easily select the i'th smallest node in O(... | How do I implement the OS-Rank() function for my binary tree in Python? | I'm trying to implement the OS-Rank() function for my binary tree that I've built. OS-Rank tags a node with a count of smaller nodes from the tree, and stores it in node.size. This allows OS-Select to easily select the i'th smallest node in O(nlgn) time.
Here is the pseudo code:
OS-RANK(x)
r = x.left.size + 1
y... | [
"Embarrassingly, I've misunderstood the purpose of OS-Rank(). I thought it set the size value of each node, but it appears that's actually done on insert. OS-Rank() returns the rank of a node by using that size value.\nNo more 2am coding, I promise!\n"
] | [
1
] | [] | [] | [
"binary_tree",
"python"
] | stackoverflow_0006121400_binary_tree_python.txt |
Q:
from java package how about in python?
I have search the ways that how can I define some thing like this in python OOP ways:
java:
package project.work;
public interface IWork
{
public void input();
public void display();
}
A:
Python doesn't really have interfaces as separate from classes. You can use... | from java package how about in python? | I have search the ways that how can I define some thing like this in python OOP ways:
java:
package project.work;
public interface IWork
{
public void input();
public void display();
}
| [
"Python doesn't really have interfaces as separate from classes. You can use the abc module to get a similar effect. Discussion on that method and on some others is here.\n"
] | [
3
] | [
"Since python is a dynamically typed language it would seem silly to try this. The notion of interfaces really only makes sense in a statically typed language, in python you call a method on an object and find out at runtime if the object given actually implements the method.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0006129714_python.txt |
Q:
Does Python have something like LINQ to XML
I need to parse XML file and put results on HTML form, but I am new to Python. Does Python 2.7 have something like LINQ to XML from C# or any good library for XML can suggest me ?
A:
Check out Pynq – Python Language Integrated Query https://github.com/heynemann/pynq/wi... | Does Python have something like LINQ to XML | I need to parse XML file and put results on HTML form, but I am new to Python. Does Python 2.7 have something like LINQ to XML from C# or any good library for XML can suggest me ?
| [
"Check out Pynq – Python Language Integrated Query https://github.com/heynemann/pynq/wiki\nI'm sure though if Pynq will be sufficient for you, although it does implement exprenssion trees in Python just like LINQ does for C#.\nFor an easy way to access XML in Python, you could check out BeautifulSoup (http://www.cr... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006121846_python.txt |
Q:
Call an External C++ function and Memory Leaks: is all allocated memory cleaned up after finishing Python script?
Python script calls an external C++ function (using ctypes). Memory leaks are possible when execution the C++ function.
Will all allocated memory (in C++ function) be automatically cleaned up after fin... | Call an External C++ function and Memory Leaks: is all allocated memory cleaned up after finishing Python script? | Python script calls an external C++ function (using ctypes). Memory leaks are possible when execution the C++ function.
Will all allocated memory (in C++ function) be automatically cleaned up after finishing of the Python script?
| [
"Yes, It will all be returned to the OS once the python interpreter exits. This is true for all processes - nothing specific to python or c++.\n"
] | [
2
] | [] | [] | [
"c++",
"ctypes",
"python"
] | stackoverflow_0006129933_c++_ctypes_python.txt |
Q:
Best Way to Process a Word Document
I receive word documents with specified formating corresponding to the data that is in them. For example, all headers have the exact same formating (Times New Roman-Font 14-Bold).
What is the best way to process such MS Word documents (.doc or .docx) into xml documents? Langua... | Best Way to Process a Word Document | I receive word documents with specified formating corresponding to the data that is in them. For example, all headers have the exact same formating (Times New Roman-Font 14-Bold).
What is the best way to process such MS Word documents (.doc or .docx) into xml documents? Language is not an issue (I'll use Lisp/Boost.S... | [
"Take a look at the python-docx library.\n",
"So I think you're saying that the structure of the document is encoded in the formatting, and you want to produce XML files that capture that structure, whilst keeping the content in plain text?\nIf that is so you will need to parse the documents, and build a data str... | [
10,
3,
2,
1,
0
] | [] | [] | [
"ms_word",
"parsing",
"python",
"xml_serialization"
] | stackoverflow_0004262903_ms_word_parsing_python_xml_serialization.txt |
Q:
Remove extra spaces in middle of string split join Python
I have the following string which forces my Python script to quit:
"625 625 QUAIL DR UNIT B"
I need to delete the extra spaces in the middle of the string so I am trying to use the following split join script:
import arcgisscripting
import logg... | Remove extra spaces in middle of string split join Python | I have the following string which forces my Python script to quit:
"625 625 QUAIL DR UNIT B"
I need to delete the extra spaces in the middle of the string so I am trying to use the following split join script:
import arcgisscripting
import logging
logger = logging.getLogger()
gp = arcgisscripting.create(... | [
"Your source code and your error do not match, the error states you didn't define the variable SIT_FULL_S.\nI am guessing that what you want is:\nName = ' '.join(row.GetValue('SIT_FULL_S').split())\n\n",
"Use the re module...\n>>> import re\n>>> str = 'A B C'\n>>> re.sub(r'\\s+', ' ', str)\n'A B C'\n\n",
"I b... | [
4,
3,
2,
0
] | [] | [] | [
"join",
"python",
"split"
] | stackoverflow_0006130067_join_python_split.txt |
Q:
Disable widget with checkbutton?
How can i disable an entry using a checkbutton... i got this but it doens't work (python 2.7.1)...
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
class Principal(tk.Tk):
def __init__(self, *args, **kwargs):
foo = ""
na... | Disable widget with checkbutton? | How can i disable an entry using a checkbutton... i got this but it doens't work (python 2.7.1)...
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
class Principal(tk.Tk):
def __init__(self, *args, **kwargs):
foo = ""
nac = ""
global ck1
nac... | [
"I made foo and nac member variable of the Principal class\n ...\n self.foo = StringVar()\n self.foo.set(\"test\")\n self.nac = IntVar()\n ...\n\nThen in naccheck() reference self.nac \n def naccheck(self):\n if self.nac == 1:\n ent.configure(state='disabled')\n self.n... | [
3,
3
] | [] | [] | [
"checkbox",
"python",
"tkinter"
] | stackoverflow_0006129936_checkbox_python_tkinter.txt |
Q:
Naming in Django: useThis or use_this?
Programmers prefer different types of coding styles.
Sometimes I think that it is strange to use class names LikeThis and field/method names like_this.
What is your opinion? Use CaptionNames or underscore_names to delelop websites powered with Django?
A:
As Django code is P... | Naming in Django: useThis or use_this? | Programmers prefer different types of coding styles.
Sometimes I think that it is strange to use class names LikeThis and field/method names like_this.
What is your opinion? Use CaptionNames or underscore_names to delelop websites powered with Django?
| [
"As Django code is Python code, PEP 8 is the default way to go.\n\nA style guide is about consistency. \n Consistency with this style guide is\n important. Consistency within a project is more important. Consistency\n within one module or function is most important.\n\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006130192_django_python.txt |
Q:
How can I put an intersphinx link to an arbitrary method in the standard library documentation?
I am trying to use Sphinx to document a project, but I cannot figure out how to use
intersphinx. I use this line:
:py:meth:`math.sin`
to add the link, but in the output, it shows up bold, not as a link.
Although that... | How can I put an intersphinx link to an arbitrary method in the standard library documentation? | I am trying to use Sphinx to document a project, but I cannot figure out how to use
intersphinx. I use this line:
:py:meth:`math.sin`
to add the link, but in the output, it shows up bold, not as a link.
Although that line does not work, both the following do:
:py:meth:`dict.items`
:py:class:`zipfile.ZipFile`
My int... | [
"The :py:meth: should be :py:func:. Basically, \nany valid domain can be used.\n",
"Have you read the documentation for intersphinx?\nEdit\nGot it to work using this:\n***\nTRY\n***\n\nMy try\n======\n\nsin\n:py:func:`math.cos`\n\npop\n:py:meth:`dict.pop`\n\ndict\n:py:meth:`dict.items`\n\nzipfile\n:py:class:`zip... | [
10,
7
] | [] | [] | [
"cross_reference",
"python",
"python_sphinx"
] | stackoverflow_0006129963_cross_reference_python_python_sphinx.txt |
Q:
ZipFile module in Python - Runtime problems
I'm doing a little script to zip multiple folders in multiple zip files following a certain structure. I've built the structure as a list. Here are some entries:
['E:\Documents\UFSCar\Primeiro Ano\Primeiro Semestre\Cálculo 1',
'E:\Documents\UFSCar\Primeiro Ano\Segundo Se... | ZipFile module in Python - Runtime problems | I'm doing a little script to zip multiple folders in multiple zip files following a certain structure. I've built the structure as a list. Here are some entries:
['E:\Documents\UFSCar\Primeiro Ano\Primeiro Semestre\Cálculo 1',
'E:\Documents\UFSCar\Primeiro Ano\Segundo Semestre\Estatistica',
'E:\Documents\UFSCar\Primeir... | [
"A bug report related to this issue was submitted in 2007: http://bugs.python.org/issue1760357\nThe problem is caused by a bug in the Windows localtime function and there's nothing the time module can do other than throw a ValueError.\nI got around the problem like this:\ntry:\n zip.write(absfilename, zipfilenam... | [
4,
0,
0
] | [] | [] | [
"python",
"zip"
] | stackoverflow_0004434629_python_zip.txt |
Q:
Wrong output using sample code from online book
I'm having trouble with this Python code.. It's supposed to give me output similar to that shown here (should differ for different music files):
album=
artist=Ghost in the Machine
title=A Time Long Forgotten (Concept
genre=31
name=/music/_singles... | Wrong output using sample code from online book | I'm having trouble with this Python code.. It's supposed to give me output similar to that shown here (should differ for different music files):
album=
artist=Ghost in the Machine
title=A Time Long Forgotten (Concept
genre=31
name=/music/_singles/a_time_long_forgotten_con.mp3
year=1999
comm... | [
"I think the problem may be here:\nif __name__ == \"__main__\":\n for info in listDirectory(\"derp/\", [\".mp3\"]):\n print \"\\n\".join([\"%s=%s\" % (k, v) for k, v in info.items()])\n print\n\nMy thought is that the file in question (info) doesn't have all the file tags filled like the example do... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0006130339_python.txt |
Q:
Python- creating a table
I am a python user in the very early stage.
I have two data set of temperature over a specific location from the year 1850 to 2010 with one value of temperature for each month for this entire period. I am trying to create a table with these values in the below given format. T is my data... | Python- creating a table | I am a python user in the very early stage.
I have two data set of temperature over a specific location from the year 1850 to 2010 with one value of temperature for each month for this entire period. I am trying to create a table with these values in the below given format. T is my data.
year data JAn FEB MAR APR MA... | [
"I would recommend that you have a look at string templates\nExample:\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>>> d = dict(who='tim')\n>>> Template('Give $who $100').substitute(d)\nTraceback (most recent call last):\... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0006129693_python.txt |
Q:
Store and load a large number linked objects in Python
I have a lot of objects which form a network by keeping references to other objects. All objects (nodes) have a dict which is their properties.
Now I'm looking for a fast way to store these objects (in a file?) and reload all of them into memory later (I don't... | Store and load a large number linked objects in Python | I have a lot of objects which form a network by keeping references to other objects. All objects (nodes) have a dict which is their properties.
Now I'm looking for a fast way to store these objects (in a file?) and reload all of them into memory later (I don't need random access). The data is about 300MB in memory whic... | [
"Pickle would be my first choice. But since you say that it didn't work, you might want to try shelve, even thought it's not shelve's primary purpose.\nReally, you should be using Pickle for this. Perhaps you could post some code so that we can take a look and figure out why it doesn't work\n",
"\"The pickle modu... | [
0,
0,
0
] | [] | [] | [
"persistent_storage",
"python"
] | stackoverflow_0006128458_persistent_storage_python.txt |
Q:
GAE on python + REST, inserting/updating db.ListProperty(users.User)
I have a simple db.Model, that has one of the fields db.ListProperty(users.User)
For the REST server I used http://code.google.com/p/appengine-rest-server/
However, I can't seem to update this field..
The app is currently password-protected but i... | GAE on python + REST, inserting/updating db.ListProperty(users.User) | I have a simple db.Model, that has one of the fields db.ListProperty(users.User)
For the REST server I used http://code.google.com/p/appengine-rest-server/
However, I can't seem to update this field..
The app is currently password-protected but if anyone wants to take a look, I can make it public.
Basically, I have a f... | [
"I managed to fix it: db.ListProperty(users.User) wants an object that serialized looks like this:\n\"developers\":{\"item\":[\"some1@email.com\",\"some2@email.com\"]}\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"gql",
"javascript",
"python",
"rest"
] | stackoverflow_0006124029_google_app_engine_gql_javascript_python_rest.txt |
Q:
Use of super() with not immediate parent
Is this a legal use of super()?
class A(object):
def method(self, arg):
pass
class B(A):
def method(self, arg):
super(B,self).method(arg)
class C(B):
def method(self, arg):
super(B,self).method(arg)
Thank you.
A:
It will work, but it... | Use of super() with not immediate parent | Is this a legal use of super()?
class A(object):
def method(self, arg):
pass
class B(A):
def method(self, arg):
super(B,self).method(arg)
class C(B):
def method(self, arg):
super(B,self).method(arg)
Thank you.
| [
"It will work, but it will probably confuse anyone trying to read your code (including you, unless you remember it specifically). Don't forget that if you want to call a method from a particular parent class, you can just do:\nA.method(self, arg)\n\n",
"Well, \"legal\" is a questionable term here. The code will e... | [
11,
3
] | [] | [] | [
"python",
"super"
] | stackoverflow_0006130629_python_super.txt |
Q:
python join "large" file
In python I have read in a file into a list using file.readlines() , later on after some logic, I would like to put it back together in a string using fileString = ''.join(file), for some reason, even without a print function, it prints the fileString out to the console up to a certain poi... | python join "large" file | In python I have read in a file into a list using file.readlines() , later on after some logic, I would like to put it back together in a string using fileString = ''.join(file), for some reason, even without a print function, it prints the fileString out to the console up to a certain point, then it just stops. It doe... | [
"File is your file pointer in memory. When you attempt to join on it, you don't actually have a string to work with. \nHow about this?\nwith open(file, 'rb') as myfile:\n strings = myfile.readlines()\n\n# do your stuff to strings\nfilestring = ''.join(strings)\n\nNote that strings is a list of lines like this:\n... | [
2,
1
] | [] | [] | [
"join",
"list",
"memory",
"python",
"string"
] | stackoverflow_0006130438_join_list_memory_python_string.txt |
Q:
Python plist parser IOError: [Errno 63] File name too long:
my Python plist parser does not like my long string that is in plist format.
plist_data = plistlib.readPlist(plistString)
plistString is actually the contents of the file I opened. Oddly enough, putting the input file into the readPlist function works, ... | Python plist parser IOError: [Errno 63] File name too long: | my Python plist parser does not like my long string that is in plist format.
plist_data = plistlib.readPlist(plistString)
plistString is actually the contents of the file I opened. Oddly enough, putting the input file into the readPlist function works, but I had to do some further formatting of that file within pytho... | [
"If you want to read a string as a file, use StringIO.\nfakeFile= StringIO.StringOI( plistString )\nplist_data = plistlib.readPlist(fakeFile)\n\nIt's better not to open and read the pList file. plistlib.readPlist does the opening and reading for you.\n",
"plistlib.readPlist takes file or file name, not contents.... | [
4,
2
] | [] | [] | [
"input",
"plist",
"python"
] | stackoverflow_0006130746_input_plist_python.txt |
Q:
What is the difference between a constructer and initializer in python?
Possible Duplicate:
Python (and Python C API): new versus init
I'm at college just now and the lecturer was using the terms constructors and initializers interchangeably. I'm pretty sure that this is wrong though.
I've tried googling the an... | What is the difference between a constructer and initializer in python? |
Possible Duplicate:
Python (and Python C API): new versus init
I'm at college just now and the lecturer was using the terms constructors and initializers interchangeably. I'm pretty sure that this is wrong though.
I've tried googling the answer but not found the answer I'm looking for.
| [
"In most OO languages, they are the same step, so he's not wrong for things like java, c++, etc. In python they are done in two steps: __new__ is the constructor; __init__ is the initializer.\nHere is another answer that goes into more detail about the differences between them.\n",
"In almost all usual cases, Pyt... | [
20,
5,
0
] | [] | [] | [
"class",
"constructor",
"initialization",
"object",
"python"
] | stackoverflow_0006130644_class_constructor_initialization_object_python.txt |
Q:
Where to join threads created in an asynchronous tornado request handler?
This one has me a bit baffled. Fairly new to tornado and threading in python, so I could be completely off the mark with what I'm trying to do here.
Probably best to start with some simplified code:
class Handler(tornado.web.RequestHandler)... | Where to join threads created in an asynchronous tornado request handler? | This one has me a bit baffled. Fairly new to tornado and threading in python, so I could be completely off the mark with what I'm trying to do here.
Probably best to start with some simplified code:
class Handler(tornado.web.RequestHandler):
def perform(self):
#do something cuz hey, we're in a thread!
def i... | [
"I believe Thread.join() will block until the thread finishes, probably something you want to avoid. Rather than joining, you can have the thread callback to the handler.\nWhen using threads, be aware that tornado isn't thread-safe, so you can't use any RequestHandler (for example) methods from threads.\nThis works... | [
12,
1
] | [] | [] | [
"join",
"multithreading",
"python",
"tornado"
] | stackoverflow_0006062997_join_multithreading_python_tornado.txt |
Q:
Some nice tutorial to introduce myself into the Telepathy API?
I would like to develop a bot for Empathy, but I don't know how to get started. I've read the Telepathy wiki, but I think it's very bad documented, does anybody know any nice tutorial? Better if it uses Python or C bindings.
Thank you.
A:
You should ... | Some nice tutorial to introduce myself into the Telepathy API? | I would like to develop a bot for Empathy, but I don't know how to get started. I've read the Telepathy wiki, but I think it's very bad documented, does anybody know any nice tutorial? Better if it uses Python or C bindings.
Thank you.
| [
"You should check the telepathy-python repository's examples directory. They have quite a few listed there:\nhttp://git.collabora.co.uk/?p=telepathy-python.git;a=tree;f=examples;h=8cede34dfe79d02dc5ce229bd2aa97934f3587c1;hb=HEAD\nI also found this PDF that shows some examples with VoIP:\nhttp://raphael.slinckx.net/... | [
2,
0
] | [] | [] | [
"api",
"bots",
"c",
"python",
"telepathy_python"
] | stackoverflow_0003384187_api_bots_c_python_telepathy_python.txt |
Q:
Creating new instance objects
I'm not sure that I've gotten this right. I'm working on learning Python and I'm wondering how exactly you call the constructor of a class. Currently the class is in it's own module that is imported in the main file. Is it right to go
Class.Class(variables, here)
Or is there some eas... | Creating new instance objects | I'm not sure that I've gotten this right. I'm working on learning Python and I'm wondering how exactly you call the constructor of a class. Currently the class is in it's own module that is imported in the main file. Is it right to go
Class.Class(variables, here)
Or is there some easier way to go about this?
| [
"You create instances like this:\nimport MyMod\nobj = MyMod.MyClass(param1, param2)\n\nThis is the canonical way to instantiate Python objects.\n",
"That's fine. Alternatively you can do:\nfrom Class import Class\nClass(variables, here)\n\n"
] | [
2,
2
] | [] | [] | [
"class",
"object",
"python"
] | stackoverflow_0006131296_class_object_python.txt |
Q:
os.listdir() fails for every directory on UNIX
This is the most strangest error ever - Python os.listdir() fails for every directory:
Python 2.5.2 (r252:60911, Jan 20 2010, 23:14:04)
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
... | os.listdir() fails for every directory on UNIX | This is the most strangest error ever - Python os.listdir() fails for every directory:
Python 2.5.2 (r252:60911, Jan 20 2010, 23:14:04)
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.listdir("/")
Tracebac... | [
"This is caused by a rootkit. I'm just looking at the same problem on a Debian (lenny) server I administer. Look at the top of strace:\nopen(\"/etc/ld.so.preload\", O_RDONLY) = 3\nfstat(3, {st_mode=S_IFREG|0644, st_size=22, ...}) = 0\nmmap(NULL, 22, PROT_READ|PROT_WRITE, MAP_PRIVATE, 3, 0) = 0x7feb24b32000\nclos... | [
7,
1
] | [] | [] | [
"linux",
"python",
"ubuntu"
] | stackoverflow_0005417265_linux_python_ubuntu.txt |
Q:
Error Installing Python
Upon hitting
make install
I get the following error
/usr/bin/install: cannot create regular file /usr/local/bin/python2.6: Permission denied make: *** [altbininstall] Error 1
I am not the root user so I assume its a permissions issue. I do have my own subfolder at /home/my_username Is the... | Error Installing Python | Upon hitting
make install
I get the following error
/usr/bin/install: cannot create regular file /usr/local/bin/python2.6: Permission denied make: *** [altbininstall] Error 1
I am not the root user so I assume its a permissions issue. I do have my own subfolder at /home/my_username Is there a way to complete the pyth... | [
"The configure script lets you specify --prefix=[dest]. From the usage:\n\nBy default, `make install' will install all the files in\n /usr/local/bin, /usr/local/lib etc. You can specify\n an installation prefix other than /usr/local using --prefix,\n for instance --prefix=$HOME.\n\nSo to install under py26 in y... | [
12
] | [] | [] | [
"centos",
"command_line",
"linux",
"python"
] | stackoverflow_0006131560_centos_command_line_linux_python.txt |
Q:
Pass python script output to another programs stdin
I have an application that takes input, either from the terminal directly or I can use a pipe to pass the output of another program into the stdin of this one. What I am trying to do is use python to generate the output so it's formatted correctly and pass that t... | Pass python script output to another programs stdin | I have an application that takes input, either from the terminal directly or I can use a pipe to pass the output of another program into the stdin of this one. What I am trying to do is use python to generate the output so it's formatted correctly and pass that to the stdin of this program all from the same script. Her... | [
"The problem is that appScan() only prints to stdout; appScan() returns None, so proc.communicate(input=appScan()) is equivalent to proc.communicate(input=None). You need appScan to return a string. \nTry this (not tested):\ndef appScan():\n os.system(\"system_profiler -xml SPApplicationsDataType > apps.xml\")\n... | [
3
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0006131395_python_subprocess.txt |
Q:
How to import modules from different folders in Python?
How to import modules from different folders? I have the following
cgi-bin
| py
|
__init.py__
http
|
__init.py__
HttpFormParser.py
xml
|
__in... | How to import modules from different folders in Python? | How to import modules from different folders? I have the following
cgi-bin
| py
|
__init.py__
http
|
__init.py__
HttpFormParser.py
xml
|
__init.py__
XmlDocumentCreator.py
I want to import... | [
"Just work out the directory you're executing from, as told by sys.argv[0]. In this case, you want to get the cgi-bin directory since it contains py:\nimport os\nimport sys\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \n os.pardir, os.pardir)))\nimport py.xml.XmlDocumentCreator\n\nP.S... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006131899_python.txt |
Q:
Python Mechanize upload
Hi I have been using mechanize and python to try and upload a file to a website, so far Ive been succesfull but im stuck at the upload page. I know mechanize does not work with JavaScript but I was wondering if anyone knows a way that I could pass a file directory to the form to upload it, ... | Python Mechanize upload | Hi I have been using mechanize and python to try and upload a file to a website, so far Ive been succesfull but im stuck at the upload page. I know mechanize does not work with JavaScript but I was wondering if anyone knows a way that I could pass a file directory to the form to upload it, any help will be greatly appr... | [
"Mechanize handles file uploads to forms like this:\nform.add_file(open(\"NAME/LOCATION OF FILE\"), \"MIME TYPE\", \"NAME OF FILE\")\nbr.form.add_file(open(\"file.txt\"), \"text/plain\", \"file.txt\")\n\n"
] | [
2
] | [] | [] | [
"file",
"javascript",
"mechanize",
"python",
"upload"
] | stackoverflow_0006066198_file_javascript_mechanize_python_upload.txt |
Q:
SOAP Method Max Item Number
I was wondering if there was a maximum limit to the number of items that could be received through a SOAP method, or if the server I'm communicating with just has a strange limit.
When using Python's framework Suds, I used a method called getRecords from a database of about 39,000 rows.... | SOAP Method Max Item Number | I was wondering if there was a maximum limit to the number of items that could be received through a SOAP method, or if the server I'm communicating with just has a strange limit.
When using Python's framework Suds, I used a method called getRecords from a database of about 39,000 rows. Unfortunately, when I actually ... | [
"There is no such limit. It's just on the server side so that big queries wouldn't hinder the server's work.\n"
] | [
0
] | [] | [] | [
"python",
"soap",
"suds"
] | stackoverflow_0006132080_python_soap_suds.txt |
Q:
boost::python - how to pass by reference/pointer to python overriden class functions
I have some class functions that takes in parameters by pointer. However, when I expose and override these functions in boost::python, any changes I make to the parameters are not reflected back to the original, meaning it isn't b... | boost::python - how to pass by reference/pointer to python overriden class functions | I have some class functions that takes in parameters by pointer. However, when I expose and override these functions in boost::python, any changes I make to the parameters are not reflected back to the original, meaning it isn't being passed by pointer as I expected. I previously had them as pass-by-reference, but the ... | [
"Well after searching around for a bit I found the answer. Turns out you have to explicitly indicate to call_method not to make a copy when it's pass by reference (by using ref(T)) or pointer (by using ptr(T)). \nBy Changing \nvoid StatusEffectWrapper::TickCharacter(Game::Character::BaseCharacter* character, Game::... | [
2
] | [] | [] | [
"boost_python",
"c++",
"python"
] | stackoverflow_0006128373_boost_python_c++_python.txt |
Q:
ISAAC cipher in python
Does anyone have any working implementations of the ISAAC cipher in python?
I tried to find this, but it seems no one ever did it.
Thanks.
A:
I read some code examples on the ISAAC home page and the code appears straightforward to implement. If you need it in pure Python there are several ... | ISAAC cipher in python | Does anyone have any working implementations of the ISAAC cipher in python?
I tried to find this, but it seems no one ever did it.
Thanks.
| [
"I read some code examples on the ISAAC home page and the code appears straightforward to implement. If you need it in pure Python there are several examples in other languages to guide your porting effort.\nAnother way of using isaac() from Python is to build the C code as a shared library and access it via the ct... | [
4
] | [] | [] | [
"encryption",
"python"
] | stackoverflow_0006127076_encryption_python.txt |
Q:
Memory Leaks Comet Server in PHP
Why would a Comet Server like Tornado be especially prone to memory leaks if written in PHP?
Are there genuine weaknesses particular to PHP for implementing a long polling framework/service like Tornado?
Thanks
A:
The gist of it is that PHP was originally written with the intent ... | Memory Leaks Comet Server in PHP | Why would a Comet Server like Tornado be especially prone to memory leaks if written in PHP?
Are there genuine weaknesses particular to PHP for implementing a long polling framework/service like Tornado?
Thanks
| [
"The gist of it is that PHP was originally written with the intent of having a brand new process for every request that you could just throw away once said request ended, at a time where things like Comet and long polling weren't really on the table.\nAs such there are quite a few areas - notably the garbage collec... | [
4
] | [] | [] | [
"comet",
"long_polling",
"php",
"python",
"tornado"
] | stackoverflow_0006131620_comet_long_polling_php_python_tornado.txt |
Q:
Python TKinter text variable
I get this error :
mySocket.send ( userInput )
TypeError: must be string or buffer, not instance
userInput = StringVar()
e = Entry(gui, textvariable=userInput)
e.pack()
def sendPacket():
mySocket = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
mySocket.connect ( ( 'CENSORED', 2727... | Python TKinter text variable | I get this error :
mySocket.send ( userInput )
TypeError: must be string or buffer, not instance
userInput = StringVar()
e = Entry(gui, textvariable=userInput)
e.pack()
def sendPacket():
mySocket = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
mySocket.connect ( ( 'CENSORED', 2727 ) )
mySocket.send ( userInput )
| [
"My tkinter is a bit rusty, but I think it's a simple oversight -- you need to call the StringVar.get() method to return it as an actual string, rather than referencing the StringVar object instance.\nmySocket.send ( userInput.get() )\n\n"
] | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006132264_python_tkinter.txt |
Q:
Create python string with fill char and counter
I'd like to do it in an elegant fashion:
>>> ''.zfill(5, '-')
'-----'
There's any way to initialize a string with a fill char and a counter?
Of course, count may vary.
A:
Just try:
>>> '-'*5
'-----'
It's that simple in Python :)
A:
The introduction to strings i... | Create python string with fill char and counter | I'd like to do it in an elegant fashion:
>>> ''.zfill(5, '-')
'-----'
There's any way to initialize a string with a fill char and a counter?
Of course, count may vary.
| [
"Just try:\n>>> '-'*5\n'-----'\n\nIt's that simple in Python :)\n",
"The introduction to strings in the \"official\" tutorial says:\n\nStrings can be concatenated (glued\n together) with the + operator, and\n repeated with *\n\n"
] | [
13,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0006132048_python_string.txt |
Q:
Python DB Connection Error
I'm trying example listed in How do I connect to a MySQL Database in Python?
When I try to execute the program in Python 3.0 GUI I receive error for last print statement
for x in range(0,numrows):
row = cursor.fetchone()
print row[0], "-->", row[1]
Error is Invalid Syntax for row[0]
An... | Python DB Connection Error | I'm trying example listed in How do I connect to a MySQL Database in Python?
When I try to execute the program in Python 3.0 GUI I receive error for last print statement
for x in range(0,numrows):
row = cursor.fetchone()
print row[0], "-->", row[1]
Error is Invalid Syntax for row[0]
Any Pointers would be helpful.
Tha... | [
"in python3 print is a function, so it's print(row[0]+\"-->\"+row[1])\n"
] | [
4
] | [] | [] | [
"python",
"syntax_error"
] | stackoverflow_0006132518_python_syntax_error.txt |
Q:
python: Detecting a negative number within a string
So I have a number of text files with a line like this:
STRT .M -9.0: START DEPTH
I wish to detect the negative number and replace it with 0.1.
I can detect the negative number, simply by looking for the '-'
text.count('-')
if text.count('-') >... | python: Detecting a negative number within a string | So I have a number of text files with a line like this:
STRT .M -9.0: START DEPTH
I wish to detect the negative number and replace it with 0.1.
I can detect the negative number, simply by looking for the '-'
text.count('-')
if text.count('-') > 0, there is a negative number.
My question is: How do I ... | [
"The simple solution is to user .replace('-9.0','0.1') (see documentation for .replace()), but I think you need more flexible solution based on regular expressions:\nimport re\nnew_string = re.sub(r'-\\d+\\.\\d+', '0.1', your_string)\n\n",
"Looks like you are working with LAS files. You can check out libLAS to se... | [
6,
4,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0006132626_python_string.txt |
Q:
django 'module' object has no attribute 'StringProperty'
I'm just starting... I'm trying to use Django models but I'm getting the:
AttributeError: 'module' object has no attribute 'StringProperty'
Can you please tell where can be the issue?
from django.db import models
# Create your models here.
class Test(models... | django 'module' object has no attribute 'StringProperty' | I'm just starting... I'm trying to use Django models but I'm getting the:
AttributeError: 'module' object has no attribute 'StringProperty'
Can you please tell where can be the issue?
from django.db import models
# Create your models here.
class Test(models.Model):
text = models.StringProperty()
date = models.... | [
"Your problem is you've got some bogus model field types. Here are the correct ones for django (read about them and other available field types in the django model field reference docs)\nfrom django.db import models\n\n# Create your models here.\nclass Test(models.Model):\n text = models.CharField(max_length=255... | [
1
] | [] | [] | [
"attributeerror",
"django_models",
"python"
] | stackoverflow_0006132695_attributeerror_django_models_python.txt |
Q:
Unable to replicate examples of running ironpython in browser with silverlight
Basically i am following this tutorial: http://blog.jimmy.schementi.com/2010/03/pycon-2010-python-in-browser.html
According to it, this code should run fine:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/htm... | Unable to replicate examples of running ironpython in browser with silverlight | Basically i am following this tutorial: http://blog.jimmy.schementi.com/2010/03/pycon-2010-python-in-browser.html
According to it, this code should run fine:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript"
src="htt... | [
"It's failing to download repl.py; looks like a bug as it's falling back to the DOM downloader when doing cross-domain downloads, but throws. As a work-around copy it to your web-server as well; here's it working: http://www.schementi.com/silverlight/Sunny88.html.\nAlso, locally you must run under a local web-serve... | [
1
] | [] | [] | [
"client_side",
"ironpython",
"python",
"silverlight"
] | stackoverflow_0006117834_client_side_ironpython_python_silverlight.txt |
Q:
Python/Django iterating over one list, while checking inside Object
What would the cleanest way to the following pseudocode be?
class Player
id
name
class Participant (is a subset of Player with an added status)
player_id (ForeignKey to Player)
status
So you can have a list of Players (Wayne, Chuck,... | Python/Django iterating over one list, while checking inside Object | What would the cleanest way to the following pseudocode be?
class Player
id
name
class Participant (is a subset of Player with an added status)
player_id (ForeignKey to Player)
status
So you can have a list of Players (Wayne, Chuck, Bobby)
And then a list of Participants (Wayne(status:YES), Bobby(status... | [
"add in another loop\nplayer_list = list with Player objects\nparticipant_list = list with Participant objects\n\nfor player in player_list:\n for participant in participant_list:\n if player == participant.player:\n print participant.status\n break\n\nNot the prettiest solution but ... | [
3,
2,
2,
0
] | [
"or i think you can also do:\nplayer_list = list with Player objects\nparticipant_list = list with Participant objects\n\nfor player, participant in zip(player_list, participant_list):\n if player == participant.player:\n print participant.status\n break\n\nbut both player_list and particip... | [
-1
] | [
"django",
"python"
] | stackoverflow_0006119384_django_python.txt |
Q:
Confused situation with Mercurial
I'm in this situation:
First of all I just started to use mercurial.
I've a server where there's a my django project.
I want to clone repository from the project dir on server in my local computer.
I've done this:
user@host> cd myproject
user@host> hg init
user@host> hg add
user@h... | Confused situation with Mercurial | I'm in this situation:
First of all I just started to use mercurial.
I've a server where there's a my django project.
I want to clone repository from the project dir on server in my local computer.
I've done this:
user@host> cd myproject
user@host> hg init
user@host> hg add
user@host> hg commit -m "Added initial files.... | [
"It doesn't answer your question directly, but I've found a good way to manage local settings is by putting them in a separate file (ignored by your SCM) and loading them in settings.py.\nFor example, put this at the bottom of settings.py:\n try:\n import settings_local\n except ImportError:\n pass # Ignore wh... | [
3,
2,
1
] | [] | [] | [
"django",
"mercurial",
"python"
] | stackoverflow_0006133196_django_mercurial_python.txt |
Q:
What does this Python cProfile output mean?
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 65.417 65.417 <string>:1(<module>)
1 43.675 43.675 65.417 65.417 primenumber_o.py:3(main)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.... | What does this Python cProfile output mean? | ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 65.417 65.417 <string>:1(<module>)
1 43.675 43.675 65.417 65.417 primenumber_o.py:3(main)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
99999 21.742 0.000 21.7... | [
"The third line is all of the code in the file that isn't range().\n",
"I haven't used cProfile, but it looks to me that it assigns runtime into buckets based on function names. 21 seconds is being used by the built-in function range() in the for statement. The other 43 seconds isn't in a separate, named function... | [
1,
0
] | [] | [] | [
"cprofile",
"profiling",
"python"
] | stackoverflow_0006133716_cprofile_profiling_python.txt |
Q:
python web parser
I would like to parse a particular database on the web. I would also like to store elements of that database in an online MySQL db.
Why this isn't obvious to me: not sure what language to use, should I be looking at Rails instead of command line python
This is probably the first step in several q... | python web parser | I would like to parse a particular database on the web. I would also like to store elements of that database in an online MySQL db.
Why this isn't obvious to me: not sure what language to use, should I be looking at Rails instead of command line python
This is probably the first step in several question, but I suspect ... | [
"I would suggest learning to program and find a language that you are comfortable in. Then after you know some general principals or Ruby, Python or any other language you should be comfortable tackling this on your own. It just seems to me that you are trying to run before you know how to walk so to speak and if y... | [
0
] | [] | [] | [
"database",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0006133544_database_python_ruby_ruby_on_rails.txt |
Q:
Python tuple unpack problem
sendnpc = (npc2alive,Orinpc3,Posnpc3)
Data = dumps((PosYou,OriYou,Shoot,txtt,Posnpc,Orinpc,npcalive,Posnpc2,Orinpc2,sendnpc))
I'm sending this material to another computer, the problem is when I'm unpacking it.
The unpacking part of the script looks like this:
Data, SRIP = GameLogic... | Python tuple unpack problem | sendnpc = (npc2alive,Orinpc3,Posnpc3)
Data = dumps((PosYou,OriYou,Shoot,txtt,Posnpc,Orinpc,npcalive,Posnpc2,Orinpc2,sendnpc))
I'm sending this material to another computer, the problem is when I'm unpacking it.
The unpacking part of the script looks like this:
Data, SRIP = GameLogic.sClient.recvfrom(1024)
UPData = ... | [
"Nest the LHS tuples.\n>>> a, b, (c, d, e) = [1, 2, [3, 4, 5]]\n>>> a\n1\n>>> b\n2\n>>> c\n3\n>>> d\n4\n>>> e\n5\n\n",
"I notice that in most cases, the position comes before the orientation. But, in that last tuple, you have the orientation before the position: (npc2alive,Orinpc3,Posnpc3). When you unpack it, yo... | [
1,
1
] | [] | [] | [
"iterable_unpacking",
"python"
] | stackoverflow_0006134318_iterable_unpacking_python.txt |
Q:
Extract ID3 tags of a MP3 URL using python
I am developing a python program which can extract ID3 tags of mp3 files. I am using urllib2 for checking MIME type of the URL (if it is audio/mpeg), after that I need to find information about this MP3 file.
Problem is, I dont want to load that Mp3 file completely in my ... | Extract ID3 tags of a MP3 URL using python | I am developing a python program which can extract ID3 tags of mp3 files. I am using urllib2 for checking MIME type of the URL (if it is audio/mpeg), after that I need to find information about this MP3 file.
Problem is, I dont want to load that Mp3 file completely in my PC, I just want to extract ID3 tags? so is it po... | [
"You can do a partial download: Download file using partial download (HTTP) (if the server supports it)\non rereading, and seeing joelhardi's comment, this is even easier:\njcomeau@intrepid:/tmp$ python\nPython 2.6.6 (r266:84292, Apr 20 2011, 11:58:30) \n[GCC 4.5.2] on linux2\nType \"help\", \"copyright\", \"credit... | [
3
] | [] | [] | [
"id3",
"mime_types",
"python",
"url",
"urllib2"
] | stackoverflow_0006134521_id3_mime_types_python_url_urllib2.txt |
Q:
Why does strip() fix this pexpect script?
I have an object.
This object has a connect() method which spawns a pexpect process.
The process that's spawned is a custom serial interface. On launch, this tool prints a menu of serial devices to connect to, like so:
libftdi device (0): A6005jpt
libftdi device (1): acFX9... | Why does strip() fix this pexpect script? | I have an object.
This object has a connect() method which spawns a pexpect process.
The process that's spawned is a custom serial interface. On launch, this tool prints a menu of serial devices to connect to, like so:
libftdi device (0): A6005jpt
libftdi device (1): acFX9DQf
Serial device (a) : /dev/cu.Bluetooth-PDA-S... | [
"I'm guessing you're getting a TIMEOUT exception. Based on where the \"MATCHED A DEVICE LINE!\" message is in the output, my hypothesis is that the spawn instance has multiple lines when it tests for a match. When pexpect compiles the regexes, it sets re.DOTALL, so the .* includes the newline and the additional lin... | [
1
] | [] | [] | [
"expect",
"pexpect",
"python",
"regex"
] | stackoverflow_0006132858_expect_pexpect_python_regex.txt |
Q:
ImportError: No module named mysql.base, in django project on Ubuntu 11.04 server
I am following the steps in the Django Book and got to the part where the authors explain hot wo set up a django project to use a database. I chose mysql.
My settings in settings.py are:
DATABASES = {
'default': {
'ENGINE... | ImportError: No module named mysql.base, in django project on Ubuntu 11.04 server | I am following the steps in the Django Book and got to the part where the authors explain hot wo set up a django project to use a database. I chose mysql.
My settings in settings.py are:
DATABASES = {
'default': {
'ENGINE': 'mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
... | [
"The correct database setting is 'django.db.backends.mysql'.\n"
] | [
18
] | [] | [] | [
"django",
"mysql",
"mysql_python",
"python"
] | stackoverflow_0006132181_django_mysql_mysql_python_python.txt |
Q:
Python optparse is not able to parse the `$` symbol
if I am using a $ symbol in the arguments, python optparse is not able to parse it properly. It just ignores the symbol and the next character. If I am giving a \ before $ then it is working fine. But I don't want to give a \. Please help me out how to overcome t... | Python optparse is not able to parse the `$` symbol | if I am using a $ symbol in the arguments, python optparse is not able to parse it properly. It just ignores the symbol and the next character. If I am giving a \ before $ then it is working fine. But I don't want to give a \. Please help me out how to overcome this situation.
Its happening only in Linux; on Windows it... | [
"I think that this happens because Linux uses $ to identify shell variables.\nSo, if you want to use this symbole in your arguments, your only chance is to pass '\\$', that won't be replaced by the invoking shell. Windows uses %variablename% to identify that kind of variables, that's why you don't experience this k... | [
4
] | [] | [] | [
"optparse",
"python"
] | stackoverflow_0006134642_optparse_python.txt |
Q:
Caught IOError while rendering: 'No such file or directory' Error when trying to view images
I'm getting the error above when trying to display thumbnails of larger images. Full size images work fine.
Here is the code for the image definitions in the models.py file.
def _get_thumb_url(self, folder, size):
... | Caught IOError while rendering: 'No such file or directory' Error when trying to view images | I'm getting the error above when trying to display thumbnails of larger images. Full size images work fine.
Here is the code for the image definitions in the models.py file.
def _get_thumb_url(self, folder, size):
""" get a thumbnail giver a folder and a size. """
if not self.coverart:
r... | [
"I think im.save doesn't create directories if they don't exist. It's better to create empty file with desired path, open it and then save your image to it.\n"
] | [
0
] | [] | [] | [
"django",
"pinax",
"python"
] | stackoverflow_0006134883_django_pinax_python.txt |
Q:
Slicing the prefix from the stem in Python
I want to slice the affixes from stem. I tried the suffixes with the following command and it was OK for 'dishes'. However when I want to do it with a prefix (for example, 'undo'), how can I define the prefix in Python to get the result of un-do?
>>> def stem(word):
f... | Slicing the prefix from the stem in Python | I want to slice the affixes from stem. I tried the suffixes with the following command and it was OK for 'dishes'. However when I want to do it with a prefix (for example, 'undo'), how can I define the prefix in Python to get the result of un-do?
>>> def stem(word):
for suffix in ['ing', 'lity', 'es']:
if w... | [
"Well, why not use regulare expressions the same way you did ?\n>>> re.findall(r'^(un|ir)(.*)$', 'undo')\n[('un', 'do')]\n\n"
] | [
2
] | [] | [] | [
"prefixes",
"python",
"slice"
] | stackoverflow_0006134831_prefixes_python_slice.txt |
Q:
Macport Python with PyObj and XCode
How can I get the Macport Python version to work with XCode? Which Python.framework do I have to choose?
A:
Perhaps take a look here: < https://superuser.com/questions/35256/how-can-i-change-the-default-python-version-on-snow-leopard >. The final solution mentions using python... | Macport Python with PyObj and XCode | How can I get the Macport Python version to work with XCode? Which Python.framework do I have to choose?
| [
"Perhaps take a look here: < https://superuser.com/questions/35256/how-can-i-change-the-default-python-version-on-snow-leopard >. The final solution mentions using python_select. Assuming you install different versions of Python in a standard way, this will let you switch between them and then Xcode should respect ... | [
1
] | [] | [] | [
"pyobjc",
"python",
"xcode"
] | stackoverflow_0002404505_pyobjc_python_xcode.txt |
Q:
matplotlib navtoolbar doesn't realize in wx 2.9 (Mac OS X)
The following piece of code produces a matplotlib NavToolbar2 at the top of a frame as expected when run on wxPython 2.8.x, Python 2.5.4/2.6, Matplotlib 0.99.x.
However, I've recently moved to Python 2.7, and wxPython 2.9.1 in an attempt to support OS X in... | matplotlib navtoolbar doesn't realize in wx 2.9 (Mac OS X) | The following piece of code produces a matplotlib NavToolbar2 at the top of a frame as expected when run on wxPython 2.8.x, Python 2.5.4/2.6, Matplotlib 0.99.x.
However, I've recently moved to Python 2.7, and wxPython 2.9.1 in an attempt to support OS X in 64-bit. It's under this environment that the code below produce... | [
"It seems like a bug, but I do not know if the problem lies in matplotlib, in wxPython or in the backend_wx.py. What I did to fix it is that I looked in the backend_wx.py source code for the Toolbar and put it directly in my wxPython toolbar. So this works for me:\nimport os\nimport wx\nfrom matplotlib.backends.bac... | [
4
] | [] | [] | [
"matplotlib",
"python",
"toolbar",
"wxpython"
] | stackoverflow_0006124419_matplotlib_python_toolbar_wxpython.txt |
Q:
How to debug Python import failure
I have a directory structure:
network/__init__.py
network/model.py
network/transformer/__init__.py
network/transformer/t_model.py
both __init__.py files have appropriate
__all__ = [
"model", # or "t_model" in the case of transformer
"view",
]
In t_model.py, I have
... | How to debug Python import failure | I have a directory structure:
network/__init__.py
network/model.py
network/transformer/__init__.py
network/transformer/t_model.py
both __init__.py files have appropriate
__all__ = [
"model", # or "t_model" in the case of transformer
"view",
]
In t_model.py, I have
from .. import model
but it says:
Impor... | [
"This works for me. Can you run/import model.py? If it has syntax errors you can't import it. (In general I recommend not to do relative imports, the use of them is limited).\nYour absolute import is very confusing. The way to do an absolute import in this package is:\nfrom network model import Node\n\nThis works f... | [
4,
0
] | [] | [] | [
"import",
"python",
"python_import"
] | stackoverflow_0006134146_import_python_python_import.txt |
Q:
In PyGTK, what is a simple way to show a PNG file?
The following PyGTK code displays a PNG file in a window.
Is there a simpler or better way of displaying the PNG file, like, by using a gtk.DrawingArea? For example, how do you resize the file?
import gtk
import pygtk
pygtk.require('2.0')
class Gui:
def __in... | In PyGTK, what is a simple way to show a PNG file? | The following PyGTK code displays a PNG file in a window.
Is there a simpler or better way of displaying the PNG file, like, by using a gtk.DrawingArea? For example, how do you resize the file?
import gtk
import pygtk
pygtk.require('2.0')
class Gui:
def __init__(self):
# Create an Image object for a PNG ... | [
"You should call directly image.set_from_file instead of creating a pixbuf and a pixmap. As to handle resizing, I did it once by using directly a gtk.DrawingArea, using the configure signal to get the height and width of the drawing area, and the expose-event event to paint it with cairo on the whole surface. But t... | [
6
] | [] | [] | [
"gtk",
"gtk2",
"png",
"pygtk",
"python"
] | stackoverflow_0006125902_gtk_gtk2_png_pygtk_python.txt |
Q:
python: Selective redirection of stdout to a file
I am using python's module called dis for analysis of bytecode. By default dis will send the output to the screen. I would like to re-direct the output of dis to a file without modifying dis module. The problem is, i call dis from within a long program after some c... | python: Selective redirection of stdout to a file | I am using python's module called dis for analysis of bytecode. By default dis will send the output to the screen. I would like to re-direct the output of dis to a file without modifying dis module. The problem is, i call dis from within a long program after some condition is true. I will give an example!
class foo(obj... | [
"You can set and reset sys.stdout before and after calling dis routines:\nsys.stdout = dis_output_file\ndis.dis(method1)\ndis.dis(method2)\nsys.stdout = sys.__stdout__\n\nsys.__stdout__ always refers to the actual standard output of your application.\nOf course, if you are using multiple threads, this approach woul... | [
5
] | [] | [] | [
"python",
"stdout"
] | stackoverflow_0006135617_python_stdout.txt |
Q:
For loops and multiple conditions
In C++, it's possible to say:
for (int i = 0; i < 100 && !found; i++) {
if (items[i] == "the one I'm looking for")
found = true;
}
so you don't need to use the "break" statement.
In Python, I guess you need to write:
found = False
for item in items:
if item == "the one... | For loops and multiple conditions | In C++, it's possible to say:
for (int i = 0; i < 100 && !found; i++) {
if (items[i] == "the one I'm looking for")
found = true;
}
so you don't need to use the "break" statement.
In Python, I guess you need to write:
found = False
for item in items:
if item == "the one I'm looking for"
found = True
... | [
">>> from itertools import dropwhile\n>>> try:\n... item = next(dropwhile(lambda x: x!=\"the one I'm looking for\", items))\n... found = True\n... except:\n... found = False\n\nOf course you can also write this without the lambda function as\n>>> from itertools import dropwhile\n>>> try:\n... item =... | [
6,
3,
2,
1,
0
] | [] | [] | [
"conditional_statements",
"loops",
"python"
] | stackoverflow_0006133753_conditional_statements_loops_python.txt |
Q:
2 similar looking "update" variants work different
Here is snapshot #1:
strr = "UPDATE fileinfo SET file_name = ? WHERE md5sum = ?"
cr.execute(strr, ( rec[0], rec[1]) )
and #2:
strr = "UPDATE fileinfo SET file_name = {0} WHERE md5sum = {1}".format(rec[0], rec[1])
cr.execute(strr)
The first one works fine while t... | 2 similar looking "update" variants work different | Here is snapshot #1:
strr = "UPDATE fileinfo SET file_name = ? WHERE md5sum = ?"
cr.execute(strr, ( rec[0], rec[1]) )
and #2:
strr = "UPDATE fileinfo SET file_name = {0} WHERE md5sum = {1}".format(rec[0], rec[1])
cr.execute(strr)
The first one works fine while the second one fails. It throws
sqlite3.OperationalError... | [
"The two variants you show are very different. In the first, you are using the database api to fill in the parameters - the values are being properly escaped.\nIn the second variant, you just use pythons string formatting to add the variables to the SQL string - values are not escaped and depending on the contents ... | [
1,
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0006135329_python_sqlite.txt |
Q:
question for python experts: code doesn't work when called with generators
I have a small snippet that does not work in an inexplicable way.
The purpose is to generate all combinations of two or more sequences.
It works when called with lists, but it doesn't when called with generators.
def comb(seqs):
if seqs... | question for python experts: code doesn't work when called with generators | I have a small snippet that does not work in an inexplicable way.
The purpose is to generate all combinations of two or more sequences.
It works when called with lists, but it doesn't when called with generators.
def comb(seqs):
if seqs:
for item in seqs[0]:
for rest in comb(seqs[1:]):
... | [
"A generator is exhausted once it has generated everything that it is going generate whereas a list can be iterated through multiple times.\nYour comb generator relies on being able to iterate through the second and later sequences that it is passed multiple times so won't work if these sequences are actually a gen... | [
7,
2,
2,
0
] | [] | [] | [
"generator",
"python"
] | stackoverflow_0006135750_generator_python.txt |
Q:
Find the sum of subsets of a list in python
This is probably very simple and I'm overlooking something...
I have a long list of integers, in this case representing daily visitors to a website. I want a new list of weekly visitors. So I need to get groups of seven from the original list, sum them, and add them to... | Find the sum of subsets of a list in python | This is probably very simple and I'm overlooking something...
I have a long list of integers, in this case representing daily visitors to a website. I want a new list of weekly visitors. So I need to get groups of seven from the original list, sum them, and add them to a new list.
My solution seems pretty brute force... | [
"weekly = [ sum(visitors[x:x+7]) for x in range(0, len(daily), 7)]\n\nOr slightly less densely:\nweekly = []\nfor x in range(0, len(daily), 7):\n weekly.append( sum(visitors[x:x+7]) )\n\nAlternatively, using the numpy module.\nby_week = numpy.reshape(visitors, (7, -1))\nweekly = numpy.sum( by_week, axis = 1)\n\... | [
15,
0,
0
] | [] | [] | [
"chunks",
"list",
"python"
] | stackoverflow_0006133434_chunks_list_python.txt |
Q:
Repeated Function Application
I'm having trouble with a question which follows: Write a recursive function repeatedlyApply that takes as arguments a function
f of one argument and a positive integer n. The result of repeatedlyApply is a function of one argument that applies f to that argument n times.
So, for exa... | Repeated Function Application | I'm having trouble with a question which follows: Write a recursive function repeatedlyApply that takes as arguments a function
f of one argument and a positive integer n. The result of repeatedlyApply is a function of one argument that applies f to that argument n times.
So, for example, we would have
repeatedlyApp... | [
"Correct answer is:\ndef recApply(func, n):\n if n > 1:\n rec_func = recApply(func, n - 1)\n return lambda x: func(rec_func(x))\n return func\n\nAnd the output:\n>>>> print recApply(lambda x: x+1,10)(100)\n110\n\n",
"I have a solution based on lambdas:\n>>> f = lambda x: x + 10\n>>> iterate = ... | [
4,
3,
3,
0
] | [] | [] | [
"lambda",
"python",
"recursion"
] | stackoverflow_0006135432_lambda_python_recursion.txt |
Q:
CSV file Read in Python
I have two type of csv's having data like:
Format 1 read from csv created from spreadsheet having two coloums.
datas = [[u'Woeoe;"ww@w.com"'], [u'wqqq;"Ww2@2.com"'], [u'Asasasa;"122@22.co.in"']]
format 2 read from the csv created from text editor save as .csv and having data like
fname l... | CSV file Read in Python | I have two type of csv's having data like:
Format 1 read from csv created from spreadsheet having two coloums.
datas = [[u'Woeoe;"ww@w.com"'], [u'wqqq;"Ww2@2.com"'], [u'Asasasa;"122@22.co.in"']]
format 2 read from the csv created from text editor save as .csv and having data like
fname lname,email@email.com
fname1 l... | [
"The first file use \";\" as delimiter. So, you just have to say it to the reader.\nTry to read the first file with csv.reader(input, quotechar='\"', delimiter=';')\n"
] | [
2
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0006136154_csv_python.txt |
Q:
cleaning my list
Hello I have a loop which goes counts different records in my MySQL database and then saves the numbers to a list. Here is the list:
[1L, 2L, 2L, 5L, 4L, 1L, 1L, 1L, 3L, 1L, 1L, 2L, 2L, 3L, 3L, 1L, 2L, 4L, 2L, 1L, 3L, 1L, 2L, 4L, 1L, 2L, 1L, 1L, 3L, 1L, 3L, 1L, 5L, 2L, 1L, 1L, 5L, 1L, 1L, 1L, 4L, ... | cleaning my list | Hello I have a loop which goes counts different records in my MySQL database and then saves the numbers to a list. Here is the list:
[1L, 2L, 2L, 5L, 4L, 1L, 1L, 1L, 3L, 1L, 1L, 2L, 2L, 3L, 3L, 1L, 2L, 4L, 2L, 1L, 3L, 1L, 2L, 4L, 1L, 2L, 1L, 1L, 3L, 1L, 3L, 1L, 5L, 2L, 1L, 1L, 5L, 1L, 1L, 1L, 4L, 2L, 1L, 3L, 2L, 1L, 2L... | [
"Just put it in a set.\n>>> foo = [1,1,1,2,2,3,3,4,1,4,3,6,5,6]\n>>> set(foo)\nset([1, 2, 3, 4, 5, 6])\n\nThis will automatically filter out all duplicates. Maybe you can even skip the list, and put it in a set in the first place.\n",
"You might fall into problem such as:\nlist = [1,2,3,4]\nfor l in list:\n pr... | [
7,
0
] | [] | [] | [
"loops",
"nested_lists",
"python"
] | stackoverflow_0006136608_loops_nested_lists_python.txt |
Q:
Clutter - run method at marker?
Markers seem to be designed to run a timeline at a point in another timeline. Is there any way to run an ordinary method at a marker, rather than a timeline?
A:
no, markers on ClutterTimeline can run any function. just use the ClutterTimeline::marker-reached signal. if you are int... | Clutter - run method at marker? | Markers seem to be designed to run a timeline at a point in another timeline. Is there any way to run an ordinary method at a marker, rather than a timeline?
| [
"no, markers on ClutterTimeline can run any function. just use the ClutterTimeline::marker-reached signal. if you are interested in a specific marker, you can detail the signal using the marker name, e.g.:\ng_signal_connect (timeline, \"marker-reached::my-marker\",\n G_CALLBACK (on_my_marker_reache... | [
1
] | [] | [] | [
"clutter",
"python"
] | stackoverflow_0005716563_clutter_python.txt |
Q:
Counting backwards
I've got a list organized like this :
[('down', 0.0098000000000000309),
('up', 0.0015000000000000568),
('down', 0.008900000000000019),
('down', 0.023300000000000098),
('down', 0.011599999999999944),
('down', 0.0027000000000000357),
('up', 0.0023999999999999577),
('up', 0.00650000000000006... | Counting backwards | I've got a list organized like this :
[('down', 0.0098000000000000309),
('up', 0.0015000000000000568),
('down', 0.008900000000000019),
('down', 0.023300000000000098),
('down', 0.011599999999999944),
('down', 0.0027000000000000357),
('up', 0.0023999999999999577),
('up', 0.0065000000000000613),
('down', 0.0057000... | [
"Create a sliding window, and test on that:\ndef slidingwindow(iterable):\n iterator = iter(iterable)\n first, second = iterator.next(), iterator.next()\n for next in iterator:\n yield (first, second, next)\n first, second = second, next\n\ndef testforcondition(data):\n for window in slidi... | [
5,
3,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006136716_python.txt |
Q:
Escaping escape sequence in Python
I am kind of new to python. Goal is to execute a shell command using subprocess parse & retrive the printed output from shell. The execution errors out as shown in the sample output msg below. Also shown below is the sample code snippet
Code snippet:
testStr = "cat tst.txt | gre... | Escaping escape sequence in Python | I am kind of new to python. Goal is to execute a shell command using subprocess parse & retrive the printed output from shell. The execution errors out as shown in the sample output msg below. Also shown below is the sample code snippet
Code snippet:
testStr = "cat tst.txt | grep Location | sed -e '/.*Location: //g' "... | [
"I suppose your main error is not python related. To be more precise, there are 3 of them:\n\nYou forgot to import subprocess.\nIt should be sed -e 's/.*Location: //g'. You wrote ///g instead of s///g.\ntst.txt does not exist.\n\n",
"You should be passing testStr directly as the first argument, rather than enclos... | [
1,
1
] | [] | [] | [
"escaping",
"python",
"unicode_escapes"
] | stackoverflow_0006136504_escaping_python_unicode_escapes.txt |
Q:
Expat xml parser in python
When using expat xml parser in python, how can I get it store the parsed the xml data in a string or in a file or in any data structure. Please show me a way to accomplish how to parse and use the nodes of the xml data.
A:
Why are you using a low-level interface like the expat parser w... | Expat xml parser in python | When using expat xml parser in python, how can I get it store the parsed the xml data in a string or in a file or in any data structure. Please show me a way to accomplish how to parse and use the nodes of the xml data.
| [
"Why are you using a low-level interface like the expat parser when you can use xml.etree.[c]ElementTree? It creates a tree of elements (nodes) for you. Elements have tag, text, and tail attributes and contain a dict that maps attribute names to values, and a list of child elements.\nHave a look at the Python docum... | [
7
] | [] | [] | [
"expat_parser",
"python",
"xml_parsing"
] | stackoverflow_0006136515_expat_parser_python_xml_parsing.txt |
Q:
Pyenchant Module - Spell checker
How do I trim the output of Python Pyenchat Module's 'suggested words list ?
Quite often it gives me a huge list of 20 suggested words that looks awkward when displayed on the screen and also has a tendency to go out of the screen .
A:
Like sentinel, I'm not sure if the problem ... | Pyenchant Module - Spell checker | How do I trim the output of Python Pyenchat Module's 'suggested words list ?
Quite often it gives me a huge list of 20 suggested words that looks awkward when displayed on the screen and also has a tendency to go out of the screen .
| [
"Like sentinel, I'm not sure if the problem you're having is specific to pyenchant or a python-familiarity issue. If I assume the latter, you could simply select the number of values you'd like as part of your program. In simple form, this could be as easy as:\nsuggestion_list = pyenchant_function(document_filled... | [
1,
0
] | [] | [] | [
"pyenchant",
"python"
] | stackoverflow_0006136315_pyenchant_python.txt |
Q:
Rounded division by power of 2
I'm implementing a quantization algorithm from a textbook. I'm at a point where things pretty much work, except I get off-by-one errors when rounding. This is what the textbook has to say about that:
Rounded division by 2^p may be carried out by adding an offset and right-shifting... | Rounded division by power of 2 | I'm implementing a quantization algorithm from a textbook. I'm at a point where things pretty much work, except I get off-by-one errors when rounding. This is what the textbook has to say about that:
Rounded division by 2^p may be carried out by adding an offset and right-shifting by p bit positions
Now, I get the ... | [
"The shift will truncate. The shift is a binary operator operating. I'm using square brackets to denote the base here:\n196605[10] = 101111111111111111[2]\n101111111111111111[2] >> 16[10] = 10[2] = 2[10]\n\nTo perform correct rounding you need to add half of your divisor before doing the shift.\n101111111111111111[... | [
10,
4,
3,
1
] | [] | [] | [
"bit_manipulation",
"bitwise_operators",
"python",
"rounding"
] | stackoverflow_0006135157_bit_manipulation_bitwise_operators_python_rounding.txt |
Q:
File locks in SQLite
I'm writing my first SQLAlchemy (0.6.8)/Python (2.7.1) program, sitting on top of SQLite (3.7.6.3, I think), running on Windows Vista.
In order to perform unit-testing, I am pointing SQLite to a test database, and my unit-test scripts routinely delete the database file, so I am continuously wo... | File locks in SQLite | I'm writing my first SQLAlchemy (0.6.8)/Python (2.7.1) program, sitting on top of SQLite (3.7.6.3, I think), running on Windows Vista.
In order to perform unit-testing, I am pointing SQLite to a test database, and my unit-test scripts routinely delete the database file, so I am continuously working with a known initial... | [
"Someone had a similar problem: http://www.mail-archive.com/sqlalchemy@googlegroups.com/msg20724.html\nYou should use a NullPool at the connection establishement to ensure that no active connection stay after session.close() \nfrom sqlalchemy import create_engine\nfrom sqlalchemy.pool import NullPool\n\nto_engine =... | [
5,
1
] | [] | [] | [
"python",
"sqlalchemy",
"sqlite"
] | stackoverflow_0006134980_python_sqlalchemy_sqlite.txt |
Q:
Variable names with dictionaries?
Python beginner here. A question about dictionaries.
My input is a variable length list (eg a = ['eggs', 'ham', 'bacon'...] ) which functions as a list of search terms to be used on an imported CSV file.
I have defined four functions that match each term to various values from sai... | Variable names with dictionaries? | Python beginner here. A question about dictionaries.
My input is a variable length list (eg a = ['eggs', 'ham', 'bacon'...] ) which functions as a list of search terms to be used on an imported CSV file.
I have defined four functions that match each term to various values from said CSV file. So, each input term will re... | [
"Not an approach I'd recommend, but you can access both the local and global namespaces as dictionaries; e.g. you can add arbitrary variables to those namespaces using the familiar dict interface:\n>>> globals()['foo'] = 'bar'\n>>> foo\n'bar'\n>>> locals()['spam'] = 'eggs'\n>>> spam\n'eggs'\n\nYou will run into nam... | [
4,
2,
2
] | [] | [] | [
"dictionary",
"nested_lists",
"python"
] | stackoverflow_0006137853_dictionary_nested_lists_python.txt |
Q:
SqlAlchemy: Check if one object is in any relationship (or_(object.relationship1.contains(otherObject), object.relationship2.contains(otherObject))
Let's say I have a class like this:
class Foo(declarativeBase):
bars1 = relationship(Bar.Bar, secondary=foos_to_bars1, collection_class=set())
bars2 = relati... | SqlAlchemy: Check if one object is in any relationship (or_(object.relationship1.contains(otherObject), object.relationship2.contains(otherObject)) | Let's say I have a class like this:
class Foo(declarativeBase):
bars1 = relationship(Bar.Bar, secondary=foos_to_bars1, collection_class=set())
bars2 = relationship(Bar.Bar, secondary=foos_to_bars2, collection_class=list())
(Each of the relationships gives me "Bar"s with a certain conditions). At a certain po... | [
"You are right, session.query(Foo).filter(Foo.bars1.contains(bar)|Foo.bars2.contains(bar)) produces the following SQL:\nSELECT \"Foo\".id AS \"Foo_id\" \nFROM \"Foo\", foos_to_bars1 AS foos_to_bars1_1, foos_to_bars2 AS foos_to_bars2_1 \nWHERE \"Foo\".id = foos_to_bars1_1.foo AND ? = foos_to_bars1_1.bar OR \n\"Foo\"... | [
4
] | [] | [] | [
"python",
"relationship",
"sqlalchemy"
] | stackoverflow_0006118783_python_relationship_sqlalchemy.txt |
Q:
Generalized Model in Django
My first question helped me a LOT, so I figured I'd go ahead and ask a second one.
My current (practice) project is to create a generalized model. Here's what I've written so far:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class... | Generalized Model in Django | My first question helped me a LOT, so I figured I'd go ahead and ask a second one.
My current (practice) project is to create a generalized model. Here's what I've written so far:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Block(models.Model):
title =... | [
"Your code seems correct to me. I also worked on a generic class for my project and it was similar to this one. One remark, when you get a block, you should do some type checking to retrieve the class data so, I recommend you to add a field to store its type. e.g:\nclass Block(models.Model):\n title = models.CharF... | [
3
] | [] | [] | [
"django",
"django_models",
"django_views",
"logic",
"python"
] | stackoverflow_0006080500_django_django_models_django_views_logic_python.txt |
Q:
Web sockets / Tornado - Notify client on database update
I'm trying to use a Tornado web socket server to notify my user when changes are made to a database in realtime. I was hoping to use HTML5 web sockets for this, even though most browsers don't support them. None of the demos that come with the Tornado packag... | Web sockets / Tornado - Notify client on database update | I'm trying to use a Tornado web socket server to notify my user when changes are made to a database in realtime. I was hoping to use HTML5 web sockets for this, even though most browsers don't support them. None of the demos that come with the Tornado package use web sockets and they are not mentioned in the documentat... | [
"A Lee's answer is a good one, you probably want socket.io if you need to support older browsers.\nWebsockets are very easy in tornado though:\nimport tornado.websocket\n\n class EchoWebSocket(tornado.websocket.WebSocketHandler):\n def open(self):\n print \"WebSocket opened\"\n\n def on_message(... | [
8,
6,
0
] | [] | [] | [
"python",
"tornado",
"websocket"
] | stackoverflow_0006131915_python_tornado_websocket.txt |
Q:
What is the best REST implemenation when using tornado RequestHandlers
I would like to define a REST API with a general pattern of:
mysite.com/OBJECT_ID/associations
For example:
mysite.com/USER_ID/vacations - manage a users vacation
mysite.com/USER_ID/music - manage music in the user's music library
mysite.com/P... | What is the best REST implemenation when using tornado RequestHandlers | I would like to define a REST API with a general pattern of:
mysite.com/OBJECT_ID/associations
For example:
mysite.com/USER_ID/vacations - manage a users vacation
mysite.com/USER_ID/music - manage music in the user's music library
mysite.com/PLAYLIST_ID/music - manage music in the context of the given playlist
I am u... | [
"First of all, to guard against mysite.com/LOCATION_ID/music I would create differences between all of your id's. For instance, have LOCATION_ID be a 32 character string, and PLAYLIST_ID 34, etc. This way you can check for the string length as soon as the handler is called. \n\nAlternatively, you can use regular ex... | [
2,
2
] | [] | [] | [
"python",
"requesthandler",
"rest",
"tornado"
] | stackoverflow_0005560638_python_requesthandler_rest_tornado.txt |
Q:
Uploading a mysql database to a webserver supporting python
I have a written a very small web-based survey using cgi with python(This is my first web app. ).The questions are extracted from a MySQL database table and the results are supposed to be saved in the same database. I have created the database along with ... | Uploading a mysql database to a webserver supporting python | I have a written a very small web-based survey using cgi with python(This is my first web app. ).The questions are extracted from a MySQL database table and the results are supposed to be saved in the same database. I have created the database along with its table locally. My app works fine on my local computer(localho... | [
"\nIf you have shell access, you can fire up the python interpreter by running python and type import MySQLdb at the >>> prompt. If you get no errors in return, then its installed.\nLikewise, if you have shell access, this page will help you with importing and exporting using the mysql command. I found it by goog... | [
2,
0,
0
] | [] | [] | [
"cpanel",
"database_connection",
"mysql",
"python"
] | stackoverflow_0006139777_cpanel_database_connection_mysql_python.txt |
Q:
Python equivalent of Java's getClass().getFields()
I'm converting a piece of code from Java to Python and I don't know how to translate the following:
Field[] fields = getClass().getFields();
for (int i = 0; i < fields.length; i++ ) {
if (fields[i].getName().startsWith((String) param){ ....
A:
In Pyt... | Python equivalent of Java's getClass().getFields() | I'm converting a piece of code from Java to Python and I don't know how to translate the following:
Field[] fields = getClass().getFields();
for (int i = 0; i < fields.length; i++ ) {
if (fields[i].getName().startsWith((String) param){ ....
| [
"In Python, you can query an object's bindings with __dict__, e.g.:\n>>> class A:\n... def foo(self): return \"bar\"\n...\n>>> A.__dict__\n{'__module__': '__main__', 'foo': <function foo at 0x7ff3d79c>, '__doc__': None}\n\nAlso, this has been asked from a C# standpoint in: How to enumerate an object's propertie... | [
8,
8,
4
] | [] | [] | [
"java",
"python",
"reflection"
] | stackoverflow_0006139588_java_python_reflection.txt |
Q:
Python/Tipfy/Jinja2: ImportError: No module named ext.jinja2
Aloha,
having some spare time and trying out python on app engine as it is much more flexible than java, I wanted to use Tipfy as my webapp framework.
My problem ist, that, whenever I try to import something like jinja2, I get:
from tipfy.ext.jinja2 impo... | Python/Tipfy/Jinja2: ImportError: No module named ext.jinja2 | Aloha,
having some spare time and trying out python on app engine as it is much more flexible than java, I wanted to use Tipfy as my webapp framework.
My problem ist, that, whenever I try to import something like jinja2, I get:
from tipfy.ext.jinja2 import render_response
ImportError: No module named ext.jinja2
I ensu... | [
"In the newest tipfy version (1.0b1), the jinja2 extension is now bundled with tipfy.\nfrom tipfyext import jinja2\n\nAre you using that version? I'm sorry because the documentation is outdated and \ndoesn't reflect this.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python",
"tipfy"
] | stackoverflow_0006139023_google_app_engine_python_tipfy.txt |
Q:
typeerror while retriving cookies in web2py
var websites = new Array("http://www.abc.com","http://www.123.com");
//i am writin cookies like this in javascript in view
var web=websites[1] ;
var exdate=new Date();
exdate.setDate(exdate.getDate() + 24);
var visit= web +" ;expires= "+ exdate.toUTCString();
document.co... | typeerror while retriving cookies in web2py | var websites = new Array("http://www.abc.com","http://www.123.com");
//i am writin cookies like this in javascript in view
var web=websites[1] ;
var exdate=new Date();
exdate.setDate(exdate.getDate() + 24);
var visit= web +" ;expires= "+ exdate.toUTCString();
document.cookie= "mycookie =" + visit;
now while retriving ... | [
"In this case request.cookies is a dictionary, so you must access it as such. As you did:\nvalue=request.cookies(\"mycookie\").value \n\nThis is treating request.cookies as a function, which is why you get a TypeError since it is not a function. To access a value in a dictionary given the key, you can use:\nvalue=... | [
1
] | [] | [] | [
"cookies",
"python",
"web2py"
] | stackoverflow_0006140154_cookies_python_web2py.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.