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-05-17 02:14:40.500
Python: How do I create a reference to a reference?
I am traditionally a Perl and C++ programmer, so apologies in advance if I am misunderstanding something trivial about Python! I would like to create a reference to a reference. Huh? Ok. All objects in Python are actually references to the real object. So, how do I create a reference to this reference? Why do I need/want this? I am overriding sys.stdout and sys.stderr to create a logging library. I would like a (second-level) reference to sys.stdout. If I could create a reference to a reference, then I could create a generic logger class where the init function receives a reference to a file handle reference that will be overrided, e.g., sys.stdout or sys.stderr. Currently, I must hard-code both values. Cheers, Kevin
This can't be done. Pass the desired attribute as a string and use getattr() and setattr().
0
false
1
563
2010-05-17 12:48:31.233
Suggestions for a pluggable task framework in Django
I am developing a website which is aimed at being a GUI for several image processing algorithms (referred to as 'tasks'). At the moment, only one of these algorithms is finished, but there are more to come (which will have a similar, but not quite the same, workflow) Basically, the algorithm works as follows (not that it matters a lot, but just for the sake of clarity): 1) Enter some parameters and an input image 2) run algorithm part one --algorithm runs-- 3) review an interim result 4) edit the parameters if needed, and go to 2. 5) run algorithm part two --algorithm runs-- 6) review the result 7) adjust some of the interim results if needed, and go to 5 8) all done I expect some of the additional tasks to have a rather similar work flow, though it is perfectly possible that they won't. So, the easy way to implement this would be to create a separate django application for each algorithm. However, I'd like to be able to browse through a sorted list (by time of completion) of completed tasks, and for each of these task display a summary (name, description, start time, thumbnail). Is there anyone that can provide me with some suggestions on how I can implement this? I'd like to keep it as simple as possible, so additional task can be 'plugged' in as easy as possible.
I would make an app with a very abstract definition of a Task model. The Task model might contain properties for: the input arguments, the function to run, the time that the task was submitted, the time that the task has been actually running, and the result (which would be something like a singleton Task.NotFinished until finished). You could consider using twisted to run the tasks because: twisted has a well designed and tested implementation of asynchronous tasks; and you could run the tasks on other processors or machines.
0
false
1
564
2010-05-17 18:21:51.340
Using virtualenv to install different versions of same package
Since I have Django 1.1x on my Debian setup - how can I use virtualenv or similar and not have it mess up my system's default django version which in turn would break all my sites? Detailed instructions or a great tutorial link would very much be appreciated - please don't offer vague advice since I'm still a noob. Currently I store all my django projects in ~/django-sites and I am using Apache2 + mod_wsgi to deploy.
If you have easy_install, or better yet pip installed, should be as easy as: easy_install/pip install virtualenv mkdir django1.2 virtualenv django1.2 This will put the python binary in a bin folder inside the django1.2 folder. Just use that python binary, and you've got a nice little self-contained environment. You can then install easy_install/pip into that environment, and then install django 1.2 as well, and hack away.
1.2
true
1
565
2010-05-18 07:52:19.637
ropemacs USAGE tutorial
There are many sites with instructions on installing ropemacs, but so far I couldn't find any with instructions on how to use it after it's already installed. I have it installed, or at least it seems so, Emacs has "Rope" menu in it's top menu bar. Now what? So far I could use only "Show documentation" (C-c d by default). An attempt to use code assist (which is auto-complete, I presume?) only causes Emacs to ask about "Rope project root folder" (what's that?) in the minibuffer and then showing nothing. So, once ropemacs is installed, what are the steps to see it in action on some simple python scripts? Something like "if you have this script in your emacs and put the blinking square here and press this, it does that" would be an answer. (I've been thinking if I should ask this or not for some time, because nobody else seems to have the same problem)
You can set the root folder with rope-open-project . Once you've set the root project a .ropeproject dir will be created. Inside it, a config.py file has hooks where you can run (python) code once the project is set. The project_opened(project): function is a good place to run code. I usually activate the virtual environment imp.load_source('/path-to-env/activate_this.py') , so that I can get source coverage for other libs in the virtual env.
0.986614
false
1
566
2010-05-18 13:24:38.767
How can I create a GUI on top of a Python APP so it can do either GUI or CLI?
I am trying to write an app in python to control a motor using serial. This all works in a CLI situation fine and is generally stable. but I was wondering how simple it was to add a GUI on top of this code base? I assume there will be more code, but is there a simple way of detecting something like GTK, so it only applied the code when GTK was present? Also, GUI creation in Python in general: is it best to keep as little GUI specifics out of the code and use something like GTK's XML based approach (using gtk.glade.XML() function)? Are there other GUI toolkits that have a similar approach to the Glade / XML / "Explode in Code" approach? Thanks for any advice. Andy
I don't recommend doing a GUI in XML. All the XML does is give you a mini language for describing a layout. Why use a mini language when you can have the full power of python? As for detecting GTK, I wouldn't suggest that. Instead, add a command line argument to determine whether to create a GUI or not (eg: myprogram -g). It then becomes easy to create a desktop shortcut or command line alias to start in GUI mode, while still being able to use the command line tool from any terminal. You do, however, want to keep the GUI code separate from the bits that do the real work. Give youself a class that contains all the business logic, then have the GUI and CLI both access this object to do work.
0
false
1
567
2010-05-18 14:14:02.787
Django Inlines user permissions + view only - permissions issues
I'm not sure if this is a bug or I'm just missing something (although I have already parsed the documentation about inlines), but: Let's say I have a model A. Model A is an inline of model B. User U has full access to model B, but only change permissions to model A (so, no add, nor delete). However, when editing model B, user U can still see the "Add another A" link at the bottom, although U hasn't add permissions for that respective model. What's wrong? Why does that link keep on showing? My logic says that if U does not have permissions to add A, the link shouldn't appear anymore. Also, ideally, I would like to give U only view rights to model A (so no add, delete or change - only view), but I've read about that (strange, if you ask me) philosophy according to which "If you don't trust U, just deny him access to the admin area all together". Kind of a stupid doctrine. Right now, I'm trying to simulate this 'view only permissions' by leaving U with just change rights and set all fields as read only. But I think this is kind of a stupid approach and may also cause problems like the permissions thing above... How does an average Django programmer like me achieve view-only permissions, and most of all how should I get rid of the "Add another A" link at the bottom of the admin edit form? Thanks in advance!
If I want a read-only version of what's in the admin, I just write some normal Django views and keep them out of the admin. I don't think the kind of thing you're talking about (allowing changes to an object but not its inlines) is really supported by the admin. Don't get me wrong: the admin is very flexible and useful, but it's not intended to do everything for you. The only way I see you being able to have this much control in the admin is to not inline A. "If you don't trust U, just deny him access to the admin area all together". Kind of a stupid doctrine. Not really, when you consider that the admin isn't intended to have the required level of security hardening to guarantee that fine-grain level of access control. There are many, many places in the admin, due to its open and extensible nature, where bugs can lurk (usually in user-written code) that can be exploited by bad actors. This is why untrusted users should always see all admin URLs return 404. Anyway, when access control requirements are that fine-grained, it becomes unlikely that a general (i.e. django.contrib) solution will fit.
1.2
true
1
568
2010-05-18 17:06:52.540
Distributing an executable zip file with __main__.py, how to access extra data?
I'm doing a little program and I want to distribute it using this recipe: single directory with __main__.py in it zip this directory and adding a shebang on it #!/usr/bin/env python making it executable The problem is that in this package I have also extra files (I'm using pygtk toolkit and I need images and ui xml files). When I try to access these files I have the error that the resource is unavailable (the path that I'm trying to open is something like file.zip/gui/gui.ui ). How can I handle this situation?
I figured out by myself, It's sufficient to use pkgutil.get_data to access the data inside a package.
1.2
true
1
569
2010-05-18 23:22:21.140
Queue remote calls to a Python Twisted perspective broker?
The strength of Twisted (for python) is its asynchronous framework (I think). I've written an image processing server that takes requests via Perspective Broker. It works great as long as I feed it less than a couple hundred images at a time. However, sometimes it gets spiked with hundreds of images at virtually the same time. Because it tries to process them all concurrently the server crashes. As a solution I'd like to queue up the remote_calls on the server so that it only processes ~100 images at a time. It seems like this might be something that Twisted already does, but I can't seem to find it. Any ideas on how to start implementing this? A point in the right direction? Thanks!
You might also like the txRDQ (Resizable Dispatch Queue) I wrote. Google it, it's in the tx collection on LaunchPad. Sorry I don't have more time to reply - about to go onstage. Terry
-0.386912
false
1
570
2010-05-20 17:17:10.437
What's the most scalable way to handle somewhat large file uploads in a Python webapp?
We have a web application that takes file uploads for some parts. The file uploads aren't terribly big (mostly word documents and such), but they're much larger than your typical web request and they tend to tie up our threaded servers (zope 2 servers running behind an Apache proxy). I'm mostly in the brainstorming phase right now and trying to figure out a general technique to use. Some ideas I have are: Using a python asynchronous server like tornado or diesel or gunicorn. Writing something in twisted to handle it. Just using nginx to handle the actual file uploads. It's surprisingly difficult to find information on which approach I should be taking. I'm sure there are plenty of details that would be needed to make an actual decision, but I'm more worried about figuring out how to make this decision than anything else. Can anyone give me some advice about how to proceed with this?
See if you can push the files straight from the user's browser to a static file store, like Amazon S3 or rackspace's cloudfiles service. Then you can handle a ton of parallel users.
0
false
1
571
2010-05-23 03:10:52.283
How to generate graphs and statistics from SQLAlchemy tables?
After running a bunch of simulations I'm going to be outputting the results into a table created using SQLAlchemy. I plan to use this data to generate statistics - mean and variance being key. These, in turn, will be used to generate some graphs - histograms/line graphs, pie-charts and box-and-whisker plots specifically. I'm aware of the Python graphing libraries like matplotlib. The thing is, I'm not sure how to have this integrate with the information contained within the database tables. Any suggestions on how to make these two play with each other? The main problem is that I'm not sure how to supply the information as "data sets" to the graphing library.
It looks like matplotlib takes simple python data types -- lists of numbers, etc, so you'll be need to write custom code to massage what you pull out of mysql/sqlalchemy for input into the graphing functions...
1.2
true
1
572
2010-05-23 22:09:10.470
Where to use a pyc file
I want to know what a pyc file(python bytecode) is. I want to know all the details. I want to know about how pyc files interface with the compiler. Is it a replacement for exe? Does it need to be run by python? Is it as portable as the .py file is? Where should I use this?
Python bytecode requires Python to run, cannot be ran standalone without Python, and is specific to a particular x.y release of Python. It should be portable across platforms for the same version. There is not a common reason for you to use it; Python uses it to optimize out parsing of your .py file on repeated imports. Your life will be fine ignoring the existence of pyc files.
0.995055
false
1
573
2010-05-24 01:07:28.420
how do i edit a running python program?
scenario: a modular app that loads .py modules on the fly as it works. programmer (me) wishes to edit the code of a module and then re-load it into the program without halting execution. can this be done? i have tried running import a second time on an updated module.py, but the changes are not picked up
Alex's answer and the others cover the general case. However, since these modules you're working on are your own and you'll edit only them, it's possible to implement some kind of a local reloading mechanism rather than rely on the builtin reload. You can architect your module loader as something that loads up the files, compiles it and evals them into a specific namespace and tells the calling code that it's ready. You can take care of reloading by making sure that there's a decent init function which reinitialises the module properly. I assume you'll be editing only these. It's a bit of work but might be interesting and worth your time.
0
false
1
574
2010-05-24 21:11:10.030
how to set MATLABPATH in Python and using mlabwrap?
I tried to use mlab.path(path,'/my/path') but failed. Got NameError: name 'path' is not defined in python. Anyone has an idea?
Never mind. I found out how. Use mlab.addpath().
1.2
true
1
575
2010-05-25 18:43:59.550
Good real-world uses of metaclasses (e.g. in Python)
I'm learning about metaclasses in Python. I think it is a very powerful technique, and I'm looking for good uses for them. I'd like some feedback of good useful real-world examples of using metaclasses. I'm not looking for example code on how to write a metaclass (there are plenty examples of useless metaclasses out there), but real examples where you have applied the technique and it was really the appropriate solution. The rule is: no theoretical possibilities, but metaclasses at work in a real application. I'll start with the one example I know: Django models, for declarative programming, where the base class Model uses a metaclass to fill the model objects of useful ORM functionality from the attribute definitions. Looking forward to your contributions.
SQLalchemy also uses them for declarative database models. Sorry my answer isn't very different from your example, but if you're looking for example code, I found declarative to be pretty readable.
0
false
1
576
2010-05-26 00:21:50.267
Is it bad practice to use python's getattr extensively?
I'm creating a shell-like environment. My original method of handleing user input was to use a dictionary mapping commands (strings) to methods of various classes, making use of the fact that functions are first class objects in python. For flexibility's sake (mostly for parsing commands), I'm thinking of changing my setup such that I'm using getattr(command), to grab the method I need and then passing arguments to it at the end of my parser. Another advantage of this approach is not having to update my (currently statically implemented) command dictionary every time I add a new method/command. My question is two fold. First, does getattr have the same problems as eval? Second, will I be taking a hit to the efficiency of my shell? Does it matter how many methods/commands I have? I'm currently looking at 30 some commands, which could eventually double.
does getattr have the same problems as eval? No -- code using eval() is terribly annoying to maintain, and can have serious security problems. Calling getattr(x, "foo") is just another way to write x.foo. will I be taking a hit to the efficiency of my shell It will be imperceptibly slower if the command isn't found, but not enough to matter. You'd only notice it if doing benchmarks, with tens of thousands of entries.
0.999909
false
1
577
2010-05-26 10:16:41.307
clicked() signal for QListView in PyQt4
I have a working QListView, but from the documentation, I can't figure out how to get a signal to fire with the index of the newly selected item. Any ideas?
Imho, an easier way to achieve this would be to use a QListWidget instead of a QListView, this way you could use the itemClicked signal, which sends the selected item to the callback function.
0.201295
false
1
578
2010-05-26 19:30:41.847
Distributing a Python library (single file)
For my project I would be using the argparse library. My question is, how do I distribute it with my project. I am asking this because of the technicalities and legalities involved. Do I just: Put the argparse.py file along with my project. That is, in the tar file for my project. Create a package for it for my distro? Tell the user to install it himself?
It would be best for the user to install it so that only one copy is present on the system and so that it can be updated if there are any issues, but including it with your project is a viable option if you abide by all requirements specified in the license. Try to import it from the public location, and if that fails then resort to using the included module.
0.135221
false
1
579
2010-05-27 21:48:08.913
Get "2:35pm" instead of "02:35PM" from Python date/time?
I'm still a bit slow with Python, so I haven't got this figured out beyond what's obviously in the docs, etc. I've worked with Django a bit, where they've added some datetime formatting options via template tags, but in regular python code how can I get the 12-hour hour without a leading zero? Is there a straightforward way to do this? I'm looking at the 2.5 and 2.6 docs for "strftime()" and there doesn't seem to be a formatting option there for this case. Should I be using something else? Feel free to include any other time-formatting tips that aren't obvious from the docs. =)
I know it's pretty cheap, but you could just discard the first character if it's a zero :)
0.050976
false
1
580
2010-05-28 19:46:30.730
Methods of sending web-generated config files to servers and restarting services
We're writing a web-based tool to configure our services provided by multiple servers. This includes interfaces configuration, dhcp configs etc. etc. Having configs in database and views that generate proper output, how to send it/make it available for servers? I'm thinking about sending it through scp and invoking reload command to services through ssh. I'm also thinking about using Func to do all the job, as this is Python tool and will seemingly integrate with python-based (django) config tool. Any other proposals?
It really depends what you're intending to do, as the question is a little vague. The other answers cover the tools available; choosing one over the other comes down to purpose. Are you intending to manage servers, and services on those servers? If so, try Puppet, CFEngine, or some other tool for managing server configurations. Or, more specifically, are you looking for a deployment/buildout tool that talks to servers? So that you can type in something along the lines of "mytool deploy myproject", and have your project propagate to all the servers? In which case, fabric would be the tool to use. Generally a good configuration will consist of both anyway... but for what it's worth, from the sound of it (managing DHCP/network/etc.), Puppet's the way to go.
0
false
1
581
2010-05-29 15:35:55.667
Task Queue stopped working
I was playing with Goole App Engine Task Queue API to learn how to use it. But I couldn't make it trigger locally. My application is working like a charm when I upload to Google servers. But it doesn't trigger locally. All I see from the admin is the list of the tasks. But when their ETA comes, they just pass it. It's like they runs but they fails and waiting for the retries. But I can't see these events on command line. When I try to click "Run" on admin panel, it runs successfuly and I can see these requests from the command line. I'm using App Engine SDK 1.3.4 on Linux with google-app-engine-django. I'm trying to find the problem from 3 hours now and I couldn't find it. It's also very hard to debug GAE applications. Because debug messages do not appear on console screen. Thanks.
The development server won't run tasks automatically, you have to set them off yourself. It's a design feature, so you can see what happens when you run them, instead of them running at any point. Essentially, there's nothing wrong with your application, it's a feature of development server.
1.2
true
1
582
2010-05-29 16:46:00.447
can a python script know that another instance of the same script is running... and then talk to it?
I'd like to prevent multiple instances of the same long-running python command-line script from running at the same time, and I'd like the new instance to be able to send data to the original instance before the new instance commits suicide. How can I do this in a cross-platform way? Specifically, I'd like to enable the following behavior: "foo.py" is launched from the command line, and it will stay running for a long time-- days or weeks until the machine is rebooted or the parent process kills it. every few minutes the same script is launched again, but with different command-line parameters when launched, the script should see if any other instances are running. if other instances are running, then instance #2 should send its command-line parameters to instance #1, and then instance #2 should exit. instance #1, if it receives command-line parameters from another script, should spin up a new thread and (using the command-line parameters sent in the step above) start performing the work that instance #2 was going to perform. So I'm looking for two things: how can a python program know another instance of itself is running, and then how can one python command-line program communicate with another? Making this more complicated, the same script needs to run on both Windows and Linux, so ideally the solution would use only the Python standard library and not any OS-specific calls. Although if I need to have a Windows codepath and an *nix codepath (and a big if statement in my code to choose one or the other), that's OK if a "same code" solution isn't possible. I realize I could probably work out a file-based approach (e.g. instance #1 watches a directory for changes and each instance drops a file into that directory when it wants to do work) but I'm a little concerned about cleaning up those files after a non-graceful machine shutdown. I'd ideally be able to use an in-memory solution. But again I'm flexible, if a persistent-file-based approach is the only way to do it, I'm open to that option. More details: I'm trying to do this because our servers are using a monitoring tool which supports running python scripts to collect monitoring data (e.g. results of a database query or web service call) which the monitoring tool then indexes for later use. Some of these scripts are very expensive to start up but cheap to run after startup (e.g. making a DB connection vs. running a query). So we've chosen to keep them running in an infinite loop until the parent process kills them. This works great, but on larger servers 100 instances of the same script may be running, even if they're only gathering data every 20 minutes each. This wreaks havoc with RAM, DB connection limits, etc. We want to switch from 100 processes with 1 thread to one process with 100 threads, each executing the work that, previously, one script was doing. But changing how the scripts are invoked by the monitoring tool is not possible. We need to keep invocation the same (launch a process with different command-line parameters) but but change the scripts to recognize that another one is active, and have the "new" script send its work instructions (from the command line params) over to the "old" script. BTW, this is not something I want to do on a one-script basis. Instead, I want to package this behavior into a library which many script authors can leverage-- my goal is to enable script authors to write simple, single-threaded scripts which are unaware of multi-instance issues, and to handle the multi-threading and single-instancing under the covers.
Sounds like your best bet is sticking with a pid file but have it not only contain the process Id - have it also include the port number that the prior instance is listening on. So when starting up check for the pid file and if present see if a process with that Id is running - if so send your data to it and quit otherwise overwrite the pid file with the current process's info.
0
false
2
583
2010-05-29 16:46:00.447
can a python script know that another instance of the same script is running... and then talk to it?
I'd like to prevent multiple instances of the same long-running python command-line script from running at the same time, and I'd like the new instance to be able to send data to the original instance before the new instance commits suicide. How can I do this in a cross-platform way? Specifically, I'd like to enable the following behavior: "foo.py" is launched from the command line, and it will stay running for a long time-- days or weeks until the machine is rebooted or the parent process kills it. every few minutes the same script is launched again, but with different command-line parameters when launched, the script should see if any other instances are running. if other instances are running, then instance #2 should send its command-line parameters to instance #1, and then instance #2 should exit. instance #1, if it receives command-line parameters from another script, should spin up a new thread and (using the command-line parameters sent in the step above) start performing the work that instance #2 was going to perform. So I'm looking for two things: how can a python program know another instance of itself is running, and then how can one python command-line program communicate with another? Making this more complicated, the same script needs to run on both Windows and Linux, so ideally the solution would use only the Python standard library and not any OS-specific calls. Although if I need to have a Windows codepath and an *nix codepath (and a big if statement in my code to choose one or the other), that's OK if a "same code" solution isn't possible. I realize I could probably work out a file-based approach (e.g. instance #1 watches a directory for changes and each instance drops a file into that directory when it wants to do work) but I'm a little concerned about cleaning up those files after a non-graceful machine shutdown. I'd ideally be able to use an in-memory solution. But again I'm flexible, if a persistent-file-based approach is the only way to do it, I'm open to that option. More details: I'm trying to do this because our servers are using a monitoring tool which supports running python scripts to collect monitoring data (e.g. results of a database query or web service call) which the monitoring tool then indexes for later use. Some of these scripts are very expensive to start up but cheap to run after startup (e.g. making a DB connection vs. running a query). So we've chosen to keep them running in an infinite loop until the parent process kills them. This works great, but on larger servers 100 instances of the same script may be running, even if they're only gathering data every 20 minutes each. This wreaks havoc with RAM, DB connection limits, etc. We want to switch from 100 processes with 1 thread to one process with 100 threads, each executing the work that, previously, one script was doing. But changing how the scripts are invoked by the monitoring tool is not possible. We need to keep invocation the same (launch a process with different command-line parameters) but but change the scripts to recognize that another one is active, and have the "new" script send its work instructions (from the command line params) over to the "old" script. BTW, this is not something I want to do on a one-script basis. Instead, I want to package this behavior into a library which many script authors can leverage-- my goal is to enable script authors to write simple, single-threaded scripts which are unaware of multi-instance issues, and to handle the multi-threading and single-instancing under the covers.
Perhaps try using sockets for communication?
0.101688
false
2
583
2010-05-30 05:06:28.333
large amount of data in many text files - how to process?
I have large amounts of data (a few terabytes) and accumulating... They are contained in many tab-delimited flat text files (each about 30MB). Most of the task involves reading the data and aggregating (summing/averaging + additional transformations) over observations/rows based on a series of predicate statements, and then saving the output as text, HDF5, or SQLite files, etc. I normally use R for such tasks but I fear this may be a bit large. Some candidate solutions are to write the whole thing in C (or Fortran) import the files (tables) into a relational database directly and then pull off chunks in R or Python (some of the transformations are not amenable for pure SQL solutions) write the whole thing in Python Would (3) be a bad idea? I know you can wrap C routines in Python but in this case since there isn't anything computationally prohibitive (e.g., optimization routines that require many iterative calculations), I think I/O may be as much of a bottleneck as the computation itself. Do you have any recommendations on further considerations or suggestions? Thanks Edit Thanks for your responses. There seems to be conflicting opinions about Hadoop, but in any case I don't have access to a cluster (though I can use several unnetworked machines)...
Yes. You are right! I/O would cost most of your processing time. I don't suggest you to use distributed systems, like hadoop, for this task. Your task could be done in a modest workstation. I am not an Python expert, I think it has support for asynchronous programming. In F#/.Net, the platform has well support for that. I was once doing an image processing job, loading 20K images on disk and transform them into feature vectors only costs several minutes in parallel. all in all, load and process your data in parallel and save the result in memory (if small), in database (if big).
0.050976
false
4
584
2010-05-30 05:06:28.333
large amount of data in many text files - how to process?
I have large amounts of data (a few terabytes) and accumulating... They are contained in many tab-delimited flat text files (each about 30MB). Most of the task involves reading the data and aggregating (summing/averaging + additional transformations) over observations/rows based on a series of predicate statements, and then saving the output as text, HDF5, or SQLite files, etc. I normally use R for such tasks but I fear this may be a bit large. Some candidate solutions are to write the whole thing in C (or Fortran) import the files (tables) into a relational database directly and then pull off chunks in R or Python (some of the transformations are not amenable for pure SQL solutions) write the whole thing in Python Would (3) be a bad idea? I know you can wrap C routines in Python but in this case since there isn't anything computationally prohibitive (e.g., optimization routines that require many iterative calculations), I think I/O may be as much of a bottleneck as the computation itself. Do you have any recommendations on further considerations or suggestions? Thanks Edit Thanks for your responses. There seems to be conflicting opinions about Hadoop, but in any case I don't have access to a cluster (though I can use several unnetworked machines)...
(3) is not necessarily a bad idea -- Python makes it easy to process "CSV" file (and despite the C standing for Comma, tab as a separator is just as easy to handle) and of course gets just about as much bandwidth in I/O ops as any other language. As for other recommendations, numpy, besides fast computation (which you may not need as per your statements) provides very handy, flexible multi-dimensional arrays, which may be quite handy for your tasks; and the standard library module multiprocessing lets you exploit multiple cores for any task that's easy to parallelize (important since just about every machine these days has multi-cores;-).
1.2
true
4
584
2010-05-30 05:06:28.333
large amount of data in many text files - how to process?
I have large amounts of data (a few terabytes) and accumulating... They are contained in many tab-delimited flat text files (each about 30MB). Most of the task involves reading the data and aggregating (summing/averaging + additional transformations) over observations/rows based on a series of predicate statements, and then saving the output as text, HDF5, or SQLite files, etc. I normally use R for such tasks but I fear this may be a bit large. Some candidate solutions are to write the whole thing in C (or Fortran) import the files (tables) into a relational database directly and then pull off chunks in R or Python (some of the transformations are not amenable for pure SQL solutions) write the whole thing in Python Would (3) be a bad idea? I know you can wrap C routines in Python but in this case since there isn't anything computationally prohibitive (e.g., optimization routines that require many iterative calculations), I think I/O may be as much of a bottleneck as the computation itself. Do you have any recommendations on further considerations or suggestions? Thanks Edit Thanks for your responses. There seems to be conflicting opinions about Hadoop, but in any case I don't have access to a cluster (though I can use several unnetworked machines)...
When you say "accumulating" then solution (2) looks most suitable to problem. After initial load up to database you only update database with new files (daily, weekly? depends how often you need this). In cases (1) and (3) you need to process files each time (what was stated earlier as most time/resources-consuming), unless you find a way to stored results and update them with new files. You could use R to process files from csv to, for example, SQLite database.
0.101688
false
4
584
2010-05-30 05:06:28.333
large amount of data in many text files - how to process?
I have large amounts of data (a few terabytes) and accumulating... They are contained in many tab-delimited flat text files (each about 30MB). Most of the task involves reading the data and aggregating (summing/averaging + additional transformations) over observations/rows based on a series of predicate statements, and then saving the output as text, HDF5, or SQLite files, etc. I normally use R for such tasks but I fear this may be a bit large. Some candidate solutions are to write the whole thing in C (or Fortran) import the files (tables) into a relational database directly and then pull off chunks in R or Python (some of the transformations are not amenable for pure SQL solutions) write the whole thing in Python Would (3) be a bad idea? I know you can wrap C routines in Python but in this case since there isn't anything computationally prohibitive (e.g., optimization routines that require many iterative calculations), I think I/O may be as much of a bottleneck as the computation itself. Do you have any recommendations on further considerations or suggestions? Thanks Edit Thanks for your responses. There seems to be conflicting opinions about Hadoop, but in any case I don't have access to a cluster (though I can use several unnetworked machines)...
With terabytes, you will want to parallelize your reads over many disks anyway; so might as well go straight into Hadoop. Use Pig or Hive to query the data; both have extensive support for user-defined transformations, so you should be able to implement what you need to do using custom code.
0.201295
false
4
584
2010-05-31 08:47:26.927
python dictionary with constant value-type
I bumped into a case where I need a big (=huge) python dictionary, which turned to be quite memory-consuming. However, since all of the values are of a single type (long) - as well as the keys, I figured I can use python (or numpy, doesn't really matter) array for the values ; and wrap the needed interface (in: x ; out: d[x]) with an object which actually uses these arrays for the keys and values storage. I can use a index-conversion object (input --> index, of 1..n, where n is the different-values counter), and return array[index]. I can elaborate on some techniques of how to implement such an indexing-methods with reasonable memory requirement, it works and even pretty good. However, I wonder if there is such a data-structure-object already exists (in python, or wrapped to python from C/++), in any package (I checked collections, and some Google searches). Any comment will be welcome, thanks.
You might try using std::map. Boost.Python provides a Python wrapping for std::map out-of-the-box.
0
false
1
585
2010-05-31 17:30:45.823
python intercepting communication
lets say you run third party program on your computer whitch create a process named example.exe how do i determinate if this process is running and how many windows does he open? How do i intercept network communication between this windows and server? my goal is to create an app whitch will be monitoring network trafic between example.exe and its home server in order to analyze data and save to database, and finally simulate user interaction to get more relevant data
You could use wireshark from wireshark.org to sniff the network traffic (or any other packet sniffer).
0
false
1
586
2010-06-01 02:54:27.960
python imaging library draw text new line how to?
i have a word that will be putted on a image but the problem is that the word continues even though the word exceeds the width of the image is there anyway that the word shift's down if the word exceeds the width of the image or on a certain point the word shift's down if it exceeds the given point
PIL won't automatically do this, but you could easily do it yourself using the getsize method in the ImageFont module. That is, if the text is too big, just split it so that it's not, and put the rest on the next line. (You may want to do this recursively in case the text spans multiple lines.)
0.999988
false
1
587
2010-06-02 20:36:22.790
How to transition from PHP to Python Django?
Here's my background: Decent experience with PHP/MySql. Beginner's experience with OOP Why I want to learn Python Django? I gave in, based on many searches on SO and reading over some of the answers, Python is a great, clean, and structured language to learn. And with the framework Django, it's easier to write codes that are shorter than with PHP Questions Can i do everything in Django as in PHP? Is Django a "big" hit in web development as PHP? I know Python is a great general-purpose language but I'm focused on web development and would like to know how Django ranks in terms of web development. With PHP, PHP and Mysql are VERY closely related, is there a close relation between Django and Mysql? In PHP, you can easily switch between HTML, CSS, PHP all in one script. Does Python offer this type of ease between other languages? Or how do I incorporate HTML, CSS, javascript along with Python?
No. You can only do a LOT better. Awesome, popular. Supported by best hosters like Mediatemple. No. You can just change 'mysql' to 'postgresql' or 'sqlite' in your settings.py. NO! Python would never give you the right to mix up everything in one file and make the shittest shit in the world. Templates, static server. Django is a Model-Template-View framework, great for any applications, from small to huge. PHP works fine only with small apps. Yeah, PHP == Personal Home Page, lol. P.S. Also you can minify your CSS and JS. And compile to one single file (one js, one css). All with django-assets. And yeah, there's a lot more reusable Django apps (for registration, twi/facebook/openid auth, oembed, other stuff). Just search Bitbucket and Github for "django". No need to reinvent a bicycle, like you do with PHP.
0.101688
false
2
588
2010-06-02 20:36:22.790
How to transition from PHP to Python Django?
Here's my background: Decent experience with PHP/MySql. Beginner's experience with OOP Why I want to learn Python Django? I gave in, based on many searches on SO and reading over some of the answers, Python is a great, clean, and structured language to learn. And with the framework Django, it's easier to write codes that are shorter than with PHP Questions Can i do everything in Django as in PHP? Is Django a "big" hit in web development as PHP? I know Python is a great general-purpose language but I'm focused on web development and would like to know how Django ranks in terms of web development. With PHP, PHP and Mysql are VERY closely related, is there a close relation between Django and Mysql? In PHP, you can easily switch between HTML, CSS, PHP all in one script. Does Python offer this type of ease between other languages? Or how do I incorporate HTML, CSS, javascript along with Python?
Can i do everything in Django as in PHP? Always Is Django a "big" hit in web development as PHP? Only time will tell. With PHP, PHP and Mysql are VERY closely related, is there a close relation between Django and Mysql? Django supports several RDBMS interfaces. MySQL is popular, so is SQLite and Postgres. In PHP, you can easily switch between HTML, CSS, PHP all in one script. That doesn't really apply at all to Django. Or how do I incorporate HTML, CSS, javascript along with Python? Actually do the Django tutorial. You'll see how the presentation (via HTML created by templates) and the processing (via Python view functions) fit together. It's not like PHP.
1.2
true
2
588
2010-06-03 00:28:13.580
Is PyOpenGL a good place to start learning opengl programming?
I want to start learning OpenGL but I don't really want to have to learn another language to do it. I already am pretty proficient in python and enjoy the language. I just want to know how close it is to the regular api? Will I be able to pretty easily follow tutorials and books without too much trouble? I know C++ gives better performance, but for just learning can I go wrong with PyOpenGL?
PyOpenGL I don't think it is a good choice. In my opinon in C/C++ it is easier to play around around with your OpenGL code - start with simple app, then add shader, then add some geometry functions, make a texture/geometry generator, build scene via CSG, etc. You know - to have fun, play around with code, experiment and learn something in process. I honestly just don't see myself doing this in python. Surely it is possible to do OpenGL programming in Python, but I see no reason to actually do it. Plus several OpenGL functions take memory pointers as arguments, and although there probably a class (or dozen of alternatives) for that case, I don't see a reason to use them when a traditional way of doing things is available in C/C++, especially when I think about amount of wrappers python code uses to pass vector or array of those into OpenGL function. It just looks like making things more complicated without a real reason to do that. Plus there is a noticeable performance drop, especially when you use "RAW" OpenGL. Besides, if you're going to make games, it is very likely that you'll have to use C++ or some other "non-python" language. P.S. I've done enough OpenGL programming, a lot of DirectX programming, but I specialize on C++, and use python only for certain algorithmic tests, tools and scripts.
0
false
2
589
2010-06-03 00:28:13.580
Is PyOpenGL a good place to start learning opengl programming?
I want to start learning OpenGL but I don't really want to have to learn another language to do it. I already am pretty proficient in python and enjoy the language. I just want to know how close it is to the regular api? Will I be able to pretty easily follow tutorials and books without too much trouble? I know C++ gives better performance, but for just learning can I go wrong with PyOpenGL?
With the caveat that I have done very little OpenGL programming myself, I believe that for the purposes of learning, PyOpenGL is a good choice. The main reason is that PyOpenGL, like most other OpenGL wrappers, is just that: a thin wrapper around the OpenGL API. One large benefit of PyOpenGL is that while in C you have to worry about calling the proper glVertex3{dfiX} command, Python allows you to just write glVertex3(x,y,z) without worrying about telling Python what type of argument you passed in. That might not sound like a big deal, but it's often much simpler to use Python's duck-typing instead of being overly concerned with static typing. The OpenGL methods are almost completely all wrapped into Python methods, so while you'll be writing in Python, the algorithms and method calls you'll use are identical to writing OpenGL in any other language. But since you're writing in Python, you'll have many fewer opportunities to make "silly" mistakes with proper pointer usage, memory management, etc. that would just eat up your time if you were to study the API in C or C++, for instance.
1.2
true
2
589
2010-06-03 13:57:43.117
C++ code generation with Python
Can anyone point me to some documentation on how to write scripts in Python (or Perl or any other Linux friendly script language) that generate C++ code from XML or py files from the command line. I'd like to be able to write up some xml files and then run a shell command that reads these files and generates .h files with fully inlined functions, e.g. streaming operators, constructors, etc.
A few years ago I worked on a project to simplify interprocess shared memory management for large scale simulation systems. We used a related approach where the layout of data in shared memory was defined in XML files and a code generator, written in python, read the XML and spit out a set of header files defining structures and associated functions/operators/etc to match the XML description. At the time, I looked at several templating engines and, to my surprise, found it was easier and very straight-forward to just do it "by hand". As you read the XML, just populate a set of data structures that match your code. Header file objects contain classes and classes contain variables (which may be of other class types). Give each object a printSelf() method that iterates over its contents and calls printSelf() for each object it contains. It seems a little daunting at first but once you get started, it's pretty straight-forward. Oh, and one tip that helps with the generated code, add an indentation argument to printSelf() and increase it at each level. It makes the generated code much easier to read.
0.050976
false
1
590
2010-06-03 22:20:11.297
from string of bytes to OpenCV's IplImage in Python?
I am streaming some data down from a webcam. When I get all of the bytes for a full image (in a string called byteString) I want to display the image using OpenCV. Done fast enough, this will "stream" video from the webcam to an OpenCV window. Here's what I've done to set up the window: cvNamedWindow('name of window', CV_WINDOW_AUTOSIZE) And here's what I do when the byte string is complete: img = cvCreateImage(IMG_SIZE,PIXEL_DEPTH,CHANNELS) buf = ctypes.create_string_buffer(byteString) img.imageData = ctypes.cast(buf, ctypes.POINTER(ctypes.c_byte)) cvShowImage('name of window', img) cvWaitKey(0) For some reason this is producing an error: File "C:\Python26\lib\site-packages\ctypes_opencv\highgui_win32.py", line 226, in execute return func(*args, **kwargs) WindowsError: exception: access violation reading 0x015399E8 Does anybody know how to do what I'm trying to do / how to fix this crazy violation error?
I actually solved this problem and forgot to post the solution. Here's how I did it, though it may not be entirely robust: I analyzed the headers coming from the MJPEG of the network camera I was doing this to, then I just read from the stream 1 byte at a time, and, when I detected that the header of the next image was also in the bytestring, I cut the last 42 bytes off (since that's the length of the header). Then I had the bytes of the JPEG, so I simply created a new Cv Image by using the open(...) method and passing it the byte string wrapped in a StringIO class.
0.386912
false
1
591
2010-06-04 15:19:33.893
include udf in python?
i've a small user defined function in python, say fib(n), how do i use that in other programs or modules? def fib(n): should i use import or is there any other feature? Also i'm learning python in eclipse IDE, it wont support print "any string" but i'm forced to use like, print("string") in python manual online, its given its cross platform and same syntax, but why like above?
You use import to include the function in other programs. Just say import mymodule where the code is located in file mymodule.py. Then say mymodule.fib to use the function. To answer your second question: The syntax print "any string" is acceptable in Python 2, but is no longer allowed in Python 3.
1.2
true
1
592
2010-06-04 21:01:38.043
add xml node to xml file with python
I wonder if it is better add an element by opening file, search 'good place' and add string which contains xml code. Or use some library... i have no idea. I know how can i get nodes and properties from xml through for example lxml but what's the simpliest and the best way to add?
The safest way to add nodes to an XML document is to load it into a DOM, add the nodes programmatically and write it out again. There are several Python XML libraries. I have used minidom, but I have no reason to recommend it specifically over the others.
0.201295
false
1
593
2010-06-05 08:31:20.853
Coloring close points
I have a dense set of points in the plane. I want them colored so that points that are close to each other have the same color, and a different color if they're far away. For simplicity assume that there are, say, 5 different colors to choose from. Turns out I've not the slightest idea how to do that .. I'm using Tkinter with Python, by the way
One approach is to go through your points and partition them into sets with a "center". Since you have 5 colours, you'll have 5 sets. You compare the distance of the new point from each of the centers and then put it in the same group as the closest one. Each set corresponds to a different colour so you can just plot it after this partitioning is done.
0
false
2
594
2010-06-05 08:31:20.853
Coloring close points
I have a dense set of points in the plane. I want them colored so that points that are close to each other have the same color, and a different color if they're far away. For simplicity assume that there are, say, 5 different colors to choose from. Turns out I've not the slightest idea how to do that .. I'm using Tkinter with Python, by the way
I'd start with identifying the concentrations of the spots in the plane. Find the centers of those agglomerations and assign them each unique color. Then for other spots you could simply calculate the color using the linear principle. For example, if one center is red and the other is yellow, a point somewhere in the middle would become orange. I'd probably use some exponential function instead of a linear principle. This will keep the point groups more or less of the same color only giving a noticeable color change to far away points, or, to be more exact, to far away and somewhere in between points.
0
false
2
594
2010-06-06 19:53:26.243
Adding percentage in python - xlwt / pyexcelerator
just a quick question, how to add percent sign to numbers without modifying number. I have tried format percent with myStyleFont.num_format_str = '0.00%' but it multiplies with 100 but I need just to append percent. Ty in advance. Regards.
Note carefully: "modifying" and "multiplies with 100" affect the displayed result, they affect neither the value stored in the file nor the value used in formula calculations. The technique of making an operator be treated as a literal is known as "escaping". The escape character in Excel number format strings is the backslash. To do what you want, your format should be r"0.00\%" or "0.00\\%" The above is a property of Excel, not restricted to Python or xlwt etc. You can test this using one of the UIs (Excel, OpenOffice Calc, Gnumeric). Note that unless you have a restricted set of users who will read and understand the documentation that you will write [unlikely * 3], you shouldn't do that; it will be rather confusing -- the normal Excel user on seeing 5.00% assumes that the underlying number is 0.05. To see this, in Excel etc type these into A1, A2, A3: 5% then .05 then =A1=A2 ... you will see TRUE in A3. pyExcelerator is abandonware; why do you mention it??? About myStyleFont.num_format_str = '0.00%' (1) "font" and "num_format_str" are quite independent components of a style aka XF; your variable name "myStyleFont" is confused/confusing. (2) Setting up XFs by poking attributes into objects is old hat in xlwt; use easyxf instead.
1.2
true
2
595
2010-06-06 19:53:26.243
Adding percentage in python - xlwt / pyexcelerator
just a quick question, how to add percent sign to numbers without modifying number. I have tried format percent with myStyleFont.num_format_str = '0.00%' but it multiplies with 100 but I need just to append percent. Ty in advance. Regards.
The 00.0% number format expects percentages, so multiplying by 100 to display it is the correct behavior. To get the results you want, you could either put the data in the cell as a string in whatever format you choose or you could divide by 100.0 before you store the value in the cell.
0.101688
false
2
595
2010-06-07 02:24:39.973
what should i do after openid (or twitter ,facebook) user login my site ,on gae
how to integration local user and openid(or facebook twitter) user , did you know some framework have already done this , updated my mean is : how to deal with 'local user' and 'openid user', and how to mix them in one model . please give me a framework that realize 'local user' and 'openid user'
I understand your question. You wish to be able to maintain a list of users that have signed up with your service, and also want to record users using OpenID to authenticate. In order to solve this I would do either of the following: Create a new user in your users table for each new user logged in under OpenID, and store their OpenID in this table to allow you to join the two. Move your site to OpenID and change all references to your current users to OpenID users. I'd probably go with Option 1 if you already have this app in production. Note: More experienced Open ID users will probably correct me!
0.386912
false
1
596
2010-06-07 09:11:31.053
How to read a single character at a time from a file in Python?
Can anyone tell me how can I do this?
You should try f.read(1), which is definitely correct and the right thing to do.
0.029146
false
1
597
2010-06-09 03:55:24.860
Fetching a random record from the Google App Engine Datastore?
I have a datastore with around 1,000,000 entities in a model. I want to fetch 10 random entities from this. I am not sure how to do this? can someone help?
Assign each entity a random number and store it in the entity. Then query for ten records whose random number is greater than (or less than) some other random number. This isn't totally random, however, since entities with nearby random numbers will tend to show up together. If you want to beat this, do ten queries based around ten random numbers, but this will be less efficient.
1.2
true
1
598
2010-06-09 11:54:40.923
PyGTK: how to make a clipboard monitor?
How can I make a simple clipboard monitor in Python using the PyGTK GUI? I found gtk.clipboard class and but I couldn't find any solution to get the "signals" to trigger the event when the clipboard content has changed. Any ideas?
Without a proper notification API, such as WM_DrawClipboard messages, you would probably have to resort to a polling loop. And then you will cause major conflicts with other apps that are trying to use this shared resource. Do not resort to a polling loop.
1.2
true
1
599
2010-06-09 14:28:39.490
how to speed up the code?
in my program i have a method which requires about 4 files to be open each time it is called,as i require to take some data.all this data from the file i have been storing in list for manupalation. I approximatily need to call this method about 10,000 times.which is making my program very slow? any method for handling this files in a better ways and is storing the whole data in list time consuming what is better alternatives for list? I can give some code,but my previous question was closed as that only confused everyone as it is a part of big program and need to be explained completely to understand,so i am not giving any code,please suggest ways thinking this as a general question... thanks in advance
As a general strategy, it's best to keep this data in an in-memory cache if it's static, and relatively small. Then, the 10k calls will read an in-memory cache rather than a file. Much faster. If you are modifying the data, the alternative might be a database like SQLite, or embedded MS SQL Server (and there are others, too!). It's not clear what kind of data this is. Is it simple config/properties data? Sometimes you can find libraries to handle the loading/manipulation/storage of this data, and it usually has it's own internal in-memory cache, all you need to do is call one or two functions. Without more information about the files (how big are they?) and the data (how is it formatted and structured?), it's hard to say more.
0.240117
false
4
600
2010-06-09 14:28:39.490
how to speed up the code?
in my program i have a method which requires about 4 files to be open each time it is called,as i require to take some data.all this data from the file i have been storing in list for manupalation. I approximatily need to call this method about 10,000 times.which is making my program very slow? any method for handling this files in a better ways and is storing the whole data in list time consuming what is better alternatives for list? I can give some code,but my previous question was closed as that only confused everyone as it is a part of big program and need to be explained completely to understand,so i am not giving any code,please suggest ways thinking this as a general question... thanks in advance
Opening, closing, and reading a file 10,000 times is always going to be slow. Can you open the file once, do 10,000 operations on the list, then close the file once?
0.16183
false
4
600
2010-06-09 14:28:39.490
how to speed up the code?
in my program i have a method which requires about 4 files to be open each time it is called,as i require to take some data.all this data from the file i have been storing in list for manupalation. I approximatily need to call this method about 10,000 times.which is making my program very slow? any method for handling this files in a better ways and is storing the whole data in list time consuming what is better alternatives for list? I can give some code,but my previous question was closed as that only confused everyone as it is a part of big program and need to be explained completely to understand,so i am not giving any code,please suggest ways thinking this as a general question... thanks in advance
Call the open to the file from the calling method of the one you want to run. Pass the data as parameters to the method
0
false
4
600
2010-06-09 14:28:39.490
how to speed up the code?
in my program i have a method which requires about 4 files to be open each time it is called,as i require to take some data.all this data from the file i have been storing in list for manupalation. I approximatily need to call this method about 10,000 times.which is making my program very slow? any method for handling this files in a better ways and is storing the whole data in list time consuming what is better alternatives for list? I can give some code,but my previous question was closed as that only confused everyone as it is a part of big program and need to be explained completely to understand,so i am not giving any code,please suggest ways thinking this as a general question... thanks in advance
If the files are structured, kinda configuration files, it might be good to use ConfigParser library, else if you have other structural format then I think it would be better to store all this data in JSON or XML and perform any necessary operations on your data
0
false
4
600
2010-06-09 16:11:57.480
how to speed up code?
i want to speed my code compilation..I have searched the internet and heard that psyco is a very tool to improve the speed.i have searched but could get a site for download. i have installed any additional libraries or modules till date in my python.. can psyco user,tell where we can download the psyco and its installation and using procedures?? i use windows vista and python 2.6 does this work on this ??
So it seems you don't want to speed up the compile but want to speed up the execution. If that is the case, my mantra is "do less." Save off results and keep them around, don't re-read the same file(s) over and over again. Read a lot of data out of the file at once and work with it. On files specifically, your performance will be pretty miserable if you're reading a little bit of data out of each file and switching between a number of files while doing it. Just read in each file in completion, one at a time, and then work with them.
0.201295
false
1
601
2010-06-10 08:07:48.540
how to make a chat room on gae ,has any audio python-framework to do this?
i want to make a chat room on gae ,(audio chat) has any framework to do this ? thanks
You'll need two things: A browser plugin to get audio. You could build this on top of eg. http://code.google.com/p/libjingle/'>libjingle which has the advantage of being cross-platform and allowing P2P communication, not to mention being able to talk to arbitrary other XMPP endoints. Or you could use Flash to grab the audio and bounce the stream off a server you build (I think trying to do STUN in Flash for P2P would be impossible), but this would be very tricky to do in App Engine because you'd need it to be long-running. A way to get signaling messages between your clients. You'll have to poll until the Channel API is released (soon). This is a big hairy problem, to put it mildly, but it would be awesome if you did it.
0
false
3
602
2010-06-10 08:07:48.540
how to make a chat room on gae ,has any audio python-framework to do this?
i want to make a chat room on gae ,(audio chat) has any framework to do this ? thanks
App Engine doesn't directly support audio chat of any sort, and since it's based around a request-response system with (primarily) HTTP requests, you can't implement it yourself.
1.2
true
3
602
2010-06-10 08:07:48.540
how to make a chat room on gae ,has any audio python-framework to do this?
i want to make a chat room on gae ,(audio chat) has any framework to do this ? thanks
Try Adobe Stratus (it works with p2p connections) and you could use Google App Engine only for exchanging peer ids.
0.101688
false
3
602
2010-06-10 09:21:55.470
Sequence and merge jpeg images using Python?
im doing a project as part of academic programme.Im doing this in linux platform.here i wanted to create a application which retrieve some information from some pdf files .for eg i have pdfs of subject2,subject1,in both the whole pdf is divided in to 4 modules and i want to get the data of module 1 from pdf..for this purpose my tutor told me to use pdftohtml application and convert pdf files to html and jpeg images.now i want to create a Python script which will combine the pages(which have been coverted in to jpeg images) under module 1 and merge it into a single file and then i will convert it back to pdf . how can i do this?.if anyone can provide any such python script which have done any functions similar to this then it will be very helpful. .... thanks in advance
Not exactly knowing what you mean my sequence - ImageMagick, esp. its 'montage' is probably the tool you need. IM has python interface, too, altough I have never used it. EDIT: As after your edit I do not get the point of this any more, I cannot recommend anything, either. :(
0.673066
false
1
603
2010-06-10 13:19:06.677
How can I build a wrapper to wait for listening on a port?
I am looking for a way of programmatically testing a script written with the asyncore Python module. My test consists of launching the script in question -- if a TCP listen socket is opened, the test passes. Otherwise, if the script dies before getting to that point, the test fails. The purpose of this is knowing if a nightly build works (at least up to a point) or not. I was thinking the best way to test would be to launch the script in some kind of sandbox wrapper which waits for a socket request. I don't care about actually listening for anything on that port, just intercepting the request and using that as an indication that my test passed. I think it would be preferable to intercept the open socket request, rather than polling at set intervals (I hate polling!). But I'm a bit out of my depths as far as how exactly to do this. Can I do this with a shell script? Or perhaps I need to override the asyncore module at the Python level? Thanks in advance, - B
Another option is to mock the socket module before importing the asyncore module. Of course, then you have to make sure that the mock works properly first.
0
false
1
604
2010-06-10 15:31:25.473
Fast Esp Custom Stage Development
I am working on Enterprise Search and we are using Fast ESP and for now i have 4 projects but i have no information about stages and python. But i realize that i have learn custom stage development. Because we have a lot of difficulties about document processing. I want to know how can i develop custom stage and especially i wanna know about how i can find Attributefilter stage source code. I am waiting your answers
I had worked with FAST ESP for document processing and we used to modify the python files. you can modify them but you need to restart the document processor each time you modify any file. You need to search for document processing in the admin UI, there you go to the pipelines, and you can create a custom pipeline based on standard pipelines included in FAST ESP. Once you create your pipeline, then you can select the stage (python program) that you want to modify and the UI shows you the path of each script. I highly recommend you to create your custom stages for each pipeline you modify.
0
false
2
605
2010-06-10 15:31:25.473
Fast Esp Custom Stage Development
I am working on Enterprise Search and we are using Fast ESP and for now i have 4 projects but i have no information about stages and python. But i realize that i have learn custom stage development. Because we have a lot of difficulties about document processing. I want to know how can i develop custom stage and especially i wanna know about how i can find Attributefilter stage source code. I am waiting your answers
The FAST documentation (ESP Document Processor Integration Guide) has a pretty good example of how to write a custom document processor. FAST does not provide the source code to any of it's software, but the AttributeFilter stage functionality should be very straightforward.
1.2
true
2
605
2010-06-11 04:53:39.087
how to make a python or perl script portable to both linux and windows?
I was wondering how to make a python script portable to both linux and windows? One problem I see is shebang. How to write the shebang so that the script can be run on both windows and linux? Are there other problems besides shebang that I should know? Is the solution same for perl script? Thanks and regards!
Windows will just ignore the shebang (which is, after all, a comment); in Windows you need to associate the .py extension to the Python executable in the registry, but you can perfectly well leave the shebang on, it will be perfectly innocuous there. There are many bits and pieces which are platform-specific (many only exist on Unix, msvcrt only on Windows) so if you want to be portable you should abstain from those; some are subtly different (such as the detailed precise behavior of subprocess.Popen or mmap) -- it's all pretty advanced stuff and the docs will guide you there. If you're executing (via subprocess or otherwise) external commands you'd better make sure they exist on both platforms, of course, or check what platform you're in and use different external commands in each case. Remember to always use /, not \, as path separator (forward slash works in both platforms, backwards slash is windows-only), and be meticulous as to whether each file you're opening is binary or text. I think that's about it...
1.2
true
2
606
2010-06-11 04:53:39.087
how to make a python or perl script portable to both linux and windows?
I was wondering how to make a python script portable to both linux and windows? One problem I see is shebang. How to write the shebang so that the script can be run on both windows and linux? Are there other problems besides shebang that I should know? Is the solution same for perl script? Thanks and regards!
The shebang line will be interpreted as a comment by Perl or Python. The only thing that assigns it a special meaning is the UNIX/Linux shell; it gets ignored on Windows. The way Windows knows which interpreter to use to run the file is through the file associations in the registry, a different mechanism altogether.
0.201295
false
2
606
2010-06-11 07:35:15.440
send xml file to http using python
how can i send an xml file on my system to an http server using python standard library??
You can achieve that through a standard http post request.
0.201295
false
1
607
2010-06-11 15:44:52.190
How to merge or copy anonymous session data into user data when user logs in?
This is a general question, or perhaps a request for pointers to other open source projects to look at: I'm wondering how people merge an anonymous user's session data into the authenticated user data when a user logs in. For example, someone is browsing around your websites saving various items as favourites. He's not logged in, so they're saved to an anonymous user's data. Then he logs in, and we need to merge all that data into their (possibly existing) user data. Is this done different ways in an ad-hoc fashion for different applications? Or are there some best practices or other projects people can direct me to?
If very much depends on your system ofcourse. But personally I always try to merge the data and immediately store it in the same way as it would be stored as when the user would be logged in. So if you store it in a session for an anonymous user and in the database for any authenticated user. Just merge all data as soon as you login.
0.386912
false
1
608
2010-06-12 11:52:28.960
Newbie : installing and upgrading python module
I have downloaded and install a python library, via setup.py , python2.5 setup.py install ... now the version is changed at the source . a newer library is available. originally , i have clone it via mercurial, and install it. right now , i have updated repository. how do i use the newer version ? overwrite the installation ? by simply doing setup.py install again ?
Yes, just do setup.py install again.
1.2
true
1
609
2010-06-13 07:47:20.700
Raising events and object persistence in Django
I have a tricky Django problem which didn't occur to me when I was developing it. My Django application allows a user to sign up and store his login credentials for a sites. The Django application basically allows the user to search this other site (by scraping content off it) and returns the result to the user. For each query, it does a couple of queries of the other site. This seemed to work fine but sometimes, the other site slaps me with a CAPTCHA. I've written the code to get the CAPTCHA image and I need to return this to the user so he can type it in but I don't know how. My search request (the query, the username and the password) in my Django application gets passed to a view which in turn calls the backend that does the scraping/search. When a CAPTCHA is detected, I'd like to raise a client side event or something on those lines and display the CAPTCHA to the user and wait for the user's input so that I can resume my search. I would somehow need to persist my backend object between calls. I've tried pickling it but it doesn't work because I get the Can't pickle 'lock' object error. I don't know to implement this though. Any help/ideas? Thanks a ton.
Something else to remember: You need to maintain a browser session with the remote site so that site knows which CAPTCHA you're trying to solve. Lots of webclients allow you to store your cookies and I'd suggest you dump them in the Django Session of the user you're doing the screen scraping for. Then load them back up when you submit the CAPTCHA. Here's how I see the full turn of events: User places search request Query remote site If not CAPTCHA, GOTO #10 Save remote cookies in local session Download image captcha (perhaps to session too?) Present CAPTCHA to your user and a form User Submits CAPTCHA You load up cookies from #4 and submit the form as a POST GOTO #3 Process the data off the page, present to user, high-five yourself.
1.2
true
2
610
2010-06-13 07:47:20.700
Raising events and object persistence in Django
I have a tricky Django problem which didn't occur to me when I was developing it. My Django application allows a user to sign up and store his login credentials for a sites. The Django application basically allows the user to search this other site (by scraping content off it) and returns the result to the user. For each query, it does a couple of queries of the other site. This seemed to work fine but sometimes, the other site slaps me with a CAPTCHA. I've written the code to get the CAPTCHA image and I need to return this to the user so he can type it in but I don't know how. My search request (the query, the username and the password) in my Django application gets passed to a view which in turn calls the backend that does the scraping/search. When a CAPTCHA is detected, I'd like to raise a client side event or something on those lines and display the CAPTCHA to the user and wait for the user's input so that I can resume my search. I would somehow need to persist my backend object between calls. I've tried pickling it but it doesn't work because I get the Can't pickle 'lock' object error. I don't know to implement this though. Any help/ideas? Thanks a ton.
request.session['name'] = variable will store it then, variable = request.session['name'] will retrieve it. Remember though, its not a database, just a simple session store and shouldn't be relied on for anything critical
0
false
2
610
2010-06-13 13:29:14.863
Detecting and interacting with long running process
I want a script to start and interact with a long running process. The process is started first time the script is executed, after that the script can be executed repeatedly, but will detect that the process is already running. The script should be able to interact with the process. I would like this to work on Unix and Windows. I am unsure how I do this. Specifically how do I detect if the process is already running and open a pipe to it? Should I use sockets (e.g. registering the server process on a known port and then check if it responds) or should I use "named pipes"? Or is there some easier way?
Sockets are easier to make portable between Windows and any other OS, so that's what I would recommend it over named pipes (that's why e.g. IDLE uses sockets rather than named pipes -- the latter require platform-dependent code on Windows, e.g. via ctypes [[or third-party win32all or cython &c]], while sockets just work).
1.2
true
2
611
2010-06-13 13:29:14.863
Detecting and interacting with long running process
I want a script to start and interact with a long running process. The process is started first time the script is executed, after that the script can be executed repeatedly, but will detect that the process is already running. The script should be able to interact with the process. I would like this to work on Unix and Windows. I am unsure how I do this. Specifically how do I detect if the process is already running and open a pipe to it? Should I use sockets (e.g. registering the server process on a known port and then check if it responds) or should I use "named pipes"? Or is there some easier way?
Well here is an idea... place a status somewhere else, that can be polled/queried. when the process starts, post the 'running' status. have the script check here to see if the process is running. I would also use a seperate place to post control values. e.g. set a value to the 'control set' and have the process look for those values whenever it gets to decision points in its runtime behavior.
0
false
2
611
2010-06-13 23:32:37.893
Removing python and then re-installing on Mac OSX
I was wondering if anyone had tips on how to completely remove a python installation form Mac OSX (10.5.8) ... including virtual environments and its related binaries. Over the past few years I've completely messed up the installed site-packages, virtual-environments, etc. and the only way I can see to fix it is to just uninstall everything and re-install. I'd like to completely re-do everything and use virtualenv, pip, etc. from the beginning. On the other hand if anyone knows a way to do this without removing python and re-installing I'd be happy to here about it. Thanks, Will
You should be able to delete the packages you've installed from /Library/Python/2.*/site-packages/. I do not think any package installers will install by default to /System/Library, which should save you from needing to remove Python itself. That said, you could also use virtualenv with --no-site-packages, and just ignore whatever packages you've installed system-wide without needing to remove them.
0
false
1
612
2010-06-14 05:41:43.637
how do i install zope interface with python 2.6?
During setup, I'm like missing vcvarsall.bat running build running build_py running build_ext building '_zope_interface_coptimizations' extension error: Unable to find vcvarsall.bat
vcvarsall.bat is a batch file that comes with MSVC. Make sure that it is in your %PATH%.
1.2
true
1
613
2010-06-14 11:05:46.023
Django admin, filter objects by ManyToMany reference
There's photologue application, simple photo gallery for django, implementing Photo and Gallery objects. Gallery object has ManyToMany field, which references Photo objects. I need to be able to get list of all Photos for a given Gallery. Is it possible to add Gallery filter to Photo's admin page? If it's possible, how to do it best?
Well, that's how I've done it. I made custom admin template "change_list.html". Custom template tag creates a list of all existing galleries. Filtering is made like this: class PhotoAdmin(admin.ModelAdmin): ... def queryset(self, request): if request.COOKIES.has_key("gallery"): gallery = Gallery.objects.filter(title_slug=request.COOKIES["gallery"]) if len(gallery)>0: return gallery[0].photos.all() return super(PhotoAdmin, self).queryset(request) Cookie is set with javascript.
0
false
1
614
2010-06-14 12:44:51.260
Get number of results from Django's raw() query function
I'm using a raw query and i'm having trouble finding out how to get the number of results it returns. Is there a way? edit .count() doesnt work. it returns: 'RawQuerySet' object has no attribute 'count'
Count Works on RawQuerySet ModelName.objects.raw("select 1 as id , COUNT(*) from modelnames_modelname")
0.265586
false
1
615
2010-06-15 03:15:11.550
How to determine what user and group a Python script is running as?
I have a CGI script that is getting an "IOError: [Errno 13] Permission denied" error in the stack trace in the web server's error log. As part of debugging this problem, I'd like to add a little bit of code to the script to print the user and (especially) group that the script is running as, into the error log (presumably STDERR). I know I can just print the values to sys.stderr, but how do I figure out what user and group the script is running as? (I'm particularly interested in the group, so the $USER environment variable won't help; the CGI script has the setgid bit set so it should be running as group "list" instead of the web server's "www-data" - but I need code to see if that's actually happening.)
os.getgid() and os.getuid() can be useful. For other environment variables, look into os.getenv. For example, os.getenv('USER') on my Mac OS X returns the username. os.getenv('USERNAME') would return the username on Windows machines.
0.135221
false
1
616
2010-06-15 13:49:18.710
How does Qt work (exactly)?
When you write an application using Qt, can it just be run right away in different operating systems? And (correct me if I'm wrong) you don't need to have Qt already installed in all of the different platforms where you want to execute your application? How exactly does this work? Does Qt compile to the desired platform, or does it bundle some "dlls" (libs), or how does it do it? Is it different from programming a Java application, that runs cross-platform. If you use Python to write a Qt application with Python bindings, does your end user need to have Python installed?
Qt (ideally) provides source compatibility, not binary compatibility. You still have to compile the application separately for each platform, and use the appropriate dynamic Qt libraries (which also need to be compiled separately, and have some platform-specific code). For your final question, the user would need Python, the Qt libraries, and the binding library (e.g. pyqt), but there are various ways to bundle these.
0.999909
false
1
617
2010-06-15 14:19:33.083
Django: how to create sites dynamically?
I need to create an application for the company where I can create sites dynamically. For example, I need an admin interface (Django's admin is enough) where I can setup a new site and add some settings to it. Each site must hold a domain (domains can be manually added to apache conf, but if Django can handle it too would be awesome). Each site must be independent of the others, I mean, I shouldn't be able to see the data content of other sites but I can share same applications/models. I've seen the Django's Sites framework, but I'm not sure if it's possible to implement that way. Should I use Sites framework or create a new app that can handle sites better? What do you think?
The django site framework will do that, but it can't server the site according to the domain name. You'll have to do that using you server such as Apache, Nginx, etc.
0
false
1
618
2010-06-15 14:37:21.637
I suspect I have multiple version of Python 2.6 installed on Mac OS X 10.6.3; how do I set which one Terminal should launch?
When I enter in python in Terminal it loads up Python 2.6.2. However there are folders by the name of Python 2.6 in different places on my drive. I'm not sure if that's because Python 2.6 has been installed in different places or because Python just likes to have lots of folers in different places. If there are multiple installations, I could really do with being able to set which one should be used.
When you run python in a shell or command prompt it will execute the first executable file which is found in your PATH environment variable. To find out what file is being executed use which python or where python.
0.496174
false
1
619
2010-06-16 03:07:22.907
redirection follow by post
just wonder how those air ticket booking website redirect the user to the airline booking website and then fill up(i suppose doing POST) the required information so that the users will land on the booking page with origin/destination/date selected? Is the technique used is to open up new browser window and do a ajax POST from there? Thanks.
It can work like this: on air ticket booking system you have a html form pointing on certain airline booking website (by action parameter). If user submits data then data lands on airline booking website and this website proceed the request. Usuallly people want to get back to the first site. This can be done by sending return url with request data. Of course there must be an API on the airline booking site to handle such url. This is common mechanism when you do online payments, all kind of reservations, etc. Not sure about your idea to use ajax calls. Simple html form is enough here. Note that also making ajax calls between different domains can be recognized as attempt to access the restricted url.
1.2
true
1
620
2010-06-16 03:18:12.867
On Ubuntu, how do you install a newer version of python and keep the older python version?
Background: I am using Ubuntu The newer python version is not in the apt-get repository (or synaptic) I plan on keeping the old version as the default python when you call "python" from the command line I plan on calling the new python using pythonX.X (X.X is the new version). Given the background, how do you install a newer version of python and keep the older python version? I have downloaded from python.org the "install from source" *.tgz package. The readme is pretty simple and says "execute three commands: ./configure; make; make test; sudo make install;" If I do the above commands, will the installation overwrite the old version of python I have (I definitely need the old version)?
When you install from source, by default, the installation goes in /usr/local -- the executable in particular becomes /usr/local/bin/pythonX.Y with a symlink to it that's named /usr/local/python. Ubuntu's own installation is in /usr/ (e.g., /usr/bin/python), so the new installation won't overwrite it. Take care that the PATH environment variable doesn't have /usr/local/bin before /usr/bin, or else simple mentions of python would execute the new one, not the old one.
1.2
true
1
621
2010-06-16 14:01:27.360
Django : In a view how do I obtain the sessionid which will be part of the Set-Cookie header of following response?
In case of views that contain login or logout, this sessionid is different from the one submitted in request's Coockie header. I need to retrieve it before returning response for some purpose. How can I do this ?
I think you should be able to access this via request.session.session_key
1.2
true
1
622
2010-06-16 23:04:40.720
Python CLI tool - general parsing question
If possible I would like to use the following structure for a command however I can't seem to figure out how to achieve this in Python: ./somescript.py arg <optional argument> -- "some long argument" Would it be possible to achieve this in a feasible manner without too much dirty code? Or should I just reconsider the syntax (which is primarily preference). Thanks!
You just need to stick something like this on the first line: #/usr/local/bin/python Just make yours be wherever your python binary is located. As for args look at getopt or optparser And remember to chmod your file to make it executable.
0
false
1
623
2010-06-18 00:05:39.683
Reboot windows machines at a certain time of day and automatically login with Python
I know how to reboot machines remotely, so that's the easy part. However, the complexity of the issue is trying to setup the following. I'd like to control machines on a network for after-hours use such that when users logoff and go home, or shutdown their computers, whatever, python or some combination of python + windows could restart their machines (for cleanliness) and automatically login, running a process for the night, then in the morning, stop said process and restart the machine so the user could easily login like normal. I've looked around, haven't had too terribly much luck, though it looks like one could do it with a changing of the registry. That sounds like a rough idea though, modifying the registry on a per-day basis. Is there an easier way?
Thanks for the responses. To be more clear on what I'm doing, I have a program that automatically starts on bootup, so getting logged in would be preferred. I'm coding a manager for a render-farm for work which will take all the machines that our guys use during the day and turn them into render servers at night (or whenever they log off for a period of time, for example). I'm not sure if I necessarily require a GUI app, but the computer would need to boot and login to launch a server application that does the rendering, and I'm not certain if that can be done without logging in. What i'm needing to run is Autodesk's Backburner Server.exe Maybe that can be run without needing to be logged in specifically, but I'm unfamiliar with doing things of that nature.
0
false
2
624
2010-06-18 00:05:39.683
Reboot windows machines at a certain time of day and automatically login with Python
I know how to reboot machines remotely, so that's the easy part. However, the complexity of the issue is trying to setup the following. I'd like to control machines on a network for after-hours use such that when users logoff and go home, or shutdown their computers, whatever, python or some combination of python + windows could restart their machines (for cleanliness) and automatically login, running a process for the night, then in the morning, stop said process and restart the machine so the user could easily login like normal. I've looked around, haven't had too terribly much luck, though it looks like one could do it with a changing of the registry. That sounds like a rough idea though, modifying the registry on a per-day basis. Is there an easier way?
I can't think of any way to do strictly what you want off the top of my head other than the registry, at least not without even more drastic measures. But doing this registry modification isn't a big deal; just change the autologon username/password and reboot the computer. To have the computer reboot when the user logs off, give them a "logoff" option that actually reboots rather than logging off; I've seen other places do that. (edit)FYI: for registry edits, Windows has a REG command that will be useful if you decide to go with that route.(/edit) Also, what kind of process are you trying to run? If it's not a GUI app that needs your interaction, you don't have to go through any great pains; just run the app remotely. At my work, we use psexec to do it very simply, and I've also created C++ programs that run code remotely. It's not that difficult, the way I do it is to have C++ call the WinAPI function to remotely register a service on the remote PC and start it, the service then does whatever I want (itself, or as a staging point to launch other things), then unregisters itself. I have only used Python for simple webpage stuff, so I'm not sure what kind of support it has for accessing the DLLs required, but if it can do that, you can still use Python here. Or even better yet, if you don't need to do this remotely but just want it done every night, you can just use the Windows scheduler to run whatever application you want run during the night. You can even do this programmatically as there are a couple Windows commands for that: one is the "at" command, and I don't recall right now what the other is but just a little Googling should find it for you.
1.2
true
2
624
2010-06-18 20:43:39.873
ZeroConf Chat with Python
I am trying to set up a Bonjour (or Ahavi) chatbot for our helpdesk system that would answer basic questions based on a menu system. The basis of my question is how do I get python to create the bot so that it connects to the network as a chat client. Basically, anyone on my network with iChat or Empathy (or any chat program able to view users over the local network) should see the bot just as they see another user. The actual bot part would be quite simple to program, but I have no idea how to get it on the network. I have looked into ZeroConf, but I'm not exactly sure how it works, or how to get a chat service running with python. I have seen references to pybonjour, python bindings for avahi, and pyzeroconf, but again, I have no idea how to set them up. If anyone could give an example, or reference, or even a good article to read on the subject, it would be much appreciated. Thanks! Kory
The easiest thing to do is to use Telepathy Salut or Pidgin/libpurple, and talk with it over D-Bus.
0
false
1
625
2010-06-19 02:38:53.503
From the web to games
I'm a basic web developer. I know PHP, a little bit of Python and Ruby. JavaScript as well [some stuff]. I'm not a hardcore developer. I know what it takes do develop most of web cases. Now, I have this desire to go deeper and start developing games. I know it sounds a huge leap, but that is why I'm asking here. I already have some games ideas. It would be simple 2d plataform games, and I would like to know what is the best way to start. I don't want to start with Flash. I'm looking for working with other stuff. I already started to look around for the Unity 3D framework and UDK, but I just don't know how to get started. So, any hints, tips or sugestions to make?
If you want to learn more Python while doing so, you may want to take PyGame or an equivalent program. PHP, Ruby and JavaScript aren't going to help you in the video game section, though. They're all related to the internet. If you want to start of real easy, try out Genesis3D. you can make awesome 3D FPS games, and its quite easy to get the hang of too. Took me only 5 days :D Unity made me sick to my stomach, and so did Blender3D's game engine, so I personally say not to use those. It intimidated me.
0
false
4
626
2010-06-19 02:38:53.503
From the web to games
I'm a basic web developer. I know PHP, a little bit of Python and Ruby. JavaScript as well [some stuff]. I'm not a hardcore developer. I know what it takes do develop most of web cases. Now, I have this desire to go deeper and start developing games. I know it sounds a huge leap, but that is why I'm asking here. I already have some games ideas. It would be simple 2d plataform games, and I would like to know what is the best way to start. I don't want to start with Flash. I'm looking for working with other stuff. I already started to look around for the Unity 3D framework and UDK, but I just don't know how to get started. So, any hints, tips or sugestions to make?
Python's Pygame is certainly a good choice as others have said. If you want to get in to deep video game programming though.. move on to something like C++ or another lower level language.. from experience, most higher level languages tend to put artificial hurdles up in regards to decent video games. Though for a simple 2d game you cant go wrong with python. another decent environment to use is Ogre3d, but you would need C++ or the PyOgre bindings (which are not up to date, but I hear they do work okay). Going from web to game design really is a decent step, as long as you have a good sense of design. the physics and game logic can be learned, but ive yet to see anyone who could properly learn how to write a decent GUI.. as is seen in most cases these days, the final GUI lay out tends to be a process of elimination or beta with trial and error. Only suggestion i have left is keep your game logic as far away as possible from your graphics. Be Modular. -edit- oh and a note.. stay away from Tkinter in python for anything more than a simple tool.. I have found it most frustrating to use. there is wxPython, GTK, pygame, and PyQT.. and all of them (in my opinion) are far better graphic frameworks.
0.201295
false
4
626
2010-06-19 02:38:53.503
From the web to games
I'm a basic web developer. I know PHP, a little bit of Python and Ruby. JavaScript as well [some stuff]. I'm not a hardcore developer. I know what it takes do develop most of web cases. Now, I have this desire to go deeper and start developing games. I know it sounds a huge leap, but that is why I'm asking here. I already have some games ideas. It would be simple 2d plataform games, and I would like to know what is the best way to start. I don't want to start with Flash. I'm looking for working with other stuff. I already started to look around for the Unity 3D framework and UDK, but I just don't know how to get started. So, any hints, tips or sugestions to make?
Looking at your tags, web games are mostly client side, and since you aren't going to use flash, i would say JavaScript would work for 2D. With all the libraries and plug-ins out there, JavaScript can actually handle it.
0
false
4
626
2010-06-19 02:38:53.503
From the web to games
I'm a basic web developer. I know PHP, a little bit of Python and Ruby. JavaScript as well [some stuff]. I'm not a hardcore developer. I know what it takes do develop most of web cases. Now, I have this desire to go deeper and start developing games. I know it sounds a huge leap, but that is why I'm asking here. I already have some games ideas. It would be simple 2d plataform games, and I would like to know what is the best way to start. I don't want to start with Flash. I'm looking for working with other stuff. I already started to look around for the Unity 3D framework and UDK, but I just don't know how to get started. So, any hints, tips or sugestions to make?
Taking a look at OpenGL may not be a terrible idea. You can use the library in many languages, and is supported with in HTML5 (WebGL). There are several excellent tutorials out there.
0
false
4
626
2010-06-19 20:38:22.590
Does GQL automatically add an "ID" Property
I currently work with Google's AppEngine and I could not find out, whether a Google DataStorage Object Entry has an ID by default, and if not, how I add such a field and let it increase automatically? regards,
Yes, they have id's by default, and it is named ID as you mentioned.
1.2
true
2
627
2010-06-19 20:38:22.590
Does GQL automatically add an "ID" Property
I currently work with Google's AppEngine and I could not find out, whether a Google DataStorage Object Entry has an ID by default, and if not, how I add such a field and let it increase automatically? regards,
An object has a Key, part of which is either an automatically-generated numeric ID, or an assigned key name. IDs are not guaranteed to be increasing, and they're almost never going to be consecutive because they're allocated to an instance in big chunks, and IDs unused by the instance to which they're allocated will never be used by another instance (at least, not currently). They're also only unique within the same entity group for a kind; they're not unique to the entire kind if you have parent relationships.
0.496174
false
2
627
2010-06-20 13:24:12.277
Ruby HAML with Django?
Ok, so I really love HAML. Particularly, I love the integration with RedCloth and BlueCloth, so I can use Markdown and Textile intermixed with my HAML. I also love Python and Django. So, I would like to use HAML with Django. Now, I already understand that there are some attempts at cloning HAML-like syntax in Python (SHPAML and others). I've tried these, and while they aren't bad, I've found that I really just want the real HAML. Partially for its syntax, but also for things like RedCloth and BlueCloth. So, my question is, how to make HAML and Django work together? One solution, I think, would be to create HAML templates, and then compile them into HTML using the command line tool every time they're updated. Quesiton 1: Will I run into any problems here? I also wonder if there's a way to get Python and Ruby to play together a little more. One idea I had was actually forking out Ruby processes. This is probably a bad idea, but anyone have any thoughts about this? Question 2: What about using Python to call the real Ruby HAML? Finally, if anyone knows of a Python implementation of HAML that is complete, and that supports either Textile or Markdown, as well as plaintext passthru, then let me know. Question 3: Is there a full translation of HAML to Python including Markdown or Textile support? Thanks!
While this could end up being more trouble than it is worth, it is PROBABLY possible to leverage the Java or .NET platform and still run your Django application in Jython or IronPython (with some minor adjustments I'm sure) and also be able to leverage Ruby's HAML gem via jRuby or IronRuby. I'm sure there will be some quirks in getting this to work, but I'm sure it would be possible. Again, this is probably a lot more trouble than it's worth (considering that you'd have to move your application to a completely new platform), but it would be a pretty fun project to work on.
0
false
2
628
2010-06-20 13:24:12.277
Ruby HAML with Django?
Ok, so I really love HAML. Particularly, I love the integration with RedCloth and BlueCloth, so I can use Markdown and Textile intermixed with my HAML. I also love Python and Django. So, I would like to use HAML with Django. Now, I already understand that there are some attempts at cloning HAML-like syntax in Python (SHPAML and others). I've tried these, and while they aren't bad, I've found that I really just want the real HAML. Partially for its syntax, but also for things like RedCloth and BlueCloth. So, my question is, how to make HAML and Django work together? One solution, I think, would be to create HAML templates, and then compile them into HTML using the command line tool every time they're updated. Quesiton 1: Will I run into any problems here? I also wonder if there's a way to get Python and Ruby to play together a little more. One idea I had was actually forking out Ruby processes. This is probably a bad idea, but anyone have any thoughts about this? Question 2: What about using Python to call the real Ruby HAML? Finally, if anyone knows of a Python implementation of HAML that is complete, and that supports either Textile or Markdown, as well as plaintext passthru, then let me know. Question 3: Is there a full translation of HAML to Python including Markdown or Textile support? Thanks!
I strongly recommend that you do not fork any processes out of your django views, because the overhead is significant. You should have a persistent ruby process to serve your templates for you, and invoke it from your django code. I leave the IPC technology to you, but the obvious choices would either be some kind of message queuing technology, or speaking HTTP over a socket to the ruby process.
0.101688
false
2
628
2010-06-21 02:05:11.337
can someone help me with tags in canvas?
i tried to figure out what tags were in canvas however i am having a hard time understanding it. can someone explain what tags do and how to use them in canvas when using python.
Every object in a canvas has an id. You can reference that object by that id to delete it, modify it, move it, etc. Objects can also have one or more tags. A tag can be associated with a single object, in which case it is just another name for that object. For example, if you draw a red rectangle and a blue rectangle, you can give the first one the tag "red_rect" and the second "blue_rect". Then, anywhere you might need the id you could instead use the tag. One tag can be associated with more than a single item. So, for example, in addition to the "red_rect" and "blue_rect" tags, you could also give each item a "rect" tag. Then, when you use "rect" where you might use an id (such as to move the object), this will affect all objects with the tag. In this way you can move, configure or delete whole groups of items at a time. You can use tags to implement such common features as letting the user name objects that they draw interactively, or to logically group multiple objects into a single composite object.
0
false
1
629
2010-06-21 08:47:03.660
How C# use python program?
If it doesn't use ironpython, how C# use cpython program(py file)? Because there are some bugs that ironpython load cpython code.
If you need strict CPython behavior and do not want to change Python program I am afraid that in this case you should spawn separate CPython process and interact with it via some RPC protocol (there are plenty to choose from) via pipe or network connection to localhost. As alternative to "serialized" RPC you might use system's facilities e.g. COM if you're on Windows or D-Bus on Linux - but this would make code platform dependent and not necessarily simpler.
1.2
true
1
630
2010-06-21 10:17:18.530
How do I get tags/keywords from a webpage/feed?
I have to build a tag cloud out of a webpage/feed. Once you get the word frequency table of tags, it's easy to build the tagcloud. But my doubt is how do I retrieve the tags/keywords from the webpage/feed? This is what I'm doing now: Get the content -> strip HTML -> split them with \s\n\t(space,newline,tab) -> Keyword list But this does not work great. Is there a better way?
What you have is a rough 1st order approximation. I think if you then go back through the data and search for frequency of 2-word phrases, then 3 word phrases, up till the total number of words that can be considered a tag, you'll get a better representation of keyword frequency. You can refine this rough search pattern by specifying certain words that can be contained as part of a phrase (pronouns ect).
0
false
1
631
2010-06-22 15:29:38.457
how to load a big file and cut it into smaller files?
I have file about 4MB (which i called as big one)...this file has about 160000 lines..in a specific format...and i need to cut them at regular interval(not at equal intervals) i.e at the end of a certain format and write the part into another file.. Basically,what i wanted is to copy the information for the big file into the many smaller files ...as i read the big file keep writing the information into one file and after the a certain pattern occurs then end this and starting writing for that line into another file... Normally, if it is a small file i guess it can be done dont know if i can perform file.readline() to read each line check if pattern end if not then write it to a file if patter end then change the file name open new file..so on but how to do it for this big file.. thanks in advance.. didnt mention the file format as i felt it is not neccesary will mention if required..
A 4MB file is very small, it fits in memory for sure. The fastest approach would be to read it all and then iterate over each line searching for the pattern, writing out the line to the appropriate file depending on the pattern (your approach for small files.)
0.135221
false
1
632
2010-06-22 20:38:16.823
How to calculate the time interval between two time strings
I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS). I need the difference between the two times. I've been looking through documentation for Python and searching online and I would imagine it would have something to do with the datetime and/or time modules. I can't get it to work properly and keep finding only how to do this when a date is involved. Ultimately, I need to calculate the averages of multiple time durations. I got the time differences to work and I'm storing them in a list. I now need to calculate the average. I'm using regular expressions to parse out the original times and then doing the differences. For the averaging, should I convert to seconds and then average?
you could try this: from datetime import datetime start = datetime.now() print(start) #some code here end = datetime.now() print(end) print(end - start)
0
false
2
633
2010-06-22 20:38:16.823
How to calculate the time interval between two time strings
I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS). I need the difference between the two times. I've been looking through documentation for Python and searching online and I would imagine it would have something to do with the datetime and/or time modules. I can't get it to work properly and keep finding only how to do this when a date is involved. Ultimately, I need to calculate the averages of multiple time durations. I got the time differences to work and I'm storing them in a list. I now need to calculate the average. I'm using regular expressions to parse out the original times and then doing the differences. For the averaging, should I convert to seconds and then average?
Take a look at the datetime module and the timedelta objects. You should end up constructing a datetime object for the start and stop times, and when you subtract them, you get a timedelta.
0.050976
false
2
633
2010-06-23 05:58:52.023
Changing the selected item colour in a GtkTreeview using python
I have a dialog which contains a pygtk.treeview for listing tasks by priority. Each row has the background colour set based on that priority, so for example the highest priority has a light red background. The row selection color is not so easy to change. I can set it using treeview.modify_base(gtk.STATE_SELECTED, "#C4C4C4"), but no colours work well with the colours used to enhance the concept of priority. I had the idea to change the selection colour to be a slightly darker version of the colour used as the normal row background, so in the example above, that would be a darker red. I tried calling the function above in response to the treeselection's changed signal, and it works, but with heavy flickering. Another idea was to change the selection to transparent and put a border around it instead, but as far as I can tell, this isn't possible. How can I change the selection colour in the way described above without the flickering? Can I change show the selection by having only a border around the row? Note: I'm aware that this violates the theme selected by the user. I feel I have a good reason for it. Having the priority indicated by colour makes it instantly recognisable. The selection colour hides this. If you have alternative suggestions, I am open to them, but it needs to retain the ease at which a user can identify the priority.
Not sure what you mean by flickering. A border would require subclassing TreeView. I'd make the STATE_SELECTED color identical to STATE_NORMAL to disable the built-in highlighting. Then set a data_func on each column and change some color on the cell renderer depending on whether it's in the selection or not. You're probably already doing this for your priority, so just multiply the color with something to highlight a row.
0
false
2
634
2010-06-23 05:58:52.023
Changing the selected item colour in a GtkTreeview using python
I have a dialog which contains a pygtk.treeview for listing tasks by priority. Each row has the background colour set based on that priority, so for example the highest priority has a light red background. The row selection color is not so easy to change. I can set it using treeview.modify_base(gtk.STATE_SELECTED, "#C4C4C4"), but no colours work well with the colours used to enhance the concept of priority. I had the idea to change the selection colour to be a slightly darker version of the colour used as the normal row background, so in the example above, that would be a darker red. I tried calling the function above in response to the treeselection's changed signal, and it works, but with heavy flickering. Another idea was to change the selection to transparent and put a border around it instead, but as far as I can tell, this isn't possible. How can I change the selection colour in the way described above without the flickering? Can I change show the selection by having only a border around the row? Note: I'm aware that this violates the theme selected by the user. I feel I have a good reason for it. Having the priority indicated by colour makes it instantly recognisable. The selection colour hides this. If you have alternative suggestions, I am open to them, but it needs to retain the ease at which a user can identify the priority.
Calling both ModifyBase and ModifyText worked for me. Calling just ModifyBase changes the text color to White Example in GTK C#: treeViewList.ModifyBase(StateType.Selected, treeViewList.Style.Base(StateType.Normal)); treeViewList.ModifyText(StateType.Selected, treeViewList.Style.Text(StateType.Normal));
0
false
2
634
2010-06-24 01:43:41.017
Any productive way to install a bunch of packages
I had one machine with my commonly used python package installed. and i would like to install the same package on another machine or same machine with different python version. I would like to know whether pip or easy-install or some other method can let me install those packages in a batch. When i use perl, it has something like a bundle package, how to do that in python?
Pip has some great features for this. It lets you save all requirements from an environment in a file using pip freeze > reqs.txt You can then later do : pip install -r reqs.txt and you'll get the same exact environnement. You can also bundle several libraries into a .pybundle file with the command pip bundle MyApp.pybundle -r reqs.txt, and later install it with pip install MyApp.pybundle. I guess that's what you're looking for :)
0.999753
false
2
635
2010-06-24 01:43:41.017
Any productive way to install a bunch of packages
I had one machine with my commonly used python package installed. and i would like to install the same package on another machine or same machine with different python version. I would like to know whether pip or easy-install or some other method can let me install those packages in a batch. When i use perl, it has something like a bundle package, how to do that in python?
I keep a requirements.txt file in one of my repositories that has all my basic python requirements and use PIP to install them on any new machine. Each of my projects also has it's own requirements.txt file that contains all of it's dependencies for use w/virtualenv.
0
false
2
635
2010-06-24 08:25:55.350
In Python script, how do I set PYTHONPATH?
I know how to set it in my /etc/profile and in my environment variables. But what if I want to set it during a script? Is it import os, sys? How do I do it?
you can set PYTHONPATH, by os.environ['PATHPYTHON']=/some/path, then you need to call os.system('python') to restart the python shell to make the newly added path effective.
-0.265586
false
1
636