content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python, create a loop 'For'
With this query i will select so many row in this table x_giolam.
-I want create a 'For' to which sum all 'giolam' with all rows i were select in this query.
cr.execute("""select name,giolam from x_giolam where name=%s"""%(ma_luong)),
i want to create a loop to sum all 'giolam' with r... | Python, create a loop 'For' | With this query i will select so many row in this table x_giolam.
-I want create a 'For' to which sum all 'giolam' with all rows i were select in this query.
cr.execute("""select name,giolam from x_giolam where name=%s"""%(ma_luong)),
i want to create a loop to sum all 'giolam' with rows were select
| [
"You should do that in the query, not in a for loop:\nSELECT name, SUM(giolam) as giolam_sum FROM x_giolam WHERE name=%s GROUP BY name\n\nOr, since you're limiting by name=%s already you don't need the GROUP BY\nSELECT SUM(giolam) as giolam_sum FROM x_giolam WHERE name=%s\n\n",
"As Michael noted, you should calcu... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0008526275_python.txt |
Q:
Python error with debugging
I am very new with Python and I have just received this message while trying to use Visual Studio plugin for Python:
try:
import boinc # getting the exception here
_BOINC_ENABLED = True
except:
_BOINC_ENABLED = False
and this is the error message that I get:
exceptions.Imp... | Python error with debugging | I am very new with Python and I have just received this message while trying to use Visual Studio plugin for Python:
try:
import boinc # getting the exception here
_BOINC_ENABLED = True
except:
_BOINC_ENABLED = False
and this is the error message that I get:
exceptions.ImportError occurred Message: No mod... | [
"problem was that my project was not on the root of my hard drive and \nthe project was inside a folder named in hebrew.\nthe path of the folder containning the project must be in english for it to work\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008493100_python.txt |
Q:
Library to parse SVG in Ruby or Python
SVG is a huge standard, which is based on XML. I have parsed SVG as XML in the past. However, some things are hard.
For example, I would like to know the size of a group. As far as I can tell, this is only possible by recursively stepping through all the children in the grou... | Library to parse SVG in Ruby or Python | SVG is a huge standard, which is based on XML. I have parsed SVG as XML in the past. However, some things are hard.
For example, I would like to know the size of a group. As far as I can tell, this is only possible by recursively stepping through all the children in the group (noting all their transformations) and acc... | [
"In python you have pysvg:\nimport pysvg.parser\n\nsvg = pysvg.parser.parse(<filename>)\nprint svg.get_width(), svg.get_height()\n\n"
] | [
6
] | [] | [] | [
"python",
"ruby",
"svg"
] | stackoverflow_0008534265_python_ruby_svg.txt |
Q:
Python Handling Socketserver request in the Thread
In the next examlpe I have Socket server handled in the thread. In the handle function we create Thread and pass request and client_address.
When we handle the request in run-method of the Thread it's only possible to receive data, but when I try to send somthing ... | Python Handling Socketserver request in the Thread | In the next examlpe I have Socket server handled in the thread. In the handle function we create Thread and pass request and client_address.
When we handle the request in run-method of the Thread it's only possible to receive data, but when I try to send somthing an Exception is raised ([Errno 9] Bad file descriptor)
W... | [
"I think you are looking for ThreadingMixIn:\nfrom SocketServer import TCPServer, ThreadingMixIn\n\nclass MyServerThread(ThreadingMixIn, TCPServer): pass\n\n",
"Your problem is:\nthread1.start()\n\nAbove code is return immediately, MyServerThread.run() run in background. So MyThreadedSocketServerHandler.handle() ... | [
1,
0,
0
] | [] | [] | [
"multithreading",
"python",
"sockets"
] | stackoverflow_0008534651_multithreading_python_sockets.txt |
Q:
How many ways to build a perfectly balanced tree?
The question is, how many ways are there to build a perfectly balanced binary tree with 15 elements?
One possibility would bei 8-4-12-2-6-10-14-1-3-5-7-9-11-13-15..
My idea was to write some code that generates every possible permutation (which would be like.. 15!)... | How many ways to build a perfectly balanced tree? | The question is, how many ways are there to build a perfectly balanced binary tree with 15 elements?
One possibility would bei 8-4-12-2-6-10-14-1-3-5-7-9-11-13-15..
My idea was to write some code that generates every possible permutation (which would be like.. 15!) and then remove the ones that are incorrect.
Correct o... | [
"The correct number is 21964800. This is the appropriate integer sequence:\nhttp://oeis.org/A076615\nBasically you recursively multiply the possibilities:\nOn the lowest level you can choose between two possibilities, e.g: 2-1-3 and 2-3-1. On the level above that you can entangle the chosen order of both lower laye... | [
2,
1,
0,
0
] | [] | [] | [
"binary_tree",
"memory",
"permutation",
"python",
"tree"
] | stackoverflow_0008403543_binary_tree_memory_permutation_python_tree.txt |
Q:
Is there a possibility in python to call a classmethod out of the constructor?
Is there a possibility in python to call a classmethod out of the constructor?
I have a method in a class and want to call it while creating a new element.
Is it possible?
def __init__(self, val1, val2):
if (val1 == 5) and (val2 =... | Is there a possibility in python to call a classmethod out of the constructor? | Is there a possibility in python to call a classmethod out of the constructor?
I have a method in a class and want to call it while creating a new element.
Is it possible?
def __init__(self, val1, val2):
if (val1 == 5) and (val2 == 2):
function5_2(self)
def function5_2(self):
(arg... | [
"Yes you can do it:\nclass Foo(object):\n\n def __init__(self, a):\n self.a = a\n self.cls_method()\n\n @classmethod\n def cls_method(cls):\n print 'class %s' % cls.__name__\n\nOutput:\nclass Foo\n\n",
"Yes, it is. Here is an example of a classmethod getting called from a constructor... | [
4,
2
] | [] | [] | [
"class",
"constructor",
"methods",
"python"
] | stackoverflow_0008535138_class_constructor_methods_python.txt |
Q:
How can I create a dictionary in python from a txt file?
I have a file that looks like this:
NODE=SC-1,CPU=90
NODE=SC-1,MEM=10
NODE=SC-1,FS=80
NODE=SC-1,DIORead=30
NODE=SC-1,DIOWrite=40
NODE=SC-1,NTX=30
NODE=SC-1,NRX=40
NODE=SC-2,CPU=80
NODE=SC-2,MEM=10
NODE=SC-2,FS=80
NODE=SC-2,DIORead=30
NODE=SC-2,DIOWrite=40
NO... | How can I create a dictionary in python from a txt file? | I have a file that looks like this:
NODE=SC-1,CPU=90
NODE=SC-1,MEM=10
NODE=SC-1,FS=80
NODE=SC-1,DIORead=30
NODE=SC-1,DIOWrite=40
NODE=SC-1,NTX=30
NODE=SC-1,NRX=40
NODE=SC-2,CPU=80
NODE=SC-2,MEM=10
NODE=SC-2,FS=80
NODE=SC-2,DIORead=30
NODE=SC-2,DIOWrite=40
NODE=SC-2,NTX=30
NODE=SC-2,NRX=40
How can I parse the file and ... | [
"from collections import defaultdict\nd = defaultdict(dict)\nfor line in open('input_file','r'):\n line = line.strip()\n a,b = line.split(',')\n node = a.split('=')[1] \n key, value = b.split('=')\n d[node][key] = value\n\n",
"I believe you want to parse this file & keep all SC-* as keys and the re... | [
4,
0,
0,
0,
0
] | [] | [] | [
"dictionary",
"parsing",
"python"
] | stackoverflow_0008535073_dictionary_parsing_python.txt |
Q:
What does python depend on while executing a script?
The awkward scenario
I am developing a python package and would like to make use of an external package, that was not written by myself, as a dependency.
Since the external package is quite complex it also comes with all kinds of surplus software like its own ba... | What does python depend on while executing a script? | The awkward scenario
I am developing a python package and would like to make use of an external package, that was not written by myself, as a dependency.
Since the external package is quite complex it also comes with all kinds of surplus software like its own bash or python executable. Naturally I do not want to use th... | [
"All environment variables used by Python are listed here: Python environment variables\nEnsure that your Python interpreter has the same version than the external one .\n"
] | [
1
] | [] | [] | [
"dependencies",
"environment_variables",
"python"
] | stackoverflow_0008534914_dependencies_environment_variables_python.txt |
Q:
Pypy JIT gives a speed boost even if a script is run only once?
I have a script that loads several hundred images, resize them and then composes a bigger image
Every time is started with a different set of images:
python myscript.py imageFolder/
Running it in a virtualenv with Pypy doesn't show a noticeable speed... | Pypy JIT gives a speed boost even if a script is run only once? | I have a script that loads several hundred images, resize them and then composes a bigger image
Every time is started with a different set of images:
python myscript.py imageFolder/
Running it in a virtualenv with Pypy doesn't show a noticeable speed gain (all run in ~8 seconds with mprofile, with the pypy version spe... | [
"From your description it appears that PIL.resize() is the dominant operation. That function is written in C and not in Python. Therefore, I doubt you can expect PyPy to make much of a difference to your script.\nIf you're looking to speed things up, you could consider parallelizing the loading and resizing of the ... | [
10,
1
] | [] | [] | [
"pypy",
"python"
] | stackoverflow_0008535310_pypy_python.txt |
Q:
positions in a list. python
Lets say I have this list:
lst = [[0], [0, 0], [0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0]...]
how can I add a certain number to each cell according to its position in the lists
for exapmle:
I want to add a formula to each cell by multipying 3 with the position on the list*position in... | positions in a list. python | Lets say I have this list:
lst = [[0], [0, 0], [0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0]...]
how can I add a certain number to each cell according to its position in the lists
for exapmle:
I want to add a formula to each cell by multipying 3 with the position on the list*position in the nested list
so lets say the ... | [
"Looks like a job for enumerate!\nfor i, sublist in enumerate(lst):\n for j, elem in enumerate(sublist):\n sublist[j] = 3*(i+1)*(j+1)\n\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0008535535_python.txt |
Q:
Iterate through tuple values python
I have a list like
[(1, 3), (6, 7)]
and a string
'AABBCCDD'
I need to get the result AABCD.
I know I can get the integers form the tuple with nameOfTuple[0][0] yielding 1.
I also know that I can get the chars form the string with nameOfString[0] yielding A.
My question is, how d... | Iterate through tuple values python | I have a list like
[(1, 3), (6, 7)]
and a string
'AABBCCDD'
I need to get the result AABCD.
I know I can get the integers form the tuple with nameOfTuple[0][0] yielding 1.
I also know that I can get the chars form the string with nameOfString[0] yielding A.
My question is, how do I iterate through two arguments in the ... | [
"In [1]: l = [(1, 3), (6, 7)]\n\nIn [2]: s = 'AABBCCDD'\n\nIn [3]: ''.join(s[start-1:end] for (start,end) in l)\nOut[3]: 'AABCD'\n\nHere, pairs of indices from l are assigned to start and end, one pair at a time. The relevant portion of the string is then extracted using s[start-1:end], yielding a sequence of strin... | [
10
] | [] | [] | [
"loops",
"python",
"tuples"
] | stackoverflow_0008535662_loops_python_tuples.txt |
Q:
Most Pythonic Way to Split an Array by Repeating Elements
I have a list of items that I want to split based on a delimiter. I want all delimiters to be removed and the list to be split when a delimiter occurs twice. For example, if the delimiter is 'X', then the following list:
['a', 'b', 'X', 'X', 'c', 'd', 'X',... | Most Pythonic Way to Split an Array by Repeating Elements | I have a list of items that I want to split based on a delimiter. I want all delimiters to be removed and the list to be split when a delimiter occurs twice. For example, if the delimiter is 'X', then the following list:
['a', 'b', 'X', 'X', 'c', 'd', 'X', 'X', 'f', 'X', 'g']
Would turn into:
[['a', 'b'], ['c', 'd'],... | [
"I don't think there's going to be a nice, elegant solution to this (I'd love to be proven wrong of course) so I would suggest something straightforward:\ndef nSplit(lst, delim, count=2):\n output = [[]]\n delimCount = 0\n for item in lst:\n if item == delim:\n delimCount += 1\n el... | [
13,
4,
4,
3,
2,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008530210_python.txt |
Q:
appengine import_transform custom value
From what I could figure out, it is not very easy to assign default values to properties in the bulkloader.yaml file. I learned that one way to set default values is to write your own function:
- property: status
external_name: status
import_transform: extrabulk... | appengine import_transform custom value | From what I could figure out, it is not very easy to assign default values to properties in the bulkloader.yaml file. I learned that one way to set default values is to write your own function:
- property: status
external_name: status
import_transform: extrabulkloadfunctions.staticvalue(int)
So I modified... | [
"import_transform: \"lambda x: 'default A'\"\n\n"
] | [
0
] | [] | [] | [
"bulkloader",
"google_app_engine",
"python"
] | stackoverflow_0008525895_bulkloader_google_app_engine_python.txt |
Q:
Django reportlabs didn't return HttpResponse Object
I am trying to generate a pdf using reportlabs and I am encountering a The view APP.VIEW didn't return an HttpResponse object. error.
The function and view runs without any exceptions, even the line return HttpResponse(result.getvalue(), mimetype='application/pd... | Django reportlabs didn't return HttpResponse Object | I am trying to generate a pdf using reportlabs and I am encountering a The view APP.VIEW didn't return an HttpResponse object. error.
The function and view runs without any exceptions, even the line return HttpResponse(result.getvalue(), mimetype='application/pdf'). But I keep getting the error.
Below is my code:
def ... | [
"You aren't returning anything from the view. You can't just call render_to_pdf or HttpResponse - you actually have to return the result.\n"
] | [
2
] | [] | [] | [
"django",
"pdf",
"python",
"reportlab"
] | stackoverflow_0008535997_django_pdf_python_reportlab.txt |
Q:
How to create a queue that pops its contens, item by item, with a given time interval, without halting the program?
I need to create a queue that pops out its items in a given time interval.
And here's the catch: this activity should run in the background, so it won't halt the program's execution until the queue i... | How to create a queue that pops its contens, item by item, with a given time interval, without halting the program? | I need to create a queue that pops out its items in a given time interval.
And here's the catch: this activity should run in the background, so it won't halt the program's execution until the queue is empty.
This is the how my queue looks like at the moment:
from collections import deque
class Queue():
def __init... | [
"As the two people who commented on your question have put, the immediate response would be to use threads, just so long as when you mention that there will be many instances, the many instances is a reasonable amount. Something like the following:\nimport threading\nimport Queue\nimport time\n\nclass QueuePrinter(... | [
1
] | [] | [] | [
"background",
"python",
"queue",
"timer"
] | stackoverflow_0008535961_background_python_queue_timer.txt |
Q:
Declare a global variable only in a context (with)
I don't know if it is possible, but i need to set a global object but only in a context (with)
for example, i have 2 part of code. the first is a worker object that read and write some files.
but the worker don't actually know the real path of these files, so i h... | Declare a global variable only in a context (with) | I don't know if it is possible, but i need to set a global object but only in a context (with)
for example, i have 2 part of code. the first is a worker object that read and write some files.
but the worker don't actually know the real path of these files, so i have created a wrapper for redirect the open to the good ... | [
"I think the clean solution to your problem is to pass the wrapper object around.\nIf that's impractical, you could make your global variable \"thread-local\" by using threading.local. However, I think the first approach (passing wrapper around) is far, far superior.\n",
"Instead of using a wrapper object to pass... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0008535507_python.txt |
Q:
In Python 2.5, how do I kill a subprocess?
I am using the subprocess package in Python to run a subprocess, which I later need to kill. However, the documentation of the subprocess package states that the terminate() function is only available from 2.6
We are running Linux with 2.5 and for backwards compatibility ... | In Python 2.5, how do I kill a subprocess? | I am using the subprocess package in Python to run a subprocess, which I later need to kill. However, the documentation of the subprocess package states that the terminate() function is only available from 2.6
We are running Linux with 2.5 and for backwards compatibility reasons I cannot upgrade to 2.6, what is the alt... | [
"You call os.kill on the process pid.\nos.kill(process.pid, signal.SIGKILL)\n\nYou're OK because you're on on Linux. Windows users are out of luck.\n",
"To complete @Gareth's answer, on Windows you do:\nimport ctypes\nPROCESS_TERMINATE = 1\nhandle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, th... | [
41,
40,
6,
4
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0001064335_python_subprocess.txt |
Q:
Matplotlib histogram bins selection depends on whether data is plotted "alone" or with some other data: how so?
The title has it. :)
Example:
from numpy import random
from matplotlib import pyplot as plt
data = [1 + random.randn(1000), random.randn(1000)]
bins = 10
plt.hist(data, bins, label=['first', 'second'])... | Matplotlib histogram bins selection depends on whether data is plotted "alone" or with some other data: how so? | The title has it. :)
Example:
from numpy import random
from matplotlib import pyplot as plt
data = [1 + random.randn(1000), random.randn(1000)]
bins = 10
plt.hist(data, bins, label=['first', 'second'])
plt.hist(data[1], bins, histtype='step', label=['second again'])
plt.legend()
plt.show()
gives ('step' type chose... | [
"Here is the process that hist currently uses (in the matplotlib git repo) for determining the bins:\n\nIf bins is given as the actual bins, those bins will be used\nIf bin_range is given, then those two values will be used for the bin_range.\nIf bin_range is not given, then use [min of all data, max of all data] a... | [
4,
2
] | [] | [] | [
"histogram",
"matplotlib",
"plot",
"python"
] | stackoverflow_0008534535_histogram_matplotlib_plot_python.txt |
Q:
python regexp parse
I have hash:
{'login': u'myemail (myemail@gmail.com)'}
I need parse only email myemail@gmail.com
What regexp I must compose
A:
No regex is needed. Use string manipulation instead. This will split the value on the first space, then strip the () from the second item ([1]) of the returned arra... | python regexp parse | I have hash:
{'login': u'myemail (myemail@gmail.com)'}
I need parse only email myemail@gmail.com
What regexp I must compose
| [
"No regex is needed. Use string manipulation instead. This will split the value on the first space, then strip the () from the second item ([1]) of the returned array.\nyourhash = {'login': u'myemail (myemail@gmail.com)'}\n\nemail = yourhash['login'].split()[1].strip(\"()\")\n\nprint(email)\n# myemail@gmail.com\n\... | [
2,
2,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008536362_python_regex.txt |
Q:
Array initialization in Python
I want to initialize an array with 10 values starting at X and incrementing by Y. I cannot directly use range() as it requires to give the maximum value, not the number of values.
I can do this in a loop, as follows:
a = []
v = X
for i in range(10):
a.append(v)
v = v + Y
But... | Array initialization in Python | I want to initialize an array with 10 values starting at X and incrementing by Y. I cannot directly use range() as it requires to give the maximum value, not the number of values.
I can do this in a loop, as follows:
a = []
v = X
for i in range(10):
a.append(v)
v = v + Y
But I'm certain there's a cute python o... | [
">>> x = 2\n>>> y = 3\n>>> [i*y + x for i in range(10)]\n[2, 5, 8, 11, 14, 17, 20, 23, 26, 29]\n\n",
"You can use this:\n>>> x = 3\n>>> y = 4\n>>> range(x, x+10*y, y)\n\n[3, 7, 11, 15, 19, 23, 27, 31, 35, 39]\n\n",
"Just another way of doing it\nY=6\nX=10\nN=10\n[y for x,y in zip(range(0,N),itertools.count(X,Y)... | [
17,
9,
2,
2,
1
] | [] | [] | [
"algorithm",
"arrays",
"initialization",
"python"
] | stackoverflow_0008535672_algorithm_arrays_initialization_python.txt |
Q:
python multiple imports for a common module
I am working on a project wherein I need to use a third party module in different project files(.py files). The situation is like this.
I have a file "abc.py" which imports third party module "common.py". There are couple of other files which also import "common.py". All... | python multiple imports for a common module | I am working on a project wherein I need to use a third party module in different project files(.py files). The situation is like this.
I have a file "abc.py" which imports third party module "common.py". There are couple of other files which also import "common.py". All these files are also imported in main project fi... | [
"Importing only ever loads a module once. Any imports after that simply add it to the current namespace.\nJust import things in the files you need them to be available and let Python do the heavy-lifting of figuring out loading the modules.\n",
"Yes, you are right, this behavior really exists in Python. Namely, i... | [
20,
3
] | [] | [] | [
"python"
] | stackoverflow_0004689252_python.txt |
Q:
How do I setup django with apache so that my appliction is at the root url?
I am new to django so please forgive me if this turns out to be obvious.
I have worked through the tutorials so I have a project (I called it "trydj") which has a application called "polls". What I want to do is have polls served at the r... | How do I setup django with apache so that my appliction is at the root url? | I am new to django so please forgive me if this turns out to be obvious.
I have worked through the tutorials so I have a project (I called it "trydj") which has a application called "polls". What I want to do is have polls served at the root, ie:
http://www.example.com/ would invoke the polls index view and
http://ww... | [
"Just change this line:\nurl(r'^polls/', include('polls.urls')), \n\nto this\nurl(r'^', include('polls.urls')),\n\nSo that all URLs that reach this point are passed through to your urls.py file in polls, rather than just ones prefixed with polls/.\nOh, and I should add that it's important to have this line where it... | [
3
] | [] | [] | [
"apache",
"django",
"python"
] | stackoverflow_0008536635_apache_django_python.txt |
Q:
msbuild fails and returns 1 when when I assign stdout and stdout to os.devnull, returns 0 otherwise
I am trying to write a python script that checks out a revision from a mercurial repo for a visual studio 2010 native c++ project, builds it, and then runs a program under various scenarios. Then I will compare res... | msbuild fails and returns 1 when when I assign stdout and stdout to os.devnull, returns 0 otherwise | I am trying to write a python script that checks out a revision from a mercurial repo for a visual studio 2010 native c++ project, builds it, and then runs a program under various scenarios. Then I will compare results from other builds, etc. So I am just getting started with a prototype, and I have:
from subprocess ... | [
"Apparently this is a bug in msbuild:\nhttp://connect.microsoft.com/VisualStudio/feedback/details/633122/msbuild-fails-with-1-when-redirecting-the-output-1-nul-2-anywhere\n"
] | [
3
] | [] | [] | [
"msbuild",
"python",
"visual_c++",
"visual_studio_2010"
] | stackoverflow_0008482098_msbuild_python_visual_c++_visual_studio_2010.txt |
Q:
User interaction in twisted process
I am running a twisted process which needs to interact with the user, without blocking. The idea is that the user will be asked to input some data, and once a complete line has been entered, the program will process it, eventually triggering events. During the period that the us... | User interaction in twisted process | I am running a twisted process which needs to interact with the user, without blocking. The idea is that the user will be asked to input some data, and once a complete line has been entered, the program will process it, eventually triggering events. During the period that the user is entering data, the reactor must kee... | [
"You can read from standard input using twisted.internet.stdio. See stdiodemo.py and stdin.py at http://twistedmatrix.com/documents/current/core/examples/.\nYou can also use Gtk using twisted.internet.gtk2reactor. See the pbgtk2.py example at the same examples page.\nYou can also use other GUI toolkits, though Gt... | [
1
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0008532387_python_twisted.txt |
Q:
Moving crops within the same image
Tried looking in the PIL module but couldn't find this covered.
I have an image, and I need to take a cropped piece of the image and move it to a different area within the same image. Simple enough, but I will need to do this for thousands of images, so I will do batch image pro... | Moving crops within the same image | Tried looking in the PIL module but couldn't find this covered.
I have an image, and I need to take a cropped piece of the image and move it to a different area within the same image. Simple enough, but I will need to do this for thousands of images, so I will do batch image processing.
PIL seems too basic for this, a... | [
"Actually, PIL looks like it can do it very well, if you want to copy and paste rectangular areas.\nCheck the documentation on the crop and paste methods on image, on the documentation here:\nhttp://effbot.org/imagingbook/image.htm\nIf you need non-rectangular areas, though, you will have to resort to more sophisti... | [
1,
0,
0
] | [] | [] | [
"image",
"image_processing",
"python"
] | stackoverflow_0008536891_image_image_processing_python.txt |
Q:
Recovering lost multiprocessing.Queue items when a worker Process dies
My scenario is this:
I've got worker which enqueues tasks into a multiprocessing.Queue() if said is empty. This is to ensure execution of tasks follow a certain priority and multiprocessing.Queue() doesn't do priorities.
There are a number of ... | Recovering lost multiprocessing.Queue items when a worker Process dies | My scenario is this:
I've got worker which enqueues tasks into a multiprocessing.Queue() if said is empty. This is to ensure execution of tasks follow a certain priority and multiprocessing.Queue() doesn't do priorities.
There are a number of workers which pop from the mp.Queue and do some stuff. Sometimes (<0.1%) the... | [
"This solution uses three queues to keep track of the work (simulated as WORK_ID):\n\ntodo_q: Any work to be done (including that to be redone if the process died in-flight)\nstart_q: Any work that has been started by a process\nfinish_q: Any work that has been completed\n\nUsing this method you should not need a t... | [
3
] | [] | [] | [
"algorithm",
"multiprocessing",
"python",
"queue"
] | stackoverflow_0008532215_algorithm_multiprocessing_python_queue.txt |
Q:
How to get Python to tell equal integers apart
Have a bit of a problem distinguishing between identical integers.
In the following (which is obviously a trivial case) a, b, c are integers. I wish to create a dicionary, diction, which will contain {a: 'foo', b: 'bar', c: 'baz'}
diction = {}
for i in (a, b, c):
... | How to get Python to tell equal integers apart | Have a bit of a problem distinguishing between identical integers.
In the following (which is obviously a trivial case) a, b, c are integers. I wish to create a dicionary, diction, which will contain {a: 'foo', b: 'bar', c: 'baz'}
diction = {}
for i in (a, b, c):
j = ('foo', 'bar', 'baz')[(a, b, c).index(i)]
d... | [
"To create a dictionary from two different iterables, you can use the following code:\nd = dict(zip((a, b, c), ('foo', 'bar', 'baz')))\n\nwhere zip is used to combine both iterables in a list of tuples that can be passed to the dictionary constructor.\nNote that if a==b, then the 'foo' will be overwritten with 'bar... | [
3,
2,
1,
1,
0
] | [] | [] | [
"dictionary",
"equals",
"indexing",
"list",
"python"
] | stackoverflow_0008537167_dictionary_equals_indexing_list_python.txt |
Q:
Sorting a List of Strings, Ignoring ASCII Ordinal Values
I want to sort this list:
>>> L = ['A', 'B', 'C', ... 'Z', 'AA', 'AB', 'AC', ... 'AZ', 'BA' ...]
Exactly the way it is, regardless of the contents (assuming all CAPS alpha).
>>> L.sort()
>>> L
['A', 'AA', 'AB', 'AC'...]
How can I make this:
>>> L.parkinglo... | Sorting a List of Strings, Ignoring ASCII Ordinal Values | I want to sort this list:
>>> L = ['A', 'B', 'C', ... 'Z', 'AA', 'AB', 'AC', ... 'AZ', 'BA' ...]
Exactly the way it is, regardless of the contents (assuming all CAPS alpha).
>>> L.sort()
>>> L
['A', 'AA', 'AB', 'AC'...]
How can I make this:
>>> L.parkinglot_sort()
>>> L
['A', 'B', 'C', ... ]
I was thinking of testin... | [
"What about this?\nl.sort(key=lambda element: (len(element), element))\n\nIt will sort the list taking into account not only each element, but also its length.\n>>> l = ['A', 'AA', 'B', 'BB', 'C', 'CC']\n>>> l.sort(key=lambda element: (len(element), element))\n>>> print l\n['A', 'B', 'C', 'AA', 'BB', 'CC']\n\n"
] | [
6
] | [] | [] | [
"ordinal",
"python",
"sorting"
] | stackoverflow_0008537483_ordinal_python_sorting.txt |
Q:
Python coroutine that consumes and produces
In a web-crawler of mine, I have a class that keeps track of urls to crawl, removing duplicates, etc:
class VisitOnlyOnceClerk(object):
def __init__(self):
self.visited = set()
self.to_visit = set()
def enqueue(self, url, referer):
if not... | Python coroutine that consumes and produces | In a web-crawler of mine, I have a class that keeps track of urls to crawl, removing duplicates, etc:
class VisitOnlyOnceClerk(object):
def __init__(self):
self.visited = set()
self.to_visit = set()
def enqueue(self, url, referer):
if not url in self.visited:
self.to_visit.a... | [
"I don't think coroutine are the way to go here your class generator IMHO is way to much readable and understandable and easy to use than the way Python coroutine will allow you to do.\nTo make my point here is how i will implement the coroutine:\ndef visit_once_clerk(start_point=None):\n visited = set()\n to... | [
0
] | [] | [] | [
"coroutine",
"python"
] | stackoverflow_0008537375_coroutine_python.txt |
Q:
modify list element with list comprehension in python
folks,
I want to modify list element with list comprehension. For example, if the element is negative, add 4 to it.
Thus the list
a = [1, -2 , 2]
will be converted to
a = [1, 2, 2]
The following code works, but i am wondering if there is a better way to do... | modify list element with list comprehension in python | folks,
I want to modify list element with list comprehension. For example, if the element is negative, add 4 to it.
Thus the list
a = [1, -2 , 2]
will be converted to
a = [1, 2, 2]
The following code works, but i am wondering if there is a better way to do it?
Thanks.
for i in range(len(a)):
if a[i]<0:
... | [
"a = [b + 4 if b < 0 else b for b in a]\n\n",
"If you want to change the list in-place, this is almost the best way. List comprehension will create a new list. You could also use enumerate, and assignment must be done to a[i]:\nfor i, x in enumerate(a):\n if x < 0:\n a[i] = x + 4\n\n",
"This version is olde... | [
24,
8,
3,
2,
1
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0008537824_list_comprehension_python.txt |
Q:
How to store the return value of os.system that it has printed to stdout in python?
I am writing a python script which checks for number of active connections for a particular IP / port. For this I use os.system( 'my_command') to grab the output. os.system returns the exit status of the command I've passed it (0 m... | How to store the return value of os.system that it has printed to stdout in python? | I am writing a python script which checks for number of active connections for a particular IP / port. For this I use os.system( 'my_command') to grab the output. os.system returns the exit status of the command I've passed it (0 means the command returned without error).
How can I store this value which os.system thro... | [
"a=os.popen(\"your command\").read()\n\nnew result stored at variable a :)\n",
"import subprocess\np = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nout, error = p.communicate()\n\n",
"import subprocess\np = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subproce... | [
17,
6,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006746126_python.txt |
Q:
How to communicate with a python daemon from PHP scripts
I'm making a scan server for my company, which will be used to launch scans from tools such as nessus, nmap, nikto etc. I've written the pages in PHP, but I need to have control over the subsequent processes (spawned with nohup and backgrounded with &) as I ... | How to communicate with a python daemon from PHP scripts | I'm making a scan server for my company, which will be used to launch scans from tools such as nessus, nmap, nikto etc. I've written the pages in PHP, but I need to have control over the subsequent processes (spawned with nohup and backgrounded with &) as I need to perform various actions once the scans have completed ... | [
"I think something like gearman would certainly make it easier to implement this.\nGearman is a job server which lets you start jobs, query if the job is still running and fetch the output of the job (as text). \nIt supports PHP and Python (among others).\n(This answer made me feel like a salesman).\n",
"So your ... | [
5,
1
] | [] | [] | [
"daemon",
"ipc",
"php",
"python"
] | stackoverflow_0008537863_daemon_ipc_php_python.txt |
Q:
AttributeError: 'time.struct_time' object has no attribute 'toordinal'
I'm novice in python, and I couldn't understand how to correctly formatting dates.
My data is like this Fri, 09 Dec 2011 06:50:37 UTC
I'm preparing it like this:
dates.append(time.strptime(row[5], "%a, %d %b %Y %H:%M:%S %Z"))
Then I'm trying t... | AttributeError: 'time.struct_time' object has no attribute 'toordinal' | I'm novice in python, and I couldn't understand how to correctly formatting dates.
My data is like this Fri, 09 Dec 2011 06:50:37 UTC
I'm preparing it like this:
dates.append(time.strptime(row[5], "%a, %d %b %Y %H:%M:%S %Z"))
Then I'm trying to use it
dates = matplotlib.dates.date2num(dates)
get following error:
Att... | [
"You are using the time module, but matplotlib expects the datetime object.\nTry using something like this:\nfrom datetime import datetime\n\ndates.append(datetime.strptime(row[5], \"%a, %d %b %Y %H:%M:%S %Z\"))\n...\n\n"
] | [
5
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008538296_matplotlib_python.txt |
Q:
Iterating over an unknown number of lists referenced by dictionary key to allow comparison of values within each list
I recently started writing a small script where my intent is to input a directory full of files (eBooks in this case epub,mobi,djvu,pdf) find files that match each other in (almost) every way excep... | Iterating over an unknown number of lists referenced by dictionary key to allow comparison of values within each list | I recently started writing a small script where my intent is to input a directory full of files (eBooks in this case epub,mobi,djvu,pdf) find files that match each other in (almost) every way except extension (e.g. Multiple eBook file formats for the same 'book'), create a directory for that 'book' and place the files ... | [
"Instead, I would store the found files by their name so they are grouped as soon as you read them. Like this:\nfoundFiles = {}\nfor ext in fileExtensions:\n print('Looking for ' + ext + ' files in ' + workDirectory)\n for file in glob.glob(workDirectory + '/*.' + ext):\n basename = os.path.basename(os... | [
2,
1,
0
] | [] | [] | [
"dictionary",
"list",
"loops",
"python"
] | stackoverflow_0008537192_dictionary_list_loops_python.txt |
Q:
Return min/max of multidimensional in Python?
I have a list in the form of
[ [[a,b,c],[d,e,f]] , [[a,b,c],[d,e,f]] , [[a,b,c],[d,e,f]] ... ] etc.
I want to return the minimal c value and the maximal c+f value. Is this possible?
A:
For the minimum c:
min(c for (a,b,c),(d,e,f) in your_list)
For the maximum c+f
m... | Return min/max of multidimensional in Python? | I have a list in the form of
[ [[a,b,c],[d,e,f]] , [[a,b,c],[d,e,f]] , [[a,b,c],[d,e,f]] ... ] etc.
I want to return the minimal c value and the maximal c+f value. Is this possible?
| [
"For the minimum c:\nmin(c for (a,b,c),(d,e,f) in your_list)\n\nFor the maximum c+f\nmax(c+f for (a,b,c),(d,e,f) in your_list)\n\nExample:\n>>> your_list = [[[1,2,3],[4,5,6]], [[0,1,2],[3,4,5]], [[2,3,4],[5,6,7]]]\n>>> min(c for (a,b,c),(d,e,f) in lst)\n2\n>>> max(c+f for (a,b,c),(d,e,f) in lst)\n11\n\n",
"List c... | [
16,
5,
1,
1,
1
] | [] | [] | [
"list",
"max",
"min",
"python",
"sorting"
] | stackoverflow_0008538714_list_max_min_python_sorting.txt |
Q:
Is there a django template equivalent of the python string multiplication function?
In python I can write "Hello" * 5 and get
HelloHelloHelloHelloHello
Is there a way to do this in a django template? Something like {% multiply "Hello" 5 %} or as a filter {% "Hello"|multiply:"5" %}
Or maybe a "repeat" loop control... | Is there a django template equivalent of the python string multiplication function? | In python I can write "Hello" * 5 and get
HelloHelloHelloHelloHello
Is there a way to do this in a django template? Something like {% multiply "Hello" 5 %} or as a filter {% "Hello"|multiply:"5" %}
Or maybe a "repeat" loop control? Something like:
{% repeat 5 %}
Hello
{% endrepeat %}
I can write a filter or tag mysel... | [
"Here's another hack:\n{% for x in \"\"|ljust:\"100\" %}\n Hello World!\n{% endfor %}\n\nI'm using an empty string as the value here, and I repeat the thing 100x. You can also use a variable to determine the number of repeats with this hack :) just replace \"100\" with the variable.\n{% for x in \"\"|ljust:repea... | [
18,
4
] | [] | [] | [
"django",
"django_template_filters",
"django_templates",
"python"
] | stackoverflow_0008536757_django_django_template_filters_django_templates_python.txt |
Q:
How can I keep row selections in QItemSelectionModel when columns are sorted?
I'm using QItemSelectionModel with QTableView to allow the users to select rows. The problem is that when the user then clicks on a column header to sort the rows, the selection disappears and all the sorted data is displayed. How can I ... | How can I keep row selections in QItemSelectionModel when columns are sorted? | I'm using QItemSelectionModel with QTableView to allow the users to select rows. The problem is that when the user then clicks on a column header to sort the rows, the selection disappears and all the sorted data is displayed. How can I keep the selection, and just sort that, rather than having all the rows appear?
Tha... | [
"Here is the way I ended up solving this problem:\n\nWhen row selections are made, put the unique IDs of each hidden row into a list, then hide all hidden rows\nUse self.connect(self.myHorizontalHeader, SIGNAL(\"sectionClicked(int)\"), self.keepSelectionValues) to catch the\nevent when a user clicks on a column hea... | [
0
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0008388659_pyqt_python.txt |
Q:
python's glob only returning the first result
I am really stumped on this one.
I have a simple python wrapper which looks something like this:
import glob
for found in glob.glob(filename):
if not os.path.isdir(found):
my_module.do_stuff(found)
where filename has been read in from sys.argv.
When I try glob ... | python's glob only returning the first result | I am really stumped on this one.
I have a simple python wrapper which looks something like this:
import glob
for found in glob.glob(filename):
if not os.path.isdir(found):
my_module.do_stuff(found)
where filename has been read in from sys.argv.
When I try glob in an interactive shell, or a hello world script, I... | [
"The shell is expanding the glob before your Python script sees it. Therefore your Python script sees the first full filename that matches the glob in sys.argv[1], passes that to glob(), and of course it only matches one file.\nEither quote the argument in the shell with single quotes so that the shell does not exp... | [
16,
1
] | [] | [] | [
"python"
] | stackoverflow_0008538564_python.txt |
Q:
Python: first character when splitting
I just noticed the split method produces an empty string in the result list if the first character is a delimiter string.
Example:
>>> s = '/foo/bar/blarg'
>>> s.split('/')
['', 'foo', 'bar', 'blarg']
I expected this to produce:
['foo', 'bar', 'blarg']
Is there some reason ... | Python: first character when splitting | I just noticed the split method produces an empty string in the result list if the first character is a delimiter string.
Example:
>>> s = '/foo/bar/blarg'
>>> s.split('/')
['', 'foo', 'bar', 'blarg']
I expected this to produce:
['foo', 'bar', 'blarg']
Is there some reason why this is desirable behavior, or is this s... | [
"This is the desired behaviour, because otherwise it would be impossible to distinguish between \"/foo\".split(\"/\") and \"foo\".split(\"/').\nWhen I'm using split and know that I don't want possibly empty strings, I'll use filter(None, foo.split(\"/\")) to remove them:\n>>> filter(None, \"/foo//bar\".split(\"/\")... | [
5,
4,
2,
1
] | [] | [] | [
"python",
"split",
"string"
] | stackoverflow_0008539029_python_split_string.txt |
Q:
Pygtk: CellRenderer using up all vertical space
I made a user interface with a ComboBox. I'm using glade so I'm doing the following at runtime
combo_box.set_model(liststore)
cell = gtk.CellRendererText()
combo_box.pack_start(cell,False)
combo_box.add_attribute(cell,'text',0)
And when I click on the ComboBox the c... | Pygtk: CellRenderer using up all vertical space | I made a user interface with a ComboBox. I'm using glade so I'm doing the following at runtime
combo_box.set_model(liststore)
cell = gtk.CellRendererText()
combo_box.pack_start(cell,False)
combo_box.add_attribute(cell,'text',0)
And when I click on the ComboBox the cellrenderer takes up all the vertical space of the sc... | [
"From what I know this is in GTK+ by design (though I have no references, and could equally be completely wrong). The idea is that when you have a list of items in a ComboBox or Menu, which forces the list off the screen. GTK+ makes a decision to place the first item both at the top of the list, and beneath you mou... | [
1
] | [] | [] | [
"gtk",
"gtk2",
"pygtk",
"python"
] | stackoverflow_0008461933_gtk_gtk2_pygtk_python.txt |
Q:
Calling SOAP Methods with dots in the name using Python/Suds
Trying to make a SOAP call using Python Suds. It imports the WSDL fine, and the client it generates looks well-formed, but I am unable to access the methods.
The Suds documentation describes the method calls like this:
client.service.Company.GetQueue()... | Calling SOAP Methods with dots in the name using Python/Suds | Trying to make a SOAP call using Python Suds. It imports the WSDL fine, and the client it generates looks well-formed, but I am unable to access the methods.
The Suds documentation describes the method calls like this:
client.service.Company.GetQueue()
But all I get with every variation of this is:
suds.MethodNotFo... | [
"kfed is right, it's the dots that do it. but I don't want to alter my WSDL.\nHowever, I found this workaround:\nUse getattr to reference the method name with a string, get a handle to the method, then call it:\nCompany_GetTokenCount = getattr(client.service, 'Company.GetTokenCount')\nCompany_GetTokenCount()\n\nht... | [
5,
0
] | [] | [] | [
"python",
"soap",
"suds"
] | stackoverflow_0004629931_python_soap_suds.txt |
Q:
python-payflowpro on-demand payments
I'm trying to build a python solution where a user can enter a credit card which will be submitted and saved to the Payflow pro servers and can be billed on an on-demand basis. I know python-payflowpro supports recurring billing, but that occurs on a regular schedule, such as ... | python-payflowpro on-demand payments | I'm trying to build a python solution where a user can enter a credit card which will be submitted and saved to the Payflow pro servers and can be billed on an on-demand basis. I know python-payflowpro supports recurring billing, but that occurs on a regular schedule, such as weekly or monthly. I'm looking to find a ... | [
"Looking closer at the api source code, I found an undocumented function called reference_transaction, which allows reference transactions. It seems to allow you to make use of PayPal's Reference Transactions and allow you to store credit cards online and charge them on an ad-hoc basis. \nhttps://github.com/bkeatin... | [
0
] | [] | [] | [
"ondemand",
"payflowpro",
"payment",
"python"
] | stackoverflow_0007272414_ondemand_payflowpro_payment_python.txt |
Q:
Extracting brackets with regex from a string in python
How I can extract {{template|{{template2}}|other params}} from this string if we just know "template":
{{template0}}
{{template|{{template2}}|other params}}
{{template3}}
A:
This should do what you want:
>>> match = re.search(r'^{{template\b.*$', your_string... | Extracting brackets with regex from a string in python | How I can extract {{template|{{template2}}|other params}} from this string if we just know "template":
{{template0}}
{{template|{{template2}}|other params}}
{{template3}}
| [
"This should do what you want:\n>>> match = re.search(r'^{{template\\b.*$', your_string, re.M)\n>>> match.group()\n'{{template|{{template2}}|other params}}'\n\nIt uses a word boundary (\\b) after 'template' so it will not match 'template0' or 'template3'. The re.M option is used so ^ and $ will match the beginning... | [
2
] | [] | [] | [
"brackets",
"python",
"regex",
"wikipedia"
] | stackoverflow_0008539628_brackets_python_regex_wikipedia.txt |
Q:
Class Iterator for Nested (2-D) Dictionary?
I've been using python for a couple years on and off, but not much for complicated object oriented programming and I rarely use dictionaries as a structure. For this application I'm trying to build a database of geo-located waypoints on a map.
As such, I want to create a... | Class Iterator for Nested (2-D) Dictionary? | I've been using python for a couple years on and off, but not much for complicated object oriented programming and I rarely use dictionaries as a structure. For this application I'm trying to build a database of geo-located waypoints on a map.
As such, I want to create a container class that is capable of accessing a 2... | [
"Instead of trying to support iteration in GeoWayPtData, it may be easier to iterate over the defaultdict in GeoWayPtData:\nfor equip in data.dictWayPts.itervalues():\n for waypt in equip.itervalues():\n print waypt.ID, waypt.EquipClassStr\n\nOf course you could also add this functionality to GeoWayPtData... | [
1
] | [] | [] | [
"dictionary",
"iterator",
"object",
"python"
] | stackoverflow_0008539673_dictionary_iterator_object_python.txt |
Q:
Can I create a "simple" Cyclic Redundancy Check program in Python?
I am quite green in the ways of Python programming and was tasked with creating a simple program that ran a CRC check. Can anyone suggest a good start point on which modules to use/read up on? I suppose a simple program would just be doing a CRC o... | Can I create a "simple" Cyclic Redundancy Check program in Python? | I am quite green in the ways of Python programming and was tasked with creating a simple program that ran a CRC check. Can anyone suggest a good start point on which modules to use/read up on? I suppose a simple program would just be doing a CRC on binary code generated in Python, and not on actual executables.
Anothe... | [
"If you need to calculate the CRC, its already part of the binascii module. There is also a short example to help to get started.\n",
"You can use pycrc to do standard CRCs\n"
] | [
2,
1
] | [] | [] | [
"crc",
"cyclic",
"directory_listing",
"python",
"redundancy"
] | stackoverflow_0008539998_crc_cyclic_directory_listing_python_redundancy.txt |
Q:
How to switch execution to a new script in Python?
Is it possible to have one script call another and then exit (don't know if I'm putting this right), leaving the other script running? Specifically I want an update script to download installer.py and then run it. Since installer.py overwrites the update script I ... | How to switch execution to a new script in Python? | Is it possible to have one script call another and then exit (don't know if I'm putting this right), leaving the other script running? Specifically I want an update script to download installer.py and then run it. Since installer.py overwrites the update script I can't just do a subprocess.call() since it will fail at ... | [
"One of the os.exec* family of functions should do what you want.\n",
"Since you're downloading another Python script, you could try using exec to run it. In 2.x there is a helper function execfile for this sort of thing (which wraps the use of the exec keyword; in 3.x you must read the file and pass the resultin... | [
3,
0
] | [] | [] | [
"exec",
"execute",
"python"
] | stackoverflow_0008539024_exec_execute_python.txt |
Q:
How to crop from one image and paste into another with PIL?
With PIL, I am trying to copy a rectangle out of an image, and paste it into another. This is my code:
import Image
ii = Image.open("ramza.png")
box = (70, 70, 30, 30)
region = ii.crop(box)
io = Image.open("template.png")
io.paste(region, box)
io.save("ou... | How to crop from one image and paste into another with PIL? | With PIL, I am trying to copy a rectangle out of an image, and paste it into another. This is my code:
import Image
ii = Image.open("ramza.png")
box = (70, 70, 30, 30)
region = ii.crop(box)
io = Image.open("template.png")
io.paste(region, box)
io.save("output.png")
And I am getting this error:
ValueError: images do n... | [
"A PIL crop box is defined as a 4-tuple of pixel coordinates: (left, upper, right, lower).\nTo fix your code to get a 30x30 crop:\nbox = (70, 70, 100, 100)\n\nBroken down into components:\nx, y, w, h = (70, 70, 30, 30)\nbox = (x, y, x + w, y + h)\n\n",
"For future visitors: this error may also come up if the box ... | [
16,
4
] | [] | [] | [
"crop",
"paste",
"python",
"python_imaging_library"
] | stackoverflow_0005723400_crop_paste_python_python_imaging_library.txt |
Q:
Using Python, how can I tell the user they already entered a number in the list?
I have to write a program for my class that
gets user input (numbers)
make to parallel list for even numbers and odd numbers
tell the user is a number was already entered
print the list
and other things I know how to do.
I have ever... | Using Python, how can I tell the user they already entered a number in the list? | I have to write a program for my class that
gets user input (numbers)
make to parallel list for even numbers and odd numbers
tell the user is a number was already entered
print the list
and other things I know how to do.
I have everything else just the only thing I don't know how to do is tell the user that a number ... | [
"Start reading about testing membership with in and using set to create unique list of numbers\n",
"read the following example code and try to adapt its ideas. the \"in\" keyword is python specific and replaces iterating over the lists while comparing.\nodd = [1, 3, 5, 7]\neven = [2, 4, 6, 8]\n\nuser_input = int... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0008540115_python.txt |
Q:
HTTP GET Encoding for Web Service Calls
I have a web service that I'm calling from C#. I've been able to successfully get a response using simple GET queries, such as:
http://localhost:8080/cgi-bin/py-wps.cgi?service=wps&version=1.0.0&request=describeprocess&identifier=test
However, when make more complex quer... | HTTP GET Encoding for Web Service Calls | I have a web service that I'm calling from C#. I've been able to successfully get a response using simple GET queries, such as:
http://localhost:8080/cgi-bin/py-wps.cgi?service=wps&version=1.0.0&request=describeprocess&identifier=test
However, when make more complex queries the response is always an error.
http://... | [
"Your '=' signs in \"[key1=val1,val2,val3;key2=val4;key3=val5]\" will need to be double escaped. Try escaping the value of datainputs and then escape the full URL.\n"
] | [
0
] | [] | [] | [
"c#",
"get",
"http",
"python"
] | stackoverflow_0008539888_c#_get_http_python.txt |
Q:
Modifying a program to Decrypt a message using a past encrypted alphabet on python
I need help in writing the second part to this program, which is almost complete. I finish writing the part in which an alphabet is encrypted, but now I find myself stuck in trying to use the new encryption as a sort of decoder ring... | Modifying a program to Decrypt a message using a past encrypted alphabet on python | I need help in writing the second part to this program, which is almost complete. I finish writing the part in which an alphabet is encrypted, but now I find myself stuck in trying to use the new encryption as a sort of decoder ring, to decrypt a a random scrambled message that someone might input into the program.
So ... | [
"There are functions in the Python standard library that make this task quite easy. Have a look at str.translate() and string.maketrans():\n>>> import string\n>>> t = string.maketrans(\"NHPWJXEYOZMAFUSCIGLVTDBKRQ\",\n string.ascii_uppercase)\n>>> \"DRSA SA XG 1AD AZCEZD XZAAUJZ!\".translate... | [
2,
1
] | [] | [] | [
"encryption",
"python"
] | stackoverflow_0008540249_encryption_python.txt |
Q:
Python/wxPython: AUI Manager, Prevent Panel from Leaving the Frame
I'm using the code below to test some of the features from AUI. If you run the code, you should find a frame with 2 panels in it that can be detached/floated. However, the panel can be dragged anywhere on the screen. I'd like to prevent the pane... | Python/wxPython: AUI Manager, Prevent Panel from Leaving the Frame | I'm using the code below to test some of the features from AUI. If you run the code, you should find a frame with 2 panels in it that can be detached/floated. However, the panel can be dragged anywhere on the screen. I'd like to prevent the panel from leaving the main frame. Is this possible? I thought there would... | [
"In AuiPaneInfo() you can add Floatable(False) to the pane you dont want it to float:\nwx.aui.AuiPaneInfo().Left().Floatable(False)\n\n"
] | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008509203_python_wxpython.txt |
Q:
How to handle two versions of the same site
My project consists of two versions of the same thing. For example version 1 is Freshman and version 2 is Sophomore. To avoid redundancy I am using the same templates and views as the implementation in both the version is not very different. The only difference in this s... | How to handle two versions of the same site | My project consists of two versions of the same thing. For example version 1 is Freshman and version 2 is Sophomore. To avoid redundancy I am using the same templates and views as the implementation in both the version is not very different. The only difference in this site would be in the urls. Such that
localhost:800... | [
"I would suggest looking into using one url pattern for both, but pass unique parameters into each. You achieve this using the django.con.urls.defaults.include function. In this case, the first include sets the kwarg current_app to freshman, and the second to sophomore.\nfrom django.conf.urls.defaults import *\n\... | [
2,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008540052_django_python.txt |
Q:
PyQT center toolbar buttons
By default the toolbar buttons in PyQT are aligned to the left, is it possible to make them centered so that they slide along when resizing?
A:
I am not sure I understand correctly, but if you are looking for a way to center buttons on toolbar with respect to QMainWindow, then yes the... | PyQT center toolbar buttons | By default the toolbar buttons in PyQT are aligned to the left, is it possible to make them centered so that they slide along when resizing?
| [
"I am not sure I understand correctly, but if you are looking for a way to center buttons on toolbar with respect to QMainWindow, then yes there is a (hackish) way. You just need to put a widget that acts like a 'spacer'. That is basically a QWidget with expanding size policy.\nHere is a minimal example:\nimport sy... | [
13
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0008537474_pyqt_pyqt4_python.txt |
Q:
Using the Python GData API, cannot get editable video entry
I am having trouble getting a video entry which includes a link rel="edit". I need such an entry in order to be able to call DeleteVideoEntry(...) on it.
I am retrieving the video using GetYouTubeVideoEntry(youtube_id=XXXXXXX). My yt_service is initialize... | Using the Python GData API, cannot get editable video entry | I am having trouble getting a video entry which includes a link rel="edit". I need such an entry in order to be able to call DeleteVideoEntry(...) on it.
I am retrieving the video using GetYouTubeVideoEntry(youtube_id=XXXXXXX). My yt_service is initialized with a username, password, and a developer key. I use Programma... | [
"I've just deleted youtube video using gdata and ProgrammaticLogin()\nHere is some steps to reproduce:\nimport gdata.youtube.service\nyt_service = gdata.youtube.service.YouTubeService()\n\nyt_service.developer_key = 'developer_key'\nyt_service.email = 'email'\nyt_service.password = 'password'\nyt_service.Programmat... | [
6,
1
] | [] | [] | [
"django",
"gdata",
"gdata_api",
"python",
"youtube"
] | stackoverflow_0008475553_django_gdata_gdata_api_python_youtube.txt |
Q:
Please help: pylint does not work with Emacs23
I am trying to use Pylint with Emacs on Windows XP. My Emacs version is EmacsW32 23.1, pylint is 0.21.3 with Python 2.5. After easy_install pylint, I added the following lines to Emacs init file, copied form Emacs Wiki.
When I invoke the flymake-mode on a .py file, I... | Please help: pylint does not work with Emacs23 | I am trying to use Pylint with Emacs on Windows XP. My Emacs version is EmacsW32 23.1, pylint is 0.21.3 with Python 2.5. After easy_install pylint, I added the following lines to Emacs init file, copied form Emacs Wiki.
When I invoke the flymake-mode on a .py file, I can see the flymake starting the syntax check, the ... | [
"The program called by flymake should return 0 errorlevel or else flymake thinks there have been problems calling subprocesses.\nReading this answer and those patches, I have managed to run flymake with pylint :\nOn Windows, but you could do the same kind of thing on Un*x, I have created a batch file pycheckers.bat... | [
3,
0,
0
] | [] | [] | [
"emacs",
"pylint",
"python"
] | stackoverflow_0003827076_emacs_pylint_python.txt |
Q:
How many installations of macports do I need
Over the past couple of months I've set about using Wing IDE to do the vast majority of my programming. I chose Wing primarily because it works well with wxPython, allowing me to debug much more quickly than was the case when I was using TextWrangler alongside Terminal.... | How many installations of macports do I need | Over the past couple of months I've set about using Wing IDE to do the vast majority of my programming. I chose Wing primarily because it works well with wxPython, allowing me to debug much more quickly than was the case when I was using TextWrangler alongside Terminal. A quirk of Wing however is that there is no satis... | [
"No you don't need separate versions of macport, what you need is separate versions of python.\nClear steps to do it :\n\nInstall macports. You should be able to use port command after that. You should have /opt/local/bin first in your path automatically, if you are using the installer for Mac.\nInstall python 2.6 ... | [
3,
3
] | [] | [] | [
"32bit_64bit",
"macports",
"osx_snow_leopard",
"python"
] | stackoverflow_0008540636_32bit_64bit_macports_osx_snow_leopard_python.txt |
Q:
How to import data from scanned text into Django models
I have a hundreds of pages of "quiz" questions, multiple-choice options and associated answer keys and explanations. I'm trying to create a simple Django app to administer these questions. I have created a simple but effective Python parser to parse the scann... | How to import data from scanned text into Django models | I have a hundreds of pages of "quiz" questions, multiple-choice options and associated answer keys and explanations. I'm trying to create a simple Django app to administer these questions. I have created a simple but effective Python parser to parse the scanned, OCR'd pages into the proper objects.
I want to have a "ut... | [
"This is the working version I came up with. Dirty, but effective. Both @akonsu and @Ivan Kharlamov were helpful. Thanks...\nimport os, re, Levenshtein as lev, codecs\nfrom SimpleQuiz.quiz.models import Choice, Question\nfrom django.core.management.base import BaseCommand, CommandError\nimport optparse\n\nclass Com... | [
0,
0
] | [] | [] | [
"django",
"import",
"python"
] | stackoverflow_0007844630_django_import_python.txt |
Q:
example of python distutils package code that depends on other modules?
can someone point out a simple example of making a Python package using distutils that depends on other python modules being installed, e.g. numpy (a particular version) and scipy? I found very simple examples online but could not find an exa... | example of python distutils package code that depends on other modules? | can someone point out a simple example of making a Python package using distutils that depends on other python modules being installed, e.g. numpy (a particular version) and scipy? I found very simple examples online but could not find an example that depends on a known package. I want to find the easiest system where... | [
"Distutils by itself does not install dependencies. You need to use an add-on to Distutils, like pip or plain Distribute/setuptools.\n"
] | [
2
] | [] | [] | [
"distribution",
"distutils",
"installation",
"package_managers",
"python"
] | stackoverflow_0008540367_distribution_distutils_installation_package_managers_python.txt |
Q:
Embedding Fortran in Python with f2py
I need a script to recurse across a directory structure, extract numbers from files in the directories, then perform calculations on those numbers. I am using Python as the main language for the script, but wanted to use Fortran for the numerical computations. (I am more com... | Embedding Fortran in Python with f2py | I need a script to recurse across a directory structure, extract numbers from files in the directories, then perform calculations on those numbers. I am using Python as the main language for the script, but wanted to use Fortran for the numerical computations. (I am more comfortable with Fortran and it is a better to... | [
"I have never tried using f2py to wrap a full Fortran module. However, if you extract the itimes function from the module into its own file and then run the same f2py command, everything appears to work when I tried it locally (f2py v2, numpy 1.6.1, python 2.7.2, gfortran 4.1.2).\nAlso, note that you are not expli... | [
1
] | [] | [] | [
"f2py",
"fortran",
"python"
] | stackoverflow_0008526632_f2py_fortran_python.txt |
Q:
matplotlib: Centering period labels under the period's data in a time-series plot
matplotlib's axis-formatting options tend to fall flat when it comes to plotting and effectively labeling dense time-series data.
One problem is that tick labels are tied to ticks, so if you set axis ticks at an appropriate frequency... | matplotlib: Centering period labels under the period's data in a time-series plot | matplotlib's axis-formatting options tend to fall flat when it comes to plotting and effectively labeling dense time-series data.
One problem is that tick labels are tied to ticks, so if you set axis ticks at an appropriate frequency, there are usually too many labels. This also means that if you are plotting, say, dai... | [
"Have you looked at the tsplot capability in scikits.timeseries? It hasn't been maintained much recently, but it works pretty well. I'll be porting that code into pandas at some point in the relative near future.\n"
] | [
1
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0006260211_matplotlib_plot_python.txt |
Q:
bsddb in Python and Unix
I haven't heard of bsddb till recently.
http://www.oracle.com/us/products/database/berkeley-db/index.html
http://en.wikipedia.org/wiki/Berkeley_DB
I haven't been able to figure out what exactly it is. bsddb seems to be installed on my Mac but I definitely didn't install it. Is that because... | bsddb in Python and Unix | I haven't heard of bsddb till recently.
http://www.oracle.com/us/products/database/berkeley-db/index.html
http://en.wikipedia.org/wiki/Berkeley_DB
I haven't been able to figure out what exactly it is. bsddb seems to be installed on my Mac but I definitely didn't install it. Is that because bsddb comes installed by defa... | [
"BDB is a database system available on Unix machines for probably two or more decades. It originally provided single-process database services (not at all like MySQL or PostgreSQL database daemons that provide services for other processes) so that applications could focus on their code and save everyone the hassle ... | [
0
] | [] | [] | [
"bsddb",
"database",
"python"
] | stackoverflow_0008541424_bsddb_database_python.txt |
Q:
hadoop-streaming: reducer in pending state, doesn't start?
I have a map reduce job which was running fine until I started to see some failed map tasks like
attempt_201110302152_0003_m_000010_0 task_201110302152_0003_m_000010 worker1 FAILED
Task attempt_201110302152_0003_m_000010_0 failed to report status fo... | hadoop-streaming: reducer in pending state, doesn't start? | I have a map reduce job which was running fine until I started to see some failed map tasks like
attempt_201110302152_0003_m_000010_0 task_201110302152_0003_m_000010 worker1 FAILED
Task attempt_201110302152_0003_m_000010_0 failed to report status for 602 seconds. Killing!
-------
Task attempt_201110302152_0003_m... | [
"You should have a look at mapred.task.timeout. If you have a very large amount of data and few machines to process it, your task might be timing out. You can set this value to 0 which disables this timeout. \nAlternatively, if you can call context.progress or some equivalent function to say that something is happe... | [
1,
0
] | [] | [] | [
"hadoop",
"hadoop_streaming",
"mapreduce",
"python"
] | stackoverflow_0007956644_hadoop_hadoop_streaming_mapreduce_python.txt |
Q:
String Equivalence/Comparison in Python
I can't seem to compare strings properly in python, what is the correct way to compare it in the if condition?
Testfile = "test.txt"
with open(TestFile) as testSet:
line = testSet.read().rstrip('\n')
if "#*#*# ham" or "#*#*# spam" in line:
print line
My tes... | String Equivalence/Comparison in Python | I can't seem to compare strings properly in python, what is the correct way to compare it in the if condition?
Testfile = "test.txt"
with open(TestFile) as testSet:
line = testSet.read().rstrip('\n')
if "#*#*# ham" or "#*#*# spam" in line:
print line
My test.txt something like looks like this:
#*#*# h... | [
"Do:\nTestfile = \"test.txt\"\nwith open(TestFile) as testSet:\n for line in testSet:\n line = line.strip() \n if \"#*#*# ham\" in line or \"#*#*# spam\" in line: \n print line\n\ninstead of what you are doing. You are reading the whole file into the line variable, the way your code is.\... | [
4,
2,
0
] | [] | [] | [
"file",
"if_statement",
"python",
"string",
"string_comparison"
] | stackoverflow_0008541570_file_if_statement_python_string_string_comparison.txt |
Q:
Problems juggling system python and python 27 on Mac Snow Leopard
I had a lot of problems getting geoDjango installed on mac os x snow leopard.
After the dust settled, I realized that the system install of python (2.6) was on the recieivng end of psycopg2
Python 2.7 is on the system path. And when I invoke python ... | Problems juggling system python and python 27 on Mac Snow Leopard | I had a lot of problems getting geoDjango installed on mac os x snow leopard.
After the dust settled, I realized that the system install of python (2.6) was on the recieivng end of psycopg2
Python 2.7 is on the system path. And when I invoke python in the terminal, python 2.7 is the one the is fired up.
But if I do an ... | [
"The best way to solve this is to use virtualenv. When you create a virtual environment, you have the option (-p) of specifying which Python executable you want. Once you're in the virtualenv, you don't have to worry about it at all, and all your regular commands (including pip) will refer to the proper Python ex... | [
1,
0
] | [] | [] | [
"macos",
"psycopg2",
"python"
] | stackoverflow_0008539146_macos_psycopg2_python.txt |
Q:
If I rebuild Python will it break my Django installation?
Recently I was told I should rebuild Python 2.7.2 in order to get the Python interpreter behaving correctly as it's been acting strange lately.
If I rebuild Python will it break my Django installation and other eggs in the site-packages dir?
A:
Django it... | If I rebuild Python will it break my Django installation? | Recently I was told I should rebuild Python 2.7.2 in order to get the Python interpreter behaving correctly as it's been acting strange lately.
If I rebuild Python will it break my Django installation and other eggs in the site-packages dir?
| [
"Django itself uses no C modules, so rebuilding Python will not affect it. Third-party apps that do have C modules may be affected though, so make sure to test them after rebuilding.\n",
"I suggest you using Virtualenv for your work\n"
] | [
2,
1
] | [] | [] | [
"build",
"django",
"installation",
"python",
"rebuild"
] | stackoverflow_0008540923_build_django_installation_python_rebuild.txt |
Q:
How to automate the delegation of __special_methods__ in Python?
Let spam be an instance of some class Spam, and suppose that spam.ham is an object of some built-in type, say dict. Even though Spam is not a subclass of dict, I would like its instances to have the same API as a regular dict (i.e. the same methods ... | How to automate the delegation of __special_methods__ in Python? | Let spam be an instance of some class Spam, and suppose that spam.ham is an object of some built-in type, say dict. Even though Spam is not a subclass of dict, I would like its instances to have the same API as a regular dict (i.e. the same methods with the same signatures), but I want to avoid typing out a bazillion ... | [
"This may not be helpful if you need a solution that prohibits metaclasses as well, but here is the solution I came up with:\ndef _wrapper(func):\n def _wrapped(self, *args, **kwargs):\n return getattr(self.ham, func)(*args, **kwargs)\n return _wrapped\n\nclass DictMeta(type):\n def __new__(cls, nam... | [
5,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008541137_python.txt |
Q:
python import package - subpackage should not show up in symbol table
I am wondering why the directory (subpackage) that holds submodules in a python package shows up as a symbol when the package is imported. For instance, if I have this package:
PyModTest/ Top-level package
__ini... | python import package - subpackage should not show up in symbol table | I am wondering why the directory (subpackage) that holds submodules in a python package shows up as a symbol when the package is imported. For instance, if I have this package:
PyModTest/ Top-level package
__init__.py Initialize the package
Source/ ... | [
"Two things to note here:\n\nIn Python, modules are actual objects, and the dot that appears between their names represents an actual attribute access\nYou are doing a relative import, meaning that Source is actually PyModTest.Source (thanks to TokenMacGuy for pointing this out)\n\nSo: in order to import PyModTest.... | [
8
] | [] | [] | [
"python"
] | stackoverflow_0008541716_python.txt |
Q:
python subtract time and run if loop
I want to compare two times and if the new time is more than 2min then the if statement will print output, I can get the output of datetime.datetime.now() , but how do I check whether the old time is less than 2mins?
#!/usr/bin/env python
import datetime
from time import sleep... | python subtract time and run if loop | I want to compare two times and if the new time is more than 2min then the if statement will print output, I can get the output of datetime.datetime.now() , but how do I check whether the old time is less than 2mins?
#!/usr/bin/env python
import datetime
from time import sleep
now = datetime.datetime.now()
sleep(2)
... | [
"Subtracting two datetime instances returns a timedelta that has a total_seconds method:\ncontant = 2 * 60\ndiff = late-now\nif diff.total_seconds() <= constant:\n\n",
"This is only an answer to the update since the answer from sje397 was perfect.\nUse a format string like this to match the whole time string:\nnn... | [
3,
2,
1
] | [] | [] | [
"debian",
"linux",
"python"
] | stackoverflow_0008535913_debian_linux_python.txt |
Q:
How to easily extract ID from iTunes URL using Python
iTunes URLs look like the following:
http://itunes.apple.com/us/album/break-of-dawn/id472335316?ign-mpt=uo%3D
http://itunes.apple.com/us/app/monopoly-here-now-the-world/id299110947?mt=8
http://itunes.apple.com/es/app/revista-/id397781759?mt=8%3Futm_so%3Dtwitter... | How to easily extract ID from iTunes URL using Python | iTunes URLs look like the following:
http://itunes.apple.com/us/album/break-of-dawn/id472335316?ign-mpt=uo%3D
http://itunes.apple.com/us/app/monopoly-here-now-the-world/id299110947?mt=8
http://itunes.apple.com/es/app/revista-/id397781759?mt=8%3Futm_so%3Dtwitter
http://itunes.apple.com/app/id426698291&mt=8"
http://itune... | [
"import re\n\ndef get_id(toParse):\n return re.search('id(\\d+)', toParse).groups()[0]\n\nI'll let you figure out error handling...\n",
"You can use a regex something like \"/id(\\\\d+).*\"; the first capture group will have the id number in it. I think you can also write it as r\"/id(\\d+).*\" in Python.\n",
... | [
9,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0008541783_python_regex.txt |
Q:
Why is a line in this python function necessary? (memoized recursion)
I got the following code snippet from Peter Norvig's website; it's a decorator to enable memoization on function calls (caching prior calls to the function to change an exponential recursion into a simple dynamic program).
def memo(f):
tabl... | Why is a line in this python function necessary? (memoized recursion) | I got the following code snippet from Peter Norvig's website; it's a decorator to enable memoization on function calls (caching prior calls to the function to change an exponential recursion into a simple dynamic program).
def memo(f):
table = {}
def fmemo(*args):
if args not in table:
tabl... | [
"Since functions are objects just like anything else, you can set attributes on them. See:\n>>> def foo(): pass\n>>> foo.x = 1\n>>> foo.x\n1\n\nThe second-to-line sets the internal cache of values as an attribute on the function object, thus exposing it. This means that you can take a memoised function and fiddle w... | [
12
] | [] | [] | [
"decorator",
"python",
"recursion"
] | stackoverflow_0008542087_decorator_python_recursion.txt |
Q:
What does Django do with `MEDIA_ROOT`?
What does Django do with MEDIA_ROOT exactly? I never understood it. Since Django itself doesn't serve static media, and you have to set up apache or something similar for it, why does it care in which directory it sits?
A:
You're not the only one who wonders; check out Djan... | What does Django do with `MEDIA_ROOT`? | What does Django do with MEDIA_ROOT exactly? I never understood it. Since Django itself doesn't serve static media, and you have to set up apache or something similar for it, why does it care in which directory it sits?
| [
"You're not the only one who wonders; check out Django ticket #10650. Based on the comments by Django developers there, I think this pretty much sums up what MEDIA_ROOT is used for:\n\nUnfortunately, Django is also at fault for being far too vague in its docs about what\n MEDIA_ROOT and MEDIA_URL are used for. Se... | [
10,
2,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002303254_django_python.txt |
Q:
Correcting printed items in Python
I'd like to correct a script. But my head is nested. So I'd like to ask SO.
Script is:
from xml.dom.minidom import parse
from itertools import groupby
yXML = parse('/root/Desktop/gb/data/yConfig.xml')
servers = []
for AllConfigurations in yXML.getElementsByTagName('AllConfigura... | Correcting printed items in Python | I'd like to correct a script. But my head is nested. So I'd like to ask SO.
Script is:
from xml.dom.minidom import parse
from itertools import groupby
yXML = parse('/root/Desktop/gb/data/yConfig.xml')
servers = []
for AllConfigurations in yXML.getElementsByTagName('AllConfigurations'):
for DeployConfigurations in... | [
"Warning: this answer is huge.\nYou have a bunch of problems in your code.\nitertools.groupby() used incorrectly\nThe most relevant is that you are sorting and grouping your servers using two different key functions. When you group a sequence, it should be ordered by the same key function that will group it. In you... | [
2
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0008541698_python_xml.txt |
Q:
Is it possible to assign several functions to one URL in Django?
Say I have these functions in my views.py:
from django.shortcuts import render_to_response
def foo(request):
a = 2
return render_to_response('test.html', {'a': a})
def bar(request):
b = 3
return render_to_response('test.html', {'b':... | Is it possible to assign several functions to one URL in Django? | Say I have these functions in my views.py:
from django.shortcuts import render_to_response
def foo(request):
a = 2
return render_to_response('test.html', {'a': a})
def bar(request):
b = 3
return render_to_response('test.html', {'b': b})
This would be my urls.py:
urlpatterns = patterns('',
(r'^test/$... | [
"The idea behind your urls file is that you're telling the framework what function to call for a given url. If you give it more than one function, how will it know where to send the request?\nIf you want to separate out the functionality into a few different functions, the simplest solution is to create a dispatchi... | [
7
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008542158_django_python.txt |
Q:
Tornado async request timeout - how to check that user is still connected
I'm trying to code a web chat using the tornado.
The client (user) sends a long post request, during which I send him messages in response. But I am having problems with checking whether the user is online.
When a user sign out or simply clo... | Tornado async request timeout - how to check that user is still connected | I'm trying to code a web chat using the tornado.
The client (user) sends a long post request, during which I send him messages in response. But I am having problems with checking whether the user is online.
When a user sign out or simply close the tab / browser - everything is simple, executed on_connection_close() and... | [
"You might want to take look at tornadio2 which is Tornado+Socket.io, and implement multiplex connection, one to handle to push messages, the other is to ping the server so that you can check if the client is still connected or not. \nThe multiplex does not open multiple connections but uses the single connection t... | [
0
] | [] | [] | [
"python",
"tornado"
] | stackoverflow_0008196836_python_tornado.txt |
Q:
Connected Component Counting
In the standard algorithm for connected component counting, a disjoint-set data structure called union-find is used.
Why is this data structure used? I've written code to just search the image linearly, maintaining two linear buffers to store the current and next component counts for ... | Connected Component Counting | In the standard algorithm for connected component counting, a disjoint-set data structure called union-find is used.
Why is this data structure used? I've written code to just search the image linearly, maintaining two linear buffers to store the current and next component counts for each connected pixels by just exam... | [
"I didn't completely understand your question, you'd really gain for yourself in writing this up clearly and structuring your question.\nWhat I understand is that you want to do a connected component labeling in a 0-1 image by using the 8 neighborhood. If this is so your assumption that the resulting neighborhood g... | [
0,
0,
0
] | [] | [] | [
"c",
"c++",
"graph_algorithm",
"image_processing",
"python"
] | stackoverflow_0008264693_c_c++_graph_algorithm_image_processing_python.txt |
Q:
What are the downsides to defining a C macro that works like the Python "with" statement?
After playing around a bit with C preprocessors, I thought of a way to have something similar to a Pythonian with control structure, defined like this:
#define with(var) for(int i##__LINE__=0;i##__LINE__<1;)for(var;i##__LINE_... | What are the downsides to defining a C macro that works like the Python "with" statement? | After playing around a bit with C preprocessors, I thought of a way to have something similar to a Pythonian with control structure, defined like this:
#define with(var) for(int i##__LINE__=0;i##__LINE__<1;)for(var;i##__LINE__<1;++i##__LINE__)
Sample usage:
#include <cstdio>
#include "FileClass.hpp"
#include "with.hpp... | [
"\nis there any reason this isn't used everywhere?\n\nYes, C++ is not Python, and if I understood your code correctly, this does exactly the same:\n{\n FileClass file(\"test.txt\");\n printf(\"%s\\n\", file.readlines().c_str());\n}\n\nSo, what are the downsides? Unnatural syntax, usage of the preprocessor for cod... | [
6,
4,
1,
1,
0
] | [] | [] | [
"c++",
"control_structure",
"python"
] | stackoverflow_0008542320_c++_control_structure_python.txt |
Q:
Python working with classes
I am working with classes in Python 3 and I am having a hard time with them. I have two programs here (One is being imported into the other)
The idea is that you are making a list of employees and you have three classes of employee Hourly, Salary, and Volunteer.
I seem to be having an i... | Python working with classes | I am working with classes in Python 3 and I am having a hard time with them. I have two programs here (One is being imported into the other)
The idea is that you are making a list of employees and you have three classes of employee Hourly, Salary, and Volunteer.
I seem to be having an issue with my show_pay in each cla... | [
"You're inputting the salary as a string. Convert it.\nann_salary = int(input('Enter employee annual salary: '))\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008542244_python.txt |
Q:
How to make a button that returns the input filename of tkFileDialog.askopenfilename() as a string?
How can I create a snippet of code that will create a Tkinter Button widget that opens a tkFileDialog.askopenfilename() window, and when you click the "Open" button in the window, make it get the filename as a strin... | How to make a button that returns the input filename of tkFileDialog.askopenfilename() as a string? | How can I create a snippet of code that will create a Tkinter Button widget that opens a tkFileDialog.askopenfilename() window, and when you click the "Open" button in the window, make it get the filename as a string, and insert it into an entry.
Here is what I have.
iconEntry = Entry(iconRow)
iconEntry.pack()
def get... | [
"I've got it myself.\nroot = Tk()\n\ndef getFIleName(varName, entryName):\n varName = tkFileDialog.askopenfilename()\n entryName.insert(0, varName)\n\niconButton = Button(root, text=\"Browse\", command=(lambda: getImageName(campIcon, iconEntry)))\niconButton.pack()\n\n"
] | [
4
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0008514119_python_tkinter.txt |
Q:
How to forward email using Python
First, let me say, I already know that this was asked at Forwarding an email with python smtplib already.
The reason that I am posting something so closely related to that question is that I have tried using the answers to that question, I have tried changing things, I have searc... | How to forward email using Python | First, let me say, I already know that this was asked at Forwarding an email with python smtplib already.
The reason that I am posting something so closely related to that question is that I have tried using the answers to that question, I have tried changing things, I have searched Google and relentlessly monkeyed wi... | [
"More than likely, the Received: headers of the original email are causing gmail to drop the message. Try removing all of them before forwarding it. \nIf that doesn't fix it, print out the headers and code it to remove all of the ones that would not normally be there on a newly composed message. \nHowever, why forw... | [
1
] | [] | [] | [
"forward",
"gmail",
"gmail_imap",
"python",
"smtp"
] | stackoverflow_0008542021_forward_gmail_gmail_imap_python_smtp.txt |
Q:
python manage.py sql is throwing a no suitable image found exception
I have macbook pro running OS X 10.7 on Intel processor. I have installed Django 1.3.1, MySQL-python 1.2.3. All the packages installed fine. When I execute command "python manage.py sql poll", I'm running into the following exception.
Traceback (... | python manage.py sql is throwing a no suitable image found exception | I have macbook pro running OS X 10.7 on Intel processor. I have installed Django 1.3.1, MySQL-python 1.2.3. All the packages installed fine. When I execute command "python manage.py sql poll", I'm running into the following exception.
Traceback (most recent call last):
File "manage.py", line 14, in <module>
execu... | [
"Chances are that the Python you are using (the Apple-supplied Python 2.7.1, perhaps) is running in 64-bit mode but the MySQLdb extension module that you've installed is 32-bit only. Or, possibly, the reverse. The output of this shell command should tell you what architectures the extension module was compiled fo... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008542673_django_python.txt |
Q:
Writing functions to work on vectors and matrices
As part of a larger function, I'm writing some code to generate a vector/matrix (depending on the input) containing the mean value of each column of the input vector/matrix 'x'. These values are stored in a vector/matrix of the same shape as the input vector.
My pr... | Writing functions to work on vectors and matrices | As part of a larger function, I'm writing some code to generate a vector/matrix (depending on the input) containing the mean value of each column of the input vector/matrix 'x'. These values are stored in a vector/matrix of the same shape as the input vector.
My preliminary solution for it to work on both a 1-D and mat... | [
"You don't need to distinguish between vectors and matrices for the mean calculation itself - if you use the axis parameter Numpy will perform the calculation along the vector (for vectors) or columns (for matrices). And then to construct the output, you can use a good old-fashioned list comprehension, although it ... | [
6,
3
] | [] | [] | [
"matlab",
"numpy",
"python",
"scipy"
] | stackoverflow_0008540568_matlab_numpy_python_scipy.txt |
Q:
Scrapy is following and scraping non-allowed links
I have a CrawlSpider set up to following certain links and scrape a news magazine where the links to each issue follow the following URL scheme:
http://example.com/YYYY/DDDD/index.htm where YYYY is the year and DDDD is the three or four digit issue number.
I only ... | Scrapy is following and scraping non-allowed links | I have a CrawlSpider set up to following certain links and scrape a news magazine where the links to each issue follow the following URL scheme:
http://example.com/YYYY/DDDD/index.htm where YYYY is the year and DDDD is the three or four digit issue number.
I only want issues 928 onwards, and have my rules below. I don'... | [
"You need to pass deny arguments to SgmlLinkExtractor which collects links to follow. And you don't need to create so many Rule's if they call one function parse_item. I would write your code as:\nrules = (\n Rule(SgmlLinkExtractor(\n allow = ('\\d\\d\\d\\d/(92[8-9]|9[3-9][0-9]|\\d\\d\\d\\... | [
7
] | [] | [] | [
"python",
"scrapy",
"screen_scraping",
"web_crawler"
] | stackoverflow_0008537687_python_scrapy_screen_scraping_web_crawler.txt |
Q:
Being a good citizen and web-scraping
I have a two part question.
First, I'm writing a web-scraper based on the CrawlSpider spider in Scrapy. I'm aiming to scrape a website that has many thousands (possible into the hundreds of thousands) of records. These records are buried 2-3 layers down from the start page. So... | Being a good citizen and web-scraping | I have a two part question.
First, I'm writing a web-scraper based on the CrawlSpider spider in Scrapy. I'm aiming to scrape a website that has many thousands (possible into the hundreds of thousands) of records. These records are buried 2-3 layers down from the start page. So basically I have the spider start on a cer... | [
"\nIs there possibly a way to do thing's incrementally \n\nI'm using Scrapy caching ability to scrape site incrementaly\nHTTPCACHE_ENABLED = True\nOr you can use new 0.14 feature Jobs: pausing and resuming crawls\n\nor put a pause in between different requests?\n\ncheck this settings:\nDOWNLOAD_DELAY \nRANDOMIZE... | [
6
] | [
"You have to start crawling and log everything. In case you get banned, you can add sleep() before pages request.\nChanging User-Agent is a good practise, too (http://www.user-agents.org/ http://www.useragentstring.com/ )\nIf you get banned by ip, use proxy to bypass it. Cheers.\n"
] | [
-2
] | [
"python",
"scrapy",
"screen_scraping"
] | stackoverflow_0008542552_python_scrapy_screen_scraping.txt |
Q:
Python 2.7 - Thread-safe and url keyword not recognized in eclipse with google app engine SDK and Pydev
I am using Eclipse with Pydev and googleAppengine. I have python 2.7 installed. I am trying to run the easiest first program about hello world which is available here: http://code.google.com/appengine/docs/pytho... | Python 2.7 - Thread-safe and url keyword not recognized in eclipse with google app engine SDK and Pydev | I am using Eclipse with Pydev and googleAppengine. I have python 2.7 installed. I am trying to run the easiest first program about hello world which is available here: http://code.google.com/appengine/docs/python/gettingstartedpython27/helloworld.html
The problem is my app.yaml is not recognizing Thread-safe and url ke... | [
"Python 2.7 isn't yet supported via the Google Plugin for Eclipse.\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0008533513_google_app_engine_python.txt |
Q:
Splitting a string after punctuation while including punctuation
I'm trying to split a string of words into a list of words via regex. I'm still a bit of a beginner with regular expressions.
I'm using nltk.regex_tokenize, which is yielding results that are close, but not quite what I want.
This is what I have so f... | Splitting a string after punctuation while including punctuation | I'm trying to split a string of words into a list of words via regex. I'm still a bit of a beginner with regular expressions.
I'm using nltk.regex_tokenize, which is yielding results that are close, but not quite what I want.
This is what I have so far:
>>> import re, codecs, nltk
>>> sentence = "détesté Rochard ! m'ét... | [
"It seems that the desired output is not consistent with your input sentence\n\n[u\"qu'\", u'on'] : I can't figure out from where did these two matches were determined from your sentence\nWhy u'.' was not part of u'hyper-cool' (Assuming you want the punctuation as part of the word.\nWhy u\"'\" was not part of u\"C'... | [
1
] | [] | [] | [
"nltk",
"punctuation",
"python",
"regex",
"tokenize"
] | stackoverflow_0008543087_nltk_punctuation_python_regex_tokenize.txt |
Q:
I want to use matplotlib in osx lion
I installed matplotlib from macports, and version of python is 2.7.1.
$ sudo port install py27-matplotlib py27-matplotlib-basemap
I wrote a sample program below.
#!/usr/bin/python
# -*- coding: utf-8 -*-
from pylab import *
plot([1,2,3])
show()
But this didn't work correctly... | I want to use matplotlib in osx lion | I installed matplotlib from macports, and version of python is 2.7.1.
$ sudo port install py27-matplotlib py27-matplotlib-basemap
I wrote a sample program below.
#!/usr/bin/python
# -*- coding: utf-8 -*-
from pylab import *
plot([1,2,3])
show()
But this didn't work correctly with error log "no module named pylab".
A... | [
"To ensure a compatible environment, MacPorts Python packages automatically install a MacPorts Python. By default, you can invoke it via /opt/local/bin/python2.7. And that's where you will find the MacPorts installed matplotlib et al. /usr/bin/python will invoke the Apple-supplied system Python 2.7.1 and, when yo... | [
4,
0
] | [] | [] | [
"matplotlib",
"osx_lion",
"python"
] | stackoverflow_0008543148_matplotlib_osx_lion_python.txt |
Q:
Counting passed seconds
How can we count the number of seconds
passed since the start of the day 0.00 ?
Is there a module
function or do we have to do it ourselves?
A:
from datetime import datetime, time
now = datetime.now()
beginning_of_day = datetime.combine(now.date(), time(0))
print (now - beginning_of_day... | Counting passed seconds | How can we count the number of seconds
passed since the start of the day 0.00 ?
Is there a module
function or do we have to do it ourselves?
| [
"from datetime import datetime, time\n\nnow = datetime.now()\nbeginning_of_day = datetime.combine(now.date(), time(0))\nprint (now - beginning_of_day).seconds\n\nSee docs for datetime module here.\n"
] | [
9
] | [] | [] | [
"pys60",
"python"
] | stackoverflow_0008543725_pys60_python.txt |
Q:
Python saving string to file. Unicode error
I am extracting data from a Google spreadsheet using Spreadsheet API in Python. I can print every row of my spreadsheet on the commandline with a for loop but some of the text contain symbols e.g. celsius degree symbol(little circle). As I print these rows on the comma... | Python saving string to file. Unicode error | I am extracting data from a Google spreadsheet using Spreadsheet API in Python. I can print every row of my spreadsheet on the commandline with a for loop but some of the text contain symbols e.g. celsius degree symbol(little circle). As I print these rows on the commandline I want to write them to a file. But I get ... | [
"You want to decode it from whatever encoding it's in:\ndecoded_str = encoded_str.decode('utf-8')\n\nFor more information on how to deal with unicode strings, you should go over http://docs.python.org/howto/unicode.html\n",
"import unicodedata\ndecoded = unicodedata.normalize('NFKD', encoded).decode('UTF-8', 'ign... | [
5,
0
] | [
"''.join(c for c in current if ord(c) < 128)\n\n"
] | [
-1
] | [
"ascii",
"python",
"unicode",
"utf"
] | stackoverflow_0008543690_ascii_python_unicode_utf.txt |
Q:
How do I convert a file's format from Unicode to ASCII using Python?
I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.
What is the best way to convert the entire file format using Python?
A:
You can conve... | How do I convert a file's format from Unicode to ASCII using Python? | I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.
What is the best way to convert the entire file format using Python?
| [
"You can convert the file easily enough just using the unicode function, but you'll run into problems with Unicode characters without a straight ASCII equivalent.\nThis blog recommends the unicodedata module, which seems to take care of roughly converting characters without direct corresponding ASCII values, e.g.\... | [
44,
11,
4,
2,
2,
2,
0,
0
] | [] | [] | [
"ascii",
"encoding",
"file",
"python",
"unicode"
] | stackoverflow_0000175240_ascii_encoding_file_python_unicode.txt |
Q:
How to create an (x,y) list in which only one of the variables change but the other one stays the same?
SHIPS = (('AirCraftCarrier', 5), ('Battleship', 4),
('Submarine', 3), ('Destroyer', 3), ('PatrolBoat', 2))
position = ('v', 'h')
def setShip(self, board, graphics):
maxval = board.getSize() - 1... | How to create an (x,y) list in which only one of the variables change but the other one stays the same? | SHIPS = (('AirCraftCarrier', 5), ('Battleship', 4),
('Submarine', 3), ('Destroyer', 3), ('PatrolBoat', 2))
position = ('v', 'h')
def setShip(self, board, graphics):
maxval = board.getSize() - 1
coords = []
sizes = [(v) for k, v in SHIPS]
for i in sizes:
legal = Fals... | [
"You must take out the variables you want not to change from the while loop that is checking the available positions. You can do this in more than one way. One option is this: \ndef setShip(self, board, graphics):\n maxval = board.getSize() - 1\n coords = []\n sizes = [v for k, v in SHIPS]\n ... | [
0
] | [] | [] | [
"list",
"python",
"tuples"
] | stackoverflow_0008515999_list_python_tuples.txt |
Q:
python26.dll was not found
When I try pyuic4 -o hello.py hello.ui in command prompt, an error occurs saying
python26.dll was not found
I downloaded the same and copied in C:\windows\system32\.... But now I'm getting the following error:
C:\>pyuic4 -o hello.py hello.ui
Traceback (most recent call last):
File "... | python26.dll was not found | When I try pyuic4 -o hello.py hello.ui in command prompt, an error occurs saying
python26.dll was not found
I downloaded the same and copied in C:\windows\system32\.... But now I'm getting the following error:
C:\>pyuic4 -o hello.py hello.ui
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\Py... | [
"\ni installed PyQt-Py2.6-gpl-4.7-1.exe and python-2.5.msi\n\nBinary packages are compiled against a specific python version.\nYou should always install the binary package corresponding to your installed python version. The python version is often indicated in the name of the package. In your case, Py2.6 indicates... | [
4,
2
] | [] | [] | [
"pyqt4",
"python",
"qt"
] | stackoverflow_0008531003_pyqt4_python_qt.txt |
Q:
IE7 throws "parseerror" parsing JSON using jQuery
IE7 throws an exception: "jquery: parseerror" when running the following code. It works in all other browsers I've tested (Firefox, Opera, Chrome, Chromium).
Script:
function check(){
$("#form").ajaxSubmit({
url: "/send-file",
... | IE7 throws "parseerror" parsing JSON using jQuery | IE7 throws an exception: "jquery: parseerror" when running the following code. It works in all other browsers I've tested (Firefox, Opera, Chrome, Chromium).
Script:
function check(){
$("#form").ajaxSubmit({
url: "/send-file",
dataType: "json",
success:
... | [
"the problem seems to be in the jQuery plugin for uploading files using hidden frame. If it is the plugin, than it contains an error (if i recall correctly it reads the contents of the json from the body tag). I wanted to chat on the issue with the author, but the facebook comments in his blog raised an exception. ... | [
1,
0
] | [] | [] | [
"jquery",
"json",
"pylons",
"python"
] | stackoverflow_0008535542_jquery_json_pylons_python.txt |
Q:
Some NLP stuff to do with grammar, tagging, stemming, and word sense disambiguation in Python
Background (TLDR; provided for the sake of completion)
Seeking advice on an optimal solution to an odd requirement.
I'm a (literature) student in my fourth year of college with only my own guidance in programming. I'm com... | Some NLP stuff to do with grammar, tagging, stemming, and word sense disambiguation in Python | Background (TLDR; provided for the sake of completion)
Seeking advice on an optimal solution to an odd requirement.
I'm a (literature) student in my fourth year of college with only my own guidance in programming. I'm competent enough with Python that I won't have trouble implementing solutions I find (most of the time... | [
"I think that the comment above on n-gram language model fits your requirements better than parsing and tagging. Parsers and taggers (unless modified) will suffer from the lack of right context of the target word (i.e., you don't have the rest of the sentence available at time of query). On the other hand, language... | [
5
] | [] | [] | [
"grammar",
"nlp",
"nltk",
"python",
"tagging"
] | stackoverflow_0008541447_grammar_nlp_nltk_python_tagging.txt |
Q:
Python BeautifulSoup is unnecessarily slow
While this code works pretty fast:
for olay in soup("li", {"class":"textb"}):
tanim = olay("strong")
try:
print tanim[0]
except IndexError:
pass
Getting string property like this makes this code considerably slower:
for olay in soup("li", {"cl... | Python BeautifulSoup is unnecessarily slow | While this code works pretty fast:
for olay in soup("li", {"class":"textb"}):
tanim = olay("strong")
try:
print tanim[0]
except IndexError:
pass
Getting string property like this makes this code considerably slower:
for olay in soup("li", {"class":"textb"}):
tanim = olay("strong")
t... | [
"If you just want to print the string representation of tanim[0]. You should just do: print str(tanim[0]). Also, do a dir(tanim[0]) to see if it has a property called string at all.\nfor olay in soup(\"li\", {\"class\":\"textb\"}):\n tanim = olay(\"strong\")\n try:\n print str(tanim[0])\n except Ind... | [
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0008544199_beautifulsoup_python.txt |
Q:
spoj palindrome, why isn't this being accepted?
The next code runs fine on my computer and does exactly what the problem states so why isn't it accepted? it keeps telling me time limit exceeded but this runs in under half a second...
The problem is this:
Input
The first line contains integer t, the number of test ... | spoj palindrome, why isn't this being accepted? | The next code runs fine on my computer and does exactly what the problem states so why isn't it accepted? it keeps telling me time limit exceeded but this runs in under half a second...
The problem is this:
Input
The first line contains integer t, the number of test cases. Integers K are given in the next t lines.
Outp... | [
"I do not know the exact formulation of the problem, but I think it is too slow for more complicated examples. Consider for instance the input \nFind_Smallest_Palindrome(9999999900000000)\n\nThis will take very long with your code. I think, they test the given methods with such examples.\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0008544355_python.txt |
Q:
python, debugging, function is not working
I need some help to get my function to work:
the function differences should take two codons (strings) and return a list containing 0 if the letter on the position is the same and 1 if it is not, eg. differences('TAG',TAA') should return [0,0,1]
def differences(codon1, co... | python, debugging, function is not working | I need some help to get my function to work:
the function differences should take two codons (strings) and return a list containing 0 if the letter on the position is the same and 1 if it is not, eg. differences('TAG',TAA') should return [0,0,1]
def differences(codon1, codon2):
lst=[]
for i in range(len(codon1)... | [
"you're calling s=h(element,codon) when h is defined to accept only one parameter:\ndef h(codon):\n"
] | [
2
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0008544426_debugging_python.txt |
Q:
regarding multiple choice field
I have many objects in categories. like
English
etc
French
I tried to display that categories into multiplechocieField. So I'm using following code. But its just display last object like.
French
Here is my forms.py
class UserProfileForm(forms.Form):
categories = Category.object... | regarding multiple choice field | I have many objects in categories. like
English
etc
French
I tried to display that categories into multiplechocieField. So I'm using following code. But its just display last object like.
French
Here is my forms.py
class UserProfileForm(forms.Form):
categories = Category.objects.all()
for c in categories:
CHO... | [
"You are reassigning (not appending) a new value to CHOICES in every iteration of the for loop. It should be something like:\nclass UserProfileForm(forms.Form):\ncategories = Category.objects.all()\nCHOICES = []\nfor c in categories:\n CHOICES.append((c.id, c.name))\n\nanswers = forms.MultipleChoiceField(widget... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008544407_django_python.txt |
Q:
Django + OsX Lion + Mysql with XAMPP
I have the following on my MacBook with Osx Lion:
Mysql running with xampp (http://www.apachefriends.org/it/xampp.html)
Django 1.3 running in a virtualenv
I installed Mysql-python with pip install MySQL-python
but when trying to use manage.py syncdb I get the following error:... | Django + OsX Lion + Mysql with XAMPP | I have the following on my MacBook with Osx Lion:
Mysql running with xampp (http://www.apachefriends.org/it/xampp.html)
Django 1.3 running in a virtualenv
I installed Mysql-python with pip install MySQL-python
but when trying to use manage.py syncdb I get the following error:
(django_1.3)Daniel-Mac:fz_biblio daniel$ ... | [
"I finally sorted out the problem installing the right version of MySQL for my machine.\nI installed MySQL 64bit version --> Mac OS X ver. 10.6 (x86, 64-bit)\nAfter installing it Everything started working fine. I guess it was due to the fact that my previous installation was a 32bit one, that why mysql-python was... | [
0
] | [] | [] | [
"django",
"mysql",
"mysql_python",
"osx_lion",
"python"
] | stackoverflow_0007302249_django_mysql_mysql_python_osx_lion_python.txt |
Q:
Handle multiple simultaneous clients in python
I want to keep a socket open accepting unlimited number of clients, and be able to send independent data to each one, giving a ID for each client or something like that.
It seems easy in my mind but hard to put in the code as always.
I've tryed with asyncore but i can... | Handle multiple simultaneous clients in python | I want to keep a socket open accepting unlimited number of clients, and be able to send independent data to each one, giving a ID for each client or something like that.
It seems easy in my mind but hard to put in the code as always.
I've tryed with asyncore but i cant get it to work, maybe im using the wrong plugin i ... | [
"Python twistted - http://twistedmatrix.com/\n"
] | [
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0008544551_python_sockets.txt |
Q:
PIL convert picture leads to bad result
i take a photo via a DSLR, then ps it, and want to resize it using PIL. here is the core code
image = Image.open(img_obj, 'r')
for pic_size_name, pic_size_val in pic_sizes.items():
width, height = [int(item) for item in pic_size_val.split('x')]
img_width, img_height ... | PIL convert picture leads to bad result | i take a photo via a DSLR, then ps it, and want to resize it using PIL. here is the core code
image = Image.open(img_obj, 'r')
for pic_size_name, pic_size_val in pic_sizes.items():
width, height = [int(item) for item in pic_size_val.split('x')]
img_width, img_height = image.size
pic_save_path = os.path.join... | [
"WHen downloading and looking at both images in GIMP, however, the difference is that the one in Flickr sported an embedded Color Profile, while the one generated by PIL did not. As I don't notice any contrast or sharpness differences, I suppose the resulting color difference is what you are troubled about.\nYou ha... | [
2
] | [] | [] | [
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0008543426_image_processing_python_python_imaging_library.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.