title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
python long running daemon job processor | 1,107,826 | <p>I want to write a long running process (linux daemon) that serves two purposes:</p>
<ul>
<li>responds to REST web requests</li>
<li>executes jobs which can be scheduled </li>
</ul>
<p>I originally had it working as a simple program that would run through runs and do the updates which I then cronâd, but now I have the added REST requirement, and would also like to change the frequency of some jobs, but not others (letâs say all jobs have different frequencies). </p>
<p>I have 0 experience writing long running processes, especially ones that do things on their own, rather than responding to requests.</p>
<p>My basic plan is to run the REST part in a separate thread/process, and figured Iâd run the jobs part separately.</p>
<p>Iâm wondering if there exists any patterns, specifically python, (Iâve looked and havenât really found any examples of what I want to do) or if anyone has any suggestions on where to begin with transitioning my project to meet these new requirements.
Iâve seen a few projects that touch on scheduling, but Iâm really looking for real world user experience / suggestions here. What works / doesnât work for you?</p>
| 2 | 2009-07-10T05:16:44Z | 1,108,019 | <p>The usual design pattern for a scheduler would be:</p>
<ul>
<li>Maintain a list of scheduled jobs, sorted by next-run-time (as Date-Time value);</li>
<li>When woken up, compare the first job in the list with the current time. If it's due or overdue, remove it from the list and run it. Continue working your way through the list this way until the first job is not due yet, then go to sleep for (next_job_due_date - current_time);</li>
<li>When a job finishes running, re-schedule it if appropriate;</li>
<li>After adding a job to the schedule, wake up the scheduler process.</li>
</ul>
<p>Tweak as appropriate for your situation (eg. sometimes you might want to re-schedule jobs to run again at the point that they start running rather than finish).</p>
| 0 | 2009-07-10T06:36:49Z | [
"python",
"web-services",
"scheduling",
"long-running-processes"
] |
python long running daemon job processor | 1,107,826 | <p>I want to write a long running process (linux daemon) that serves two purposes:</p>
<ul>
<li>responds to REST web requests</li>
<li>executes jobs which can be scheduled </li>
</ul>
<p>I originally had it working as a simple program that would run through runs and do the updates which I then cronâd, but now I have the added REST requirement, and would also like to change the frequency of some jobs, but not others (letâs say all jobs have different frequencies). </p>
<p>I have 0 experience writing long running processes, especially ones that do things on their own, rather than responding to requests.</p>
<p>My basic plan is to run the REST part in a separate thread/process, and figured Iâd run the jobs part separately.</p>
<p>Iâm wondering if there exists any patterns, specifically python, (Iâve looked and havenât really found any examples of what I want to do) or if anyone has any suggestions on where to begin with transitioning my project to meet these new requirements.
Iâve seen a few projects that touch on scheduling, but Iâm really looking for real world user experience / suggestions here. What works / doesnât work for you?</p>
| 2 | 2009-07-10T05:16:44Z | 1,108,243 | <ul>
<li><p>If the REST server and the scheduled jobs have nothing in common, do two separate implementations, the REST server and the jobs stuff, and run them as separate processes.</p></li>
<li><p>As mentioned previously, look into existing schedulers for the jobs stuff. I don't know if <a href="http://twistedmatrix.com/trac/" rel="nofollow" title="Twisted">Twisted</a> would be an alternative, but you might want to check this platform.</p></li>
<li><p>If, OTOH, the REST interface invokes the same functionality as the scheduled jobs do, you should try to look at them as two interfaces to the same functionality, e.g. like this:</p>
<ul>
<li>Write the actual jobs as programs the REST server can fork and run.</li>
<li>Have a separate scheduler that handles the timing of the jobs.</li>
<li>If a job is due to run, let the scheduler issue a corresponding REST request to the local server.
This way the scheduler only handles job descriptions, but has no own knowledge how they are implemented.</li>
</ul></li>
<li><p>It's a common trait for long-running, high-availability processes to have an additional "supervisor" process that just checks the necessary demons are up and running, and restarts them as necessary.</p></li>
</ul>
| 2 | 2009-07-10T07:45:54Z | [
"python",
"web-services",
"scheduling",
"long-running-processes"
] |
python long running daemon job processor | 1,107,826 | <p>I want to write a long running process (linux daemon) that serves two purposes:</p>
<ul>
<li>responds to REST web requests</li>
<li>executes jobs which can be scheduled </li>
</ul>
<p>I originally had it working as a simple program that would run through runs and do the updates which I then cronâd, but now I have the added REST requirement, and would also like to change the frequency of some jobs, but not others (letâs say all jobs have different frequencies). </p>
<p>I have 0 experience writing long running processes, especially ones that do things on their own, rather than responding to requests.</p>
<p>My basic plan is to run the REST part in a separate thread/process, and figured Iâd run the jobs part separately.</p>
<p>Iâm wondering if there exists any patterns, specifically python, (Iâve looked and havenât really found any examples of what I want to do) or if anyone has any suggestions on where to begin with transitioning my project to meet these new requirements.
Iâve seen a few projects that touch on scheduling, but Iâm really looking for real world user experience / suggestions here. What works / doesnât work for you?</p>
| 2 | 2009-07-10T05:16:44Z | 1,108,777 | <p>Here's what we did.</p>
<ol>
<li><p>Wrote a simple, pure-wsgi web application to respond to REST requests.</p>
<ul>
<li><p>Start jobs</p></li>
<li><p>Report status of jobs</p></li>
</ul></li>
<li><p>Extended the built-in <a href="http://docs.python.org/library/wsgiref.html" rel="nofollow">wsgiref</a> server to use the <a href="http://docs.python.org/library/select.html" rel="nofollow">select</a> module to check for incoming requests.</p>
<ul>
<li><p>Activity on the socket is ordinary REST request, we let the wsgiref handle this.
It will -- eventually -- call our WSGI applications to respond to status and
submit requests.</p></li>
<li><p>Timeout means that we have to do two things:</p>
<ul>
<li><p>Check all children that are running to see if they're done. Update their status, etc.</p></li>
<li><p>Check a crontab-like schedule to see if there's any scheduled work to do. This is a SQLite database that this server maintains.</p></li>
</ul></li>
</ul></li>
</ol>
| 1 | 2009-07-10T10:16:47Z | [
"python",
"web-services",
"scheduling",
"long-running-processes"
] |
Looking for testing/QA idea for Python Web Application Project | 1,107,858 | <p>I have the 'luck' of develop and enhance a legacy python web application for almost 2 years. The major contribution I consider I made is the introduction of the use of unit test, nosestest, pychecker and CI server. Yes, that's right, there are still project out there that has no single unit test (To be fair, it has a few doctest, but are broken).</p>
<p>Nonetheless, progress is slow, because literally the coverage is limited by how many unit tests you can afford to write. </p>
<p>From time to time embarrassing mistakes still occur, and it does not look good on management reports. (e.g. even pychecker cannot catch certain "missing attribute" situation, and the program just blows up in run time)</p>
<p>I just want to know if anyone has any suggestion about what additional thing I can do to improve the QA. The application uses WebWare 0.8.1, but I have expermentially ported it to cherrypy, so I can potentially take advantage of WSGI to conduct integration tests. </p>
<p>Mixed language development and/or hiring an additional tester are also options I am thinking.</p>
<p>Nothing is too wild, as long as it works.</p>
| 1 | 2009-07-10T05:29:02Z | 1,107,890 | <p>Feather's <a href="http://rads.stackoverflow.com/amzn/click/0131177052" rel="nofollow">great book</a> is the first resource I always recommend to anybody in your situation (wish I had it in hand before I faced it my first four times or so!-) -- not Python specific but a lot of VERY useful general-purpose pieces of advice.</p>
<p>Another technique I've been happy with is <a href="http://en.wikipedia.org/wiki/Fuzz%5Ftesting" rel="nofollow">fuzz testing</a> -- low-effort, great returns in terms of catching sundry bugs and vulnerabilitues; check it out!</p>
<p>Last but not least, if you do have the headcount & budget to hire one more engineer, please do, but make sure he or she is a "software engineer in testing", NOT a warm body banging at the keyboard or mouse for manual "testing" -- somebody who's rarin' to write and integrate all sorts of <em>automated</em> testing approaches as opposed to spending their days endlessly repeating (if they're lucky) the same manual testing sequences!!!</p>
<p>I'm not sure what you think mixed language dev't will buy you in terms of QA. WSGI OTOH <em>will</em> give you nice bottlenecks/hooks to exploit in your forthcoming integration-test infrastructure -- it's good for that (AND for sundry other things too;-).</p>
| 2 | 2009-07-10T05:44:14Z | [
"python",
"testing",
"integration-testing"
] |
Looking for testing/QA idea for Python Web Application Project | 1,107,858 | <p>I have the 'luck' of develop and enhance a legacy python web application for almost 2 years. The major contribution I consider I made is the introduction of the use of unit test, nosestest, pychecker and CI server. Yes, that's right, there are still project out there that has no single unit test (To be fair, it has a few doctest, but are broken).</p>
<p>Nonetheless, progress is slow, because literally the coverage is limited by how many unit tests you can afford to write. </p>
<p>From time to time embarrassing mistakes still occur, and it does not look good on management reports. (e.g. even pychecker cannot catch certain "missing attribute" situation, and the program just blows up in run time)</p>
<p>I just want to know if anyone has any suggestion about what additional thing I can do to improve the QA. The application uses WebWare 0.8.1, but I have expermentially ported it to cherrypy, so I can potentially take advantage of WSGI to conduct integration tests. </p>
<p>Mixed language development and/or hiring an additional tester are also options I am thinking.</p>
<p>Nothing is too wild, as long as it works.</p>
| 1 | 2009-07-10T05:29:02Z | 1,108,333 | <p>Automated testing seems to be as a very interesting approach. If you are developping a web app, you may be interested in WebDriver <a href="http://code.google.com/p/webdriver/" rel="nofollow">http://code.google.com/p/webdriver/</a></p>
| 1 | 2009-07-10T08:10:53Z | [
"python",
"testing",
"integration-testing"
] |
Looking for testing/QA idea for Python Web Application Project | 1,107,858 | <p>I have the 'luck' of develop and enhance a legacy python web application for almost 2 years. The major contribution I consider I made is the introduction of the use of unit test, nosestest, pychecker and CI server. Yes, that's right, there are still project out there that has no single unit test (To be fair, it has a few doctest, but are broken).</p>
<p>Nonetheless, progress is slow, because literally the coverage is limited by how many unit tests you can afford to write. </p>
<p>From time to time embarrassing mistakes still occur, and it does not look good on management reports. (e.g. even pychecker cannot catch certain "missing attribute" situation, and the program just blows up in run time)</p>
<p>I just want to know if anyone has any suggestion about what additional thing I can do to improve the QA. The application uses WebWare 0.8.1, but I have expermentially ported it to cherrypy, so I can potentially take advantage of WSGI to conduct integration tests. </p>
<p>Mixed language development and/or hiring an additional tester are also options I am thinking.</p>
<p>Nothing is too wild, as long as it works.</p>
| 1 | 2009-07-10T05:29:02Z | 1,108,346 | <p>Since it is a web app, I'm wondering whether browser-based testing would make sense for you. If so, check out <a href="http://seleniumhq.org/" rel="nofollow" title="Selenium">Selenium</a>, an open-source suite of test tools. Here are some items that might be interesting to you:</p>
<ul>
<li>automatically starts and stops browser instances on major platforms (linux, win32, macos)</li>
<li>tests by emulating user actions on web pages (clicking, typing), Javascript based</li>
<li>uses assertions for behavioral results (new web page loaded, containing text, ...)</li>
<li>can record interactive tests in firefox</li>
<li>can be driven by Python test scripts, using a simple communication API and running against a coordination server (Selenium RC).</li>
<li>can run multiple browsers on the same machine or multiple machines</li>
</ul>
<p>It has a learning curve, but particularly the Selenium RC server architecture is very helpful in conducting automated browser tests.</p>
| 1 | 2009-07-10T08:14:03Z | [
"python",
"testing",
"integration-testing"
] |
Looking for testing/QA idea for Python Web Application Project | 1,107,858 | <p>I have the 'luck' of develop and enhance a legacy python web application for almost 2 years. The major contribution I consider I made is the introduction of the use of unit test, nosestest, pychecker and CI server. Yes, that's right, there are still project out there that has no single unit test (To be fair, it has a few doctest, but are broken).</p>
<p>Nonetheless, progress is slow, because literally the coverage is limited by how many unit tests you can afford to write. </p>
<p>From time to time embarrassing mistakes still occur, and it does not look good on management reports. (e.g. even pychecker cannot catch certain "missing attribute" situation, and the program just blows up in run time)</p>
<p>I just want to know if anyone has any suggestion about what additional thing I can do to improve the QA. The application uses WebWare 0.8.1, but I have expermentially ported it to cherrypy, so I can potentially take advantage of WSGI to conduct integration tests. </p>
<p>Mixed language development and/or hiring an additional tester are also options I am thinking.</p>
<p>Nothing is too wild, as long as it works.</p>
| 1 | 2009-07-10T05:29:02Z | 1,108,352 | <p>Have a look at <a href="http://twill.idyll.org/" rel="nofollow">Twill</a>, it's a headless web browser written in Python, specifically for automated testing. It can record and replay actions, and it can also hook directly into a WSGI stack.</p>
| 0 | 2009-07-10T08:16:00Z | [
"python",
"testing",
"integration-testing"
] |
Looking for testing/QA idea for Python Web Application Project | 1,107,858 | <p>I have the 'luck' of develop and enhance a legacy python web application for almost 2 years. The major contribution I consider I made is the introduction of the use of unit test, nosestest, pychecker and CI server. Yes, that's right, there are still project out there that has no single unit test (To be fair, it has a few doctest, but are broken).</p>
<p>Nonetheless, progress is slow, because literally the coverage is limited by how many unit tests you can afford to write. </p>
<p>From time to time embarrassing mistakes still occur, and it does not look good on management reports. (e.g. even pychecker cannot catch certain "missing attribute" situation, and the program just blows up in run time)</p>
<p>I just want to know if anyone has any suggestion about what additional thing I can do to improve the QA. The application uses WebWare 0.8.1, but I have expermentially ported it to cherrypy, so I can potentially take advantage of WSGI to conduct integration tests. </p>
<p>Mixed language development and/or hiring an additional tester are also options I am thinking.</p>
<p>Nothing is too wild, as long as it works.</p>
| 1 | 2009-07-10T05:29:02Z | 1,108,750 | <p>Few things help as much as testing.</p>
<p>These two quotes are really important.</p>
<ul>
<li><p>"how many unit tests you can afford to write."</p></li>
<li><p>"From time to time embarrassing mistakes still occur,"</p></li>
</ul>
<p>If mistakes occur, you haven't written enough tests. If you're still having mistakes, then you <strong>can</strong> afford to write more unit tests. It's that simple. </p>
<p>Each embarrassing mistake is a direct result of not writing enough unit tests. </p>
<p>Each management report that describes an embarrassing mistake should also describe what testing is required to prevent that mistake from ever happening again. </p>
<p>A unit test is a permanent prevention of further problems.</p>
| 0 | 2009-07-10T10:09:11Z | [
"python",
"testing",
"integration-testing"
] |
Komodo Edit Changes Python sys.path If you "Show in Explorer" | 1,107,865 | <p>I am using <a href="http://www.activestate.com/komodo%5Fedit/" rel="nofollow">Komodo Edit</a>, a code editor.</p>
<p>When I right click on projects and click "Show in Explorer", it will pop up a box just like Windows Explorer at the directory my project is. This is very convenient.</p>
<p>However, I noticed an insidious side effect. When you try to run a python file with this window that looks exactly like Windows Explorer, you will find out that it completely messes up sys.path in Python to use its own directory.</p>
<p>Is there any way to avoid this?</p>
<pre><code>import sys
sys.path
C:\Windows\system32\python26.zip
C:\Program Files\ActiveState Komodo Edit 5\lib\python\DLLs
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\plat-win
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\lib-tk
C:\Python26
C:\Program Files\ActiveState Komodo Edit 5\lib\python
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\win32
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\win32\lib
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\Pythonwin
</code></pre>
| 2 | 2009-07-10T05:31:35Z | 1,108,322 | <p>Oups! I've the same behavior on my Vista machine. I didn't see any settings for that feature and I think that this is a Komodo bug.</p>
<p>I though about a workaround: create a new command in the toolbox with "explorer %D" as command line. But it has the same problem :-( </p>
<p>Update: The workaround works if you put %D for StartIn. See the capture: </p>
<p><img src="http://img10.imageshack.us/img10/2972/komodoshowinexplorer.jpg" alt="alt text" /> </p>
| 2 | 2009-07-10T08:07:16Z | [
"python",
"path",
"module",
"komodo",
"komodoedit"
] |
Komodo Edit Changes Python sys.path If you "Show in Explorer" | 1,107,865 | <p>I am using <a href="http://www.activestate.com/komodo%5Fedit/" rel="nofollow">Komodo Edit</a>, a code editor.</p>
<p>When I right click on projects and click "Show in Explorer", it will pop up a box just like Windows Explorer at the directory my project is. This is very convenient.</p>
<p>However, I noticed an insidious side effect. When you try to run a python file with this window that looks exactly like Windows Explorer, you will find out that it completely messes up sys.path in Python to use its own directory.</p>
<p>Is there any way to avoid this?</p>
<pre><code>import sys
sys.path
C:\Windows\system32\python26.zip
C:\Program Files\ActiveState Komodo Edit 5\lib\python\DLLs
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\plat-win
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\lib-tk
C:\Python26
C:\Program Files\ActiveState Komodo Edit 5\lib\python
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\win32
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\win32\lib
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\Pythonwin
</code></pre>
| 2 | 2009-07-10T05:31:35Z | 1,108,374 | <p>What should your <code>sys.path</code> be instead? It looks like Python is already on the path, but maybe you need other libraries there, too.</p>
<p>If you're missing some key directories, use <code>sys.path.append</code> in one of your Python modules. If you need to move the directory of the Python interpreter (which may be necessary in order to get relative pathnames to work), use <code>os.chdir</code> as well.</p>
<p>Edit: It strikes me that you probably already know about those functions and that the problem lies elsewhere.</p>
| 0 | 2009-07-10T08:26:25Z | [
"python",
"path",
"module",
"komodo",
"komodoedit"
] |
Komodo Edit Changes Python sys.path If you "Show in Explorer" | 1,107,865 | <p>I am using <a href="http://www.activestate.com/komodo%5Fedit/" rel="nofollow">Komodo Edit</a>, a code editor.</p>
<p>When I right click on projects and click "Show in Explorer", it will pop up a box just like Windows Explorer at the directory my project is. This is very convenient.</p>
<p>However, I noticed an insidious side effect. When you try to run a python file with this window that looks exactly like Windows Explorer, you will find out that it completely messes up sys.path in Python to use its own directory.</p>
<p>Is there any way to avoid this?</p>
<pre><code>import sys
sys.path
C:\Windows\system32\python26.zip
C:\Program Files\ActiveState Komodo Edit 5\lib\python\DLLs
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\plat-win
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\lib-tk
C:\Python26
C:\Program Files\ActiveState Komodo Edit 5\lib\python
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\win32
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\win32\lib
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\Pythonwin
</code></pre>
| 2 | 2009-07-10T05:31:35Z | 1,108,734 | <p>This is indeed a problem in Komodo. It actually stems from the Explorer window spawned by Komodo having the <code>PYTHONHOME</code> environment variable set to include Komodo's path, since the child process inherits the parent's environment. I noticed this by opening a Command Prompt window through an Explorer spawned by Komodo. If you look at the output from <code>set</code>, it contains (among other things) the following:</p>
<pre><code>PYTHONHOME=C:\Program Files\ActiveState Komodo Edit 5\lib\python
_KOMODO_HOSTUSERDATADIR=C:\Users\Dev\AppData\Roaming\ActiveState\KomodoEdit\5.1\host-host\
_KOMODO_VERUSERDATADIR=C:\Users\Dev\AppData\Roaming\ActiveState\KomodoEdit\5.1\
_XRE_USERAPPDATADIR=C:\Users\Dev\AppData\Roaming\ActiveState\KomodoEdit\5.1\host-host\XRE
</code></pre>
<p>I reported this bug <a href="http://bugs.activestate.com/show%5Fbug.cgi?id=83693" rel="nofollow">here at the ActiveState bug tracker</a>.</p>
| 4 | 2009-07-10T10:04:59Z | [
"python",
"path",
"module",
"komodo",
"komodoedit"
] |
Komodo Edit Changes Python sys.path If you "Show in Explorer" | 1,107,865 | <p>I am using <a href="http://www.activestate.com/komodo%5Fedit/" rel="nofollow">Komodo Edit</a>, a code editor.</p>
<p>When I right click on projects and click "Show in Explorer", it will pop up a box just like Windows Explorer at the directory my project is. This is very convenient.</p>
<p>However, I noticed an insidious side effect. When you try to run a python file with this window that looks exactly like Windows Explorer, you will find out that it completely messes up sys.path in Python to use its own directory.</p>
<p>Is there any way to avoid this?</p>
<pre><code>import sys
sys.path
C:\Windows\system32\python26.zip
C:\Program Files\ActiveState Komodo Edit 5\lib\python\DLLs
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\plat-win
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\lib-tk
C:\Python26
C:\Program Files\ActiveState Komodo Edit 5\lib\python
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\win32
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\win32\lib
C:\Program Files\ActiveState Komodo Edit 5\lib\python\lib\site-packages\Pythonwin
</code></pre>
| 2 | 2009-07-10T05:31:35Z | 4,893,611 | <p>I'd recommend going into Komodo Edit's Preferences >> Environment, and changing PYTHONHOME back to the original python install (e.g. c:\python27)</p>
| 0 | 2011-02-04T01:16:30Z | [
"python",
"path",
"module",
"komodo",
"komodoedit"
] |
Datastore access optimization | 1,108,072 | <p>I'm writing a small program to record reading progress, the data models are simple:</p>
<pre><code>class BookState(db.Model):
isbn = db.StringProperty()
title = db.StringProperty(required=True)
pages = db.IntegerProperty(required=True)
img = db.StringProperty()
class UpdatePoint(db.Model):
book = db.ReferenceProperty(BookState)
date = db.DateProperty(required=True)
page = db.IntegerProperty(required=True)
</code></pre>
<p>The UpdatePoint class records how many pages the user has read on corresponding date. Now I want to draw a chart from the data stored in App Engine database, the function looks like this:</p>
<pre><code>book = db.get(bookkey)
ups = book.updatepoint_set
ups.order('date')
for (i, up) in enumerate(ups):
if i == 0: continue
# code begin
days = (up.date - ups[i-1].date).days
pages = up.page - ups[i-1].page
# code end
# blah blah
</code></pre>
<p>I find that for a book with about 40 update points, it will costs more than 4 seconds to run the code. And after timing I find the commented code snippet seems to be the root of poor performance. Each loop costs about 0.08 seconds or more.</p>
<p>It seems UpdatePoint is fetched in a lazy way that it won't be loaded until it is needed. I want to know whether there is any better solution to accelerate the data access like fetch the data in a bunch.</p>
<p>Many thanks for your reply.</p>
| 0 | 2009-07-10T06:55:39Z | 1,108,157 | <p>It seems I used Query class in a wrong way. I need to call ups.fetch() first to get the data. Now the code is a lot faster than before:</p>
<pre><code>book = db.get(bookkey)
q = book.updatepoint_set
q.order('date')
ups = q.fetch(50)
</code></pre>
| 3 | 2009-07-10T07:21:48Z | [
"python",
"database",
"google-app-engine"
] |
Datastore access optimization | 1,108,072 | <p>I'm writing a small program to record reading progress, the data models are simple:</p>
<pre><code>class BookState(db.Model):
isbn = db.StringProperty()
title = db.StringProperty(required=True)
pages = db.IntegerProperty(required=True)
img = db.StringProperty()
class UpdatePoint(db.Model):
book = db.ReferenceProperty(BookState)
date = db.DateProperty(required=True)
page = db.IntegerProperty(required=True)
</code></pre>
<p>The UpdatePoint class records how many pages the user has read on corresponding date. Now I want to draw a chart from the data stored in App Engine database, the function looks like this:</p>
<pre><code>book = db.get(bookkey)
ups = book.updatepoint_set
ups.order('date')
for (i, up) in enumerate(ups):
if i == 0: continue
# code begin
days = (up.date - ups[i-1].date).days
pages = up.page - ups[i-1].page
# code end
# blah blah
</code></pre>
<p>I find that for a book with about 40 update points, it will costs more than 4 seconds to run the code. And after timing I find the commented code snippet seems to be the root of poor performance. Each loop costs about 0.08 seconds or more.</p>
<p>It seems UpdatePoint is fetched in a lazy way that it won't be loaded until it is needed. I want to know whether there is any better solution to accelerate the data access like fetch the data in a bunch.</p>
<p>Many thanks for your reply.</p>
| 0 | 2009-07-10T06:55:39Z | 1,108,166 | <p>From the look of the code, it appears that your slow down is because its in the loop and have to kinda pop out to find the object you want. Have you tried something like</p>
<pre><code>i = 0
for up in ups:
if i != 0:
days = (up.date - previous.date).days
pages = up.page - previous.page
i += 1
previous = up
</code></pre>
| 0 | 2009-07-10T07:23:35Z | [
"python",
"database",
"google-app-engine"
] |
How can I extract the call graph of a function from Python source files? | 1,108,119 | <p>Do you know an integrated tool that will generate the call graph of a function from Python sources? I need one that is consistent and can run on Windows OS.</p>
| 10 | 2009-07-10T07:09:58Z | 1,108,142 | <p>You could try with <a href="http://pycallgraph.slowchop.com/">PyCallGraph</a><br />
From its documentation:</p>
<blockquote>
<p>Python Call Graph works with Linux,
Windows and Mac OS X.</p>
</blockquote>
<p>Otherwise, you can directly do it on your own, using the traceback module:</p>
<pre><code>import traceback
traceback.print_stack()
</code></pre>
| 9 | 2009-07-10T07:16:55Z | [
"python",
"windows",
"call-graph"
] |
How can I extract the call graph of a function from Python source files? | 1,108,119 | <p>Do you know an integrated tool that will generate the call graph of a function from Python sources? I need one that is consistent and can run on Windows OS.</p>
| 10 | 2009-07-10T07:09:58Z | 1,108,153 | <p>What about <a href="http://pycallgraph.slowchop.com/">pycallgraph</a>, it's a Python module that creates call graphs for Python programs. It works on windows.
Just download <a href="http://www.graphviz.org/Download%5Fwindows.php">graphviz</a> and <a href="http://pycallgraph.slowchop.com/pycallgraph/wiki/documentation/0.5.1/PythonCallGraphInstall">pycallgraph</a>, <a href="http://pycallgraph.slowchop.com/files/download/pycallgraph-0.5.1.tar.gz">pycallgraphs's source tarball</a> has some examples.<br />
Hope this helps</p>
| 5 | 2009-07-10T07:20:30Z | [
"python",
"windows",
"call-graph"
] |
How can I extract the call graph of a function from Python source files? | 1,108,119 | <p>Do you know an integrated tool that will generate the call graph of a function from Python sources? I need one that is consistent and can run on Windows OS.</p>
| 10 | 2009-07-10T07:09:58Z | 10,366,447 | <p>PyCallGraph produces the dynamic graph resulting from the specific execution of a Python program and not the static graph extracted from the source code. Does anybody know of a tool which produces the static graph?</p>
| 9 | 2012-04-28T18:40:30Z | [
"python",
"windows",
"call-graph"
] |
How to include a python .egg library that is in a subdirectory (relative location)? | 1,108,384 | <p>How do you import python .egg files that are stored in a relative location to the .py code?</p>
<p>For example,</p>
<pre><code>My Application/
My Application/library1.egg
My Application/libs/library2.egg
My Application/test.py
</code></pre>
<p>How do you import and use library1 and library2 from within test.py, while leaving the .egg libraries in-place?</p>
| 12 | 2009-07-10T08:29:05Z | 1,108,400 | <p>An .egg is just a .zip file that acts like a directory from which you can import stuff.</p>
<p>You can use the <code>PYTHONPATH</code> variable to add the <code>.egg</code> to your path, or append a directory to
<code>sys.path</code>. Another option is to use a <code>.pth</code> file pointing to the eggs.</p>
<p>For more info see <a href="http://mrtopf.de/blog/python_zope/a-small-introduction-to-python-eggs/">A Small Introduction to Python eggs</a>, <a href="http://peak.telecommunity.com/DevCenter/PythonEggs">Python Eggs</a> and <a href="http://www.ibm.com/developerworks/linux/library/l-cppeak3/index.html">All about eggs</a>.</p>
<p>For example, if your <code>library1.egg</code> contains a package named <code>foo</code>, and you add <code>library1.egg</code> to <code>PYTHONPATH</code>, you can simply <code>import foo</code></p>
<p>If you can't set <code>PYTHONPATH</code>, you can write:</p>
<pre><code>import sys
sys.path.append("library1.egg")
import foo
</code></pre>
| 18 | 2009-07-10T08:32:35Z | [
"python",
"egg"
] |
How to include a python .egg library that is in a subdirectory (relative location)? | 1,108,384 | <p>How do you import python .egg files that are stored in a relative location to the .py code?</p>
<p>For example,</p>
<pre><code>My Application/
My Application/library1.egg
My Application/libs/library2.egg
My Application/test.py
</code></pre>
<p>How do you import and use library1 and library2 from within test.py, while leaving the .egg libraries in-place?</p>
| 12 | 2009-07-10T08:29:05Z | 1,108,423 | <p>You can include each egg on the sys.path, or create a .pth file that mentions each egg.</p>
<p>If you have many eggs that you need in your system I'd recommend using something like buildout, that will make the setup easily replicatable. It will handle the eggs for you.</p>
<p><a href="http://pypi.python.org/pypi/zc.buildout/" rel="nofollow">http://pypi.python.org/pypi/zc.buildout/</a></p>
| 1 | 2009-07-10T08:38:58Z | [
"python",
"egg"
] |
How do I read a date in Excel format in Python? | 1,108,428 | <p>How can I convert an Excel date (in a number format) to a proper date in Python?</p>
| 32 | 2009-07-10T08:41:45Z | 1,108,474 | <p>You can use <a href="http://pypi.python.org/pypi/xlrd">xlrd</a>.</p>
<p>From its <a href="http://www.lexicon.net/sjmachin/xlrd.html">documentation</a>, you can read that dates are always stored as numbers; however, you can use <a href="http://www.lexicon.net/sjmachin/xlrd.html#xlrd.xldate%5Fas%5Ftuple-function"><code>xldate_as_tuple</code></a> to convert it to a python date.</p>
<p>Note: the version on the PyPI seems more up-to-date than the one available on xlrd's website.</p>
| 50 | 2009-07-10T08:53:44Z | [
"python",
"excel",
"datetime"
] |
How do I read a date in Excel format in Python? | 1,108,428 | <p>How can I convert an Excel date (in a number format) to a proper date in Python?</p>
| 32 | 2009-07-10T08:41:45Z | 1,109,523 | <p>After testing and a few days wait for feedback, I'll svn-commit the following whole new function in xlrd's xldate module ... note that it won't be available to the diehards still running Python 2.1 or 2.2.</p>
<pre><code>##
# Convert an Excel number (presumed to represent a date, a datetime or a time) into
# a Python datetime.datetime
# @param xldate The Excel number
# @param datemode 0: 1900-based, 1: 1904-based.
# <br>WARNING: when using this function to
# interpret the contents of a workbook, you should pass in the Book.datemode
# attribute of that workbook. Whether
# the workbook has ever been anywhere near a Macintosh is irrelevant.
# @return a datetime.datetime object, to the nearest_second.
# <br>Special case: if 0.0 <= xldate < 1.0, it is assumed to represent a time;
# a datetime.time object will be returned.
# <br>Note: 1904-01-01 is not regarded as a valid date in the datemode 1 system; its "serial number"
# is zero.
# @throws XLDateNegative xldate < 0.00
# @throws XLDateAmbiguous The 1900 leap-year problem (datemode == 0 and 1.0 <= xldate < 61.0)
# @throws XLDateTooLarge Gregorian year 10000 or later
# @throws XLDateBadDatemode datemode arg is neither 0 nor 1
# @throws XLDateError Covers the 4 specific errors
def xldate_as_datetime(xldate, datemode):
if datemode not in (0, 1):
raise XLDateBadDatemode(datemode)
if xldate == 0.00:
return datetime.time(0, 0, 0)
if xldate < 0.00:
raise XLDateNegative(xldate)
xldays = int(xldate)
frac = xldate - xldays
seconds = int(round(frac * 86400.0))
assert 0 <= seconds <= 86400
if seconds == 86400:
seconds = 0
xldays += 1
if xldays >= _XLDAYS_TOO_LARGE[datemode]:
raise XLDateTooLarge(xldate)
if xldays == 0:
# second = seconds % 60; minutes = seconds // 60
minutes, second = divmod(seconds, 60)
# minute = minutes % 60; hour = minutes // 60
hour, minute = divmod(minutes, 60)
return datetime.time(hour, minute, second)
if xldays < 61 and datemode == 0:
raise XLDateAmbiguous(xldate)
return (
datetime.datetime.fromordinal(xldays + 693594 + 1462 * datemode)
+ datetime.timedelta(seconds=seconds)
)
</code></pre>
| 20 | 2009-07-10T13:29:51Z | [
"python",
"excel",
"datetime"
] |
How do I read a date in Excel format in Python? | 1,108,428 | <p>How can I convert an Excel date (in a number format) to a proper date in Python?</p>
| 32 | 2009-07-10T08:41:45Z | 1,112,664 | <p>Here's the bare-knuckle no-seat-belts use-at-own-risk version:</p>
<pre><code>import datetime
def minimalist_xldate_as_datetime(xldate, datemode):
# datemode: 0 for 1900-based, 1 for 1904-based
return (
datetime.datetime(1899, 12, 30)
+ datetime.timedelta(days=xldate + 1462 * datemode)
)
</code></pre>
| 17 | 2009-07-11T01:25:02Z | [
"python",
"excel",
"datetime"
] |
How do I read a date in Excel format in Python? | 1,108,428 | <p>How can I convert an Excel date (in a number format) to a proper date in Python?</p>
| 32 | 2009-07-10T08:41:45Z | 24,132,415 | <p>For quick and dirty:</p>
<pre><code>year, month, day, hour, minute, second = xlrd.xldate_as_tuple(excelDate, wb.datemode)
whatYouWant = str(month)+'/'+str(day)+'/'+str(year)
</code></pre>
| 0 | 2014-06-10T03:35:15Z | [
"python",
"excel",
"datetime"
] |
How do I read a date in Excel format in Python? | 1,108,428 | <p>How can I convert an Excel date (in a number format) to a proper date in Python?</p>
| 32 | 2009-07-10T08:41:45Z | 26,231,244 | <p>Please refer to this link: <a href="http://stackoverflow.com/questions/13962837/reading-date-as-a-string-not-float-from-excel-using-python-xlrd">Reading date as a string not float from excel using python xlrd</a></p>
<p>it worked for me: </p>
<p>in shot this the link has: </p>
<pre><code>import datetime, xlrd
book = xlrd.open_workbook("myfile.xls")
sh = book.sheet_by_index(0)
a1 = sh.cell_value(rowx=0, colx=0)
a1_as_datetime = datetime.datetime(*xlrd.xldate_as_tuple(a1, book.datemode))
print 'datetime: %s' % a1_as_datetime
</code></pre>
| 2 | 2014-10-07T07:59:29Z | [
"python",
"excel",
"datetime"
] |
How do I read a date in Excel format in Python? | 1,108,428 | <p>How can I convert an Excel date (in a number format) to a proper date in Python?</p>
| 32 | 2009-07-10T08:41:45Z | 28,220,798 | <p><code>xlrd.xldate_as_tuple</code> is nice, but there's <code>xlrd.xldate.xldate_as_datetime</code> that converts to datetime as well.</p>
<pre><code>import xlrd
wb = xlrd.open_workbook(filename)
xlrd.xldate.xldate_as_datetime(41889, wb.datemode)
=> datetime.datetime(2014, 9, 7, 0, 0)
</code></pre>
| 12 | 2015-01-29T17:21:59Z | [
"python",
"excel",
"datetime"
] |
How do I read a date in Excel format in Python? | 1,108,428 | <p>How can I convert an Excel date (in a number format) to a proper date in Python?</p>
| 32 | 2009-07-10T08:41:45Z | 29,336,555 | <p>A combination of peoples post gave me the date and the time for excel conversion. I did return it as a string</p>
<pre><code>def xldate_to_datetime(xldate):
tempDate = datetime.datetime(1900, 1, 1)
deltaDays = datetime.timedelta(days=int(xldate))
secs = (int((xldate%1)*86400)-60)
detlaSeconds = datetime.timedelta(seconds=secs)
TheTime = (tempDate + deltaDays + detlaSeconds )
return TheTime.strftime("%Y-%m-%d %H:%M:%S")
</code></pre>
| 0 | 2015-03-30T00:14:18Z | [
"python",
"excel",
"datetime"
] |
How do I read a date in Excel format in Python? | 1,108,428 | <p>How can I convert an Excel date (in a number format) to a proper date in Python?</p>
| 32 | 2009-07-10T08:41:45Z | 36,034,857 | <p>When converting an excel file to CSV the date/time cell looks like this:</p>
<p>foo, 3/16/2016 10:38, bar,</p>
<p>To convert the datetime text value to datetime python object do this:</p>
<pre><code>from datetime import datetime
date_object = datetime.strptime('3/16/2016 10:38', '%m/%d/%Y %H:%M') # excel format (CSV file)
</code></pre>
<p>print date_object will return 2005-06-01 13:33:00</p>
| 0 | 2016-03-16T11:49:23Z | [
"python",
"excel",
"datetime"
] |
Returning MatPotLib image as string | 1,108,881 | <p>I am using matplotlib in a django app and would like to directly return the rendered image.
So far I can go <code>plt.savefig(...)</code>, then return the location of the image</p>
<p>What I want to do is:</p>
<pre><code>return HttpResponse(plt.renderfig(...), mimetype="image/png")
</code></pre>
<p>Any ideas?</p>
| 6 | 2009-07-10T10:46:42Z | 1,108,930 | <p>Employ ducktyping and pass a object of your own, in disguise of file object</p>
<pre><code>class MyFile(object):
def __init__(self):
self._data = ""
def write(self, data):
self._data += data
myfile = MyFile()
fig.savefig(myfile)
print myfile._data
</code></pre>
<p>you can use myfile = StringIO.StringIO() instead in real code and return data in reponse e.g.</p>
<pre><code>output = StringIO.StringIO()
fig.savefig(output)
contents = output.getvalue()
return HttpResponse(contents , mimetype="image/png")
</code></pre>
| 0 | 2009-07-10T11:01:13Z | [
"python",
"django",
"matplotlib"
] |
Returning MatPotLib image as string | 1,108,881 | <p>I am using matplotlib in a django app and would like to directly return the rendered image.
So far I can go <code>plt.savefig(...)</code>, then return the location of the image</p>
<p>What I want to do is:</p>
<pre><code>return HttpResponse(plt.renderfig(...), mimetype="image/png")
</code></pre>
<p>Any ideas?</p>
| 6 | 2009-07-10T10:46:42Z | 1,108,972 | <p>what about <a href="http://docs.python.org/library/stringio.html#module-cStringIO">cStringIO</a>?</p>
<pre><code>import pylab
import cStringIO
pylab.plot([3,7,2,1])
output = cStringIO.StringIO()
pylab.savefig('test.png', dpi=75)
pylab.savefig(output, dpi=75)
print output.getvalue() == open('test.png', 'rb').read() # True
</code></pre>
| 6 | 2009-07-10T11:12:49Z | [
"python",
"django",
"matplotlib"
] |
Returning MatPotLib image as string | 1,108,881 | <p>I am using matplotlib in a django app and would like to directly return the rendered image.
So far I can go <code>plt.savefig(...)</code>, then return the location of the image</p>
<p>What I want to do is:</p>
<pre><code>return HttpResponse(plt.renderfig(...), mimetype="image/png")
</code></pre>
<p>Any ideas?</p>
| 6 | 2009-07-10T10:46:42Z | 1,109,442 | <p>Django's <code>HttpResponse</code> object supports file-like API and you can pass a file-object to savefig.</p>
<pre><code>response = HttpResponse(mimetype="image/png")
# create your image as usual, e.g. pylab.plot(...)
pylab.savefig(response, format="png")
return response
</code></pre>
<p>Hence, you can return the image directly in the <code>HttpResponse</code>.</p>
| 14 | 2009-07-10T13:13:05Z | [
"python",
"django",
"matplotlib"
] |
Returning MatPotLib image as string | 1,108,881 | <p>I am using matplotlib in a django app and would like to directly return the rendered image.
So far I can go <code>plt.savefig(...)</code>, then return the location of the image</p>
<p>What I want to do is:</p>
<pre><code>return HttpResponse(plt.renderfig(...), mimetype="image/png")
</code></pre>
<p>Any ideas?</p>
| 6 | 2009-07-10T10:46:42Z | 1,112,190 | <p>There is a recipe in the <a href="http://scipy.org/Cookbook/Matplotlib/Django" rel="nofollow">Matplotlib Cookbook</a> that does exactly this. At its core, it looks like:</p>
<pre><code>def simple(request):
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
fig=Figure()
ax=fig.add_subplot(111)
ax.plot(range(10), range(10), '-')
canvas=FigureCanvas(fig)
response=django.http.HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
</code></pre>
<p>Put that in your views file, point your URL to it, and you're off and running.</p>
<p>Edit: As noted, this is a simplified version of a recipe in the cookbook. However, it looks like there is a difference between calling <code>print_png</code> and <code>savefig</code>, at least in the initial test that I did. Calling <code>fig.savefig(response, format='png')</code> gave an image with that was larger and had a white background, while the original <code>canvas.print_png(response)</code> gave a slightly smaller image with a grey background. So, I would replace the last few lines above with:</p>
<pre><code> canvas=FigureCanvas(fig)
response=django.http.HttpResponse(content_type='image/png')
fig.savefig(response, format='png')
return response
</code></pre>
<p>You still need to have the canvas instantiated, though.</p>
| 2 | 2009-07-10T21:56:05Z | [
"python",
"django",
"matplotlib"
] |
How to store an IP in mySQL | 1,108,918 | <p>We've got a healthy debate going on in the office this week. We're creating a Db to store proxy information, for the most part we have the schema worked out except for how we should store IPs. One camp wants to use 4 smallints, one for each octet and the other wants to use a 1 big int,INET_ATON.</p>
<p>These tables are going to be huge so performance is key. I am in middle here as I normally use MS SQL and 4 small ints in my world. I don't have enough experience with this type of volume storing IPs. </p>
<p>We'll be using perl and python scripts to access the database to further normalize the data into several other tables for top talkers, interesting traffic etc.</p>
<p>I am sure there are some here in the community that have done something simular to what we are doing and I am interested in hearing about their experiences and which route is best, 1 big int, or 4 small ints for IP addresses.</p>
<p><strong>EDIT</strong> - One of our concerns is space, this database is going to be huge like in 500,000,000 records a day. So we are trying to weigh the space issue along with the performance issue.</p>
<p><strong>EDIT 2</strong> Some of the conversation has turned over to the volume of data we are going to store...that's not my question. The question is which is the preferable way to store an IP address and why. Like I've said in my comments, we work for a large fortune 50 company. Our log files contain usage data from our users. This data in turn will be used within a security context to drive some metrics and to drive several security tools. </p>
| 19 | 2009-07-10T10:58:42Z | 1,108,931 | <p>Use PostgreSQL, there's a <a href="http://www.postgresql.org/docs/8.4/static/datatype-net-types.html#DATATYPE-INET" rel="nofollow">native data type</a> for that.</p>
<p>More seriously, I would fall into the "one 32-bit integer" camp. An IP address only makes sense when all four octets are considered together, so there's no reason to store the octets in separate columns in the database. Would you store a phone number using three (or more) different fields?</p>
| 3 | 2009-07-10T11:01:16Z | [
"python",
"mysql",
"perl",
"ip-address"
] |
How to store an IP in mySQL | 1,108,918 | <p>We've got a healthy debate going on in the office this week. We're creating a Db to store proxy information, for the most part we have the schema worked out except for how we should store IPs. One camp wants to use 4 smallints, one for each octet and the other wants to use a 1 big int,INET_ATON.</p>
<p>These tables are going to be huge so performance is key. I am in middle here as I normally use MS SQL and 4 small ints in my world. I don't have enough experience with this type of volume storing IPs. </p>
<p>We'll be using perl and python scripts to access the database to further normalize the data into several other tables for top talkers, interesting traffic etc.</p>
<p>I am sure there are some here in the community that have done something simular to what we are doing and I am interested in hearing about their experiences and which route is best, 1 big int, or 4 small ints for IP addresses.</p>
<p><strong>EDIT</strong> - One of our concerns is space, this database is going to be huge like in 500,000,000 records a day. So we are trying to weigh the space issue along with the performance issue.</p>
<p><strong>EDIT 2</strong> Some of the conversation has turned over to the volume of data we are going to store...that's not my question. The question is which is the preferable way to store an IP address and why. Like I've said in my comments, we work for a large fortune 50 company. Our log files contain usage data from our users. This data in turn will be used within a security context to drive some metrics and to drive several security tools. </p>
| 19 | 2009-07-10T10:58:42Z | 1,108,942 | <p>A <code>BIGINT</code> is <code>8</code> bytes in <code>MySQL</code>.</p>
<p>To store <code>IPv4</code> addresses, an <code>UNSINGED INT</code> is enough, which I think is what you shoud use.</p>
<p>I can't imagine a scenario where <code>4</code> octets would gain more performance than a single <code>INT</code>, and the latter is much more convenient.</p>
<p>Also note that if you are going to issue queries like this:</p>
<pre><code>SELECT *
FROM ips
WHERE ? BETWEEN start_ip AND end_ip
</code></pre>
<p>, where <code>start_ip</code> and <code>end_ip</code> are columns in your table, the performance will be poor.</p>
<p>These queries are used to find out if a given <code>IP</code> is within a subnet range (usually to ban it).</p>
<p>To make these queries efficient, you should store the whole range as a <code>LineString</code> object with a <code>SPATIAL</code> index on it, and query like this:</p>
<pre><code>SELECT *
FROM ips
WHERE MBRContains(?, ip_range)
</code></pre>
<p>See this entry in my blog for more detail on how to do it:</p>
<ul>
<li><a href="http://explainextended.com/2009/04/04/banning-ips/"><strong>Banning IPs</strong></a></li>
</ul>
| 12 | 2009-07-10T11:03:11Z | [
"python",
"mysql",
"perl",
"ip-address"
] |
How to store an IP in mySQL | 1,108,918 | <p>We've got a healthy debate going on in the office this week. We're creating a Db to store proxy information, for the most part we have the schema worked out except for how we should store IPs. One camp wants to use 4 smallints, one for each octet and the other wants to use a 1 big int,INET_ATON.</p>
<p>These tables are going to be huge so performance is key. I am in middle here as I normally use MS SQL and 4 small ints in my world. I don't have enough experience with this type of volume storing IPs. </p>
<p>We'll be using perl and python scripts to access the database to further normalize the data into several other tables for top talkers, interesting traffic etc.</p>
<p>I am sure there are some here in the community that have done something simular to what we are doing and I am interested in hearing about their experiences and which route is best, 1 big int, or 4 small ints for IP addresses.</p>
<p><strong>EDIT</strong> - One of our concerns is space, this database is going to be huge like in 500,000,000 records a day. So we are trying to weigh the space issue along with the performance issue.</p>
<p><strong>EDIT 2</strong> Some of the conversation has turned over to the volume of data we are going to store...that's not my question. The question is which is the preferable way to store an IP address and why. Like I've said in my comments, we work for a large fortune 50 company. Our log files contain usage data from our users. This data in turn will be used within a security context to drive some metrics and to drive several security tools. </p>
| 19 | 2009-07-10T10:58:42Z | 1,109,046 | <p>I would suggest looking at what type of queries you will be running to decide which format you adopt.</p>
<p>Only if you need to pull out or compare individual octets would you have to consider splitting them up into separate fields.</p>
<p>Otherwise, store it as an 4 byte integer. That also has the bonus of allowing you to use the MySQL built-in <a href="http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_inet-aton" rel="nofollow"><code>INET_ATON()</code></a> and <a href="http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_inet-ntoa" rel="nofollow"><code>INET_NTOA()</code></a> functions.</p>
<p>EDIT: Updated for:</p>
<h2>Performance vs. Space</h2>
<p><strong>Storage:</strong></p>
<p>If you are only going to support IPv4 address then your datatype in MySQL can be an <code>UNSIGNED INT</code> which only uses 4 bytes of storage.</p>
<p>To store the individual octets you would only need to use <code>UNSIGNED TINYINT</code> datatypes, not <code>SMALLINTS</code>, which would use up 1 byte each of storage.</p>
<p>Both methods would use similar storage with perhaps slightly more for separate fields for some overhead.</p>
<p>More info:</p>
<ul>
<li><a href="https://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html" rel="nofollow">Numeric Type Overview</a></li>
<li><a href="https://dev.mysql.com/doc/refman/5.0/en/integer-types.html" rel="nofollow">Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT</a></li>
</ul>
<p><strong>Performance:</strong></p>
<p>Using a single field will yield much better performance, its a single comparison instead of 4. You mentioned that you will only run queries against the whole IP address, so there should be no need to keep the octets seperate. Using the `INET_*? functions of MySQL will do the conversion between the text and integer representations once for the comparison.</p>
| 19 | 2009-07-10T11:34:58Z | [
"python",
"mysql",
"perl",
"ip-address"
] |
How to store an IP in mySQL | 1,108,918 | <p>We've got a healthy debate going on in the office this week. We're creating a Db to store proxy information, for the most part we have the schema worked out except for how we should store IPs. One camp wants to use 4 smallints, one for each octet and the other wants to use a 1 big int,INET_ATON.</p>
<p>These tables are going to be huge so performance is key. I am in middle here as I normally use MS SQL and 4 small ints in my world. I don't have enough experience with this type of volume storing IPs. </p>
<p>We'll be using perl and python scripts to access the database to further normalize the data into several other tables for top talkers, interesting traffic etc.</p>
<p>I am sure there are some here in the community that have done something simular to what we are doing and I am interested in hearing about their experiences and which route is best, 1 big int, or 4 small ints for IP addresses.</p>
<p><strong>EDIT</strong> - One of our concerns is space, this database is going to be huge like in 500,000,000 records a day. So we are trying to weigh the space issue along with the performance issue.</p>
<p><strong>EDIT 2</strong> Some of the conversation has turned over to the volume of data we are going to store...that's not my question. The question is which is the preferable way to store an IP address and why. Like I've said in my comments, we work for a large fortune 50 company. Our log files contain usage data from our users. This data in turn will be used within a security context to drive some metrics and to drive several security tools. </p>
| 19 | 2009-07-10T10:58:42Z | 1,109,278 | <p>Having seperate fields doesn't sound particularly sensible to me - much like splitting a zipcode into sections or a phone number.</p>
<p>Might be useful if you wanted specific info on the sections, but I see no real reason to not use a 32 bit int.</p>
| 1 | 2009-07-10T12:38:51Z | [
"python",
"mysql",
"perl",
"ip-address"
] |
How to store an IP in mySQL | 1,108,918 | <p>We've got a healthy debate going on in the office this week. We're creating a Db to store proxy information, for the most part we have the schema worked out except for how we should store IPs. One camp wants to use 4 smallints, one for each octet and the other wants to use a 1 big int,INET_ATON.</p>
<p>These tables are going to be huge so performance is key. I am in middle here as I normally use MS SQL and 4 small ints in my world. I don't have enough experience with this type of volume storing IPs. </p>
<p>We'll be using perl and python scripts to access the database to further normalize the data into several other tables for top talkers, interesting traffic etc.</p>
<p>I am sure there are some here in the community that have done something simular to what we are doing and I am interested in hearing about their experiences and which route is best, 1 big int, or 4 small ints for IP addresses.</p>
<p><strong>EDIT</strong> - One of our concerns is space, this database is going to be huge like in 500,000,000 records a day. So we are trying to weigh the space issue along with the performance issue.</p>
<p><strong>EDIT 2</strong> Some of the conversation has turned over to the volume of data we are going to store...that's not my question. The question is which is the preferable way to store an IP address and why. Like I've said in my comments, we work for a large fortune 50 company. Our log files contain usage data from our users. This data in turn will be used within a security context to drive some metrics and to drive several security tools. </p>
| 19 | 2009-07-10T10:58:42Z | 1,109,477 | <p>Efficient transformation of ip to int and int to ip (could be useful to you):
(PERL)</p>
<pre><code>sub ip2dec {
my @octs = split /\./,shift;
return ($octs[0] << 24) + ($octs[1] << 16) + ($octs[2] << 8) + $octs[3];
}
sub dec2ip {
my $number = shift;
my $first_oct = $number >> 24;
my $reverse_1_ = $number - ($first_oct << 24);
my $secon_oct = $reverse_1_ >> 16;
my $reverse_2_ = $reverse_1_ - ($secon_oct << 16);
my $third_oct = $reverse_2_ >> 8;
my $fourt_oct = $reverse_2_ - ($third_oct << 8);
return "$first_oct.$secon_oct.$third_oct.$fourt_oct";
}
</code></pre>
| -1 | 2009-07-10T13:21:38Z | [
"python",
"mysql",
"perl",
"ip-address"
] |
Finding the coordinates of tiles that are covered by a rectangle with x,y,w,h pixel coordinates | 1,108,929 | <p>Say I have a tile based system using 16x16 pixels. How would you find out what tiles are covered by a rectangle defined by floating point pixel units? </p>
<p>for eg,</p>
<pre><code>rect(x=16.0,y=16.0, w=1.0, h=1.0) -> tile(x=1, y=1, w=1, h=1)
rect(x=16.0,y=16.0, w=16.0, h=16.0) -> tile(x=1, y=1, w=1, h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.0, y=8.0) -> (x=1,y=1,w=1,h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.1, y=8.1) -> (x=1,y=1,w=2,h=2)
</code></pre>
<p>The only way I can do this reliably is by using a loop. Is there a better way? Dividing by 16 gives me the wrong answer on edge cases. Here's some example code I use in python:</p>
<pre><code>#!/usr/bin/env python
import math
TILE_W = 16
TILE_H = 16
def get_tile(x,y,w,h):
t_x = int(x / TILE_W)
t_x2 = t_x
while t_x2*TILE_W < (x+w):
t_x2 += 1
t_w = t_x2-t_x
t_y = int( y / TILE_H)
t_y2 = t_y
while t_y2*TILE_H < (y+h):
t_y2 += 1
t_h = t_y2-t_y
return t_x,t_y,t_w,t_h
(x,y) = 16.0,16.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 15.0, 15.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 16.0, 16.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 16.1, 16.1
assert get_tile(x,y,w,h) == (1,1,2,2)
(x,y) = 24.0, 24.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 24.0, 24.0
(w,h) = 8.0, 8.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 24.0, 24.0
(w,h) = 8.1, 8.1
assert get_tile(x,y,w,h) == (1,1,2,2)
(x,y) = 24.0, 24.0
(w,h) = 9.0, 9.0
assert get_tile(x,y,w,h) == (1,1,2,2)
</code></pre>
| 2 | 2009-07-10T11:01:03Z | 1,108,981 | <p>here is the one which passes your test cases, tell me if there is any edge case</p>
<pre><code>TILE_W = TILE_H = 16
from math import floor, ceil
def get_tile2(x,y,w,h):
x1 = int(x/TILE_W)
y1 = int(y/TILE_H)
x2 = int((x+w)/TILE_W)
y2 = int((y+h)/TILE_H)
if (x+w)%16 == 0: #edge case
x2-=1
if (y+h)%16 == 0: #edge case
y2-=1
tw = x2-x1 + 1
th = y2-y1 + 1
return x1, y1, tw, th
(x,y) = 16.0, 16.0
(w,h) = 1.0, 1.0
assert get_tile2(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0, 16.0
(w,h) = 15.0, 15.0
assert get_tile2(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0, 16.0
(w,h) = 16.0, 16.0
assert get_tile2(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0, 16.0
(w,h) = 16.1, 16.1
assert get_tile2(x,y,w,h) == (1,1,2,2)
</code></pre>
<p>I am now explicitly checking for the edge case, but be aware that floating point comparison sometime may not seem obvious and result may not be as expected.</p>
| 0 | 2009-07-10T11:15:29Z | [
"python",
"algorithm",
"math",
"geometry",
"coordinates"
] |
Finding the coordinates of tiles that are covered by a rectangle with x,y,w,h pixel coordinates | 1,108,929 | <p>Say I have a tile based system using 16x16 pixels. How would you find out what tiles are covered by a rectangle defined by floating point pixel units? </p>
<p>for eg,</p>
<pre><code>rect(x=16.0,y=16.0, w=1.0, h=1.0) -> tile(x=1, y=1, w=1, h=1)
rect(x=16.0,y=16.0, w=16.0, h=16.0) -> tile(x=1, y=1, w=1, h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.0, y=8.0) -> (x=1,y=1,w=1,h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.1, y=8.1) -> (x=1,y=1,w=2,h=2)
</code></pre>
<p>The only way I can do this reliably is by using a loop. Is there a better way? Dividing by 16 gives me the wrong answer on edge cases. Here's some example code I use in python:</p>
<pre><code>#!/usr/bin/env python
import math
TILE_W = 16
TILE_H = 16
def get_tile(x,y,w,h):
t_x = int(x / TILE_W)
t_x2 = t_x
while t_x2*TILE_W < (x+w):
t_x2 += 1
t_w = t_x2-t_x
t_y = int( y / TILE_H)
t_y2 = t_y
while t_y2*TILE_H < (y+h):
t_y2 += 1
t_h = t_y2-t_y
return t_x,t_y,t_w,t_h
(x,y) = 16.0,16.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 15.0, 15.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 16.0, 16.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 16.1, 16.1
assert get_tile(x,y,w,h) == (1,1,2,2)
(x,y) = 24.0, 24.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 24.0, 24.0
(w,h) = 8.0, 8.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 24.0, 24.0
(w,h) = 8.1, 8.1
assert get_tile(x,y,w,h) == (1,1,2,2)
(x,y) = 24.0, 24.0
(w,h) = 9.0, 9.0
assert get_tile(x,y,w,h) == (1,1,2,2)
</code></pre>
| 2 | 2009-07-10T11:01:03Z | 1,108,992 | <p>You could try aligning you pixel coordinates ot integers before dividing by tile width:</p>
<pre><code>xlower = int(floor(x))
xupper = int(ceil(x + w))
</code></pre>
| 0 | 2009-07-10T11:17:47Z | [
"python",
"algorithm",
"math",
"geometry",
"coordinates"
] |
Finding the coordinates of tiles that are covered by a rectangle with x,y,w,h pixel coordinates | 1,108,929 | <p>Say I have a tile based system using 16x16 pixels. How would you find out what tiles are covered by a rectangle defined by floating point pixel units? </p>
<p>for eg,</p>
<pre><code>rect(x=16.0,y=16.0, w=1.0, h=1.0) -> tile(x=1, y=1, w=1, h=1)
rect(x=16.0,y=16.0, w=16.0, h=16.0) -> tile(x=1, y=1, w=1, h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.0, y=8.0) -> (x=1,y=1,w=1,h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.1, y=8.1) -> (x=1,y=1,w=2,h=2)
</code></pre>
<p>The only way I can do this reliably is by using a loop. Is there a better way? Dividing by 16 gives me the wrong answer on edge cases. Here's some example code I use in python:</p>
<pre><code>#!/usr/bin/env python
import math
TILE_W = 16
TILE_H = 16
def get_tile(x,y,w,h):
t_x = int(x / TILE_W)
t_x2 = t_x
while t_x2*TILE_W < (x+w):
t_x2 += 1
t_w = t_x2-t_x
t_y = int( y / TILE_H)
t_y2 = t_y
while t_y2*TILE_H < (y+h):
t_y2 += 1
t_h = t_y2-t_y
return t_x,t_y,t_w,t_h
(x,y) = 16.0,16.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 15.0, 15.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 16.0, 16.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 16.1, 16.1
assert get_tile(x,y,w,h) == (1,1,2,2)
(x,y) = 24.0, 24.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 24.0, 24.0
(w,h) = 8.0, 8.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 24.0, 24.0
(w,h) = 8.1, 8.1
assert get_tile(x,y,w,h) == (1,1,2,2)
(x,y) = 24.0, 24.0
(w,h) = 9.0, 9.0
assert get_tile(x,y,w,h) == (1,1,2,2)
</code></pre>
| 2 | 2009-07-10T11:01:03Z | 1,117,936 | <p>This could probably be condensed a bit more, but here you go.</p>
<pre><code>def get_tile(x,y,w,h):
x1 = int(x / TILE_W)
x2 = (x + w) / TILE_W
y1 = int(y / TILE_H)
y2 = (x + w) / TILE_H
if int(x2) == x2:
x2 = int(x2 - 1)
else:
x2 = int(x2)
if int(y2) == y2:
y2 = int(y2 - 1)
else:
y2 = int(y2)
tw = x2 - x1 + 1
th = y2 - y1 + 1
return x1, y1, tw, th
</code></pre>
| 0 | 2009-07-13T06:25:57Z | [
"python",
"algorithm",
"math",
"geometry",
"coordinates"
] |
Finding the coordinates of tiles that are covered by a rectangle with x,y,w,h pixel coordinates | 1,108,929 | <p>Say I have a tile based system using 16x16 pixels. How would you find out what tiles are covered by a rectangle defined by floating point pixel units? </p>
<p>for eg,</p>
<pre><code>rect(x=16.0,y=16.0, w=1.0, h=1.0) -> tile(x=1, y=1, w=1, h=1)
rect(x=16.0,y=16.0, w=16.0, h=16.0) -> tile(x=1, y=1, w=1, h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.0, y=8.0) -> (x=1,y=1,w=1,h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.1, y=8.1) -> (x=1,y=1,w=2,h=2)
</code></pre>
<p>The only way I can do this reliably is by using a loop. Is there a better way? Dividing by 16 gives me the wrong answer on edge cases. Here's some example code I use in python:</p>
<pre><code>#!/usr/bin/env python
import math
TILE_W = 16
TILE_H = 16
def get_tile(x,y,w,h):
t_x = int(x / TILE_W)
t_x2 = t_x
while t_x2*TILE_W < (x+w):
t_x2 += 1
t_w = t_x2-t_x
t_y = int( y / TILE_H)
t_y2 = t_y
while t_y2*TILE_H < (y+h):
t_y2 += 1
t_h = t_y2-t_y
return t_x,t_y,t_w,t_h
(x,y) = 16.0,16.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 15.0, 15.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 16.0, 16.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 16.1, 16.1
assert get_tile(x,y,w,h) == (1,1,2,2)
(x,y) = 24.0, 24.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 24.0, 24.0
(w,h) = 8.0, 8.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 24.0, 24.0
(w,h) = 8.1, 8.1
assert get_tile(x,y,w,h) == (1,1,2,2)
(x,y) = 24.0, 24.0
(w,h) = 9.0, 9.0
assert get_tile(x,y,w,h) == (1,1,2,2)
</code></pre>
| 2 | 2009-07-10T11:01:03Z | 1,164,203 | <p>Matt's solution with bug-fixes:</p>
<pre><code>from __future__ import division
import math
TILE_W = TILE_H = 16
def get_tile(x,y,w,h):
x1 = int(math.floor(x/TILE_W))
x2 = int(math.ceil((x + w)/TILE_W))
y1 = int(math.floor(y/TILE_H))
y2 = int(math.ceil((y + h)/TILE_H))
return x1, y1, x2-x1, y2-y1
</code></pre>
| 1 | 2009-07-22T09:52:56Z | [
"python",
"algorithm",
"math",
"geometry",
"coordinates"
] |
Issues with inspect.py when used inside Jython | 1,108,958 | <p>I am using an application developed in Jython. When I try to use the inspect.py in that, it shows error message.</p>
<p>My code goes like this</p>
<pre><code>import inspect,os,sys,pprint,imp
def handle_stackframe_without_leak(getframe):
frame = inspect.currentframe()
try:
function = inspect.getframeinfo(getframe)
print inspect.getargvalues(getframe)
finally:
del frame
#
def raja(a):
handle_stackframe_without_leak(inspect.currentframe())
print a
#
def callraja():
handle_stackframe_without_leak(inspect.currentframe())
raja("raja@ad.com")
#
callraja()
raja("raja@ad.com")
#
</code></pre>
<p>When I run this using python.exe, there are no issues. However, using this inside the app throwing the following error </p>
<pre><code> File "C:\Program Files\jython221ondiffjava\Lib\inspect.py", line 722, in getframeinfo
File "C:\Program Files\jython221ondiffjava\Lib\inspect.py", line 413, in findsource
File "C:\Program Files\jython221ondiffjava\Lib\sre.py", line 179, in compile
File "C:\Program Files\jython221ondiffjava\Lib\sre.py", line 227, in _compile
File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 437, in compile
File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 421, in _code
File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 143, in _compile
ValueError: ('unsupported operand type', 'branch')
at org.python.core.Py.makeException(Unknown Source)
at sre_compile$py._compile$1(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:143)
at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at sre_compile$py._code$11(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:421)
at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at sre_compile$py.compile$12(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:437)
at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.core.PyObject.invoke(Unknown Source)
at sre$py._compile$13(C:\Program Files\jython221ondiffjava\Lib\sre.py:227)
at sre$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at sre$py.compile$8(C:\Program Files\jython221ondiffjava\Lib\sre.py:179)
at sre$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.core.PyObject.invoke(Unknown Source)
at inspect$py.findsource$24(C:\Program Files\jython221ondiffjava\Lib\inspect.py:413)
at inspect$py.call_function(C:\Program Files\jython221ondiffjava\Lib\inspect.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at inspect$py.getframeinfo$54(C:\Program Files\jython221ondiffjava\Lib\inspect.py:722)
at inspect$py.call_function(C:\Program Files\jython221ondiffjava\Lib\inspect.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.core.PyObject.invoke(Unknown Source)
at custom$py.handle_stackframe_without_leak$4(C:\Program Files\<my app>\jars\custom.py:29)
at custom$py.call_function(C:\Program Files\<my app>\.\jars\custom.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at definitions$py.gotonotificationprofile$122(C:\Program Files\<my app>\.\jars\definitions.py:1738)
at definitions$py.call_function(C:\Program Files\<my app>\.\jars\definitions.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at notificationcases$py.A003$2(C:\Program Files\<my app>\.\jars\notificationcases.py:143)
at notificationcases$py.call_function(C:\Program Files\<my app>\.\jars\notificationcases.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.pycode._pyx171.f$0(003:8)
at org.python.pycode._pyx171.call_function(003)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyCode.call(Unknown Source)
at org.python.core.Py.runCode(Unknown Source)
at org.python.util.PythonInterpreter.execfile(Unknown Source)
</code></pre>
<p>Any help will be appreciated. </p>
<p>Thanks
Rajasankar</p>
| 2 | 2009-07-10T11:07:44Z | 1,112,619 | <p>This might help <a href="http://grinder.sourceforge.net/faq.html#re-problems" rel="nofollow">http://grinder.sourceforge.net/faq.html#re-problems</a>.</p>
<p>For a quick check, try adding <code>import re</code> in findsource method (<em>C:\Program Files\jython221ondiffjava\Lib\inspect.py</em>)</p>
<pre><code>
def findsource(object):
"""Return the entire source file and starting line number for an object.
(...snip...)"""
import re
file = getsourcefile(object) or getfile(object)
</code></pre>
<p>Can't promise anything, though... </p>
| 0 | 2009-07-11T00:58:54Z | [
"python",
"module",
"jython",
"inspect"
] |
Issues with inspect.py when used inside Jython | 1,108,958 | <p>I am using an application developed in Jython. When I try to use the inspect.py in that, it shows error message.</p>
<p>My code goes like this</p>
<pre><code>import inspect,os,sys,pprint,imp
def handle_stackframe_without_leak(getframe):
frame = inspect.currentframe()
try:
function = inspect.getframeinfo(getframe)
print inspect.getargvalues(getframe)
finally:
del frame
#
def raja(a):
handle_stackframe_without_leak(inspect.currentframe())
print a
#
def callraja():
handle_stackframe_without_leak(inspect.currentframe())
raja("raja@ad.com")
#
callraja()
raja("raja@ad.com")
#
</code></pre>
<p>When I run this using python.exe, there are no issues. However, using this inside the app throwing the following error </p>
<pre><code> File "C:\Program Files\jython221ondiffjava\Lib\inspect.py", line 722, in getframeinfo
File "C:\Program Files\jython221ondiffjava\Lib\inspect.py", line 413, in findsource
File "C:\Program Files\jython221ondiffjava\Lib\sre.py", line 179, in compile
File "C:\Program Files\jython221ondiffjava\Lib\sre.py", line 227, in _compile
File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 437, in compile
File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 421, in _code
File "C:\Program Files\jython221ondiffjava\Lib\sre_compile.py", line 143, in _compile
ValueError: ('unsupported operand type', 'branch')
at org.python.core.Py.makeException(Unknown Source)
at sre_compile$py._compile$1(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:143)
at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at sre_compile$py._code$11(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:421)
at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at sre_compile$py.compile$12(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py:437)
at sre_compile$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre_compile.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.core.PyObject.invoke(Unknown Source)
at sre$py._compile$13(C:\Program Files\jython221ondiffjava\Lib\sre.py:227)
at sre$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at sre$py.compile$8(C:\Program Files\jython221ondiffjava\Lib\sre.py:179)
at sre$py.call_function(C:\Program Files\jython221ondiffjava\Lib\sre.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.core.PyObject.invoke(Unknown Source)
at inspect$py.findsource$24(C:\Program Files\jython221ondiffjava\Lib\inspect.py:413)
at inspect$py.call_function(C:\Program Files\jython221ondiffjava\Lib\inspect.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at inspect$py.getframeinfo$54(C:\Program Files\jython221ondiffjava\Lib\inspect.py:722)
at inspect$py.call_function(C:\Program Files\jython221ondiffjava\Lib\inspect.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.core.PyObject.invoke(Unknown Source)
at custom$py.handle_stackframe_without_leak$4(C:\Program Files\<my app>\jars\custom.py:29)
at custom$py.call_function(C:\Program Files\<my app>\.\jars\custom.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at definitions$py.gotonotificationprofile$122(C:\Program Files\<my app>\.\jars\definitions.py:1738)
at definitions$py.call_function(C:\Program Files\<my app>\.\jars\definitions.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at notificationcases$py.A003$2(C:\Program Files\<my app>\.\jars\notificationcases.py:143)
at notificationcases$py.call_function(C:\Program Files\<my app>\.\jars\notificationcases.py)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyFunction.__call__(Unknown Source)
at org.python.pycode._pyx171.f$0(003:8)
at org.python.pycode._pyx171.call_function(003)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyCode.call(Unknown Source)
at org.python.core.Py.runCode(Unknown Source)
at org.python.util.PythonInterpreter.execfile(Unknown Source)
</code></pre>
<p>Any help will be appreciated. </p>
<p>Thanks
Rajasankar</p>
| 2 | 2009-07-10T11:07:44Z | 1,167,318 | <p>Have you tried running your program on the command line with Jython (so outside of the app)? When I run your program with Jython 2.2.1 or Jython 2.5.0, I get identical output as from Python.</p>
| 1 | 2009-07-22T18:42:09Z | [
"python",
"module",
"jython",
"inspect"
] |
Separation of ORM and validation | 1,108,967 | <p>I use django and I wonder in what cases where model validation should go. There are at least two variants:</p>
<ol>
<li>Validate in the model's save method and to raise IntegrityError or another exception if business rules were violated</li>
<li>Validate data using forms and built-in clean_* facilities</li>
</ol>
<p>From one point of view, answer is obvious: one should use form-based validation. It is because ORM is ORM and validation is completely another concept. Take a look at CharField: forms.CharField allows min_length specification, but models.CharField does not.
Ok cool, but what the hell all that validation features are doing in django.db.models? I can specify that CharField can't be blank, I can use EmailField, FileField, SlugField validation of which are performed here, in python, not on RDBMS. Furthermore there is the URLField which checks <em>existance</em> of url involving some really complex logic.</p>
<p>From another side, if I have an entity I want to guarantee that it will not be saved in inconsistent state whether it came from a form or was modified/created by some internal algorithms. I have a model with name field, I expect it should be longer than one character. I have a min_age and a max_age fields also, it makes not much sense if min_age > max_age. So should I check such conditions in save method?</p>
<p>What are the best practices of model validation?</p>
| 0 | 2009-07-10T11:09:37Z | 1,108,987 | <p>I am not sure if this is best practise but what I do is that I tend to validate both client side and server side before pushing the data to the database. I know it requires a lot more effort but this can be done by setting some values before use and then maintaining them.</p>
<p>You could also try push in size contraints with **kwargs into a validation function that is called before the put() call.</p>
| 0 | 2009-07-10T11:17:22Z | [
"python",
"django",
"validation",
"architecture",
"django-models"
] |
Separation of ORM and validation | 1,108,967 | <p>I use django and I wonder in what cases where model validation should go. There are at least two variants:</p>
<ol>
<li>Validate in the model's save method and to raise IntegrityError or another exception if business rules were violated</li>
<li>Validate data using forms and built-in clean_* facilities</li>
</ol>
<p>From one point of view, answer is obvious: one should use form-based validation. It is because ORM is ORM and validation is completely another concept. Take a look at CharField: forms.CharField allows min_length specification, but models.CharField does not.
Ok cool, but what the hell all that validation features are doing in django.db.models? I can specify that CharField can't be blank, I can use EmailField, FileField, SlugField validation of which are performed here, in python, not on RDBMS. Furthermore there is the URLField which checks <em>existance</em> of url involving some really complex logic.</p>
<p>From another side, if I have an entity I want to guarantee that it will not be saved in inconsistent state whether it came from a form or was modified/created by some internal algorithms. I have a model with name field, I expect it should be longer than one character. I have a min_age and a max_age fields also, it makes not much sense if min_age > max_age. So should I check such conditions in save method?</p>
<p>What are the best practices of model validation?</p>
| 0 | 2009-07-10T11:09:37Z | 1,109,190 | <p>Your two options are two different things.</p>
<ul>
<li>Form-based validation can be regarded as syntactic validation + convert HTTP request parameters from text to Python types.</li>
<li>Model-based validation can be regarded as semantic validation, sometimes using context not available at the HTTP/form layer.</li>
</ul>
<p>And of course there is a third layer at the DB where constraints are enforced, and may not be checkable anywhere else because of concurrent requests updating the database (e.g. uniqueness constraints, optimistic locking).</p>
| 0 | 2009-07-10T12:14:50Z | [
"python",
"django",
"validation",
"architecture",
"django-models"
] |
Separation of ORM and validation | 1,108,967 | <p>I use django and I wonder in what cases where model validation should go. There are at least two variants:</p>
<ol>
<li>Validate in the model's save method and to raise IntegrityError or another exception if business rules were violated</li>
<li>Validate data using forms and built-in clean_* facilities</li>
</ol>
<p>From one point of view, answer is obvious: one should use form-based validation. It is because ORM is ORM and validation is completely another concept. Take a look at CharField: forms.CharField allows min_length specification, but models.CharField does not.
Ok cool, but what the hell all that validation features are doing in django.db.models? I can specify that CharField can't be blank, I can use EmailField, FileField, SlugField validation of which are performed here, in python, not on RDBMS. Furthermore there is the URLField which checks <em>existance</em> of url involving some really complex logic.</p>
<p>From another side, if I have an entity I want to guarantee that it will not be saved in inconsistent state whether it came from a form or was modified/created by some internal algorithms. I have a model with name field, I expect it should be longer than one character. I have a min_age and a max_age fields also, it makes not much sense if min_age > max_age. So should I check such conditions in save method?</p>
<p>What are the best practices of model validation?</p>
| 0 | 2009-07-10T11:09:37Z | 1,109,221 | <p>There's an ongoing Google Summer of Code project that aims to bring validation to the Django model layer. You can read more about it in <a href="http://www.honzakral.com/validation.pdf" rel="nofollow">this presentation</a> from the GSoC student (Honza Kral). There's also a <a href="http://github.com/HonzaKral/django/tree/model-validation" rel="nofollow">github repository</a> with the preliminary code.</p>
<p>Until that code finds its way into a Django release, one recommended approach is to use ModelForms to validate data, even if the source isn't a form. It's described in <a href="http://www.pointy-stick.com/blog/2008/10/15/django-tip-poor-mans-model-validation/" rel="nofollow">this blog entry</a> from one of the Django core devs.</p>
| 0 | 2009-07-10T12:24:50Z | [
"python",
"django",
"validation",
"architecture",
"django-models"
] |
Separation of ORM and validation | 1,108,967 | <p>I use django and I wonder in what cases where model validation should go. There are at least two variants:</p>
<ol>
<li>Validate in the model's save method and to raise IntegrityError or another exception if business rules were violated</li>
<li>Validate data using forms and built-in clean_* facilities</li>
</ol>
<p>From one point of view, answer is obvious: one should use form-based validation. It is because ORM is ORM and validation is completely another concept. Take a look at CharField: forms.CharField allows min_length specification, but models.CharField does not.
Ok cool, but what the hell all that validation features are doing in django.db.models? I can specify that CharField can't be blank, I can use EmailField, FileField, SlugField validation of which are performed here, in python, not on RDBMS. Furthermore there is the URLField which checks <em>existance</em> of url involving some really complex logic.</p>
<p>From another side, if I have an entity I want to guarantee that it will not be saved in inconsistent state whether it came from a form or was modified/created by some internal algorithms. I have a model with name field, I expect it should be longer than one character. I have a min_age and a max_age fields also, it makes not much sense if min_age > max_age. So should I check such conditions in save method?</p>
<p>What are the best practices of model validation?</p>
| 0 | 2009-07-10T11:09:37Z | 1,109,327 | <p><strong>"but what the hell all that validation features are doing in django.db.models? "</strong></p>
<p>One word: Legacy. Early versions of Django had less robust forms and the validation was scattered.</p>
<p><strong>"So should I check such conditions in save method?"</strong></p>
<p>No, you should use a form for all validation.</p>
<p><strong>"What are the best practices of model validation?"*</strong></p>
<p>Use a form for all validation.</p>
<p><strong>"whether it came from a form or was modified/created by some internal algorithms"</strong></p>
<p>What? If your algorithms suffer from psychotic episodes or your programmers are sociopaths, then -- perhaps -- you have to validate internally-generated data. </p>
<p>Otherwise, internally-generated data is -- by definition -- valid. Only user data can be invalid. If you don't trust your software, what's the point of writing it? Are your unit tests broken?</p>
| 0 | 2009-07-10T12:49:43Z | [
"python",
"django",
"validation",
"architecture",
"django-models"
] |
Separation of ORM and validation | 1,108,967 | <p>I use django and I wonder in what cases where model validation should go. There are at least two variants:</p>
<ol>
<li>Validate in the model's save method and to raise IntegrityError or another exception if business rules were violated</li>
<li>Validate data using forms and built-in clean_* facilities</li>
</ol>
<p>From one point of view, answer is obvious: one should use form-based validation. It is because ORM is ORM and validation is completely another concept. Take a look at CharField: forms.CharField allows min_length specification, but models.CharField does not.
Ok cool, but what the hell all that validation features are doing in django.db.models? I can specify that CharField can't be blank, I can use EmailField, FileField, SlugField validation of which are performed here, in python, not on RDBMS. Furthermore there is the URLField which checks <em>existance</em> of url involving some really complex logic.</p>
<p>From another side, if I have an entity I want to guarantee that it will not be saved in inconsistent state whether it came from a form or was modified/created by some internal algorithms. I have a model with name field, I expect it should be longer than one character. I have a min_age and a max_age fields also, it makes not much sense if min_age > max_age. So should I check such conditions in save method?</p>
<p>What are the best practices of model validation?</p>
| 0 | 2009-07-10T11:09:37Z | 1,111,592 | <p><strong>DB/Model validation</strong></p>
<p>The data store in database must always be in a certain form/state. For example: required first name, last name, foreign key, unique constraint. This is where the logic of you app resides. No matter where you think the data comes from - it should be "validated" here and an exception raised if the requirements are not met.</p>
<p><strong>Form validation</strong></p>
<p>Data being entered should <em>look</em> right. It is ok if this data is entered differently through some other means (through admin or api calls).
Examples: length of person's name, proper capitalization of the sentence...</p>
<p><strong>Example1</strong>: Object has a <em>StartDate</em> and an <em>EndDate</em>. <em>StartDate</em> must always be before <em>EndDate</em>. Where do you validate this? In the model of course! Consider a case when you might be importing data from some other system - you don't want this to go through.</p>
<p><strong>Example2</strong>: Password confirmation. You have a field for storing the password in the db. However you display two fields: password1 and password2 on your form. The form, and only the form, is responsible for comparing those two fields to see that they are the same. After form is valid you can safely store the password1 field into the db as the password.</p>
| 0 | 2009-07-10T19:43:55Z | [
"python",
"django",
"validation",
"architecture",
"django-models"
] |
switch versions of python | 1,108,974 | <p>Story:
One of the app that i have works on python 2.4 and other on 2.6. I tried to do a sym link of python2.4 to python and things started to break loose on ubuntu jaunty.
Now i am downloading every dependency of 2.4 and installing it using python2.4 setup.py install. The dependencies seem to be endless.</p>
<p>Question1: How will i tell any framework that go and use version so and so pf python like day django to use 2.6 and say mjango to use 2.4? Something like we say use database databasename kinda syntax.</p>
<p>Question2: Is there more elegant way to switch between version as my hack of symlinking was a virtual disaster?</p>
<p>Question3: Can I download a deb for say hardy and make jaunty believe its for her?</p>
| 14 | 2009-07-10T11:12:53Z | 1,108,999 | <p>Use <a href="http://pypi.python.org/pypi/virtualenv">Virtualenv</a>.</p>
<p>There is more information here: <a href="http://web.archive.org/web/20120303203403/http://www.arthurkoziel.com/2008/10/22/working-virtualenv/">Working with virtualenv</a>.</p>
<p>Using virtualenv you can create a new virtual python environment with whatever version of Python you want for each project or application. You can then activate the appropriate environment when you need it.</p>
<p><strong>To expand on my answer:</strong></p>
<p>You can install multiple versions of Python on your computer (I have 2.4, 2.5, 2.6 and 3.1 on my machine - I install each from source). I use a Mac, and keep my system Python as whatever OS X sets as the default.</p>
<p>I use *easy_install* to install packages. On ubuntu you can get easy_install like this:</p>
<pre><code>sudo apt-get install python-setuptools
</code></pre>
<p>To install virtualenv then do:</p>
<pre><code>easy_install virtualenv
</code></pre>
<p>I tend to create a new virtualenv for each project I'm working on and don't give it access to the global site-packages. This keeps all the packages tight together and allows me to have the specific versions of everything I need.</p>
<pre><code>virtualenv -p python2.6 --no-site-packages ~/env/NEW_DJANGO_PROJECT
</code></pre>
<p>And then whenever I am doing anything related to this project I activate it:</p>
<pre><code>source ~/env/NEW_DJANGO_PROJECT/bin/activate
</code></pre>
<p>If I run python now it uses this new python. If I use easy_install it installs things into my new virtual environment.</p>
<p>So, virtualenv should be able to solve all of your problems.</p>
| 30 | 2009-07-10T11:19:31Z | [
"python",
"development-environment",
"ubuntu-9.04"
] |
switch versions of python | 1,108,974 | <p>Story:
One of the app that i have works on python 2.4 and other on 2.6. I tried to do a sym link of python2.4 to python and things started to break loose on ubuntu jaunty.
Now i am downloading every dependency of 2.4 and installing it using python2.4 setup.py install. The dependencies seem to be endless.</p>
<p>Question1: How will i tell any framework that go and use version so and so pf python like day django to use 2.6 and say mjango to use 2.4? Something like we say use database databasename kinda syntax.</p>
<p>Question2: Is there more elegant way to switch between version as my hack of symlinking was a virtual disaster?</p>
<p>Question3: Can I download a deb for say hardy and make jaunty believe its for her?</p>
| 14 | 2009-07-10T11:12:53Z | 1,109,135 | <p>A more grassroot approach than Virtualenv is the side-by-side installation of two Python versions.</p>
<p>If there is an existing installation, and you want a second installation into the same root path (e.g. /usr/local), use this target when making install:</p>
<pre><code>make altinstall
</code></pre>
<p>When your second installation is Python 2.6, this will leave you with a /usr/local/bin/python2.6 alongside the old /usr/local/bin/python.</p>
<p>A simple way to switch between these two versions is using a shell alias (alias python=/usr/local/bin/python2.6) on the shell where you invoke the interpreter. But this won't work across sub-shells and she-bang invocations.</p>
| 3 | 2009-07-10T11:57:08Z | [
"python",
"development-environment",
"ubuntu-9.04"
] |
switch versions of python | 1,108,974 | <p>Story:
One of the app that i have works on python 2.4 and other on 2.6. I tried to do a sym link of python2.4 to python and things started to break loose on ubuntu jaunty.
Now i am downloading every dependency of 2.4 and installing it using python2.4 setup.py install. The dependencies seem to be endless.</p>
<p>Question1: How will i tell any framework that go and use version so and so pf python like day django to use 2.6 and say mjango to use 2.4? Something like we say use database databasename kinda syntax.</p>
<p>Question2: Is there more elegant way to switch between version as my hack of symlinking was a virtual disaster?</p>
<p>Question3: Can I download a deb for say hardy and make jaunty believe its for her?</p>
| 14 | 2009-07-10T11:12:53Z | 1,109,305 | <p>"Question1: How will i tell any framework that go and use version so and so pf python like day django to use 2.6 and say mjango to use 2.4?"</p>
<p>You simply run them with the specific python version they need. Run mjango with /usr/bin/python2.4 and django with /usr/bin/python2.6. As easy as that.</p>
<p>"Question2: Is there more elegant way to switch between version as my hack of symlinking was a virtual disaster?"</p>
<p>Yes, see above. Have two separate installs of Python, and run explicitly with the different versions.</p>
<p>"Question3: Can I download a deb for say hardy and make jaunty believe its for her?"</p>
<p>That generally works. If it doesn't, it's because it has dependencies that exist in Hardy, and does not exist in Jaunty, and then you can't.</p>
<p>And here is a Question 4 you didn't ask, but should have. ;)</p>
<p>"Is there an easier way to download all those Python modules?"</p>
<p>Yes, there is. Install setuptools, and use easy_install. It will not help you with library dependecies for those Python modules that have C code and need to be compiled. But it <em>will</em> help with all others. easy_install will download and install all the Python dependencies of the module in question in one go. That makes it a lot quicker to install Python modules.</p>
| 1 | 2009-07-10T12:43:57Z | [
"python",
"development-environment",
"ubuntu-9.04"
] |
switch versions of python | 1,108,974 | <p>Story:
One of the app that i have works on python 2.4 and other on 2.6. I tried to do a sym link of python2.4 to python and things started to break loose on ubuntu jaunty.
Now i am downloading every dependency of 2.4 and installing it using python2.4 setup.py install. The dependencies seem to be endless.</p>
<p>Question1: How will i tell any framework that go and use version so and so pf python like day django to use 2.6 and say mjango to use 2.4? Something like we say use database databasename kinda syntax.</p>
<p>Question2: Is there more elegant way to switch between version as my hack of symlinking was a virtual disaster?</p>
<p>Question3: Can I download a deb for say hardy and make jaunty believe its for her?</p>
| 14 | 2009-07-10T11:12:53Z | 9,547,468 | <p>I find <a href="http://github.com/utahta/pythonbrew" rel="nofollow">http://github.com/utahta/pythonbrew</a> much easier to install and use than any other solution.</p>
<p>Just install it and you'll have these options:</p>
<pre><code>pythonbrew install 2.7.2
pythonbrew use 2.7.2 # use 2.7.2 for a current terminal session
pythonbrew switch 2.7.2 # use 2.7.2 by default system wide
pythonbrew uninstall 2.7.2
</code></pre>
<p><em>Note:</em> if you use Linux operating system with preinstalled Python, switching (system wide) to another version can make things go wrong, so be careful.</p>
| 2 | 2012-03-03T15:57:54Z | [
"python",
"development-environment",
"ubuntu-9.04"
] |
switch versions of python | 1,108,974 | <p>Story:
One of the app that i have works on python 2.4 and other on 2.6. I tried to do a sym link of python2.4 to python and things started to break loose on ubuntu jaunty.
Now i am downloading every dependency of 2.4 and installing it using python2.4 setup.py install. The dependencies seem to be endless.</p>
<p>Question1: How will i tell any framework that go and use version so and so pf python like day django to use 2.6 and say mjango to use 2.4? Something like we say use database databasename kinda syntax.</p>
<p>Question2: Is there more elegant way to switch between version as my hack of symlinking was a virtual disaster?</p>
<p>Question3: Can I download a deb for say hardy and make jaunty believe its for her?</p>
| 14 | 2009-07-10T11:12:53Z | 10,750,234 | <p>Pythonbrew is a magical tool. Which can also be called as Python version manager similar to that of RVM-Ruby version manager but Pythonbrew is inspired by Perlbrew.</p>
<p>Pythonbrew is a program to automate the building and installation of Python in the users $HOME.</p>
<pre><code> Dependencies â curl
</code></pre>
<p>Before Installing the Pythonbrew, Install âcurlâ in the machine, to install curl use the below command in the terminal, give the the password for the user when prompted.</p>
<pre><code> $sudo apt-get install curl
</code></pre>
<p>After Installing the curl, Now Install Pythonbrew, copy and paste the following commands in the terminal and type the password for the user when prompted.</p>
<p>Recomended method of installation - Easy Install</p>
<pre><code> $ sudo easy_install pythonbrew
</code></pre>
<p>To complete the installation, type the following command</p>
<pre><code> $pythonbrew_install
</code></pre>
<p>Alternate method of installation:</p>
<p>Use curl command to download the latest version of pythonbrew from github.</p>
<pre><code>curl -kLO http://github.com/utahta/pythonbrew/raw/master/pythonbrew-install
</code></pre>
<p>After downloading, change âpythonbrew-installâ to âexecutableâ</p>
<pre><code> chmod +x pythonbrew-install
</code></pre>
<p>Then, run the pythonbrew-install in the terminal</p>
<pre><code>./pythonbrew-install
</code></pre>
<p>Now the Pythonbrew has been installed in the <code>âHome Directoryâ</code> i.e., <code>/home/user/.pythonbrew</code></p>
<p>Next, copy and paste the following line to the end of ~/.bashrc</p>
<p>*NOTE: change <code>âuserâ</code> to your user name in the system</p>
<pre><code>source /home/user/.pythonbrew/etc/bashrc
</code></pre>
<p>Thats it! Close the terminal.
Steps to Install different versions of Python:</p>
<p>Open a new terminal, type the following command or copy and paste it.</p>
<pre><code>$pythonbrew install 2.6.6
</code></pre>
<p>This will install Python 2.6.6 and to install Python 2.7 or Python 3.2, change the version number in the previous command.</p>
<pre><code>$pythonbrew install 2.7
</code></pre>
<p>or</p>
<pre><code>$pythonbrew install 3.2
</code></pre>
<p>Update: If you get error while Installing then Install using the below command.</p>
<pre><code>$pythonbrew install --force 2.7
</code></pre>
<p>or</p>
<pre><code>$pythonbrew install --force 3.2
</code></pre>
<p>How to manage different versions of Python installed in system</p>
<p>For instance, if Python <code>2.6.6</code>, <code>Python 2.7</code> and <code>Python 3.2</code> is installed in your system, switching between the versions can be done as follows:</p>
<p>By default, <code>Python 2.6.6</code> will be active and in order to switch to Python 2.7 use the below command</p>
<pre><code>$pythonbrew switch 2.7
</code></pre>
<p>The default Python is changed to Python 2.7.</p>
<p>Now, to switch to Python 3.2 change the version number in the previous command.</p>
<pre><code>$pythonbrew switch 3.2
</code></pre>
<p>Use the below command to check or list the installed Python versions</p>
<pre><code>$pythonbrew list
</code></pre>
<p>Use the below command to check or list the available Python Versions to install</p>
<pre><code>$pythonbrew list -k
</code></pre>
<p>To uninstall any of the installed Python version (for example to uninstall Python 2.7), use the below command.</p>
<pre><code>$pythonbrew uninstall 2.7
</code></pre>
<p>Use the below command to update the <code>Pythonbrew</code></p>
<pre><code>$pythonbrew update
</code></pre>
<p>Use the below command to disable the <code>Pythonbrew</code> and to activate the default version</p>
<pre><code>$pythonbrew off
</code></pre>
<p>Enjoy the experience of installing multiple versions of Python in single Linux / ubuntu machine!</p>
| 6 | 2012-05-25T07:26:01Z | [
"python",
"development-environment",
"ubuntu-9.04"
] |
switch versions of python | 1,108,974 | <p>Story:
One of the app that i have works on python 2.4 and other on 2.6. I tried to do a sym link of python2.4 to python and things started to break loose on ubuntu jaunty.
Now i am downloading every dependency of 2.4 and installing it using python2.4 setup.py install. The dependencies seem to be endless.</p>
<p>Question1: How will i tell any framework that go and use version so and so pf python like day django to use 2.6 and say mjango to use 2.4? Something like we say use database databasename kinda syntax.</p>
<p>Question2: Is there more elegant way to switch between version as my hack of symlinking was a virtual disaster?</p>
<p>Question3: Can I download a deb for say hardy and make jaunty believe its for her?</p>
| 14 | 2009-07-10T11:12:53Z | 27,402,164 | <p><a href="https://github.com/yyuu/pyenv" rel="nofollow">pyenv</a> is yet another Python manager. The README.md at that link has a good set of instructions, but they basically are:</p>
<pre><code>$ cd
$ git clone git://github.com/yyuu/pyenv.git .pyenv
</code></pre>
<p>Then set up your $PATH.</p>
<pre><code>$ echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
$ echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
</code></pre>
<p>Install the desired versions of Python:</p>
<pre><code>$ pyenv install 2.7.8
</code></pre>
<p>After installing you need to run this:</p>
<pre><code>$ pyenv rehash
</code></pre>
<p>Then switch to the version of Python you want to run, for the shell:</p>
<pre><code>$ pyenv shell 2.7.8
</code></pre>
| 0 | 2014-12-10T13:24:32Z | [
"python",
"development-environment",
"ubuntu-9.04"
] |
switch versions of python | 1,108,974 | <p>Story:
One of the app that i have works on python 2.4 and other on 2.6. I tried to do a sym link of python2.4 to python and things started to break loose on ubuntu jaunty.
Now i am downloading every dependency of 2.4 and installing it using python2.4 setup.py install. The dependencies seem to be endless.</p>
<p>Question1: How will i tell any framework that go and use version so and so pf python like day django to use 2.6 and say mjango to use 2.4? Something like we say use database databasename kinda syntax.</p>
<p>Question2: Is there more elegant way to switch between version as my hack of symlinking was a virtual disaster?</p>
<p>Question3: Can I download a deb for say hardy and make jaunty believe its for her?</p>
| 14 | 2009-07-10T11:12:53Z | 35,381,570 | <p>Move to the project directory :</p>
<p>Create an environment :
virtualenv -p python2.7 --no-site-packages ~/env/twoseven</p>
<p>Then activate your source :
source ~/env/twoseven/bin/activate</p>
| 0 | 2016-02-13T15:18:51Z | [
"python",
"development-environment",
"ubuntu-9.04"
] |
Getting list of pixel values from PIL | 1,109,422 | <p>Guys, I'm looking for a bit of assistance. I'm a newbie programmer and one of the problems I'm having at the minute is trying to convert a black & white <code>.jpg</code> image into a list which I can then modulate into an audio signal. This is part of a lager project to create a python SSTV program.</p>
<p>I have imported the PIL module and am trying to call the built-in function: <code>list(im.getdata())</code>. When I call it, python crashes. Is there some way of breaking down the image (always 320x240) into 240 lines to make the computations easier? Or am I just calling the wrong function.</p>
<p>If anyone has any suggestions please fire away. If anyone has experience of generating modulated audio tones using python I would gladly accept any 'pearls of wisdom' they are willing to impart.
Thanks in advance</p>
| 12 | 2009-07-10T13:08:07Z | 1,109,747 | <p>Python shouldn't crash when you call getdata(). The image might be corrupted or there is something wrong with your PIL installation. Try it with another image or post the image you are using.</p>
<p>This should break down the image the way you want:</p>
<pre><code>from PIL import Image
im = Image.open('um_000000.png')
pixels = list(im.getdata())
width, height = im.size
pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)]
</code></pre>
| 29 | 2009-07-10T14:04:23Z | [
"python",
"image",
"python-imaging-library"
] |
Getting list of pixel values from PIL | 1,109,422 | <p>Guys, I'm looking for a bit of assistance. I'm a newbie programmer and one of the problems I'm having at the minute is trying to convert a black & white <code>.jpg</code> image into a list which I can then modulate into an audio signal. This is part of a lager project to create a python SSTV program.</p>
<p>I have imported the PIL module and am trying to call the built-in function: <code>list(im.getdata())</code>. When I call it, python crashes. Is there some way of breaking down the image (always 320x240) into 240 lines to make the computations easier? Or am I just calling the wrong function.</p>
<p>If anyone has any suggestions please fire away. If anyone has experience of generating modulated audio tones using python I would gladly accept any 'pearls of wisdom' they are willing to impart.
Thanks in advance</p>
| 12 | 2009-07-10T13:08:07Z | 1,110,124 | <p>If you have <a href="http://numpy.scipy.org/">numpy</a> installed you can try:</p>
<pre><code>data = numpy.asarray(im)
</code></pre>
<p>(I say "try" here, because it's unclear why <code>getdata()</code> isn't working for you, and I don't know whether <code>asarray</code> uses getdata, but it's worth a test.)</p>
| 13 | 2009-07-10T15:12:52Z | [
"python",
"image",
"python-imaging-library"
] |
Getting list of pixel values from PIL | 1,109,422 | <p>Guys, I'm looking for a bit of assistance. I'm a newbie programmer and one of the problems I'm having at the minute is trying to convert a black & white <code>.jpg</code> image into a list which I can then modulate into an audio signal. This is part of a lager project to create a python SSTV program.</p>
<p>I have imported the PIL module and am trying to call the built-in function: <code>list(im.getdata())</code>. When I call it, python crashes. Is there some way of breaking down the image (always 320x240) into 240 lines to make the computations easier? Or am I just calling the wrong function.</p>
<p>If anyone has any suggestions please fire away. If anyone has experience of generating modulated audio tones using python I would gladly accept any 'pearls of wisdom' they are willing to impart.
Thanks in advance</p>
| 12 | 2009-07-10T13:08:07Z | 1,111,950 | <p>I assume you are getting an error like.. <code>TypeError: 'PixelAccess' object is not iterable</code>...?</p>
<p>See the <a href="http://effbot.org/imagingbook/image.htm#tag-Image.Image.load">Image.load</a> documentation for how to access pixels..</p>
<p>Basically, to get the list of pixels in an image, using <code>PIL</code>:</p>
<pre><code>from PIL import Image
i = Image.open("myfile.png")
pixels = i.load() # this is not a list, nor is it list()'able
width, height = i.size
all_pixels = []
for x in range(width):
for y in range(height):
cpixel = pixels[x, y]
all_pixels.append(cpixel)
</code></pre>
<p>That appends every pixel to the <code>all_pixels</code> - if the file is an RGB image (even if it only contains a black-and-white image) these will be a tuple, for example:</p>
<pre><code>(255, 255, 255)
</code></pre>
<p>To convert the image to monochrome, you just average the three values - so, the last three lines of code would become..</p>
<pre><code>cpixel = pixels[x, y]
bw_value = int(round(sum(cpixel) / float(len(cpixel))))
# the above could probably be bw_value = sum(cpixel)/len(cpixel)
all_pixels.append(bw_value)
</code></pre>
<p>Or to get the luminance (weighted average):</p>
<pre><code>cpixel = pixels[x, y]
luma = (0.3 * cpixel[0]) + (0.59 * cpixel[1]) + (0.11 * cpixel[2])
all_pixels.append(luma)
</code></pre>
<p>Or pure 1-bit looking black and white:</p>
<pre><code>cpixel = pixels[x, y]
if round(sum(cpixel)) / float(len(cpixel)) > 127:
all_pixels.append(255)
else:
all_pixels.append(0)
</code></pre>
<p>There is probably methods within PIL to do such <code>RGB -> BW</code> conversions quicker, but this works, and isn't particularly slow.</p>
<p>If you only want to perform calculations on each row, you could skip adding all the pixels to an intermediate list.. For example, to calculate the average value of each row:</p>
<pre><code>from PIL import Image
i = Image.open("myfile.png")
pixels = i.load() # this is not a list
width, height = i.size
row_averages = []
for y in range(height):
cur_row_ttl = 0
for x in range(width):
cur_pixel = pixels[x, y]
cur_pixel_mono = sum(cur_pixel) / len(cur_pixel)
cur_row_ttl += cur_pixel_mono
cur_row_avg = cur_row_ttl / width
row_averages.append(cur_row_avg)
print "Brighest row:",
print max(row_averages)
</code></pre>
| 10 | 2009-07-10T20:55:24Z | [
"python",
"image",
"python-imaging-library"
] |
Getting list of pixel values from PIL | 1,109,422 | <p>Guys, I'm looking for a bit of assistance. I'm a newbie programmer and one of the problems I'm having at the minute is trying to convert a black & white <code>.jpg</code> image into a list which I can then modulate into an audio signal. This is part of a lager project to create a python SSTV program.</p>
<p>I have imported the PIL module and am trying to call the built-in function: <code>list(im.getdata())</code>. When I call it, python crashes. Is there some way of breaking down the image (always 320x240) into 240 lines to make the computations easier? Or am I just calling the wrong function.</p>
<p>If anyone has any suggestions please fire away. If anyone has experience of generating modulated audio tones using python I would gladly accept any 'pearls of wisdom' they are willing to impart.
Thanks in advance</p>
| 12 | 2009-07-10T13:08:07Z | 20,018,486 | <p>Or if you want to count white or black pixels</p>
<p>This is also a solution:</p>
<pre><code>from PIL import Image
import operator
img = Image.open("your_file.png").convert('1')
black, white = img.getcolors()
print black[0]
print white[0]
</code></pre>
| 2 | 2013-11-16T12:31:29Z | [
"python",
"image",
"python-imaging-library"
] |
Getting list of pixel values from PIL | 1,109,422 | <p>Guys, I'm looking for a bit of assistance. I'm a newbie programmer and one of the problems I'm having at the minute is trying to convert a black & white <code>.jpg</code> image into a list which I can then modulate into an audio signal. This is part of a lager project to create a python SSTV program.</p>
<p>I have imported the PIL module and am trying to call the built-in function: <code>list(im.getdata())</code>. When I call it, python crashes. Is there some way of breaking down the image (always 320x240) into 240 lines to make the computations easier? Or am I just calling the wrong function.</p>
<p>If anyone has any suggestions please fire away. If anyone has experience of generating modulated audio tones using python I would gladly accept any 'pearls of wisdom' they are willing to impart.
Thanks in advance</p>
| 12 | 2009-07-10T13:08:07Z | 22,503,379 | <p>As I commented above, problem seems to be the conversion from PIL internal list format to a standard python list type. I've found that Image.tostring() is much faster, and depending on your needs it might be enough. In my case, I needed to calculate the CRC32 digest of image data, and it suited fine.</p>
<p>If you need to perform more complex calculations, tom10 response involving numpy might be what you need.</p>
| 1 | 2014-03-19T10:49:16Z | [
"python",
"image",
"python-imaging-library"
] |
Getting list of pixel values from PIL | 1,109,422 | <p>Guys, I'm looking for a bit of assistance. I'm a newbie programmer and one of the problems I'm having at the minute is trying to convert a black & white <code>.jpg</code> image into a list which I can then modulate into an audio signal. This is part of a lager project to create a python SSTV program.</p>
<p>I have imported the PIL module and am trying to call the built-in function: <code>list(im.getdata())</code>. When I call it, python crashes. Is there some way of breaking down the image (always 320x240) into 240 lines to make the computations easier? Or am I just calling the wrong function.</p>
<p>If anyone has any suggestions please fire away. If anyone has experience of generating modulated audio tones using python I would gladly accept any 'pearls of wisdom' they are willing to impart.
Thanks in advance</p>
| 12 | 2009-07-10T13:08:07Z | 38,550,318 | <p>Not PIL, but <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imread.html" rel="nofollow"><code>scipy.misc.imread</code></a> might still be interesting:</p>
<pre><code>import scipy.misc
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
print(im.shape)
</code></pre>
<p>gives</p>
<pre><code>(480, 640, 3)
</code></pre>
<p>so it is (height, width, channels). So you can iterate over it by</p>
<pre><code>for y in range(im.shape[0]):
for x in range(im.shape[1]):
color = tuple(im[y][x])
r, g, b = color
</code></pre>
| 0 | 2016-07-24T08:56:36Z | [
"python",
"image",
"python-imaging-library"
] |
What's a good way to render outlined fonts? | 1,109,498 | <p>I'm writing a game in python with pygame and need to render text onto the screen.</p>
<p>I want to render this text in one colour with an outline, so that I don't have to worry about what sort of background the the text is being displayed over.</p>
<p>pygame.font doesn't seem to offer support for doing this sort of thing directly, and I'm wondering if anyone has any good solutions for achieving this?</p>
| 6 | 2009-07-10T13:24:56Z | 1,109,548 | <p>I can give you a quick and <em>bad</em> solution:<br><br>
print the text 8 times, to surround it, plus one more time for the inner text, like this</p>
<pre><code>UUU
UIU
UUU
</code></pre>
<p>U for outer color and I for the inner color.</p>
| 2 | 2009-07-10T13:35:01Z | [
"python",
"fonts",
"pygame"
] |
What's a good way to render outlined fonts? | 1,109,498 | <p>I'm writing a game in python with pygame and need to render text onto the screen.</p>
<p>I want to render this text in one colour with an outline, so that I don't have to worry about what sort of background the the text is being displayed over.</p>
<p>pygame.font doesn't seem to offer support for doing this sort of thing directly, and I'm wondering if anyone has any good solutions for achieving this?</p>
| 6 | 2009-07-10T13:24:56Z | 1,109,553 | <p>A quick and dirty way would be to render your text multiple times with the outline color, shifted by small amounts on a circle around the text position:</p>
<pre>
1
8 | 2
\ | /
\|/
7----*----3
/|\
/ | \
6 | 4
5
</pre>
<p><strong>Edit</strong>: Doh you've been faster ! I wont delete my answer though, this ASCII art is just too good and deserves to live !</p>
<p><strong>Edit 2:</strong> As OregonGhost mentioned, you may need more or fewer steps for the outline rendering, depending on your outline width.</p>
| 3 | 2009-07-10T13:35:38Z | [
"python",
"fonts",
"pygame"
] |
Does python have a sorted list? | 1,109,804 | <p>By which I mean a structure with:</p>
<ul>
<li>O(log n) complexity for <code>x.push()</code> operations</li>
<li>O(log n) complexity to find an element</li>
<li>O(n) complexity to compute <code>list(x)</code> which will be sorted</li>
</ul>
<p>I also had a related question about performance of <code>list(...).insert(...)</code> which is now <a href="http://stackoverflow.com/questions/1110332/performance-of-list-insert">here</a>.</p>
| 78 | 2009-07-10T14:18:00Z | 1,109,866 | <p>The standard Python list is not sorted in any form. The standard heapq module can be used to append in O(log n) and remove the smallest one in O(log n), but isn't a sorted list in your definition.</p>
<p>There are various implementations of balanced trees for Python that meet your requirements, e.g. <a href="http://pypi.python.org/pypi/rbtree/">rbtree</a>, <a href="http://newcenturycomputers.net/projects/rbtree.html">RBTree</a>, or <a href="http://sourceforge.net/projects/pyavl/">pyavl</a>.</p>
| 35 | 2009-07-10T14:26:45Z | [
"python",
"list",
"sorting"
] |
Does python have a sorted list? | 1,109,804 | <p>By which I mean a structure with:</p>
<ul>
<li>O(log n) complexity for <code>x.push()</code> operations</li>
<li>O(log n) complexity to find an element</li>
<li>O(n) complexity to compute <code>list(x)</code> which will be sorted</li>
</ul>
<p>I also had a related question about performance of <code>list(...).insert(...)</code> which is now <a href="http://stackoverflow.com/questions/1110332/performance-of-list-insert">here</a>.</p>
| 78 | 2009-07-10T14:18:00Z | 1,109,973 | <p>Though it does not (yet) provide a custom search function, the <a href="http://docs.python.org/3.0/library/heapq.html"><code>heapq</code></a> module may suit your needs. It implements a heap queue using a regular list. You'd have to write your own efficient membership test that makes use of the queue's internal structure (that can be done in <em>O(log n)</em>, I'd say...). There is one downside: extracting a sorted list has complexity <em>O(n log n)</em>.</p>
| 5 | 2009-07-10T14:43:24Z | [
"python",
"list",
"sorting"
] |
Does python have a sorted list? | 1,109,804 | <p>By which I mean a structure with:</p>
<ul>
<li>O(log n) complexity for <code>x.push()</code> operations</li>
<li>O(log n) complexity to find an element</li>
<li>O(n) complexity to compute <code>list(x)</code> which will be sorted</li>
</ul>
<p>I also had a related question about performance of <code>list(...).insert(...)</code> which is now <a href="http://stackoverflow.com/questions/1110332/performance-of-list-insert">here</a>.</p>
| 78 | 2009-07-10T14:18:00Z | 6,130,146 | <p>Though I have still never checked the "big O" speeds of basic Python list operations,
the <code>bisect</code> standard module is probably also worth mentioning in this context: </p>
<pre><code>import bisect
L = [0, 100]
bisect.insort(L, 50)
bisect.insort(L, 20)
bisect.insort(L, 21)
print L
## [0, 20, 21, 50, 100]
i = bisect.bisect(L, 20)
print L[i-1], L[i]
## 20, 21
</code></pre>
<p>PS. Ah, sorry, <code>bisect</code> is mentioned in the referenced question. Still, I think it won't be much harm if this information will be here )</p>
<p>PPS. And <a href="http://jjinux.blogspot.com/2008/03/pycon-core-python-containers-under-hood.html">CPython lists are actually arrays</a> (not, say, skiplists or etc) . Well, I guess they have to be something simple, but as for me, the name is a little bit misleading.</p>
<hr>
<p>So, if I am not mistaken, the bisect/list speeds would probably be:</p>
<ul>
<li>for a push(): O(n) for the worst case ;</li>
<li>for a search: if we consider the speed of array indexing to be O(1), search should be an O(log(n)) operation ;</li>
<li>for the list creation: O(n) should be the speed of the list copying, otherwise it's O(1) for the same list ) </li>
</ul>
<p><strong>Upd.</strong> Following a discussion in the comments, let me link here these SO questions: <a href="http://stackoverflow.com/questions/3917574/how-is-pythons-list-implemented">How is Python's List Implemented</a> and <a href="http://stackoverflow.com/questions/1005590/what-is-the-runtime-complexity-of-python-list-functions">What is the runtime complexity of python list functions</a></p>
| 21 | 2011-05-25T19:59:28Z | [
"python",
"list",
"sorting"
] |
Does python have a sorted list? | 1,109,804 | <p>By which I mean a structure with:</p>
<ul>
<li>O(log n) complexity for <code>x.push()</code> operations</li>
<li>O(log n) complexity to find an element</li>
<li>O(n) complexity to compute <code>list(x)</code> which will be sorted</li>
</ul>
<p>I also had a related question about performance of <code>list(...).insert(...)</code> which is now <a href="http://stackoverflow.com/questions/1110332/performance-of-list-insert">here</a>.</p>
| 78 | 2009-07-10T14:18:00Z | 12,829,310 | <p>It may not be hard to implement your own sortlist on Python. Below is a proof of concept:</p>
<pre><code>import bisect
class sortlist:
def __init__(self, list):
self.list = list
self.sort()
def sort(self):
l = []
for i in range(len(self.list)):
bisect.insort(l, self.list[i])
self.list = l
self.len = i
def insert(self, value):
bisect.insort(self.list, value)
self.len += 1
def show(self):
print self.list
def search(self,value):
left = bisect.bisect_left(self.list, value)
if abs(self.list[min([left,self.len-1])] - value) >= abs(self.list[left-1] - value):
return self.list[left-1]
else:
return self.list[left]
list = [101, 3, 10, 14, 23, 86, 44, 45, 45, 50, 66, 95, 17, 77, 79, 84, 85, 91, 73]
slist = sortlist(list)
slist.show()
slist.insert(99)
slist.show()
print slist.search(100000000)
print slist.search(0)
print slist.search(56.7)
</code></pre>
<p>========= Results ============</p>
<p>[3, 10, 14, 17, 23, 44, 45, 45, 50, 66, 73, 77, 79, 84, 85, 86, 91, 95, 101]</p>
<p>[3, 10, 14, 17, 23, 44, 45, 45, 50, 66, 73, 77, 79, 84, 85, 86, 91, 95, 99, 101]</p>
<p>101</p>
<p>3</p>
<p>50</p>
| 0 | 2012-10-10T22:18:25Z | [
"python",
"list",
"sorting"
] |
Does python have a sorted list? | 1,109,804 | <p>By which I mean a structure with:</p>
<ul>
<li>O(log n) complexity for <code>x.push()</code> operations</li>
<li>O(log n) complexity to find an element</li>
<li>O(n) complexity to compute <code>list(x)</code> which will be sorted</li>
</ul>
<p>I also had a related question about performance of <code>list(...).insert(...)</code> which is now <a href="http://stackoverflow.com/questions/1110332/performance-of-list-insert">here</a>.</p>
| 78 | 2009-07-10T14:18:00Z | 22,616,929 | <p>Is there a particular reason for your big-O requirements? Or do you just want it to be fast? The <a href="http://www.grantjenks.com/docs/sortedcontainers/">sortedcontainers</a> module is pure-Python and fast (as in fast-as-C implementations like blist and rbtree).</p>
<p>The <a href="http://www.grantjenks.com/docs/sortedcontainers/performance.html">performance comparison</a> shows it benchmarks faster or on par with blist's sorted list type. Note also that rbtree, RBTree, and PyAVL provide sorted dict and set types but don't have a sorted list type.</p>
<p>If performance is a requirement, always remember to benchmark. A module that substantiates the claim of being fast with Big-O notation should be suspect until it also shows benchmark comparisons.</p>
<p><strong>Disclaimer:</strong> I am the author of the Python sortedcontainers module.</p>
<hr>
<p>Installation:</p>
<pre><code>pip install sortedcontainers
</code></pre>
<p>Usage:</p>
<pre><code>>>> from sortedcontainers import SortedList
>>> l = SortedList()
>>> l.update([0, 4, 1, 3, 2])
>>> l.index(3)
3
>>> l.add(5)
>>> l[-1]
5
</code></pre>
| 21 | 2014-03-24T17:52:26Z | [
"python",
"list",
"sorting"
] |
Does python have a sorted list? | 1,109,804 | <p>By which I mean a structure with:</p>
<ul>
<li>O(log n) complexity for <code>x.push()</code> operations</li>
<li>O(log n) complexity to find an element</li>
<li>O(n) complexity to compute <code>list(x)</code> which will be sorted</li>
</ul>
<p>I also had a related question about performance of <code>list(...).insert(...)</code> which is now <a href="http://stackoverflow.com/questions/1110332/performance-of-list-insert">here</a>.</p>
| 78 | 2009-07-10T14:18:00Z | 25,101,497 | <pre><code>class sortedlist(list):
'''just a list but with an insort (insert into sorted position)'''
def insort(self,x):
self=bisect.insort(self,x)
</code></pre>
| 1 | 2014-08-03T03:59:14Z | [
"python",
"list",
"sorting"
] |
Does python have a sorted list? | 1,109,804 | <p>By which I mean a structure with:</p>
<ul>
<li>O(log n) complexity for <code>x.push()</code> operations</li>
<li>O(log n) complexity to find an element</li>
<li>O(n) complexity to compute <code>list(x)</code> which will be sorted</li>
</ul>
<p>I also had a related question about performance of <code>list(...).insert(...)</code> which is now <a href="http://stackoverflow.com/questions/1110332/performance-of-list-insert">here</a>.</p>
| 78 | 2009-07-10T14:18:00Z | 31,736,695 | <p>I would use the <code>biscect</code> or <code>sortedcontainers</code> modules. I don't really am experienced, but I think the <code>heapq</code> module works. It contains a <code>Heap Queue</code></p>
| 1 | 2015-07-31T01:26:19Z | [
"python",
"list",
"sorting"
] |
python singleton into multiprocessing | 1,109,870 | <p>How can I code to share the same instance of a "singletonic" class among processes?</p>
| 4 | 2009-07-10T14:27:34Z | 1,109,920 | <p>The whole point of processes is to have different address spaces. If you want to share information between processes you must use some means of <a href="http://en.wikipedia.org/wiki/Inter-process%5Fcommunication" rel="nofollow">interprocess communication</a>.</p>
| 4 | 2009-07-10T14:35:52Z | [
"python",
"multiprocessing"
] |
python singleton into multiprocessing | 1,109,870 | <p>How can I code to share the same instance of a "singletonic" class among processes?</p>
| 4 | 2009-07-10T14:27:34Z | 1,109,930 | <p>Best is to designate one specific process as owning that instance and dedicated to it; any other process requiring access to that instance obtains it by sending messages to the owning process via a Queue (as supplied by the multiprocessing module) or other IPC mechanisms for message passing, and gets answers back via similar mechanisms.</p>
| 5 | 2009-07-10T14:37:28Z | [
"python",
"multiprocessing"
] |
python singleton into multiprocessing | 1,109,870 | <p>How can I code to share the same instance of a "singletonic" class among processes?</p>
| 4 | 2009-07-10T14:27:34Z | 1,109,978 | <p>I do not think you can share the instance between the processes, but you can have the instance access shared memory: <a href="http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes" rel="nofollow">http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes</a> to control it's state if that is really what you want to do.</p>
<p>However, as stated in other answers, it might be easier to achieve what you want with a Queue.</p>
| 1 | 2009-07-10T14:44:14Z | [
"python",
"multiprocessing"
] |
python singleton into multiprocessing | 1,109,870 | <p>How can I code to share the same instance of a "singletonic" class among processes?</p>
| 4 | 2009-07-10T14:27:34Z | 1,109,994 | <p>In Python 2.6 the <code>multiprocessing</code> module has a <code>Value</code> object used for <a href="http://docs.python.org/dev/library/multiprocessing.html#sharing-state-between-processes" rel="nofollow">sharing state between processes</a>. They have a code sample that should give you an idea of how to share state in this manner, and you can use this approach when writing a singleton class.</p>
| 2 | 2009-07-10T14:47:41Z | [
"python",
"multiprocessing"
] |
Python clock function on FreeBSD | 1,110,063 | <p>While testing Pythons time.clock() function on FreeBSD I've noticed it always returns the same value, around 0.156</p>
<p>The time.time() function works properly but I need a something with a slightly higher resolution.</p>
<p>Does anyone the C function it's bound to and if there is an alternative high resolution timer?</p>
<p>I'm not profiling so the TimeIt module is not really appropriate here.</p>
| 0 | 2009-07-10T15:02:09Z | 1,110,113 | <p>Python's time.clock calls C function clock(3) -- <code>man clock</code> should confirm that it's supposed to work on BSD, so I don't know why it's not working for you. Maybe you can try working around this apparent bug in your Python port by using <code>ctypes</code> to call the clock function from the system C library directly (if you have said library as a .so/.dynlib/.dll or whatever dynamic shared libraries are called on FreeBSD)?</p>
<p>time.time is supposed to be very high resolution, BTW, as internally it calls gettimeofday (well, in a properly built Python, anyway) -- what resolution do you observe for it on your system?</p>
<p><strong>Edit</strong>: here's <code>wat.c</code>, a BSD-specific extension (tested on my Mac only -- sorry but I have no other BSD flavor at hand right know) to work around this apparent FreeBSD port problem:</p>
<pre><code>#include "Python.h"
#include <sys/time.h>
static PyObject *
wat_time(PyObject *self, PyObject *args)
{
struct timeval t;
if (gettimeofday(&t, (struct timezone *)NULL) == 0) {
double result = (double)t.tv_sec + t.tv_usec*0.000001;
return PyFloat_FromDouble(result);
}
return PyErr_SetFromErrno(PyExc_OSError);
}
static PyMethodDef wat_methods[] = {
{"time", wat_time, METH_VARARGS,
PyDoc_STR("time() -> microseconds since epoch")},
{NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(wat_module_doc,
"Workaround for time.time issues on FreeBsd.");
PyMODINIT_FUNC
initwat(void)
{
Py_InitModule3("wat", wat_methods, wat_module_doc);
}
</code></pre>
<p>And here's the <code>setup.py</code> to put in the same directory:</p>
<pre><code>from distutils.core import setup, Extension
setup (name = "wat",
version = "0.1",
maintainer = "Alex Martelli",
maintainer_email = "aleaxit@gmail.com",
url = "http://www.aleax.it/wat.zip",
description = "WorkAround for Time in FreeBSD",
ext_modules = [Extension('wat', sources=['wat.c'])],
)
</code></pre>
<p>The URL is correct, so you can also get these two files zipped up <a href="http://ttp://www.aleax.it/wat.zip" rel="nofollow">here</a>.</p>
<p>To build & install this extension, <code>python setup.py install</code> (if you have permission to write in your Python's installation) or <code>python setup.py build_ext -i</code> to write wat.so in the very directory in which you put the sources (and then manually move it wherever you prefer to have it, but first try it out e.g. with <code>python -c'import wat; print repr(wat.time())'</code> in the same directory in which you've built it).</p>
<p>Please let me know how it works on FreeBSD (or any other Unix flavor with <code>gettimeofday</code>!-) -- if the C compiler complains about <code>gettimeofday</code>, you may be on a system which doesn't want to see its second argument, try without it!-).</p>
| 3 | 2009-07-10T15:11:20Z | [
"python",
"timer",
"freebsd",
"bsd",
"gettimeofday"
] |
Python clock function on FreeBSD | 1,110,063 | <p>While testing Pythons time.clock() function on FreeBSD I've noticed it always returns the same value, around 0.156</p>
<p>The time.time() function works properly but I need a something with a slightly higher resolution.</p>
<p>Does anyone the C function it's bound to and if there is an alternative high resolution timer?</p>
<p>I'm not profiling so the TimeIt module is not really appropriate here.</p>
| 0 | 2009-07-10T15:02:09Z | 1,110,116 | <p><code>time.clock()</code> returns CPU time on UNIX systems, and wallclock time since program start on Windows. This is a very unfortunate insymmetry, in my opinion.</p>
<p>You can find the definition for <code>time.time()</code> in the Python sources <a href="http://www.google.com/codesearch/p?hl=en&sa=N&cd=2&ct=rc#aT6TRYVYVHk/Python-2.5.1/Modules/timemodule.c&q=time%20package:python-2.5&l=857" rel="nofollow">here</a> (link to Google Code Search). It seems to use the highest-resolution timer available, which according to a quick Googling is <code>gettimeofday()</code> on FreeBSD as well, and that should be in the microsecond accuracy class.</p>
<p>However, if you really need more accuracy, you could look into writing your own C module for really high-resolution timing (something that might just return the current microsecond count, maybe!). <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow">Pyrex</a> makes Python extension writing very effortless, and <a href="http://www.swig.org/" rel="nofollow">SWIG</a> is the other common choice. (Though really, if you want to shave as many microseconds off your timer accuracy, just write it as a pure C Python extension yourself.) Ctypes is also an option, but probably rather slow.</p>
<p>Best of luck!</p>
| 1 | 2009-07-10T15:11:54Z | [
"python",
"timer",
"freebsd",
"bsd",
"gettimeofday"
] |
Python clock function on FreeBSD | 1,110,063 | <p>While testing Pythons time.clock() function on FreeBSD I've noticed it always returns the same value, around 0.156</p>
<p>The time.time() function works properly but I need a something with a slightly higher resolution.</p>
<p>Does anyone the C function it's bound to and if there is an alternative high resolution timer?</p>
<p>I'm not profiling so the TimeIt module is not really appropriate here.</p>
| 0 | 2009-07-10T15:02:09Z | 1,110,127 | <p>time.clock() is implemented to return a double value resulting from</p>
<pre><code> ((double)clock()) / CLOCKS_PER_SEC
</code></pre>
<p>Why do you think time.time() has bad resolution? It uses gettimeofday, which in turn reads the hardware clock, which has very good resolution.</p>
| 0 | 2009-07-10T15:12:58Z | [
"python",
"timer",
"freebsd",
"bsd",
"gettimeofday"
] |
Python clock function on FreeBSD | 1,110,063 | <p>While testing Pythons time.clock() function on FreeBSD I've noticed it always returns the same value, around 0.156</p>
<p>The time.time() function works properly but I need a something with a slightly higher resolution.</p>
<p>Does anyone the C function it's bound to and if there is an alternative high resolution timer?</p>
<p>I'm not profiling so the TimeIt module is not really appropriate here.</p>
| 0 | 2009-07-10T15:02:09Z | 1,110,298 | <p>time.clock() returns the processor time. That is, how much time the current process has used on the processor. So if you have a Python script called "clock.py", that does <code>import time;print time.clock()</code> it will indeed print about exactly the same each time you run it, as a new process is started each time.</p>
<p>Here is a python console log that might explain it to you:</p>
<pre><code>>>> import time
>>> time.clock()
0.11
>>> time.clock()
0.11
>>> time.clock()
0.11
>>> for x in xrange(100000000): pass
...
>>> time.clock()
7.7800000000000002
>>> time.clock()
7.7800000000000002
>>> time.clock()
7.7800000000000002
</code></pre>
<p>I hope this clarifies things.</p>
| 1 | 2009-07-10T15:37:25Z | [
"python",
"timer",
"freebsd",
"bsd",
"gettimeofday"
] |
swfupload failing in my django runserver | 1,110,082 | <p>I have copied and pasted the code from <a href="http://demo.swfupload.org/v220/simpledemo/" rel="nofollow">http://demo.swfupload.org/v220/simpledemo/</a> into a django template, but when I upload a photo, the demo says "Server (IO) Error" before it actually uploads the entire file. The runserver is getting the request and returning a 200. Is there something I am missing here? What steps should I take to debug?</p>
<p>Thanks,
Collin Anderson</p>
| 0 | 2009-07-10T15:05:58Z | 1,111,531 | <p>Make sure you have write permission to your server. In the folder you installed that thing. Check the user that is running runserver. If in windows - check folder is not readonly.</p>
| 0 | 2009-07-10T19:30:47Z | [
"python",
"django",
"swfupload"
] |
swfupload failing in my django runserver | 1,110,082 | <p>I have copied and pasted the code from <a href="http://demo.swfupload.org/v220/simpledemo/" rel="nofollow">http://demo.swfupload.org/v220/simpledemo/</a> into a django template, but when I upload a photo, the demo says "Server (IO) Error" before it actually uploads the entire file. The runserver is getting the request and returning a 200. Is there something I am missing here? What steps should I take to debug?</p>
<p>Thanks,
Collin Anderson</p>
| 0 | 2009-07-10T15:05:58Z | 1,119,383 | <p>Found it. I was uploading to a dummy view, and for some reason if you don't actually access request.POST or request.FILES it gives that error message.</p>
| 1 | 2009-07-13T13:17:46Z | [
"python",
"django",
"swfupload"
] |
What is the most efficent way to store a list in the Django models? | 1,110,153 | <p>Currently I have a lot of python objects in my code similar to the following:</p>
<pre><code>class MyClass():
def __init__(self, name, friends):
self.myName = name
self.myFriends = [str(x) for x in friends]
</code></pre>
<p>Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is a list of strings.</p>
<pre><code>from django.db import models
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ??? # what goes here?
</code></pre>
<p>Since the list is such a common data structure in python, I sort of expected there to be a Django model field for it. I know I can use a ManyToMany or OneToMany relationship, but I was hoping to avoid that extra indirection in the code.</p>
<p><strong>Edit:</strong></p>
<p>I added this <a href="http://stackoverflow.com/questions/1126642/how-would-you-inherit-from-and-override-the-django-model-classes-to-create-a-list">related question</a>, which people may find useful.</p>
| 68 | 2009-07-10T15:16:19Z | 1,110,207 | <p>Would not this relationship be better expressed as a one-to-many foreign key relationship to a <code>Friends</code> table? I understand that <code>myFriends</code> are just strings but I would think that a better design would be to create a <code>Friend</code> model and have <code>MyClass</code> contain a foreign key realtionship to the resulting table.</p>
| 37 | 2009-07-10T15:23:18Z | [
"python",
"django",
"django-models"
] |
What is the most efficent way to store a list in the Django models? | 1,110,153 | <p>Currently I have a lot of python objects in my code similar to the following:</p>
<pre><code>class MyClass():
def __init__(self, name, friends):
self.myName = name
self.myFriends = [str(x) for x in friends]
</code></pre>
<p>Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is a list of strings.</p>
<pre><code>from django.db import models
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ??? # what goes here?
</code></pre>
<p>Since the list is such a common data structure in python, I sort of expected there to be a Django model field for it. I know I can use a ManyToMany or OneToMany relationship, but I was hoping to avoid that extra indirection in the code.</p>
<p><strong>Edit:</strong></p>
<p>I added this <a href="http://stackoverflow.com/questions/1126642/how-would-you-inherit-from-and-override-the-django-model-classes-to-create-a-list">related question</a>, which people may find useful.</p>
| 68 | 2009-07-10T15:16:19Z | 1,110,237 | <p>Remember that this eventually has to end up in a relational database. So using relations really <em>is</em> the common way to solve this problem. If you absolutely insist on storing a list in the object itself, you could make it for example comma-separated, and store it in a string, and then provide accessor functions that split the string into a list. With that, you will be limited to a maximum number of strings, and you will lose efficient queries.</p>
| 6 | 2009-07-10T15:27:43Z | [
"python",
"django",
"django-models"
] |
What is the most efficent way to store a list in the Django models? | 1,110,153 | <p>Currently I have a lot of python objects in my code similar to the following:</p>
<pre><code>class MyClass():
def __init__(self, name, friends):
self.myName = name
self.myFriends = [str(x) for x in friends]
</code></pre>
<p>Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is a list of strings.</p>
<pre><code>from django.db import models
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ??? # what goes here?
</code></pre>
<p>Since the list is such a common data structure in python, I sort of expected there to be a Django model field for it. I know I can use a ManyToMany or OneToMany relationship, but I was hoping to avoid that extra indirection in the code.</p>
<p><strong>Edit:</strong></p>
<p>I added this <a href="http://stackoverflow.com/questions/1126642/how-would-you-inherit-from-and-override-the-django-model-classes-to-create-a-list">related question</a>, which people may find useful.</p>
| 68 | 2009-07-10T15:16:19Z | 1,111,201 | <p>You can store virtually any object using a Django Pickle Field, ala this snippet:</p>
<p><a href="http://www.djangosnippets.org/snippets/513/" rel="nofollow">http://www.djangosnippets.org/snippets/513/</a></p>
| 4 | 2009-07-10T18:27:21Z | [
"python",
"django",
"django-models"
] |
What is the most efficent way to store a list in the Django models? | 1,110,153 | <p>Currently I have a lot of python objects in my code similar to the following:</p>
<pre><code>class MyClass():
def __init__(self, name, friends):
self.myName = name
self.myFriends = [str(x) for x in friends]
</code></pre>
<p>Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is a list of strings.</p>
<pre><code>from django.db import models
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ??? # what goes here?
</code></pre>
<p>Since the list is such a common data structure in python, I sort of expected there to be a Django model field for it. I know I can use a ManyToMany or OneToMany relationship, but I was hoping to avoid that extra indirection in the code.</p>
<p><strong>Edit:</strong></p>
<p>I added this <a href="http://stackoverflow.com/questions/1126642/how-would-you-inherit-from-and-override-the-django-model-classes-to-create-a-list">related question</a>, which people may find useful.</p>
| 68 | 2009-07-10T15:16:19Z | 1,111,475 | <pre><code>class Course(models.Model):
name = models.CharField(max_length=256)
students = models.ManyToManyField(Student)
class Student(models.Model):
first_name = models.CharField(max_length=256)
student_number = models.CharField(max_length=128)
# other fields, etc...
friends = models.ManyToManyField('self')
</code></pre>
| 8 | 2009-07-10T19:21:37Z | [
"python",
"django",
"django-models"
] |
What is the most efficent way to store a list in the Django models? | 1,110,153 | <p>Currently I have a lot of python objects in my code similar to the following:</p>
<pre><code>class MyClass():
def __init__(self, name, friends):
self.myName = name
self.myFriends = [str(x) for x in friends]
</code></pre>
<p>Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is a list of strings.</p>
<pre><code>from django.db import models
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ??? # what goes here?
</code></pre>
<p>Since the list is such a common data structure in python, I sort of expected there to be a Django model field for it. I know I can use a ManyToMany or OneToMany relationship, but I was hoping to avoid that extra indirection in the code.</p>
<p><strong>Edit:</strong></p>
<p>I added this <a href="http://stackoverflow.com/questions/1126642/how-would-you-inherit-from-and-override-the-django-model-classes-to-create-a-list">related question</a>, which people may find useful.</p>
| 68 | 2009-07-10T15:16:19Z | 1,113,039 | <h2><strong>"Premature optimization is the root of all evil."</strong></h2>
<p>With that firmly in mind, let's do this! Once your apps hit a certain point, denormalizing data is very common. Done correctly, it can save numerous expensive database lookups at the cost of a little more housekeeping.</p>
<p>To return a <code>list</code> of friend names we'll need to create a custom Django Field class that will return a list when accessed.</p>
<p><a href="http://cramer.io/2008/08/08/custom-fields-in-django/">David Cramer posted a guide to creating a SeperatedValueField on his blog</a>. Here is the code:</p>
<pre><code>from django.db import models
class SeparatedValuesField(models.TextField):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
self.token = kwargs.pop('token', ',')
super(SeparatedValuesField, self).__init__(*args, **kwargs)
def to_python(self, value):
if not value: return
if isinstance(value, list):
return value
return value.split(self.token)
def get_db_prep_value(self, value):
if not value: return
assert(isinstance(value, list) or isinstance(value, tuple))
return self.token.join([unicode(s) for s in value])
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_db_prep_value(value)
</code></pre>
<p>The logic of this code deals with serializing and deserializing values from the database to Python and vice versa. Now you can easily import and use our custom field in the model class:</p>
<pre><code>from django.db import models
from custom.fields import SeparatedValuesField
class Person(models.Model):
name = models.CharField(max_length=64)
friends = SeparatedValuesField()
</code></pre>
| 74 | 2009-07-11T05:43:45Z | [
"python",
"django",
"django-models"
] |
What is the most efficent way to store a list in the Django models? | 1,110,153 | <p>Currently I have a lot of python objects in my code similar to the following:</p>
<pre><code>class MyClass():
def __init__(self, name, friends):
self.myName = name
self.myFriends = [str(x) for x in friends]
</code></pre>
<p>Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is a list of strings.</p>
<pre><code>from django.db import models
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ??? # what goes here?
</code></pre>
<p>Since the list is such a common data structure in python, I sort of expected there to be a Django model field for it. I know I can use a ManyToMany or OneToMany relationship, but I was hoping to avoid that extra indirection in the code.</p>
<p><strong>Edit:</strong></p>
<p>I added this <a href="http://stackoverflow.com/questions/1126642/how-would-you-inherit-from-and-override-the-django-model-classes-to-create-a-list">related question</a>, which people may find useful.</p>
| 68 | 2009-07-10T15:16:19Z | 1,113,362 | <p>Using one-to-many relation (FK from Friend to parent class) will make your app more scalable (as you can trivially extend the Friend object with additional attributes beyond the simple name). And thus this is the best way </p>
| 1 | 2009-07-11T09:51:13Z | [
"python",
"django",
"django-models"
] |
What is the most efficent way to store a list in the Django models? | 1,110,153 | <p>Currently I have a lot of python objects in my code similar to the following:</p>
<pre><code>class MyClass():
def __init__(self, name, friends):
self.myName = name
self.myFriends = [str(x) for x in friends]
</code></pre>
<p>Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is a list of strings.</p>
<pre><code>from django.db import models
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ??? # what goes here?
</code></pre>
<p>Since the list is such a common data structure in python, I sort of expected there to be a Django model field for it. I know I can use a ManyToMany or OneToMany relationship, but I was hoping to avoid that extra indirection in the code.</p>
<p><strong>Edit:</strong></p>
<p>I added this <a href="http://stackoverflow.com/questions/1126642/how-would-you-inherit-from-and-override-the-django-model-classes-to-create-a-list">related question</a>, which people may find useful.</p>
| 68 | 2009-07-10T15:16:19Z | 7,151,813 | <p>A simple way to store a list in Django is to just convert it into a JSON string, and then save that as Text in the model. You can then retrieve the list by converting the (JSON) string back into a python list. Here's how:</p>
<p>The "list" would be stored in your Django model like so:</p>
<pre><code>class MyModel(models.Model):
myList = models.TextField(null=True) # JSON-serialized (text) version of your list
</code></pre>
<p>In your view/controller code:</p>
<p><strong>Storing the list in the database:</strong></p>
<pre><code>import simplejson as json # this would be just 'import json' in Python 2.7 and later
...
...
myModel = MyModel()
listIWantToStore = [1,2,3,4,5,'hello']
myModel.myList = json.dumps(listIWantToStore)
myModel.save()
</code></pre>
<p><strong>Retrieving the list from the database:</strong></p>
<pre><code>jsonDec = json.decoder.JSONDecoder()
myPythonList = jsonDec.decode(myModel.myList)
</code></pre>
<p><strong>Conceptually, here's what's going on:</strong></p>
<pre><code>>>> myList = [1,2,3,4,5,'hello']
>>> import simplejson as json
>>> myJsonList = json.dumps(myList)
>>> myJsonList
'[1, 2, 3, 4, 5, "hello"]'
>>> myJsonList.__class__
<type 'str'>
>>> jsonDec = json.decoder.JSONDecoder()
>>> myPythonList = jsonDec.decode(myJsonList)
>>> myPythonList
[1, 2, 3, 4, 5, u'hello']
>>> myPythonList.__class__
<type 'list'>
</code></pre>
| 21 | 2011-08-22T18:24:31Z | [
"python",
"django",
"django-models"
] |
What is the most efficent way to store a list in the Django models? | 1,110,153 | <p>Currently I have a lot of python objects in my code similar to the following:</p>
<pre><code>class MyClass():
def __init__(self, name, friends):
self.myName = name
self.myFriends = [str(x) for x in friends]
</code></pre>
<p>Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is a list of strings.</p>
<pre><code>from django.db import models
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ??? # what goes here?
</code></pre>
<p>Since the list is such a common data structure in python, I sort of expected there to be a Django model field for it. I know I can use a ManyToMany or OneToMany relationship, but I was hoping to avoid that extra indirection in the code.</p>
<p><strong>Edit:</strong></p>
<p>I added this <a href="http://stackoverflow.com/questions/1126642/how-would-you-inherit-from-and-override-the-django-model-classes-to-create-a-list">related question</a>, which people may find useful.</p>
| 68 | 2009-07-10T15:16:19Z | 14,715,454 | <p>As this is an old question, and Django techniques must have changed significantly since, this answer reflects Django version 1.4, and is most likely applicable for v 1.5.</p>
<p>Django by default uses relational databases; you should make use of 'em. Map friendships to database relations (foreign key constraints) with the use of ManyToManyField. Doing so allows you to use RelatedManagers for friendlists, which use smart querysets. You can use all available methods such as <code>filter</code> or <code>values_list</code>.</p>
<p>Using <code>ManyToManyField</code> relations and properties:</p>
<pre><code>class MyDjangoClass(models.Model):
name = models.CharField(...)
friends = models.ManyToManyField("self")
@property
def friendlist(self):
# Watch for large querysets: it loads everything in memory
return list(self.friends.all())
</code></pre>
<p>You can access a user's friend list this way:</p>
<pre><code>joseph = MyDjangoClass.objects.get(name="Joseph")
friends_of_joseph = joseph.friendlist
</code></pre>
<p>Note however that these relations are symmetrical: if Joseph is a friend of Bob, then Bob is a friend of Joseph.</p>
| 12 | 2013-02-05T19:35:21Z | [
"python",
"django",
"django-models"
] |
What is the most efficent way to store a list in the Django models? | 1,110,153 | <p>Currently I have a lot of python objects in my code similar to the following:</p>
<pre><code>class MyClass():
def __init__(self, name, friends):
self.myName = name
self.myFriends = [str(x) for x in friends]
</code></pre>
<p>Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is a list of strings.</p>
<pre><code>from django.db import models
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ??? # what goes here?
</code></pre>
<p>Since the list is such a common data structure in python, I sort of expected there to be a Django model field for it. I know I can use a ManyToMany or OneToMany relationship, but I was hoping to avoid that extra indirection in the code.</p>
<p><strong>Edit:</strong></p>
<p>I added this <a href="http://stackoverflow.com/questions/1126642/how-would-you-inherit-from-and-override-the-django-model-classes-to-create-a-list">related question</a>, which people may find useful.</p>
| 68 | 2009-07-10T15:16:19Z | 36,257,323 | <p>If you are using 1.9 Django with Postgres you can use advantages of <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/postgres/fields/#django.contrib.postgres.fields.ArrayField" rel="nofollow">ArrayField</a></p>
<blockquote>
<p>A field for storing lists of data. Most field types can be used, you
simply pass another field instance as the base_field. You may also
specify a size. ArrayField can be nested to store multi-dimensional
arrays.</p>
</blockquote>
| 2 | 2016-03-28T06:44:27Z | [
"python",
"django",
"django-models"
] |
What is the most efficent way to store a list in the Django models? | 1,110,153 | <p>Currently I have a lot of python objects in my code similar to the following:</p>
<pre><code>class MyClass():
def __init__(self, name, friends):
self.myName = name
self.myFriends = [str(x) for x in friends]
</code></pre>
<p>Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is a list of strings.</p>
<pre><code>from django.db import models
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ??? # what goes here?
</code></pre>
<p>Since the list is such a common data structure in python, I sort of expected there to be a Django model field for it. I know I can use a ManyToMany or OneToMany relationship, but I was hoping to avoid that extra indirection in the code.</p>
<p><strong>Edit:</strong></p>
<p>I added this <a href="http://stackoverflow.com/questions/1126642/how-would-you-inherit-from-and-override-the-django-model-classes-to-create-a-list">related question</a>, which people may find useful.</p>
| 68 | 2009-07-10T15:16:19Z | 38,517,318 | <p>In case you're using postgres, you can use something like this:</p>
<p>class ChessBoard(models.Model):</p>
<pre><code>board = ArrayField(
ArrayField(
models.CharField(max_length=10, blank=True),
size=8,
),
size=8,
)
</code></pre>
<p>if you need more details you can read in the link below:
<a href="https://docs.djangoproject.com/pt-br/1.9/ref/contrib/postgres/fields/" rel="nofollow">https://docs.djangoproject.com/pt-br/1.9/ref/contrib/postgres/fields/</a></p>
| 0 | 2016-07-22T02:41:58Z | [
"python",
"django",
"django-models"
] |
How can I tell if my script is being run from a cronjob or from the command line? | 1,110,203 | <p>I have a script and it's display show's upload progress by writing to the same console line. When the script is run from a cron job, rather than writing to a single line, I get many lines:</p>
<pre><code>*** E0710091001.DAT *** [0.67%]
*** E0710091001.DAT *** [1.33%]
*** E0710091001.DAT *** [2.00%]
*** E0710091001.DAT *** [2.66%]
*** E0710091001.DAT *** [3.33%]
*** E0710091001.DAT *** [3.99%]
*** E0710091001.DAT *** [4.66%]
*** E0710091001.DAT *** [5.32%]
*** E0710091001.DAT *** [5.99%]
*** E0710091001.DAT *** [6.65%]
*** E0710091001.DAT *** [7.32%]
*** E0710091001.DAT *** [7.98%]
*** E0710091001.DAT *** [8.65%]
*** E0710091001.DAT *** [9.32%]
*** E0710091001.DAT *** [9.98%]
*** E0710091001.DAT *** [10.65%]
*** E0710091001.DAT *** [11.31%]
*** E0710091001.DAT *** [11.98%]
*** E0710091001.DAT *** [12.64%]
*** E0710091001.DAT *** [13.31%]
*** E0710091001.DAT *** [13.97%]
*** E0710091001.DAT *** [14.64%]
*** E0710091001.DAT *** [15.30%]
*** E0710091001.DAT *** [15.97%]
*** E0710091001.DAT *** [16.63%]
*** E0710091001.DAT *** [17.30%]
*** E0710091001.DAT *** [17.97%]
*** E0710091001.DAT *** [18.63%]
</code></pre>
<p>I just want to know if I can tell from inside the script if it's being called from cron, and if so, I won't display this output. </p>
| 2 | 2009-07-10T15:22:22Z | 1,110,218 | <p>you could create a flag. Possibly undocumented that your cron job would pass to the utility to structure the output.</p>
| 8 | 2009-07-10T15:24:39Z | [
"python",
"cron"
] |
How can I tell if my script is being run from a cronjob or from the command line? | 1,110,203 | <p>I have a script and it's display show's upload progress by writing to the same console line. When the script is run from a cron job, rather than writing to a single line, I get many lines:</p>
<pre><code>*** E0710091001.DAT *** [0.67%]
*** E0710091001.DAT *** [1.33%]
*** E0710091001.DAT *** [2.00%]
*** E0710091001.DAT *** [2.66%]
*** E0710091001.DAT *** [3.33%]
*** E0710091001.DAT *** [3.99%]
*** E0710091001.DAT *** [4.66%]
*** E0710091001.DAT *** [5.32%]
*** E0710091001.DAT *** [5.99%]
*** E0710091001.DAT *** [6.65%]
*** E0710091001.DAT *** [7.32%]
*** E0710091001.DAT *** [7.98%]
*** E0710091001.DAT *** [8.65%]
*** E0710091001.DAT *** [9.32%]
*** E0710091001.DAT *** [9.98%]
*** E0710091001.DAT *** [10.65%]
*** E0710091001.DAT *** [11.31%]
*** E0710091001.DAT *** [11.98%]
*** E0710091001.DAT *** [12.64%]
*** E0710091001.DAT *** [13.31%]
*** E0710091001.DAT *** [13.97%]
*** E0710091001.DAT *** [14.64%]
*** E0710091001.DAT *** [15.30%]
*** E0710091001.DAT *** [15.97%]
*** E0710091001.DAT *** [16.63%]
*** E0710091001.DAT *** [17.30%]
*** E0710091001.DAT *** [17.97%]
*** E0710091001.DAT *** [18.63%]
</code></pre>
<p>I just want to know if I can tell from inside the script if it's being called from cron, and if so, I won't display this output. </p>
| 2 | 2009-07-10T15:22:22Z | 1,110,221 | <p>You want to check if you're on a terminal or not. See this stack overflow question:
<a href="http://stackoverflow.com/questions/911168/detect-if-shell-script-is-running-through-a-pipe">http://stackoverflow.com/questions/911168/detect-if-shell-script-is-running-through-a-pipe</a></p>
| 6 | 2009-07-10T15:24:51Z | [
"python",
"cron"
] |
How can I tell if my script is being run from a cronjob or from the command line? | 1,110,203 | <p>I have a script and it's display show's upload progress by writing to the same console line. When the script is run from a cron job, rather than writing to a single line, I get many lines:</p>
<pre><code>*** E0710091001.DAT *** [0.67%]
*** E0710091001.DAT *** [1.33%]
*** E0710091001.DAT *** [2.00%]
*** E0710091001.DAT *** [2.66%]
*** E0710091001.DAT *** [3.33%]
*** E0710091001.DAT *** [3.99%]
*** E0710091001.DAT *** [4.66%]
*** E0710091001.DAT *** [5.32%]
*** E0710091001.DAT *** [5.99%]
*** E0710091001.DAT *** [6.65%]
*** E0710091001.DAT *** [7.32%]
*** E0710091001.DAT *** [7.98%]
*** E0710091001.DAT *** [8.65%]
*** E0710091001.DAT *** [9.32%]
*** E0710091001.DAT *** [9.98%]
*** E0710091001.DAT *** [10.65%]
*** E0710091001.DAT *** [11.31%]
*** E0710091001.DAT *** [11.98%]
*** E0710091001.DAT *** [12.64%]
*** E0710091001.DAT *** [13.31%]
*** E0710091001.DAT *** [13.97%]
*** E0710091001.DAT *** [14.64%]
*** E0710091001.DAT *** [15.30%]
*** E0710091001.DAT *** [15.97%]
*** E0710091001.DAT *** [16.63%]
*** E0710091001.DAT *** [17.30%]
*** E0710091001.DAT *** [17.97%]
*** E0710091001.DAT *** [18.63%]
</code></pre>
<p>I just want to know if I can tell from inside the script if it's being called from cron, and if so, I won't display this output. </p>
| 2 | 2009-07-10T15:22:22Z | 1,110,223 | <p>An easy way would be to have the script take an argument that means to suppress that output, and supply that argument when you call it from cron.</p>
| 2 | 2009-07-10T15:25:14Z | [
"python",
"cron"
] |
How can I tell if my script is being run from a cronjob or from the command line? | 1,110,203 | <p>I have a script and it's display show's upload progress by writing to the same console line. When the script is run from a cron job, rather than writing to a single line, I get many lines:</p>
<pre><code>*** E0710091001.DAT *** [0.67%]
*** E0710091001.DAT *** [1.33%]
*** E0710091001.DAT *** [2.00%]
*** E0710091001.DAT *** [2.66%]
*** E0710091001.DAT *** [3.33%]
*** E0710091001.DAT *** [3.99%]
*** E0710091001.DAT *** [4.66%]
*** E0710091001.DAT *** [5.32%]
*** E0710091001.DAT *** [5.99%]
*** E0710091001.DAT *** [6.65%]
*** E0710091001.DAT *** [7.32%]
*** E0710091001.DAT *** [7.98%]
*** E0710091001.DAT *** [8.65%]
*** E0710091001.DAT *** [9.32%]
*** E0710091001.DAT *** [9.98%]
*** E0710091001.DAT *** [10.65%]
*** E0710091001.DAT *** [11.31%]
*** E0710091001.DAT *** [11.98%]
*** E0710091001.DAT *** [12.64%]
*** E0710091001.DAT *** [13.31%]
*** E0710091001.DAT *** [13.97%]
*** E0710091001.DAT *** [14.64%]
*** E0710091001.DAT *** [15.30%]
*** E0710091001.DAT *** [15.97%]
*** E0710091001.DAT *** [16.63%]
*** E0710091001.DAT *** [17.30%]
*** E0710091001.DAT *** [17.97%]
*** E0710091001.DAT *** [18.63%]
</code></pre>
<p>I just want to know if I can tell from inside the script if it's being called from cron, and if so, I won't display this output. </p>
| 2 | 2009-07-10T15:22:22Z | 1,110,230 | <p>I'd check <code>sys.stderr.isatty()</code> -- this way you avoid useless "decoration" output to stderr whenever it wouldn't be immediately perceptible by the user anyway.</p>
| 9 | 2009-07-10T15:26:48Z | [
"python",
"cron"
] |
How can I tell if my script is being run from a cronjob or from the command line? | 1,110,203 | <p>I have a script and it's display show's upload progress by writing to the same console line. When the script is run from a cron job, rather than writing to a single line, I get many lines:</p>
<pre><code>*** E0710091001.DAT *** [0.67%]
*** E0710091001.DAT *** [1.33%]
*** E0710091001.DAT *** [2.00%]
*** E0710091001.DAT *** [2.66%]
*** E0710091001.DAT *** [3.33%]
*** E0710091001.DAT *** [3.99%]
*** E0710091001.DAT *** [4.66%]
*** E0710091001.DAT *** [5.32%]
*** E0710091001.DAT *** [5.99%]
*** E0710091001.DAT *** [6.65%]
*** E0710091001.DAT *** [7.32%]
*** E0710091001.DAT *** [7.98%]
*** E0710091001.DAT *** [8.65%]
*** E0710091001.DAT *** [9.32%]
*** E0710091001.DAT *** [9.98%]
*** E0710091001.DAT *** [10.65%]
*** E0710091001.DAT *** [11.31%]
*** E0710091001.DAT *** [11.98%]
*** E0710091001.DAT *** [12.64%]
*** E0710091001.DAT *** [13.31%]
*** E0710091001.DAT *** [13.97%]
*** E0710091001.DAT *** [14.64%]
*** E0710091001.DAT *** [15.30%]
*** E0710091001.DAT *** [15.97%]
*** E0710091001.DAT *** [16.63%]
*** E0710091001.DAT *** [17.30%]
*** E0710091001.DAT *** [17.97%]
*** E0710091001.DAT *** [18.63%]
</code></pre>
<p>I just want to know if I can tell from inside the script if it's being called from cron, and if so, I won't display this output. </p>
| 2 | 2009-07-10T15:22:22Z | 1,110,253 | <p>See code below. Replace my print statements with what you want to show.</p>
<pre><code>import sys
if sys.stdout.isatty():
print "Running from command line"
else:
print "Running from cron"
</code></pre>
| 5 | 2009-07-10T15:29:54Z | [
"python",
"cron"
] |
Performance of list(...).insert(...) | 1,110,332 | <p>I thought about the following question about computer's architecture. Suppose I do in Python</p>
<pre><code>from bisect import bisect
index = bisect(x, a) # O(log n) (also, shouldn't it be a standard list function?)
x.insert(index, a) # O(1) + memcpy()
</code></pre>
<p>which takes <code>log n</code>, plus, if I correctly understand it, a memory copy operation for <code>x[index:]</code>. Now I read recently that the bottleneck is usually in the communication between processor and the memory so the memory copy <em>could</em> be done by RAM quite fast. Is it how that works?</p>
| 10 | 2009-07-10T15:42:33Z | 1,110,446 | <p>Python is a language. <a href="http://www.python.org/dev/implementations/">Multiple implementations exist</a>, and they <em>may</em> have different implementations for lists. So, without looking at the code of an actual implementation, you cannot know for sure how lists are implemented and how they behave under certain circumstances.</p>
<p>My bet would be that the references to the objects in a list are stored in contiguous memory (certainly not as a linked list...). If that is indeed so, then insertion using <code>x.insert</code> will cause all elements behind the inserted element to be moved. This may be done efficiently by the hardware, but the complexity would still be <em>O(n)</em>.</p>
<p>For small lists the <code>bisect</code> operation may take more time than <code>x.insert</code>, even though the former is <em>O(log n)</em> while the latter is <em>O(n)</em>. For long lists, however, I'd hazard a guess that <code>x.insert</code> is the bottleneck. In such cases you must consider using a different data structure.</p>
| 12 | 2009-07-10T15:58:34Z | [
"python",
"architecture",
"memory",
"list",
"memcpy"
] |
Performance of list(...).insert(...) | 1,110,332 | <p>I thought about the following question about computer's architecture. Suppose I do in Python</p>
<pre><code>from bisect import bisect
index = bisect(x, a) # O(log n) (also, shouldn't it be a standard list function?)
x.insert(index, a) # O(1) + memcpy()
</code></pre>
<p>which takes <code>log n</code>, plus, if I correctly understand it, a memory copy operation for <code>x[index:]</code>. Now I read recently that the bottleneck is usually in the communication between processor and the memory so the memory copy <em>could</em> be done by RAM quite fast. Is it how that works?</p>
| 10 | 2009-07-10T15:42:33Z | 1,111,127 | <p>CPython lists are contiguous arrays. Which one of the O(log n) bisect and O(n) insert dominates your performance profile depends on the size of your list and also the constant factors inside the O(). Particularly, the comparison function invoked by bisect can be something expensive depending on the type of objects in the list.</p>
<p>If you need to hold potentially large mutable sorted sequences then the linear array underlying Pythons list type isn't a good choice. Depending on your requirements heaps, trees or skip-lists might be appropriate.</p>
| 5 | 2009-07-10T18:12:44Z | [
"python",
"architecture",
"memory",
"list",
"memcpy"
] |
Performance of list(...).insert(...) | 1,110,332 | <p>I thought about the following question about computer's architecture. Suppose I do in Python</p>
<pre><code>from bisect import bisect
index = bisect(x, a) # O(log n) (also, shouldn't it be a standard list function?)
x.insert(index, a) # O(1) + memcpy()
</code></pre>
<p>which takes <code>log n</code>, plus, if I correctly understand it, a memory copy operation for <code>x[index:]</code>. Now I read recently that the bottleneck is usually in the communication between processor and the memory so the memory copy <em>could</em> be done by RAM quite fast. Is it how that works?</p>
| 10 | 2009-07-10T15:42:33Z | 1,111,886 | <p>Use the <a href="http://www.python.org/pypi/blist/">blist module</a> if you need a list with better insert performance.</p>
| 8 | 2009-07-10T20:44:12Z | [
"python",
"architecture",
"memory",
"list",
"memcpy"
] |
Performance of list(...).insert(...) | 1,110,332 | <p>I thought about the following question about computer's architecture. Suppose I do in Python</p>
<pre><code>from bisect import bisect
index = bisect(x, a) # O(log n) (also, shouldn't it be a standard list function?)
x.insert(index, a) # O(1) + memcpy()
</code></pre>
<p>which takes <code>log n</code>, plus, if I correctly understand it, a memory copy operation for <code>x[index:]</code>. Now I read recently that the bottleneck is usually in the communication between processor and the memory so the memory copy <em>could</em> be done by RAM quite fast. Is it how that works?</p>
| 10 | 2009-07-10T15:42:33Z | 1,112,251 | <p>Yes, I think sometimes O(n) is inevitable, <a href="http://www.pycon.it/static/stuff/slides/core-python-containers-under-hood.ppt" rel="nofollow">Core Python Containers: Under the Hood</a> talks about List performance from page 4 to page 14.It is concordant with your viewpoint and is worth reading.</p>
| 1 | 2009-07-10T22:14:37Z | [
"python",
"architecture",
"memory",
"list",
"memcpy"
] |
Python ftplib - uploading multiple files? | 1,110,374 | <p>I've googled but I could only find how to upload one file... and I'm trying to upload all files from local directory to remote ftp directory. Any ideas how to achieve this?</p>
| 3 | 2009-07-10T15:47:30Z | 1,110,380 | <p>with the loop?</p>
<p><strong>edit</strong>: in universal case uploading only files would look like this:</p>
<pre><code>import os
for root, dirs, files in os.walk('path/to/local/dir'):
for fname in files:
full_fname = os.path.join(root, fname)
ftp.storbinary('STOR remote/dir' + fname, open(full_fname, 'rb'))
</code></pre>
<p>Obviously, you need to look out for name collisions if you're just preserving file names like this.</p>
| 9 | 2009-07-10T15:48:55Z | [
"python",
"ftplib"
] |
Python ftplib - uploading multiple files? | 1,110,374 | <p>I've googled but I could only find how to upload one file... and I'm trying to upload all files from local directory to remote ftp directory. Any ideas how to achieve this?</p>
| 3 | 2009-07-10T15:47:30Z | 1,110,688 | <p>Create a FTP batch file (with a list of files that you need to transfer). Use python to execute ftp.exe with the "-s" option and pass in the list of files.</p>
<p>This is kludgy but apparently the FTPlib does not have accept multiple files in its STOR command.</p>
<p>Here is a sample ftp batch file.</p>
<p>*</p>
<pre><code>OPEN inetxxx
myuser mypasswd
binary
prompt off
cd ~/my_reg/cronjobs/k_load/incoming
mput *.csv
bye
</code></pre>
<ul>
<li><p>If the above contents were in a file called "abc.ftp" - then my ftp command would be</p>
<p>ftp -s abc.ftp</p></li>
</ul>
<p>Hope that helps.</p>
| -1 | 2009-07-10T16:49:48Z | [
"python",
"ftplib"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.