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:
Summing non-integers in Python
Is it possible to take the sum of non-integers in Python?
I tried the command
sum([[1], [2]])
to get [1, 2], but it gives the error
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
sum([[1], [2]])
TypeError: unsupported operand type(s) for +: 'int' and 'list'
I suspect sum tries to add 0 to the list [1], resulting in failure. I'm sure there are many hacks to work around this limitation (wrapping stuff in a class, and implementing __radd__ manually), but is there a more elegant way to do this?
A:
It looks like you want this:
>>> sum([[1],[2]], [])
[1, 2]
You're right that it's trying to add 0 to [1] and getting an error. The solution is to give sum an extra parameter giving the start value, which for you would be the empty list.
Edit: As gnibbler says, though, sum is not a good way to concatenate things. And if you just want to aggregate a sequence of things, you should probably use reduce rather than make your own __radd__ function just to use sum. Here's an example (with the same poor behavior as sum):
>>> reduce(lambda x, y: x+y, [[1],[2]])
[1, 2]
A:
It's a bad idea to use sum() on anything other than numbers, as it has quadradic performance for sequences/strings/etc.
Better to use a list comprehension to sum your lists
[j for i in [[1],[2]] for j in i]
A:
It is more efficient to concatenate using itertools.chain.
>>> m = [[i] for i in range(200)]
>>> m
[[0], [1], [2], [3], [4], [5], [6], [7], [8], ...]
>>> from itertools import *
>>> list(chain(*m))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ...]
Personally, I prefer this over list comprehension as it's hard to remember which for loop comes first. There is even a more efficient variant, list(chain.from_iterable(m)).
Microbenchmark results (with Python 3 using the timeit module. A list size of p x q means m = [list(range(q)) for _ in range(p)]):
list size | chain(*m) | sum(m,[]) | list comp | flatten |
----------+------------+---------------+------------+------------+
2 x 1 | 1.78 µs | 0.646 µs | 0.905 µs | 1.49 µs |
20 x 1 | 4.37 µs | 7.49 µs | 5.19 µs | 3.59 µs |
200 x 1 | 26.9 µs | 134 µs | 40 µs | 24.4 µs |
2000 x 1 | 233 µs | 12.2 ms | 360 µs | 203 µs |
----------+------------+---------------+------------+------------+
2 x 1 | 1.78 µs | 0.646 µs | 0.905 µs | 1.49 µs |
2 x 10 | 2.55 µs | 0.899 µs | 3.14 µs | 2.2 µs |
2 x 100 | 9.07 µs | 2.03 µs | 17.2 µs | 8.55 µs |
2 x 1000 | 51.3 µs | 21.9 µs | 139 µs | 49.5 µs |
----------+------------+---------------+------------+------------+
chain(*m) -> list(chain(*m))
sum(m,[]) -> sum(m, [])
list comp -> [j for i in m for j in i]
flatten -> icfi = chain.from_iterable; list(icfi(m))
It shows that sum is efficient only when the outer list size is very short. But then you have an even more efficient variant: m[0]+m[1].
A:
As the docs say,
The iterable‘s items are normally
numbers, and are not allowed to be
strings.
What this means is that the tedious process of actually forbidding anything but numbers (except for forbidding summing strings, a particularly heinous and common error) was eschewed -- if you're summing anything but numbers, you'll probably destroy your program's performance for no good purpose, but, hey, Python's not really about stopping programmers from doing every kind of terrible mistake.
If you do insist on doing things the wrong way, as other answers have mentioned, using sum's third parameter (as the starting value, instead of the default, 0) is the right way to do the wrong thing;-). So, the literal answer to your question:
Is it possible to take the sum of
non-integers in python?
(once the very erroneous suggestion is removed, that integers behave any differently than any other kind of numbers here, by rephrasing it as "non-numbers" -- summing any kind of numbers is quite fine, and does not necessarily require any special precaution, though math.fsum is better for summing floats) is...: "yes, it is possible (just like it's possible to use a hammer to bang your thumb quite painfully) -- mind you, it's absolutely not advisable (just as hammering your thumb isn't), but, it's definitely possible, if you really insist";-).
A:
I little misunderstood your question to be of addition and made this solution:
# for me the guestion looks for me to do sum of sum of list
# i would do like this
list_of_numlists=[[1,2,3],[2,3,4]]
print "Input =",list_of_numlists
sum_of_it=sum(sum(x) for x in list_of_numlists)
print "Sum = %i" % sum_of_it
## --> Sum = 15
# second version to understand the request is
sum_of_items=[sum(x) for x in zip(*list_of_numlists)]
print "Sum of each is", sum_of_items
""" Output:
Input = [[1, 2, 3], [2, 3, 4]]
Sum = 15
Sum of each is [3, 5, 7]
"
""
Actually you should not talk about sum but concatenating or joining sequences.
A:
sum(iterable[, start])
Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and are not allowed to be strings.
In [26]: sum([[1],[2]], [])
Out[26]: [1, 2]
As in the Docs...
By the way Gabe has given the right solution to use reduce(lambda x, y: x+y, [[1],[2]]).
Alternatively you can use a lay man method:-
In [69]: l = [[1],[2]]
In [70]: a = str(l[0]).strip('[]')
In [71]: b = str(l[1]).strip('[]')
In [72]: l = [int(a), int(b)]
In [73]: l
Out[73]: [1, 2]
A:
For case of one element sequences there is also special solution:
m = [[i] for i in range(200)]
list_of_m = list((zip(*m))[0])
print list_of_m
Also if you have strings in list you can use the standard Python join to catenate
''.join(m)
| Summing non-integers in Python | Is it possible to take the sum of non-integers in Python?
I tried the command
sum([[1], [2]])
to get [1, 2], but it gives the error
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
sum([[1], [2]])
TypeError: unsupported operand type(s) for +: 'int' and 'list'
I suspect sum tries to add 0 to the list [1], resulting in failure. I'm sure there are many hacks to work around this limitation (wrapping stuff in a class, and implementing __radd__ manually), but is there a more elegant way to do this?
| [
"It looks like you want this:\n>>> sum([[1],[2]], [])\n[1, 2]\n\nYou're right that it's trying to add 0 to [1] and getting an error. The solution is to give sum an extra parameter giving the start value, which for you would be the empty list.\nEdit: As gnibbler says, though, sum is not a good way to concatenate thi... | [
10,
9,
6,
3,
1,
0,
0
] | [] | [] | [
"python",
"sum"
] | stackoverflow_0003315365_python_sum.txt |
Q:
call program with arguments
i would like to start a python file (.py) with arguments and receive the output of it after it is finished. i have already heard about "popen" and "subprocess.call" but i could not find any tutorials how to use them
does anyone know a good tutorial?
A:
You don't need them ; just launch your file as a program giving argument like
./main.py arg1 arg2 arg3 >some_file
(for that your file must begin with something like #!/usr/bin/env python)
Using sys module you can access them :
arg1 = sys.argv[1]
arg2 = sys.argv[2]
arg3 = sys.argv[3]
A:
i would like to start a python file (.py) with arguments and receive the output of it after it is finished.
Step 1. Don't use subprocess. You're doing it wrong.
Step 2. Read the Python file you want to run. Let's call it runme.py.
Step 3. Read it again. If it's competently written, there is a block of code that starts if __name__ == "__main__":. What follows is the "external interface" to that file. Since you provided no information in the question, I'll assume it looks like this.
if __name__ == "__main__":
main()
Step 4. Read the "main" function invoked by the calling script. Since you provided no information, I'll assume it looks like this.
def main():
options, args = parse_options()
for name in args:
process( options, file )
Keep reading to be sure you see how parse_options and process work. I'll assume parse_options uses optparse.
Step 5. Write your "calling" script.
import runme
import sys
import optparse
options = options= optparse.Values({'this':'that','option':'arg','flag':True})
with open( "theoutput.out", "w" ) as results:
sys.stdout= results
for name in ('some', 'list', 'of', 'arguments' ):
runme.process( options, name )
This is the correct way to run a Python file from within Python.
Actually figure out the interface for the thing you want to run. And run it.
A:
runme.py
print 'catch me'
main.py
import sys
from StringIO import StringIO
new_out = StringIO()
old_out = sys.stdout
sys.stdout = new_out
import runme
sys.stdout = old_out
new_out.seek(0)
print new_out.read()
and...
$ python main.py
catch me
A:
Unless you mean you want to start the Python file from within Python? In which case it's even nicer:
import nameOfPythonFile
| call program with arguments | i would like to start a python file (.py) with arguments and receive the output of it after it is finished. i have already heard about "popen" and "subprocess.call" but i could not find any tutorials how to use them
does anyone know a good tutorial?
| [
"You don't need them ; just launch your file as a program giving argument like\n./main.py arg1 arg2 arg3 >some_file\n\n(for that your file must begin with something like #!/usr/bin/env python)\nUsing sys module you can access them :\narg1 = sys.argv[1]\narg2 = sys.argv[2]\narg3 = sys.argv[3]\n\n",
"\ni would like... | [
6,
5,
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0003316961_python_python_3.x.txt |
Q:
script for mounting an iso on another server
i need to mount a iso on another linux system
is there any way to send mount command to the linux system?
Thanks
A:
SSH seems to be your best bet. Although I have never used it, http://commandline.org.uk/python/sftp-python-really-simple-ssh/ seems to be a good option.
import ssh
s = ssh.Connection('[Target Machine]')
s.execute('mount -o loop [ISO File] [Mount Point]')
s.close()
A:
import subprocess
subprocess.call(['ssh', 'user@host', 'mount', '-o', 'loop', '-t', 'iso9660', '<isofilename>', '<mountpoint>'])
| script for mounting an iso on another server | i need to mount a iso on another linux system
is there any way to send mount command to the linux system?
Thanks
| [
"SSH seems to be your best bet. Although I have never used it, http://commandline.org.uk/python/sftp-python-really-simple-ssh/ seems to be a good option.\nimport ssh\ns = ssh.Connection('[Target Machine]')\ns.execute('mount -o loop [ISO File] [Mount Point]')\ns.close()\n\n",
"import subprocess\nsubprocess.call(['... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003317481_python.txt |
Q:
Using serial over lan with python
I'd like to write a python script to gather data from serial over lan but I can't seem to find a place to start with IPMI. I've looked at OpenIPMI's python bindings but there doesn't seem to be any documentation. Perhaps I can use the subprocess module and ipmitool? I'm not sure that would be simple though. Does anyone have any experience with this? How can I capture serial over lan data in python? Thanks.
A:
Have you seen this thread that has a sample OpenIPMI python program?
And the OpenIPMI documentation (pdf)?
| Using serial over lan with python | I'd like to write a python script to gather data from serial over lan but I can't seem to find a place to start with IPMI. I've looked at OpenIPMI's python bindings but there doesn't seem to be any documentation. Perhaps I can use the subprocess module and ipmitool? I'm not sure that would be simple though. Does anyone have any experience with this? How can I capture serial over lan data in python? Thanks.
| [
"Have you seen this thread that has a sample OpenIPMI python program?\nAnd the OpenIPMI documentation (pdf)?\n"
] | [
2
] | [] | [] | [
"api",
"networking",
"python",
"serial_port"
] | stackoverflow_0003311516_api_networking_python_serial_port.txt |
Q:
Nested loop comparison in Python,Java and C
The following code in python takes very long to run. (I couldn't wait until the program ended, though my friend told me for him it took 20 minutes.)
But the equivalent code in Java runs in approximately 8 seconds and in C it takes 45 seconds.
I expected Python to be slow but not this much, and in case of C which I expected to be faster than Java was actually slower. Is the JVM using some loop unrolling technique to achieve this speed? Is there any reason for Python being so slow?
import time
st=time.time()
for i in xrange(0,100000):
for j in xrange(0,100000):
continue;
print "Time taken : ",time.time()-st
A:
Your test is not measuring anything meaningful.
A language's performance in the real world has little to do with how quickly it executes a tight loop.
Frankly, I'm intrigued that C and Java took as long as they did; I would have expected both of their compilers to realize that there was nothing happening inside the inner loop, and have optimized both of them away into nonexistence (and 0 seconds).
Python, on the other hand, is still interpreted (I could be wrong about this). In any case, it looks like the outer loop is needing to construct 100,000 xrange objects on which to run the empty inner loop, and that's unlikely to be optimized away.
So all you're really measuring is various compilers' ability to see through the fact that no real computing work is being done.
A:
The lesson is: Performance is never what you expect. Therefore, always measure, never believe.
Some reasons why you might see these numbers (and from the first sentence, some of these might be completely wrong):
C is compiled for an "i586" processor (also called Pentium). That CPU was sold from 1993 to about 2000. Have you seen one lately? Guess not. So the C code isn't really optimized for what your CPU can do (or to put it another way around: Today's CPUs try very hard to be a fast Pentium CPU). Java, OTOH, is compiled for your CPU as the code is loaded. It can pull some tricks that C simply can't. The price is that the C program starts in 15ms while the Java program needs 4 Seconds.
Python has no JIT (just in time compiler), yet. All code is converted into bytecode which is then interpreted. This means the loop above is turned into a dozen bytecode instructions which are then interpreted by a C program. That just takes time. Python is not meant for huge loops, it's meant for smart algorithms which you simply can't express in any other language (at least not with the same amount of code and readability).
So just as it doesn't make sense to go shopping with a 18t truck (you can transport anything but you won't find a space to park it), chose your programming language according to the problem you need to solve. It has to be small&fast? C. Just fast? Java. Flexible? Python. Flexible&Fast: Python with a helper library in C (like NumPy).
A:
Is there any reason for Python being so slow?
Yes.
But what does it matter? You've created 100,000 xrange objects. Why? What does that matter? What is your real question on performance? What algorithm do you actually have that's actually too slow?
for i in xrange(0,100000): # Creates one xrange object
for j in xrange(0,100000): # Creates a fresh xrange object each time through the loop
A:
for i in xrange(0, 10000):
for j in xrange(0, 10000):
pass
or
for i in xrange(0, 100000000):
pass
Python 2.6.5 - Time taken : 8.50866484642
PyPy 1.3 - Time taken : 1.55999398232
reason of slow work not in creation of xrange objects
A:
gcc 4.2 with the -O1 flag or higher optimize away the loop and the program takes 1 milli second to execute.
This benchmark is not very representative as it is very far from any real world use.
You're doing a nested loop for a reason, and you never leave it empty.
Python doesn't optimize away the loop, although I see no technical reason why it couldn't.
Python is slower than C because it's further from the machine language. xrange is a nice abstraction but it adds a heavy layer of machine code compared to a simple C loop.
C source:
int main( void ){
int i, j;
for (i=0;i<100000;i++){
for (j=0;j<100000;j++){
continue;
}
}
return 0;
}
A:
A good compiler would optimise away the loop.
Assuming the loop isn't optimised away, I'd expect Python to be something like 100 times slower than the C version
| Nested loop comparison in Python,Java and C | The following code in python takes very long to run. (I couldn't wait until the program ended, though my friend told me for him it took 20 minutes.)
But the equivalent code in Java runs in approximately 8 seconds and in C it takes 45 seconds.
I expected Python to be slow but not this much, and in case of C which I expected to be faster than Java was actually slower. Is the JVM using some loop unrolling technique to achieve this speed? Is there any reason for Python being so slow?
import time
st=time.time()
for i in xrange(0,100000):
for j in xrange(0,100000):
continue;
print "Time taken : ",time.time()-st
| [
"Your test is not measuring anything meaningful.\nA language's performance in the real world has little to do with how quickly it executes a tight loop. \nFrankly, I'm intrigued that C and Java took as long as they did; I would have expected both of their compilers to realize that there was nothing happening inside... | [
12,
9,
5,
3,
2,
1
] | [] | [] | [
"c",
"java",
"performance",
"python"
] | stackoverflow_0003318012_c_java_performance_python.txt |
Q:
How to find out if I have installed a Python module in Linux?
I tried to install a Python module by typing: sudo python setup.py install
After I typed this command I got a lot of output to the screen.
The lest few lines are bellow:
writing manifest file 'scikits.audiolab.egg-info/SOURCES.txt'
removing '/usr/lib/python2.5/site-packages/scikits.audiolab-0.10.2-py2.5.egg-info' (and everything under it)
Copying scikits.audiolab.egg-info to /usr/lib/python2.5/site-packages/scikits.audiolab-0.10.2-py2.5.egg-info
Installing /usr/lib/python2.5/site-packages/scikits.audiolab-0.10.2-py2.5-nspkg.pth
running install_scripts
So, there were nothing suspicious. But when I tried to use the module from the Python:
import pyaudiolab
I see that Python does not find the module:
Traceback (most recent call last):
File "test.py", line 1, in <module>
import pyaudiolab ImportError: No module named pyaudiolab
How can I found out what went wrong? As a result of the installation I get a new directory:
/usr/lib/python2.5/site-packages (so something happened) but I still cannot use the module. Can anybody help me with that?
A:
Have you tried import scikits.audiolab or import audiolab?
A:
From the OP's comment to an answer, it's clear that scikits.audiolab is indeed where this module's been installed, but it also needs you to install numpy. Assuming the module's configuration files are correct, by using easy_install instead of the usual python setup.py run, you might have automatically gotten and installed such extra dependencies -- that's one of the main points of easy_install after all. But you can also do it "manually" (for better control of where you get dependencies from and exactly how you install them), of course -- however, in that case, you do need to check and manually install the dependencies, too.
A:
Your library depends upon numoy. Try installing numpy:
sudo apt-get install python-numpy
A:
You need a more recent version of numpy (>= 1.2.0), as indicated on the audiolab installation informations.
A:
check if you have the module somewhere inside:
/usr/lib/python2.5/site-packages/
(search for a file named |modulename|.py so in your example - try: pyaudiolab.py or audiolab.py)
if it exists - check if the directory in which it exists is found in the sys.path variable:
import sys
sys.path
| How to find out if I have installed a Python module in Linux? | I tried to install a Python module by typing: sudo python setup.py install
After I typed this command I got a lot of output to the screen.
The lest few lines are bellow:
writing manifest file 'scikits.audiolab.egg-info/SOURCES.txt'
removing '/usr/lib/python2.5/site-packages/scikits.audiolab-0.10.2-py2.5.egg-info' (and everything under it)
Copying scikits.audiolab.egg-info to /usr/lib/python2.5/site-packages/scikits.audiolab-0.10.2-py2.5.egg-info
Installing /usr/lib/python2.5/site-packages/scikits.audiolab-0.10.2-py2.5-nspkg.pth
running install_scripts
So, there were nothing suspicious. But when I tried to use the module from the Python:
import pyaudiolab
I see that Python does not find the module:
Traceback (most recent call last):
File "test.py", line 1, in <module>
import pyaudiolab ImportError: No module named pyaudiolab
How can I found out what went wrong? As a result of the installation I get a new directory:
/usr/lib/python2.5/site-packages (so something happened) but I still cannot use the module. Can anybody help me with that?
| [
"Have you tried import scikits.audiolab or import audiolab?\n",
"From the OP's comment to an answer, it's clear that scikits.audiolab is indeed where this module's been installed, but it also needs you to install numpy. Assuming the module's configuration files are correct, by using easy_install instead of the u... | [
5,
1,
1,
1,
0
] | [] | [] | [
"import",
"installation",
"module",
"python"
] | stackoverflow_0002058172_import_installation_module_python.txt |
Q:
Python twisted: how to schedule?
Having 1-day experience in Twisted I try to schedule message sending in reply to tcp client:
import os, sys, time
from twisted.internet import protocol, reactor
self.scenario = [(1, "Message after 1 sec!"), (4, "This after 4 secs"), (2, "End final after 2 secs")]
for timeout, data in self.scenario:
reactor.callLater(timeout, self.sendata, data)
print "waited %d time, sent %s\n"%(timeout, data)
Now it sends messages, but I have 2 problems:
1) "timeout" is going from "now", and I want to count it after each previous task was completed (previous message was sent)
2) I don't know how to close connection after all messages were sent. If I place self.transport.loseConnection() after callLaters it closes connection immediately.
In previous try I didn't use reactor.callLater, but only self.transport.write() and time.sleep(n) in for loop. In this case all messages were sent together after all timeouts passed... Not something I wanted.
The purpose is to wait for client connection, wait timeout1 and send message1, wait timeout2 and send message2, ... etc. After final message - close connection.
A:
The important thing to realize when working with Twisted is that nothing waits for anything. When you call reactor.callLater(), you're asking the reactor to call something later, not now. The call finishes right away (after the call has been scheduled, before it has been executed.) Consequently, your print statement is a lie: you didn't wait timeout time; you didn't wait at all.
You can fix it in multiple ways, and which to use depends on what you actually want. If you want the second task to start four seconds after the first task started, you can simply add the delay (your timeout variable) of the first task to the delay of the second task. The first task may not start exactly when you schedule it, though; it may start later, if Twisted is too busy to start it sooner. Also, if your task takes a long time it may not actually be done before the second task starts.
The more common way is for the first task to schedule the second task, instead of scheduling the second task right away. You can schedule it four seconds after the first task ended (by calling reactor.callLater() at the end of the first task), or four seconds after the first task started (by calling reactor.callLater() at the start of the first task), or perform more complex calculations to determine when it should start, keeping track of elapsed time.
When you realize nothing in Twisted waits, dealing with closing the connection when you've performed all scheduled tasks becomes easy: you simply have your last task call self.transport.loseConnection(). For more complex situations you may want to chain Deferreds together, or use a DeferredList to perform the loseConnection() when all pending tasks have finished, even when they aren't strictly sequential.
A:
Final solution for this deal..
import os, sys, time
from twisted.internet import protocol, reactor
import itertools
def sendScenario(self):
def sendelayed(d):
self.sendata(d)
self.factory.out_dump.write(d)
try:
timeout, data = next(self.sc)
reactor.callLater(timeout, sendelayed, data)
except StopIteration:
print "Scenario completed!"
self.transport.loseConnection()
self.scenario = [(1, "Message after 1 sec!"), (4, "This after 4 secs"), (2, "End final after 2 secs")]
self.sc = iter(self.scenario)
timeout, data = next(self.sc)
reactor.callLater(timeout, sendelayed, data)
| Python twisted: how to schedule? | Having 1-day experience in Twisted I try to schedule message sending in reply to tcp client:
import os, sys, time
from twisted.internet import protocol, reactor
self.scenario = [(1, "Message after 1 sec!"), (4, "This after 4 secs"), (2, "End final after 2 secs")]
for timeout, data in self.scenario:
reactor.callLater(timeout, self.sendata, data)
print "waited %d time, sent %s\n"%(timeout, data)
Now it sends messages, but I have 2 problems:
1) "timeout" is going from "now", and I want to count it after each previous task was completed (previous message was sent)
2) I don't know how to close connection after all messages were sent. If I place self.transport.loseConnection() after callLaters it closes connection immediately.
In previous try I didn't use reactor.callLater, but only self.transport.write() and time.sleep(n) in for loop. In this case all messages were sent together after all timeouts passed... Not something I wanted.
The purpose is to wait for client connection, wait timeout1 and send message1, wait timeout2 and send message2, ... etc. After final message - close connection.
| [
"The important thing to realize when working with Twisted is that nothing waits for anything. When you call reactor.callLater(), you're asking the reactor to call something later, not now. The call finishes right away (after the call has been scheduled, before it has been executed.) Consequently, your print stateme... | [
8,
4
] | [] | [] | [
"networking",
"python",
"twisted"
] | stackoverflow_0003302185_networking_python_twisted.txt |
Q:
Python distutils.Extension : setting a concurrency level
I'm wondering how to reproduce the equivalent of a make -j<n> on a setup.py using distutils.Extension, in order to build a C extension to Python 2.6 .
My desired outcome: having setup.py build using a few instances of my C-compiler in the same time, instead of only one.
There are probably an environnement var or two that I'm missing.
Thanks,
Florian
A:
And the answer from distutils-sig's mailing list is : a patch for distutils2 is still to be written.
| Python distutils.Extension : setting a concurrency level | I'm wondering how to reproduce the equivalent of a make -j<n> on a setup.py using distutils.Extension, in order to build a C extension to Python 2.6 .
My desired outcome: having setup.py build using a few instances of my C-compiler in the same time, instead of only one.
There are probably an environnement var or two that I'm missing.
Thanks,
Florian
| [
"And the answer from distutils-sig's mailing list is : a patch for distutils2 is still to be written.\n"
] | [
0
] | [] | [] | [
"concurrency",
"distutils",
"python"
] | stackoverflow_0003272022_concurrency_distutils_python.txt |
Q:
wxPython: wx.PyControl layout problem when it is a child of a wx.Panel
This is a continuation from this question:
wxPython: Can a wx.PyControl contain a wx.Sizer?
The main topic here is using a wx.Sizer inside a wx.PyControl. I had problems Fit()ting my CustomWidget around its child widgets. That problem was solved by calling Layout() after Fit().
However, as far as I have experienced, the solution only works when the CustomWidget is a direct child of a wx.Frame. It breaks down when it becomes a child of a wx.Panel.
EDIT: Using the code below, the CustomWidget doesn't resize correctly to fit its children. I observed that this only happens when the CustomWidget (as a subclass of wx.PyControl) is a child of a wx.Panel; otherwise, if it is a direct child of a wx.Frame, it Fit()s perfectly.
Here is the code:
import wx
class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent=None)
panel = Panel(parent=self)
custom = CustomWidget(parent=panel)
self.Show()
class Panel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
self.SetSize(parent.GetClientSize())
class CustomWidget(wx.PyControl):
def __init__(self, parent):
wx.PyControl.__init__(self, parent=parent)
# Create the sizer and make it work for the CustomWidget
sizer = wx.GridBagSizer()
self.SetSizer(sizer)
# Create the CustomWidget's children
text = wx.TextCtrl(parent=self)
spin = wx.SpinButton(parent=self, style=wx.SP_VERTICAL)
# Add the children to the sizer
sizer.Add(text, pos=(0, 0), flag=wx.ALIGN_CENTER)
sizer.Add(spin, pos=(0, 1), flag=wx.ALIGN_CENTER)
# Make sure that CustomWidget will auto-Layout() upon resize
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Fit()
def OnSize(self, event):
self.Layout()
app = wx.App(False)
frame = Frame()
app.MainLoop()
A:
.SetSizerAndFit(sizer) does the job. I'm not sure why a .SetSizer(sizer) then a .Fit() won't work. Any ideas?
import wx
class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent=None)
panel = Panel(parent=self)
custom = CustomWidget(parent=panel)
self.Show()
class Panel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
self.SetSize(parent.GetClientSize())
class CustomWidget(wx.PyControl):
def __init__(self, parent):
wx.PyControl.__init__(self, parent=parent)
# Create the sizer and make it work for the CustomWidget
sizer = wx.GridBagSizer()
self.SetSizer(sizer)
# Create the CustomWidget's children
text = wx.TextCtrl(parent=self)
spin = wx.SpinButton(parent=self, style=wx.SP_VERTICAL)
# Add the children to the sizer
sizer.Add(text, pos=(0, 0), flag=wx.ALIGN_CENTER)
sizer.Add(spin, pos=(0, 1), flag=wx.ALIGN_CENTER)
# Set sizer and fit, then layout
self.SetSizerAndFit(sizer)
self.Layout()
# ------------------------------------------------------------
# # Make sure that CustomWidget will auto-Layout() upon resize
# self.Bind(wx.EVT_SIZE, self.OnSize)
# self.Fit()
#
#def OnSize(self, event):
# self.Layout()
# ------------------------------------------------------------
app = wx.App(False)
frame = Frame()
app.MainLoop()
| wxPython: wx.PyControl layout problem when it is a child of a wx.Panel | This is a continuation from this question:
wxPython: Can a wx.PyControl contain a wx.Sizer?
The main topic here is using a wx.Sizer inside a wx.PyControl. I had problems Fit()ting my CustomWidget around its child widgets. That problem was solved by calling Layout() after Fit().
However, as far as I have experienced, the solution only works when the CustomWidget is a direct child of a wx.Frame. It breaks down when it becomes a child of a wx.Panel.
EDIT: Using the code below, the CustomWidget doesn't resize correctly to fit its children. I observed that this only happens when the CustomWidget (as a subclass of wx.PyControl) is a child of a wx.Panel; otherwise, if it is a direct child of a wx.Frame, it Fit()s perfectly.
Here is the code:
import wx
class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, parent=None)
panel = Panel(parent=self)
custom = CustomWidget(parent=panel)
self.Show()
class Panel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
self.SetSize(parent.GetClientSize())
class CustomWidget(wx.PyControl):
def __init__(self, parent):
wx.PyControl.__init__(self, parent=parent)
# Create the sizer and make it work for the CustomWidget
sizer = wx.GridBagSizer()
self.SetSizer(sizer)
# Create the CustomWidget's children
text = wx.TextCtrl(parent=self)
spin = wx.SpinButton(parent=self, style=wx.SP_VERTICAL)
# Add the children to the sizer
sizer.Add(text, pos=(0, 0), flag=wx.ALIGN_CENTER)
sizer.Add(spin, pos=(0, 1), flag=wx.ALIGN_CENTER)
# Make sure that CustomWidget will auto-Layout() upon resize
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Fit()
def OnSize(self, event):
self.Layout()
app = wx.App(False)
frame = Frame()
app.MainLoop()
| [
".SetSizerAndFit(sizer) does the job. I'm not sure why a .SetSizer(sizer) then a .Fit() won't work. Any ideas?\nimport wx\n\nclass Frame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, parent=None)\n panel = Panel(parent=self)\n custom = CustomWidget(parent=panel)\n self.Show()\n\nclass Pane... | [
1
] | [] | [] | [
"custom_controls",
"python",
"sizer",
"widget",
"wxpython"
] | stackoverflow_0003308485_custom_controls_python_sizer_widget_wxpython.txt |
Q:
Python: Thread safe dictionary with short lived keys, is this correct?
import threading
import weakref
_mainlock = threading.RLock()
_job_locks = weakref.WeakValueDictionary()
def do_thing(job_id):
_mainlock.acquire() #Dictionary modification lock acquire
_job_locks.setdefault(job_id, threading.RLock()) #Possibly modifies the dictionary
_mainlock.release()
_job_locks[job_id].acquire()
try:
one_time_init(job_id)
finally:
_job_locks[job_id].release()
#On function return, the weakref.WeakValueDictionary should cause the key to evaporate
Assuming do_thing() is called many times on many threads with id numbers that may or may not be the same (say, 4 times with ID 3 and one time each with different IDs), is this thread safe? Will one_time_init() ever run more than once for a particular job ID at a time? (PS: one_time_init saves it's state that is has been run once for each ID, so calling it is a no-op if it has already run to completion)
Updated code (thanks THC4k):
import threading
import weakref
_mainlock = threading.RLock()
_job_locks = weakref.WeakValueDictionary()
def do_thing(job_id):
with _mainlock:
jl = _job_locks.setdefault(job_id, threading.RLock())
with jl:
one_time_init(job_id)
A:
Seems very safe. Why do you even need the _job_locks if one_time_init checks again if it was run? You could add the lock there. Why RLock instead of Lock (the function seems to never re-enter)?
Anyways, the with statement looks way nicer:
import threading
import weakref
_mainlock = threading.RLock()
_job_locks = weakref.WeakValueDictionary()
def do_thing(job_id):
with _mainlock:
_job_locks.setdefault(job_id, threading.RLock())
with _job_locks[job_id]:
one_time_init(job_id)
| Python: Thread safe dictionary with short lived keys, is this correct? | import threading
import weakref
_mainlock = threading.RLock()
_job_locks = weakref.WeakValueDictionary()
def do_thing(job_id):
_mainlock.acquire() #Dictionary modification lock acquire
_job_locks.setdefault(job_id, threading.RLock()) #Possibly modifies the dictionary
_mainlock.release()
_job_locks[job_id].acquire()
try:
one_time_init(job_id)
finally:
_job_locks[job_id].release()
#On function return, the weakref.WeakValueDictionary should cause the key to evaporate
Assuming do_thing() is called many times on many threads with id numbers that may or may not be the same (say, 4 times with ID 3 and one time each with different IDs), is this thread safe? Will one_time_init() ever run more than once for a particular job ID at a time? (PS: one_time_init saves it's state that is has been run once for each ID, so calling it is a no-op if it has already run to completion)
Updated code (thanks THC4k):
import threading
import weakref
_mainlock = threading.RLock()
_job_locks = weakref.WeakValueDictionary()
def do_thing(job_id):
with _mainlock:
jl = _job_locks.setdefault(job_id, threading.RLock())
with jl:
one_time_init(job_id)
| [
"Seems very safe. Why do you even need the _job_locks if one_time_init checks again if it was run? You could add the lock there. Why RLock instead of Lock (the function seems to never re-enter)?\nAnyways, the with statement looks way nicer:\nimport threading\nimport weakref\n_mainlock = threading.RLock()\n_job_lock... | [
4
] | [] | [] | [
"dictionary",
"multithreading",
"python",
"thread_safety",
"weak_references"
] | stackoverflow_0003319392_dictionary_multithreading_python_thread_safety_weak_references.txt |
Q:
Problem encoding accented characters with python
I'm having trouble encoding accented characters in a URL using the python command line. Reducing my problem to the essential, this code:
>>> import urllib
>>> print urllib.urlencode({'foo' : raw_input('> ')})
> áéíóúñ
prints this in a mac command line:
foo=%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1
but the same code prints this in windows' command line:
foo=%A0%82%A1%A2%A3%A4
The mac result is correct and the characters get encoded as needed; but in windows I get a bunch of gibberish.
I'm guessing the problem lies in the way windows encodes characters, but I haven't been able to find a solution; I'd be very grateful if you could help me. Thanks in advance!
A:
You can use explicit encoding to get consistent result.
>>> str = u"áéíóúñ"
>>> import urllib
>>> urllib.urlencode({'foo':str.encode('utf-8')})
'foo=%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1'
However you need to ensure your string is in unicode first, so it may require decoding if its not, like raw_input().decode('latin1') or raw_input().decode('utf-8')
Input encoding depends on the locale of console, I believe, so its system-specific.
EDIT: unicode(str) should use locale encoding too to convert to unicode, so that could be a solution.
A:
The Windows command line uses cp437 encoding in US Windows. You need utf-8:
>>> import sys
>>> sys.stdin.encoding
'cp437'
>>> print urllib.urlencode({'foo':raw_input('> ').decode('cp437').encode('utf8')})
> áéíóúñ
foo=%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1
| Problem encoding accented characters with python | I'm having trouble encoding accented characters in a URL using the python command line. Reducing my problem to the essential, this code:
>>> import urllib
>>> print urllib.urlencode({'foo' : raw_input('> ')})
> áéíóúñ
prints this in a mac command line:
foo=%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1
but the same code prints this in windows' command line:
foo=%A0%82%A1%A2%A3%A4
The mac result is correct and the characters get encoded as needed; but in windows I get a bunch of gibberish.
I'm guessing the problem lies in the way windows encodes characters, but I haven't been able to find a solution; I'd be very grateful if you could help me. Thanks in advance!
| [
"You can use explicit encoding to get consistent result.\n>>> str = u\"áéíóúñ\"\n>>> import urllib\n>>> urllib.urlencode({'foo':str.encode('utf-8')})\n'foo=%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1'\n\nHowever you need to ensure your string is in unicode first, so it may require decoding if its not, like raw_input().dec... | [
3,
2
] | [] | [] | [
"encoding",
"macos",
"python",
"utf_8",
"windows"
] | stackoverflow_0003315095_encoding_macos_python_utf_8_windows.txt |
Q:
can i store result directly as .txt file without getting displayed on GUI in python?
my programme gives me very large results containg huge number of symbols,numbers.so that GUI often becomes 'non responding'.also takes so much time to display result.is there any way to store result as .txt file without getting displayed on GUI?
A:
Sorry for being a little unspecific, but that's what I get out of your question.
# results will contain your large dataset ...
handle = open("filename.txt", "w")
handle.write(results)
handle.close()
Or:
with open("filename.txt", "w") as f:
f.write(results)
In case your results happen to be an iterable:
# results will contain your large dataset ...
handle = open("filename.txt", "w")
handle.write(''.join(results)) # a little ugly, though
handle.close()
Or:
with open("filename.txt", "w") as f:
for item in results:
f.write(item)
A:
Yes.
with open("filename.txt", "w") as f:
for result_datum in get_my_results():
f.write(result_datum)
Or if you need to use print for some reason:
f = open("filename.txt", "w")
_saved_stdout = sys.stdout
try:
sys.stdout = f
doMyCalculation()
finally:
sys.stdout = _saved_stdout
f.close()
| can i store result directly as .txt file without getting displayed on GUI in python? | my programme gives me very large results containg huge number of symbols,numbers.so that GUI often becomes 'non responding'.also takes so much time to display result.is there any way to store result as .txt file without getting displayed on GUI?
| [
"Sorry for being a little unspecific, but that's what I get out of your question.\n # results will contain your large dataset ...\n handle = open(\"filename.txt\", \"w\")\n handle.write(results)\n handle.close()\n\nOr:\n with open(\"filename.txt\", \"w\") as f:\n f.write(results)\n\nIn case your results happen ... | [
3,
1
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0003319669_python_user_interface.txt |
Q:
Class not refreshing on 2nd url call
I have a web page with a link to a url eg./customer/showitem?id=7, which displays details of a specific customer in a child-window using method showitem() in class customer. The method may set the value of a customer class attribute that controls an alert which is displayed when the page is loaded (eg. self.onloadalert="Warning! Customer is in debt.").
If the customer window is closed, then opened again (perhaps with a different id eg. /customer/showitem?id=8), details of the new customer are displayed correctly, but the onload warning above still appears because customer.onloadalert has not changed since the last call (I've verified this it via. debugging). It looks as though even though the method runs from scratch on the 2nd url call, the customer class (and all its attribute values) still persists from the previous call.
I can solve the problem for this particular attribute by resetting it at the beginning of showitem(), but what about other customer.attributes? (especially if there are a lot of them) - I can't reset them all by name! How can I ensure that the class reloads (hence re-initialises) for each url call?
I am using CherryPy (3.20rc1), although I guess the question is applicable to other frameworks that use the same /class/method?params url format.
Any help would be appreciated.
Alan
A:
If you want data to persist for just one request, stick it on the cherrypy.request object:
cherrypy.request.onloadalert="Warning!"
The cherrypy.request object is completely destroyed and recreeated for each request, even though it's safely importable. Figuring out how is left as an exercise for the reader. ;)
| Class not refreshing on 2nd url call | I have a web page with a link to a url eg./customer/showitem?id=7, which displays details of a specific customer in a child-window using method showitem() in class customer. The method may set the value of a customer class attribute that controls an alert which is displayed when the page is loaded (eg. self.onloadalert="Warning! Customer is in debt.").
If the customer window is closed, then opened again (perhaps with a different id eg. /customer/showitem?id=8), details of the new customer are displayed correctly, but the onload warning above still appears because customer.onloadalert has not changed since the last call (I've verified this it via. debugging). It looks as though even though the method runs from scratch on the 2nd url call, the customer class (and all its attribute values) still persists from the previous call.
I can solve the problem for this particular attribute by resetting it at the beginning of showitem(), but what about other customer.attributes? (especially if there are a lot of them) - I can't reset them all by name! How can I ensure that the class reloads (hence re-initialises) for each url call?
I am using CherryPy (3.20rc1), although I guess the question is applicable to other frameworks that use the same /class/method?params url format.
Any help would be appreciated.
Alan
| [
"If you want data to persist for just one request, stick it on the cherrypy.request object:\ncherrypy.request.onloadalert=\"Warning!\"\n\nThe cherrypy.request object is completely destroyed and recreeated for each request, even though it's safely importable. Figuring out how is left as an exercise for the reader. ;... | [
1
] | [] | [] | [
"cherrypy",
"persistence",
"python",
"url"
] | stackoverflow_0003314833_cherrypy_persistence_python_url.txt |
Q:
join tables with django
queryObj = Rating.objects.select_related(
'Candidate','State','RatingCandidate','Sig','Office','OfficeCandidate').get(
rating_id = ratingId,
ratingcandidate__rating = ratingId,
ratingcandidate__rating_candidate_id = \
officecandidate__office_candidate_id)
This line gives me an error. I'm trying to get many different tables that are linked by primary keys and regular ids. The last selection is the problem:
ratingcandidate__rating_candidate_id = officecandidate__office_candidate_id.
I need to skip around to get all the data.
A:
I'm trying to get many different tables that are linked by primary keys and regular ids.
Don't try to "join" tables. This isn't SQL.
You have to do multiple gets to get data from many different tables.
Don't worry about select_related until you can prove that you have a bottle-neck.
Just do the various GETs from the various classes as needed.
Let's focus on Candidate and Rating.
class Rating( Model ):
...
class Candidate( Model ):
rating = Models.ForeignKey( Rating )
Do this.
r = Rating.objects.get( id=rating_id )
c = r.candidate_set.all()
This will get the rating and all the candidates that have that rating. This is -- in effect -- what a SQL join is: it's two fetches. In the Django ORM, just write the two fetches as simply as possible. Let Django (and your database) cache things for you.
To display elements of multiple tables in a single row on a template form, you do this.
In the view:
r = Rating.objects.get( id=rating_id )
return render_to_response( some_form, { 'rating':r } )
In the template:
Rating: {{rating}}. Candidates: {% for c in rating.candidate_set.all %} {{c}} {%endfor%}
Etc.
You simply "navigate" among your objects in your template to display the requested information.
A:
You can't use the double-underscore syntax on its own on the right-hand side of the expression. If you need to reference field names on the right-hand side, use the F() function:
ratingcandidate__rating_candidate_id = F('officecandidate__office_candidate_id')
| join tables with django | queryObj = Rating.objects.select_related(
'Candidate','State','RatingCandidate','Sig','Office','OfficeCandidate').get(
rating_id = ratingId,
ratingcandidate__rating = ratingId,
ratingcandidate__rating_candidate_id = \
officecandidate__office_candidate_id)
This line gives me an error. I'm trying to get many different tables that are linked by primary keys and regular ids. The last selection is the problem:
ratingcandidate__rating_candidate_id = officecandidate__office_candidate_id.
I need to skip around to get all the data.
| [
"\nI'm trying to get many different tables that are linked by primary keys and regular ids.\n\nDon't try to \"join\" tables. This isn't SQL.\nYou have to do multiple gets to get data from many different tables.\nDon't worry about select_related until you can prove that you have a bottle-neck.\nJust do the various ... | [
13,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003319632_django_python.txt |
Q:
How complicate can a Django application go?
I'm tasked to create a simple CRUD MVC application, and I thought it's a good opportunity to learn python. Because of its great documentation, I'm thinking now that I'll go with Django.
Now, this simple CRUD MVC application could become quite complicated in the future. I might have receive and issue JMS messages, display charts that are updated periodically (I'm thinking about ajax) and what not.
Given this I'm a little worried, since while I'm told it's easy to call Java code from python (I'm a Java developer), I'm also told that Django is generally best for content based web application, and can be restrictive.
Do you think it is okay to go with Django in this case?
A:
simple CRUD MVC application
Django does this "out of the box" The admin interface is a simple, CRUD, MVC application. You don't do much programming to make this happen. You create the model. That's it. Use the Django admin for your CRUD application. Done.
I might have receive and issue JMS messages, display charts that are updated periodically (I'm thinking about ajax) and what not.
That's the point. Since you didn't waste time writing the CRUD application, you are able to write the other, more interesting stuff.
Look at http://hjb.python-hosting.com/ for a Python-JMS bridge.
We have FLEX front-end and Django-based RESTful web services. The Django apps create PDF's, and other things. The FLEX does pretty pictures and charts.
Django is generally best for content based web application, and can be restrictive.
Doesn't mean anything. Provide a quote or a link to whatever it is you're talking about.
A:
Mozilla is currently rewriting two of our largest sites on Django. These are both fairly complex applications that interact with numerous online and offline services. With Python's large collection of libraries, anything Django doesn't do itself we've usually been able to find, or create pretty easily. For example, we have both cron jobs and on-demand offline tasks, backed by AMQP, which is similar to JMS.
Short answer: you can get pretty darn complicated if that's what you need to do, and odds are there's already a Python project or library to do what you need.
| How complicate can a Django application go? | I'm tasked to create a simple CRUD MVC application, and I thought it's a good opportunity to learn python. Because of its great documentation, I'm thinking now that I'll go with Django.
Now, this simple CRUD MVC application could become quite complicated in the future. I might have receive and issue JMS messages, display charts that are updated periodically (I'm thinking about ajax) and what not.
Given this I'm a little worried, since while I'm told it's easy to call Java code from python (I'm a Java developer), I'm also told that Django is generally best for content based web application, and can be restrictive.
Do you think it is okay to go with Django in this case?
| [
"\nsimple CRUD MVC application\n\nDjango does this \"out of the box\" The admin interface is a simple, CRUD, MVC application. You don't do much programming to make this happen. You create the model. That's it. Use the Django admin for your CRUD application. Done.\n\nI might have receive and issue JMS messages... | [
2,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003319890_django_python.txt |
Q:
How to correctly extract data with Regular Expressions
i'm facing regulars expressions for the first time and i need to extract some data from this report (a txt file with formatting info):
\n10: Vikelis M, Rapoport AM. Role of
antiepileptic drugs as preventive
agents for \nmigraine. CNS Drugs. 2010
Jan 1;24(1):21-33.
doi:\n10.2165/11310970-000000000-00000.
Review. PubMed PMID:
20030417.\n\n\n21: Johannessen Landmark C, Larsson PG, Rytter E,
Johannessen SI. Antiepileptic\ndrugs
in epilepsy and other disorders--a
population-based study of
prescriptions.\nEpilepsy Res. 2009
Nov;87(1):31-9. Epub 2009 Aug 13.
PubMed PMID: 19679449.\n\n\n
As you can see all the txt's records begins with a number like "xx:" and always ends with "PubMed PMID: dddddddd. but using a RegEx like this:
regex = re.compile(r"^\d+: .+ PMID: \d{8}.$")
regex.findall(inputfile)
Gives me a list with one big string, so i'm misunderstanding something. How can i extract data from these records?
A:
Use .+? for non-greedy matching instead of .+ which gives you greedy matching. You also want a re.DOTALL to make sure your . matches the line-end characters it needs to match, and re.MULTILINE to make sure the ^ and $ match starts and ends of line, not just of the whole string. The options in question need to be joined with the "bit-OR" | operator and passed as the second argument to re.compile.
A:
If the records are as consistent as presented in your example, you don't need to use regular expressions. A simple partition of the text file into lists of tokens will do the trick. For instance:
txt = '\n10: Vikelis M, Rapoport AM. Role of antiepileptic drugs as preventive agents for \nmigraine. CNS Drugs. 2010 Jan 1;24(1):21-33. doi:\n10.2165/11310970-000000000-00000. Review. PubMed PMID: 20030417.\n\n\n21: Johannessen Landmark C, Larsson PG, Rytter E, Johannessen SI. Antiepileptic\ndrugs in epilepsy and other disorders--a population-based study of prescriptions.\nEpilepsy Res. 2009 Nov;87(1):31-9. Epub 2009 Aug 13. PubMed PMID: 19679449.\n\n\n'
lines = [token.replace('\n', '') for token in txt.split('.')]
for line in lines:
print line
will print line by line each element of your references:
10: Vikelis M, Rapoport AM
Role of antiepileptic drugs as preventive agents for migraine
CNS Drugs
2010 Jan 1;24(1):21-33
doi:10
2165/11310970-000000000-00000
Review
PubMed PMID: 20030417
21: Johannessen Landmark C, Larsson PG, Rytter E, Johannessen SI
Antiepilepticdrugs in epilepsy and other disorders--a population-based study of prescriptions
Epilepsy Res
2009 Nov;87(1):31-9
Epub 2009 Aug 13
PubMed PMID: 19679449
Again, if you can trust that the first line of a record has the author; the second one the title, the third one the journal, etc, you may be able to do this very fast. If the information is a bit more "contextual" then you can START using regexp at this point.
Good luck.
| How to correctly extract data with Regular Expressions | i'm facing regulars expressions for the first time and i need to extract some data from this report (a txt file with formatting info):
\n10: Vikelis M, Rapoport AM. Role of
antiepileptic drugs as preventive
agents for \nmigraine. CNS Drugs. 2010
Jan 1;24(1):21-33.
doi:\n10.2165/11310970-000000000-00000.
Review. PubMed PMID:
20030417.\n\n\n21: Johannessen Landmark C, Larsson PG, Rytter E,
Johannessen SI. Antiepileptic\ndrugs
in epilepsy and other disorders--a
population-based study of
prescriptions.\nEpilepsy Res. 2009
Nov;87(1):31-9. Epub 2009 Aug 13.
PubMed PMID: 19679449.\n\n\n
As you can see all the txt's records begins with a number like "xx:" and always ends with "PubMed PMID: dddddddd. but using a RegEx like this:
regex = re.compile(r"^\d+: .+ PMID: \d{8}.$")
regex.findall(inputfile)
Gives me a list with one big string, so i'm misunderstanding something. How can i extract data from these records?
| [
"Use .+? for non-greedy matching instead of .+ which gives you greedy matching. You also want a re.DOTALL to make sure your . matches the line-end characters it needs to match, and re.MULTILINE to make sure the ^ and $ match starts and ends of line, not just of the whole string. The options in question need to be... | [
2,
1
] | [] | [] | [
"python",
"regex",
"text_files"
] | stackoverflow_0003320214_python_regex_text_files.txt |
Q:
Dealing with dates and timezones in a python project
In a side project I have to manage, compare and display dates from different formats. What's the best design strategy to follow?
I planned:
All dates are parsed according their
format and stored in the db in
9-tuple python format using UTC
When I have to do calculations and
compares I transform 9-tuple in
datetime object (using UTC). If I
have to store back some date
calculation I use again 9 tuple
format
On user interface time is
display converting from UTC to
user's timezone
Have you any feedback about this strategy?
A:
I'd use the DB's native datetime format rather than this "9-tuple" format. It'll make queries easier, and it's probably more space-efficient too.
Shouldn't be too hard to convert from that back into a Python datetime object. You can use the dateutil module if you're having trouble.
I think you're right about keeping a consistent timezone throughout the DB though, and the convert it to the user's timezone when you need to.
| Dealing with dates and timezones in a python project | In a side project I have to manage, compare and display dates from different formats. What's the best design strategy to follow?
I planned:
All dates are parsed according their
format and stored in the db in
9-tuple python format using UTC
When I have to do calculations and
compares I transform 9-tuple in
datetime object (using UTC). If I
have to store back some date
calculation I use again 9 tuple
format
On user interface time is
display converting from UTC to
user's timezone
Have you any feedback about this strategy?
| [
"I'd use the DB's native datetime format rather than this \"9-tuple\" format. It'll make queries easier, and it's probably more space-efficient too.\nShouldn't be too hard to convert from that back into a Python datetime object. You can use the dateutil module if you're having trouble.\nI think you're right about k... | [
2
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0003320374_datetime_python.txt |
Q:
Does Python Django support custom SQL and denormalized databases with no Foreign Key relationships?
I've just started learning Python Django and have a lot of experience building high traffic websites using PHP and MySQL. What worries me so far is Python's overly optimistic approach that you will never need to write custom SQL and that it automatically creates all these Foreign Key relationships in your database. The one thing I've learned in the last few years of building Chess.com is that its impossible to NOT write custom SQL when you're dealing with something like MySQL that frequently needs to be told what indexes it should use (or avoid), and that Foreign Keys are a death sentence. Percona's strongest recommendation was for us to remove all FKs for optimal performance.
Is there a way in Django to do this in the models file? create relationships without creating actual DB FKs? Or is there a way to start at the database level, design/create my database, and then have Django reverse engineer the models file?
A:
If you don't want foreign keys, then avoid using
models.ForeignKey(),
models.ManyToManyField(), and
models.OneToOneField().
Django will automatically create an auto-increment int field named id that you can use to refer to individual records, or you can override that by marking a field as primary_key=True.
There is also documentation on running raw SQL queries on the database.
A:
Raw SQL is as easy as this :
for obj in MyModel.objects.raw('SELECT * FROM myapp_mymodel'):
print obj
Denormalizing a database is up to you at model definition time.
You can use non-relational databases (MongoDB, ...) too with Django NonRel
A:
django-admin inspectdb allows you to reverse engineer a models file from existing tables. That is only a very partial response to your question ;)
A:
You can just create the model.py and avoid having SQL Alchemy automatically create the tables leaving it up to you to define the actual tables as you please. So although there are foreign key relationships in the model.py this does not mean that they must exist in the actual tables. This is a very good thing considering how ludicrously foreign key constraints are implemented in MySQL - MyISAM just ignores them and InnoDB creates a non-optional index on every single one regardless of whether it makes sense.
A:
I concur with the 'no foreign keys' advice (with the disclaimer: I also work for Percona).
The reason why it is is recommended is for concurrency / reducing locking internally.
It can be a difficult "optimization" to sell, but if you consider that the database has transactions (and is more or less ACID compliant) then it should only be application-logic errors that cause foreign-key violations. Not to say they don't exist, but if you enable foreign keys in development hopefully you should find at least a few bugs.
In terms of whether or not you need to write custom SQL:
The explanation I usually give is that "optimization rarely decreases complexity". I think it is okay to stick with an ORM by default, but if in a profiler it looks like one particular piece of functionality is taking a lot more time than you suspect it would when written by hand, then you need to be prepared to fix it (assuming the code is called often enough).
The real secret here is that you need good instrumentation / profiling in order to be frugal with your complexity adding optimization(s).
| Does Python Django support custom SQL and denormalized databases with no Foreign Key relationships? | I've just started learning Python Django and have a lot of experience building high traffic websites using PHP and MySQL. What worries me so far is Python's overly optimistic approach that you will never need to write custom SQL and that it automatically creates all these Foreign Key relationships in your database. The one thing I've learned in the last few years of building Chess.com is that its impossible to NOT write custom SQL when you're dealing with something like MySQL that frequently needs to be told what indexes it should use (or avoid), and that Foreign Keys are a death sentence. Percona's strongest recommendation was for us to remove all FKs for optimal performance.
Is there a way in Django to do this in the models file? create relationships without creating actual DB FKs? Or is there a way to start at the database level, design/create my database, and then have Django reverse engineer the models file?
| [
"If you don't want foreign keys, then avoid using\n\nmodels.ForeignKey(), \nmodels.ManyToManyField(), and \nmodels.OneToOneField().\n\nDjango will automatically create an auto-increment int field named id that you can use to refer to individual records, or you can override that by marking a field as primary_key=Tru... | [
1,
1,
0,
0,
0
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0003066255_django_mysql_python.txt |
Q:
Python import inconsistent behavior
I have a py file like this, which errors out.
from world import acme
def make_stuff_happen():
acme.account.foo() # Works
acme.subscription.bar() # FAIL: "module 'object' has no attribute 'subscription'"
make_stuff_happen()
But this works!
from world import acme
from world.acme import subscription
def make_stuff_happen():
acme.account.foo() # Works
subscription.bar() # Now this works.
make_stuff_happen()
All I can say is WTF, What could be causing this?
The behavior should at least be consistent for both acme.account and acme.subscription.
Thanks!
Update- Folder structure of the acme folder:
acme
|-- __init__.py
|-- account.py
|-- catalog.py
|-- core.py
|-- proxy.py
|-- subscription.py
`-- utils.py
And __init__.py is completely blank.
A:
Submodules are referenced in the __init__.py file in the module folder. It appears that subscription is not referenced in acme's __init__.py.
However, when you do import world.acme.subscription, it knows to go digging in that folder without talking to __init__.py.
According to your description of __init__.py as being empty, you should import subscription in __init__.py.
More on how modules are set up can be seen in the documentation. There is a pretty good example setting up a sound module.
| Python import inconsistent behavior | I have a py file like this, which errors out.
from world import acme
def make_stuff_happen():
acme.account.foo() # Works
acme.subscription.bar() # FAIL: "module 'object' has no attribute 'subscription'"
make_stuff_happen()
But this works!
from world import acme
from world.acme import subscription
def make_stuff_happen():
acme.account.foo() # Works
subscription.bar() # Now this works.
make_stuff_happen()
All I can say is WTF, What could be causing this?
The behavior should at least be consistent for both acme.account and acme.subscription.
Thanks!
Update- Folder structure of the acme folder:
acme
|-- __init__.py
|-- account.py
|-- catalog.py
|-- core.py
|-- proxy.py
|-- subscription.py
`-- utils.py
And __init__.py is completely blank.
| [
"Submodules are referenced in the __init__.py file in the module folder. It appears that subscription is not referenced in acme's __init__.py.\nHowever, when you do import world.acme.subscription, it knows to go digging in that folder without talking to __init__.py.\nAccording to your description of __init__.py as ... | [
6
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0003320467_import_module_python.txt |
Q:
Mutex locks vs Threading locks. Which to use?
My main question is does the Threading lock object create atomic locks? It doesn't say that the lock is atomic in the module documentation. in pythons mutex documentation it does say the mutex lock is atomic but it seems that I read somewhere that in fact it isn't. I am wondering if someone could could give me a bit of insight on this mater. Which lock should I use. I am currently running my scripts using python 2.4
A:
Locks of any nature would be rather useless if they weren't atomic - the whole point of the lock is to allow for higher-level atomic operations.
All of threading's synchronization objects (locks, rlocks, semaphores, boundedsemaphores) utilize atomic instructions, as do mutexes.
You should use threading, since mutex is actually deprecated going forward (and removed in Python 3).
| Mutex locks vs Threading locks. Which to use? | My main question is does the Threading lock object create atomic locks? It doesn't say that the lock is atomic in the module documentation. in pythons mutex documentation it does say the mutex lock is atomic but it seems that I read somewhere that in fact it isn't. I am wondering if someone could could give me a bit of insight on this mater. Which lock should I use. I am currently running my scripts using python 2.4
| [
"Locks of any nature would be rather useless if they weren't atomic - the whole point of the lock is to allow for higher-level atomic operations.\nAll of threading's synchronization objects (locks, rlocks, semaphores, boundedsemaphores) utilize atomic instructions, as do mutexes.\nYou should use threading, since mu... | [
13
] | [] | [] | [
"locking",
"multithreading",
"mutex",
"python"
] | stackoverflow_0003320514_locking_multithreading_mutex_python.txt |
Q:
Efficiently filter large number of datastore entities with a large number of property values
In my App Engine datastore I've got an entity type which may hold a large number of entities, each of which will have the property 'customer_id'. For example, lets say a given customer_id has 10,000 entities, and there are 50,000 customer_ids.
I'm trying to filter this effectively, so that a user could get information for at least 2000 customer_ids at one time. That is, read them out to the UI within the 30 second time out limit (further filtering will be done at the front end, so the user isn't bombarded with all results at once).
Below I've listed a view of my current datastore models. 'Reports' refer to sets of customer_ids, so continuing the above example, I could get my 2000 customer_ids from ReportCids.
class Users(db.Model):
user = db.StringProperty()
report_keys_list = db.ListProperty(db.Key)
class Reports(db.Model):
#report_key
report_name = db.StringProperty()
class ReportCids(db.Model):
report_key_reference = db.ReferenceProperty(Reports, collection_name="report_cid_set")
customer_id = db.IntegerProperty()
start_timestamp = db.IntegerProperty()
end_timestamp = db.IntegerProperty()
class CustomerEvent(db.Model):
customer_id = db.IntegerProperty()
timestamp = db.IntegerProperty()
event_type = db.IntegerProperty()
The options I considered:
-Perform a separate query for each customer_in in my set of 2000
-Use lists of keys indicating customer events, but this is limited to 5000 entries in a list (so I've read)
-Get all entries, and filter in my code
I'd really appreciate if anyone had some advice on how to do this in the most efficient way, or if I'm approaching the problem in completely the wrong way. I'm a novice in terms of using the datastore effectively.
Of course happy to provide any clarification or information if it helps.
Thanks very much!
A:
Thanks for getting back to me. It looks like I had an issue with the account used when I posted so I need to respond in the comments here.
Having thought about it and from what you've said, fetching that many results is not going to work.
Here's what I'm trying to do:
I'm trying to make a report that shows for multiple Customer IDs the events that happened for that group of customers. So lets say I have a report to view information for 2000 customers. I want to be able to get all events (CustomerEvent) and then filter this by event_type. I'm likely asking a lot here, but what I was hoping to do was get all of these events for 2000 customers, and then do the event_type filtering at the front end, so that a user could dynamically adjust the event_type they want to look for and get some information on successful actions for that event type.
So my main problem is getting the right entities out of CustomerEvent effectively.
Right now, I'm grabbing a list of Customer IDs like this:
cid_list = []
this_report = models.Reports.get(report_key)
if this_report.report_cid_set:
for entity in this_report.report_cid_set:
cid_list.append(entity.customer_id)
My estimation of 10,000 CustomerEvent entities was quite high, but theoretically it could happen. Perhaps when I go to get the report results, I could filter straight away by the event_type specified by the user. This means that I have to go back to the datastore each time they choose a new option which isn't ideal, but perhaps it's my only option given this set up.
Thanks very much for taking the time to look at this!
| Efficiently filter large number of datastore entities with a large number of property values | In my App Engine datastore I've got an entity type which may hold a large number of entities, each of which will have the property 'customer_id'. For example, lets say a given customer_id has 10,000 entities, and there are 50,000 customer_ids.
I'm trying to filter this effectively, so that a user could get information for at least 2000 customer_ids at one time. That is, read them out to the UI within the 30 second time out limit (further filtering will be done at the front end, so the user isn't bombarded with all results at once).
Below I've listed a view of my current datastore models. 'Reports' refer to sets of customer_ids, so continuing the above example, I could get my 2000 customer_ids from ReportCids.
class Users(db.Model):
user = db.StringProperty()
report_keys_list = db.ListProperty(db.Key)
class Reports(db.Model):
#report_key
report_name = db.StringProperty()
class ReportCids(db.Model):
report_key_reference = db.ReferenceProperty(Reports, collection_name="report_cid_set")
customer_id = db.IntegerProperty()
start_timestamp = db.IntegerProperty()
end_timestamp = db.IntegerProperty()
class CustomerEvent(db.Model):
customer_id = db.IntegerProperty()
timestamp = db.IntegerProperty()
event_type = db.IntegerProperty()
The options I considered:
-Perform a separate query for each customer_in in my set of 2000
-Use lists of keys indicating customer events, but this is limited to 5000 entries in a list (so I've read)
-Get all entries, and filter in my code
I'd really appreciate if anyone had some advice on how to do this in the most efficient way, or if I'm approaching the problem in completely the wrong way. I'm a novice in terms of using the datastore effectively.
Of course happy to provide any clarification or information if it helps.
Thanks very much!
| [
"Thanks for getting back to me. It looks like I had an issue with the account used when I posted so I need to respond in the comments here.\nHaving thought about it and from what you've said, fetching that many results is not going to work.\nHere's what I'm trying to do:\nI'm trying to make a report that shows for ... | [
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003316301_google_app_engine_google_cloud_datastore_python.txt |
Q:
Dynamically loading two libpython versions
I have a program which embeds both python2 and python3 interpreters. The libpython shared libraries are dlopen()ed by the respective commands which provide access to the interpreters and each interpreter maintains its own state.
This all works just fine if the user only uses pure python modules or builtins. Trying to load a C extension (like termios) then complains "undefined symbol: PyExc_TypeError". This happens because the C extensions aren't linked against libpython. Python upstream doesn't think this is a problem.
To get around that, I can change the dlopen() calls in my program for the libpython shared libraries to use RTLD_GLOBAL. As soon as I do that, however, trying to use both the python2 and python3 interpreters in the same session of the program causes it to ABRT in the process of calling Py_Initialize for whichever interpreter was invoked second. Using only one of the interpreters works fine.
Any idea how to get this to work when the C extensions won't be linked against libpython, therefore requiring the use of RTLD_GLOBAL?
A:
Sorry, but this won't work the way you want it to. The solution ordinarily would involve linking each extension to versioned libpython symbols; or one could have a namespace-capable linker, such that one could map each library to a different namespace, rather than a global one. Unfortunately neither of these options are easily applied, so you're probably stuck with a multi-process model. Simply fork and have one process link to each version of Python. The tough bit then is how to share whatever data led you to require two distinct Python interpreters in the first place. Perhaps a description of what problem led to the question may help find a better solution?
| Dynamically loading two libpython versions | I have a program which embeds both python2 and python3 interpreters. The libpython shared libraries are dlopen()ed by the respective commands which provide access to the interpreters and each interpreter maintains its own state.
This all works just fine if the user only uses pure python modules or builtins. Trying to load a C extension (like termios) then complains "undefined symbol: PyExc_TypeError". This happens because the C extensions aren't linked against libpython. Python upstream doesn't think this is a problem.
To get around that, I can change the dlopen() calls in my program for the libpython shared libraries to use RTLD_GLOBAL. As soon as I do that, however, trying to use both the python2 and python3 interpreters in the same session of the program causes it to ABRT in the process of calling Py_Initialize for whichever interpreter was invoked second. Using only one of the interpreters works fine.
Any idea how to get this to work when the C extensions won't be linked against libpython, therefore requiring the use of RTLD_GLOBAL?
| [
"Sorry, but this won't work the way you want it to. The solution ordinarily would involve linking each extension to versioned libpython symbols; or one could have a namespace-capable linker, such that one could map each library to a different namespace, rather than a global one. Unfortunately neither of these optio... | [
1
] | [] | [] | [
"c",
"dynamic",
"python"
] | stackoverflow_0003320742_c_dynamic_python.txt |
Q:
Troubles in installing python-sybase module
I am trying to install this module simply following the installation guide:
http:// python-sybase.sourceforge.net/sybase/node5.html
I get an error that I don't understand, I am wondering if it's not a firewall problem but I don't know how to handle that:
C:\Documents and Settings\lippela\Desktop\python-sybase-0.39>python setup.py ins
tall
---------------------------------------------------------------------------
This script requires setuptools version 0.6c6 to run (even to display
help). I will attempt to download it for you (from
http: //cheeseshop.python.org/packages/2.4/s/setuptools/), but
you may need to enable firewall access for this script first.
I will start the download in 15 seconds.
(Note: if this machine does not have network access, please obtain the file
http:// cheeseshop.python.org/packages/2.4/s/setuptools/setuptools-0.6c6-py2.4.egg
and place it in this directory before rerunning this script.)
---------------------------------------------------------------------------
Downloading http: //cheeseshop.python.org/packages/2.4/s/setuptools/setuptools-0.6c6-py2.4.egg
Traceback (most recent call last):
File "setup.py", line 31, in ?
use_setuptools()
File "C:\Documents and Settings\lippela\Desktop\python-sybase-0.39\ez_setup.py
", line 86, in use_setuptools
egg = download_setuptools(version, download_base, to_dir, download_delay)
File "C:\Documents and Settings\lippela\Desktop\python-sybase-0.39\ez_setup.py
", line 140, in download_setuptools
src = urllib2.urlopen(url)
File "C:\Python24\lib\urllib2.py", line 130, in urlopen
return _opener.open(url, data)
File "C:\Python24\lib\urllib2.py", line 358, in open
response = self._open(req, data)
File "C:\Python24\lib\urllib2.py", line 376, in _open
'_open', req)
File "C:\Python24\lib\urllib2.py", line 337, in _call_chain
result = func(*args)
File "C:\Python24\lib\urllib2.py", line 1021, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "C:\Python24\lib\urllib2.py", line 996, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error (11001, 'getaddrinfo failed')>
Any idea?
A:
The setup script failed to download the .egg it tries to download. It also tells you what to do when that happens: download the file yourself and place it in the same directory as the script.
| Troubles in installing python-sybase module | I am trying to install this module simply following the installation guide:
http:// python-sybase.sourceforge.net/sybase/node5.html
I get an error that I don't understand, I am wondering if it's not a firewall problem but I don't know how to handle that:
C:\Documents and Settings\lippela\Desktop\python-sybase-0.39>python setup.py ins
tall
---------------------------------------------------------------------------
This script requires setuptools version 0.6c6 to run (even to display
help). I will attempt to download it for you (from
http: //cheeseshop.python.org/packages/2.4/s/setuptools/), but
you may need to enable firewall access for this script first.
I will start the download in 15 seconds.
(Note: if this machine does not have network access, please obtain the file
http:// cheeseshop.python.org/packages/2.4/s/setuptools/setuptools-0.6c6-py2.4.egg
and place it in this directory before rerunning this script.)
---------------------------------------------------------------------------
Downloading http: //cheeseshop.python.org/packages/2.4/s/setuptools/setuptools-0.6c6-py2.4.egg
Traceback (most recent call last):
File "setup.py", line 31, in ?
use_setuptools()
File "C:\Documents and Settings\lippela\Desktop\python-sybase-0.39\ez_setup.py
", line 86, in use_setuptools
egg = download_setuptools(version, download_base, to_dir, download_delay)
File "C:\Documents and Settings\lippela\Desktop\python-sybase-0.39\ez_setup.py
", line 140, in download_setuptools
src = urllib2.urlopen(url)
File "C:\Python24\lib\urllib2.py", line 130, in urlopen
return _opener.open(url, data)
File "C:\Python24\lib\urllib2.py", line 358, in open
response = self._open(req, data)
File "C:\Python24\lib\urllib2.py", line 376, in _open
'_open', req)
File "C:\Python24\lib\urllib2.py", line 337, in _call_chain
result = func(*args)
File "C:\Python24\lib\urllib2.py", line 1021, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "C:\Python24\lib\urllib2.py", line 996, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error (11001, 'getaddrinfo failed')>
Any idea?
| [
"The setup script failed to download the .egg it tries to download. It also tells you what to do when that happens: download the file yourself and place it in the same directory as the script.\n"
] | [
1
] | [] | [] | [
"python",
"sybase"
] | stackoverflow_0003320659_python_sybase.txt |
Q:
Generating all unique combinations for "drive ya nuts" puzzle
A while back I wrote a simple python program to brute-force the single solution for the drive ya nuts puzzle.
(source: tabbykat.com)
The puzzle consists of 7 hexagons with the numbers 1-6 on them, and all pieces must be aligned so that each number is adjacent to the same number on the next piece.
The puzzle has ~1.4G non-unique possibilities: you have 7! options to sort the pieces by order (for example, center=0, top=1, continuing in clockwise order...). After you sorted the pieces, you can rotate each piece in 6 ways (each piece is a hexagon), so you get 6**7 possible rotations for a given permutation of the 7 pieces. Totalling: 7!*(6**7)=~1.4G possibilities. The following python code generates these possible solutions:
def rotations(p):
for i in range(len(p)):
yield p[i:] + p[:i]
def permutations(l):
if len(l)<=1:
yield l
else:
for perm in permutations(l[1:]):
for i in range(len(perm)+1):
yield perm[:i] + l[0:1] + perm[i:]
def constructs(l):
for p in permutations(l):
for c in product(*(rotations(x) for x in p)):
yield c
However, note that the puzzle has only ~0.2G unique possible solutions, as you must divide the total number of possibilities by 6 since each possible solution is equivalent to 5 other solutions (simply rotate the entire puzzle by 1/6 a turn).
Is there a better way to generate only the unique possibilities for this puzzle?
A:
To get only unique valid solutions, you can fix the orientation of the piece in the center. For example, you can assume that that the "1" on the piece in the center is always pointing "up".
If you're not already doing so, you can make your program much more efficient by checking for a valid solution after placing each piece. Once you've placed two pieces in an invalid way, you don't need to enumerate all of the other invalid combinations.
A:
If there were no piece in the centre, this would be easy. Simply consider only the situations where piece 0 is at the top.
But we can extend that idea to the actual situation. You can consider only the situations where piece i is in the centre, and piece (i+1) % 7 is at the top.
A:
I think the search space is quite small, though the programming might be awkward.
We have seven choices for the centre piece. Then we have 6 choices for the
piece above that but its orientation is fixed, as its bottom edge must match the top edge of the centre piece, and similarly whenever we choose a piece to go in a slot, the orientation is fixed.
There are fewer choices for the remaining pieces. Suppose for
example we had chosen the centre piece and top piece as in the picture; then the
top right piece must have (clockwise) consecutive edges (5,3) to match the pieces in
place, and only three of the pieces have such a pair of edges (and in fact we've already
chosen one of them as the centre piece).
One could first off build a table with a list
of pieces for each edge pair, and then for each of the 42 choices of centre and top
proceed clockwise, choosing only among the pieces that have the required pair of edges (to match the centre piece and the previously placed piece) and backtracking if there are no such pieces.
I reckon the most common pair of edges is (1,6) which occurs on 4 pieces, two other edge pairs ((6,5) and (5,3)) occur on 3 pieces, there are 9 edge pairs that occur on two pieces, 14
that occur on 1 piece and 4 that don't occur at all.
So a very pessimistic estimate of the number of choices we must make is
7*6*4*3*3*2 or 3024.
| Generating all unique combinations for "drive ya nuts" puzzle | A while back I wrote a simple python program to brute-force the single solution for the drive ya nuts puzzle.
(source: tabbykat.com)
The puzzle consists of 7 hexagons with the numbers 1-6 on them, and all pieces must be aligned so that each number is adjacent to the same number on the next piece.
The puzzle has ~1.4G non-unique possibilities: you have 7! options to sort the pieces by order (for example, center=0, top=1, continuing in clockwise order...). After you sorted the pieces, you can rotate each piece in 6 ways (each piece is a hexagon), so you get 6**7 possible rotations for a given permutation of the 7 pieces. Totalling: 7!*(6**7)=~1.4G possibilities. The following python code generates these possible solutions:
def rotations(p):
for i in range(len(p)):
yield p[i:] + p[:i]
def permutations(l):
if len(l)<=1:
yield l
else:
for perm in permutations(l[1:]):
for i in range(len(perm)+1):
yield perm[:i] + l[0:1] + perm[i:]
def constructs(l):
for p in permutations(l):
for c in product(*(rotations(x) for x in p)):
yield c
However, note that the puzzle has only ~0.2G unique possible solutions, as you must divide the total number of possibilities by 6 since each possible solution is equivalent to 5 other solutions (simply rotate the entire puzzle by 1/6 a turn).
Is there a better way to generate only the unique possibilities for this puzzle?
| [
"To get only unique valid solutions, you can fix the orientation of the piece in the center. For example, you can assume that that the \"1\" on the piece in the center is always pointing \"up\".\nIf you're not already doing so, you can make your program much more efficient by checking for a valid solution after pl... | [
5,
3,
1
] | [] | [] | [
"combinatorics",
"language_agnostic",
"probability",
"python"
] | stackoverflow_0002600924_combinatorics_language_agnostic_probability_python.txt |
Q:
Python: File not formatting like it should
The could below doesnt write to the text file as it should:
import re
download_results = open('download_result.txt', 'w')
s = 'AAAAAAABBBBCDEEEEEFFFFFFFFFFFFFGGGGGGGGGGGG##GGGGGGHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJKKKKKKKKKKKKLLLLLLLLLLLLLLLLMMMMMMM&&MMMMMMMMNNNNNNNNNNNNOOOOOOOOOOOO'
s = re.sub(r'[^\w]','',s)
s = ''.join(s)
for i in range(0, len(s), 60):
download_results.write('%s' % (s[i:i+60]))
download_results.write('\n\n')
download_results.close()
The output in the text file is:
AAAAAAABBBBCDEEEEEFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJKKKKKKKKKKKKLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMNNNNNNNNNNNNOOOOOOOOOOOO
But i would like the output to be:
AAAAAAABBBBCDEEEEEFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGHHHHHHHHHHH
HHHIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJKKKKKKKKKKKKLLLLLLLLLLLLLL
LLMMMMMMMMMMMMMMMNNNNNNNNNNNNOOOOOOOOOOOO
Where the script writes "S" in lines containing 60 characters.
A:
Change this:
download_results.write('%s' % (s[i:i+60]))
to this:
download_results.write('%s\n' % (s[i:i+60]))
A:
Then append a newline in your write call within the loop - write() doesn't automatically add a newline, unlike print.
for i in range(0, len(s), 60):
download_results.write('%s\n' % (s[i:i+60]))
download_results.write('\n')
download_results.close()
A:
You aren't writing any newline characters to the file.
A:
Add a newline to the .write invocation. write doesn't add a newline itself (print does, which might have been what confused you)
| Python: File not formatting like it should | The could below doesnt write to the text file as it should:
import re
download_results = open('download_result.txt', 'w')
s = 'AAAAAAABBBBCDEEEEEFFFFFFFFFFFFFGGGGGGGGGGGG##GGGGGGHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJKKKKKKKKKKKKLLLLLLLLLLLLLLLLMMMMMMM&&MMMMMMMMNNNNNNNNNNNNOOOOOOOOOOOO'
s = re.sub(r'[^\w]','',s)
s = ''.join(s)
for i in range(0, len(s), 60):
download_results.write('%s' % (s[i:i+60]))
download_results.write('\n\n')
download_results.close()
The output in the text file is:
AAAAAAABBBBCDEEEEEFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJKKKKKKKKKKKKLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMNNNNNNNNNNNNOOOOOOOOOOOO
But i would like the output to be:
AAAAAAABBBBCDEEEEEFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGHHHHHHHHHHH
HHHIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJKKKKKKKKKKKKLLLLLLLLLLLLLL
LLMMMMMMMMMMMMMMMNNNNNNNNNNNNOOOOOOOOOOOO
Where the script writes "S" in lines containing 60 characters.
| [
"Change this:\ndownload_results.write('%s' % (s[i:i+60]))\n\nto this:\ndownload_results.write('%s\\n' % (s[i:i+60]))\n\n",
"Then append a newline in your write call within the loop - write() doesn't automatically add a newline, unlike print.\nfor i in range(0, len(s), 60):\n download_results.write('%s\\n' % (s... | [
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003321348_python.txt |
Q:
I need help making a list
I am trying to make a disorganized text file into a list suitable for use with another python program. The text file is a list of data seperated by a few spaces but not in standard columns or anything organized. The goal of this program is to read through the file using python and after each piece of data that I want there is a space, so I want to make a new line. The output should be a list of data with each term on one line. In addition there are some terms that I do not want. All the terms that I want start with "JJ".
Here is what i have so far. Note this does not run yet. I am looking for help finishing this program that will select all the terms starting with JJ and make a new line at the space after the JJ term. Thanks Robert
datafile = open ('C:\\textfile.txt', 'r')
line_list = line.split(" ")
for x in line_list:
if x.startswith("JJ") : print line_list
EDIT: So i want to open the file called textfile and have python keep only the lines of data that start with "JJ". Additionaly I want each data to be on it's own line, which is why I want to seperate them using the space after each ilne of data? Is that clearer?
A:
lines = [item for item in open('C:\textfile.txt', 'r').read().split(' ') if item.startswith("JJ")]
| I need help making a list | I am trying to make a disorganized text file into a list suitable for use with another python program. The text file is a list of data seperated by a few spaces but not in standard columns or anything organized. The goal of this program is to read through the file using python and after each piece of data that I want there is a space, so I want to make a new line. The output should be a list of data with each term on one line. In addition there are some terms that I do not want. All the terms that I want start with "JJ".
Here is what i have so far. Note this does not run yet. I am looking for help finishing this program that will select all the terms starting with JJ and make a new line at the space after the JJ term. Thanks Robert
datafile = open ('C:\\textfile.txt', 'r')
line_list = line.split(" ")
for x in line_list:
if x.startswith("JJ") : print line_list
EDIT: So i want to open the file called textfile and have python keep only the lines of data that start with "JJ". Additionaly I want each data to be on it's own line, which is why I want to seperate them using the space after each ilne of data? Is that clearer?
| [
"lines = [item for item in open('C:\\textfile.txt', 'r').read().split(' ') if item.startswith(\"JJ\")]\n"
] | [
-1
] | [] | [] | [
"python"
] | stackoverflow_0003321651_python.txt |
Q:
Python list remove method: how's the implementation?
In java, I have my client class that have the "code" attr, and the equals method. Method equals receives another client and compares with itself's code attr.
In python, I just read that we have the __cmp__ method, to do the same as java method equals. Ok, I did that. I created my class client, with "code" attr and the method comp that verify if the code is the same.
class Client():
def __init__(self, code):
self.code = code
def __cmp__(self, obj):
return obj.code == self.code
def __repr__(self):
return str(self.code)
Then I put 3 Client objects in a python's list:
bla = [Client(1), Client(2), Client(3)]
Then, when I try:
bla.remove(Client(3))
The amazing python removes the first element (the Client with code 1).
What I am doing wrong? I searched the implementation of list in python's Lib files, but is not easy to find.
Anyone can help?
A:
http://docs.python.org/reference/datamodel.html#object.__cmp__
__cmp__(self, other)
Called by comparison operations if
rich comparison (see above) is not
defined. Should return a negative
integer if self < other, zero if self
== other, a positive integer if self > other.
Basically, you should change your implementation of __cmp__ to be...
def __cmp__(self, obj):
return cmp(obj.code, self.code)
The cmp() builtin function of Python is specifically designed to return the values that __cmp__ is expected to return by comparing its two arguments.
There is also a different function in Python called __eq__ which only checks equality, for which your current implementation of __cmp__ would be better suited.
A:
Sounds like you actually want __eq__
class Client():
def __init__(self, code):
self.code = code
def __eq__(self, obj):
return obj.code == self.code
# this is how you usually write cmp, Amber explained the problem
def __cmp__(self, other):
return cmp(self.code, other.code)
def __repr__(self):
return str(self.code)
Btw, what happens in your buggy example is that __cmp__ returns False as expected. But in Python False == 0 and returning 0 from __cmp__ means the compared elements are equal. So that is why it removes the first element!
| Python list remove method: how's the implementation? | In java, I have my client class that have the "code" attr, and the equals method. Method equals receives another client and compares with itself's code attr.
In python, I just read that we have the __cmp__ method, to do the same as java method equals. Ok, I did that. I created my class client, with "code" attr and the method comp that verify if the code is the same.
class Client():
def __init__(self, code):
self.code = code
def __cmp__(self, obj):
return obj.code == self.code
def __repr__(self):
return str(self.code)
Then I put 3 Client objects in a python's list:
bla = [Client(1), Client(2), Client(3)]
Then, when I try:
bla.remove(Client(3))
The amazing python removes the first element (the Client with code 1).
What I am doing wrong? I searched the implementation of list in python's Lib files, but is not easy to find.
Anyone can help?
| [
"http://docs.python.org/reference/datamodel.html#object.__cmp__\n\n__cmp__(self, other)\nCalled by comparison operations if\n rich comparison (see above) is not\n defined. Should return a negative\n integer if self < other, zero if self\n == other, a positive integer if self > other.\n\nBasically, you should ch... | [
5,
4
] | [] | [] | [
"compare",
"list",
"python"
] | stackoverflow_0003321676_compare_list_python.txt |
Q:
Search a file and save the lines the search term is in to a new file
I have two files. One is a csv and contains the search strings (one per line) and the other is a huge file which contains the search term at the start of each line but has extra information after which I would like to extract.
The search terms file is called 'search.csv' and looks like this:
3ksr
3ky8
2g5w
2gou
The file containing the other info is called 'CSA.txt' and looks like this:
3ksr,INFO.....
3ky8,INFO.....
2g5w,INFO.....
2gou,INFO.....
However, it is a very big file (over 8mb) and each search term has more than one occurence but the information is different for every occurence. I have some sample code:
import fileinput
import csv
csa = fileinput.input("CSA.dat", inplace=1)
pdb = csv.reader(open("search.csv"))
outfile = csv.writer(open("outfile.csv"), dielect = 'excel', delimiter = '\t')
for id in pdb:
for line in csa:
if id in str(line):
outfile.writerow([id, line])
csa.close()
However, this code doesnt work and seems to delete CSA.dat every time I try and run it (its backed up in an archive), or it says 'Text file busy'. Please help! Thanks in advance!
A:
Depending on how many search terms you have, and assuming they're all 4 characters:
terms = open('search.csv').split(',')
with open('CSV.dat', 'r') as f:
for line in f:
if line[:4] in terms:
#do something with line
print line
if they're not 4 chars you can do line[:line.find(',')] that will return either up to the first ',', or if that's not found it will return the entire line.
edit:
I had never heard of fileinput, but I just looked at it and "you're doing it wrong."
Helper class to quickly write a loop over all standard input files.
fileinput is for passing files to your program as command line arguments, which you're not doing. open(filename, mode) is how you open files in Python.
And for something that (seems) this simple, the csv reader is overkill, though it's probably worth using to write your file if you really want it in an excel format.
A:
It appears that the deletion of CSA.dat happens because you say inplace=1 in the fileinput constructor.
| Search a file and save the lines the search term is in to a new file | I have two files. One is a csv and contains the search strings (one per line) and the other is a huge file which contains the search term at the start of each line but has extra information after which I would like to extract.
The search terms file is called 'search.csv' and looks like this:
3ksr
3ky8
2g5w
2gou
The file containing the other info is called 'CSA.txt' and looks like this:
3ksr,INFO.....
3ky8,INFO.....
2g5w,INFO.....
2gou,INFO.....
However, it is a very big file (over 8mb) and each search term has more than one occurence but the information is different for every occurence. I have some sample code:
import fileinput
import csv
csa = fileinput.input("CSA.dat", inplace=1)
pdb = csv.reader(open("search.csv"))
outfile = csv.writer(open("outfile.csv"), dielect = 'excel', delimiter = '\t')
for id in pdb:
for line in csa:
if id in str(line):
outfile.writerow([id, line])
csa.close()
However, this code doesnt work and seems to delete CSA.dat every time I try and run it (its backed up in an archive), or it says 'Text file busy'. Please help! Thanks in advance!
| [
"Depending on how many search terms you have, and assuming they're all 4 characters:\nterms = open('search.csv').split(',')\n\nwith open('CSV.dat', 'r') as f:\n for line in f:\n if line[:4] in terms:\n #do something with line\n print line\n\nif they're not 4 chars you can do line[:line.f... | [
1,
0
] | [] | [] | [
"python",
"search"
] | stackoverflow_0003321962_python_search.txt |
Q:
Making directories recursively in python
I need to create a file with python, in the directory:
foo/bar/baz/filename.fil
The only problem, is that I don't know if baz, bar, or even foo have been created (they may have been, but the script doesn't guarantee it). So, obiously I can't do simply:
file = open('foo/bar/baz/filename.fil', 'wb')
# Stuff
# file.close()
because I will get an IOError if foo or bar or baz doesn't exist. So, I was thinking I could write a script that would
1. Through a loop of os.path.split()s, get each directory.
2. In a loop: Test to see if each directory exists:
3. If it doesn't: make it
4. Then write the file.
However, it seems like python should have a better way of doing this, so am I missing something, or is the only (or best) way to do it is the algorithm I listed above?
Thank you.
A:
Use os.makedirs
| Making directories recursively in python | I need to create a file with python, in the directory:
foo/bar/baz/filename.fil
The only problem, is that I don't know if baz, bar, or even foo have been created (they may have been, but the script doesn't guarantee it). So, obiously I can't do simply:
file = open('foo/bar/baz/filename.fil', 'wb')
# Stuff
# file.close()
because I will get an IOError if foo or bar or baz doesn't exist. So, I was thinking I could write a script that would
1. Through a loop of os.path.split()s, get each directory.
2. In a loop: Test to see if each directory exists:
3. If it doesn't: make it
4. Then write the file.
However, it seems like python should have a better way of doing this, so am I missing something, or is the only (or best) way to do it is the algorithm I listed above?
Thank you.
| [
"Use os.makedirs\n"
] | [
4
] | [] | [] | [
"file",
"python"
] | stackoverflow_0003322126_file_python.txt |
Q:
Ensuring code coverage in unit testing?
I have noticed that even though I have a lot of doctests in our Python code, when I trace the testing using the methods described here:
traceit
I find that there are certain lines of code that are never executed. I currently sift through the traceit logs to identify blocks of code that are never run, and then try to come up with different test cases to exercise these particular blocks. As you can imagine, this is very time-consuming and I was wondering if we are going about this the wrong way and whether you all have other advice or suggestions to deal with this problem, which I'm sure must be common as software becomes sufficiently complex.
A:
coverage.py is a very handy tool. Among other things, it provides branch coverage.
A:
Do you have a mandate from management to be dogmatic about obtaining 100% code coverage with your test cases? If not, do you believe touching every line of code is the most effective way to find bugs in your code? Assuming you don't have infinite time and people resources, you should probably focus on reasonably testing all of your non trivial code with emphasis on the parts that the developers know were tricky to write or error prone.
Although code coverage is great because you surely can't say a piece of code is tested until it has been touched, I just don't equate touching a piece of code to calling it tested. I'm not against code coverage, but it's too easy to fall into using code coverage as the metric to know when testing is complete. I think that would be a mistake.
| Ensuring code coverage in unit testing? | I have noticed that even though I have a lot of doctests in our Python code, when I trace the testing using the methods described here:
traceit
I find that there are certain lines of code that are never executed. I currently sift through the traceit logs to identify blocks of code that are never run, and then try to come up with different test cases to exercise these particular blocks. As you can imagine, this is very time-consuming and I was wondering if we are going about this the wrong way and whether you all have other advice or suggestions to deal with this problem, which I'm sure must be common as software becomes sufficiently complex.
| [
"coverage.py is a very handy tool. Among other things, it provides branch coverage.\n",
"Do you have a mandate from management to be dogmatic about obtaining 100% code coverage with your test cases? If not, do you believe touching every line of code is the most effective way to find bugs in your code? Assuming yo... | [
30,
19
] | [] | [] | [
"code_coverage",
"python",
"testing",
"unit_testing"
] | stackoverflow_0003322123_code_coverage_python_testing_unit_testing.txt |
Q:
Simple Python variable scope
It seems to me that functions can reference variables outside of their scope but cannot set them. Is this correct? Am I understanding this right?
I also included the globals usage. I know they are bad ju-ju and will avoid them; I know how to get around this, but just wanted to be clear.
My example program:
import foo
# beginning of functions
# this one works because I look at the variable but dont modify it
def do_something_working:
if flag_to_do_something:
print "I did it"
# this one does not work because I modify the var
def do_something_not_working:
if flag_to_do_something:
print "I did it"
flag_to_do_something = 0
# this one works, but if I do this God kills a kitten
def do_something_using_globals_working_bad_ju_ju:
global flag_to_do_something
if flag_to_do_something:
print "I did it"
flag_to_do_something = 0
# end of functions
flag_to_do_something = 1
do_something_working()
do_something_not_working()
do_something_using_globals_working_bad_ju_ju()
A:
Correct. Well mostly. When you flag_to_do_something = 0 you are not modifying the variable, you are creating a new variable. The flag_to_do_something that is created in the function will be a separate link to (in this case) the same object. However, if you had used a function or operator that modified the variable in place, then the code would have worked.
Example:
g = [1,2,3]
def a():
g = [1,2]
a()
print g #outputs [1,2,3]
g = [1,2,3]
def b():
g.remove(3)
b()
print g #outputs [1,2]
A:
Yep, pretty much. Note that "global" variables in Python are actually module-level variables - their scope is that Python module (a.k.a. source file), not the entire program, as would be the case with a true global variable. So Python globals aren't quite as bad as globals in, say, C. But it's still preferable to avoid them.
| Simple Python variable scope | It seems to me that functions can reference variables outside of their scope but cannot set them. Is this correct? Am I understanding this right?
I also included the globals usage. I know they are bad ju-ju and will avoid them; I know how to get around this, but just wanted to be clear.
My example program:
import foo
# beginning of functions
# this one works because I look at the variable but dont modify it
def do_something_working:
if flag_to_do_something:
print "I did it"
# this one does not work because I modify the var
def do_something_not_working:
if flag_to_do_something:
print "I did it"
flag_to_do_something = 0
# this one works, but if I do this God kills a kitten
def do_something_using_globals_working_bad_ju_ju:
global flag_to_do_something
if flag_to_do_something:
print "I did it"
flag_to_do_something = 0
# end of functions
flag_to_do_something = 1
do_something_working()
do_something_not_working()
do_something_using_globals_working_bad_ju_ju()
| [
"Correct. Well mostly. When you flag_to_do_something = 0 you are not modifying the variable, you are creating a new variable. The flag_to_do_something that is created in the function will be a separate link to (in this case) the same object. However, if you had used a function or operator that modified the variable... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0003322430_python.txt |
Q:
App Engine SDK: How do I view keys in a specific namespace using the Memcache Viewer?
I'm trying to use the Memcache Viewer in the App Engine Dev Console to view keys in a specific namespace. The obvious syntax of namespace.key is not working; I haven't been able to find documentation describing specific usage. Is this possible?
A:
Not possible. In dev, check namespace'd memcache items programmatically, e.g. using a handler.
Credit: moraes on #appengine / freenode (validated by looking at source)
| App Engine SDK: How do I view keys in a specific namespace using the Memcache Viewer? | I'm trying to use the Memcache Viewer in the App Engine Dev Console to view keys in a specific namespace. The obvious syntax of namespace.key is not working; I haven't been able to find documentation describing specific usage. Is this possible?
| [
"Not possible. In dev, check namespace'd memcache items programmatically, e.g. using a handler.\nCredit: moraes on #appengine / freenode (validated by looking at source)\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"memcached",
"python"
] | stackoverflow_0003175462_google_app_engine_memcached_python.txt |
Q:
Help on Regular Expression problem
i wonder if it's possible to make a RegEx for the following data pattern:
'152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.'
string = '152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.'
I am using this Regular Expression (Using Python's re module) to extract these names:
re.findall(r'(\d+): (.+), (.+), (.+), (.+).', string, re.M | re.S)
Result:
[('152', 'Ashkenazi A', 'Benlifer A', 'Korenblit J', 'Silberstein SD')]
Now trying with a different number (less than 4 or more than 4) of name data pattern doesn't work anymore because the RegEx expects to find only 4 of them:
(.+), (.+), (.+), (.+).
I can't find a way to generalize this pattern.
A:
A regular expression probably isn't the best way to solve this. You could use split():
>>> s = '152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.'
>>> s.split(": ")
['152', 'Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.']
>>> s.split(": ")[1].split(", ")
['Ashkenazi A', 'Benlifer A', 'Korenblit J', 'Silberstein SD.']
A:
This should do the trick if you only want the stuff after the numbers:
re.findall(r'\d+: (.+)(?:, .+)*\.', input, re.M | re.S)
And if you want everything:
re.findall(r'(\d+): (.+)(?:, .+)*\.', input, re.M | re.S)
And if you want to get them separated out into a list of matches, a nested regex will do it:
re.findall(r'[^,]+,|[^,]+$', re.findall(r'\d+: (.+)(?:, .+)*\.', input, re.M | re.S)[0],re.M|re.S)
A:
If you means that there may be more (or less too) names, you should maybe try something like this:
(\d+): (.+)*? Asterisk (*) means 0 or more occurrence of (.+)
A:
I can get close, but further processing may be necessary. It is probably better to do manual string splitting, especially if the data is reliably well-formatted.
Code
import re
string1 = '152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.'
string2 = '152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD, Hattingh CJR.'
for i in [string1, string2]:
print re.findall(r'(\d+):|(?:[.,\s?])?(.*?)(?:[.,])', i)
Output
[('152', ''), ('', 'Ashkenazi A'), ('', 'Benlifer A'), ('', 'Korenblit J'), ('', 'Silberstein SD')]
[('152', ''), ('', 'Ashkenazi A'), ('', 'Benlifer A'), ('', 'Korenblit J'), ('', 'Silberstein SD'), ('', 'Hattingh CJR')]
Edit: using 2 expressions
If you are willing to use two regex expressions, it can be done fairly painlessly:
import re
string1 = '152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.'
string2 = '152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD, Hattingh CJR.'
for i in [string1, string2]:
print re.findall(r'^(\d+):', i)
print re.findall(r'(?:[:,] )(\S+ [A-Z]+)(?=[\.,])', i)
produces
['152']
['Ashkenazi A', 'Benlifer A', 'Korenblit J', 'Silberstein SD']
['152']
['Ashkenazi A', 'Benlifer A', 'Korenblit J', 'Silberstein SD', 'Hattingh CJR']
| Help on Regular Expression problem | i wonder if it's possible to make a RegEx for the following data pattern:
'152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.'
string = '152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.'
I am using this Regular Expression (Using Python's re module) to extract these names:
re.findall(r'(\d+): (.+), (.+), (.+), (.+).', string, re.M | re.S)
Result:
[('152', 'Ashkenazi A', 'Benlifer A', 'Korenblit J', 'Silberstein SD')]
Now trying with a different number (less than 4 or more than 4) of name data pattern doesn't work anymore because the RegEx expects to find only 4 of them:
(.+), (.+), (.+), (.+).
I can't find a way to generalize this pattern.
| [
"A regular expression probably isn't the best way to solve this. You could use split():\n>>> s = '152: Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.'\n>>> s.split(\": \")\n['152', 'Ashkenazi A, Benlifer A, Korenblit J, Silberstein SD.']\n>>> s.split(\": \")[1].split(\", \")\n['Ashkenazi A', 'Benlifer A', 'K... | [
6,
1,
0,
0
] | [] | [] | [
"python",
"regex",
"string",
"unicode"
] | stackoverflow_0003322735_python_regex_string_unicode.txt |
Q:
Can I use python to create flash like browser games?
is it possible to use python to create flash like browser games? (Actually I want to use it for an economic simulation, but it amounts to the same as a browser game)
Davoud
A:
The answer would be yes, assuming you consider this a good example of what you want to do:
http://pyjs.org/examples/Space.html
This browser-based version of Asteroids was created using Pyjamas, which enables you to write the code in python in one place, and have it run either on the browser, or on the desktop:
http://pyjs.org/
Having recently found Pyjamas, and also preferring to consolidate my code in one language (Python!) and location (instead of having some code server-side, and some browser/client-side, in different languages), it's definitely an exciting technology. Its authors have ported the Google Web Toolkit to Python, a really impressive feat, retaining the expressive power of Python (something like 80,000 lines of Java was shrunk to 8,000 lines of Python). More Pythonistas should know about it. :)
A:
You could use Python to do client side scripting using Silverlight + IronPython. Of course, this requires all your users install Silverlight.
I think you're talking about using Python on the back end, in which case running something on the server side with Python (in which case this Django vs other Python web frameworks SO question is a good general list and may have what you're looking for.
A:
You need to use something that the current browsers support, this means you're stuck with Flash, Java applets or Javascript+HTML if you want your game displayed in a browser.
You can use python on the backend and display pure HTML, if that is enough for your needs.
A:
Yes, but there a a number of ways to get there.
Flash is the client side rendering. You could use Python to generate Flash, or you could use Python to generate some dynamic HTML with Javascript, etc. that was interactive in a similar way.
But the Python will be running on the server. The Flash, ActionScript, HTML, JavaScript, etc. will all be running on the client.
So while the answer to the question is yes, I am going to suggest you might need to do more research and ask a better question.
A:
You could have Python CGI code as a backend and send input in to it through AJAX. Its probably better just use something on the client side for this, though.
| Can I use python to create flash like browser games? | is it possible to use python to create flash like browser games? (Actually I want to use it for an economic simulation, but it amounts to the same as a browser game)
Davoud
| [
"The answer would be yes, assuming you consider this a good example of what you want to do:\nhttp://pyjs.org/examples/Space.html\nThis browser-based version of Asteroids was created using Pyjamas, which enables you to write the code in python in one place, and have it run either on the browser, or on the desktop:\n... | [
13,
4,
2,
1,
1
] | [] | [] | [
"browser",
"python",
"python_webbrowser"
] | stackoverflow_0002899907_browser_python_python_webbrowser.txt |
Q:
Suppose I had a list in Python. What's the most pythonic and efficient way to randomize it by sections?
I have a list of X items.
I want the first 10 to be randomized. Then, the 2nd 10 items to be randomized. Then the 3rd.
What's the most efficient way to do this?
A:
It's good to break apart problems into smaller problems which can be solved with reusable parts. The grouper idiom provides one such reusable part: it takes an iterable and groups its elements into groups of size n:
import random
import itertools
def grouper(n, iterable, fillvalue=None):
# Source: http://docs.python.org/library/itertools.html#recipes
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
return itertools.izip_longest(*[iter(iterable)]*n,fillvalue=fillvalue)
X=100
alist=xrange(X)
blist=[]
for group in grouper(10,alist):
group=list(group)
random.shuffle(group)
blist.extend(group)
print(group)
# [7, 6, 4, 9, 8, 1, 5, 2, 0, 3]
# [16, 19, 11, 15, 12, 18, 10, 17, 13, 14]
# [26, 27, 28, 22, 24, 21, 23, 20, 25, 29]
# [33, 32, 37, 39, 38, 35, 30, 36, 34, 31]
# [49, 46, 47, 42, 40, 48, 44, 43, 41, 45]
# [55, 51, 50, 52, 56, 58, 57, 53, 59, 54]
# [69, 66, 61, 60, 64, 68, 62, 67, 63, 65]
# [73, 76, 71, 78, 72, 77, 70, 74, 79, 75]
# [85, 88, 82, 87, 80, 83, 84, 81, 89, 86]
# [92, 90, 95, 98, 94, 97, 91, 93, 99, 96]
print(blist)
# [7, 6, 4, 9, 8, 1, 5, 2, 0, 3, 16, 19, 11, 15, 12, 18, 10, 17, 13, 14, 26, 27, 28, 22, 24, 21, 23, 20, 25, 29, 33, 32, 37, 39, 38, 35, 30, 36, 34, 31, 49, 46, 47, 42, 40, 48, 44, 43, 41, 45, 55, 51, 50, 52, 56, 58, 57, 53, 59, 54, 69, 66, 61, 60, 64, 68, 62, 67, 63, 65, 73, 76, 71, 78, 72, 77, 70, 74, 79, 75, 85, 88, 82, 87, 80, 83, 84, 81, 89, 86, 92, 90, 95, 98, 94, 97, 91, 93, 99, 96]
A:
How about this?
import random
a = [1,2,3,4,5,6,7,8,9,0,'a','b','c','d','e','f','g','h','i','j','k','l','m']
parts=[a[i:i+10] for i in range(0, len(a), 10)]
map(random.shuffle,parts)
result = sum(parts,[])
A:
import random
random.seed()
a = [1,2,3,4,5,6,7,8,9,0,'a','b','c','d','e','f','g','h','i','j']
def groupRand (elems, gsize=10):
temp_list = elems[:]
result = []
while temp_list:
aux = temp_list[:gsize]
random.shuffle (aux)
result += aux
del(temp_list[:gsize])
return result
print (groupRand(a))
# [7, 8, 3, 1, 0, 6, 9, 4, 2, 5, 'i', 'e', 'g', 'b', 'h', 'c', 'j', 'd', 'f', 'a']
| Suppose I had a list in Python. What's the most pythonic and efficient way to randomize it by sections? | I have a list of X items.
I want the first 10 to be randomized. Then, the 2nd 10 items to be randomized. Then the 3rd.
What's the most efficient way to do this?
| [
"It's good to break apart problems into smaller problems which can be solved with reusable parts. The grouper idiom provides one such reusable part: it takes an iterable and groups its elements into groups of size n: \nimport random\nimport itertools\n\ndef grouper(n, iterable, fillvalue=None):\n # Source: http:... | [
2,
2,
0
] | [] | [] | [
"algorithm",
"list",
"python",
"random",
"sorting"
] | stackoverflow_0003321961_algorithm_list_python_random_sorting.txt |
Q:
Cross-Platform Bonjour
Is it possible to write a program using Bonjour or a Bonjour-compatible library in a cross-platform language such as Java or Python?
If so, where can I find the files needed for this?
A:
For Java have a look at the jmdns library which does it all in pure Java. http://jmdns.sourceforge.net/
I do not believe it can delegate to the native implementation if running on OS X, but it has been a while, so it might these days.
| Cross-Platform Bonjour | Is it possible to write a program using Bonjour or a Bonjour-compatible library in a cross-platform language such as Java or Python?
If so, where can I find the files needed for this?
| [
"For Java have a look at the jmdns library which does it all in pure Java. http://jmdns.sourceforge.net/\nI do not believe it can delegate to the native implementation if running on OS X, but it has been a while, so it might these days.\n"
] | [
1
] | [] | [] | [
"bonjour",
"cross_platform",
"java",
"python"
] | stackoverflow_0003322689_bonjour_cross_platform_java_python.txt |
Q:
Am I supposed to directly modify User models in auth modules in frameworks?
I am new to using Frameworks for web development and I have noticed that frameworks like django, turbogears etc come with auth packages which contains user models. Am I supposed to directly modify these and use them as my User models or am I supposed to associate my own user models to these and use them just for authentication?
A:
The latter: build a model with a one to one relationship to the User. Don't modify the django one directly or you'll likely run into trouble sooner or later. The django team won't be taking your changes into account after all and you could be adversely impacted if any internal changes are made. (Though you needn't worry about compatibility with the external interface to your own application.)
| Am I supposed to directly modify User models in auth modules in frameworks? | I am new to using Frameworks for web development and I have noticed that frameworks like django, turbogears etc come with auth packages which contains user models. Am I supposed to directly modify these and use them as my User models or am I supposed to associate my own user models to these and use them just for authentication?
| [
"The latter: build a model with a one to one relationship to the User. Don't modify the django one directly or you'll likely run into trouble sooner or later. The django team won't be taking your changes into account after all and you could be adversely impacted if any internal changes are made. (Though you need... | [
1
] | [] | [] | [
"django",
"frameworks",
"python",
"turbogears"
] | stackoverflow_0003323139_django_frameworks_python_turbogears.txt |
Q:
How to use same cookies in multiple request in python?
I am using this code:
def req(url, postfields):
proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})
opener = urllib2.build_opener(proxy_support)
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
return opener.open(url).read()
To make a simple http get request (using tor as proxy).
Now I would like to know how to make multiple request using the same cookie.
For example:
req('http://loginpage', 'postfields')
source = req('http://pageforloggedinonly', 0)
#do stuff with source
req('http://anotherpageforloggedinonly', 'StuffFromSource')
I know that my function req doesn't support POST (yet), but I have sent postfields using httplib so I guess I can figure that by myself, but I don't understand how to use cookies, I saw some examples but they are all one request only, I want to reuse the cookie from the first login request in the succeeding requests, or saving/using the cookie from a file (like curl does), that would make everything easier.
The code I posted I only to illustrate what I am trying to achieve, I think I will use httplib(2) for the final app.
UPDATE:
cookielib.LWPCOokieJar worked fine, here's a sample I did for testing:
import urllib2, cookielib, os
def request(url, postfields, cookie):
urlopen = urllib2.urlopen
cj = cookielib.LWPCookieJar()
Request = urllib2.Request
if os.path.isfile(cookie):
cj.load(cookie)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
req = Request(url, postfields, txheaders)
handle = urlopen(req)
cj.save(cookie)
return handle.read()
print request('http://google.com', None, 'cookie.txt')
A:
The cookielib module is what you need to do this. There's a nice tutorial with some code samples.
| How to use same cookies in multiple request in python? | I am using this code:
def req(url, postfields):
proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})
opener = urllib2.build_opener(proxy_support)
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
return opener.open(url).read()
To make a simple http get request (using tor as proxy).
Now I would like to know how to make multiple request using the same cookie.
For example:
req('http://loginpage', 'postfields')
source = req('http://pageforloggedinonly', 0)
#do stuff with source
req('http://anotherpageforloggedinonly', 'StuffFromSource')
I know that my function req doesn't support POST (yet), but I have sent postfields using httplib so I guess I can figure that by myself, but I don't understand how to use cookies, I saw some examples but they are all one request only, I want to reuse the cookie from the first login request in the succeeding requests, or saving/using the cookie from a file (like curl does), that would make everything easier.
The code I posted I only to illustrate what I am trying to achieve, I think I will use httplib(2) for the final app.
UPDATE:
cookielib.LWPCOokieJar worked fine, here's a sample I did for testing:
import urllib2, cookielib, os
def request(url, postfields, cookie):
urlopen = urllib2.urlopen
cj = cookielib.LWPCookieJar()
Request = urllib2.Request
if os.path.isfile(cookie):
cj.load(cookie)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
req = Request(url, postfields, txheaders)
handle = urlopen(req)
cj.save(cookie)
return handle.read()
print request('http://google.com', None, 'cookie.txt')
| [
"The cookielib module is what you need to do this. There's a nice tutorial with some code samples.\n"
] | [
2
] | [] | [] | [
"cookies",
"http",
"httprequest",
"python"
] | stackoverflow_0003323355_cookies_http_httprequest_python.txt |
Q:
Python Regex Question
I have an end tag followed by a carriage return line feed (x0Dx0A) followd by one or more tabs (x09) followed by a new start tag .
Something like this:
</tag1>x0Dx0Ax09x09x09<tag2> or </tag1>x0Dx0Ax09x09x09x09x09<tag2>
What Python regex should I use to replace it with something like this:
</tag1><tag3>content</tag3><tag2>
Thanks in advance.
A:
Here is code for something like what you say that you need:
>>> import re
>>> sample = '</tag1>\r\n\t\t\t\t<tag2>'
>>> sample
'</tag1>\r\n\t\t\t\t<tag2>'
>>> pattern = '(</tag1>)\r\n\t+(<tag2>)'
>>> replacement = r'\1<tag3>content</tag3>\2'
>>> re.sub(pattern, replacement, sample)
'</tag1><tag3>content</tag3><tag2>'
>>>
Note that \r\n\t+ may be a bit too specific, especially if production of your input is not under your control. It may be better to adopt the much more general \s* (zero or more whitespace characters).
Using regexes to parse XML and HTML is not a good idea in general ... while it's hard to see a failure mode here (apart from elementary errors in getting the pattern correct), you might like to tell us what the underlying problem is, in case some other solution is better.
| Python Regex Question | I have an end tag followed by a carriage return line feed (x0Dx0A) followd by one or more tabs (x09) followed by a new start tag .
Something like this:
</tag1>x0Dx0Ax09x09x09<tag2> or </tag1>x0Dx0Ax09x09x09x09x09<tag2>
What Python regex should I use to replace it with something like this:
</tag1><tag3>content</tag3><tag2>
Thanks in advance.
| [
"Here is code for something like what you say that you need:\n>>> import re\n>>> sample = '</tag1>\\r\\n\\t\\t\\t\\t<tag2>'\n>>> sample\n'</tag1>\\r\\n\\t\\t\\t\\t<tag2>'\n>>> pattern = '(</tag1>)\\r\\n\\t+(<tag2>)'\n>>> replacement = r'\\1<tag3>content</tag3>\\2'\n>>> re.sub(pattern, replacement, sample)\n'</tag1>... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003322383_python_regex.txt |
Q:
Character detection in a text file in Python using the Universal Encoding Detector (chardet)
I am trying to use the Universal Encoding Detector (chardet) in Python to detect the most probable character encoding in a text file ('infile') and use that in further processing.
While chardet is designed primarily for detecting the character encoding of webpages, I have found an example of it being used on individual text files.
However, I cannot work out how to tell the script to set the most likely character encoding to the variable 'charenc' (which is used several times throughout the script).
My code, based on a combination of the aforementioned example and chardet's own documentation is as follows:
import chardet
rawdata=open(infile,"r").read()
chardet.detect(rawdata)
Character detection is necessary as the script goes on to run the following (as well as several similar uses):
inF=open(infile,"rb")
s=unicode(inF.read(),charenc)
inF.close()
Any help would be greatly appreciated.
A:
chardet.detect() returns a dictionary which provides the encoding as the value associated with the key 'encoding'. So you can do this:
import chardet
rawdata = open(infile, 'rb').read()
result = chardet.detect(rawdata)
charenc = result['encoding']
The chardet documentation is not explicitly clear about whether text strings and/or byte strings are supposed to work with the module, but it stands to reason that if you have a text string you don't need to run character detection on it, so you should probably be passing byte strings. Hence the binary mode flag (b) in the call to open(). But chardet.detect() might also work with a text string depending on which versions of Python and of the library you're using, i.e. if you do omit the b you might find that it works anyway even though you're technically doing something wrong.
| Character detection in a text file in Python using the Universal Encoding Detector (chardet) | I am trying to use the Universal Encoding Detector (chardet) in Python to detect the most probable character encoding in a text file ('infile') and use that in further processing.
While chardet is designed primarily for detecting the character encoding of webpages, I have found an example of it being used on individual text files.
However, I cannot work out how to tell the script to set the most likely character encoding to the variable 'charenc' (which is used several times throughout the script).
My code, based on a combination of the aforementioned example and chardet's own documentation is as follows:
import chardet
rawdata=open(infile,"r").read()
chardet.detect(rawdata)
Character detection is necessary as the script goes on to run the following (as well as several similar uses):
inF=open(infile,"rb")
s=unicode(inF.read(),charenc)
inF.close()
Any help would be greatly appreciated.
| [
"chardet.detect() returns a dictionary which provides the encoding as the value associated with the key 'encoding'. So you can do this:\nimport chardet \nrawdata = open(infile, 'rb').read()\nresult = chardet.detect(rawdata)\ncharenc = result['encoding']\n\nThe chardet documentation is not explicitly clear about ... | [
66
] | [] | [] | [
"character_encoding",
"python"
] | stackoverflow_0003323770_character_encoding_python.txt |
Q:
celery-django can't find settings
I have a Django project that uses Celery for running asynchronous tasks. I'm doing my development on a Windows XP machine.
Starting my Django server (python manage.py runserver 80) works fine, but attempting to start the Celery Daemon (python manage.py celeryd start) fails with the following error:
ImportError: Could not import settings 'src.settings' (Is it on sys.path? Does it have syntax errors?): No module named src.settings
sys.path includes 'C:\development\SpaceCorps\src', so I'm not sure why it can't find this module.
Here's the full output from starting the daemon:
C:\development\SpaceCorps\src>python manage.py celeryd start
[2010-07-23 18:29:31,456: WARNING/MainProcess] ?[1;33mcelery@mike-laptop v2.0.1 is starting.?[0m
[2010-07-23 18:29:31,456: WARNING/MainProcess] ?[1;33mC:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\bin\celeryd.py:206: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in a production environment!
warnings.warn("Using settings.DEBUG leads to a memory leak, "?[0m
[2010-07-23 18:29:31,456: WARNING/MainProcess] ?[1;33mConfiguration ->
. broker -> amqp://guest@localhost:5672/
. queues ->
. celery -> exchange:celery (direct) binding:celery
. concurrency -> 2
. loader -> djcelery.loaders.DjangoLoader
. logfile -> [stderr]@WARNING
. events -> OFF
. beat -> OFF?[0m
[2010-07-23 18:29:31,706: WARNING/MainProcess] ?[1;33mcelery@mike-laptop has started.?[0m
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Program Files\Python26\lib\multiprocessing\forking.py", line 342, in main
self = load(from_parent)
File "C:\Program Files\Python26\lib\pickle.py", line 1370, in load
return Unpickler(file).load()
File "C:\Program Files\Python26\lib\pickle.py", line 858, in load
Traceback (most recent call last):
File "<string>", line 1, in <module>
dispatch[key](self)
File "C:\Program Files\Python26\lib\pickle.py", line 1090, in load_global
File "C:\Program Files\Python26\lib\multiprocessing\forking.py", line 342, in main
self = load(from_parent)
File "C:\Program Files\Python26\lib\pickle.py", line 1370, in load
klass = self.find_class(module, name)
File "C:\Program Files\Python26\lib\pickle.py", line 1124, in find_class
return Unpickler(file).load()
File "C:\Program Files\Python26\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Program Files\Python26\lib\pickle.py", line 1090, in load_global
__import__(module)
File "C:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\concurrency\processes\__init__.py", line 7, in <module>
from celery import log
File "C:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\log.py", line 8, in <module>
from celery import conf
File "C:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\conf.py", line 118, in <module>
ALWAYS_EAGER = _get("CELERY_ALWAYS_EAGER")
File "C:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\conf.py", line 109, in _get
value = getattr(settings, alias)
File "c:\development\django\django\utils\functional.py", line 276, in __getattr__
self._setup()
File "c:\development\django\django\conf\__init__.py", line 40, in _setup
self._wrapped = Settings(settings_module)
File "c:\development\django\django\conf\__init__.py", line 75, in __init__
raise ImportError("Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'src.settings' (Is it on sys.path? Does it have syntax errors?): No module named src.settings
A:
Apparently this is a problem with running Celery on Windows. Using the --settings argument ala python manage.py celeryd start --settings=settings did the trick.
A:
sys.path must include 'C:\development\SpaceCorps' not 'C:\development\SpaceCorps\src',
because he is looking for src.settings, not just settings.
| celery-django can't find settings | I have a Django project that uses Celery for running asynchronous tasks. I'm doing my development on a Windows XP machine.
Starting my Django server (python manage.py runserver 80) works fine, but attempting to start the Celery Daemon (python manage.py celeryd start) fails with the following error:
ImportError: Could not import settings 'src.settings' (Is it on sys.path? Does it have syntax errors?): No module named src.settings
sys.path includes 'C:\development\SpaceCorps\src', so I'm not sure why it can't find this module.
Here's the full output from starting the daemon:
C:\development\SpaceCorps\src>python manage.py celeryd start
[2010-07-23 18:29:31,456: WARNING/MainProcess] ?[1;33mcelery@mike-laptop v2.0.1 is starting.?[0m
[2010-07-23 18:29:31,456: WARNING/MainProcess] ?[1;33mC:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\bin\celeryd.py:206: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in a production environment!
warnings.warn("Using settings.DEBUG leads to a memory leak, "?[0m
[2010-07-23 18:29:31,456: WARNING/MainProcess] ?[1;33mConfiguration ->
. broker -> amqp://guest@localhost:5672/
. queues ->
. celery -> exchange:celery (direct) binding:celery
. concurrency -> 2
. loader -> djcelery.loaders.DjangoLoader
. logfile -> [stderr]@WARNING
. events -> OFF
. beat -> OFF?[0m
[2010-07-23 18:29:31,706: WARNING/MainProcess] ?[1;33mcelery@mike-laptop has started.?[0m
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Program Files\Python26\lib\multiprocessing\forking.py", line 342, in main
self = load(from_parent)
File "C:\Program Files\Python26\lib\pickle.py", line 1370, in load
return Unpickler(file).load()
File "C:\Program Files\Python26\lib\pickle.py", line 858, in load
Traceback (most recent call last):
File "<string>", line 1, in <module>
dispatch[key](self)
File "C:\Program Files\Python26\lib\pickle.py", line 1090, in load_global
File "C:\Program Files\Python26\lib\multiprocessing\forking.py", line 342, in main
self = load(from_parent)
File "C:\Program Files\Python26\lib\pickle.py", line 1370, in load
klass = self.find_class(module, name)
File "C:\Program Files\Python26\lib\pickle.py", line 1124, in find_class
return Unpickler(file).load()
File "C:\Program Files\Python26\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Program Files\Python26\lib\pickle.py", line 1090, in load_global
__import__(module)
File "C:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\concurrency\processes\__init__.py", line 7, in <module>
from celery import log
File "C:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\log.py", line 8, in <module>
from celery import conf
File "C:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\conf.py", line 118, in <module>
ALWAYS_EAGER = _get("CELERY_ALWAYS_EAGER")
File "C:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\conf.py", line 109, in _get
value = getattr(settings, alias)
File "c:\development\django\django\utils\functional.py", line 276, in __getattr__
self._setup()
File "c:\development\django\django\conf\__init__.py", line 40, in _setup
self._wrapped = Settings(settings_module)
File "c:\development\django\django\conf\__init__.py", line 75, in __init__
raise ImportError("Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'src.settings' (Is it on sys.path? Does it have syntax errors?): No module named src.settings
| [
"Apparently this is a problem with running Celery on Windows. Using the --settings argument ala python manage.py celeryd start --settings=settings did the trick.\n",
"sys.path must include 'C:\\development\\SpaceCorps' not 'C:\\development\\SpaceCorps\\src', \nbecause he is looking for src.settings, not just set... | [
19,
0
] | [] | [] | [
"celery",
"django",
"python",
"python_import",
"settings"
] | stackoverflow_0003323125_celery_django_python_python_import_settings.txt |
Q:
Python: An empty element remains after the list comprehension
keywords_list = """
cow
dog
cat
"""
keywords_list = [i.strip() for i in keywords_list.split("\n") if i]
I'm still getting an empty element(last element) and I'm wondering why. Also suggestions to improve my code would be appreciated.
Thanks in advance!
edit:
solved it myself by stripping the string first but I'm still wondering why there's a remaining empty string element in the list.
Here's my solution:
keywords_list = [i.strip() for i in keywords_list.strip().split("\n")]
A:
You're checking if i, and that succeeds for any non-empty string i -- including one that's all whitespace and so will produce an empty string after stripping. To fix, use
if i and not i.isspace()
as your listcomp's condition (so this only succeeds for non-empty, non-all-whitespace strings).
A:
solved it myself by stripping the string first but I'm still wondering why there's a remaining empty string element in the list.
Because your initial string is "\ncow\ndog\ncat\n", so when you split('\n'), you get ['', 'cow', 'dog', 'cat', ''].
Its just the way split works - whenever it finds separator, it splits content in 2 elements, one for part before separator, one for part after it, even if one of them is empty.
A:
When you have a string, 'abc<sep>def<sep>ghi', you clearly want the split to produce ['abc', 'def', 'ghi']. If your string is truncated to 'abc<sep>def<sep>', you still have two separators, so you will still end up with three list items, the last one being the empty string that follows the second separator.
In short, your string uses '\n' as a terminator, but the split function interprets it as a separator.
You can fix this without requiring strip(). Think of '\n' as a separator, and remove the final newline from the input string:
keywords_list = """
cow
dog
cat"""
| Python: An empty element remains after the list comprehension | keywords_list = """
cow
dog
cat
"""
keywords_list = [i.strip() for i in keywords_list.split("\n") if i]
I'm still getting an empty element(last element) and I'm wondering why. Also suggestions to improve my code would be appreciated.
Thanks in advance!
edit:
solved it myself by stripping the string first but I'm still wondering why there's a remaining empty string element in the list.
Here's my solution:
keywords_list = [i.strip() for i in keywords_list.strip().split("\n")]
| [
"You're checking if i, and that succeeds for any non-empty string i -- including one that's all whitespace and so will produce an empty string after stripping. To fix, use\nif i and not i.isspace()\n\nas your listcomp's condition (so this only succeeds for non-empty, non-all-whitespace strings).\n",
"\nsolved it... | [
2,
1,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003323805_list_python.txt |
Q:
Recursion Recursion Recursion --- How can i Improve Performance? (Python Archive Recursive Extraction)
I am trying to develop a Recursive Extractor. The problem is , it is Recursing Too Much (Evertime it found an archive type) and taking a performance hit.
So how can i improve below code?
My Idea 1:
Get the 'Dict' of direcories first , together with file types.Filetypes as Keys. Extract the file types. When an Archive is found Extract only that one. Then Regenerate Archive Dict again.
My Idea 2:
os.walk returns Generator. So is there something i can do with generators? I am new to Generators.
here is the current code :
import os, magic
m = magic.open( magic.MAGIC_NONE )
m.load()
archive_type = [ 'gzip compressed data',
'7-zip archive data',
'Zip archive data',
'bzip2 compressed data',
'tar archive',
'POSIX tar archive',
'POSIX tar archive (GNU)',
'RAR archive data',
'Microsoft Outlook email folder (>=2003)',
'Microsoft Outlook email folder']
def extractRecursive( path ,archives):
i=0
for dirpath, dirnames, filenames in os.walk( path ):
for f in filenames:
fp = os.path.join( dirpath, f )
i+=1
print i
file_type = m.file( fp ).split( "," )[0]
if file_type in archives:
arcExtract(fp,file_type,path,True)
extractRecursive(path,archives)
return "Done"
def arcExtract(file_path,file_type,extracted_path="/home/v3ss/Downloads/extracted",unlink=False):
import subprocess,shlex
if file_type in pst_types:
cmd = "readpst -o '%s' -S '%s'" % (extracted_path,file_path)
else:
cmd = "7z -y -r -o%s x '%s'" % (extracted_path,file_path)
print cmd
args= shlex.split(cmd)
print args
try:
sp = subprocess.Popen( args, shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE )
out, err = sp.communicate()
print out, err
ret = sp.returncode
except OSError:
print "Error no %s Message %s" % (OSError.errno,OSError.message)
pass
if ret == 0:
if unlink==True:
os.unlink(file_path)
return "OK!"
else:
return "Failed"
if __name__ == '__main__':
extractRecursive( 'Path/To/Archives' ,archive_type)
A:
You can simplify your extractRecursive method to use os.walk as it should be used. os.walk already reads all subdirectories so your recursion is unneeded.
Simply remove the recursive call and it should work :)
def extractRecursive(path, archives, extracted_archives=None):
i = 0
if not extracted_archives:
extracted_archives = set()
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
i += 1
print i
file_type = m.file(fp).split(',')[0]
if file_type in archives and fp not in extracted_archives:
extracted_archives.add(fp)
extracted_in.add(dirpath)
arcExtract(fp, file_type, path, True)
for path in extracted_in:
extractRecursive(path, archives, extracted_archives)
return "Done"
A:
If, as it appears, you want to extract the archive files to paths "above" the one they're in, os.walk per se (in its normal top-down operation) can't help you (because by the time you extract an archive into a certain directory x, os.walk may likely, though not necessarily, already considered directory x -- so only by having os.walk look at the whole path over and over again can you get all contents). Except, I'm surprised your code ever terminates, since the archive-type files should keep getting found and extracted -- I don't see what can ever terminate the recursion. (To solve that it would suffice to keep a set of all the paths of archive-type files you've already extracted, to avoid considering them again when you meet them again).
By far the best architecture, anyway, would be if arcExtract was to return a list of all the files it has extracted (specifically their destination paths) -- then you could simply keep extending a list with all these extracted files during the os.walk loop (no recursion), and then keep looping just on the list (no need to keep asking the OS about files and directories, saving lots of time on that operation too) and producing a new similar list. No recursion, no redundancy of work. I imagine that readpst and 7z are able to supply such lists (maybe on their standard output or error, which you currently just display but don't process) in some textual form that you could parse to make it into a list...?
| Recursion Recursion Recursion --- How can i Improve Performance? (Python Archive Recursive Extraction) | I am trying to develop a Recursive Extractor. The problem is , it is Recursing Too Much (Evertime it found an archive type) and taking a performance hit.
So how can i improve below code?
My Idea 1:
Get the 'Dict' of direcories first , together with file types.Filetypes as Keys. Extract the file types. When an Archive is found Extract only that one. Then Regenerate Archive Dict again.
My Idea 2:
os.walk returns Generator. So is there something i can do with generators? I am new to Generators.
here is the current code :
import os, magic
m = magic.open( magic.MAGIC_NONE )
m.load()
archive_type = [ 'gzip compressed data',
'7-zip archive data',
'Zip archive data',
'bzip2 compressed data',
'tar archive',
'POSIX tar archive',
'POSIX tar archive (GNU)',
'RAR archive data',
'Microsoft Outlook email folder (>=2003)',
'Microsoft Outlook email folder']
def extractRecursive( path ,archives):
i=0
for dirpath, dirnames, filenames in os.walk( path ):
for f in filenames:
fp = os.path.join( dirpath, f )
i+=1
print i
file_type = m.file( fp ).split( "," )[0]
if file_type in archives:
arcExtract(fp,file_type,path,True)
extractRecursive(path,archives)
return "Done"
def arcExtract(file_path,file_type,extracted_path="/home/v3ss/Downloads/extracted",unlink=False):
import subprocess,shlex
if file_type in pst_types:
cmd = "readpst -o '%s' -S '%s'" % (extracted_path,file_path)
else:
cmd = "7z -y -r -o%s x '%s'" % (extracted_path,file_path)
print cmd
args= shlex.split(cmd)
print args
try:
sp = subprocess.Popen( args, shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE )
out, err = sp.communicate()
print out, err
ret = sp.returncode
except OSError:
print "Error no %s Message %s" % (OSError.errno,OSError.message)
pass
if ret == 0:
if unlink==True:
os.unlink(file_path)
return "OK!"
else:
return "Failed"
if __name__ == '__main__':
extractRecursive( 'Path/To/Archives' ,archive_type)
| [
"You can simplify your extractRecursive method to use os.walk as it should be used. os.walk already reads all subdirectories so your recursion is unneeded.\nSimply remove the recursive call and it should work :)\ndef extractRecursive(path, archives, extracted_archives=None):\n i = 0\n if not extracted_archive... | [
1,
1
] | [] | [] | [
"archive",
"extract",
"generator",
"python",
"recursion"
] | stackoverflow_0003323829_archive_extract_generator_python_recursion.txt |
Q:
python mysqldb cursor messages list shows errors twice
For some reason whenever i run a query on the db cursor, it generates two errors in its .messages list, is this a feature?
here is the code that runs the query, all the application does is open a connection to the db, run this once with a forced error, read the .messages, then exit
import MySQLdb
class dbobject:
def __init__(self, dbhost, dbuser, dbpass, dbname):
self.connection = MySQLdb.connect( user=dbuser, passwd=dbpass, host=dbhost, db=dbname )
self.cursor = self.connection.cursor()
def try_query(self, query, args=()):
""" attempts to run a query, where
query is the query to be run, with '%s' statements where the values should be, and
args is a tuple of the values to go with the query"""
try:
if args == ():
self.cursor.execute(query)
else:
self.cursor.execute(query, args)
self.connection.commit()
except:
self.connection.rollback()
def add_unit(self, name, version, credits):
""" takes name, version, credits
name is the name of the unit paper
version is the unit version, and
credits is how many credits its worth"""
self.try_query("insert into dsfdf tbl_unit (unit_name, unit_version, unit_credits) values (%s,%s,%s)",(name,version,credits))
def close(self):
self.cursor.close()
self.connection.close()
blah = dbobject(#####################)
blah.add_unit( "thing", "something", 6)
for i in blah.cursor.messages:
print i
blah.close()
A:
Perhaps you can post the message(s) you receive.
mysql_insert_etc.py:22: Warning: Data
truncated for column 'val' at row 1
self.cursor.execute(query, args)
(,
('Warning', 1265L, "Data truncated for
column 'val' at row 1"))
From the above (manufactured error) it appears that MySQLdb returns:
the MySQL warning, and
its own exception.
Using the code below you can either suppress warnings, or have them raise exceptions.
Raise an exception (slightly modified from this example):
from warnings import catch_warnings, simplefilter
def try_query(self, query, args=()):
with catch_warnings():
simplefilter('error', MySQLdb.Warning)
try:
if args == ():
self.cursor.execute(query)
else:
self.cursor.execute(query, args)
self.connection.commit()
except MySQLdb.Error, e:
self.connection.rollback()
raise e
Suppress warnings (from here):
from warnings import filterwarnings
filterwarnings('ignore', category=MySQLdb.Warning)
| python mysqldb cursor messages list shows errors twice | For some reason whenever i run a query on the db cursor, it generates two errors in its .messages list, is this a feature?
here is the code that runs the query, all the application does is open a connection to the db, run this once with a forced error, read the .messages, then exit
import MySQLdb
class dbobject:
def __init__(self, dbhost, dbuser, dbpass, dbname):
self.connection = MySQLdb.connect( user=dbuser, passwd=dbpass, host=dbhost, db=dbname )
self.cursor = self.connection.cursor()
def try_query(self, query, args=()):
""" attempts to run a query, where
query is the query to be run, with '%s' statements where the values should be, and
args is a tuple of the values to go with the query"""
try:
if args == ():
self.cursor.execute(query)
else:
self.cursor.execute(query, args)
self.connection.commit()
except:
self.connection.rollback()
def add_unit(self, name, version, credits):
""" takes name, version, credits
name is the name of the unit paper
version is the unit version, and
credits is how many credits its worth"""
self.try_query("insert into dsfdf tbl_unit (unit_name, unit_version, unit_credits) values (%s,%s,%s)",(name,version,credits))
def close(self):
self.cursor.close()
self.connection.close()
blah = dbobject(#####################)
blah.add_unit( "thing", "something", 6)
for i in blah.cursor.messages:
print i
blah.close()
| [
"Perhaps you can post the message(s) you receive. \n\nmysql_insert_etc.py:22: Warning: Data\n truncated for column 'val' at row 1\n self.cursor.execute(query, args)\n (,\n ('Warning', 1265L, \"Data truncated for\n column 'val' at row 1\"))\n\nFrom the above (manufactured error) it appears that MySQLdb returns... | [
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003323918_mysql_python.txt |
Q:
Is Python's ctypes.c_long 64 bit on 64 bit systems?
In C, long is 64 bit on a 64 bit system. Is this reflected in Python's ctypes module?
A:
The size of long depends on the memory model. On Windows (LLP64) it is 32-bit, on UNIX (LP64) it is 64-bit.
If you need a 64-bit integer, use c_int64.
If you need a pointer-sized integer, use c_void_p (“The value is represented as integer”).
A:
Actually no.
On a Windows 64-bit system, long is 32 bits.
Python 3.1.2 (r312:79149, Mar 20 2010, 22:55:39) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> ctypes.c_long(2**31)
c_long(-2147483648)
>>> ctypes.c_long(2**31+1)
c_long(-2147483647)
>>> ctypes.c_long(2**31-1)
c_long(2147483647)
>>>
See What is the bit size of long on 64-bit Windows?
A:
If a C long is 64-bit (like it is on LP64 and ILP64 systems, pretty much any 64-bit system other than Windows), then so is ctypes.c_long. If a C long isn't 64-bit (like on LLP64 systems such as 64-bit Windows) then a ctypes.c_long isn't, either.
A:
Yes.
>>> ctypes.c_long(2**50)
c_long(1125899906842624)
>>> ctypes.c_long(2**64)
c_long(0)
>>> ctypes.c_long(2**63)
c_long(-9223372036854775808)
| Is Python's ctypes.c_long 64 bit on 64 bit systems? | In C, long is 64 bit on a 64 bit system. Is this reflected in Python's ctypes module?
| [
"The size of long depends on the memory model. On Windows (LLP64) it is 32-bit, on UNIX (LP64) it is 64-bit.\nIf you need a 64-bit integer, use c_int64. \nIf you need a pointer-sized integer, use c_void_p (“The value is represented as integer”).\n",
"Actually no.\nOn a Windows 64-bit system, long is 32 bits.\nPyt... | [
10,
4,
2,
1
] | [] | [] | [
"64_bit",
"ctypes",
"python"
] | stackoverflow_0003323778_64_bit_ctypes_python.txt |
Q:
python : tracking change in class to save it at the end
class A(object):
def __init__(self):
self.db = create_db_object()
def change_Db_a(self):
self.db.change_something()
self.db.save()
def change_db_b(self):
self.db.change_anotherthing()
self.db.save()
I am getting object from database, I changing it in multiple function and saving it back.
which is slow because it hits database on every function call. is there anything like deconstructor where I can save the database object so that I don't have to save it for every function call and not waste time.
A:
Don't rely on the __del__ method for saving your object. For details, see this blog post.
You can use use the context management protocol by defining __enter__ and __exit__ methods:
class A(object):
def __enter__(self):
print 'enter'
# create database object here (or in __init__)
pass
def __exit__(self, exc_type, exc_val, exc_tb):
print 'exit'
# save database object here
# other methods
Then use the with statement when you create your object:
with A() as myobj:
print 'inside with block'
myobj.do_something()
When you enter the with block, the A.__enter__ method will be called. When you exit the with block the __exit__ method will be called. For example, with the code above you should see the following output:
enter
inside with block
exit
Here's more information on the with statement:
Understanding Python's "with" statement
A:
You can define a del method.
def __del__(self):
self.db.save()
But note that this violates data consistency.
| python : tracking change in class to save it at the end | class A(object):
def __init__(self):
self.db = create_db_object()
def change_Db_a(self):
self.db.change_something()
self.db.save()
def change_db_b(self):
self.db.change_anotherthing()
self.db.save()
I am getting object from database, I changing it in multiple function and saving it back.
which is slow because it hits database on every function call. is there anything like deconstructor where I can save the database object so that I don't have to save it for every function call and not waste time.
| [
"Don't rely on the __del__ method for saving your object. For details, see this blog post.\nYou can use use the context management protocol by defining __enter__ and __exit__ methods:\nclass A(object):\n def __enter__(self):\n print 'enter'\n # create database object here (or in __init__)\n ... | [
3,
1
] | [] | [] | [
"class",
"object",
"python"
] | stackoverflow_0003324317_class_object_python.txt |
Q:
Perforce P4Python API Bug
I am compiling on Ubuntu 10.04 LTS. The Perforce Python API uses their C++ API for some of it. So, I point the setup.py at the C++'s API directory using the --apidir= they say to use. When it starts to compile the C++, I get a whole load of errors (temporary error list link is now gone). No one else has had these errors as far as I can tell. So, my question is, is it my idiocy, or Perforce's?
P.S. The reason I don't have the flag in the command is because I setup the setup.cfg file to point at the API.
A:
Woops! Forgot I still needed to install python-dev...
| Perforce P4Python API Bug | I am compiling on Ubuntu 10.04 LTS. The Perforce Python API uses their C++ API for some of it. So, I point the setup.py at the C++'s API directory using the --apidir= they say to use. When it starts to compile the C++, I get a whole load of errors (temporary error list link is now gone). No one else has had these errors as far as I can tell. So, my question is, is it my idiocy, or Perforce's?
P.S. The reason I don't have the flag in the command is because I setup the setup.cfg file to point at the API.
| [
"Woops! Forgot I still needed to install python-dev... \n"
] | [
0
] | [] | [] | [
"c++",
"perforce",
"python"
] | stackoverflow_0003324490_c++_perforce_python.txt |
Q:
Delaying execution of code?
I'm sorry if my title is a little unclear. Basically I want to print a '.' every second for five seconds then execute a chunk of code. Here is what I tried:
for iteration in range(5) :
timer = threading.Timer(1.0, print_dot)
timer.start()
#Code chunk
It seems as though that Timer starts its own thread for every instance, so the five timers all go off very close to each other plus the code chunk also executes too early.
A:
Use time.sleep().
http://docs.python.org/library/time.html#time.sleep
A:
Your example queues up 5 timers and starts them all (relatively) at once.
Instead, chain the timers. Pseudo-code (since I hardly know python):
iterationCount = 0
function execute_chained_print_dot:
if iterationCount < 5
iterationCount = iterationCount + 1
timer = threading.Timer(1.0, execute_chained_print_dot)
timer.start()
print_dot()
execute_chained_print_dot()
This assumes that the python Timer class only fires the print_dot method once. If it doesn't do this, and repeatedly fires print_dot until it is stopped, then do this instead:
iterationCount = 0
timer = threading.Timer(1.0, execute_print_dot_until_finished)
timer.start()
function execute_print_dot_until_finished:
if iterationCount < 5
iterationCount = iterationCount + 1
print_dot()
else
timer.stop()
Disclaimer: I will not be held responsible for any off-by-one errors in this code ;)
| Delaying execution of code? | I'm sorry if my title is a little unclear. Basically I want to print a '.' every second for five seconds then execute a chunk of code. Here is what I tried:
for iteration in range(5) :
timer = threading.Timer(1.0, print_dot)
timer.start()
#Code chunk
It seems as though that Timer starts its own thread for every instance, so the five timers all go off very close to each other plus the code chunk also executes too early.
| [
"Use time.sleep().\nhttp://docs.python.org/library/time.html#time.sleep\n",
"Your example queues up 5 timers and starts them all (relatively) at once.\nInstead, chain the timers. Pseudo-code (since I hardly know python):\niterationCount = 0\nfunction execute_chained_print_dot:\n if iterationCount < 5\n itera... | [
3,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0003324604_multithreading_python.txt |
Q:
How to unique a dict by value?
I want to unique duplicate values in a dict. It looks like this:
d = {
"a":1,
"b":2,
"c":2,
"d":3,
"e":4,
"f":5,
"g":1,
"h":2,
"i":2,
"j":1,
"k":1}
Here is what I did:
# sort and unique the dict values
obj = d.values()
K = []
K = sorted(list(zip(*[(x,K.append(x)) for x in obj if not x in K])[0]
V=[]
for v1 in L:
V.append([k for k, v in obj.iteritems() if v == v1][0])
d_out = dict(zip(K, V))
1.
So, will the K,V be in a right order?
Also, it may a bit complex, can anyone give a simple solution to unique a dict by it's values?
2.
Can the following be more simple?
for v1 in L:
V.append([k for k, v in obj.iteritems() if v == v1][0])
This is not working on my testing:
[V.append([k for k, v in obj.iteritems() if v == v1][0]) for v1 in L]
3.
I realized I may use the swap key value to achieve that (unique a dict by its value), but I have no idea how to select the key when swap caused a key conflict with this:
dict((value, key) for key, value in my_dict.iteritems())
I know if swap it again the value will be unique, however, this just overwrites the key when a key conflict happens, giving no chance to make a selection. I feel confused why this gives no key conflict error? And can I do something to select the key beside the ugly way overwrite the new dict's key later?
4.
I searched and find some "None" values for python dict are well discussed, anyone can give me a sample what it is used for and what it will impacted in using python dict?
A:
A dict is not a sequence. There is no ordering.
You need a simpler overall approach.
A dict does not give a "key conflict error". It assumes that you want to overwrite the old value with the new value.
I don't understand what you're asking here.
The solution below is a more straightforward way of removing dupe values from a dictionary. Adjust either the sort or the insertion loop to control which keys should appear in the final dict.
d = {
"a":1,
"b":2,
"c":2,
"d":3,
"e":4,
"f":5,
"g":1,
"h":2,
"i":2,
"j":1,
"k":1}
# Extract the dictionary into a list of (key, value) tuples.
t = [(k, d[k]) for k in d]
# Sort the list -- by default it will sort by the key since it is
# first in the tuple.
t.sort()
# Reset the dictionary so it is ready to hold the new dataset.
d = {}
# Load key-values into the dictionary. Only the first value will be
# stored.
for k, v in t:
if v in d.values():
continue
d[k] = v
print d
A:
try it out:
from collections import defaultdict
dout = defaultdict(dict)
for k,v in d.iteritems():
dout[v] = k
dout = dict(dout)
fdict = dict(zip(dout.values(), dout.keys()))
N.B: dictionary don't have duplicate key so input dictionary has no duplicate key
hopefully it will works
A:
Maybe this is of some help:
import collections
d = ... # like above
d1 = collections.defaultdict(list)
for k, v in d.iteritems():
d1[v].append(k)
print d1
| How to unique a dict by value? | I want to unique duplicate values in a dict. It looks like this:
d = {
"a":1,
"b":2,
"c":2,
"d":3,
"e":4,
"f":5,
"g":1,
"h":2,
"i":2,
"j":1,
"k":1}
Here is what I did:
# sort and unique the dict values
obj = d.values()
K = []
K = sorted(list(zip(*[(x,K.append(x)) for x in obj if not x in K])[0]
V=[]
for v1 in L:
V.append([k for k, v in obj.iteritems() if v == v1][0])
d_out = dict(zip(K, V))
1.
So, will the K,V be in a right order?
Also, it may a bit complex, can anyone give a simple solution to unique a dict by it's values?
2.
Can the following be more simple?
for v1 in L:
V.append([k for k, v in obj.iteritems() if v == v1][0])
This is not working on my testing:
[V.append([k for k, v in obj.iteritems() if v == v1][0]) for v1 in L]
3.
I realized I may use the swap key value to achieve that (unique a dict by its value), but I have no idea how to select the key when swap caused a key conflict with this:
dict((value, key) for key, value in my_dict.iteritems())
I know if swap it again the value will be unique, however, this just overwrites the key when a key conflict happens, giving no chance to make a selection. I feel confused why this gives no key conflict error? And can I do something to select the key beside the ugly way overwrite the new dict's key later?
4.
I searched and find some "None" values for python dict are well discussed, anyone can give me a sample what it is used for and what it will impacted in using python dict?
| [
"\nA dict is not a sequence. There is no ordering.\nYou need a simpler overall approach.\nA dict does not give a \"key conflict error\". It assumes that you want to overwrite the old value with the new value.\nI don't understand what you're asking here.\n\nThe solution below is a more straightforward way of removin... | [
3,
2,
1
] | [] | [] | [
"dictionary",
"duplicates",
"python",
"unique"
] | stackoverflow_0003253716_dictionary_duplicates_python_unique.txt |
Q:
in django how do I create a queryset to find double barrel names?
In django, I have a table of people, each of which has a namefirst and namelast.
I want to do the sql:
select * from names where left(namefirst,1)=left(namelast,1).
Right now my best effort is
qs=People.objects.extra(select={'db':'select left(namefirst,1)=left(namelast,1)'})
but then if i stick a .filter(db=1) on that it generates an error.
I suppose I could order by db and just cut it off, but I know there is a better way to do this.
A:
Your extra parameter doesn't look right. You should be using the where parameter (not select):
People.objects.extra(where=['left(namefirst,1)=left(namelast,1)'])
| in django how do I create a queryset to find double barrel names? | In django, I have a table of people, each of which has a namefirst and namelast.
I want to do the sql:
select * from names where left(namefirst,1)=left(namelast,1).
Right now my best effort is
qs=People.objects.extra(select={'db':'select left(namefirst,1)=left(namelast,1)'})
but then if i stick a .filter(db=1) on that it generates an error.
I suppose I could order by db and just cut it off, but I know there is a better way to do this.
| [
"Your extra parameter doesn't look right. You should be using the where parameter (not select):\nPeople.objects.extra(where=['left(namefirst,1)=left(namelast,1)'])\n\n"
] | [
0
] | [] | [] | [
"django",
"django_models",
"django_queryset",
"python"
] | stackoverflow_0003324733_django_django_models_django_queryset_python.txt |
Q:
XML reading using ElementTree
I have one xml file.
<Item>Item value</Item>
<Itemdate>24/07/2010</Itemdate>
<Total>1</Total>
<Itemcategory>Income</Itemcategory>
<GroupName>Salary</GroupName>
<EditId>undefined</EditId>
<Item>Item value</Item>
<Itemdate>24/07/2010</Itemdate>
<Total>1</Total>
<Itemcategory>Income</Itemcategory>
<GroupName>Salary</GroupName>
<EditId>undefined</EditId>
<Item>Item value</Item>
<Itemdate>24/07/2010</Itemdate>
<Total>1</Total>
<Itemcategory>Income</Itemcategory>
<GroupName>Trfr fm Savings</GroupName>
<EditId>undefined</EditId>
<Item>Item value</Item>
<Itemdate>24/07/2010</Itemdate>
<Total>1</Total>
<Itemcategory>Income</Itemcategory>
<GroupName>Dividend</GroupName>
<EditId>undefined</EditId>
<Item>Item value</Item>
<Itemdate>24/07/2010</Itemdate>
<Total>1</Total>
<Itemcategory>Income</Itemcategory>
<GroupName>Dividend</GroupName>
<EditId>undefined</EditId>
Now i want to get the all item,itemdate, etc are seperately using elementtree. Any one can help me?
Rgds,
Nimmy
A:
As sje397 wrote in the comment, you should restructure it if you have an option. Either put it all into item tags:
<item>
<value>...</value>
<date>...</date>
...
</item>
Or using attributes:
<item value="..." date="..." ... />
Those are largely equivalent (attributes an appear in any order though, while tags can be forced into a certain order via Schema/DTD) with the exception that you have to and I think it's a matter of taste. Of course you can mix the two, but that will complicate extracting the information (as you'll need to use seperate methods to get attributes vs tags). Either way, you just get one item tag and then get all its [children|attributes].
If the xml absolutely has to stay this way, you might want to look into SAX parsers, which inherently preserve the order of the tags. It requires an event-based approach though.
| XML reading using ElementTree | I have one xml file.
<Item>Item value</Item>
<Itemdate>24/07/2010</Itemdate>
<Total>1</Total>
<Itemcategory>Income</Itemcategory>
<GroupName>Salary</GroupName>
<EditId>undefined</EditId>
<Item>Item value</Item>
<Itemdate>24/07/2010</Itemdate>
<Total>1</Total>
<Itemcategory>Income</Itemcategory>
<GroupName>Salary</GroupName>
<EditId>undefined</EditId>
<Item>Item value</Item>
<Itemdate>24/07/2010</Itemdate>
<Total>1</Total>
<Itemcategory>Income</Itemcategory>
<GroupName>Trfr fm Savings</GroupName>
<EditId>undefined</EditId>
<Item>Item value</Item>
<Itemdate>24/07/2010</Itemdate>
<Total>1</Total>
<Itemcategory>Income</Itemcategory>
<GroupName>Dividend</GroupName>
<EditId>undefined</EditId>
<Item>Item value</Item>
<Itemdate>24/07/2010</Itemdate>
<Total>1</Total>
<Itemcategory>Income</Itemcategory>
<GroupName>Dividend</GroupName>
<EditId>undefined</EditId>
Now i want to get the all item,itemdate, etc are seperately using elementtree. Any one can help me?
Rgds,
Nimmy
| [
"As sje397 wrote in the comment, you should restructure it if you have an option. Either put it all into item tags:\n<item>\n <value>...</value>\n <date>...</date>\n ...\n</item>\n\nOr using attributes:\n<item value=\"...\" date=\"...\" ... />\n\nThose are largely equivalent (attributes an appear in any or... | [
5
] | [] | [] | [
"elementtree",
"python"
] | stackoverflow_0003324665_elementtree_python.txt |
Q:
XML GUI in Python
I'm working on a project where someone wrote a PyGTK GUI that uses docks from GDL. He has the GUI saved as an XML file:
<?xml version="1.0"?>
<interface>
<requires lib="gtk+" version="2.16"/>
<object class="GtkUIManager" id="uimanager"/>
<object class="GtkWindow" id="mainWindow">
<property name="title" translatable="yes">Title</property>
...
The code calls
self.dock_layout.load_from_file("gui_layout.xml")
I need to remove the GDL dependency. Can I still use the XML layout? If so, how?
A:
This seems to be a GtkBuilder file. You can use it, e.g.
builder = gtk.Builder()
builder.add_from_file("gui_layout.xml")
window = builder.get_object("mainWindow")
| XML GUI in Python | I'm working on a project where someone wrote a PyGTK GUI that uses docks from GDL. He has the GUI saved as an XML file:
<?xml version="1.0"?>
<interface>
<requires lib="gtk+" version="2.16"/>
<object class="GtkUIManager" id="uimanager"/>
<object class="GtkWindow" id="mainWindow">
<property name="title" translatable="yes">Title</property>
...
The code calls
self.dock_layout.load_from_file("gui_layout.xml")
I need to remove the GDL dependency. Can I still use the XML layout? If so, how?
| [
"This seems to be a GtkBuilder file. You can use it, e.g.\nbuilder = gtk.Builder()\nbuilder.add_from_file(\"gui_layout.xml\")\n\nwindow = builder.get_object(\"mainWindow\")\n\n"
] | [
0
] | [] | [] | [
"dock",
"gtk",
"python"
] | stackoverflow_0003302676_dock_gtk_python.txt |
Q:
Django manytomany, imageField and upload_to
I have the two models shown below:
class EntryImage(models.Model):
image = models.ImageField(upload_to="entries")
class Entry(models.Model):
code = models.CharField(max_length=70, unique=True)
images = models.ManyToManyField(EntryImage, null=True, blank=True)
As you can see, Entry can have 0 or more images.
My question is: Is it possible to have that kind of
schema and dynamically change the upload_to based on the Entry code?
A:
Well without going too far off, you could make an intermediary M2M table EntryImageDir with the directory name in it. You would link your EntryImages there with a foreign key and you could create the EntryImageDir either with a signal on Entry create or when uploading something.
The documentation for M2M with custom fields is here:
http://www.djangoproject.com/documentation/models/m2m_intermediary/
A:
You can make upload_to a callable, in which case it will be called and passed the instance of the model it is on. However, this may not have been saved yet, in which case you may not be able to query the Entry code.
| Django manytomany, imageField and upload_to | I have the two models shown below:
class EntryImage(models.Model):
image = models.ImageField(upload_to="entries")
class Entry(models.Model):
code = models.CharField(max_length=70, unique=True)
images = models.ManyToManyField(EntryImage, null=True, blank=True)
As you can see, Entry can have 0 or more images.
My question is: Is it possible to have that kind of
schema and dynamically change the upload_to based on the Entry code?
| [
"Well without going too far off, you could make an intermediary M2M table EntryImageDir with the directory name in it. You would link your EntryImages there with a foreign key and you could create the EntryImageDir either with a signal on Entry create or when uploading something.\nThe documentation for M2M with cus... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002647065_django_python.txt |
Q:
Which technology should I use to develop a high performance web application
I have couple of ideas in my brain which I would like to bring out before it's too late. Basically I want to develop a web application which I could sell it to clients. So which technology shall I use to accomplish this? I have been a C and C++ software developer but it's been a very long time since I have developed one. So the things I would like to know is:
Scalability and Performance?
Easy way to develop web application in a faster manner?
Any Framework?
Application server?
and which programming language?
A:
Usually the programming language doesn't really matter. All have their own strengths and weaknesses. All come up with their own best-practices and frameworks.
It's really up to you what's your preference. If you are coming from Microsoft C/C++ I'd use .NET, if you are from Linux world I'd use Java.
Back in the 90s Java was well known as a slow framework, however there was much of myth and the framework architecture is dramatically changed since that. Today, there is no generally slow or fast framework.
You can find thousands of sites in the web that tell you that the one or the other is faster. However, at the end of the day it depends on how you implemented your solution and how you utilized the best features of the framework.
Greets
Flo
A:
Build with:
C#, you'll love it (I'm also an old C++ developer)
ASP.Net MVC (Validation, caching, Spark view engine)
Any ORM having a cache layer (I prefer nhibernate)
Database with lots of allocated memory
A:
I would suggest using C++ with CPPCMS as it's becoming stable and is precisely targeted at high performance web applications.
See if the rationale match your goals.
A:
I kinda think this is almost more like a religious problem, than a real technical issue. For almost every programming language you can find a big website that's using it.
.NET -> Microsoft
Ruby -> Twitter (yes, they have a few issues, but still)
PHP -> Facebook
Java -> Lots of finance companies
Don't know about Phyton, but I'm sure there is.
More important is a good scalable architecture. That is where Twitter kinda screwed it up it seems.
Personally I use ASP.NET. Works fine, is somewhat easy and has a nice IDE. And the market is not so fragmented. Before I used Java with Websphere. Was running on a Sergenti Sun Box, so could definitely handle a lot.
I would more see into what you can get yourself into the quickest. If you know C++ C# or Java are easy to learn.
A:
You should take a look at ASP.NET.
Using ASP.NET has got a lot of advantages, and it is very performant. Here you've got a short list of some advantages:
ASP.NET drastically reduces the amount of code required to build large applications.
With built-in Windows authentication and per-application
configuration, your applications are
safe and secured.
It provides better performance by taking advantage of early binding,
just-in-time compilation, native
optimization, and caching services
right out of the box.
The ASP.NET framework is complemented by a rich toolbox and
designer in the Visual Studio
integrated development environment.
WYSIWYG editing, drag-and-drop server
controls, and automatic deployment are
just a few of the features this
powerful tool provides.
Provides simplicity as ASP.NET makes it easy to perform common tasks,
from simple form submission and client
authentication to deployment and site
configuration.
The source code and HTML are together therefore ASP.NET pages are
easy to maintain and write. Also the
source code is executed on the server.
This provides a lot of power and
flexibility to the web pages.
All the processes are closely monitored and managed by the ASP.NET
runtime, so that if process is dead, a
new process can be created in its
place, which helps keep your
application constantly available to
handle requests.
It is purely server-side technology so, ASP.NET code executes on the
server before it is sent to the
browser.
Being language-independent, it allows you to choose the language that
best applies to your application or
partition your application across many
languages.
ASP.NET makes for easy deployment. There is no need to register
components because the configuration
information is built-in.
| Which technology should I use to develop a high performance web application | I have couple of ideas in my brain which I would like to bring out before it's too late. Basically I want to develop a web application which I could sell it to clients. So which technology shall I use to accomplish this? I have been a C and C++ software developer but it's been a very long time since I have developed one. So the things I would like to know is:
Scalability and Performance?
Easy way to develop web application in a faster manner?
Any Framework?
Application server?
and which programming language?
| [
"Usually the programming language doesn't really matter. All have their own strengths and weaknesses. All come up with their own best-practices and frameworks.\nIt's really up to you what's your preference. If you are coming from Microsoft C/C++ I'd use .NET, if you are from Linux world I'd use Java.\nBack in the ... | [
6,
3,
3,
1,
0
] | [] | [] | [
"c#",
"java",
"python"
] | stackoverflow_0003324683_c#_java_python.txt |
Q:
Declaring members only in constructor
I'm coming from a C++ background to python
I have been declaring member variables and setting them in a C++esqe way like so:
class MyClass:
my_member = []
def __init__(self,arg_my_member):
self.my_member = arg_my_member
Then I noticed in some open source code, that the initial declaration my_member = [] was completely left out and only created in the constructor.
Which obviously is possible as python is dynamic.
My question is, is this the preferred or Pythonic way of doing things, and are there and pros and cons of either?
A:
The way you are doing it means that you'll now have a "static" member and a "non-static" member of the same name.
class MyClass:
my_member = []
def __init__(self, arg_my_member):
self.my_member = arg_my_member
>>> a = MyClass(42)
>>> print a.my_member
42
>>> print MyClass.my_member
[]
A:
If you define it inside the class then it is a class variable and if you define it inside the constructor it is an object variable.
So if you don't define it inside the constructor ALL instances of the class share the same class variable.
A:
Both ways are acceptable for python, except in case of mutable values. When you declare it like in your example, you can get very unexpected result:
>>> class MyClass:
... my_member = []
...
>>> A = MyClass()
>>> B = MyClass()
>>> A.my_member.append(1)
>>> A.my_member
[1]
>>> B.my_member.append(2)
>>> B.my_member
[1, 2]
>>> A.my_member
[1, 2]
>>> MyClass.my_member
[1, 2]
Since class members are generated only once, when class itself is being processed at module load. If your member is intended to be used in instance scope, you should set it in __init__
Immutable values are fine tho.
A:
This creates a class attribute called my_member
class MyClass:
my_member = []
If the instances did not have an instance variable called my_member, all the instances would have access to the same list via self.my_member.
Since you are creating an instance variable called my_member it is quite likely that the class variable is never used and is just a sign of confusion
| Declaring members only in constructor | I'm coming from a C++ background to python
I have been declaring member variables and setting them in a C++esqe way like so:
class MyClass:
my_member = []
def __init__(self,arg_my_member):
self.my_member = arg_my_member
Then I noticed in some open source code, that the initial declaration my_member = [] was completely left out and only created in the constructor.
Which obviously is possible as python is dynamic.
My question is, is this the preferred or Pythonic way of doing things, and are there and pros and cons of either?
| [
"The way you are doing it means that you'll now have a \"static\" member and a \"non-static\" member of the same name.\nclass MyClass:\n my_member = []\n\n def __init__(self, arg_my_member):\n self.my_member = arg_my_member\n\n\n>>> a = MyClass(42)\n>>> print a.my_member\n42\n>>> print MyClass.my_membe... | [
9,
4,
1,
0
] | [] | [] | [
"constructor",
"member",
"python"
] | stackoverflow_0003324697_constructor_member_python.txt |
Q:
python file copying
Is there any difference in speed of copying files from one location to another betwen python or delphi or c++ ?
I guess that all 3 laguages uses same or similar win api calls and that there is not much performance difference.
A:
Pythons shutil module does not use the Windows API, but instead uses an open/read/write loop. This may or may not be slower than using CopyFile(Ex). Please measure it, everything else is just guessing.
| python file copying | Is there any difference in speed of copying files from one location to another betwen python or delphi or c++ ?
I guess that all 3 laguages uses same or similar win api calls and that there is not much performance difference.
| [
"Pythons shutil module does not use the Windows API, but instead uses an open/read/write loop. This may or may not be slower than using CopyFile(Ex). Please measure it, everything else is just guessing.\n"
] | [
1
] | [] | [] | [
"comparison",
"performance",
"python",
"windows"
] | stackoverflow_0003324870_comparison_performance_python_windows.txt |
Q:
PHP devs that moved to Python, is the experience better?
I'm planning on moving to Python and I have a couple of additional questions along with the title:
did you have more fun with python?
are you as productive as when you're using PHP?
what made you change to python?
Would you do a project again in PHP? If so, why?
Your answers would really be useful for us PHP devs wanting something more I guess :)
Thanks in advance!
A:
I was a PHP dev for about 5 years before switching to Python almost exclusively a year ago. The experience has been a mostly positive one; I'll answer your questions but also list a few gotchas I ran into.
Definitely. I continually find surprisingly powerful features/expressions in Python that do a great deal in a small amount of code (yet still being more readable than Perl).
Far more productive. It might just be my style, but Python's functional programming tools, generator expressions, list comprehensions, etc. allow me to accomplish tasks correctly with less code and less time invested than PHP.
I had an analytics project that needed a powerful stats package, so I went with Python+numpy. Then I found Turbogears and loved the syntax. Eventually I discovered coroutines and cooperative multitasking, and there's no going back. I use bottle, gevent, and gunicorn to crank out lean, fast, scalable web apps in record time.
Not if I could help it. PHP's verbose "everything is a long-named function call" syntax is just hard on my eyes at this point. I find it tedious to optimize as well (every page load reinterprets the source code in a default configuration).
Here are a few of the gotchas to be aware of:
For cheap, low-traffic sites, it's much harder to find a web host with a good python environment.
Apache isn't really a typical setup for Python in my experience. Python webapps are usually daemons that are exposed to the public with a reverse proxy webserver in front (nginx is very common). A number of corporate environments balk at new-fangled technology like nginx. It also takes some adjustment to think about your webapps as daemons, and it can take some effort at first to get your daemonizing correct and consistent.
If you use mysql, you will have some pain switching for a while. There just isn't a Python mysql library that is highly compatible with PHP-style mysql queries. For example, most of them don't use the simple "?" syntax for parameterized queries, so you can't just paste your queries over (you have to use printf-style "%s", etc.). Also, just the fact that you actually have to choose and install a mysql library is an extra step over PHP. This no longer bothers me, since I don't use mysql anymore anyway.
This is a broad topic with much, much more to say, but I hope this was helpful.
A:
I'll try my best to answer your questions as best I can:
Did you have more fun with python?
I really enjoy how minimalist python is, having modules with non-redundant naming conventions is really nice. I found this to be especially convenient when reading/debugging other peoples code.
I also love all of the python tricks to do some very elegant things in a single line of code such as list comprehensions and the itertools library.
I tend to develop my applications using mod_wsgi and it took some time to wrap my head around writing thread-safe web applications, but it was really worth it.
I also find unicode to be much less frustrating with python especially with python 3k.
are you as productive as when you're using PHP?
For simple websites python can be less fun to setup and use. One nice feature of PHP that I miss with python is mixing PHP and HTML in the same file. Python has a lot of nice template languages that make this easy as well, but they have to be installed.
what made you change to python?
I became frustrated with a lot of the little nuances of PHP such as strange integer and string conversions and so forth. I also started to feel that PHP was getting very bloated with a lot of methods with inconsistent naming schemes. I was referring to the PHP documentation quite frequently despite having a large portion of the php library memorized.
Would you do a project again in PHP? If so, why?
I would develop a PHP project again, it has a lot of nice features and a great community. Plus I have a lot of experience with PHP. I'd prefer to use python, but if the client wants PHP I'm not going to force something they don't want.
A:
Well, I started with PHP, and have delved into Python recently. I wouldn't say that I've "moved to", but I do use both (still PHP more, but a fair bit of Python as well).
I wouldn't say that I have more "fun" with Python. There are a lot of really cool and easy things that I really wish I could take to PHP. So I guess it could be considered "fun". But I still enjoy PHP, so...
I'm more productive with PHP. I know PHP inside and out. I know most of the little nuances involved in writing effective PHP code. I don't know Python that well (I've maybe written 5k lines of Python)... I know enough to do what I need to, but not nearly as in-depth as PHP.
I wanted to try something new. I never liked Python, but then one day I decided to learn the basics, and that changed my views on it. Now I really like some parts (and can see how it influences what PHP I write)...
I am still doing PHP projects. It's my best language. And IMHO it's better than Python at some web tasks (like high traffic sites). PHP has a built in multi-threaded FastCGI listener. Python you need to find one (there are a bunch out there). But in my benchmarks, Python was never able to get anywhere near as as fast as PHP with FastCGI (The best Py performed it was 25% slower than PHP. The worst was several hundered times, depending on the FCGI library). But that's based on my experience (which admittedly isn't much). I know PHP, so I feel more comfortable committing a large site to it than I would PY...
A:
I run a self-developed private social site for 100+ users. Python was absolutely fantastic for making and running this.
did you have more fun with python?
Most definitely.
are you as productive as when you're using PHP?
Mostly yes. Python coding style, at least for me is so much quicker and easier. But python does sometimes lack in included libraries and documentation over PHP. (But PHP seems second to none in that reguard). Also requires a tad more to get running under apache.
what made you change to python?
Easier to manage code, and quicker development (A good IDE helps there, I use WingIDE for python), as well as improving my python skills for when I switch to non-web based projects.
Would you do a project again in PHP? If so, why?
Perhaps if I were working on a large scale professional project. PHP is so ubiquitous on the web A company would have a much easier time finding a replacement PHP programmer.
A:
Last year I switched job to get away from PHP and work in Python. I'm very much satisfied with the decision I made :)
To answer the individual questions:
did you have more fun with python?
Yes!
are you as productive as when you're using PHP?
More productive I'd say. But the overall increased experience in programming also had something to with that.
what made you change to python?
You are not expected to be a jack of all trades in non-PHP jobs. (Photoshop/Web Design/Flash is required for many PHP jobs, and I hate Flash). And I liked Python/Django a lot.
4. Would you do a project again in PHP? If so, why?
If it's small stuff that's better done without any framework, then yes.
A:
yes
yes
curiosity, search for better languages, etc. (actually, I learned them somewhat in parallel many years ago)
yes, if a project requires it explicitly
disclaimer: I never really moved from php.
A:
I've never really worked with PHP (nothing major) and come from the .NET world. The project I am currently on requires a lot of Python work and I must say I love it. Very easy and "cool" language, ie. FUN!
.NET will always be my wife but Python is my mistress ;)
A:
did you have more fun with python?
Yes. Lot more.
are you as productive as when you're using PHP?
No. I think more.
what made you change to python?
Django.
Would you do a project again in PHP? If so, why?
Only if it is required.
| PHP devs that moved to Python, is the experience better? | I'm planning on moving to Python and I have a couple of additional questions along with the title:
did you have more fun with python?
are you as productive as when you're using PHP?
what made you change to python?
Would you do a project again in PHP? If so, why?
Your answers would really be useful for us PHP devs wanting something more I guess :)
Thanks in advance!
| [
"I was a PHP dev for about 5 years before switching to Python almost exclusively a year ago. The experience has been a mostly positive one; I'll answer your questions but also list a few gotchas I ran into.\n\nDefinitely. I continually find surprisingly powerful features/expressions in Python that do a great deal i... | [
19,
4,
3,
3,
2,
1,
1,
1
] | [] | [] | [
"php",
"python"
] | stackoverflow_0003319261_php_python.txt |
Q:
Bug in third-party dependency creates python packaging dilemma
I'm a developer on a software project for Linux that uses Python and PyGTK. The program we are writing depends on a number of third-party packages that are available through all mayor distro repositories. One of these is a python binding (written in C) that allows our program to chat with a common C library. Unfortunately, there's a bug in the bindings that affects our program a great deal. A fix/patch was recently presented, but hasn't been committed yet. We want to include this fix as soon as possible, but are unsure that the best course of action would be.
Based on the scenario I described, we figured we have the following options. Hopefully someone can give more insight or maybe point us to a solution we haven't considered yet
Wait for the python bindings to be updated. The problem with this is that we have no way of knowing when the update would be accepted into distribution repositories, or even if it will be backported to earlier releases.
Include a modified version of the python bindings including the fix with our program and have users compile it on installation. This would provide a burden for packagers as every version of every distribution would link against another version of the C library.
Rewrite our program in C++ and avoid dealing with python bindings all together. Yep, actually considering this hehe.
Keep the ugly hack we have in place intact. Not preferable obviously as it is, well, an ugly hack
Thanks in advance!
A:
As long as the ugly hack works, use it. It will have drawbacks local to your package. Additionally, you can phase it out (significantly) later by requiring a bug-free version of your dependency, when it is released and is available for some time so that distros have a chance to start shipping it.
| Bug in third-party dependency creates python packaging dilemma | I'm a developer on a software project for Linux that uses Python and PyGTK. The program we are writing depends on a number of third-party packages that are available through all mayor distro repositories. One of these is a python binding (written in C) that allows our program to chat with a common C library. Unfortunately, there's a bug in the bindings that affects our program a great deal. A fix/patch was recently presented, but hasn't been committed yet. We want to include this fix as soon as possible, but are unsure that the best course of action would be.
Based on the scenario I described, we figured we have the following options. Hopefully someone can give more insight or maybe point us to a solution we haven't considered yet
Wait for the python bindings to be updated. The problem with this is that we have no way of knowing when the update would be accepted into distribution repositories, or even if it will be backported to earlier releases.
Include a modified version of the python bindings including the fix with our program and have users compile it on installation. This would provide a burden for packagers as every version of every distribution would link against another version of the C library.
Rewrite our program in C++ and avoid dealing with python bindings all together. Yep, actually considering this hehe.
Keep the ugly hack we have in place intact. Not preferable obviously as it is, well, an ugly hack
Thanks in advance!
| [
"As long as the ugly hack works, use it. It will have drawbacks local to your package. Additionally, you can phase it out (significantly) later by requiring a bug-free version of your dependency, when it is released and is available for some time so that distros have a chance to start shipping it.\n"
] | [
3
] | [] | [] | [
"linux",
"packaging",
"python",
"repository"
] | stackoverflow_0003325161_linux_packaging_python_repository.txt |
Q:
What are some good free parsing programs?
Are there any good free parsing programs out there in Python or Java?
I have been using a lot of textfiles recently and they are all different. I have been spending a lot of time writing code to parse these textfiles. I was wondering if there is some program that could get all the names of a person out of a textfile or parse the file based on a keyword.
A:
Pyparsing is a good Python add-on module for plain text. Easy to get something going quickly, but has enough supporting components to do some pretty elaborate parsing work. See http://pyparsing.wikispaces.com, and check out the Examples page. (Plus it is very liberally licensed, so there are no restrictions or runtime encumberances.)
A:
ANTLR is pretty popular and even has an IDE to help you develop / test your grammars.
A:
Take a look at JavaCC.
From the JavaCC FAQ:
JavaCC stands for "the Java Compiler
Compiler"; it is a parser generator
and lexical analyzer generator. JavaCC
will read a description of a language
and generate code, written in Java,
that will read and analyze that
language. JavaCC is particularly
useful when you have to write code to
deal with an input language has a
complex structure
A:
I think you are looking for something like Apache Lucene.
Check this: http://lucene.apache.org/java/docs/index.html
A:
It depends on what you need to parse.
If you need to solve a particular problem domain then the best way is to create a domain-specific language and parse it in Groovy.
A:
If the text has a known format, a grammar parser might be your best bet.
Gold Parser is open source and has both Java and Python support, among others.
A:
Lepl is a general-purpose, recursive descent parser for Python that I maintain.
It's similar to pyparsing, in that both are parsers that you write directly in Python. Here's an example that parses and evaluates an arithmetic expression:
>>> from operator import add, sub, mul, truediv
>>> # ast nodes
... class Op(List):
... def __float__(self):
... return self._op(float(self[0]), float(self[1]))
...
>>> class Add(Op): _op = add
...
>>> class Sub(Op): _op = sub
...
>>> class Mul(Op): _op = mul
...
>>> class Div(Op): _op = truediv
...
>>> # tokens
>>> value = Token(UnsignedFloat())
>>> symbol = Token('[^0-9a-zA-Z \t\r\n]')
>>> number = Optional(symbol('-')) + value >> float
>>> group2, group3 = Delayed(), Delayed()
>>> # first layer, most tightly grouped, is parens and numbers
... parens = ~symbol('(') & group3 & ~symbol(')')
>>> group1 = parens | number
>>> # second layer, next most tightly grouped, is multiplication
... mul_ = group1 & ~symbol('*') & group2 > Mul
>>> div_ = group1 & ~symbol('/') & group2 > Div
>>> group2 += mul_ | div_ | group1
>>> # third layer, least tightly grouped, is addition
... add_ = group2 & ~symbol('+') & group3 > Add
>>> sub_ = group2 & ~symbol('-') & group3 > Sub
>>> group3 += add_ | sub_ | group2
... ast = group3.parse('1+2*(3-4)+5/6+7')[0]
>>> print(ast)
Add
+- 1.0
`- Add
+- Mul
| +- 2.0
| `- Sub
| +- 3.0
| `- 4.0
`- Add
+- Div
| +- 5.0
| `- 6.0
`- 7.0
>>> float(ast)
6.833333333333333
>>> 1+2*(3-4)+5/6+7
6.833333333333333
The main advantages of Lepl over pyparsing are that it's slightly more powerful (it can compile itself to regular expressions in places for speed, handle left recursive grammars, uses trampolining to avoid running out of stack space). The main disadvantages are that it's younger than pyparsing, so doesn't have the same number of users or as large and supportive a community.
| What are some good free parsing programs? | Are there any good free parsing programs out there in Python or Java?
I have been using a lot of textfiles recently and they are all different. I have been spending a lot of time writing code to parse these textfiles. I was wondering if there is some program that could get all the names of a person out of a textfile or parse the file based on a keyword.
| [
"Pyparsing is a good Python add-on module for plain text. Easy to get something going quickly, but has enough supporting components to do some pretty elaborate parsing work. See http://pyparsing.wikispaces.com, and check out the Examples page. (Plus it is very liberally licensed, so there are no restrictions or ... | [
4,
3,
1,
1,
0,
0,
0
] | [] | [] | [
"java",
"parsing",
"python"
] | stackoverflow_0003320161_java_parsing_python.txt |
Q:
Stoping generator in first answer, use return instead
I am using too much to my taste the pattern (after every possible solution branch of the search). This is the code to find boggle words in given square. It had a bug if the words are not preselected to include only those whose letter pairs are neighbours, which I fixed now by changing comparrision not pos to pos is None.
def word_path(word,used=[],pos=None):
if not word:
yield False
return
else:
correct_neighbour = [neigh for p,neigh in neighbour_set
if (not pos or pos==p) and (neigh not in used) and boggle[neigh]==word[0] ]
for i in correct_neighbour:
used_copy=used[:]+[i]
if boggle[i]==word:
yield used_copy
return
else:
for solution in word_path(word[1:],used_copy,pos=i) or (False,):
if solution:
yield solution
return
Is there any better alternative to make generator which stops after any answer was found?
Solution based on why not use return
Finally it got me and returned sequence is iterator no matter that it was returned not yielded value. so I changed my word_path code to use return and cleaned up the expressions generally. Instead of giving None or False the function returns (False,). Then I have not problem with None not accepted for for statement.
def word_path(word,used=[],pos=None):
if word:
correct_neighbour = [neigh
for p,neigh in neighbour_set
if ((pos is None or pos==p) and
(neigh not in used) and
boggle[neigh]==word[0]
)
]
for i in correct_neighbour:
used_copy=used[:]+[i]
if len(word)==1:
if boggle[i]==word:
return (used_copy,)
else:
for solution in word_path(word[1:],used_copy,pos=i):
if solution:
return (solution,)
return (False,)
A:
Why do you make it a generator in the first place when you only want one answer? Just search for answers and return the first one instead of yielding it.
A:
return iter([anwser])
| Stoping generator in first answer, use return instead | I am using too much to my taste the pattern (after every possible solution branch of the search). This is the code to find boggle words in given square. It had a bug if the words are not preselected to include only those whose letter pairs are neighbours, which I fixed now by changing comparrision not pos to pos is None.
def word_path(word,used=[],pos=None):
if not word:
yield False
return
else:
correct_neighbour = [neigh for p,neigh in neighbour_set
if (not pos or pos==p) and (neigh not in used) and boggle[neigh]==word[0] ]
for i in correct_neighbour:
used_copy=used[:]+[i]
if boggle[i]==word:
yield used_copy
return
else:
for solution in word_path(word[1:],used_copy,pos=i) or (False,):
if solution:
yield solution
return
Is there any better alternative to make generator which stops after any answer was found?
Solution based on why not use return
Finally it got me and returned sequence is iterator no matter that it was returned not yielded value. so I changed my word_path code to use return and cleaned up the expressions generally. Instead of giving None or False the function returns (False,). Then I have not problem with None not accepted for for statement.
def word_path(word,used=[],pos=None):
if word:
correct_neighbour = [neigh
for p,neigh in neighbour_set
if ((pos is None or pos==p) and
(neigh not in used) and
boggle[neigh]==word[0]
)
]
for i in correct_neighbour:
used_copy=used[:]+[i]
if len(word)==1:
if boggle[i]==word:
return (used_copy,)
else:
for solution in word_path(word[1:],used_copy,pos=i):
if solution:
return (solution,)
return (False,)
| [
"Why do you make it a generator in the first place when you only want one answer? Just search for answers and return the first one instead of yielding it.\n",
"return iter([anwser])\n\n"
] | [
3,
1
] | [] | [] | [
"prolog",
"prolog_cut",
"python",
"yield"
] | stackoverflow_0003325045_prolog_prolog_cut_python_yield.txt |
Q:
How to re-read in the last point ! python
how to read txt file and stop then continue at last read line
example:
Joe
LOley
Hana fat
oh beef come one
example = the txt file
and that last line i had read it is Hana fat
so how i can continue ?
like that:
#!/usr/bin/python
#this script name is x.py don't forget that
import os
f= open("Str1k3r.txt", "r")
for pwd in f.readlines():
con(pwd.replace("\r", "").replace("\n", ""))
os.system('x.py')
x.py= the script file when i run it again he continue in last line he had read !
\\\\
why i need that ?because my script try to connect pop3.live.com
and try to log in with so many password from txt file
and the only way to pass is run the script over and over again but with different line of the txt file
so how we can do ?
that my code .. so how to do it?
because my script try to connect pop3.live.com
and try to log in with so many password from txt file
and the only way to pass is run the script over and over again but with different line of the txt file
that is my code
import poplib
def con(pwd):
M = poplib.POP3_SSL('pop3.live.com', 995)
try:
M.user("test123@hotmail.com")
M.rset(M.pass_(pwd))
except:
print "[-]password incorrect"
else:
print '[+]really Password is:', pwd
exit()
f = open("Str1k3r.txt", "r")
for pwd in f.readlines():
A:
you might want to try using seek(), tell() etc... See the documents for more.
A:
f= open("Str1k3r.txt", "r")
for line in f:
print line
break
for line in f:
print line # Continues with line 2 as f knows where it stopped
break # It's actually using file.next()
A:
Every time you execute 'x.py', you reopen the file - at the beginning. That's what 'open' does.
If you want to continue reading, you'll probably want to arrange that the file is read from a known file descriptor - possibly standard input - so that you don't keep resetting it. That said, you might have to worry about buffered I/O. The first process might read a buffer full of the file, and only process part of the data in the buffer; the second process would continue where the I/O finished, not where the program finished.
Also, because you're using os.system(), you are gradually building up a set of processes that have not terminated, all waiting on their next child to die. Investigate your 'exec' options.
| How to re-read in the last point ! python | how to read txt file and stop then continue at last read line
example:
Joe
LOley
Hana fat
oh beef come one
example = the txt file
and that last line i had read it is Hana fat
so how i can continue ?
like that:
#!/usr/bin/python
#this script name is x.py don't forget that
import os
f= open("Str1k3r.txt", "r")
for pwd in f.readlines():
con(pwd.replace("\r", "").replace("\n", ""))
os.system('x.py')
x.py= the script file when i run it again he continue in last line he had read !
\\\\
why i need that ?because my script try to connect pop3.live.com
and try to log in with so many password from txt file
and the only way to pass is run the script over and over again but with different line of the txt file
so how we can do ?
that my code .. so how to do it?
because my script try to connect pop3.live.com
and try to log in with so many password from txt file
and the only way to pass is run the script over and over again but with different line of the txt file
that is my code
import poplib
def con(pwd):
M = poplib.POP3_SSL('pop3.live.com', 995)
try:
M.user("test123@hotmail.com")
M.rset(M.pass_(pwd))
except:
print "[-]password incorrect"
else:
print '[+]really Password is:', pwd
exit()
f = open("Str1k3r.txt", "r")
for pwd in f.readlines():
| [
"you might want to try using seek(), tell() etc... See the documents for more.\n",
"f= open(\"Str1k3r.txt\", \"r\")\nfor line in f:\n print line\n break\n\nfor line in f:\n print line # Continues with line 2 as f knows where it stopped\n break # It's actually using file.next()\n\n",
"Every time... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003325308_python.txt |
Q:
Emailing admin when a 500 error occurs
How can I send an email to admin when a 500 error occurs, in python.
The web framework I'm using is 'bottle'.
A:
Just use the @error(code) decorator to define an error handling page, like so:
from bottle import run, error, route
@error(500)
def handle_500_error(code):
# add mail send code here
return "Error message here"
@route("/test_500")
def cause_error():
raise Exception
run()
Just navigate to /test_500 to see it in action
You can of course use a template for the error page just like with any other page. I'm not sure if there's a way to get the built-in bottle error page while having an error handler.
Edit:
Apparently if you're using the latest Bottle v0.8, the function to which you apply the @error decorator receives as a parameter not the error code, but an bottle.HTTPError object, which contains the exception and traceback.
Alternatively, you can set Bottle to not handle exceptions by setting bottle.app().catchall to False as described here, and then use some appropriate WSGI middleware to handle them and send the email (e.g. something like this).
A:
The following is a line from the Bottle documentation.
All unhandled exceptions other than bottle.HTTPError will result in a 500 Internal Server Error response, so they won't crash your WSGI server.
Judging by this you would want to catch those Exceptions and write the code to send an email to whomsoever it may concern. Your code will go into the try block and you will have a some code for the bottle.HTTPError exception and then code to catch all other Exceptions which sends the desired email.
| Emailing admin when a 500 error occurs | How can I send an email to admin when a 500 error occurs, in python.
The web framework I'm using is 'bottle'.
| [
"Just use the @error(code) decorator to define an error handling page, like so:\nfrom bottle import run, error, route\n\n@error(500)\ndef handle_500_error(code):\n # add mail send code here\n return \"Error message here\"\n\n@route(\"/test_500\")\ndef cause_error():\n raise Exception\n\nrun()\n\nJust navigate to... | [
8,
1
] | [] | [] | [
"bottle",
"python"
] | stackoverflow_0003324743_bottle_python.txt |
Q:
What is the relation between PATH_MAX and NAME_MAX, and how do I obtain?
In limits.h, and in various places in the POSIX manpages, there are references to PATH_MAX and NAME_MAX.
How do these relate to one another?
Where is the official documentation for them?
How can I obtain them at run time, and (where relevant) compile time for the C, Python, and GNU (shell) environments?
A:
PATH_MAX is the maximum length of a filesystem path. NAME_MAX is the maximum length of a filename (in a particular spot). So, /foo/bar is restricted by PATH_MAX, and only the bar portion has its length limited by NAME_MAX.
You can get these at run time via pathconf, as _PC_PATH_MAX and _PC_NAME_MAX, although standard practice is generally just to use the static macros at compile time. I suppose it would be better to use the run-time option because you could potentially support longer values that way, but I'm not sure what (if any) systems actually provide a return from pathconf which is greater than the value of the POSIX_FOO_MAX values.
| What is the relation between PATH_MAX and NAME_MAX, and how do I obtain? | In limits.h, and in various places in the POSIX manpages, there are references to PATH_MAX and NAME_MAX.
How do these relate to one another?
Where is the official documentation for them?
How can I obtain them at run time, and (where relevant) compile time for the C, Python, and GNU (shell) environments?
| [
"PATH_MAX is the maximum length of a filesystem path. NAME_MAX is the maximum length of a filename (in a particular spot). So, /foo/bar is restricted by PATH_MAX, and only the bar portion has its length limited by NAME_MAX.\nYou can get these at run time via pathconf, as _PC_PATH_MAX and _PC_NAME_MAX, although st... | [
6
] | [] | [] | [
"c",
"gnu",
"limits",
"posix",
"python"
] | stackoverflow_0003325602_c_gnu_limits_posix_python.txt |
Q:
How to cache username and passwd in pysvn
here is my code
#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
import pysvn
def main():
client = pysvn.Client()
client.callback_get_login = lambda realm, username, may_save:(True, "myusername", "mypasswd", True)
print client.cat('http://svn.mydomain.com/file1.py')
print client.cat('http://svn.mydomain.com/file2.py')
return 0
if __name__ == "__main__":
sys.exit(main())
and I noticed that pysvn established two HTTP sessions, but in each session, it first tried a OPTION method without the "Authorization" header, after the server response 401, it sent "Authorization" header.
Since the two url is in the same domain, why not pysvn send the username/passwd directly in the subsequence sessions?
I have this question because I'm suspecting that too much 401 made my svn server failed to response. And the svnkit in eclipse works just fine and send "Authorization" header automatic.
Edit:
to Alex Martelli:
try passing an explicit path to a known-to-be-writable config dir when you call Client.
tried, not work
it may be that the serving is sending different realms for the two files
the realms of two response is the same.
It looks like pysvn calls "svn_client_cat2()" from libsvn and this function does not cache username/passwd between invoking even for the same url and same realms.
So I don't think I can do any more to this problem, adding new interface to libsvn and cache username/passwd for future actions will cost too much time for my task. Thanks anyway!
A:
Looks like (bug hypothesis number one) the configuration directory might be not writable -- try passing an explicit path to a known-to-be-writable config dir when you call Client.
If that doesn't help (bug hypothesis number two) it may be that the serving is sending different realms for the two files (the fact that it's the same domain doesn't stop the server from doing that, though it would be a peculiar configuration choice or configuration error on the server's part... but then a server that fails due to "too many 401s" does have something peculiar anyway, so it's a suspect already;-).
| How to cache username and passwd in pysvn | here is my code
#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
import pysvn
def main():
client = pysvn.Client()
client.callback_get_login = lambda realm, username, may_save:(True, "myusername", "mypasswd", True)
print client.cat('http://svn.mydomain.com/file1.py')
print client.cat('http://svn.mydomain.com/file2.py')
return 0
if __name__ == "__main__":
sys.exit(main())
and I noticed that pysvn established two HTTP sessions, but in each session, it first tried a OPTION method without the "Authorization" header, after the server response 401, it sent "Authorization" header.
Since the two url is in the same domain, why not pysvn send the username/passwd directly in the subsequence sessions?
I have this question because I'm suspecting that too much 401 made my svn server failed to response. And the svnkit in eclipse works just fine and send "Authorization" header automatic.
Edit:
to Alex Martelli:
try passing an explicit path to a known-to-be-writable config dir when you call Client.
tried, not work
it may be that the serving is sending different realms for the two files
the realms of two response is the same.
It looks like pysvn calls "svn_client_cat2()" from libsvn and this function does not cache username/passwd between invoking even for the same url and same realms.
So I don't think I can do any more to this problem, adding new interface to libsvn and cache username/passwd for future actions will cost too much time for my task. Thanks anyway!
| [
"Looks like (bug hypothesis number one) the configuration directory might be not writable -- try passing an explicit path to a known-to-be-writable config dir when you call Client.\nIf that doesn't help (bug hypothesis number two) it may be that the serving is sending different realms for the two files (the fact th... | [
1
] | [] | [] | [
"pysvn",
"python"
] | stackoverflow_0003325489_pysvn_python.txt |
Q:
Noob Question: Python + Twitter + App Engine - Oauth
I'm sorry but I'm having some trouble implementing Oauth within my app engine python project.
I've been working from http://github.com/tav/tweetapp, but I don't think I have a strong enough grasp on this platform to understand how to implement this class within my main.py I'm building the rest of my app in.
This maybe a feeble attempt, but here is what I have so far:
twa = twitter_auth
client = twa.OAuthClient('twitter')
I've created a source folder within my project called "twitter_auth" and that contains a file within it called "twitter_auth.py" which contains the above linked library, and a file called __ init__.py (no space) which is completely empty.
I really have no idea what to do from here :/
A:
Let me recommend taking a look at the tweepy library and some example tweepy apps. Specifically here: http://github.com/wasauce/tweepy-examples
This shows how to use oauth to authenticate a user: http://github.com/wasauce/tweepy-examples/tree/master/appengine/oauth_example/
A:
As Hagge said, it sounds like your issue is more with the tweetapp library than with App Engine. However, if you would like to know more about OAuth on App Engine and if I may be allowed to link to myself, my two articles on the topic seem to be reasonably popular.
A:
The tweetapp library was a an early prototype for Twitter OAuth on twitter. Tav did the heavy lifting and I deployed the site http://twitteroauth.appspot.com , using some of the tweetapp library. The actual source of that site is here (I need to update the site to point here): http://github.com/ryanwi/twitteroauth
I am still using it in production, but, it has aged and does not work for all API calls. I'd recommend trying a different, more up to date and maintained library as others have mentioned.
But, take a look at the twitteroauth source if you want to try to get a first attempt working.
These two are on Twitter's list
http://github.com/brosner/python-oauth2
http://code.google.com/p/oauth-python-twitter2/
A:
I'm not familiar with that library, but after a quick look and seeing the warning that it is not maintained I'd search for something better. I implemented a simple Twitter connection based on Tornado's auth: see an example of how to make Twitter API calls here (and an authentication example here). In case you don't want to use tipfy, I recommend implementing the python-twitter library in your framework of choice.
| Noob Question: Python + Twitter + App Engine - Oauth | I'm sorry but I'm having some trouble implementing Oauth within my app engine python project.
I've been working from http://github.com/tav/tweetapp, but I don't think I have a strong enough grasp on this platform to understand how to implement this class within my main.py I'm building the rest of my app in.
This maybe a feeble attempt, but here is what I have so far:
twa = twitter_auth
client = twa.OAuthClient('twitter')
I've created a source folder within my project called "twitter_auth" and that contains a file within it called "twitter_auth.py" which contains the above linked library, and a file called __ init__.py (no space) which is completely empty.
I really have no idea what to do from here :/
| [
"Let me recommend taking a look at the tweepy library and some example tweepy apps. Specifically here: http://github.com/wasauce/tweepy-examples\nThis shows how to use oauth to authenticate a user: http://github.com/wasauce/tweepy-examples/tree/master/appengine/oauth_example/\n",
"As Hagge said, it sounds like yo... | [
1,
1,
1,
0
] | [] | [] | [
"google_app_engine",
"pydev",
"python",
"twitter"
] | stackoverflow_0003305701_google_app_engine_pydev_python_twitter.txt |
Q:
Python: Accessing Values For Dict Key Made Using Variables
Hi I've been coding a console version of Minesweeper just to learn some of the basics of Python. It uses a coordinate system that is recorded in a dictionary. Now, I have been able to implement it successfully but accessing or assigning a value to a specific coordinate key using variables for the "x,y" of the coordinate seems... clunky. There are two different ways that I've come up with but they don't seem very elegant when I have to use them so often.
for i in range(1, ROWS+1):
for j in range(1, COLS+1):
mine_field["%i,%i" % (i,j)] = 0
or
for i in range(1, ROWS+1):
for j in range(1, COLS+1):
mine_field[",".join([i, j])] = 0
It works well enough but it does start to look messy when assigning or swapping values. Is there a better way that this can be done?
Thanks in advance.
A:
Why not simply use a tuple as the key?
for i in range(1, ROWS+1):
for j in range(1, COLS+1):
mine_field[(i, j)] = 0 # you don't even need the parentheses!
Using this method, you can use comma-separated indices like so:
d = {(1,2):3}
print d[1, 2] # will print 3
And BTW why are you using one-based indices?
A:
If you make mine_field a list of lists, then you can use nicer syntax:
mine_field = [[0]*ROWS for i in range(COLS)]
mine_field[i][j] = 1
| Python: Accessing Values For Dict Key Made Using Variables | Hi I've been coding a console version of Minesweeper just to learn some of the basics of Python. It uses a coordinate system that is recorded in a dictionary. Now, I have been able to implement it successfully but accessing or assigning a value to a specific coordinate key using variables for the "x,y" of the coordinate seems... clunky. There are two different ways that I've come up with but they don't seem very elegant when I have to use them so often.
for i in range(1, ROWS+1):
for j in range(1, COLS+1):
mine_field["%i,%i" % (i,j)] = 0
or
for i in range(1, ROWS+1):
for j in range(1, COLS+1):
mine_field[",".join([i, j])] = 0
It works well enough but it does start to look messy when assigning or swapping values. Is there a better way that this can be done?
Thanks in advance.
| [
"Why not simply use a tuple as the key?\nfor i in range(1, ROWS+1):\n for j in range(1, COLS+1):\n mine_field[(i, j)] = 0 # you don't even need the parentheses!\n\nUsing this method, you can use comma-separated indices like so:\nd = {(1,2):3}\nprint d[1, 2] # will print 3\n\nAnd BTW why are you using one-... | [
5,
1
] | [] | [] | [
"dictionary",
"key",
"python",
"variables"
] | stackoverflow_0003325719_dictionary_key_python_variables.txt |
Q:
Use of properties in python like in example C#
I currently work with Python for a while and I came to the point where I questioned myself whether I should use "Properties" in Python as often as in C#.
In C# I've mostly created properties for the majority of my classes.
It seems that properties are not that popular in python, am I wrong?
How to use properties in Python?
regards,
A:
Properties are often no required if all you do is set and query member variables. Because Python has no concept of encapsulation, all member variables are public and often there is no need to encapsulate accesses. However, properties are possible, perfectly legitimate and popular:
class C(object):
def __init__(self):
self._x = 0
@property
def x(self):
return self._x
@x.setter
def x(self, value):
if value <= 0:
raise ValueError("Value must be positive")
self._x = value
o = C()
print o.x
o.x = 5
print o.x
o.x = -2
A:
I would you recommend to read this, even it is directed to Java progrmamers:
Python Is Not Java
A:
If you make an attribute public in C# then later need to change it into a property you also need to recompile all code that uses the original class. This is bad, so make any public attributes into properties from day one 'just in case'.
If you have an attribute that is used from other code then later need to change it into a property then you just change it and nothing else needs to happen. So use ordinary attributes until such time as you find you need something more complicated.
| Use of properties in python like in example C# | I currently work with Python for a while and I came to the point where I questioned myself whether I should use "Properties" in Python as often as in C#.
In C# I've mostly created properties for the majority of my classes.
It seems that properties are not that popular in python, am I wrong?
How to use properties in Python?
regards,
| [
"Properties are often no required if all you do is set and query member variables. Because Python has no concept of encapsulation, all member variables are public and often there is no need to encapsulate accesses. However, properties are possible, perfectly legitimate and popular:\nclass C(object):\n def __init... | [
15,
7,
2
] | [] | [] | [
"c#",
"properties",
"python"
] | stackoverflow_0003324920_c#_properties_python.txt |
Q:
Python list, lookup object name, efficiency advice
Suppose I have the following object:
class Foo(object):
def __init__(self, name=None):
self.name = name
def __repr__(self):
return self.name
And a list containing multiple instances, such as:
list = [Foo(name='alice'), Foo(name='bob'), Foo(name='charlie')]
If I want to find an object with a given name, I could use the following:
def get_by_name(name, list):
return [foo for foo in list if foo.name == name][-1]
Which would obviously mean:
print get_by_name('alice', list)
>> alice
However, is there a more efficient data structure or method for retrieving such objects? In reality, the object names are only known at runtime and could in theory change throughout the lifecycle of the object.
Any advice?
UPDATE:
Thanks to Matt Joiners answer, I have updated it to support multiple Foo's with the same name:
class Foo(object):
_all_names = {}
def __init__(self, name=None):
self._name = None
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
if self._name is not None:
self._all_names[self._name].remove(self)
self._name = name
if name is not None:
self._all_names.setdefault(name, []).append(self)
@classmethod
def get_by_name(cls, name):
return cls._all_names[name]
def __repr__(self):
return "{0}".format(self.name)
l = [Foo("alice"), Foo("bob"), Foo('alice'), Foo('charlie')]
print Foo.get_by_name("alice")
print Foo.get_by_name("charlie")
Any comments on this approach?
A:
Try this for size:
class Foo(object):
_all_names = {}
def __init__(self, name=None):
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
self._all_names[name] = self
@classmethod
def get_by_name(cls, name):
return cls._all_names[name]
def __str__(self):
return "Foo({0})".format(self.name)
a = Foo("alice")
b = Foo("bob")
print Foo.get_by_name("alice")
Keep in mind it's kept minimal to convey the idea, there are many tweaks and checks you can make here and there.
A:
The situation is a little confusing.
You're going to be searching for this object in a list which is a linear data structure. The only way to look for something is by going through it one by one. This makes the time grow linearly with the length of the list. So that is where your speed issue is.
The way to get some speed gains is to use some kind of hashing scheme to keep your objects directly indexable by the key you're interested in (in your case, name). This will allow you to look up an object in a way similar to dictionary key lookup. It's a constant time operation. This is basically what Matt's answer does. He's keeping an "index" as a class level structure so that you can look things up using hashing rather than by walking a list.
| Python list, lookup object name, efficiency advice | Suppose I have the following object:
class Foo(object):
def __init__(self, name=None):
self.name = name
def __repr__(self):
return self.name
And a list containing multiple instances, such as:
list = [Foo(name='alice'), Foo(name='bob'), Foo(name='charlie')]
If I want to find an object with a given name, I could use the following:
def get_by_name(name, list):
return [foo for foo in list if foo.name == name][-1]
Which would obviously mean:
print get_by_name('alice', list)
>> alice
However, is there a more efficient data structure or method for retrieving such objects? In reality, the object names are only known at runtime and could in theory change throughout the lifecycle of the object.
Any advice?
UPDATE:
Thanks to Matt Joiners answer, I have updated it to support multiple Foo's with the same name:
class Foo(object):
_all_names = {}
def __init__(self, name=None):
self._name = None
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
if self._name is not None:
self._all_names[self._name].remove(self)
self._name = name
if name is not None:
self._all_names.setdefault(name, []).append(self)
@classmethod
def get_by_name(cls, name):
return cls._all_names[name]
def __repr__(self):
return "{0}".format(self.name)
l = [Foo("alice"), Foo("bob"), Foo('alice'), Foo('charlie')]
print Foo.get_by_name("alice")
print Foo.get_by_name("charlie")
Any comments on this approach?
| [
"Try this for size:\nclass Foo(object):\n _all_names = {}\n def __init__(self, name=None):\n self.name = name\n @property\n def name(self):\n return self._name\n @name.setter\n def name(self, name):\n self._name = name\n self._all_names[name] = self\n @classmethod\n ... | [
8,
1
] | [] | [] | [
"algorithm",
"list",
"list_comprehension",
"performance",
"python"
] | stackoverflow_0003325711_algorithm_list_list_comprehension_performance_python.txt |
Q:
python matplotlib will only plot integers
I'm very new to python. two days. trying to get a plot working with matplotlib. I'm getting this error:
cannot perform reduce with flexible type
the line with the error is:
ax.scatter(x,y,z,marker='o')
Variables:
ax is defined as: ax = Axes3D(fig)
fig is defined as: fig = plt.figure()
x, y, z are lists
Any python experts tell me why? I got the plot to work but the values are integers. Decimal values are preferred.
I read that lists in python are not very good with numbers... can someone clarify? I got it to work with lists and ndarrays but all the values have to be integers.
Thanks!
A:
Compare your code with this basic scatter plot code. Notice that there xs,ys,zs are ndarrays of floats. Does that code work for you? Maybe you can incrementally morph that code into your own to get code that works (or learn where yours breaks).
If that doesn't help, perhaps post enough code to allow us to reproduce the problem. At the very least, post the output of
print(repr(x))
print(repr(y))
print(repr(z))
A:
Thanks for the responses.
I got it working with floats but maybe you all can tell me why. I just created an account here and can't edit my guest question...
I'm getting my data from a sqlite database. I can round the values in the sql or cast to floats and it works. I'm guessing that the data was a numerical object even though it was numerical. Is this correct?
Here's an excerpt of the code that doesn't work. I got it to work by casting the values as floats.
import sqlite3
import re
import numpy as np
from numpy import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
conn = sqlite3.connect('./RES/resDB.dbl')
fig = plt.figure()
ax = Axes3D(fig)
sam = array([])
x = array([])
y = array([])
z = array([])
for sv in conn.execute('select sam,easting,northing,altitude from trx_all'):
sam = np.append(sam, [sv[0]]) #this works: sam = np.append(sam, [float(sv[0])])
x = np.append(x, [sv[1]]) #this works: x = np.append(x, [float(sv[1])])
y = np.append(y, [sv[2]]) #this works: y = np.append(y, [float(sv[2])])
z = np.append(z, [sv[3]]) #this works: z = np.append(z, [float(sv[3])])
if sam.__len__() > 0:
print(repr(x))
print(repr(y))
print(repr(z))
ax.scatter(x, y, z, marker='o')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title("3D plot")
plt.show()
unutbu requested the output of print(repr(x)):
x: array([u'227004.744896075', u'227029.694213685', u'227051.351657645', ...,
u'226416.484484696', u'226436.436477995', u'226401.253669657'],
dtype='U16')
y: array([u'3648736.75423911', u'3648737.3357031', u'3648746.34280013', ...,
u'3645870.67565062', u'3645893.61216942', u'3645866.95833722'],
dtype='U16')
z: array([u'1600.2589433603', u'1535.77224937826', u'1429.01016684435', ...,
u'341.064685015939', u'343.452275622636', u'312.491347198375'],
dtype='U16')
and finally here's the error that it outputs on the line ax.scatter(x,y,z,marker='o') :
Traceback (most recent call last):
File "C:\stripped_3dplot.py", line 27, in
ax.scatter(x, y, z, marker='o')
File "C:\Python27\lib\site-packages\mpl_toolkits\mplot3d\axes3d.py", line 1019, in scatter
patches = Axes.scatter(self, xs, ys, *args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 5813, in scatter
minx = np.amin(temp_x)
File "C:\Python27\lib\site-packages\numpy\core\fromnumeric.py", line 1846, in amin
return amin(axis, out)
TypeError: cannot perform reduce with flexible type
Like i said i think it was just the wrong type, but if you all can tell me what type causes the error i could learn something.
Thanks.
| python matplotlib will only plot integers | I'm very new to python. two days. trying to get a plot working with matplotlib. I'm getting this error:
cannot perform reduce with flexible type
the line with the error is:
ax.scatter(x,y,z,marker='o')
Variables:
ax is defined as: ax = Axes3D(fig)
fig is defined as: fig = plt.figure()
x, y, z are lists
Any python experts tell me why? I got the plot to work but the values are integers. Decimal values are preferred.
I read that lists in python are not very good with numbers... can someone clarify? I got it to work with lists and ndarrays but all the values have to be integers.
Thanks!
| [
"Compare your code with this basic scatter plot code. Notice that there xs,ys,zs are ndarrays of floats. Does that code work for you? Maybe you can incrementally morph that code into your own to get code that works (or learn where yours breaks).\nIf that doesn't help, perhaps post enough code to allow us to reprodu... | [
3,
1
] | [] | [] | [
"integer",
"matplotlib",
"plot",
"python"
] | stackoverflow_0003323185_integer_matplotlib_plot_python.txt |
Q:
Common convention for invoking unit tests across a python project?
Is there a standard convention, or even a growing one, around where and how to invoke the tests associated with a project? In many projects, I'm seeing it bundled into a Make, a separate test.py script at the top level of the project, etc to do the work.
I looked around for some common thing with setup.py, but didn't spot anything there (granted, I didn't look hard). What's common and best practice?
A:
The short answer is yes, there's a simple convention built-in to the unittest module. See this previous question.
| Common convention for invoking unit tests across a python project? | Is there a standard convention, or even a growing one, around where and how to invoke the tests associated with a project? In many projects, I'm seeing it bundled into a Make, a separate test.py script at the top level of the project, etc to do the work.
I looked around for some common thing with setup.py, but didn't spot anything there (granted, I didn't look hard). What's common and best practice?
| [
"The short answer is yes, there's a simple convention built-in to the unittest module. See this previous question.\n"
] | [
1
] | [] | [] | [
"python",
"testing",
"unit_testing"
] | stackoverflow_0003326116_python_testing_unit_testing.txt |
Q:
GAE - Sharing Authentication Across Apps
Let's say I had a root app and multiple sub-apps. Would it be possible to share authenticated sessions across them?
I'm using Google App Engine (Python).
A:
If you use tipfy, the wonderful lightweight almost-not-a-framework that @moraes developed specifically for App Engine use, you get many excellent choices for authentication approaches (see here) several of which will let you achieve what you're after.
A:
Not using the built in authentication support - users have to authenticate separately with each application.
| GAE - Sharing Authentication Across Apps | Let's say I had a root app and multiple sub-apps. Would it be possible to share authenticated sessions across them?
I'm using Google App Engine (Python).
| [
"If you use tipfy, the wonderful lightweight almost-not-a-framework that @moraes developed specifically for App Engine use, you get many excellent choices for authentication approaches (see here) several of which will let you achieve what you're after.\n",
"Not using the built in authentication support - users ha... | [
4,
1
] | [] | [] | [
"authentication",
"google_app_engine",
"openid",
"python"
] | stackoverflow_0003325906_authentication_google_app_engine_openid_python.txt |
Q:
How to use twisted for downloading a remote file?
I'm relatively new to twisted and I'm planning on using it to create a file downloader. It would accept a file url and a number of parts to download the file.
What I have in mind is to split the file into how many parts the user specified and download each parts through deferred and when it is done, all parts gets assembled.
But do I need a protocol for each file to be downloaded and have each protocol dispatch a defer to download each file's chunks?
Is there a twisted component to read the remote file that has a seek? I really don't have any idea where to start.
A:
If your mention of a URL implies that the protocol in use is HTTP (and I hope HTTP 1.1;-), then you could use twisted's relatively new HTTP 1.1 client (discussed at length here, and from the fact that the issue was marked as fixed 9 months ago I assume the client is finally in -- I have not checked that), using HTTP 1.1's range requests to get "slices" of the file.
If you're stuck with HTTP 1.0, or a not fully compliant server, you may be out of luck; if you really mean the "U" part of "URL", i.e., you need a Universal solution across all kinds of protocols, the problem of course becomes much, much harder.
| How to use twisted for downloading a remote file? | I'm relatively new to twisted and I'm planning on using it to create a file downloader. It would accept a file url and a number of parts to download the file.
What I have in mind is to split the file into how many parts the user specified and download each parts through deferred and when it is done, all parts gets assembled.
But do I need a protocol for each file to be downloaded and have each protocol dispatch a defer to download each file's chunks?
Is there a twisted component to read the remote file that has a seek? I really don't have any idea where to start.
| [
"If your mention of a URL implies that the protocol in use is HTTP (and I hope HTTP 1.1;-), then you could use twisted's relatively new HTTP 1.1 client (discussed at length here, and from the fact that the issue was marked as fixed 9 months ago I assume the client is finally in -- I have not checked that), using HT... | [
1
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003325871_python_twisted.txt |
Q:
doing textwrap and dedent in Windows Powershell (or dotNet aka .net)
Background
Python has "textwrap" and "dedent" functions. They do pretty much what you expect to any string you supply.
textwrap.wrap(text[, width[, ...]])
Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.
textwrap.dedent(text)
Remove any common leading whitespace from every line in text.
http://docs.python.org/library/textwrap.html
Question:
How do you do this in Windows PowerShell, (or with .NET methods you call from PowerShell)?
A:
This is a negligent code...
#requires -version 2.0
function wrap( [string]$text, [int]$width ) {
$i=0;
$text.ToCharArray() | group { [Math]::Floor($i/$width); (gv i).Value++ } | % { -join $_.Group }
}
function dedent( [string[]]$text ) {
$i = $text | % { $_ -match "^(\s*)" | Out-Null ; $Matches[1].Length } | sort | select -First 1
$text -replace "^\s{$i}"
}
A:
I think you should create a CLI utility with this behaviour and customize it as you like. And then just use it as a command in your shell. Maybe you will also need to add you script into PATH.
A:
Looking at the results in python at http://try-python.mired.org/, it appears that the correct algorithm splits at word boundaries, rather than taking fixed-length substrings from the text.
function wrap( [string]$text, [int]$width = 70 ) {
$line = ''
# Split the text into words.
$text.Split( ' '.ToCharArray( ) ) | % {
# Initialize the first line with the first word.
if( -not $line ) { $line = $_ }
else {
# For each new word, try to add it to the current line.
$next = $line + ' ' + $_
# If the new word goes over the limit,
# return the last line and start a new one.
if( $next.Length -ge $width ) { $line; $line = $_ }
# Otherwise, use the updated line with the new word.
else { $line = $next }
}
}
# Return the last line, containing the remainder of the text.
$line
}
And here's an alternate implementation for dedent as well.
function dedent( [string[]]$lines ) {
# Find the shortest length of leading whitespace common to all lines.
$commonLength = (
$lines | % {
$i = 0
while( $i -lt $_.Length -and [char]::IsWhitespace( $_, $i ) ) { ++$i }
$i
} | Measure-Object -minimum
).Minimum
# Remove the common whitespace from each string
$lines | % { $_.Substring( $commonLength ) }
}
Hopefully their greater verbosity will provide better clarity :)
| doing textwrap and dedent in Windows Powershell (or dotNet aka .net) | Background
Python has "textwrap" and "dedent" functions. They do pretty much what you expect to any string you supply.
textwrap.wrap(text[, width[, ...]])
Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.
textwrap.dedent(text)
Remove any common leading whitespace from every line in text.
http://docs.python.org/library/textwrap.html
Question:
How do you do this in Windows PowerShell, (or with .NET methods you call from PowerShell)?
| [
"This is a negligent code...\n#requires -version 2.0\n function wrap( [string]$text, [int]$width ) {\n $i=0;\n $text.ToCharArray() | group { [Math]::Floor($i/$width); (gv i).Value++ } | % { -join $_.Group }\n}\n\nfunction dedent( [string[]]$text ) {\n $i = $text | % { $_ -match \"^(\\s*)\" | Out-Null ; ... | [
3,
1,
1
] | [] | [] | [
".net",
"powershell",
"python",
"string",
"text"
] | stackoverflow_0001417663_.net_powershell_python_string_text.txt |
Q:
Python: Detecting the actual text paragraphs in a string
The big mission: I am trying to get a few lines of summary of a webpage. i.e. I want to have a function that takes a URL and returns the most informative paragraph from that page. (Which would usually be the first paragraph of actual content text, in contrast to "junk text", like the navigation bar.)
So I managed to reduce an HTML page to a bunch of text by cutting out the tags, throwing out the <HEAD> and all the scripts. But some of the text is still "junk text". I want to know where the actual paragraphs of text begin. (Ideally it should be human-language-agnostic, but if you have a solution only for English, that might help too.)
How can I figure out which of the text is "junk text" and which is actual content?
UPDATE: I see some people have pointed me to use an HTML parsing library. I am using Beautiful Soup. My problem isn't parsing HTML; I already got rid of all the HTML tags, I just have a bunch of text and I want to separate the context text from the junk text.
A:
A general solution to this problem is a non-trivial problem to solve.
To put this in context, a large part of Google's success with search has come from their ability to automatically discern some semantic meaning from arbitrary Web pages, namely figuring out where the "content" is.
One idea that springs to mind is if you can crawl many pages from the same site then you will be able to identify patterns. Menu markup will be largely the same between all pages. If you zero this out somehow (and it will need to fairly "fuzzy") what's left is the content.
The next step would be to identify the text and what constitutes a boundary. Ideally that would be some HTML paragraphs but you won't get that lucky most of the time.
A better approach might be to find the RSS feeds for the site and get the content that way because that will be stripped down as is. Ignore any AdSense (or similar) content and you should be able to get the text.
Oh and absolutely throw out your regex code for this. This requires an HTML parser absolutely without question.
A:
You could use the approach outlined at the AI depot blog along with some python code:
The Easy Way to Extract Useful Text from Arbitrary HTML
A:
Probably a bit overkill, but you could try nltk, the Natural Language Toolkit. That library is used for parsing natural languages. It's quite a nice library and an interesting subject. If you want to just get sentences from a text you would do something like:
>>> import nltk
>>> nltk.sent_tokenize("Hi this is a sentence. And isn't this a second one, a sentence with a url http://www.google.com in it?")
['Hi this is a sentence.', "And isn't this a second one, a sentence with a url http://www.google.com in it?"]
Or you could use the sentences_from_text method from the PunktSentenceTokenizer class. You have to do nltk.download() before you get started.
A:
I'd recommend having a look at what Readability does. Readability strips out all but the actual content of the page and restyles it for easy reading. It seems to work very well in terms of detecting the content from my experience.
Have a look at its source code (particularly the grabArticle function) and maybe you can get some ideas.
| Python: Detecting the actual text paragraphs in a string | The big mission: I am trying to get a few lines of summary of a webpage. i.e. I want to have a function that takes a URL and returns the most informative paragraph from that page. (Which would usually be the first paragraph of actual content text, in contrast to "junk text", like the navigation bar.)
So I managed to reduce an HTML page to a bunch of text by cutting out the tags, throwing out the <HEAD> and all the scripts. But some of the text is still "junk text". I want to know where the actual paragraphs of text begin. (Ideally it should be human-language-agnostic, but if you have a solution only for English, that might help too.)
How can I figure out which of the text is "junk text" and which is actual content?
UPDATE: I see some people have pointed me to use an HTML parsing library. I am using Beautiful Soup. My problem isn't parsing HTML; I already got rid of all the HTML tags, I just have a bunch of text and I want to separate the context text from the junk text.
| [
"A general solution to this problem is a non-trivial problem to solve.\nTo put this in context, a large part of Google's success with search has come from their ability to automatically discern some semantic meaning from arbitrary Web pages, namely figuring out where the \"content\" is.\nOne idea that springs to mi... | [
2,
2,
1,
0
] | [] | [] | [
"html",
"python",
"screen_scraping",
"text"
] | stackoverflow_0003325817_html_python_screen_scraping_text.txt |
Q:
GAE + Python vs Webfaction + Python + django - for a relative new dev
Basically I have a webfaction space (assume for the purposes of this question that its free).
I am trying to learn python by created some simple web applications on Google App Engine using Eclipse + Pydev for development.
So far I have some basic functionality working in App Engine, though I have had some frustration with some library imports not working and whatnot (this may not be app engine specific).
So, is it worth it to switch now to webfaction, and leave GAE?
A:
I am trying to learn python by created
some simple web applications on Google
App Engine using Eclipse + Pydev for
development.
This seems reasonable. Nothing wrong with using GAE, Eclipse, and Pydev to learn to do Python web dev.
So far I have some basic functionality
working in App Engine, though I have
had some frustration with some library
imports not working and whatnot (this
may not be app engine specific).
So, is it worth it to switch now to
webfaction, and leave GAE?
You haven't provided much of a reason to leave GAE now that you've started there. I think that "some frustration" is normal for learning on any platform.
Beyond that I think this could descend into a general GAE good for learning vs. GAE bad for learning discussion.
So let me get that started...
Since GAE is a 'Platform as a service' (PaaS) it makes deployment and maintenance very simple. You can get right to coding and not worry about the platform. As well, this platform provides some services, such as e-mail and authentication that make those tasks very easy. For example, on first pass you can just make use of their authentication API (supports Google and now openID authentication I think) and leave more complicated authentication options for later.
On the other hand, this platform is kinda' non-standard. The datastore is the main issue and that affects Django. That's a pain because it means that the Django running on GAE is slightly different then the standard Django and the Django docs that you are reading might not apply for GAE, etc.
Here is a current thread about getting started with Django on GAE (which addresses the datastore issue):
http://groups.google.com/group/google-appengine-python/browse_thread/thread/8d1c945d27b6305f
Hope that helps.
| GAE + Python vs Webfaction + Python + django - for a relative new dev | Basically I have a webfaction space (assume for the purposes of this question that its free).
I am trying to learn python by created some simple web applications on Google App Engine using Eclipse + Pydev for development.
So far I have some basic functionality working in App Engine, though I have had some frustration with some library imports not working and whatnot (this may not be app engine specific).
So, is it worth it to switch now to webfaction, and leave GAE?
| [
"\nI am trying to learn python by created\n some simple web applications on Google\n App Engine using Eclipse + Pydev for\n development.\n\nThis seems reasonable. Nothing wrong with using GAE, Eclipse, and Pydev to learn to do Python web dev.\n\nSo far I have some basic functionality\n working in App Engine, t... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003326308_google_app_engine_python.txt |
Q:
How to properly columnize tables in a Django template
I am currently trying to break a list of people (aprox 20 to 30 items) into a table with 4 columns. Here is my current code.
<table>
{% for person in people %}
{% cycle "<tr><td>" "<td>" "<td>" "<td>" %}
{{ person }}
{% cycle "</td>" "</td>" "</td>" "</td></tr>" %}
{% endfor %}
</table>
Obviously, this is pretty ugly, and doesn't always close the last TR tag. One alternative I found was to break my list of people into multiple lists of 4 people, and then loop through each of those lists. I was hoping there was an easier way to do this in the templates side alone, without extending django templates myself (which I also found and considered)
Thanks!
A:
Use the divisibleby filter.
<tr>
{% for person in people %}
<td>{{ person }}</td>
{% if forloop.counter|divisibleby:4 and not forloop.last %}</tr><tr>{% endif %}
{% endfor %}
</tr>
| How to properly columnize tables in a Django template | I am currently trying to break a list of people (aprox 20 to 30 items) into a table with 4 columns. Here is my current code.
<table>
{% for person in people %}
{% cycle "<tr><td>" "<td>" "<td>" "<td>" %}
{{ person }}
{% cycle "</td>" "</td>" "</td>" "</td></tr>" %}
{% endfor %}
</table>
Obviously, this is pretty ugly, and doesn't always close the last TR tag. One alternative I found was to break my list of people into multiple lists of 4 people, and then loop through each of those lists. I was hoping there was an easier way to do this in the templates side alone, without extending django templates myself (which I also found and considered)
Thanks!
| [
"Use the divisibleby filter.\n<tr>\n{% for person in people %}\n <td>{{ person }}</td>\n {% if forloop.counter|divisibleby:4 and not forloop.last %}</tr><tr>{% endif %}\n{% endfor %}\n</tr>\n\n"
] | [
11
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003326514_django_django_templates_python.txt |
Q:
Python: Error in MySQL
import MySQLdb
import random
db = MySQLdb.connect (host = "localhost", user = "python-test", passwd = "python", db = "python-test")
cursor = db.cursor()
var = .3
sql = "INSERT INTO RandomInt
(RAND)
VALUES
(var)" # RandomInt is the name of the table and Rand is the Column Name
cursor.execute(sql)
db.commit()
db.close()
I get an error saying Operational Error: (1054, "Unknown column 'var' in 'field list'") Why do I get this error and how do I fix this although I have already defined var?
A:
As written, var is being sent to MySQL as a string.
Give this a shot instead:
sql = "INSERT INTO RandomInt (RAND) VALUES (%s)"
cursor.execute(sql, (var,))
Edit:
>>> import MySQLdb
>>> MySQLdb.paramstyle
'format'
MySQLdb's paramstyle is format; which, according to the DB-API is %s:
'format' ANSI C printf format codes,
e.g. '...WHERE name=%s'
A:
This will fix one issue:
sql = "INSERT INTO RandomInt (RAND) VALUES (%s)"
cursors.execute(sql, (var,))
What remains is the name of the table where you write into, 0.3 is not an int.
Edit: paramstyle of mysqldb is %s not ?.
A:
var = .3
sql = "INSERT INTO RandomInt (RAND) VALUES (%s)"
cursor.execute(sql, (var,))
A:
Your sql appears to MySQL as:
INSERT INTO RandomInt (RAND) VALUES (var)
To actually have the string substitute var, try this:
sql = "INSERT INTO RandomInt (RAND) VALUES (%d)" % (var,)
Now, MySQL should see:
INSERT INTO RandomInt (RAND) VALUES (0.3)
NOTE: Adam Bernier is right about sql injection. See the cursor.execute doc for parameter substitution as well as his answer.
| Python: Error in MySQL | import MySQLdb
import random
db = MySQLdb.connect (host = "localhost", user = "python-test", passwd = "python", db = "python-test")
cursor = db.cursor()
var = .3
sql = "INSERT INTO RandomInt
(RAND)
VALUES
(var)" # RandomInt is the name of the table and Rand is the Column Name
cursor.execute(sql)
db.commit()
db.close()
I get an error saying Operational Error: (1054, "Unknown column 'var' in 'field list'") Why do I get this error and how do I fix this although I have already defined var?
| [
"As written, var is being sent to MySQL as a string.\nGive this a shot instead:\nsql = \"INSERT INTO RandomInt (RAND) VALUES (%s)\"\ncursor.execute(sql, (var,))\n\nEdit:\n>>> import MySQLdb\n>>> MySQLdb.paramstyle\n'format'\n\nMySQLdb's paramstyle is format; which, according to the DB-API is %s:\n\n 'for... | [
5,
1,
1,
0
] | [] | [] | [
"mysql",
"mysql_error_1054",
"python"
] | stackoverflow_0003327188_mysql_mysql_error_1054_python.txt |
Q:
How can I enumerate filesystems from Python?
I'm using os.statvfs to find out the free space available on a volume -- in addition to querying free space for a particular path, I'd like to be able to iterate over all volumes. I'm working on Linux at the moment, but ideally would like something which returns ["/", "/boot", "home"] on Linux and ["C:\", "D:\"] on Windows.
A:
For Linux how about parsing /etc/mtab or /proc/mounts? Or:
import commands
mount = commands.getoutput('mount -v')
lines = mount.split('\n')
points = map(lambda line: line.split()[2], lines)
print points
For Windows I found something like this:
import string
from ctypes import windll
def get_drives():
drives = []
bitmask = windll.kernel32.GetLogicalDrives()
for letter in string.uppercase:
if bitmask & 1:
drives.append(letter)
bitmask >>= 1
return drives
if __name__ == '__main__':
print get_drives()
and this:
from win32com.client import Dispatch
fso = Dispatch('scripting.filesystemobject')
for i in fso.Drives :
print i
Try those, maybe they help.
Also this should help: Is there a way to list all the available drive letters in python?
| How can I enumerate filesystems from Python? | I'm using os.statvfs to find out the free space available on a volume -- in addition to querying free space for a particular path, I'd like to be able to iterate over all volumes. I'm working on Linux at the moment, but ideally would like something which returns ["/", "/boot", "home"] on Linux and ["C:\", "D:\"] on Windows.
| [
"For Linux how about parsing /etc/mtab or /proc/mounts? Or:\nimport commands\n\nmount = commands.getoutput('mount -v')\nlines = mount.split('\\n')\npoints = map(lambda line: line.split()[2], lines)\n\nprint points\n\nFor Windows I found something like this:\nimport string\nfrom ctypes import windll\n\ndef get_drive... | [
3
] | [] | [] | [
"filesystems",
"linux",
"python",
"windows"
] | stackoverflow_0003327528_filesystems_linux_python_windows.txt |
Q:
Monitor Yahoo! Instant Messages in Python?
I am trying to add some security to my computer at home and would like to have a copy of all Yahoo! IMs sent to me. I am using Python 2.6 on Windows.
I would also like to have every URL in Internet Explorer sent to me.
A:
Wireshark has custom filters for chat protocols like yahoo or to filter for all HTTP traffic. I don't know why you would want to filter only IE, its not the most common browser but you could probably filter by user agent. Wireshark can be invoked on the commandline and you can tap into these pre-built filters. You should use python's subprocess module to execute Wireshark.
| Monitor Yahoo! Instant Messages in Python? | I am trying to add some security to my computer at home and would like to have a copy of all Yahoo! IMs sent to me. I am using Python 2.6 on Windows.
I would also like to have every URL in Internet Explorer sent to me.
| [
"Wireshark has custom filters for chat protocols like yahoo or to filter for all HTTP traffic. I don't know why you would want to filter only IE, its not the most common browser but you could probably filter by user agent. Wireshark can be invoked on the commandline and you can tap into these pre-built filters. ... | [
0
] | [] | [] | [
"internet_explorer_8",
"python",
"security",
"windows",
"yahoo_messenger"
] | stackoverflow_0002893395_internet_explorer_8_python_security_windows_yahoo_messenger.txt |
Q:
Control access to parts of a system, but also to certain pieces of information
This is a tricky question, we've been talking about this for a while (days) and haven't found a convincingly good solution. This is the situation:
We have users and groups. A user can belong to many groups (many to many relation)
There are certain parts of the site that need access control, but:
There are certain ROWS of certain tables that need access control, ie. a certain user (or certain group) should not be able to delete a certain row, but other rows of the same table could have a different permission setting for that user (or group)
Is there an easy way to acomplish this? Are we missing something?
We need to implement this in python (if that's any help).
A:
This problem is not really new; it's basically the general problem of authorization and access rights/control.
In order to avoid having to model and maintain a complete graph of exactly what objects each user can access in each possible way, you have to make decisions (based on what your application does) about how to start reigning in the multiplicative scale factors. So first: where do users get their rights? If each user is individually assigned rights, you're going to pose a significant ongoig management challenge to whoever needs to add users, modify users, etc.
Perhaps users can get their rights from the groups they're members of. Now you have a scale factor that simplifies management and makes the system easier to understand. Changing a group changes the effective rights for all users who are members.
Now, what do these rights look like? It's still probably not wise to assign rights on a target object by object basis. Thus maybe rights should be thought of as a set of abstract "access cards". Objects in the system can be marked as requiring "blue" access for read, "red" access for update, and "black" access for delete. Those abstract rights might be arranged in some sort of topology, such that having "black" access means you implicitly also have "red" and "blue", or maybe they're all disjoint; it's up to you and how your application has to work. (Note also that you may want to consider that object types — tables, if you like — may need their own access rules, at least for "create".
By introducing collection points in the graph pictures you draw relating actors in the system to objects they act upon, you can handle scale issues and keep the complexity of authorization under control. It's never easy, however, and often it's the case that voiced customer desires result in something that will never work out and never in fact achieve what the customer (thinks she) wants.
The implementation language doesn't have a lot to do with the architectural decisions you need to make.
A:
1)create a table with rights, ie delete, update, etc
2)create a three way pivot table on the rights table, whatever table you want row level access for and whatever table contains the unit of access rights (either group or user).
3) check for a relationship in the pivot table before you allow the operation to proceed.
your rights table could look like:
ID RIGHT
1 DELETE
2 UPDATE
the table that you want row level access control for could look like (say a blog for example):
ID TITLE CONTENT
1 blog entry 1 This is a blog entry
2 blog entry 2 This is another blog entry
and your user table could be:
ID NAME
1 Bob
2 Alice
Then the pivot table would be like
ID USER_ID RIGHT_ID BLOG_ID
1 1 2 1
2 2 1 1
3 2 2 1
4 2 1 2
5 2 2 2
This means that Bob can only update blog entry 1 but Alice can update or delete either blog entry
EDIT: If you want a right to come from the user or the group then you need two pivot tables for each table; one for users and one for groups. You will also have to query the database to check for user level rights and group level rights before you allow or disallow an operation
EDIT2: This is more complicated than David's solution but doesn't require you to compose permission_classes ahead of time: you can mix and match whatever group level and user level permissions you want which is what it seems like you want to do.
A:
It's hard to be specific without knowing more about your setup and about why exactly you need different users to have different permissions on different rows. But generally, I would say that whenever you access any data in the database in your code, you should precede it by an authorization check, which examines the current user and group and the row being inserted/updated/deleted/etc. and decides whether the operation should be allowed or not. Consider designing your system in an encapsulated manner - for example you could put all the functions that directly access the database in one module, and make sure that each of them contains the proper authorization check. (Having them all in one file makes it less likely that you'll miss one)
It might be helpful to add a permission_class column to the table, and have another table specifying which users or groups have which permission classes. Then your authorization check simply has to take the value of the permission class for the current row, and see if the permissions table contains an association between that permission class and either the current user or any of his/her groups.
A:
Add additional column "category" or "type" to the table(s), that will categorize the rows (or if you will, group/cluster them) - and then create a pivot table that defines the access control between (rowCategory, userGroup). So for each row, by its category you can pull which userGroups have access (and what kind of access).
| Control access to parts of a system, but also to certain pieces of information | This is a tricky question, we've been talking about this for a while (days) and haven't found a convincingly good solution. This is the situation:
We have users and groups. A user can belong to many groups (many to many relation)
There are certain parts of the site that need access control, but:
There are certain ROWS of certain tables that need access control, ie. a certain user (or certain group) should not be able to delete a certain row, but other rows of the same table could have a different permission setting for that user (or group)
Is there an easy way to acomplish this? Are we missing something?
We need to implement this in python (if that's any help).
| [
"This problem is not really new; it's basically the general problem of authorization and access rights/control.\nIn order to avoid having to model and maintain a complete graph of exactly what objects each user can access in each possible way, you have to make decisions (based on what your application does) about h... | [
2,
1,
0,
0
] | [] | [] | [
"access_control",
"python"
] | stackoverflow_0003327279_access_control_python.txt |
Q:
Crossplatform method for inserting text into raw_input (to avoid readine) in Python
I have an application (CLI) which includes the feature of editing account information. It does this by asking a question and putting in the old value in the answer so that it is editable. Currently I'm using the readline module to do this. I'd like another way of doing the same thing that avoids this module (I want to allow the app to run with all features on Windows as well as GNU/Linux any operating system that python runs on).
I originally found the following code (I modified it a bit to fit into a function) at the following website but since that thread is 4 years old I figured I'd ask here. http://bytes.com/topic/python/answers/471407-default-editable-string-raw_input
import readline
def editInput(question, old_value):
readline.set_startup_hook(lambda: readline.insert_text(old_value))
try:
new_value = raw_input(question)
finally:
readline.set_startup_hook(None)
return new_value
editInput('What\'s the answer? ', '32')
UPDATE: I don't necessarily need an alternative for readline (such as PyReadline). I just need the same result. I updated the question to mention that I don't necessarily need it to run on Windows and GNU/Linux but on any OS supported by python. So basically, only use very basic functions (such as sys.stdin, etc.)
A:
Line editing functionality is far from trivial to duplicate. For example, just a functionality such as "read the next keystroke without echoing" (even before you start intepreting the meaning of that keystroke in order to reposition the cursor and alter the on-screen appearance as well as the remembered contents of the text line being edited) cannot be done simply in a cross-platform way: you need msvcrt functionality on Windows and curses functionality on Unix-y systems -- and your demand that it works on any OS supported by Python looms huge, and impossible to satisfy.
You need to delimit very strictly the set of operating systems / platforms on which it must run, and the subset of line editing functionality it must absolutely provide, before an answer can be considered. If you just can't delimit those sets, then the answer is easy: what you're asking for is, in its excessive generality, simply impossible.
A:
Why not use PyReadline? It is used by IPython for more or less the same functionality and is well supported by them.
Actually, scratch that. I have just tried it and it doesn't work. Likely, pyreadline doesn't support set_startup_hook.
| Crossplatform method for inserting text into raw_input (to avoid readine) in Python | I have an application (CLI) which includes the feature of editing account information. It does this by asking a question and putting in the old value in the answer so that it is editable. Currently I'm using the readline module to do this. I'd like another way of doing the same thing that avoids this module (I want to allow the app to run with all features on Windows as well as GNU/Linux any operating system that python runs on).
I originally found the following code (I modified it a bit to fit into a function) at the following website but since that thread is 4 years old I figured I'd ask here. http://bytes.com/topic/python/answers/471407-default-editable-string-raw_input
import readline
def editInput(question, old_value):
readline.set_startup_hook(lambda: readline.insert_text(old_value))
try:
new_value = raw_input(question)
finally:
readline.set_startup_hook(None)
return new_value
editInput('What\'s the answer? ', '32')
UPDATE: I don't necessarily need an alternative for readline (such as PyReadline). I just need the same result. I updated the question to mention that I don't necessarily need it to run on Windows and GNU/Linux but on any OS supported by python. So basically, only use very basic functions (such as sys.stdin, etc.)
| [
"Line editing functionality is far from trivial to duplicate. For example, just a functionality such as \"read the next keystroke without echoing\" (even before you start intepreting the meaning of that keystroke in order to reposition the cursor and alter the on-screen appearance as well as the remembered content... | [
1,
0
] | [] | [] | [
"python",
"readline"
] | stackoverflow_0003327524_python_readline.txt |
Q:
Django standalone run in cron
I want to run automatic newsletter function in my crontab, but no matter what I try - I cannot make it work. What is the proper method for doing this ?
This is my crontab entry :
0 */2 * * * PYTHONPATH=/home/muntu/rails python2.6 /home/muntu/rails/project/newsletter.py
And the newsletter.py file, which is located in the top folder of my django project :
#! /usr/bin/env python
import sys
import os
os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings"
from django.core.management import setup_environ
from project import settings
setup_environ(settings)
from django.template.loader import get_template, render_to_string
from django.template import Context
from django.core.mail import EmailMultiAlternatives
from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail
from django.conf import settings
from project.utilsFD.models import *
from django.http import HttpResponse, HttpResponseRedirect, Http404
def main(argv=None):
if argv is None:
argv = sys.argv
template_html = 'static/newsletter.html'
template_text = 'static/newsletter.txt'
newsletters = Newsletter.objects.filter(sent=False)
adr = NewsletterEmails.objects.all()
for a in adr:
for n in newsletters:
to = a.email
from_email = settings.DEFAULT_FROM_EMAIL
subject = _(u"Newsletter - Method #1")
text_content = render_to_string(template_text, {"title": n.title,"text": n.text, 'date': n.data, 'email': to})
html_content = render_to_string(template_html, {"title": n.title,"text": n.text, 'date': n.data, 'email': to})
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.content_subtype = "html"
msg.send()
n.sent = True
n.save()
if __name__ == '__main__':
main()
What am I doing wrong ? The function itself was working without any problems when run as django app, but when I was trying to run it from console, it gave me :
Traceback (most recent call last):
File "newsletter.py", line 7, in <module>
from project import settings
ImportError: No module named project
And it does not work from cron at all.
A:
Try changing your cron entry to:
0 */2 * * * cd /home/muntu/rails && python2.6 /home/muntu/rails/project/newsletter.py
This will ensure that the "rails" directory is in python's path. If you want to set the PYTHONPATH, then create a shell script:
#!/bin/sh
export PYTHONPATH=/home/muntu/rails
python2.6 /home/muntu/rails/project/newsletter.py
and put the shell script in the cron entry.
| Django standalone run in cron | I want to run automatic newsletter function in my crontab, but no matter what I try - I cannot make it work. What is the proper method for doing this ?
This is my crontab entry :
0 */2 * * * PYTHONPATH=/home/muntu/rails python2.6 /home/muntu/rails/project/newsletter.py
And the newsletter.py file, which is located in the top folder of my django project :
#! /usr/bin/env python
import sys
import os
os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings"
from django.core.management import setup_environ
from project import settings
setup_environ(settings)
from django.template.loader import get_template, render_to_string
from django.template import Context
from django.core.mail import EmailMultiAlternatives
from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail
from django.conf import settings
from project.utilsFD.models import *
from django.http import HttpResponse, HttpResponseRedirect, Http404
def main(argv=None):
if argv is None:
argv = sys.argv
template_html = 'static/newsletter.html'
template_text = 'static/newsletter.txt'
newsletters = Newsletter.objects.filter(sent=False)
adr = NewsletterEmails.objects.all()
for a in adr:
for n in newsletters:
to = a.email
from_email = settings.DEFAULT_FROM_EMAIL
subject = _(u"Newsletter - Method #1")
text_content = render_to_string(template_text, {"title": n.title,"text": n.text, 'date': n.data, 'email': to})
html_content = render_to_string(template_html, {"title": n.title,"text": n.text, 'date': n.data, 'email': to})
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.content_subtype = "html"
msg.send()
n.sent = True
n.save()
if __name__ == '__main__':
main()
What am I doing wrong ? The function itself was working without any problems when run as django app, but when I was trying to run it from console, it gave me :
Traceback (most recent call last):
File "newsletter.py", line 7, in <module>
from project import settings
ImportError: No module named project
And it does not work from cron at all.
| [
"Try changing your cron entry to:\n0 */2 * * * cd /home/muntu/rails && python2.6 /home/muntu/rails/project/newsletter.py\n\nThis will ensure that the \"rails\" directory is in python's path. If you want to set the PYTHONPATH, then create a shell script:\n#!/bin/sh\nexport PYTHONPATH=/home/muntu/rails\npython2.6 /h... | [
1
] | [] | [] | [
"cron",
"django",
"django_settings",
"python"
] | stackoverflow_0003327695_cron_django_django_settings_python.txt |
Q:
Python script to do a GET request on 2 urls in a cron job
I need a python script to perform a GET request on 2 urls.
I will use these scripts in a cron job on my ubuntu server.
The catch is, the 2 calls have to happen sequentially because the first GET request to Url#1 might take up to 1 minute or so to complete.
For the cron job, I want it to run every 30 minutes.
A:
I'm not sure if I'm missing something in your question. But it should be fairly simple with urllib2:
import urllib2
request = urllib2.Request('http://example.com/path')
response = urllib2.urlopen(request)
content = response.read()
# now make the second request, just as above
See the page, urllib2 The Missing Manual for more help with the urllib2 module.
A:
I suggest you read the documentation of urllib:
http://docs.python.org/library/urllib.html
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
>>> urllib.urlretrieve("http://www.google.com")
('/tmp/tmpfYqXGp', <httplib.HTTPMessage instance at 0x109c878>)
>>> urllib.urlcleanup()
>>>
| Python script to do a GET request on 2 urls in a cron job | I need a python script to perform a GET request on 2 urls.
I will use these scripts in a cron job on my ubuntu server.
The catch is, the 2 calls have to happen sequentially because the first GET request to Url#1 might take up to 1 minute or so to complete.
For the cron job, I want it to run every 30 minutes.
| [
"I'm not sure if I'm missing something in your question. But it should be fairly simple with urllib2:\nimport urllib2\n\nrequest = urllib2.Request('http://example.com/path')\nresponse = urllib2.urlopen(request)\ncontent = response.read()\n\n# now make the second request, just as above\n\nSee the page, urllib2 The ... | [
3,
0
] | [] | [] | [
"cron",
"python"
] | stackoverflow_0003327252_cron_python.txt |
Q:
Can the execution of statements in Python be delayed?
I want it to run the first line print 1 then wait 1 second to run the second command print 2, etc.
Pseudo-code:
print 1
wait(1 seconds)
print 2
wait(0.45 seconds)
print 3
wait(3 seconds)
print 4
A:
time.sleep(seconds)
import time
print 1
time.sleep(1)
print 2
time.sleep(0.45)
print 3
time.sleep(3)
print 4
A:
All the answers have assumed that you want or can manually insert time.sleep after each line, but may be you want a automated way to do that for a large number of lines of code e.g. consider this code
def func1():
print "func1 1",time.time()
print "func1 2",time.time()
def func2():
print "func2 1",time.time()
print "func2 2",time.time()
def main():
print 1,time.time()
print 2,time.time()
func1()
func2()
If you want to delay execution of each line, either you can manually insert time.sleep before each line which is cumbersome and error-prone, instead you can use sys.settrace to get you own function called before each line is executed and in that callback you can delay execution, so without manually inserting time.sleep at every place and littering code, you can do this instead
import sys
import time
def func1():
print "func1 1",time.time()
print "func1 2",time.time()
def func2():
print "func2 1",time.time()
print "func2 2",time.time()
def main():
print 1,time.time()
print 2,time.time()
func1()
func2()
def mytrace(frame, event, arg):
if event == "line":
time.sleep(1)
return mytrace
sys.settrace(mytrace)
main()
Without trace output is:
1 1280032100.88
2 1280032100.88
func1 1 1280032100.88
func1 2 1280032100.88
func2 1 1280032100.88
func2 2 1280032100.88
With trace output is:
1 1280032131.27
2 1280032132.27
func1 1 1280032134.27
func1 2 1280032135.27
func2 1 1280032137.27
func2 2 1280032138.27
You can further tweak it according to your needs, may be checking line contents too and most importantly this is very easy to disable and will work with any code.
A:
import time
# ...
time.sleep(1)
| Can the execution of statements in Python be delayed? | I want it to run the first line print 1 then wait 1 second to run the second command print 2, etc.
Pseudo-code:
print 1
wait(1 seconds)
print 2
wait(0.45 seconds)
print 3
wait(3 seconds)
print 4
| [
"time.sleep(seconds)\nimport time\n\nprint 1\ntime.sleep(1)\nprint 2\ntime.sleep(0.45)\nprint 3\ntime.sleep(3)\nprint 4\n\n",
"All the answers have assumed that you want or can manually insert time.sleep after each line, but may be you want a automated way to do that for a large number of lines of code e.g. consi... | [
47,
16,
5
] | [] | [] | [
"delay",
"python",
"sleep",
"timing"
] | stackoverflow_0003327775_delay_python_sleep_timing.txt |
Q:
Best Twitter Framework for Python on App Engine?
I'm looking to incorporate twitter API features into an app engine project that I'm working on.
I'm relatively new to both app engine and python, so I'm wondering what modules/frameworks I should use to most easily incorporate twitter, and to facilitate twitter oauth?
I've seen:
python-twitter
tipfy
gaema
A:
I heartily recomment tipfy, but, as its author @moraes just said, it is its own, little, lightweight framework -- integration with others is possible (through WSGI middleware concepts), but your life is much simpler if you stick with a single framework, and django is much richer (and, of course, much bigger and less simple -- those are two sides of the same coin;-) and very very popular.
I personally like the "very lightweight" approach of tipfy (and WSGI, and Werkzeug, on which it relies), but if you have to pick one single framework for a wide variety of uses, you could surely do much worse than going with the most popular one, that is, django (e.g. as this post suggests).
A:
python-twitter is the strongest library for a do-it-yourself approach. You implement the API in your framework of choice. It is well-maintained code.
tipfy ported the TwitterMixin from Tornado, so you don't need to care about many implementation details. It is probably easier to get something done but it is integrated to tipfy, so you can't really use it as a library for other frameworks. Auth example is here.
gaema is also ported from Tornado, but it is unmaintained.
Theres also tweetapp, but the repository says that it is also not maintained.
Other frameworks may have similar helpers (or you can use a OAuth library).
Disclaimer: I'm author of tipfy and gaema.
A:
I recommend using: Tweepy. There is an example app here: http://github.com/wasauce/tweepy-examples
Tweepy is under active development so I think it will serve you well.
A:
I'm really liking Python Twitter Tools but I haven't yet incorporated it into an App Engine app. Will be soon though. Tweepy is next on my list to checkout.
| Best Twitter Framework for Python on App Engine? | I'm looking to incorporate twitter API features into an app engine project that I'm working on.
I'm relatively new to both app engine and python, so I'm wondering what modules/frameworks I should use to most easily incorporate twitter, and to facilitate twitter oauth?
I've seen:
python-twitter
tipfy
gaema
| [
"I heartily recomment tipfy, but, as its author @moraes just said, it is its own, little, lightweight framework -- integration with others is possible (through WSGI middleware concepts), but your life is much simpler if you stick with a single framework, and django is much richer (and, of course, much bigger and le... | [
4,
3,
3,
1
] | [] | [] | [
"google_app_engine",
"python",
"twitter"
] | stackoverflow_0003325935_google_app_engine_python_twitter.txt |
Q:
Using Ruby, Perl, or Python, how to "Move the window 'Firefox' to coordinate (0,0) on screen and resize it 1024 x 768"?
Can it be moved by Window Title as well as exe name?
Other info on moving it in another language could be helpful.
Update: some Perl sample can be found in Win32::GuiTest but there seems to be no resize or move functions.
A:
Win32::API and MoveWindow. See also How do you programmatically resize and move windows with the Windows API?.
A:
Here's a way to do it in Ruby using win32-api:
# example.rb
require 'win32/api'
include Win32
FindWindow = API.new('FindWindow', 'PP', 'L', 'user32')
hWnd = FindWindow.call(nil, "firefox")
if (hWnd == 0)
puts "firefox not found"
exit 1
end
MoveWindow = API.new('MoveWindow', 'LIIIII', 'I', 'user32')
ret = MoveWindow.call(hWnd, 0, 0, 1024, 768, true)
if (ret == 0)
puts "MoveWindow failed"
exit 1
end
puts "success"
This only works if the window is called "firefox" exactly (not case-sensitive from when I tested). Since it is likely to be titled differently (e.g., "Google - Mozilla Firefox"), you'll probably want to use EnumWindows to enumerate through all windows and find the one you're looking for.
| Using Ruby, Perl, or Python, how to "Move the window 'Firefox' to coordinate (0,0) on screen and resize it 1024 x 768"? | Can it be moved by Window Title as well as exe name?
Other info on moving it in another language could be helpful.
Update: some Perl sample can be found in Win32::GuiTest but there seems to be no resize or move functions.
| [
"Win32::API and MoveWindow. See also How do you programmatically resize and move windows with the Windows API?.\n",
"Here's a way to do it in Ruby using win32-api:\n# example.rb\nrequire 'win32/api'\ninclude Win32\n\nFindWindow = API.new('FindWindow', 'PP', 'L', 'user32')\nhWnd = FindWindow.call(nil, \"firefox\")... | [
3,
2
] | [] | [] | [
"perl",
"python",
"ruby",
"winapi"
] | stackoverflow_0003323672_perl_python_ruby_winapi.txt |
Q:
Django forms, saving non-user submitted data
class SomeModel(models.Model):
text = models.TextField()
ip = models.IPAddressField()
created_on = models.DateTimeField()
updated_on = models.DateTimeField()
Say I have that as a model, what if I wanted to only display 'text' field widget for the user to submit data, but I obviously wouldn't want the user to see the widgets for ip,created_on, updated_on to be changed. Yes I know I can add it as a hidden field for the form, but that's not what I'm looking for.
I'm more wondering how can I not render those fields at all when rendering my form, and just dynamically populating the fields when a form is posted and pass form validation? I'm guessing to somehow override the blank values of ip,created_on,updated_on while the form is being cleaned/validated. I know how to do this in the view by using request.POST.copy and injected my values, but I'd like to know if it's possible in models or forms.
A:
Two things:
First ModelForms:
Class SomeModelForm(ModelForm):
class Meta:
exclude = ['ip','created_on', 'updated_on']
Two Model Fields API:
class SomeModel(models.Model):
text = models.TextField()
ip = models.IPAddressField()
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
Three:
For ip, i think you should to that in your views.
| Django forms, saving non-user submitted data | class SomeModel(models.Model):
text = models.TextField()
ip = models.IPAddressField()
created_on = models.DateTimeField()
updated_on = models.DateTimeField()
Say I have that as a model, what if I wanted to only display 'text' field widget for the user to submit data, but I obviously wouldn't want the user to see the widgets for ip,created_on, updated_on to be changed. Yes I know I can add it as a hidden field for the form, but that's not what I'm looking for.
I'm more wondering how can I not render those fields at all when rendering my form, and just dynamically populating the fields when a form is posted and pass form validation? I'm guessing to somehow override the blank values of ip,created_on,updated_on while the form is being cleaned/validated. I know how to do this in the view by using request.POST.copy and injected my values, but I'd like to know if it's possible in models or forms.
| [
"Two things:\nFirst ModelForms: \nClass SomeModelForm(ModelForm):\n class Meta:\n exclude = ['ip','created_on', 'updated_on']\n\nTwo Model Fields API:\nclass SomeModel(models.Model):\n text = models.TextField()\n ip = models.IPAddressField()\n created_on = models.DateTimeField(auto_now_add=True)\n ... | [
2
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0003328212_django_forms_python.txt |
Q:
Python operator precedence
The Python docs say that * and / have the same precedence.
I know that expressions in python are evaluated from left to right.
Can i rely on that and assume that j*j/m is always equal to (j*j)/m
avoiding the parentheses?
If this is the case can i assume that this holds for operators with the same precedence in general?
ps: The question as it is fine for my purposes,
i came to it while reading integer-only code (like the above example) without parentheses,
which at the time looked a lot suspicious to me.
A:
Yes - different operators with the same precedence are left-associative; that is, the two leftmost items will be operated on, then the result and the 3rd item, and so on.
An exception is the ** operator:
>>> 2 ** 2 ** 3
256
Also, comparison operators (==, >, et cetera) don't behave in an associative manner, but instead translate x [cmp] y [cmp] z into (x [cmp] y) and (y [cmp] z).
A:
But, if it is ambiguous to you - the coder - and it must be because you have to ask, then expect it will be at least as ambiguous for the reader and waste a couple octets for clarity.
Relying on precedence rules is great if you happen to be a compiler.
added responses to comments:
For the person reading code who encounters an ambiguity that requires outside consultation for assurance, you should assume that the next reader will be less savvy than you and save them the effort and avoidable human error of parsing the same construct and add the parenthesis for them.
As it happens, even the accepted answer was incorrect (in rationale, not effect, see its first comment) which I wasn't aware of and neither were a fraction of those who upvoted it.
As to the statement about basic algebra, the particular example used in the OP is instructive. Regardless of operator precedence the expression j * (j / m) is algebraically identical to (j * j) / m. Unfortunately, Python algebra is only an approximation of "Platonic ideal" algebra which could yield incorrect answers for either form depending on the magnitudes of j and m. For example:
>>> m = 1e306
>>> m
1e+306
>>> j = 1e307
>>> j
9.9999999999999999e+306
>>> j / m
10.0
>>> j*j
inf
>>> j * (j / m)
1e+308
>>> (j * j) / m
inf
>>> ((j * j) / m) == (j * (j/m))
False
So indeed the identity property of Python's (and my FPU) quasi-algebra doesn't hold. And this may be different on your machine for as the documentation notes:
Floating point numbers are implemented
using double in C. All bets on their
precision are off unless you happen to
know the machine you are working with.
It could be claimed that one has no business working on the hairy edge of overflow, and that's true to some extent, but removed from context the expression is indeterminate given one order of operations and "correct" under another.
A:
Short answer: yes.
The Python documentation says the following:
Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for comparisons, including tests, which all have the same precedence and chain from left to right... and exponentiation, which groups from right to left).
So in other words the answer to your question is yes, operators with the same precedence will group left to right apart from Comparisions which chain rather than group:
>>> x = 0
>>> y = 0
>>> x == y == True
False
>>> (x == y) == True
True
>>> x == (y == True)
True
and Exponentation:
>>> 2 ** 2 ** 3
256
>>> (2 ** 2) ** 3
64
>>> 2 ** (2 ** 3)
256
Also, in assignment the right-hand side is evaluated before the left-hand side:
>>> x = 1
>>> y = x = 2
>>> y
2
| Python operator precedence | The Python docs say that * and / have the same precedence.
I know that expressions in python are evaluated from left to right.
Can i rely on that and assume that j*j/m is always equal to (j*j)/m
avoiding the parentheses?
If this is the case can i assume that this holds for operators with the same precedence in general?
ps: The question as it is fine for my purposes,
i came to it while reading integer-only code (like the above example) without parentheses,
which at the time looked a lot suspicious to me.
| [
"Yes - different operators with the same precedence are left-associative; that is, the two leftmost items will be operated on, then the result and the 3rd item, and so on.\nAn exception is the ** operator:\n>>> 2 ** 2 ** 3\n256\n\nAlso, comparison operators (==, >, et cetera) don't behave in an associative manner, ... | [
14,
14,
3
] | [] | [] | [
"expression",
"operator_precedence",
"python"
] | stackoverflow_0003328355_expression_operator_precedence_python.txt |
Q:
Yielding until all needed values are yielded, is there way to make slice to become lazy
Is there way to stop yielding when generator did not finish values and all needed results have been read? I mean that generator is giving values without ever doing StopIteration.
For example, this never stops: (REVISED)
from random import randint
def devtrue():
while True:
yield True
answers=[False for _ in range(randint(100,100000))]
answers[::randint(3,19)]=devtrue()
print answers
I found this code, but do not yet understand, how to apply it in this case:
http://code.activestate.com/recipes/576585-lazy-recursive-generator-function/
A:
You can call close() on the generator object. This way, a GeneratorExit exception is raised within the generator and further calls to its next() method will raise StopIteration:
>>> def test():
... while True:
... yield True
...
>>> gen = test()
>>> gen
<generator object test at ...>
>>> gen.next()
True
>>> gen.close()
>>> gen.next()
Traceback (most recent call last):
...
StopIteration
A:
As you have already seen,
TypeError: 'generator' object is unsubscriptable
And the way you have written devtrue it shouldn't stop. If you need that capacity you could:
def bounded_true(count)
while count > 0:
yield True
count -= 1
or far more simply:
y = [True] * 5
If you make an infinite generator, it will generate infinitely.
A:
This is best I came up with, but it does still the slicing twice to find the length and need to convert string number from splitting to int:
from time import clock
from random import randint
a=[True for _ in range(randint(1000000,10000000))]
spacing=randint(3,101)
t=clock()
try:
a[::spacing]=[False]
except ValueError as e:
a[::spacing]=[False]*int(e.message.rsplit(' ',1)[-1])
print spacing,clock()-t
# baseline
t=clock()
a[::spacing]=[False]*len(a[::spacing])
print 'Baseline:',spacing,clock()-t
I will try it to my prime sieve, but it is likely not to be faster than doing the length arithmetic from recurrence formula.
Improving pure Python prime sieve by recurrence formula
A:
In analogy with the take function in Haskell, you can build a 'limited' generator based upon another generator:
def take(n,gen):
'''borrowed concept from functional languages'''
togo=n
while togo > 0:
yield gen.next()
togo = togo - 1
def naturalnumbers():
''' an unlimited series of numbers '''
i=0
while True:
yield i
i=i+1
for n in take(10, naturalnumbers() ):
print n
You can further this idea with an "until" generator, a "while", ...
def gen_until( condition, gen ):
g=gen.next()
while( not condition(g) ):
yield g
g=gen.next()
And use it like
for i in gen_until( lambda x: x*x>100, naturalnumbers() ):
print i
...
| Yielding until all needed values are yielded, is there way to make slice to become lazy | Is there way to stop yielding when generator did not finish values and all needed results have been read? I mean that generator is giving values without ever doing StopIteration.
For example, this never stops: (REVISED)
from random import randint
def devtrue():
while True:
yield True
answers=[False for _ in range(randint(100,100000))]
answers[::randint(3,19)]=devtrue()
print answers
I found this code, but do not yet understand, how to apply it in this case:
http://code.activestate.com/recipes/576585-lazy-recursive-generator-function/
| [
"You can call close() on the generator object. This way, a GeneratorExit exception is raised within the generator and further calls to its next() method will raise StopIteration:\n>>> def test():\n... while True:\n... yield True\n... \n>>> gen = test()\n>>> gen\n<generator object test at ...>\n>>> gen.n... | [
8,
0,
0,
0
] | [] | [] | [
"generator",
"lazy_sequences",
"python",
"slice",
"variable_assignment"
] | stackoverflow_0003324947_generator_lazy_sequences_python_slice_variable_assignment.txt |
Q:
Quick & dirt CRUD interface to SQLAlchemy?
I'm researching software components to use in a future development of a business logic web application. It's gonna be written in Python and we are targeting SQLAlchemy as ORM. The app will be used by other software apps via a REST-like interface over http, possibly using web.py for that part.
For debugging, maintenance, etc we need to directly access the MySQL database but phpmyadmin is too low-level for standard tasks given the rich structure of the db modeled by SQLAlchemy, so I'm looking around for an easy CRUD interface that follows our SA models. It could be a webapp or a local (X11 or whatever) app, and should take as little time as possible to implement.
So far after some googling I've found Camelot (Qt App) and RUM (WSGI webapp).
Camelot is based over Elixir, and if we use it in our project too we should be able to share the model definition between our app and Camelot, just adding some camelot specific stuff here and there and we should end up having a Qt interface with little effort.
RUM on the other end seems to be based on declarative, and we should probably base our app on that too to leverage RUM. It's not yet clear to me how much effort should be added to get a working web interface using RUM.
I'd like to know if anyone has experience with Camelot and/or RUM to share, and if using one of the two implies the need to use its declarative layer (either Elixir or, well, declarative) to be able to share the model code without reimplementing it.
Also any other recommendation to get a CRUD interface will be really welcome.
A:
although the Camelot examples are based on Elixir, Camelot is not tied to Elixir, so you could as well use declarative to define your model. In fact Camelot can be used to display plain old python objects as well.
| Quick & dirt CRUD interface to SQLAlchemy? | I'm researching software components to use in a future development of a business logic web application. It's gonna be written in Python and we are targeting SQLAlchemy as ORM. The app will be used by other software apps via a REST-like interface over http, possibly using web.py for that part.
For debugging, maintenance, etc we need to directly access the MySQL database but phpmyadmin is too low-level for standard tasks given the rich structure of the db modeled by SQLAlchemy, so I'm looking around for an easy CRUD interface that follows our SA models. It could be a webapp or a local (X11 or whatever) app, and should take as little time as possible to implement.
So far after some googling I've found Camelot (Qt App) and RUM (WSGI webapp).
Camelot is based over Elixir, and if we use it in our project too we should be able to share the model definition between our app and Camelot, just adding some camelot specific stuff here and there and we should end up having a Qt interface with little effort.
RUM on the other end seems to be based on declarative, and we should probably base our app on that too to leverage RUM. It's not yet clear to me how much effort should be added to get a working web interface using RUM.
I'd like to know if anyone has experience with Camelot and/or RUM to share, and if using one of the two implies the need to use its declarative layer (either Elixir or, well, declarative) to be able to share the model code without reimplementing it.
Also any other recommendation to get a CRUD interface will be really welcome.
| [
"although the Camelot examples are based on Elixir, Camelot is not tied to Elixir, so you could as well use declarative to define your model. In fact Camelot can be used to display plain old python objects as well.\n"
] | [
1
] | [] | [] | [
"crud",
"python",
"sqlalchemy"
] | stackoverflow_0003150739_crud_python_sqlalchemy.txt |
Q:
Puzzle that defies the brute force approach?
I bought a blank DVD to record my favorite TV show. It came with 20 digit stickers. 2 of each of '0'-'9'.
I thought it would be a good idea to numerically label my new DVD collection. I taped the '1' sticker on my first recorded DVD and put the 19 leftover stickers in a drawer.
The next day I bought another blank DVD (receiving 20 new stickers with it) and after recording the show I labeled it '2'.
And then I started wondering: when will the stickers run out and I will no longer be able to label a DVD?
A few lines of Python, no?
Can you provide code that solves this problem with a reasonable run-time?
Edit: The brute force will simply take too long to run. Please improve your algorithm so your code will return the right answer in, say, a minute?
Extra credit: What if the DVDs came with 3 stickers of each digit?
A:
This is old solution, completely new 6 bajillion times faster solution is on the bottom.
Solution:
time { python solution.py; }
0: 0
1: 199990
2: 1999919999999980
3: 19999199999999919999999970
4: 199991999999999199999999919999999960
5: 1999919999999991999999999199999999919999999950
6: 19999199999999919999999991999999999199999999919999999940
7: 199991999999999199999999919999999991999999999199999999919999999930
8: 1999919999999991999999999199999999919999999991999999999199999999919999999920
9: 19999199999999919999999991999999999199999999919999999991999999999199999999919999999918
real 1m53.493s
user 1m53.183s
sys 0m0.036s
Code:
OPTIMIZE_1 = True # we assum that '1' will run out first (It's easy to prove anyway)
if OPTIMIZE_1:
NUMBERS = [1]
else:
NUMBERS = range(10)
def how_many_have(dight, n, stickers):
return stickers * n
cache = {}
def how_many_used(dight, n):
if (dight, n) in cache:
return cache[(dight,n)]
result = 0
if dight == "0":
if OPTIMIZE_1:
return 0
else:
assert(False)
#TODO
else:
if int(n) >= 10:
if n[0] == dight:
result += int(n[1:]) + 1
result += how_many_used(dight, str(int(n[1:])))
result += how_many_used(dight, str(int(str(int(n[0])-1) + "9"*(len(n) - 1))))
else:
result += 1 if n >= dight else 0
if n.endswith("9" * (len(n)-4)): # '4' constant was pick out based on preformence tests
cache[(dight, n)] = result
return result
def best_jump(i, stickers_left):
no_of_dights = len(str(i))
return max(1, min(
stickers_left / no_of_dights,
10 ** no_of_dights - i - 1,
))
def solve(stickers):
i = 0
stickers_left = 0
while stickers_left >= 0:
i += best_jump(i, stickers_left)
stickers_left = min(map(
lambda x: how_many_have(x, i, stickers) - how_many_used(str(x), str(i)),
NUMBERS
))
return i - 1
for stickers in range(10):
print '%d: %d' % (stickers, solve(stickers))
Prove that '1' will run out first:
def(number, position):
""" when number[position] is const, this function is injection """
if number[position] > "1":
return (position, number[:position]+"1"+number[position+1:])
else:
return (position, str(int(number[:position])-1)+"1"+number[position+1:])
A:
Here is proof that a solution exists:
Assuming you ever get to 21 digit numbers, you will start losing a sticker with every DVD you purchase and label ((+20) + (-21)).
It doesn't matter how many stickers you have accumulated until this point. From here on it is all downhill for your sticker stash and you will eventually run out.
A:
here's a quick and dirty python script:
#!/bin/env python
disc = 0
stickers = {
0: 0, 1: 0,
2: 0, 3: 0,
4: 0, 5: 0,
6: 0, 7: 0,
8: 0, 9: 0 }
def buyDisc():
global disc
disc += 1
for k in stickers.keys():
stickers[k] += 1
def labelDisc():
lbl = str(disc)
for c in lbl:
if(stickers[int(c)] <= 0): return False;
stickers[int(c)] -= 1;
return True
while True:
buyDisc()
if not labelDisc(): break
print("No stickers left after " + str(disc) + " discs.")
print("Remaining stickers: " + str(stickers))
i don't know if it yields the correct result though. if you find logical errors, please comment
result with debug output:
Bought disc 199991. Labels:
Remaining stickers: {0: 111102, 1: 0, 2: 99992, 3: 99992, 4: 99992, 5: 99997, 6: 99992, 7: 99992, 8: 99992, 9: 100024}
A:
Completely new solution. 6 bajillion times faster than first one.
time { python clean.py ; }
0: 0
1: 199990
2: 1999919999999980
3: 19999199999999919999999970
4: 199991999999999199999999919999999960
5: 1999919999999991999999999199999999919999999950
6: 19999199999999919999999991999999999199999999919999999940
7: 199991999999999199999999919999999991999999999199999999919999999930
8: 1999919999999991999999999199999999919999999991999999999199999999919999999920
9: 19999199999999919999999991999999999199999999919999999991999999999199999999919999999918
real 0m0.777s
user 0m0.772s
sys 0m0.004s
code:
cache = {}
def how_many_used(n):
if n in cache:
return cache[n]
result = 0
if int(n) >= 10:
if n[0] == '1':
result += int(n[1:]) + 1
result += how_many_used(str(int(n[1:])))
result += how_many_used(str(int(str(int(n[0])-1) + "9"*(len(n) - 1))))
else:
result += 1 if n >= '1' else 0
if n.endswith("9" * (len(n)-0)) or n.endswith("0" * (len(n)-1)):
cache[n] = result
return result
def how_many_have(i, stickers):
return int(i) * stickers
def end_state(i, stickers):
if i == '':
return 0
return how_many_have(i, stickers) - how_many_used(i)
cache2 = {}
def lowest_state(i, stickers):
if stickers <= 0:
return end_state(i, stickers)
if i in ('', '0'):
return 0
if (i, stickers) in cache2:
return cache2[(i, stickers)]
lowest_candidats = []
tail9 = '9' * (len(i)-1)
if i[0] == '1':
tail = str(int('0'+i[1:]))
lowest_candidats.append(end_state(str(10**(len(i) - 1)), stickers))
lowest_candidats.append(lowest_state(tail, stickers - 1) + end_state(str(10**(len(i) - 1)), stickers))
else:
tail = str(int(i[0])-1) + tail9
series = end_state(tail9, stickers)
if series < 0:
lowest_candidats.append(lowest_state(str(int('0'+i[1:])), stickers) + end_state(i[0] + '0'*(len(i)-1), stickers))
lowest_candidats.append(lowest_state(tail, stickers))
result = min(lowest_candidats)
cache2[(i, stickers)] = result
return result
def solve(stickers):
i=1
while lowest_state(str(i), stickers) >= 0:
i *= 2
top = i
bottom = 0
center = 0
while top - bottom > 1:
center = (top + bottom) / 2
if lowest_state(str(center), stickers) >= 0:
bottom = center
else:
top = center
if lowest_state(str(top), stickers) >= 0:
return top
else:
return bottom
import sys
sys.setrecursionlimit(sys.getrecursionlimit() * 10)
for i in xrange(10):
print "%d: %d" % (i, solve(i))
A:
The results for any base N and number of stickers per digit per DVD "S" are:
N\S ] 1 | 2 | 3 | 4 | 5 | S?
===================================================================
2 ] 2 | 14 | 62 | 254 | 1022 | 4^S - 2
----+--------+----------+------------+-----------+------+----------
3 ] 12 | 363 | 9840 | 265719 | (27^S - 3)/2
----+--------+----------+------------+-----------+-----------------
4 ] 28 | 7672 | 1965558 | 503184885 |
----+--------+----------+------------+-----------+
5 ] 181 | 571865 | 1787099985 |
----+--------+----------+------------+
6 ] 426 | 19968756 |
----+--------+----------+
7 ] 3930 | (≥ 2^31) |
----+--------+----------+
8 ] 8184 |
----+--------+
9 ] 102780 |
----+--------+
10 ] 199990 |
----+--------+
I can't see any patterns.
Alternatively, if the sticker starts from 0 instead of 1,
N\S ] 1 | 2 | 3 | 4 | 5 | S?
======================================================================
2 ] 4 | 20 | 84 | 340 | 1364 | (4^S-1)*4/3
----+---------+----------+------------+-----------+------+------------
3 ] 12 | 363 | 9840 | 265719 | (27^S - 3)/2
----+---------+----------+------------+-----------+-------------------
4 ] 84 | 7764 | 1965652 | 503184980 |
----+---------+----------+------------+-----------+
5 ] 182 | 571875 | 1787100182 |
----+---------+----------+------------+
6 ] 1728 | 19970496 |
----+---------+----------+
7 ] 3931 | (≥ 2^31) |
----+---------+----------+
8 ] 49152 |
----+---------+
9 ] 102789 |
----+---------+
10 ] 1600000 |
----+---------+
Let's assume that it's the “1” sticker running out first — which is indeed the case for most other computed info.
Suppose we are in base N and there will be S new stickers per digit per DVD.
At DVD #X, there will be totally X×S “1” stickers, used or not.
The number of “1” stickers used is just the number of “1” in the digits from 1 to X in base N expansion.
Thus we just need to find the cross-over point of X×S and the total “1” digit count.
N = 2: 1,2,4,5,7,9,12,13,15,17,20,22,25,28,32,33,35,37,40,42,45,48,52,54,57,…
N = 3: 1,1,2,4,5,5,6,6,7,9,10,12,15,17,18,20,21,21,22,22,23,25,26,26,27,…
N = 10: 1,1,1,1,1,1,1,1,1,2,4,5,6,7,8,9,10,11,12,12,13,13,13,13,13,…
there does not seem to be a closed for all these sequences, so a loop proportional X iterations is necessary. The digits can be extracted in log X time, so in principle the algorithm can finish in O(X log X) time.
This is no better than the other algorithm but at least a lot computations can be removed. A sample C code:
#include <stdio.h>
static inline int ones_in_digit(int X, int N) {
int res = 0;
while (X) {
if (X % N == 1)
++ res;
X /= N;
}
return res;
}
int main() {
int N, S, X;
printf("Base N? ");
scanf("%d", &N);
printf("Stickers? ");
scanf("%d", &S);
int count_of_1 = 0;
X = 0;
do {
++ X;
count_of_1 += S - ones_in_digit(X, N);
if (X % 10000000 == 0)
printf("%d -> %d\n", X/10000000, count_of_1);
} while (count_of_1 >= 0);
printf("%d\n", X-1);
return 0;
}
A:
Here's some thoughts on the upper bound demonstrated by @Tal Weiss:
The first 21-digit number is 10^20, at which point we will have at most 20 * 10^20 stickers. Each subsequent DVD will then cost us at least 1 net sticker, so we will definitely have run out by 10^20 + 20 * 10^20, which equals 21 * 10^20. This is therefore an upper bound on the solution. (Not a particularly tight upper bound by any means! But one that's easy to establish).
Generalising the above result to base b:
each DVD comes with 2b stickers
the first DVD that costs us 1 net sticker is number b ^ (2b), at which point we will have at most 2b . b ^ (2b) stickers
so we will definitely run out by b ^ (2b) + 2b . [b ^ (2b)], which equals (2b + 1)[b ^ (2b)]
So for example if we work in base 3, this calculation gives an upper bound of 5103; in base 4, it is 589824. These are numbers it is going to be far easier to brute-force / mathematically solve with.
| Puzzle that defies the brute force approach? | I bought a blank DVD to record my favorite TV show. It came with 20 digit stickers. 2 of each of '0'-'9'.
I thought it would be a good idea to numerically label my new DVD collection. I taped the '1' sticker on my first recorded DVD and put the 19 leftover stickers in a drawer.
The next day I bought another blank DVD (receiving 20 new stickers with it) and after recording the show I labeled it '2'.
And then I started wondering: when will the stickers run out and I will no longer be able to label a DVD?
A few lines of Python, no?
Can you provide code that solves this problem with a reasonable run-time?
Edit: The brute force will simply take too long to run. Please improve your algorithm so your code will return the right answer in, say, a minute?
Extra credit: What if the DVDs came with 3 stickers of each digit?
| [
"This is old solution, completely new 6 bajillion times faster solution is on the bottom.\nSolution:\ntime { python solution.py; } \n0: 0\n1: 199990\n2: 1999919999999980\n3: 19999199999999919999999970\n4: 199991999999999199999999919999999960\n5: 1999919999999991999999999199999999919999999950\n6: 1999919999999991999... | [
7,
6,
2,
2,
1,
1
] | [] | [] | [
"math",
"puzzle",
"python"
] | stackoverflow_0003324306_math_puzzle_python.txt |
Q:
Cannot access members of UserProperty in code
I'm new to Google Apps and I've been messing around with the hello world app that is listed on the google app site. Once I finished the app, I decided to try to expand on it. The first thing I added was a feature to allow the filtering of the guestbook posts by the user that submitted them.
All I have changed/added is simply a handler to the WSGIApplication and a new class for this handler. The model is the same, I'll post for reference:
class Greeting(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline = True)
date = db.DateTimeProperty(auto_now_add=True)
Using the Django template I changed the line that displays the authors nickname from:
<b>{{ greeting.author.nickname }}</b> wrote:
to:
<a href="/authorposts/{{ greeting.author.user_id }}">
{{ greeting.author.nickname }}
</a></b> wrote:
The issue I'm having is that inside my python code I cannot access "greeting.author.nickname", or any of the other properties, such as "user_id". However they are accessible from the Django template, as the code I listed above for the template works and correctly creates a link to the author as well as displaying the nickname.
I am using URL Mapping based on the authors (a UserProperty) property "user_id". I am trying to find a way that I can filter the datastore using the user_id as the criteria. I've tried directly applying a filter to the query, I've tried pulling all the records and then iterating through them and use an If...Else clause.
I know the value is store into the datastore, because the Django template shows it, what do I have to do to use it as filter criteria?
A:
When querying the Greeting model, you cannot filter on fields within Greeting.author (e.g., greeting.author.nickname). In SQL, this would be done by doing a join on the Greeting and User tables. However, in GAE you can only query properties directly included on the model you are querying.
Since author is a db.UserProperty, you can filter by user like this:
# fetch up to 10 greetings by the current user
user = users.get_current_user()
results = Greeting.all().filter('author =', user).fetch(10)
To filter on other fields within author, you would need to denormalize your Greeting model - i.e., add copies of fields in author which you want to be able to filter Greeting on. For example, if you wanted to filter by author.nickname, you would add an author_nickname field to your Greeting model (and keep its value up to date with author.nickname):
class Greeting(db.Model):
author = db.UserProperty()
author_nickname = db.StringProperty() # denormalization (copy of author.nickname)
content = db.StringProperty(multiline = True)
date = db.DateTimeProperty(auto_now_add=True)
If you add this sort of denormalization to your model, it might be helpful to use Nick Johnson's aetycoon library to make author_nickname update whenever author is updated (just so you don't have to manually enforce that relationship).
| Cannot access members of UserProperty in code | I'm new to Google Apps and I've been messing around with the hello world app that is listed on the google app site. Once I finished the app, I decided to try to expand on it. The first thing I added was a feature to allow the filtering of the guestbook posts by the user that submitted them.
All I have changed/added is simply a handler to the WSGIApplication and a new class for this handler. The model is the same, I'll post for reference:
class Greeting(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline = True)
date = db.DateTimeProperty(auto_now_add=True)
Using the Django template I changed the line that displays the authors nickname from:
<b>{{ greeting.author.nickname }}</b> wrote:
to:
<a href="/authorposts/{{ greeting.author.user_id }}">
{{ greeting.author.nickname }}
</a></b> wrote:
The issue I'm having is that inside my python code I cannot access "greeting.author.nickname", or any of the other properties, such as "user_id". However they are accessible from the Django template, as the code I listed above for the template works and correctly creates a link to the author as well as displaying the nickname.
I am using URL Mapping based on the authors (a UserProperty) property "user_id". I am trying to find a way that I can filter the datastore using the user_id as the criteria. I've tried directly applying a filter to the query, I've tried pulling all the records and then iterating through them and use an If...Else clause.
I know the value is store into the datastore, because the Django template shows it, what do I have to do to use it as filter criteria?
| [
"When querying the Greeting model, you cannot filter on fields within Greeting.author (e.g., greeting.author.nickname). In SQL, this would be done by doing a join on the Greeting and User tables. However, in GAE you can only query properties directly included on the model you are querying.\nSince author is a db.U... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003327958_google_app_engine_python.txt |
Q:
Python Sorting Question
i need to sort the following list of Tuples in Python:
ListOfTuples = [('10', '2010 Jan 1;', 'Rapoport AM', 'Role of antiepileptic drugs as preventive agents for migraine', '20030417'), ('21', '2009 Nov;', 'Johannessen SI', 'Antiepilepticdrugs in epilepsy and other disorders--a population-based study of prescriptions', '19679449'),...]
My purpose is to order it by Descending year (listOfTuples[2]) and by Ascending Author (listOfTuples[2]):
sorted(result, key = lambda item: (item[1], item[2]))
But it doesn't work. How can i obtain sort stability?
A:
def descyear_ascauth(atup):
datestr = atup[1]
authstr = atup[2]
year = int(datestr.split(None, 1)[0])
return -year, authstr
... sorted(result, key=descyear_ascauth) ...
Notes: you need to extract the year as an integer (not as a string), so that you can change its sign -- the latter being the key trick in order to satisfy the "descending" part of the specifications. Squeezing it all within a lambda would be possible, but there's absolutely no reason to do so and sacrifice even more readability, when a def will work just as well (and far more readably).
A:
The easiest way is to sort on each key value separately. Start at the least significant key and work your way up to the most significant.
So in this case:
import operator
ListOfTuples.sort(key=operator.itemgetter(2))
ListOfTuples.sort(key=lambda x: x[1][:4], reverse=True)
This works because Python's sorting is always stable even when you use the reverse flag: i.e. reverse doesn't just sort and then reverse (which would lose stability, it preserves stability after reversing.
Of course if you have a lot of key columns this can be inefficient as it does a full sort several times.
You don't have to convert the year to a number this way as its a genuine reverse sort, though you could if you wanted.
A:
Here is a idiom that works for everything, even thing you can't negate, for example strings:
data = [ ('a', 'a'), ('a', 'b'), ('b','a') ]
def sort_func( a, b ):
# compare tuples with the 2nd entry switched
# this inverts the sorting on the 2nd entry
return cmp( (a[0], b[1]), (b[0], a[1]) )
print sorted( data ) # [('a', 'a'), ('a', 'b'), ('b', 'a')]
print sorted( data, cmp=sort_func ) # [('a', 'b'), ('a', 'a'), ('b', 'a')]
A:
Here's a rough solution that takes month abbreviature and day (if found) in account:
import time
import operator
def sortkey(seq):
strdate, author = seq[1], seq[2]
spdate = strdate[:-1].split()
month = time.strptime(spdate[1], "%b").tm_mon
date = [int(spdate[0]), month] + map(int, spdate[2:])
return map(operator.neg, date), author
print sorted(result, key=sortkey)
"%b" is locale's abbreviated month name, you can use a dictionary if you prefer not to deal with locales.
A:
Here is the lambda version of Alex's answer. I think it looks more compact than Duncan's answer now, but obviously a lot of the readability of Alex's answer has been lost.
sorted(ListOfTuples, key=lambda atup: (-int(atup[1].split(None, 1)[0]), atup[2]))
Readability and efficiency should usually be preferred to compactness.
| Python Sorting Question | i need to sort the following list of Tuples in Python:
ListOfTuples = [('10', '2010 Jan 1;', 'Rapoport AM', 'Role of antiepileptic drugs as preventive agents for migraine', '20030417'), ('21', '2009 Nov;', 'Johannessen SI', 'Antiepilepticdrugs in epilepsy and other disorders--a population-based study of prescriptions', '19679449'),...]
My purpose is to order it by Descending year (listOfTuples[2]) and by Ascending Author (listOfTuples[2]):
sorted(result, key = lambda item: (item[1], item[2]))
But it doesn't work. How can i obtain sort stability?
| [
"def descyear_ascauth(atup):\n datestr = atup[1]\n authstr = atup[2]\n year = int(datestr.split(None, 1)[0])\n return -year, authstr\n\n... sorted(result, key=descyear_ascauth) ...\n\nNotes: you need to extract the year as an integer (not as a string), so that you can change its sign -- the latter being the key... | [
4,
2,
0,
0,
0
] | [] | [] | [
"list",
"python",
"sorting",
"stability"
] | stackoverflow_0003325574_list_python_sorting_stability.txt |
Q:
How to create partial download in twisted?
How do you create multiple HTTPDownloader instance with partial download asynchronously? and does it assemble the file automatically after all download is done?
A:
You must use Range HTTP header:
Range. Request only part of an entity.
Bytes are numbered from 0. Range:
bytes=500-999
Ie. If you want download 1000 file in 4 parts, you will starts 4 downloads:
0-2499
2500-4999
5000-7499
7500-9999
And then simply join data from responses.
To check file size you can use HEAD method:
HEAD Asks for the response identical
to the one that would correspond to a
GET request, but without the response
body. This is useful for retrieving
meta-information written in response
headers, without having to transport
the entire content.
| How to create partial download in twisted? | How do you create multiple HTTPDownloader instance with partial download asynchronously? and does it assemble the file automatically after all download is done?
| [
"You must use Range HTTP header:\n\nRange. Request only part of an entity.\n Bytes are numbered from 0. Range:\n bytes=500-999\n\nIe. If you want download 1000 file in 4 parts, you will starts 4 downloads:\n\n0-2499\n2500-4999\n5000-7499\n7500-9999\n\nAnd then simply join data from responses.\nTo check file si... | [
3
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003328059_python_twisted.txt |
Q:
Extracting semantic/stylistic features from text
I would like to know of open source tools (for java/python) which could help me extract semantic & stylistic features from text. Examples of semantic features would be adjective-noun ratio, a particular sequence of part-of-speech tags (adjective followed by a noun: adj|nn) etc. Examples of stylistic features would be number of unique words, number of pronouns etc. Currently, I know only of Word to Web Tools which converts a block of text into the rudimentary vector space model.
I am aware of few text-mining packages like GATE, NLTK , Rapid Miner, Mallet and MinorThird . However, I couldn't find any mechanism to suit my task.
Regards, --Denzil
A:
I think that the Stanford Parser is one of the best and comprehensive NLP tools available for free: not only will it allow you to parse the structural dependencies (to count nouns/adjectives) but it will also give you the grammatical dependencies in the sentence (so you can extract the subject, object, etc). The latter component is something that Python libraries simply cannot do yet (see Does NLTK have a tool for dependency parsing?) and is probably going to be the most important feature in regards to your software's ability to work with semantics.
If you're interested in Java and Python tools, then Jython is probably the most fun to use for you. I was in the exact same boat, so I wrote this post about using Jython to run the example code provided in the Stanford Parser - I would give it a glance and see what you think: http://blog.gnucom.cc/2010/using-the-stanford-parser-with-jython/
Edit: After reading one of your comments I learned you need to parse 29 Million sentences. I think you could benefit greatly by using pure Java to combine two really powerful technologies: Stanford Parser + Hadoop. Both are written purely in Java and have an extremely rich API that you can use to parse vasts amount of data in a fraction of the time on a cluster of machines. If you don't have the machines, you can use Amazon's EC2 cluster. If you need an example of using Stanford Parser + Hadoop leave a comment for me, and I'll update the post with a URL to my example.
A:
If your text is mostly natural language (in English), you try to extract phrases using a part-of-speech (POS) tagger. Monty tagger is a pure python POS tagger.
I've got very satisfactory performance out of a C++ POS tagger, such as the CRFTagger http://sourceforge.net/projects/crftagger/. I tied it to Python using subprocess.Popen. The POS tags allow you to keep only the important pieces of a sentence: nouns and verbs, for example, which can then be indexed using any indexing tools such as Lucene or Xapian (my favourite).
A:
I use Lucene's analyzers and indexing mechanism to build vector spaces for documents and then navigate in this space. You can construct term frequency vectors for documents, use an existing document to search other similar documents in the vector space. If your data is big (millions of documents, tens of thousand of features) then you could like Lucene. You can also do stemming, pos tagging and other stuff. This blog post might be a good starting point for POS tagging. In short, Lucene provides you all the necessary mechanism to implement the tasks you mentioned.
One library that I hear frequently is Semantic Vectors. It's again built on Lucene but I don't have a direct experience with that one. Other than this, I suggest to look at Wikipedia's Vector Space Model article.
A:
I used NLTK for some NLP (Natural Language Processing) tasks and it worked really well (albeit kind of slowly). Why exactly do you want such a structured representation of your text? (true question, as depending on the application sometimes much simpler representations can be better)
A:
Here's a compilation of Java NLP tools that's reasonably up-to-date:
http://www.searchenginecaffe.com/2007/03/java-open-source-text-mining-and.html
LingPipe (http://alias-i.com/lingpipe/) hasn't been mentioned in the answers yet, and is an excellent & actively developed toolkit.
A:
One of the brilliant libraries I got hold off: http://code.google.com/p/textmatrix/
| Extracting semantic/stylistic features from text | I would like to know of open source tools (for java/python) which could help me extract semantic & stylistic features from text. Examples of semantic features would be adjective-noun ratio, a particular sequence of part-of-speech tags (adjective followed by a noun: adj|nn) etc. Examples of stylistic features would be number of unique words, number of pronouns etc. Currently, I know only of Word to Web Tools which converts a block of text into the rudimentary vector space model.
I am aware of few text-mining packages like GATE, NLTK , Rapid Miner, Mallet and MinorThird . However, I couldn't find any mechanism to suit my task.
Regards, --Denzil
| [
"I think that the Stanford Parser is one of the best and comprehensive NLP tools available for free: not only will it allow you to parse the structural dependencies (to count nouns/adjectives) but it will also give you the grammatical dependencies in the sentence (so you can extract the subject, object, etc). The ... | [
3,
2,
1,
1,
1,
0
] | [] | [] | [
"java",
"machine_learning",
"python"
] | stackoverflow_0003109773_java_machine_learning_python.txt |
Q:
position contents of array.array into heap
I have a simple byte array I've filled with a x86 -program. Which I need to execute at runtime.
"""
Produces a simple callable procedure which returns a constant.
"""
from array import array
simple = array('B')
# mov rax, 0x10
simple.extend((0x81, 0xc0, 0x10, 0x0, 0x0, 0x0))
# ret
simple.append(0xc3)
Now, to get this running, I'll need to offload it into a memory region in my process that has PROT_EXEC flags. Also need to know the address of that memory region so I can call it. How could I do what I just described?
from ctypes import CFUNCTYPE, c_int
procedure = CFUNCTYPE(c_int)(program.address)
print "result correct: %r" % (procedure() == 0x10)
print "result: %r" % procedure()
Also, it might be useful to do this:
program[2] = 15
print "result correct: %r" % (procedure() == 15)
print "result: %r" % procedure()
A:
I solved this on my own. Maybe there's not much to say into it anyway.
I did a library for this. It's a small wrapping around linux mmap -command.
mmap module provided by python weren't sufficient. I couldn't get the address out of an object. Instead I had to provide my own module for just doing that.
# -*- coding: utf-8 -*-
from ctypes import (
pythonapi, c_void_p, c_size_t, c_int, c_uint64,
c_byte, cast, POINTER, memmove, string_at,
)
import errno
mmap = pythonapi.mmap
mmap.restype = c_void_p
mmap.argtypes = [c_void_p, c_size_t, c_int, c_int, c_int, c_uint64]
munmap = pythonapi.munmap
munmap.restype = c_int
munmap.argtypes = [c_void_p, c_size_t]
errno_location = pythonapi.__errno_location
errno_location.restype = POINTER(c_int)
errormessage = lambda: errno.errorcode[errno_location()[0]]
PROT_NONE = 0
PROT_READ = 1
PROT_WRITE = 2
PROT_EXEC = 4
MAP_SHARED = 1
MAP_PRIVATE = 2
MAP_ANONYMOUS = 0x20
class RawData(object):
"Allocated with mmap -call, no file handles."
def __init__(self, length, prot):
flags = MAP_PRIVATE | MAP_ANONYMOUS
self.address = mmap(None, length, prot, flags, -1, 0)
if 0 == self.address:
raise Exception(errormessage())
self.__length = length
self.__accessor = cast(self.address, POINTER(c_byte))
def __len__(self):
return self.__length
def __getitem__(self, key):
assert key < len(self)
return self.__accessor[key]
def __setitem__(self, key, value):
assert key < len(self)
self.__accessor[key] = value
def close(self):
"the mapped memory must be freed manually"
if 0 != munmap(self.address, len(self)):
raise Exception(errormessage())
def poke(self, offset, data):
"poke data (from a tuple) into requested offset"
for i, byte in enumerate(data):
self[offset+i] = byte
def upload(self, data, offset=0):
"upload the data from a string"
data = data.tostring()
assert offset+len(data) <= len(self)
memmove(self.address+offset, data, len(data))
def tostring(self):
return string_at(self.address, len(self))
__all__ = [
'PROT_NONE',
'PROT_READ',
'PROT_WRITE',
'PROT_EXEC',
'RawData',
]
I also wrote an utility library for little-endian integers which supplements the toolchain:
# -*- coding: utf-8 -*-
TWOPOWER32 = 1 << 32
TWOPOWER64 = 1 << 64
TWOPOWER31 = TWOPOWER32 >> 1
TWOPOWER63 = TWOPOWER64 >> 1
def uint32(value):
assert 0 <= value < TWOPOWER32
return (
value >> 0 & 255,
value >> 8 & 255,
value >> 16 & 255,
value >> 24 & 255
)
def uint64(value):
assert 0 <= value < TWOPOWER64
return (
value >> 0 & 255,
value >> 8 & 255,
value >> 16 & 255,
value >> 24 & 255,
value >> 32 & 255,
value >> 40 & 255,
value >> 48 & 255,
value >> 56 & 255
)
def int32(value):
assert -TWOPOWER31 <= value < TWOPOWER31
return uint32((TWOPOWER32 + value) & (TWOPOWER32-1))
def int64(value):
assert -TWOPOWER63 <= value < TWOPOWER63
return uint64((TWOPOWER64 + value) & (TWOPOWER64-1))
__all__ = ['uint32', 'int32', 'uint64', 'int64']
It's simple stuff. Here's some usage example:
from ctypes import CFUNCTYPE, c_int
from array import array
#... bunch of imports
simple = array('B')
# x86 and x64 machine code (MOV eax, 0x10; RET)
simple.extend((0x81, 0xc0) + int32(0x10))
simple.append(0xc3)
program = RawData(len(simple), PROT_READ|PROT_WRITE|PROT_EXEC)
program.upload(simple)
procedure = CFUNCTYPE(c_int)(program.address)
print "result:", procedure()
# alters the first instruction
program.poke(2, int32(123))
print "result:", procedure()
# transforms that first instruction into (NOP,NOP,NOP,NOP,NOP,NOP)
program.poke(0, [0x90]*6)
print "result:", procedure()
I think I'll have fun with it. http://hg.boxbase.org/ will eventually host this module.
I'm Using opcode and instruction references to select instructions. Here's few such references:
http://sandpile.org/
http://ref.x86asm.net/
| position contents of array.array into heap | I have a simple byte array I've filled with a x86 -program. Which I need to execute at runtime.
"""
Produces a simple callable procedure which returns a constant.
"""
from array import array
simple = array('B')
# mov rax, 0x10
simple.extend((0x81, 0xc0, 0x10, 0x0, 0x0, 0x0))
# ret
simple.append(0xc3)
Now, to get this running, I'll need to offload it into a memory region in my process that has PROT_EXEC flags. Also need to know the address of that memory region so I can call it. How could I do what I just described?
from ctypes import CFUNCTYPE, c_int
procedure = CFUNCTYPE(c_int)(program.address)
print "result correct: %r" % (procedure() == 0x10)
print "result: %r" % procedure()
Also, it might be useful to do this:
program[2] = 15
print "result correct: %r" % (procedure() == 15)
print "result: %r" % procedure()
| [
"I solved this on my own. Maybe there's not much to say into it anyway.\nI did a library for this. It's a small wrapping around linux mmap -command.\nmmap module provided by python weren't sufficient. I couldn't get the address out of an object. Instead I had to provide my own module for just doing that.\n# -*- cod... | [
1
] | [] | [] | [
"ctypes",
"memory",
"python"
] | stackoverflow_0003294333_ctypes_memory_python.txt |
Q:
Need some ideas on how to code my log parser
I have a VPS that's hosting multiple virtual hosts. Each host has it's own access.log and error.log. Currently, there's no log rotation setup, though, this may change.
Basically, I want to parse these logs to monitor bandwidth and collect stats.
My idea was to write a parser and save the information to a small sqlite database. The script will run every 5 minutes and use Python's seek and tell methods to open the log files from the last parsed locations. This prevents me from parsing a 10GB log file every 5 minutes when all I need is the new information sitting at the end of it (no log rotation, remember?).
After some thought, I realised that all I'm doing is taking the information from the log files and putting them into a database... Moving the data from one location to another :/
So how else can I do this?
I want to be able to do something like:
python logparse.py --show=bandwidth --between-dates=25,05|30,05 --vhost=test.com
This would open the log file for test.com and show me the bandwidth used for the specified 5 days.
Now, my question is, how do I prevent myself from parsing 10GB worth of data when I only want 5 days worth of data?
If I were to use my idea of saving the log data to a database every 5 minutes, I could just save a unix timestamp of the dates and pull out the data between them. Easy. But I'd prefer to parse the log file directly.
A:
Unless you create different log files for each day, you have no way other than to parse on request the whole log.
I would still use a database to hold the log data, but with your desired time-unit resolution (eg. hold the bandwidth at a day / hour interval). Another advantage in using a database is that you can make range queries, like the one you give in your example, very easily and fast. Whenever you have old data that you don't need any more you can delete it from the database to save up space.
Also, you don't need to parse the whole file each time. You could monitor the writes to the file with the help of pyinotify whenever a line is written you could update the counters in the database. Or you can store the last position in the file whenever you read from it and read from that position the next time. Be careful when the file is truncated.
To sum it up:
hold your data in the database at day resolution (eg. the bandwith for each day)
use pyinotify to monitor the writes to the log file so that you don't read the whole file over and over again
If you don't want to code your own solution, take a look at Webalizer, AWStats or pick a tool from this list.
EDIT:
WebLog Expert also looks promising. Take a look of one of the reports.
A:
Pulling just the required 5 days of data from a large logfile comes down to finding the right starting offset to seek() the file to before you begin parsing.
You could find that position each time using a binary search through the file: seek() to os.stat(filename).st_size / 2, call readline() once (discarding the result) to skip to the end of the current line, then do two more readline()s. If the first of those lines is before your desired starting time, and the second is after it, then your starting offset is tell() - len(second_line). Otherwise, do the standard binary search algorithm. (I'm ignoring the corner cases where the line you're looking for is the first or last or not in the file at all, but those are easy to add)
Once you have your starting offset, you just keep parsing lines from there until you reach one that's newer than the range you're interested in.
This will be much faster than parsing the whole logfile each time, of course, but if you're going to be doing a lot of these queries, then a database probably is worth the extra complexity. If the size of the database is a concern, you could go for a hybrid approach where the database is an index to the log file. For example, you could store the just the byte-offset of the start of each day in the database. If you don't want to update the database every 5 minutes, you could have logparse.py update it with new data each time it runs.
After all that, though, as Pierre and the_void have said, do make sure you're not reinventing the wheel -- you're not the first person ever to need bandwidth statistics :-)
A:
Save the last position
When you have finished with the parsing of a log file, save the position in a table of your database that reference both the full file path and the position. When you run the parser 5 minutes after, you query the database for the log your are going to parse, retrieve the position and start from there.
Save the first line of data
When you have log rotation, add an additionnal key in the database that will contain the first line of the log file. So when you start with a file, first read the first line. When you query the database, you have then to check on the first line and not on the file name.
First line should be unique, always, since you have the timestamp. But don't forget that W3C compliant log file usually write headers at the beginning of the file. So the first line should be the first line of data.
Save the data you need only
When parsing W3C, it's very easy to read the bytes sent. Parsing will be very fast if you keep that information only. The store it in your database, either by updating an existing row in your database, or adding a new row with a timestamp that you can aggregate with others later in a query.
Don't reinvent the wheel
Unless what you are doing is very specific, I recommand you to grab an open source parser on the web. http://awstats.sourceforge.net/
| Need some ideas on how to code my log parser | I have a VPS that's hosting multiple virtual hosts. Each host has it's own access.log and error.log. Currently, there's no log rotation setup, though, this may change.
Basically, I want to parse these logs to monitor bandwidth and collect stats.
My idea was to write a parser and save the information to a small sqlite database. The script will run every 5 minutes and use Python's seek and tell methods to open the log files from the last parsed locations. This prevents me from parsing a 10GB log file every 5 minutes when all I need is the new information sitting at the end of it (no log rotation, remember?).
After some thought, I realised that all I'm doing is taking the information from the log files and putting them into a database... Moving the data from one location to another :/
So how else can I do this?
I want to be able to do something like:
python logparse.py --show=bandwidth --between-dates=25,05|30,05 --vhost=test.com
This would open the log file for test.com and show me the bandwidth used for the specified 5 days.
Now, my question is, how do I prevent myself from parsing 10GB worth of data when I only want 5 days worth of data?
If I were to use my idea of saving the log data to a database every 5 minutes, I could just save a unix timestamp of the dates and pull out the data between them. Easy. But I'd prefer to parse the log file directly.
| [
"Unless you create different log files for each day, you have no way other than to parse on request the whole log.\nI would still use a database to hold the log data, but with your desired time-unit resolution (eg. hold the bandwidth at a day / hour interval). Another advantage in using a database is that you can m... | [
2,
1,
0
] | [] | [] | [
"logging",
"parsing",
"python"
] | stackoverflow_0003328688_logging_parsing_python.txt |
Q:
Two arguments in one def?
First, here's my code:
import poplib
def con(pwd):
M = poplib.POP3_SSL('pop3.live.com', 995)
try:
M.user(pwd)
M.pass_('!@#$%^')
except:
print "[-]Not Found!:",pwd
else:
print '[+]Found password'
exit()
f = open("Str1k3r.txt", "r")
for pwd in f.readlines():
con(pwd.replace("\r", "").replace("\n", ""))
I want have two argument in con definition, so it would be like con(pwd,cod) and M.pass_(cod), but it's doesn't work. How can I do this?
A:
Assuming, the file "Str1k3r.txt" contains username and password in the first two lines, what you want to do is the following:
import poplib
def con(pwd, cod):
M = poplib.POP3_SSL('pop3.live.com', 995)
try:
M.user(pwd)
M.pass_(cod)
except:
print "[-]Not Found!:",pwd
else:
print '[+]Found password'
exit()
f = open("Str1k3r.txt", "r")
lines = f.readlines()
pwd = lines[0].rstrip('\r\n')
cod = lines[1].rstrip('\r\n')
con(pwd, cod)
EDIT:
Although that sounds like you're doing some kind of dictionary attack, but I'll assume, that you simply forgot your password ;)
So your bottom lines should look like this:
f = open("Str1k3r.txt", "r")
lines = f.readlines()
pwd = lines[0].rstrip('\r\n')
dictfile = open("pass.txt", "r")
for password in dictfile:
con(pwd, password.rstrip('\r\n'))
A:
am thinking about
that
import poplib
def con(pwd):
M = poplib.POP3_SSL('pop3.live.com', 995)
try:
M.user(pwd)
M.pass_(here how i can put four passwords ?)
except:
print "[-]Not Found!:",pwd
else:
print '[+]Found password'
exit()
f = open("Str1k3r.txt", "r")
for pwd in f.readlines():
con(pwd.replace("\r", "").replace("\n", ""))
am thinking put in M.pass_ like that M.pass_(123456 or 'abcdefj' or '=q-2oq2' )
but it's nor active as well i mean he try only 123456 no thing else
| Two arguments in one def? | First, here's my code:
import poplib
def con(pwd):
M = poplib.POP3_SSL('pop3.live.com', 995)
try:
M.user(pwd)
M.pass_('!@#$%^')
except:
print "[-]Not Found!:",pwd
else:
print '[+]Found password'
exit()
f = open("Str1k3r.txt", "r")
for pwd in f.readlines():
con(pwd.replace("\r", "").replace("\n", ""))
I want have two argument in con definition, so it would be like con(pwd,cod) and M.pass_(cod), but it's doesn't work. How can I do this?
| [
"Assuming, the file \"Str1k3r.txt\" contains username and password in the first two lines, what you want to do is the following:\nimport poplib\ndef con(pwd, cod):\n M = poplib.POP3_SSL('pop3.live.com', 995) \n try:\n M.user(pwd)\n M.pass_(cod)\n except:\n print \"[-]Not Found!:\",pwd\... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003328749_python.txt |
Q:
django and netbeans?
I use netbeans for all of my Linux development (C/C++, Php, Python, Symfony). I am now learning django, and wondered if I could use netbeans as the IDE. I cant seem to find a Django plugin for netbeans.
Is there one?. If no when is one planned?
Worst case scenario, I'll have to use another IDE (I really dont want to learn another IDE) - But, If so, what do you guys use for django development?
A:
There is Python and Django support from the built-in Python plug-in (in short simply get any NetBeans 6.9 or more recent, go to menu Update... > Search "Python" > Install).
There is also a NetBeans-Django additional project going on but pretty dead for a while.
A:
Currently, NetBeans support for Django is limited. The last posting that I could find, from 1 January 2010 and says that Django support is coming in NetBeans 7.0. I wouldn't be surprised if a few Python improvements in support of this make it into 6.10 due out in August 2010, but 7.0, due for 2010Q4 or 2011Q1, should have some Django support. If it's half as good as Ruby on Rails support, it'll be slick.
A:
Netbeans doesn't have a django plugin that I know of. Eclipse's pydev plugin is decent, I typically use any ol' editor and bpython.
I've heard great things about wingware and intellij's new python ide is pretty good.
| django and netbeans? | I use netbeans for all of my Linux development (C/C++, Php, Python, Symfony). I am now learning django, and wondered if I could use netbeans as the IDE. I cant seem to find a Django plugin for netbeans.
Is there one?. If no when is one planned?
Worst case scenario, I'll have to use another IDE (I really dont want to learn another IDE) - But, If so, what do you guys use for django development?
| [
"There is Python and Django support from the built-in Python plug-in (in short simply get any NetBeans 6.9 or more recent, go to menu Update... > Search \"Python\" > Install).\nThere is also a NetBeans-Django additional project going on but pretty dead for a while.\n",
"Currently, NetBeans support for Django is ... | [
9,
3,
0
] | [] | [] | [
"django",
"ide",
"netbeans",
"python"
] | stackoverflow_0002971309_django_ide_netbeans_python.txt |
Q:
IRC bot functionalities
I'm learning Python and would like to start a small project. It seems that making IRC bots is a popular project amongst beginners so I thought I would implement one. Obviously, there are core functionalities like being able to connect to a server and join a channel but what are some good functionalities that are usually included in the bots? Thanks for your ideas.
A:
Unless it's solely for the educational experience, you should really just use a framework for the core functionality.
That said, here's some of the things the bot in my home IRC channel does:
Choose one item from a list of options
Display a random entry from the Linux fortunes file
Display a random set of words from the Emacs spook file
Check every line from a user and display a quote from The Big Lebowski if it's sufficiently similar (this is probably a bit my-channel specific :) )
Check if a link has been mentioned before and say who/when (we all read the same RSS feeds and tend to duplicate links a lot)
Conduct a poll
Pull a given quote from our internal QDB
Check if a given link has been posted to Reddit, and give the corresponding Reddit thread link if so. If a Reddit link is posted, give the direct link instead
Track the last time a given nick was in the channel, and the last time they spoke
Queue a message for an offline nick that's automatically sent in-channel when they join
Use Google Translate to translate a given phrase
Post a given line to our channel's Twitter feed
Choose a random user and kick them (not the best idea depending on how unruly your channel is)
Pull the summary of a given term from Wikipedia and display it along with a link to the full article
Display information about any posted Youtube link (video title, length, submitter, votes, comments, etc.)
A:
I'm also in the process of writing a bot in node.js. Here are some of my goals/functions:
map '@' command so the bot detects the last URI in message history and uses the w3 html validation service
setup a trivia game by invoking !ask, asks a question with 3 hints, have the ability to load custom questions based on category
get the weather with weather [zip/name]
hook up jseval command to evaluate javascript, same for python and perl and haskell
seen command that reports the last time the bot has "seen" a person online
translate command to translate X language string to Y language string
map dict to a dictionary service
map wik to wiki service
A:
Again, this is an utterly personal suggestion, but I would really like to see eggdrop rewritten in Python.
Such a project could use Twisted to provide the base IRC interaction, but would then need to support add-on scripts.
This would be great for allowing easy IRC bot functionality to be built upon using python, instead of TCL, scripts.
A:
That is very subjective and totally depends upon where the bot will be used. I'm sure others will have nice suggestions. But whatever you do, please do not query users arbitrarily. And do not spam the main chat periodically.
A:
Make a google search to get a library that implements IRC protocol for you. That way you only need to add the features, those are already something enough to bother you.
Common functions:
Conduct a search from a wiki or google
Notify people on project/issue updates
Leave a message
Toy for spamming the channel
Pick a topic
Categorize messages
Search from channel logs
| IRC bot functionalities | I'm learning Python and would like to start a small project. It seems that making IRC bots is a popular project amongst beginners so I thought I would implement one. Obviously, there are core functionalities like being able to connect to a server and join a channel but what are some good functionalities that are usually included in the bots? Thanks for your ideas.
| [
"Unless it's solely for the educational experience, you should really just use a framework for the core functionality.\nThat said, here's some of the things the bot in my home IRC channel does:\n\nChoose one item from a list of options\nDisplay a random entry from the Linux fortunes file\nDisplay a random set of wo... | [
2,
1,
1,
0,
0
] | [] | [] | [
"irc",
"python"
] | stackoverflow_0003328315_irc_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.