Q_CreationDate
stringlengths
23
23
Title
stringlengths
11
149
Question
stringlengths
25
6.53k
Answer
stringlengths
15
5.1k
Score
float64
-1
1.2
Is_accepted
bool
2 classes
N_answers
int64
1
17
Q_Id
int64
0
6.76k
2010-04-04 00:28:33.830
Python progression path - From apprentice to guru
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutions and also with the semantics of the language that allows such a natural flow from thoughts to workable code. What I would like to know is your answer to a kind of question I have seldom seen in this or other forums. This question seems central to me for anyone on the path to Python improvement but who wonders what his next steps should be. Let me sum up what I do NOT want to ask first ;) I don't want to know how to QUICKLY learn Python Nor do I want to find out the best way to get acquainted with the language Finally, I don't want to know a 'one trick that does it all' approach. What I do want to know your opinion about, is: What are the steps YOU would recommend to a Python journeyman, from apprenticeship to guru status (feel free to stop wherever your expertise dictates it), in order that one IMPROVES CONSTANTLY, becoming a better and better Python coder, one step at a time. Some of the people on SO almost seem worthy of worship for their Python prowess, please enlighten us :) The kind of answers I would enjoy (but feel free to surprise the readership :P ), is formatted more or less like this: Read this (eg: python tutorial), pay attention to that kind of details Code for so manytime/problems/lines of code Then, read this (eg: this or that book), but this time, pay attention to this Tackle a few real-life problems Then, proceed to reading Y. Be sure to grasp these concepts Code for X time Come back to such and such basics or move further to... (you get the point :) I really care about knowing your opinion on what exactly one should pay attention to, at various stages, in order to progress CONSTANTLY (with due efforts, of course). If you come from a specific field of expertise, discuss the path you see as appropriate in this field. EDIT: Thanks to your great input, I'm back on the Python improvement track! I really appreciate!
I'll give you the simplest and most effective piece of advice I think anybody could give you: code. You can only be better at using a language (which implies understanding it) by coding. You have to actively enjoy coding, be inspired, ask questions, and find answers by yourself. Got a an hour to spare? Write code that will reverse a string, and find out the most optimum solution. A free evening? Why not try some web-scraping. Read other peoples code. See how they do things. Ask yourself what you would do. When I'm bored at my computer, I open my IDE and code-storm. I jot down ideas that sound interesting, and challenging. An URL shortener? Sure, I can do that. Oh, I learnt how to convert numbers from one base to another as a side effect! This is valid whatever your skill level. You never stop learning. By actively coding in your spare time you will, with little additional effort, come to understand the language, and ultimately, become a guru. You will build up knowledge and reusable code and memorise idioms.
0.706807
false
5
503
2010-04-04 10:55:44.530
how to create multiple selections in text edit box in qt4?
Qt3.3 used to allow for multiple selections in the QTextEdit widget by calling the setSelection() function and specifying a different selection id (selNum) as the last argument in that function. In Qt4, to create a selection, I do it by creating a QTextCursor object and call the setPosition() or movePosition() methods. I have no problems being able to create a single selection of text. I am, however, unable to find a way to create multiple selections. The methods in Qt4 do not have an argument which allows you to set a selection id, nor can i find any other function in the QTextCursor or QTextEdit which looks like it might allow me to do so. Has this feature been completely removed from Qt4? or has is there a new and different way of doing it? Thanks. Ronny
How about creating multiple cursors (QTextCursor), each selection a different portion of the text. Would that work for you?
0
false
2
504
2010-04-04 10:55:44.530
how to create multiple selections in text edit box in qt4?
Qt3.3 used to allow for multiple selections in the QTextEdit widget by calling the setSelection() function and specifying a different selection id (selNum) as the last argument in that function. In Qt4, to create a selection, I do it by creating a QTextCursor object and call the setPosition() or movePosition() methods. I have no problems being able to create a single selection of text. I am, however, unable to find a way to create multiple selections. The methods in Qt4 do not have an argument which allows you to set a selection id, nor can i find any other function in the QTextCursor or QTextEdit which looks like it might allow me to do so. Has this feature been completely removed from Qt4? or has is there a new and different way of doing it? Thanks. Ronny
The solution, i realise now is actually quite simple. To graphically visualise all the various selections (separate QTextCursor objects), instead of calling the setTextCursor() method for the QTextEdit widget for each of the selections, i change the background color of each of those sections of text by calling the setCharFormat() method for each of those QTextCursor objects.
1.2
true
2
504
2010-04-05 13:18:44.587
PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django
I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Although I have pretty good experience with python and PHP but I have no idea how to use either of the framework. We have plenty of time to experiment and learn one of the above frameworks.Could you please specify which one would be preferred for such a scenario considering speed, features, and security of the site. Thanks, niting
Codeigniter it's fast and very documented also has a large community to and finaly friendly with the programmer.
0.201295
false
5
505
2010-04-05 13:18:44.587
PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django
I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Although I have pretty good experience with python and PHP but I have no idea how to use either of the framework. We have plenty of time to experiment and learn one of the above frameworks.Could you please specify which one would be preferred for such a scenario considering speed, features, and security of the site. Thanks, niting
I am using CodeIgniter 1.7.2 and for complex websites it's very good and powerfull, but it definitely is missing some kind of code generator which will allow for example to build an IT application in one click. I had the impression (from watching a tutorial) that Django has it.
0
false
5
505
2010-04-05 13:18:44.587
PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django
I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Although I have pretty good experience with python and PHP but I have no idea how to use either of the framework. We have plenty of time to experiment and learn one of the above frameworks.Could you please specify which one would be preferred for such a scenario considering speed, features, and security of the site. Thanks, niting
If for the PHP part I would choose CodeIgniter - it doesn't get too much into your way. But it doesn't have any code/view/model generators out of the box, you need to type a bit. But languages other than PHP appear to be more sexy.
0
false
5
505
2010-04-05 13:18:44.587
PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django
I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Although I have pretty good experience with python and PHP but I have no idea how to use either of the framework. We have plenty of time to experiment and learn one of the above frameworks.Could you please specify which one would be preferred for such a scenario considering speed, features, and security of the site. Thanks, niting
Most of the frameworks out there nowadays are fast enough to serve whatever needs you will have. It really depends on in which environment you feel most comfortable. Though there are nuances here and there, MVC frameworks share a lot of the same principles, so whichever you choose to use is really a matter of which you most enjoy using. So, if you like Python more, there's your answer. Use a Python framework, and Django is the best. If you like PHP more (which I personally don't), you've got some more decisions to make. But any of the PHP frameworks are fine. They really are. Just pick one that looks nice with comprehensive documentation and get to work.
1.2
true
5
505
2010-04-05 13:18:44.587
PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django
I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Although I have pretty good experience with python and PHP but I have no idea how to use either of the framework. We have plenty of time to experiment and learn one of the above frameworks.Could you please specify which one would be preferred for such a scenario considering speed, features, and security of the site. Thanks, niting
This is a very subjective question but personally I'd recommend Django. Python is a very nice language to use and the Django framework is small, easy to use, well documented and also has a pretty active community. This choice was made partly because of my dislike for PHP though, so take the recommendation with a pinch of salt.
0.999139
false
5
505
2010-04-05 20:23:48.887
Disable autocomplete on textfield in Django?
Does anyone know how you can turn off autocompletion on a textfield in Django? For example, a form that I generate from my model has an input field for a credit card number. It is bad practice to leave autocompletion on. When making the form by hand, I'd add a autocomplete="off" statement, but how do you do it in Django and still retain the form validation?
Add the autocomplete="off" to the form tag, so you don't have to change the django.form instance. <form action="." method="post" autocomplete="off"> {{ form }} </form>
0.999996
false
1
506
2010-04-06 13:24:47.997
Emacs bulk indent for Python
Working with Python in Emacs if I want to add a try/except to a block of code, I often find that I am having to indent the whole block, line by line. In Emacs, how do you indent the whole block at once. I am not an experienced Emacs user, but just find it is the best tool for working through ssh. I am using Emacs on the command line(Ubuntu), not as a gui, if that makes any difference.
indent-region mapped to C-M-\ should do the trick.
0.201295
false
2
507
2010-04-06 13:24:47.997
Emacs bulk indent for Python
Working with Python in Emacs if I want to add a try/except to a block of code, I often find that I am having to indent the whole block, line by line. In Emacs, how do you indent the whole block at once. I am not an experienced Emacs user, but just find it is the best tool for working through ssh. I am using Emacs on the command line(Ubuntu), not as a gui, if that makes any difference.
In addition to indent-region, which is mapped to C-M-\ by default, the rectangle edit commands are very useful for Python. Mark a region as normal, then: C-x r t (string-rectangle): will prompt you for characters you'd like to insert into each line; great for inserting a certain number of spaces C-x r k (kill-rectangle): remove a rectangle region; great for removing indentation You can also C-x r y (yank-rectangle), but that's only rarely useful.
0.470104
false
2
507
2010-04-08 04:03:48.057
deletion of folders
how can i delete a folder using python script?and what are the return values??
you can use os.rmdir() to remove a directory. To remove a directory tree recursively, you can use shutil.rmtree. If you know that you already have empty directory nodes, you can also check out os.removedirs()
0
false
1
508
2010-04-09 18:45:51.457
ISBNs are used as primary key, now I want to add non-book things to the DB - should I migrate to EAN?
I built an inventory database where ISBN numbers are the primary keys for the items. This worked great for a while as the items were books. Now I want to add non-books. some of the non-books have EANs or ISSNs, some do not. It's in PostgreSQL with django apps for the frontend and JSON api, plus a few supporting python command-line tools for management. the items in question are mostly books and artist prints, some of which are self-published. What is nice about using ISBNs as primary keys is that in on top of relational integrity, you get lots of handy utilities for validating ISBNs, automatically looking up missing or additional information on the book items, etcetera, many of which I've taken advantage. some such tools are off-the-shelf (PyISBN, PyAWS etc) and some are hand-rolled -- I tried to keep all of these parts nice and decoupled, but you know how things can get. I couldn't find anything online about 'private ISBNs' or 'self-assigned ISBNs' but that's the sort of thing I was interested in doing. I doubt that's what I'll settle on, since there is already an apparent run on ISBN numbers. should I retool everything for EAN numbers, or migrate off ISBNs as primary keys in general? if anyone has any experience with working with these systems, I'd love to hear about it, your advice is most welcome.
A simple solution (although arguably whether good) would be to use (isbn,title) or (isbn,author) which should pretty much guarantee uniqueness. Ideology is great but practicality also serves a purpose.
0.101688
false
2
509
2010-04-09 18:45:51.457
ISBNs are used as primary key, now I want to add non-book things to the DB - should I migrate to EAN?
I built an inventory database where ISBN numbers are the primary keys for the items. This worked great for a while as the items were books. Now I want to add non-books. some of the non-books have EANs or ISSNs, some do not. It's in PostgreSQL with django apps for the frontend and JSON api, plus a few supporting python command-line tools for management. the items in question are mostly books and artist prints, some of which are self-published. What is nice about using ISBNs as primary keys is that in on top of relational integrity, you get lots of handy utilities for validating ISBNs, automatically looking up missing or additional information on the book items, etcetera, many of which I've taken advantage. some such tools are off-the-shelf (PyISBN, PyAWS etc) and some are hand-rolled -- I tried to keep all of these parts nice and decoupled, but you know how things can get. I couldn't find anything online about 'private ISBNs' or 'self-assigned ISBNs' but that's the sort of thing I was interested in doing. I doubt that's what I'll settle on, since there is already an apparent run on ISBN numbers. should I retool everything for EAN numbers, or migrate off ISBNs as primary keys in general? if anyone has any experience with working with these systems, I'd love to hear about it, your advice is most welcome.
I don't know postgres but normally ISBM would be a unique index key but not the primary. It's better to have an integer as primary/foreign key. That way you only need to add a new field EAN/ISSN as nullable.
0.296905
false
2
509
2010-04-09 19:44:57.647
How to create make .so files from code written in C or C++ that are usable from Python
Looking at Python modules and at code in the "lib-dnyload" directory in the Python framework, I noticed whenever code is creating some kind of GUI or graphic it imports a non-Python file with a .so extension. And there are tons .so files in "lib-dnyload". From googling things I found that these files are called shared objects and are written in C or C++. I have a Mac and I use GCC. How do I make shared object files that are accessible via Python? Mainly just how to make shared objects with GCC using Mac OS X.
You can write python extensions in many ways, including Cython, SWIG, boost.python ... You can also write a shared library and use the "ctypes" library to access it.
0
false
1
510
2010-04-09 21:58:06.780
How do I write raw binary data in Python?
I've got a Python program that stores and writes data to a file. The data is raw binary data, stored internally as str. I'm writing it out through a utf-8 codec. However, I get UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 25: character maps to <undefined> in the cp1252.py file. This looks to me like Python is trying to interpret the data using the default code page. But it doesn't have a default code page. That's why I'm using str, not unicode. I guess my questions are: How do I represent raw binary data in memory, in Python? When I'm writing raw binary data out through a codec, how do I encode/unencode it?
You shouldn't normally use codecs with str, except to turn them into unicodes. Perhaps you should be looking at using the latin-1 codec if you think you want "raw" data in your unicodes.
0
false
2
511
2010-04-09 21:58:06.780
How do I write raw binary data in Python?
I've got a Python program that stores and writes data to a file. The data is raw binary data, stored internally as str. I'm writing it out through a utf-8 codec. However, I get UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 25: character maps to <undefined> in the cp1252.py file. This looks to me like Python is trying to interpret the data using the default code page. But it doesn't have a default code page. That's why I'm using str, not unicode. I guess my questions are: How do I represent raw binary data in memory, in Python? When I'm writing raw binary data out through a codec, how do I encode/unencode it?
NOTE: this was written for Python 2.x. Not sure if applicable to 3.x. Your use of str for raw binary data in memory is correct. [If you're using Python 2.6+, it's even better to use bytes which in 2.6+ is just an alias to str but expresses your intention better, and will help if one day you port the code to Python 3.] As others note, writing binary data through a codec is strange. A write codec takes unicode and outputs bytes into the file. You're trying to do it backwards, hence our confusion about your intentions... [And your diagnosis of the error looks correct: since the codec expects unicode, Python is decoding your str into unicode with the system's default encoding, which chokes.] What you want to see in the output file? If the file should contain the binary data as-is: Then you must not send it through a codec; you must write it directly to the file. A codec encodes everything and can only emit valid encodings of unicode (in your case, valid UTF-8). There is no input you can give it to make it emit arbitrary byte sequences! If you require a mixture of UTF-8 and raw binary data, you should open the file directly, and intermix writes of some_data with some_text.encode('utf8')... Note however that mixing UTF-8 with raw arbitrary data is very bad design, because such files are very inconvenient to deal with! Tools that understand unicode will choke on the binary data, leaving you with not convenient way to even view (let alone modify) the file. If you want a friendly representation of arbitrary bytes in unicode: Pass data.encode('base64') to the codec. Base64 produces only clean ascii (letters, numbers, and a little punctuation) so it can be clearly embedded in anything, it clearly looks to people as binary data, and it's reasonably compact (slightly over 33% overhead). P.S. you may note that data.encode('base64') is strange. .encode() is supposed to take unicode but I'm giving it a string?! Python has several pseudo-codecs that convert str->str such as 'base64' and 'zlib'. .encode() always returns an str but you'll feed it into a codec expecting unicode?! In this case it will only contain clean ascii, so it doesn't matter. You may write explicitly data.encode('base64').encode('utf8') if it makes you feel better. If you need a 1:1 mapping from arbitrary bytes to unicode: Pass data.decode('latin1') to the codec. latin1 maps bytes 0-255 to unicode characters 0-255, which is kinda elegant. The codec will, of course, encode your characters - 128-255 are encoded as 2 or 3 bytes in UTF-8 (surprisingly, the average overhead is 50%, more than base64!). This quite kills the "elegance" of having a 1:1 mapping. Note also that unicode characters 0-255 include nasty invisible/control characters (newline, formfeed, soft hyphen, etc.) making your binary data annoying to view in text editors. Considering these drawbacks, I do not recommend latin1 unless you understand exactly why you want it. I'm just mentioning it as the other "natural" encoding that springs to mind.
1.2
true
2
511
2010-04-11 03:15:41.097
How can I learn to set up a build process?
What I was taught at school is all about programming languages, software design, but hardly anything about how to automatically build a software, probably with something like unit testing integrated. Please tell me how do one start learning to set up a build process for his project. If this is too abstract to make any sense, I would add that I use Python and do web programming with Django. Thanks in advance.
For Python projects you should use setuptools. Setuptools has all the stuff to pack things up into .eggs, compile C modules, run unit tests, etc... If you've ever done "python setup.py [build|install|test]" then you've used setuptools.
0.081452
false
2
512
2010-04-11 03:15:41.097
How can I learn to set up a build process?
What I was taught at school is all about programming languages, software design, but hardly anything about how to automatically build a software, probably with something like unit testing integrated. Please tell me how do one start learning to set up a build process for his project. If this is too abstract to make any sense, I would add that I use Python and do web programming with Django. Thanks in advance.
While this is certainly not a complete answer to your question, I would like to recommend very highly the learning of the tool 'make'. I find myself using it on a VERY regular basis, for a wide variety of tasks, including (but by no means limited to) building, testing, and deploying software.
0
false
2
512
2010-04-11 03:42:56.387
Installing virtualenvwrapper on Windows
I've installed virtualenv and virtualenvwrapper on Windows using easy_install. But mkvirtualenv is missing. I tried to search on my machine but I couldn't find it. I don't know how to solve it. Do you have any idea?
mkvirtualenv is a bash script so you need to run bash shell to make use of it. mkvirtualenv is a bash function in the mkvirtualenv_bashrc script You will need to run this from cygwin under Windows. (You can call a native python from this and not need a cygwin python)
1.2
true
2
513
2010-04-11 03:42:56.387
Installing virtualenvwrapper on Windows
I've installed virtualenv and virtualenvwrapper on Windows using easy_install. But mkvirtualenv is missing. I tried to search on my machine but I couldn't find it. I don't know how to solve it. Do you have any idea?
In windows we need to use virtualenv not mkvirtualenv while creating virtual environments
0.327599
false
2
513
2010-04-11 06:01:58.793
Python: what package contains the installation metadata?
e.g., how can I find out that the executable has been installed in "/usr/bin/python" and the library files in "/usr/lib/python2.6"?
You want the sys module: >>> print sys.executable /usr/bin/python >>> print sys.path ['', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Python/2.6/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode']
0.201295
false
1
514
2010-04-11 09:45:28.490
Does python-memcached support consistent hashing & binary protocol?
Python-memcached is the official supported memcached driver for Django. Does it support Consistent hashing Binary protocol If it does, how do I use those features within Django? I couldn't find any documentation.
Looking at the _get_server method on python-memcached v1.45, it seems it doesn't use consistent hashing, but a simple hash % len(buckets). Same goes for binary protocol, python-memcache uses, as far as I can see in the source, only text commands.
1.2
true
1
515
2010-04-13 07:41:56.143
How do I start learn Python for web
I have been learning Python for a while, and now I'd like to learn Python for the web; using Python as a back-end of a website. Where and how do I start learning this? Example usages are: connecting to databases, and retrieving and storing information from forms.
there are numerous options for learning python for web. I learned python to access web data from courser.org, and the tutorial was very interesting. If you want to learn python for web then I suggest you to learn python to access web data in courser.org you can also learn python for everybody which is a specialization course with 5 courses in which each and every thing about python is given. The fun part of courser.org is that they provide assignments with due dates which means you have to complete an assessment of each week in that week itself. They also provide quiz. You have to pass all the assignments and quizzes to get the certificate which is very easy, you can easily complete the assessment and quizzes.
0
false
2
516
2010-04-13 07:41:56.143
How do I start learn Python for web
I have been learning Python for a while, and now I'd like to learn Python for the web; using Python as a back-end of a website. Where and how do I start learning this? Example usages are: connecting to databases, and retrieving and storing information from forms.
There are numerous frameworks for making websites in Python. Once you are familiar with Python and the general nature of websites which would include the knowledge of HTTP, HTML you can proceed by using any of the following to make websites using Python: Webapp2 - A simple framework to get you started with making websites and using this framework you can easily make websites and cloud services and host them on the Google App Engine service. Follow these links for more information on use and hosting: Welcome to webapp2!, Google App Engine Django - As Alex Remedios has mentioned Django is also a very popular and widely used MVC web framework for Python. It is very comprehensive and follows the MVC web design principles. Various hosting options are also available for the same. You can learn more about Django here - The Web framework for perfectionists with deadlines, The Django Book (for learning the use of Django) Flask - Flask is a simplistic framework for making webapplications and websites using Python. I do not extensive experience using it but from what I have read it is similar to Webapp2 in many ways but is not as comprehensive as Django. But, it is very easy to pickup and use. Flask (A Python Microframework) As far as my knowledge goes these are the best ways to use Python in the web. To answer your second question, it is not implicitly possible to use Python in cohesion with HTML content like you would with PHP. However, there are libraries to do that too like the following: Python Wiki - Digi Developer Karrigell 3.1.1 If you are making extensive applications/websites the above two frameworks will pose major problems in doing simple tasks.
0
false
2
516
2010-04-13 20:38:43.150
How to get a Device Specific UID using Python in ASE on Android?
I am working on am Android Scripting Environment (ASE) script in Python to replicate an iPhone app. I need a device UID of some sort. My thoughts where a salted MD5 hash of the MAC address or device phone number, but I can't figure out how to access either of those using the Python APIs within ASE. What can I do to create a UID in Python in ASE?
The newer versions of ASE now include a function call to create these identifiers.
1.2
true
1
517
2010-04-14 14:46:12.967
Python and Eclipse: How to use interactive console after running a module, with the module variables and functions
Let's consider 3 situations: 1) I write a pyhon module in Eclipse (pydev) and run it Ctrl-F11. The module runs and I don't have any control or access (AFAIK) to the module variables and functions. 2) I have defined a python interpreter as an external tool in Eclipse, so I can run it within Eclipse. It works fine, but it does not have tab completion. 3) I open my module with python IDLE (not eclipse) and press f5 (run). It runs on the IDLE opened window and when it finishes I have all the variables and functions form the module to play with. So I have 2 questions: a) how to enable, if possible, tab completion in python interpreter in Eclipse? If it's not possible, do I have any alternative to standard Python interpreter? b) I would like to run step 1) and then be able to continue developing / testing with python interpreter, just like I do with IDLE, but all inside Eclipse. Any suggestion? Thanks in advance
If you run it as a debug operation in Eclipse, you should be able to set a breakpoint, and you can then examine variables, etc. But you can evaluate random python scripts via the watch functionality.
1.2
true
1
518
2010-04-16 03:57:57.730
MySQL to AppEngine
I'm from Brazil and study at FATEC (college located in Brazil). I'm trying to learn about AppEngine. Now, I'm trying to load a large database from MySQL to AppEngine to perform some queries, but I don't know how i can do it. I did some testing with CSV files,but is there any way to perform the direct import from MySQL? This database is from Pentaho BI Server (www.pentaho.com). Thank you for your attention. Regards, Daniel Naito
If you're using Pentaho BI Server as your data source, why don't you consider using Pentaho Data Integration (ETL tool) to move the data over? At the very least PDI automate any movement of data between your data source and any AppEngine bulk loader tool (it can easily trigger any app with a shell step).
0
false
1
519
2010-04-16 04:21:52.330
Py GTK Drawing area and Rich Text Editor
I would like to include a rich text editor in a pygtk drawing area for an application i am developing. The editor ( a small resizable widget ) should be able to move around the drawing area like a rectangle. I am not sure how to start as I am pretty new to PyGTK. thank you !
gtk.TextView is "rich", in that it can display all types of formatting and even embedded widgets. If you want the functionality of editing rich text, you will have to write something yourself, though others have tried in applications like BloGTK. From which you could steal codes.
0
false
1
520
2010-04-16 07:58:56.710
how to call a c++ file from python without using any of the spam bindings?
i have this encryption algorithm written in C++ , but the values that has to be encrypted are being taken input and stored in a file by a python program . Thus how can i call this c++ program from python?
Look for the subprocess module. It is the recommended way to invoke processes from within Python. The os.system function is a viable alternative sometimes, if your needs are very simple (no pipes, simple arguments, etc.)
0.386912
false
2
521
2010-04-16 07:58:56.710
how to call a c++ file from python without using any of the spam bindings?
i have this encryption algorithm written in C++ , but the values that has to be encrypted are being taken input and stored in a file by a python program . Thus how can i call this c++ program from python?
The os.system function will invoke an arbitrary command-line from python.
0
false
2
521
2010-04-16 12:59:42.270
Inexpensive ways to add seek to a filetype object
PdfFileReader reads the content from a pdf file to create an object. I am querying the pdf from a cdn via urllib.urlopen(), this provides me a file like object, which has no seek. PdfFileReader, however uses seek. What is the simple way to create a PdfFileReader object from a pdf downloaded via url. Now, what can I do to avoid writing to disk and reading it again via file(). Thanks in advance.
I suspect you may be optimising prematurely here. Most modern systems will cache files in memory for a significant period of time before they flush them to disk, so if you write the data to a temporary file, read it back in, then close and delete the file you may find that there's no significant disc traffic (unless it really is 100MB). You might want to look at using tempfile.TemporaryFile() which creates a temporary file that is automatically deleted when closed, or else tempfile.SpooledTemporaryFile() which explicitly holds it all in memory until it exceeds a particular size.
0.135221
false
1
522
2010-04-16 16:11:58.573
access variables of other functions
in python, how can i access the variables of one function into another function, is it possible, i tried the global variable method but that doesn't work for me. can someone help me, how to access the variables from one function to another function.
Don't try to do this. Explicit is better than implicit - if your function needs access to certain variables, pass them in. If it needs to change a value in the calling function, return the new value.
0
false
2
523
2010-04-16 16:11:58.573
access variables of other functions
in python, how can i access the variables of one function into another function, is it possible, i tried the global variable method but that doesn't work for me. can someone help me, how to access the variables from one function to another function.
If you want to share data between functions then create a class and turn the functions into methods on the class.
1.2
true
2
523
2010-04-16 16:43:19.367
Django - how to write users and profiles handling in best way?
I am writing simple site that requires users and profiles to be handled. The first initial thought is to use django's build in user handling, but then the user model is too narrow and does not contain fields that I need. The documentation mentions user profiles, but user profiles section has been removed from djangobook covering django 1.0 (ideally, the solution should work with django 1.2), and the Internet is full of different solutions, not making the choice easier (like user model inheritance, user profiles and django signals, and so on). I would like to know, how to write this in good, modern, fast and secure way. Should I try to extend django builtin user model, or maybe should I create my own user model wide enough to keep all the information I need? Below you may find some specifications and expectations from the working solution: users should be able to register and authenticate every user should have profile (or model with all required fields) users dont need django builtin admin panel, but they need to edit their profiles/models via simple web form Please, let me know how do you solve those issues in your applications, and what is the best current way to handle users with django. Any links to articles/blogs or code examples are highly appreciated!
Thank you all for your answers! I know that django dev documentation mentions user profiles, but does it very briefly (roughly few lines) and links to djangobook containing information about user profiles, but... to its first version, covering django 0.96. The second version of djangobook, covering django 1.0 (that is way closer to 1.2 than 0.96) no longer has that information anywhere, what makes me highly confused - has anything changed? Is there other, better, more secure way to handle users and their profiles? Therefore this question asked.
0
false
1
524
2010-04-16 17:04:49.293
Capturing stdout within the same process in Python
I've got a python script that calls a bunch of functions, each of which writes output to stdout. Sometimes when I run it, I'd like to send the output in an e-mail (along with a generated file). I'd like to know how I can capture the output in memory so I can use the email module to build the e-mail. My ideas so far were: use a memory-mapped file (but it seems like I have to reserve space on disk for this, and I don't know how long the output will be) bypass all this and pipe the output to sendmail (but this may be difficult if I also want to attach the file)
You said that your script "calls a bunch of functions" so I'm assuming that they're python functions accessible from your program. I'm also assuming you're using print to generate the output in all these functions. If that's the case, you can just replace sys.stdout with a StringIO.StringIO which will intercept all the stuff you're writing. Then you can finally call the .getValue method on your StringIO to get everything that has been sent to the output channel. This will also work for external programs using the subprocess module which write to sys.stdout. This is a cheap way. I'd recommend that you do your output using the logging module. You'll have much more control over how it does it's output and you can control it more easily as well.
1.2
true
1
525
2010-04-17 22:24:51.723
In python, how do I drag and drop 1 or more files onto my script as arguments with absolute path? (for windows, linux, and mac)
I am writing a simple Python script with no GUI. I want to be able to drag and drop multiple files onto my python script and have access to their absolute paths inside of the script. How do I do this in Mac, Linux, and windows? For times sake, just Mac will be fine for now. I've googled this question and only found one related one but it was too confusing. I am currently running Mac OS X Snow Leopard. Any help is much appreciated. Thanks!
This really is independent of python. It depends entirely on which file browser you're using and how it supports drag and drop.
0.135221
false
2
526
2010-04-17 22:24:51.723
In python, how do I drag and drop 1 or more files onto my script as arguments with absolute path? (for windows, linux, and mac)
I am writing a simple Python script with no GUI. I want to be able to drag and drop multiple files onto my python script and have access to their absolute paths inside of the script. How do I do this in Mac, Linux, and windows? For times sake, just Mac will be fine for now. I've googled this question and only found one related one but it was too confusing. I am currently running Mac OS X Snow Leopard. Any help is much appreciated. Thanks!
Usually when you drag a file onto a script/executable, the OS passes the path to that file as a command-line argument. Check sys.argv
0.135221
false
2
526
2010-04-18 03:56:23.810
pexpect install problem
i have installed pexpect with the following command "python setup.py install" but when i try to run a program it says "AttributeError: 'module' object has no attribute 'spawn'". how to settle the matter?
Pexpect has not been ported to python3, and apparently the author has no plans on doing so. I tried converting it with the python 2to3 program, but could not get it to work.
0.135221
false
2
527
2010-04-18 03:56:23.810
pexpect install problem
i have installed pexpect with the following command "python setup.py install" but when i try to run a program it says "AttributeError: 'module' object has no attribute 'spawn'". how to settle the matter?
It looks like pexpect wasn't ported yet to python 3 (quite a late answer, but still usable for people googling here)
0.265586
false
2
527
2010-04-19 05:01:31.697
In SqlAlchemy, how to ignore m2m relationship attributes when merge?
There is a m2m relation in my models, User and Role. I want to merge a role, but i DO NOT want this merge has any effect on user and role relation-ship. Unfortunately, for some complicate reason, role.users if not empty. I tried to set role.users = None, but SA complains None is not a list. At this moment, I use sqlalchemy.orm.attributes.del_attribute, but I don't know if it's provided for this purpose.
You'd better fix your code to avoid setting role.users for the item you are going to merge. But there is another way - setting cascade='none' for this relation. Then you lose an ability to save relationship from Role side, you'll have to save User with roles attribute set.
1.2
true
1
528
2010-04-20 18:41:03.133
Regex for finding valid sphinx fields
I'm trying to validate that the fields given to sphinx are valid, but I'm having difficulty. Imagine that valid fields are cat, mouse, dog, puppy. Valid searches would then be: @cat search terms @(cat) search terms @(cat, dog) search term @cat searchterm1 @dog searchterm2 @(cat, dog) searchterm1 @mouse searchterm2 So, I want to use a regular expression to find terms such as cat, dog, mouse in the above examples, and check them against a list of valid terms. Thus, a query such as: @(goat) Would produce an error because goat is not a valid term. I've gotten so that I can find simple queries such as @cat with this regex: (?:@)([^( ]*) But I can't figure out how to find the rest. I'm using python & django, for what that's worth.
To match all allowed fields, the following rather fearful looking regex works: @((?:cat|mouse|dog|puppy)\b|\((?:(?:cat|mouse|dog|puppy)(?:, *|(?=\))))+\)) It returns these matches, in order: @cat, @(cat), @(cat, dog), @cat, @dog, @(cat, dog), @mouse. The regex breaks down as follows: @ # the literal character "@" ( # match group 1 (?:cat|mouse|dog|puppy) # one of your valid search terms (not captured) \b # a word boundary | # or... \( # a literal opening paren (?: # non-capturing group (?:cat|mouse|dog|puppy) # one of your valid search terms (not captured) (?: # non-capturing group , * # a comma "," plus any number of spaces | # or... (?=\)) # a position followed by a closing paren ) # end non-capture group )+ # end non-capture group, repeat \) # a literal closing paren ) # end match group one. Now to identify any invalid search, you would wrap all that in a negative look-ahead: @(?!(?:cat|mouse|dog|puppy)\b|\((?:(?:cat|mouse|dog|puppy)(?:, *|(?=\))))+\)) --^^ This would identify any @ character after which an invalid search term (or term combination) was attempted. Modifying it so that it also matches the invalid attempt instead of just pointing at it is not that hard anymore. You would have to prepare (?:cat|mouse|dog|puppy) from your field dynamically and plug it into the static rest of the regex. Should not be too hard to do either.
0.201295
false
1
529
2010-04-21 17:09:56.487
python: find and replace numbers < 1 in text file
I'm pretty new to Python programming and would appreciate some help to a problem I have... Basically I have multiple text files which contain velocity values as such: 0.259515E+03 0.235095E+03 0.208262E+03 0.230223E+03 0.267333E+03 0.217889E+03 0.156233E+03 0.144876E+03 0.136187E+03 0.137865E+00 etc for many lines... What I need to do is convert all the values in the text file that are less than 1 (e.g. 0.137865E+00 above) to an arbitrary value of 0.100000E+01. While it seems pretty simple to replace specific values with the 'replace()' method and a while loop, how do you do this if you want to replace a range? thanks
typical technique would be: read file line by line split each line into a list of strings convert each string to the float compare converted value with 1 replace when needed write back to the new file As I don't see you having any code yet, I hope that this would be a good start
0.265586
false
1
530
2010-04-23 10:08:06.833
Automating Excel macro using python
I am using python in Linux to automate an excel. I have finished writing data into excel by using pyexcelerator package. Now comes the real challenge. I have to add another tab to the existing sheet and that tab should contain the macro run in the first tab. All these things should be automated. I Googled a lot and found win32come to do a job in macro, but that was only for windows. Anyone have any idea of how to do this, or can you guide me with few suggestions.
Maybe manipulating your .xls with Openoffice and pyUno is a better way. Way more powerful.
0
false
2
531
2010-04-23 10:08:06.833
Automating Excel macro using python
I am using python in Linux to automate an excel. I have finished writing data into excel by using pyexcelerator package. Now comes the real challenge. I have to add another tab to the existing sheet and that tab should contain the macro run in the first tab. All these things should be automated. I Googled a lot and found win32come to do a job in macro, but that was only for windows. Anyone have any idea of how to do this, or can you guide me with few suggestions.
Excel Macros are per sheets, so, I am afraid, you need to copy the macros explicitly if you created new sheet, instead of copying existing sheet to new one.
0
false
2
531
2010-04-23 12:43:50.543
Gtk: How can I get a part of a file in a textview with scrollbars relating to the full file
I'm trying to make a very large file editor (where the editor only stores a part of the buffer in memory at a time), but I'm stuck while building my textview object. Basically- I know that I have to be able to update the text view buffer dynamically, and I don't know hot to get the scrollbars to relate to the full file while the textview contains only a small buffer of the file. I've played with Gtk.Adjustment on a Gtk.ScrolledWindow and ScrollBars, but though I can extend the range of the scrollbars, they still apply to the range of the buffer and not the filesize (which I try to set via Gtk.Adjustment parameters) when I load into textview. I need to have a widget that "knows" that it is looking at a part of a file, and can load/unload buffers as necessary to view different parts of the file. So far, I believe I'll respond to the "change_view" to calculate when I'm off, or about to be off the current buffer and need to load the next, but I don't know how to get the scrollbars to have the top relate to the beginning of the file, and the bottom relate to the end of the file, rather than to the loaded buffer in textview. Any help would be greatly appreciated, thanks!
You probably should create your own Gtk.TextBuffer implementation, as the default one relies on storing whole buffer in memory.
0.201295
false
1
532
2010-04-23 15:52:34.600
Importing Classes Within a Module
Currently, I have a parser with multiple classes that work together. For Instance: TreeParser creates multiple Product and Reactant modules which in turn create multiple Element classes. The TreeParser is called by a render method within the same module, which is called from the importer. Finally, if the package has dependencies (such as re and another another module within the same folder), where is the best place to require those modules? Within the __init__.py file or within the module itself? EDIT: When importing a part of a module that calls another def within the module, how do you call that def if it isn't imported? lib/toolset.py => def add(){ toolset.show("I'm Add"); } def show(text){print text}; if that file is called from main.py => import lib.toolset then, the show method wouldn't be loaded, or main.py => from lib.toolset import show wouldn't work. Can an import toolset be put at the top of toolset.py?
I'm not really sure what your problem is, is it that you just want to type less? get a decent source editor with autocomplete! you can do import longmodulename as ln and use ln.something instead of longmodulename.something you can do from longmodulename import ( something, otherthing ) and use something directly import * is never a good idea, it messes with coding tools, breaks silently, makes readers wonder stuff was defined and so on ...
0.386912
false
2
533
2010-04-23 15:52:34.600
Importing Classes Within a Module
Currently, I have a parser with multiple classes that work together. For Instance: TreeParser creates multiple Product and Reactant modules which in turn create multiple Element classes. The TreeParser is called by a render method within the same module, which is called from the importer. Finally, if the package has dependencies (such as re and another another module within the same folder), where is the best place to require those modules? Within the __init__.py file or within the module itself? EDIT: When importing a part of a module that calls another def within the module, how do you call that def if it isn't imported? lib/toolset.py => def add(){ toolset.show("I'm Add"); } def show(text){print text}; if that file is called from main.py => import lib.toolset then, the show method wouldn't be loaded, or main.py => from lib.toolset import show wouldn't work. Can an import toolset be put at the top of toolset.py?
I think this is the key statement in your question. I don't really want to add the module name in front of every call to the class My response: I hear what you're saying, but this is standard practice in Python. Any Python programmer reading code like "result = match(blah)" will presume you're calling a local function inside your own module. If you're actually talking about the function match() in the re module they'll expect to see "result = re.match(blah)". That's just how it is. If it helps, I didn't like this style either when I came to Python first, but now I appreciate that it removes any ambiguity over exactly which of the many functions called "match" I am calling, especially when I come back to read code that I wrote six months ago.
1.2
true
2
533
2010-04-25 20:55:44.383
How to make an executable file in Python?
I want to make an executable file (.exe) of my Python application. I want to know how to do it but have this in mind: I use a C++ DLL! Do I have to put the DLL along side with the .exe or is there some other way?
I've built exe files from Python 2.7 code using each of these tools: Cython (with --embed option) Nuitka Py2exe These all will produce a standalone exe. Your installer will have to include the requisite CRT dlls. Your end result will be indistinguishable from any other exe to the typical user. The first two compile to C first, then compile that to a final exe using whatever compiler you have installed. Py2Exe bundles Python and all your .pyo files into a zip which it embeds in the exe. When launched it unzips to the temp directory and runs the python from there. You'll need to add your dll to the .spec file so it is included in the zip resource. Alternatively, install your dll alongside the exe and load it using an absolute path in python.
0.058243
false
1
534
2010-04-27 14:27:05.607
Could Python's logging SMTP Handler be freezing my thread for 2 minutes?
A rather confusing sequence of events happened, according to my log-file, and I am about to put a lot of the blame on the Python logger, which is a bold claim. I thought I should get some second opinions about whether what I am saying could be true. I am trying to explain why there is are several large gaps in my log file (around two minutes at a time) during stressful periods for my application when it is missing deadlines. I am using Python's logging module on a remote server, and have set-up, with a configuration file, for all logs of severity of ERROR or higher to be emailed to me. Typically, only one error will be sent at a time, but during periods of sustained problems, I might get a dozen in a minute - annoying, but nothing that should stress SMTP. I believe that, after a short spurt of such messages, the Python logging system (or perhaps the SMTP system it is sitting on) is encountering errors or congestion. The call to Python's log is then BLOCKING for two minutes, causing my thread to miss its deadlines. (I was smart enough to move the logging until after the critical path of the application - so I don't care if logging takes me a few seconds, but two minutes is far too long.) This seems like a rather awkward architecture (for both a logging system that can freeze up, and for an SMTP system (Ubuntu, sendmail) that cannot handle dozens of emails in a minute**), so this surprises me, but it exactly fits the symptoms. Has anyone had any experience with this? Can anyone describe how to stop it from blocking? ** EDIT # 2 : I actually counted. 170 emails in two hours. Forget the previous edit. I counted wrong. It's late here...
Stress-testing was revealing: My logging configuration sent critical messages to SMTPHandler, and debug messages to a local log file. For testing I created a moderately large number of threads (e.g. 50) that waited for a trigger, and then simultaneosly tried to log either a critical message or a debug message, depending on the test. Test #1: All threads send critical messages: It revealed that the first critical message took about .9 seconds to send. The second critical message took around 1.9 seconds to send. The third longer still, quickly adding up. It seems that the messages that go to email block waiting for each other to complete the send. Test #2: All threads send debug messages: These ran fairly quickly, from hundreds to thousands of microseconds. Test #3: A mix of both. It was clear from the results that debug messages were also being blocked waiting for critical message's emails to go out. So, it wasn't that 2 minutes meant there was a timeout. It was the two minutes represented a large number of threads blocked waiting in the queue. Why were there so many critical messages being sent at once? That's the irony. There was a logging.debug() call inside a method that included a network call. I had some code monitoring the speed of the of the method (to see if the network call was taking too long). If so, it (of course) logged a critical error that sent an email. The next thread then blocked on the logging.debug() call, meaning it missed the deadline, triggering another email, triggering another thread to run slowly. The 2 minute delay in one thread wasn't a network timeout. It was one thread waiting for another thread, that was blocked for 1 minute 57 - because it was waiting for another thread blocked for 1 minute 55, etc. etc. etc. This isn't very pretty behaviour from SMTPHandler.
1.2
true
1
535
2010-04-28 00:55:44.230
Can I get the amount of time for which a key is pressed on a keyboard
I am working on a project in which I have to develop bio-passwords based on user's keystroke style. Suppose a user types a password for 20 times, his keystrokes are recorded, like holdtime : time for which a particular key is pressed. digraph time : time it takes to press a different key. suppose a user types a password " COMPUTER". I need to know the time for which every key is pressed. something like : holdtime for the above password is C-- 200ms O-- 130ms M-- 150ms P-- 175ms U-- 320ms T-- 230ms E-- 120ms R-- 300ms The rational behind this is , every user will have a different holdtime. Say a old person is typing the password, he will take more time then a student. And it will be unique to a particular person. To do this project, I need to record the time for each key pressed. I would greatly appreciate if anyone can guide me in how to get these times. Editing from here.. Language is not important, but I would prefer it in C. I am more interested in getting the dataset.
The answer is conditionally "yes". If your languages/environment has interactive keyboard support that offers Key-Down and Key-Up events, then you catch both events and time the difference between them. This would be trivially easy in JavaScript on a web page, which would also be the easiest way to show off your work to a wider audience.
0
false
2
536
2010-04-28 00:55:44.230
Can I get the amount of time for which a key is pressed on a keyboard
I am working on a project in which I have to develop bio-passwords based on user's keystroke style. Suppose a user types a password for 20 times, his keystrokes are recorded, like holdtime : time for which a particular key is pressed. digraph time : time it takes to press a different key. suppose a user types a password " COMPUTER". I need to know the time for which every key is pressed. something like : holdtime for the above password is C-- 200ms O-- 130ms M-- 150ms P-- 175ms U-- 320ms T-- 230ms E-- 120ms R-- 300ms The rational behind this is , every user will have a different holdtime. Say a old person is typing the password, he will take more time then a student. And it will be unique to a particular person. To do this project, I need to record the time for each key pressed. I would greatly appreciate if anyone can guide me in how to get these times. Editing from here.. Language is not important, but I would prefer it in C. I am more interested in getting the dataset.
If you read from the terminal in conical mode, you can read each keystroke as it's pressed. You won't see keydown keyup events, like you could if you trapped X events, but it's probably easier, especially if you're just running in a console or terminal.
0
false
2
536
2010-04-28 15:37:49.327
Finding all points common to two circles
In Python, how would one find all integer points common to two circles? For example, imagine a Venn diagram-like intersection of two (equally sized) circles, with center-points (x1,y1) and (x2,y2) and radii r1=r2. Additionally, we already know the two points of intersection of the circles are (xi1,yi1) and (xi2,yi2). How would one generate a list of all points (x,y) contained in both circles in an efficient manner? That is, it would be simple to draw a box containing the intersections and iterate through it, checking if a given point is within both circles, but is there a better way?
So you want to find the lattice points that are inside both circles? The method you suggested of drawing a box and iterating through all the points in the box seems the simplest to me. It will probably be efficient, as long as the number of points in the box is comparable to the number of points in the intersection. And even if it isn't as efficient as possible, you shouldn't try to optimize it until you have a good reason to believe it's a real bottleneck.
0
false
4
537
2010-04-28 15:37:49.327
Finding all points common to two circles
In Python, how would one find all integer points common to two circles? For example, imagine a Venn diagram-like intersection of two (equally sized) circles, with center-points (x1,y1) and (x2,y2) and radii r1=r2. Additionally, we already know the two points of intersection of the circles are (xi1,yi1) and (xi2,yi2). How would one generate a list of all points (x,y) contained in both circles in an efficient manner? That is, it would be simple to draw a box containing the intersections and iterate through it, checking if a given point is within both circles, but is there a better way?
You may also want to look into the various clipping algorithms used in graphics development. I have used clipping algorithms to solve alot of problems similar to what you are asking here.
0.067922
false
4
537
2010-04-28 15:37:49.327
Finding all points common to two circles
In Python, how would one find all integer points common to two circles? For example, imagine a Venn diagram-like intersection of two (equally sized) circles, with center-points (x1,y1) and (x2,y2) and radii r1=r2. Additionally, we already know the two points of intersection of the circles are (xi1,yi1) and (xi2,yi2). How would one generate a list of all points (x,y) contained in both circles in an efficient manner? That is, it would be simple to draw a box containing the intersections and iterate through it, checking if a given point is within both circles, but is there a better way?
If the locations and radii of your circles can vary with a granularity less than your grid, then you'll be checking a bunch of points anyway. You can minimize the number of points you check by defining the search area appropriately. It has a width equal to the distance between the points of intersection, and a height equal to r1 + r2 - D with D being the separation of the two centers. Note that this rectangle in general is not aligned with the X and Y axes. (This also gives you a test as to whether the two circles intersect!) Actually, you'd only need to check half of these points. If the radii are the same, you'd only need to check a quarter of them. The symmetry of the problem helps you there.
0.067922
false
4
537
2010-04-28 15:37:49.327
Finding all points common to two circles
In Python, how would one find all integer points common to two circles? For example, imagine a Venn diagram-like intersection of two (equally sized) circles, with center-points (x1,y1) and (x2,y2) and radii r1=r2. Additionally, we already know the two points of intersection of the circles are (xi1,yi1) and (xi2,yi2). How would one generate a list of all points (x,y) contained in both circles in an efficient manner? That is, it would be simple to draw a box containing the intersections and iterate through it, checking if a given point is within both circles, but is there a better way?
You're almost there. Iterating over the points in the box should be fairly good, but you can do better if for the second coordinate you iterate directly between the limits. Say you iterate along the x axis first, then for the y axis, instead of iterating between bounding box coords figure out where each circle intersects the x line, more specifically you are interested in the y coordinate of the intersection points, and iterate between those (pay attention to rounding) When you do this, because you already know you are inside the circles you can skip the checks entirely. If you have a lot of points then you skip a lot of checks and you might get some performance improvements. As an additional improvement you can pick the x axis or the y axis to minimize the number of times you need to compute intersection points.
0.067922
false
4
537
2010-04-28 19:06:45.113
Timed email reminder in python
I have written up a python script that allows a user to input a message, his email and the time and they would like the email sent. This is all stored in a mysql database. However, how do I get the script to execute on the said time and date? will it require a cron job? I mean say at 2:15 on april 20th, the script will search the database for all times of 2:15, and send out those emails. But what about for emails at 2:16? I am using a shared hosting provided, so cant have a continously running script. Thanks
If you cannot have a continuously running script, something must trigger it, so that would have to rely on your OS internals. In a unix environment a cron job, as you self state, would do the trick. Set cron to run the script, and make the script wait for a given time and then continue running and sending until the next email is more than this given time away. Then make your script add a new cron job for a new wakeup time.
1.2
true
2
538
2010-04-28 19:06:45.113
Timed email reminder in python
I have written up a python script that allows a user to input a message, his email and the time and they would like the email sent. This is all stored in a mysql database. However, how do I get the script to execute on the said time and date? will it require a cron job? I mean say at 2:15 on april 20th, the script will search the database for all times of 2:15, and send out those emails. But what about for emails at 2:16? I am using a shared hosting provided, so cant have a continously running script. Thanks
A cronjob every minute or so would do it. If you're considering this, you might like to mind two things: 1 - How many e-mails are expected to be sent per minute? If it takes you 1 second to send an e-mail and you have 100 e-mails per minute, you won't finish your queue. 2 - What will happen if one job starts before the last one finishes? Be careful not to send e-mails twice. You need either to make sure first process ends (risk: you can drop an e-mail eventually), avoid next process to start (risk: first process hangs whole queue) or make them work in parallel (risk: synchronization problems). If you take daramarak's suggestion - make you script add a new cron job at end - you have the risk of whole system colapsing if one error occurs.
0.135221
false
2
538
2010-04-29 09:00:18.540
How to get debugging of an App Engine application working?
I've got 10+ years in C/C++, and it appears Visual Studio has spoilt me during that time. In Visual Studio, debbuging issimple: I just add a breakpoint to a line of code, and as soon as that code is executed, my breakpoint triggers, at which point I can view a callstack, local/member variables, etc. I'm trying to achieve this functionality under App Engine. I assume that is possible? All the searching I've done to this point has led me to using Pydev in Eclipse. As best I can tell, I am successfully launching my simple 'hello world' program in Debug mode. But the IDE doesn't even seem to have an option to set a breakpoint? I must be missing something. I've googled long and hard about this, but am having no luck. Most results trace back to the same old threads that don't deal directly with my issue. Can anyone shed some light on how you get basic debugging setup using Pydev/Eclipse with App Engine? Alternatively, if there's an easier way to debug App Engine than using Pydev/Eclipse, I'd love to hear about it. Thanks in advance.
In fact setting a breakpoint in eclipse is very easy. You have two options: In the grey area next to your line numbers, doubleclick or right mouseclick -> toggle breakpoint.
1.2
true
1
539
2010-04-30 13:00:48.883
Change text_factory in Django/sqlite
I have a django project that uses a sqlite database that can be written to by an external tool. The text is supposed to be UTF-8, but in some cases there will be errors in the encoding. The text is from an external source, so I cannot control the encoding. Yes, I know that I could write a "wrapping layer" between the external source and the database, but I prefer not having to do this, especially since the database already contains a lot of "bad" data. The solution in sqlite is to change the text_factory to something like: lambda x: unicode(x, "utf-8", "ignore") However, I don't know how to tell the Django model driver this. The exception I get is: 'Could not decode to UTF-8 column 'Text' with text' in /var/lib/python-support/python2.5/django/db/backends/sqlite3/base.py in execute Somehow I need to tell the sqlite driver not to try to decode the text as UTF-8 (at least not using the standard algorithm, but it needs to use my fail-safe variant).
Incompatible Django version. Check Django version for solving this error first. I was running on Django==3.0.8 and it was producing an error. Than I ran virtualenv where I have Django==3.1.2 and the error was removed.
0
false
1
540
2010-04-30 19:13:05.883
Running CPython Applications With Visual Studio?
I would like to know how to use Visual Studio with CPython (the official python.org python interpreter, not IronPython). In particular, I am interested in getting "build" and "run" commands in Visual Studio working. Other features such as color highlighting and auto-complete, I am less concerned about. Also, can the "build" command be made to run py2exe or similar exe packagers?
You can create custom project that will execute a bat file when building. I remember that I used this method to generate a Inoosetup installer so that you should work to run the py2exe script. I have no idea for the rest of the features. The syntax highlighting and the auto-complete should be much more challenging. I would recommend to give a try to Komodo Edit or Eclipse/Pydev. It works out of the box
0
false
3
541
2010-04-30 19:13:05.883
Running CPython Applications With Visual Studio?
I would like to know how to use Visual Studio with CPython (the official python.org python interpreter, not IronPython). In particular, I am interested in getting "build" and "run" commands in Visual Studio working. Other features such as color highlighting and auto-complete, I am less concerned about. Also, can the "build" command be made to run py2exe or similar exe packagers?
Eclipse and PyDev already provide an excellent development environment for Python. Is there any reason you cannot use them?
0.101688
false
3
541
2010-04-30 19:13:05.883
Running CPython Applications With Visual Studio?
I would like to know how to use Visual Studio with CPython (the official python.org python interpreter, not IronPython). In particular, I am interested in getting "build" and "run" commands in Visual Studio working. Other features such as color highlighting and auto-complete, I am less concerned about. Also, can the "build" command be made to run py2exe or similar exe packagers?
Are you trying to build CPython itself? Doesn't it come with project files suitable for use with Visual Studio? (I seem to remember that it did.) If you mean that you want to use CPython but not build it, then just type c:\pythonxx\python.exe into the debugging executable and in the arguments put your script's full path name. Create a makefile project and you can do whatever you want with the build rules to get "build" to function.
0.101688
false
3
541
2010-04-30 22:37:23.463
MUD (game) design concept question about timed events
I'm trying my hand at building a MUD (multiplayer interactive-fiction game) I'm in the design/conceptualizing phase and I've run into a problem that I can't come up with a solution for. I'm hoping some more experienced programmers will have some advice. Here's the problem as best I can explain it. When the player decides to perform an action he sends a command to the server. the server then processes the command, determines whether or not the action can be performed, and either does it or responds with a reason as to why it could not be done. One reason that an action might fail is that the player is busy doing something else. For instance, if a player is mid-fight and has just swung a massive broadsword, it might take 3 seconds before he can repeat this action. If the player attempts to swing again to soon, the game will respond indicating that he must wait x seconds before doing that. Now, this I can probably design without much trouble. The problem I'm having is how I can replicate this behavior from AI creatures. All of the events that are being performed by the server ON ITS OWN, aka not as an immediate reaction to something a player has done, will have to be time sensitive. Some evil monster has cast a spell on you but must wait 30 seconds before doing it again... I think I'll probably be adding all these events to some kind of event queue, but how can I make that event queue time sensitive?
MUDs actions are usually performed on 'ticks' rather than immediately - this allows for limited affect of latency and for monster's commands to be inserted in the queue and processed fairly. Personally, I don't like this approach, but pretty much 99% of MUDs use it. You need to design a robust command queue & event queue which can handle both AI and user commands. You can then add "virtual latency" to AI commands which may be predefined or an average of all users latency, or whatever you like.
0.229097
false
5
542
2010-04-30 22:37:23.463
MUD (game) design concept question about timed events
I'm trying my hand at building a MUD (multiplayer interactive-fiction game) I'm in the design/conceptualizing phase and I've run into a problem that I can't come up with a solution for. I'm hoping some more experienced programmers will have some advice. Here's the problem as best I can explain it. When the player decides to perform an action he sends a command to the server. the server then processes the command, determines whether or not the action can be performed, and either does it or responds with a reason as to why it could not be done. One reason that an action might fail is that the player is busy doing something else. For instance, if a player is mid-fight and has just swung a massive broadsword, it might take 3 seconds before he can repeat this action. If the player attempts to swing again to soon, the game will respond indicating that he must wait x seconds before doing that. Now, this I can probably design without much trouble. The problem I'm having is how I can replicate this behavior from AI creatures. All of the events that are being performed by the server ON ITS OWN, aka not as an immediate reaction to something a player has done, will have to be time sensitive. Some evil monster has cast a spell on you but must wait 30 seconds before doing it again... I think I'll probably be adding all these events to some kind of event queue, but how can I make that event queue time sensitive?
AI's are clients. They're "part of the server" only in the most distant view. They're actually outside the main game engine. They're specialized clients with no human being. An AI client has the same interface with the server that a human's client would.
0.173164
false
5
542
2010-04-30 22:37:23.463
MUD (game) design concept question about timed events
I'm trying my hand at building a MUD (multiplayer interactive-fiction game) I'm in the design/conceptualizing phase and I've run into a problem that I can't come up with a solution for. I'm hoping some more experienced programmers will have some advice. Here's the problem as best I can explain it. When the player decides to perform an action he sends a command to the server. the server then processes the command, determines whether or not the action can be performed, and either does it or responds with a reason as to why it could not be done. One reason that an action might fail is that the player is busy doing something else. For instance, if a player is mid-fight and has just swung a massive broadsword, it might take 3 seconds before he can repeat this action. If the player attempts to swing again to soon, the game will respond indicating that he must wait x seconds before doing that. Now, this I can probably design without much trouble. The problem I'm having is how I can replicate this behavior from AI creatures. All of the events that are being performed by the server ON ITS OWN, aka not as an immediate reaction to something a player has done, will have to be time sensitive. Some evil monster has cast a spell on you but must wait 30 seconds before doing it again... I think I'll probably be adding all these events to some kind of event queue, but how can I make that event queue time sensitive?
I'll provide you an answer from an LPMud/LDMud point of view. Every player in the MUD is an instance of player.c. Player.c inherits from living.c. Things that are living have a heartbeat. The heartbeat function is processed once every 2 seconds for every living object on the mud (or anything that has a heartbeat() function). Timing events is not typically done based on seconds, but instead based on the number of heartbeats that have elapsed through counters within the object. The wonderful news that applies to your question is that monsters also inherit from living.c. This means that if you had actions that can only be performed periodically this can all be managed within the heartbeat based on the number of ticks that have occurred.
0
false
5
542
2010-04-30 22:37:23.463
MUD (game) design concept question about timed events
I'm trying my hand at building a MUD (multiplayer interactive-fiction game) I'm in the design/conceptualizing phase and I've run into a problem that I can't come up with a solution for. I'm hoping some more experienced programmers will have some advice. Here's the problem as best I can explain it. When the player decides to perform an action he sends a command to the server. the server then processes the command, determines whether or not the action can be performed, and either does it or responds with a reason as to why it could not be done. One reason that an action might fail is that the player is busy doing something else. For instance, if a player is mid-fight and has just swung a massive broadsword, it might take 3 seconds before he can repeat this action. If the player attempts to swing again to soon, the game will respond indicating that he must wait x seconds before doing that. Now, this I can probably design without much trouble. The problem I'm having is how I can replicate this behavior from AI creatures. All of the events that are being performed by the server ON ITS OWN, aka not as an immediate reaction to something a player has done, will have to be time sensitive. Some evil monster has cast a spell on you but must wait 30 seconds before doing it again... I think I'll probably be adding all these events to some kind of event queue, but how can I make that event queue time sensitive?
You could use threads to handle specific types of Mobs, and put all the instances into an array of some sort. Then, the thread simply goes through the list repeatedly applying logic. DelayTimeStart and Delay could be attributes of the parent Mob class, and when the thread goes through the loop, it can put off processing any instances of the Mob in which there is time remaining in the delay.
0.116092
false
5
542
2010-04-30 22:37:23.463
MUD (game) design concept question about timed events
I'm trying my hand at building a MUD (multiplayer interactive-fiction game) I'm in the design/conceptualizing phase and I've run into a problem that I can't come up with a solution for. I'm hoping some more experienced programmers will have some advice. Here's the problem as best I can explain it. When the player decides to perform an action he sends a command to the server. the server then processes the command, determines whether or not the action can be performed, and either does it or responds with a reason as to why it could not be done. One reason that an action might fail is that the player is busy doing something else. For instance, if a player is mid-fight and has just swung a massive broadsword, it might take 3 seconds before he can repeat this action. If the player attempts to swing again to soon, the game will respond indicating that he must wait x seconds before doing that. Now, this I can probably design without much trouble. The problem I'm having is how I can replicate this behavior from AI creatures. All of the events that are being performed by the server ON ITS OWN, aka not as an immediate reaction to something a player has done, will have to be time sensitive. Some evil monster has cast a spell on you but must wait 30 seconds before doing it again... I think I'll probably be adding all these events to some kind of event queue, but how can I make that event queue time sensitive?
A basic approach would be to have a data structure representing the evil monster's instance of its spell, with a cooldown timer on it. When the power is used, the cooldown is set (presumably to a number of seconds defined by the master definition of the spell); an attempt to use it again will fail just like with the player ability. This can be integrated with an event queue by having the queue check cooldown, and if it hasn't expired, to wait for it to expire, or abort the action, or reschedule the action, as appropriate.
0
false
5
542
2010-05-01 04:57:23.553
What are some strategies for maintaining a common database schema with a team of developers and no DBA?
I'm curious about how others have approached the problem of maintaining and synchronizing database changes across many (10+) developers without a DBA? What I mean, basically, is that if someone wants to make a change to the database, what are some strategies to doing that? (i.e. I've created a 'Car' model and now I want to apply the appropriate DDL to the database, etc..) We're primarily a Python shop and our ORM is SQLAlchemy. Previously, we had written our models in such a way to create the models using our ORM, but we recently ditched this because: We couldn't track changes using the ORM The state of the ORM wasn't in sync with the database (e.g. lots of differences primarily related to indexes and unique constraints) There was no way to audit database changes unless the developer documented the database change via email to the team. Our solution to this problem was to basically have a "gatekeeper" individual who checks every change into the database and applies all accepted database changes to an accepted_db_changes.sql file, whereby the developers who need to make any database changes put their requests into a proposed_db_changes.sql file. We check this file in, and, when it's updated, we all apply the change to our personal database on our development machine. We don't create indexes or constraints on the models, they are applied explicitly on the database. I would like to know what are some strategies to maintain database schemas and if ours seems reasonable. Thanks!
The solution is rather administrative then technical :) The general rule is easy, there should only be tree-like dependencies in the project: - There should always be a single master source of schema, stored together with the project source code in the version control - Everything affected by the change in the master source should be automatically re-generated every time the master source is updated, no manual intervention allowed never, if automatic generation does not work -- fix either master source or generator, don't manually update the source code - All re-generations should be performed by the same person who updated the master source and all changes including the master source change should be considered a single transaction (single source control commit, single build/deployment for every affected environment including DBs update) Being enforced, this gives 100% reliable result. There are essentially 3 possible choices of the master source 1) DB metadata, sources are generated after DB update by some tool connecting to the live DB 2) Source code, some tool is generating SQL scheme from the sources, annotated in a special way and then SQL is run on the DB 3) DDL, both SQL schema and source code are generated by some tool 4) some other description is used (say a text file read by a special Perl script generating both SQL schema and the source code) 1,2,3 are equally good, providing that the tool you need exists and is not over expensive 4 is a universal approach, but it should be applied from the very beginning of the project and has an overhead of couple thousands lines of code in a strange language to maintain
1.2
true
1
543
2010-05-01 14:43:37.153
Is www.example.com/post/21/edit a RESTful URI? I think I know the answer, but have another question
I'm almost afraid to post this question, there has to be an obvious answer I've overlooked, but here I go: Context: I am creating a blog for educational purposes (want to learn python and web.py). I've decided that my blog have posts, so I've created a Post class. I've also decided that posts can be created, read, updated, or deleted (so CRUD). So in my Post class, I've created methods that respond to POST, GET, PUT, and DELETE HTTP methods). So far so good. The current problem I'm having is a conceptual one, I know that sending a PUT HTTP message (with an edited Post) to, e.g., /post/52 should update post with id 52 with the body contents of the HTTP message. What I do not know is how to conceptually correctly serve the (HTML) edit page. Will doing it like this: /post/52/edit violate the idea of URI, as 'edit' is not a resource, but an action? On the other side though, could it be considered a resource since all that URI will respond to is a GET method, that will only return an HTML page? So my ultimate question is this: How do I serve an HTML page intended for user editing in a RESTful manner?
Instead of calling it /post/52/edit, what if you called it /post/52/editor? Now it is a resource. Dilemma averted.
0.201295
false
2
544
2010-05-01 14:43:37.153
Is www.example.com/post/21/edit a RESTful URI? I think I know the answer, but have another question
I'm almost afraid to post this question, there has to be an obvious answer I've overlooked, but here I go: Context: I am creating a blog for educational purposes (want to learn python and web.py). I've decided that my blog have posts, so I've created a Post class. I've also decided that posts can be created, read, updated, or deleted (so CRUD). So in my Post class, I've created methods that respond to POST, GET, PUT, and DELETE HTTP methods). So far so good. The current problem I'm having is a conceptual one, I know that sending a PUT HTTP message (with an edited Post) to, e.g., /post/52 should update post with id 52 with the body contents of the HTTP message. What I do not know is how to conceptually correctly serve the (HTML) edit page. Will doing it like this: /post/52/edit violate the idea of URI, as 'edit' is not a resource, but an action? On the other side though, could it be considered a resource since all that URI will respond to is a GET method, that will only return an HTML page? So my ultimate question is this: How do I serve an HTML page intended for user editing in a RESTful manner?
Another RESTful approach is to use the query string for modifiers: /post/52?edit=1 Also, don't get too hung up on the purity of the REST model. If your app doesn't fit neatly into the model, break the rules.
0.386912
false
2
544
2010-05-01 17:32:11.207
Google App Engine Python Unit Tests
I'd like to write some Python unit tests for my Google App Engine. How can I set that up? Does someone happen to have some sample code which shows how to write a simple test?
Since, gae is based on webhooks it can be easy to set your own testing framework for all relevant urls in your app.yaml. You can test it on sample dataset on development server ( start devel server with --datastore_path option ) and assert writes to database or webhook responses.
0.101688
false
1
545
2010-05-02 00:27:16.153
Algorithm detect repeating/similiar strings in a corpus of data -- say email subjects, in Python
I'm downloading a long list of my email subject lines , with the intent of finding email lists that I was a member of years ago, and would want to purge them from my Gmail account (which is getting pretty slow.) I'm specifically thinking of newsletters that often come from the same address, and repeat the product/service/group's name in the subject. I'm aware that I could search/sort by the common occurrence of items from a particular email address (and I intend to), but I'd like to correlate that data with repeating subject lines.... Now, many subject lines would fail a string match, but "Google Friends : Our latest news" "Google Friends : What we're doing today" are more similar to each other than a random subject line, as is: "Virgin Airlines has a great sale today" "Take a flight with Virgin Airlines" So -- how can I start to automagically extract trends/examples of strings that may be more similar. Approaches I've considered and discarded ('because there must be some better way'): Extracting all the possible substrings and ordering them by how often they show up, and manually selecting relevant ones Stripping off the first word or two and then count the occurrence of each sub string Comparing Levenshtein distance between entries Some sort of string similarity index ... Most of these were rejected for massive inefficiency or likelyhood of a vast amount of manual intervention required. I guess I need some sort of fuzzy string matching..? In the end, I can think of kludgy ways of doing this, but I'm looking for something more generic so I've added to my set of tools rather than special casing for this data set. After this, I'd be matching the occurring of particular subject strings with 'From' addresses - I'm not sure if there's a good way of building a data structure that represents how likely/not two messages are part of the 'same email list' or by filtering all my email subjects/from addresses into pools of likely 'related' emails and not -- but that's a problem to solve after this one. Any guidance would be appreciated.
I would first turn each string of characters into a set or multiset of words (ignoring punctuation and differences in lower/upper case). (If that's not powerful enough, in a second pass I could try pairs or even triples of adjacent words, known as bigrams and trigrams). The key measure of similarity between strings thus reduced is, what words that are not high frequency overall (not the, and, etc;-) are common to both strings, so a simple set intersection (or multiset intersection, but for your simple use case I think just sets would work fine, esp. sets of bigrams) should suffice to measure the "commonality". A word that's common to the two strings should be worth more the rarer it is, so negative log of frequency of the word across the whole corpus is an excellent starting point for this heuristics.
1.2
true
1
546
2010-05-02 23:17:24.667
Using recursion to sum two numbers (python)
I need to write a recursive function that can add two numbers (x, y), assuming y is not negative. I need to do it using two functions which return x-1 and x+1, and I can't use + or - anywhere in the code. I have no idea how to start, any hints?
This sounds like homework. So this is probably cheating: a+b is the same as a.__add__(b), and a-b is the same as a.__sub__(b). So you can easily add or subtract two numbers without using +/-. No need for any recursion.
-0.265586
false
1
547
2010-05-03 14:48:44.343
Writing a file shredder in python or ruby?
In the effort to learn python and/or ruby, I was wondering how a file shredder would be implemented? I would like it to take in a file as an argument and then employ an algorithm to make that file unrecoverable. Would possibly add the support for multiple files or even whole directories later.
Since this is a learning exercise and not a professional attempt to secure data. How about this: 1. Discover the length of the file. 2. Write 0's to the same length of the file. 3. Save the file. 4. Delete the file. Then make another program that tries to recover the file. But yes, if looking to make something professional and not just an exercise, look into kitsune's answer.
0.201295
false
1
548
2010-05-03 14:54:44.810
Regular expression that finds and replaces non-ascii characters with Python
I need to change some characters that are not ASCII to '_'. For example, Tannh‰user -> Tannh_user If I use regular expression with Python, how can I do this? Is there better way to do this not using RE?
I'd rather just call ord on every character in the string, 1 by 1. If ord([char]) >= 128 the character is not an ascii character and should be replaced.
0.116092
false
1
549
2010-05-03 16:41:14.363
How to maintain long-lived python projects w.r.t. dependencies and python versions?
short version: how can I get rid of the multiple-versions-of-python nightmare ? long version: over the years, I've used several versions of python, and what is worse, several extensions to python (e.g. pygame, pylab, wxPython...). Each time it was on a different setup, with different OSes, sometimes different architectures (like my old PowerPC mac). Nowadays I'm using a mac (OSX 10.6 on x86-64) and it's a dependency nightmare each time I want to revive script older than a few months. Python itself already comes in three different flavours in /usr/bin (2.5, 2.6, 3.1), but I had to install 2.4 from macports for pygame, something else (cannot remember what) forced me to install all three others from macports as well, so at the end of the day I'm the happy owner of seven (!) instances of python on my system. But that's not the problem, the problem is, none of them has the right (i.e. same set of) libraries installed, some of them are 32bits, some 64bits, and now I'm pretty much lost. For example right now I'm trying to run a three-year-old script (not written by me) which used to use matplotlib/numpy to draw a real-time plot within a rectangle of a wxwidgets window. But I'm failing miserably: py26-wxpython from macports won't install, stock python has wxwidgets included but also has some conflict between 32 bits and 64 bits, and it doesn't have numpy... what a mess ! Obviously, I'm doing things the wrong way. How do you usally cope with all that chaos ?
install the python versions you need, better if from sources when you write a script, include the full python version into it (such as #!/usr/local/bin/python2.6) I can't see what could go wrong. If something does, it's probably macports fault anyway, not yours (one of the reasons I don't use macports anymore). I know I'm probably missing something and this will get downvoted, but please leave at least a little comment in that case, thanks :)
0.050976
false
4
550
2010-05-03 16:41:14.363
How to maintain long-lived python projects w.r.t. dependencies and python versions?
short version: how can I get rid of the multiple-versions-of-python nightmare ? long version: over the years, I've used several versions of python, and what is worse, several extensions to python (e.g. pygame, pylab, wxPython...). Each time it was on a different setup, with different OSes, sometimes different architectures (like my old PowerPC mac). Nowadays I'm using a mac (OSX 10.6 on x86-64) and it's a dependency nightmare each time I want to revive script older than a few months. Python itself already comes in three different flavours in /usr/bin (2.5, 2.6, 3.1), but I had to install 2.4 from macports for pygame, something else (cannot remember what) forced me to install all three others from macports as well, so at the end of the day I'm the happy owner of seven (!) instances of python on my system. But that's not the problem, the problem is, none of them has the right (i.e. same set of) libraries installed, some of them are 32bits, some 64bits, and now I'm pretty much lost. For example right now I'm trying to run a three-year-old script (not written by me) which used to use matplotlib/numpy to draw a real-time plot within a rectangle of a wxwidgets window. But I'm failing miserably: py26-wxpython from macports won't install, stock python has wxwidgets included but also has some conflict between 32 bits and 64 bits, and it doesn't have numpy... what a mess ! Obviously, I'm doing things the wrong way. How do you usally cope with all that chaos ?
What I usually do is trying to (progressively) keep up with the Python versions as they come along (and once all of the external dependencies have correct versions available). Most of the time the Python code itself can be transferred as-is with only minor needed modifications. My biggest Python project @ work (15.000+ LOC) is now on Python 2.6 a few months (upgrading everything from Python 2.5 did take most of a day due to installing / checking 10+ dependencies...) In general I think this is the best strategy with most of the interdependent components in the free software stack (think the dependencies in the linux software repositories): keep your versions (semi)-current (or at least: progressing at the same pace).
0.050976
false
4
550
2010-05-03 16:41:14.363
How to maintain long-lived python projects w.r.t. dependencies and python versions?
short version: how can I get rid of the multiple-versions-of-python nightmare ? long version: over the years, I've used several versions of python, and what is worse, several extensions to python (e.g. pygame, pylab, wxPython...). Each time it was on a different setup, with different OSes, sometimes different architectures (like my old PowerPC mac). Nowadays I'm using a mac (OSX 10.6 on x86-64) and it's a dependency nightmare each time I want to revive script older than a few months. Python itself already comes in three different flavours in /usr/bin (2.5, 2.6, 3.1), but I had to install 2.4 from macports for pygame, something else (cannot remember what) forced me to install all three others from macports as well, so at the end of the day I'm the happy owner of seven (!) instances of python on my system. But that's not the problem, the problem is, none of them has the right (i.e. same set of) libraries installed, some of them are 32bits, some 64bits, and now I'm pretty much lost. For example right now I'm trying to run a three-year-old script (not written by me) which used to use matplotlib/numpy to draw a real-time plot within a rectangle of a wxwidgets window. But I'm failing miserably: py26-wxpython from macports won't install, stock python has wxwidgets included but also has some conflict between 32 bits and 64 bits, and it doesn't have numpy... what a mess ! Obviously, I'm doing things the wrong way. How do you usally cope with all that chaos ?
At least under Linux, multiple pythons can co-exist fairly happily. I use Python 2.6 on a CentOS system that needs Python 2.4 to be the default for various system things. I simply compiled and installed python 2.6 into a separate directory tree (and added the appropriate bin directory to my path) which was fairly painless. It's then invoked by typing "python2.6". Once you have separate pythons up and running, installing libraries for a specific version is straightforward. If you invoke the setup.py script with the python you want, it will be installed in directories appropriate to that python, and scripts will be installed in the same directory as the python executable itself and will automagically use the correct python when invoked. I also try to avoid using too many libraries. When I only need one or two functions from a library (eg scipy), I'll often see if I can just copy them to my own project.
0
false
4
550
2010-05-03 16:41:14.363
How to maintain long-lived python projects w.r.t. dependencies and python versions?
short version: how can I get rid of the multiple-versions-of-python nightmare ? long version: over the years, I've used several versions of python, and what is worse, several extensions to python (e.g. pygame, pylab, wxPython...). Each time it was on a different setup, with different OSes, sometimes different architectures (like my old PowerPC mac). Nowadays I'm using a mac (OSX 10.6 on x86-64) and it's a dependency nightmare each time I want to revive script older than a few months. Python itself already comes in three different flavours in /usr/bin (2.5, 2.6, 3.1), but I had to install 2.4 from macports for pygame, something else (cannot remember what) forced me to install all three others from macports as well, so at the end of the day I'm the happy owner of seven (!) instances of python on my system. But that's not the problem, the problem is, none of them has the right (i.e. same set of) libraries installed, some of them are 32bits, some 64bits, and now I'm pretty much lost. For example right now I'm trying to run a three-year-old script (not written by me) which used to use matplotlib/numpy to draw a real-time plot within a rectangle of a wxwidgets window. But I'm failing miserably: py26-wxpython from macports won't install, stock python has wxwidgets included but also has some conflict between 32 bits and 64 bits, and it doesn't have numpy... what a mess ! Obviously, I'm doing things the wrong way. How do you usally cope with all that chaos ?
Some tips: on Mac OS X, use only the python installation in /Library/Frameworks/Python.framework. whenever you use numpy/scipy/matplotlib, install the enthought python distribution use virtualenv and virtualenvwrapper to keep those "system" installations pristine; ideally use one virtual environment per project, so each project's dependencies are fulfilled. And, yes, that means potentially a lot of code will be replicated in the various virtual envs. That seems like a bigger mess indeed, but at least things work that way. Basically, if one of the projects works in a virtualenv, it will keep working no matter what upgrades you perform, since you never change the "system" installs.
1.2
true
4
550
2010-05-04 07:26:42.727
I am using Python on Windows. How do I delete my script after it is run?
I have written a Python script and compiled it into a MS Windows EXE file. I can modify the code, but how do I make it remove itself after running?
I think the easiest solution is make an external .bat file that executes your exe file and deletes it when finished.
1.2
true
1
551
2010-05-04 18:14:01.250
Lua parser in python
I'm looking into using Lua in a web project. I can't seem to find any way of directly parsing in pure python and running Lua code in Python. Does anyone know how to do this? Joe
@the_drow From Lua's web site: Lua is a fast language engine with small footprint that you can embed easily into your application. Lua has a simple and well documented API that allows strong integration with code written in other languages. It is easy to extend Lua with libraries written in other languages. It is also easy to extend programs written in other languages with Lua. Lua has been used to extend programs written not only in C and C++, but also in Java, C#, Smalltalk, Fortran, Ada, Erlang, and even in other scripting languages, such as Perl and Ruby. @Joe Simpson Check out Lunatic Python, it might have what you want. I know it's an old question, but other people might be looking for this answer, as well. It's a good question that deserves a good answer.
0.135221
false
2
552
2010-05-04 18:14:01.250
Lua parser in python
I'm looking into using Lua in a web project. I can't seem to find any way of directly parsing in pure python and running Lua code in Python. Does anyone know how to do this? Joe
From your comments, it appears you a interested in a secure way of executing untrusted code. Redifining python builtins, as you suggested in a comment, is a horrible way to secure code. What you want is sandboxing, there are solutions for python, but I wouldn't recommend them. You would be much better of using Jython or IronPython, because the JVM and .NET clr, were designed with sandboxing in mind. I personally believe that in most cases, if you need to execute untrusted code, then you are putting too much or not enough trust in your users.
0.265586
false
2
552
2010-05-06 01:41:56.053
Embed FCKeditor in python app
I have a python application which need a gui HTML editor, I know FCKeditor is nice, so how to embed the FCKeditor in a python desktop app?
To embed FCKeditor (or maybe better the current CKeditor?), you basically need to embed a full-fledged browser (with Javascript) -- I believe wxPython may currently be the best bet for that, as I hear it has wxIE for Windows and wxWebKitCtrl for the Mac (I don't know if old summer-of-code ideas about making something suitable for Linux ever panned out, though). Most "HTML viewer" widgets, in most GUIs, don't support Javascript, and that's a must for (F?)CKeditor.
1.2
true
2
553
2010-05-06 01:41:56.053
Embed FCKeditor in python app
I have a python application which need a gui HTML editor, I know FCKeditor is nice, so how to embed the FCKeditor in a python desktop app?
In order of difficulty: If you just need to support Windows, you can embed IE in wx - see the docs and demos. wxWebKit is looking a bit more mature, but it's still in development. You could just use the web-browser using webbrowser.open(url). Things will be very crude, and interaction will be a pain. A fourth option - you could try out pyjamas for your whole GUI, then run it all in a web-browser.
0
false
2
553
2010-05-06 10:43:07.383
why in python giving to str func a unicode string will throw an exception?
for example the following: str(u'לשום') will throw an error. how can i prevent these?
If you're running on Python 3, the u'' notation is a syntax error. Is this your problem? Because in Python <3, your code is absolutely correct, and since 'test' is plain ASCII there are no decoding issues.
0
false
2
554
2010-05-06 10:43:07.383
why in python giving to str func a unicode string will throw an exception?
for example the following: str(u'לשום') will throw an error. how can i prevent these?
Calling str() on a unicode is the same as calling .encode(sys.getdefaultencoding()) on it. If the unicode contains characters that can't be encoded in the default encoding then it will throw a UnicodeEncodeError. The fix is to explicitly encode the unicode in a useful encoding, such as 'utf-8'.
0.998178
false
2
554
2010-05-06 12:03:24.113
django authentication .htaccess static
In my app users can upload files for other users. To make the uploaded files accesible only for the addresse I need some kind of static files authentication system. My idea, is to create the apache hosted directory for each user and to limit access to this derectory using .htaccess. This means that each time new django user is created, I need to create a directory and the appropriate .htaccess file in it. I know I should do it using post_save signals on User model but I don't know how to create the .htaccess in the user's directory from python level. Can you help me with that? Or perhaps you have better solution to my problem?
Use python to rewrite the .htaccess automatically? Use a database with users and use a Apache sessions to authenticate?
0.081452
false
1
555
2010-05-07 22:05:37.713
python httplib httpexception error codes
Does httplib.HTTPException have error codes? If so how do I get at them from the exception instance? Any help is appreciated.
The httplib module doesn't use exceptions to convey HTTP responses, just genuine errors (invalid HTTP responses, broken headers, invalid status codes, prematurely broken connections, etc.) Most of the httplib.HTTPException subclasses just have an associated message string (stored in the args attribute), if even that. httplib.HTTPException itself may have an "errno" value as the first entry in args (when raised through httplib.FakeSocket) but it's not a HTTP error code. The HTTP response codes are conveyed through the httplib.HTTPConnection object, though; the getresponse method will (usually) return a HTTPResponse instance with a status attribute set to the HTTP response code, and a reason attribute set to the text version of it. This includes error codes like 404 and 500. I say "usually" because you (or a library you use) can override httplib.HTTPConnection.response_class to return something else.
1.2
true
1
556
2010-05-11 11:28:45.010
Can I get the raw SQL generated by a prepared statement in Python’s sqlite3 module?
If so, how can I do this?
When executing a prepared statement, no new SQL is generated. The idea of prepared statements is that the SQL query and its data are transmitted separately (that's why you don't have to escape any arguments) - the query is most likely only stored in an optimized form after preparing it.
0.386912
false
2
557
2010-05-11 11:28:45.010
Can I get the raw SQL generated by a prepared statement in Python’s sqlite3 module?
If so, how can I do this?
when you create a prepared statement, the "template" SQL code is sent to the DBMS already, which compiles it into an expression tree. When you pass the values, the corresponding library (python sqlite3 module in your case) doesn't merge the values into the statement. The DBMS does. If you still want to produce a normal SQL string, you can use string replace functions to replace the placeholders by the values (after escaping them). What do you need this for?
1.2
true
2
557
2010-05-12 13:21:21.693
Eval IronPython Scripts during ASP.NET Web Request; Static Engine or Not
I would like to create an ASP.NET MVC web application which has extensible logic that does not require a re-build. I was thinking of creating a filter which had an instance of the IronPython engine. What I would like to know is: how much overhead is there in creating a new engine during each web request, and would it be a better idea to keep a static engine around? However, if I were to keep a single static engine around, what are the issues I might run into as far as locking and script scope? Is it possible to have multiple scopes in the same IropPython engine so I don't get variable collision and security issues between web requests?
I've just started using IronPython as extensibility point in my ASP.NET MVC aplication. I have one ipy engine (in static property) and for each request I create new scope and execute the script in that scope. Each scope should be independent on other scopes, no locking is needed. If I run into issues, I'll post it here. However, I don't expect any ;)
1.2
true
1
558
2010-05-13 07:38:13.833
catch output from linux telnet to a python script
My problem is that i want to do something like this in linux console telnet 192.168.255.28 > process.py i.e i would like to do some transformation with console telnet output using python script. I'm see Popen in python for this case, but i can't understand how can i get input from telnet if it do not stop all time.. Pleas any ideas.
As xitrium mentioned, it would be better if you used telnetlib. You can dispense with the whole mess of shell redirection etc. If you do something like telnet foo | process.py, you can read your programs stdin (sys.stdin) to get the output of the telnet program. When you're happy, you can exit and terminate the pipeline. subprocess.Popen would be used if you're trying to open the telnet program as a subprocess of the interpreter. I'm not sure you wanted that. In any case, telnetlib is the right way to go it seems. If you simply want an output text processor, consider perl. It's strengths lean in that direction.
0.135221
false
1
559
2010-05-14 05:45:48.500
how to increase Speed of a component made from Javascript or JQuery?
I want to make my component faster, I am using Javascript and JQuery to build that. I am using JSON object to communicate with component and back-end is python. Is there any suggestion to make component faster?
If speed is the issue, and you by profiling discover that js is the culprit, then I would look into replacing the jQuery with vanilla javascript, or a more optimized library. As jQuery tries to do 'everything' and trains its users into wrapping everything in $(), its bound to introduce unnecessary method calls (I've seen that a single call to $() can result in upto 100+ method calls).
0
false
2
560
2010-05-14 05:45:48.500
how to increase Speed of a component made from Javascript or JQuery?
I want to make my component faster, I am using Javascript and JQuery to build that. I am using JSON object to communicate with component and back-end is python. Is there any suggestion to make component faster?
Setup some analysis to see what takes time to process. Then decide if you want to try to optimize the javascript and client code, the communication up/down with the server or the actual speed of the python execution. When you have decided what you want to make faster, you can post samples of that to this site and people will probably be willing to help you.
1.2
true
2
560
2010-05-14 10:10:37.250
Data munging and data import scripting
I need to write some scripts to carry out some tasks on my server (running Ubuntu server 8.04 TLS). The tasks are to be run periodically, so I will be running the scripts as cron jobs. I have divided the tasks into "group A" and "group B" - because (in my mind at least), they are a bit different. Task Group A import data from a file and possibly reformat it - by reformatting, I mean doing things like santizing the data, possibly normalizing it and or running calculations on 'columns' of the data Import the munged data into a database. For now, I am mostly using mySQL for the vast majority of imports - although some files will be imported into a sqlLite database. Note: The files will be mostly text files, although some of the files are in a binary format (my own proprietary format, written by a C++ application I developed). Task Group B Extract data from the database Perform calculations on the data and either insert or update tables in the database. My coding experience is is primarily as a C/C++ developer, although I have been using PHP as well for the last 2 years or so (+ a few other languages which are not relevant for the purpose of this question). I am from a Windows background, so I am still finding my feet in the Linux environment. My question is this - I need to write scripts to perform the tasks I described above. Although I suppose I could write a few C++ applications to be used in the shell scripts, I think it may be better to write them in a scripting language, but this may be a flawed assumption. My thinking is that it would be easier to modify things in a script - no need to rebuild etc for changes to functionality. Additionally, C++ data munging in C++ tends to involve more lines of code than "natural" scripting languages such as Perl, Python etc. Assuming that the majority of people on here agree that scripting is the way to go, herein lies my dilemma. Which scripting language do I use to perform the tasks above (giving my background)? My gut instinct tells me that Perl (shudder) would be the most obvious choice for performing all of the above tasks. BUT (and that is a big BUT). The mere mention of Perl makes my toes curl, as I had a very, very bad experience with it a while back (bought the Perl Camel book + 'data munging with Perl' many years ago, but could still not 'grok' it just felt too alien. The syntax seems quite unnatural to me - despite how many times I have tried to learn it - so if possible, I would really like to give it a miss. PHP (which I already know), also am not sure is a good candidate for scripting on the CLI (I have not seen many examples on how to do this etc - so I may be wrong). The last thing I must mention is that IF I have to learn a new language in order to do this, I cannot afford (time constraint) to spend more than a day, in learning the key commands/features required in order to do this (I can always learn the details of the language later, once I have actually deployed the scripts). So, which scripting language would you recommend (PHP, Python, Perl, [insert your favorite here]) - and most importantly WHY? Or, should I just stick to writing little C++ applications that I call in a shell script? Lastly, if you have suggested a scripting language, can you please show with a FEW lines (Perl mongers - I'm looking in your direction [nothing too cryptic!]) how I can use the language you suggested to do what I am trying to do i.e. load a CSV file into some kind of data structure where you can access data columns easily for data manipulation dump the columnar data into a mySQL table load data from mySQL table into a data structure that allows columns/rows to be accessed in the scripting language Hopefully, the snippets will allow me to quickly spot the languages that will pose the steepest learning curve for me - as well as those that simple, elegant and efficient (hopefully those two criteria [elegance and shallow learning curve] are not orthogonal - though I suspect they might be).
import data from a file and possibly reformat it Python excels at this. Be sure to read up on the csv module so you don't waste time inventing it yourself. For binary data, you may have to use the struct module. [If you wrote the C++ program that produces the binary data, consider rewriting that program to stop using binary data. Your life will be simpler in the long run. Disk storage is cheaper than your time; highly compressed binary formats are more cost than value.] Import the munged data into a database. Extract data from the database Perform calculations on the data and either insert or update tables in the database. Use the mysqldb module for MySQL. SQLite is built-in to Python. Often, you'll want to use Object-Relational mapping rather than write your own SQL. Look at sqlobject and sqlalchemy for this. Also, before doing too much of this, buy a good book on data warehousing. Your two "task groups" sound like you're starting down the data warehousing road. It's easy to get this all fouled up through poor database design. Learn what a "Star Schema" is before you do anything else.
1.2
true
1
561
2010-05-15 16:54:55.100
If I start learning C on Ubuntu will it give me an edge when I start learning Objective-C later this summer?
I know Ruby right now, however I want to learn a new language. I am running Ubuntu 10.04 right now but I am going to get a Mac later this summer. Anyways I want something more for GUI development. I was wondering if I should learn C on Ubuntu right now, and then learn Objective-C when I get an iMac? Will learning C give me an edge? Or should I just learn Python on Ubuntu and then learn Objective-C when I get a new computer?
Sure Objective-C is quite easier to learn if you know C and quite a few books on Objective-C even asume you know C. Also consider learning a bit about MacRuby for GUI development ;)
0.081452
false
4
562
2010-05-15 16:54:55.100
If I start learning C on Ubuntu will it give me an edge when I start learning Objective-C later this summer?
I know Ruby right now, however I want to learn a new language. I am running Ubuntu 10.04 right now but I am going to get a Mac later this summer. Anyways I want something more for GUI development. I was wondering if I should learn C on Ubuntu right now, and then learn Objective-C when I get an iMac? Will learning C give me an edge? Or should I just learn Python on Ubuntu and then learn Objective-C when I get a new computer?
Yes. Learn how to program in C.
0
false
4
562
2010-05-15 16:54:55.100
If I start learning C on Ubuntu will it give me an edge when I start learning Objective-C later this summer?
I know Ruby right now, however I want to learn a new language. I am running Ubuntu 10.04 right now but I am going to get a Mac later this summer. Anyways I want something more for GUI development. I was wondering if I should learn C on Ubuntu right now, and then learn Objective-C when I get an iMac? Will learning C give me an edge? Or should I just learn Python on Ubuntu and then learn Objective-C when I get a new computer?
Learning C will definitely be of help, as Objective C inherits its many properties and adds to it. You could learn Objective C either from 'Learn Objective C on the Mac', this one's really a great book, and then if you plan to learn cocoa, get 'Learn Cocoa on the Mac' or the one by James Davidson, they should give you a fine head start, you can then consider moving to the one by Hillegass, and for a stunner 'Objective C developer handbook' by David Chisnall, this is a keeper, you can read it in a month or two. For the compiler I would point you to clang though a gcc and gnustep combination will work. clang is a better choice if you want to work on Obj C 2.0 features and it is under heavy development.
0
false
4
562
2010-05-15 16:54:55.100
If I start learning C on Ubuntu will it give me an edge when I start learning Objective-C later this summer?
I know Ruby right now, however I want to learn a new language. I am running Ubuntu 10.04 right now but I am going to get a Mac later this summer. Anyways I want something more for GUI development. I was wondering if I should learn C on Ubuntu right now, and then learn Objective-C when I get an iMac? Will learning C give me an edge? Or should I just learn Python on Ubuntu and then learn Objective-C when I get a new computer?
It's frequently helpful to learn programming languages in the order they were created. The folks that wrote Objective-C clearly had C and its syntax, peculiarities, and features in mind when they defined the language. It can't hurt you to learn C now. You may have some insight into why Objective-C is structured the way it is later. C has a great, classic book on it, The C Programming Language by Kernighan & Ritchie, which is short and easy to digest if you already have another language under your belt.
0.3154
false
4
562