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
|
---|---|---|---|---|---|---|---|
2008-11-04 22:47:39.493 | How can I ask for root password but perform the action at a later time? | I have a python script that I would like to add a "Shutdown when done" feature to.
I know I can use gksudo (when the user clicks on "shutdown when done") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished).
I have thought about chmod u+s on the shutdown command so I don't need a password but I really don't want to do that.
Any ideas how I can achieve this?
Thanks in advance,
Ashy. | Instead of chmod u+sing the shutdown command, allowing passwordless sudo access to that command would be better..
As for allowing shutdown at the end of the script, I suppose you could run the entire script with sudo, then drop privileges to the initial user at the start of the script? | 0.496174 | false | 3 | 40 |
2008-11-04 22:47:39.493 | How can I ask for root password but perform the action at a later time? | I have a python script that I would like to add a "Shutdown when done" feature to.
I know I can use gksudo (when the user clicks on "shutdown when done") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished).
I have thought about chmod u+s on the shutdown command so I don't need a password but I really don't want to do that.
Any ideas how I can achieve this?
Thanks in advance,
Ashy. | Escalate priority, spawn (fork (2)) a separate process that will wait (2), and drop priority in the main process. | 0.135221 | false | 3 | 40 |
2008-11-04 22:47:39.493 | How can I ask for root password but perform the action at a later time? | I have a python script that I would like to add a "Shutdown when done" feature to.
I know I can use gksudo (when the user clicks on "shutdown when done") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished).
I have thought about chmod u+s on the shutdown command so I don't need a password but I really don't want to do that.
Any ideas how I can achieve this?
Thanks in advance,
Ashy. | gksudo should have a timeout, I believe it's from the time you last executed a gksudo command.
So I think I'd just throw out a "gksudo echo meh" or something every minute. Should reset the timer and keep you active until you reboot. | 1.2 | true | 3 | 40 |
2008-11-05 21:50:04.180 | Using Python's smtplib with Tor | I'm conducting experiments regarding e-mail spam. One of these experiments require sending mail thru Tor. Since I'm using Python and smtplib for my experiments, I'm looking for a way to use the Tor proxy (or other method) to perform that mail sending.
Ideas how this can be done? | Because of abuse by spammers, many Tor egress nodes decline to emit port 25 (SMTP) traffic, so you may have problems. | 1.2 | true | 1 | 41 |
2008-11-06 09:39:20.723 | Multiple database support in django | From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.
Can anyone please tell me how one can achieve multiple database connections in Django.
Does anyone have any idea by when Django will fully/officially support Multiple database connections. | If you read a few of the many (many) threads on this subject in django-dev, you will see that what looks straightforward, isn't. If you pick a single use case, then it looks easy, but as soon as you start to generalize in any way you start to run into trouble.
To use the above-referenced thread as an example, when you say "multiple databases", which of the following are you talking about?
All DB on the same machine under the same engine.
All DB on same machine, different engines (E.g. MySQL + PostgreSQL)
One Master DB with N read-only slaves on different machines.
Sharding of tables across multiple DB servers.
Will you need:
Foreign keys across DBs
JOINs across machines and/or engines
etc. etc.
One of the problems with a slick ORM like Django's is that it hides all of those messy details under a nice paint job. To continue to do that, but to then add in any of the above, is Not Easy (tm). | 0.121841 | false | 1 | 42 |
2008-11-07 11:35:00.583 | How should I stress test / load test a client server application? | I develop a client-server style, database based system and I need to devise a way to stress / load test the system. Customers inevitably want to know such things as:
• How many clients can a server support?
• How many concurrent searches can a server support?
• How much data can we store in the database?
• Etc.
Key to all these questions is response time. We need to be able to measure how response time and performance degrades as new load is introduced so that we could for example, produce some kind of pretty graph we could throw at clients to give them an idea what kind of performance to expect with a given hardware configuration.
Right now we just put out fingers in the air and make educated guesses based on what we already know about the system from experience. As the product is put under more demanding conditions, this is proving to be inadequate for our needs going forward though.
I've been given the task of devising a method to get such answers in a meaningful way. I realise that this is not a question that anyone can answer definitively but I'm looking for suggestions about how people have gone about doing such work on their own systems.
One thing to note is that we have full access to our client API via the Python language (courtesy of SWIG) which is a lot easier to work with than C++ for this kind of work.
So there we go, I throw this to the floor: really interested to see what ideas you guys can come up with! | For performance you are looking at two things: latency (the responsiveness of the application) and throughput (how many ops per interval). For latency you need to have an acceptable benchmark. For throughput you need to have a minimum acceptable throughput.
These are you starting points. For telling a client how many xyz's you can do per interval then you are going to need to know the hardware and software configuration. Knowing the production hardware is important to getting accurate figures. If you do not know the hardware configuration then you need to devise a way to map your figures from the test hardware to the eventual production hardware.
Without knowledge of hardware then you can really only observe trends in performance over time rather than absolutes.
Knowing the software configuration is equally important. Do you have a clustered server configuration, is it load balanced, is there anything else running on the server? Can you scale your software or do you have to scale the hardware to meet demand.
To know how many clients you can support you need to understand what is a standard set of operations. A quick test is to remove the client and write a stub client and the spin up as many of these as you can. Have each one connect to the server. You will eventually reach the server connection resource limit. Without connection pooling or better hardware you can't get higher than this. Often you will hit a architectural issue before here but in either case you have an upper bounds.
Take this information and design a script that your client can enact. You need to map how long your script takes to perform the action with respect to how long it will take the expected user to do it. Start increasing your numbers as mentioned above to you hit the point where the increase in clients causes a greater decrease in performance.
There are many ways to stress test but the key is understanding expected load. Ask your client about their expectations. What is the expected demand per interval? From there you can work out upper loads.
You can do a soak test with many clients operating continously for many hours or days. You can try to connect as many clients as you can as fast you can to see how well your server handles high demand (also a DOS attack).
Concurrent searches should be done through your standard behaviour searches acting on behalf of the client or, write a script to establish a semaphore that waits on many threads, then you can release them all at once. This is fun and punishes your database. When performing searches you need to take into account any caching layers that may exist. You need to test both caching and without caching (in scenarios where everyone makes unique search requests).
Database storage is based on physical space; you can determine row size from the field lengths and expected data population. Extrapolate this out statistically or create a data generation script (useful for your load testing scenarios and should be an asset to your organisation) and then map the generated data to business objects. Your clients will care about how many "business objects" they can store while you will care about how much raw data can be stored.
Other things to consider: What is the expected availability? What about how long it takes to bring a server online. 99.9% availability is not good if it takes two days to bring back online the one time it does go down. On the flip side a lower availablility is more acceptable if it takes 5 seconds to reboot and you have a fall over. | 0.386912 | false | 2 | 43 |
2008-11-07 11:35:00.583 | How should I stress test / load test a client server application? | I develop a client-server style, database based system and I need to devise a way to stress / load test the system. Customers inevitably want to know such things as:
• How many clients can a server support?
• How many concurrent searches can a server support?
• How much data can we store in the database?
• Etc.
Key to all these questions is response time. We need to be able to measure how response time and performance degrades as new load is introduced so that we could for example, produce some kind of pretty graph we could throw at clients to give them an idea what kind of performance to expect with a given hardware configuration.
Right now we just put out fingers in the air and make educated guesses based on what we already know about the system from experience. As the product is put under more demanding conditions, this is proving to be inadequate for our needs going forward though.
I've been given the task of devising a method to get such answers in a meaningful way. I realise that this is not a question that anyone can answer definitively but I'm looking for suggestions about how people have gone about doing such work on their own systems.
One thing to note is that we have full access to our client API via the Python language (courtesy of SWIG) which is a lot easier to work with than C++ for this kind of work.
So there we go, I throw this to the floor: really interested to see what ideas you guys can come up with! | If you have the budget, LoadRunner would be perfect for this. | 0 | false | 2 | 43 |
2008-11-16 22:11:25.050 | How do I find userid by login (Python under *NIX) | I need to set my process to run under 'nobody', I've found os.setuid(), but how do I find uid if I have login?
I've found out that uids are in /etc/passwd, but maybe there is a more pythonic way than scanning /etc/passwd. Anybody? | Never directly scan /etc/passwd.
For instance, on a Linux system I administer, the user accounts are not on /etc/passwd, but on a LDAP server.
The correct way is to use getpwent/getgrent and related C functions (as in @TFKyle's answer), which will get the information on the correct way for each system (on Linux glibc, it reads /etc/nsswitch.conf to know which NSS dynamic libraries to load to get the information). | 0.986614 | false | 1 | 44 |
2008-11-17 14:24:32.683 | What is a partial class? | What is and how can it be used in C#.
Can you use the same concept in Python/Perl? | Because python is a dynamic language you don't need a concept like partial class. In python is possible to extend object with functionality in runtime so it possible to break class declaration into different files | 0.050976 | false | 3 | 45 |
2008-11-17 14:24:32.683 | What is a partial class? | What is and how can it be used in C#.
Can you use the same concept in Python/Perl? | A Partial type is a type whose declaration is separated across multiple files. It makes sense to use them if you have a big class, which is hard to handle and read for a typical developer, to separate that class definition in separate files and to put in each file a logically separated section of code (for instance all public methods and proprieties in one file, private in other, db handling code in third and so on..)
No you don't have the same syntactical element in Python. | 0 | false | 3 | 45 |
2008-11-17 14:24:32.683 | What is a partial class? | What is and how can it be used in C#.
Can you use the same concept in Python/Perl? | Python also has meta classes but that is more like a template class than a partial class. A good example of meta class usage is the Django ORM. All of your table models inherit from a base model class which also gets functionality included from a meta class. It is a pretty cool concept that enables an active record like pattern (is it full active record?). | 0 | false | 3 | 45 |
2008-11-17 18:56:12.727 | How do I remove a specific number of files using python (version 2.5)? | I would like to remove two files from a folder at the conclusion of my script. Do I need to create a function responsible for removing these two specific files? I would like to know in some detail how to use os.remove (if that is what I should use) properly. These two files will always be discarded at the conclusion of my script (which packages a series of files together in a zip format). Thanks in advance. | It is perfectly acceptable to have a 'cleanup()' function that you call at the end of your script, which will call 'os.remove()' on your files. | 0 | false | 1 | 46 |
2008-11-18 13:52:31.717 | Django Template Variables and Javascript | When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using {{ myVar }}.
Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in. | For a dictionary, you're best of encoding to JSON first. You can use simplejson.dumps() or if you want to convert from a data model in App Engine, you could use encode() from the GQLEncoder library. | 0.201295 | false | 1 | 47 |
2008-11-18 16:22:39.447 | How can I get my python (version 2.5) script to run a jar file inside a folder instead of from command line? | I am familiar with using the os.system to run from the command line. However, I would like to be able to run a jar file from inside of a specific folder, eg. my 'test' folder. This is because my jar (located in my 'test' folder) requires a file inside of my 'test' folder. So, how would I write a function in my script that does the following: c:\test>java -jar run_this.jar required_parameter.ext ? I'm a python newbie so details are greatly appreciated. Thanks in advance. | In general: Use os.chdir to change the directory of the parent process, then os.system to run the jar file. If you need to keep Python's working directory stable, you need to chdir back to original working directory - you need to record that with os.getcwd().
On Unix: Create a child process with os.fork explicitly. In the parent, wait for the child with os.waitpid. In the child, use os.chdir, then os.exec to run java. | 0.201295 | false | 1 | 48 |
2008-11-18 18:39:05.350 | What are good ways to make my Python code run first time? | I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this? | Eric4 IDE also has a great built-in debugger. | 0 | false | 6 | 49 |
2008-11-18 18:39:05.350 | What are good ways to make my Python code run first time? | I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this? | The PyDev plugin for eclipse is my tool of choice. It recognizes simple syntax mistakes and indentation errors and underlines the error with a red line. It has a powerful debugger and even has a plugin called PyLint which warns you about dangerous code.
Edit:
It also has a user friendly stack trace on runtime errors, partial auto complete and some other nifty features.
Edit again:
I didn't notice that pydev was mentioned in the top post. I hope I brought something else to the table. | 0.101688 | false | 6 | 49 |
2008-11-18 18:39:05.350 | What are good ways to make my Python code run first time? | I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this? | I am new to python, and have been trying several different debuggers. Here are the options I've come across so far:
Eclipse with Pydev - If you're already using eclipse, this is probably the way to go. The debugger works well, and is pretty featureful.
Komodo IDE - A light-weight python IDE. Basically a text editor + a debugger. It was really easy to figure out and be productive with immediately.
WinPDB - Trying this one next. Looks very featureful, and I get to use whichever editor I choose.
PDB - Haven't tried yet since I've read about how WinPDB is a better alternative.
Ipython with %run command - I've used IPython, but not as a debugger like this. I need to try this out. (Thanks for the tip, EOL)
Eric IDE - Also on the list to try.
Old-school print, assert statements - Simple, useful, but not a full solution.
Memory debugging - To debug memory problems, I've come across a few tools:
objgraph - Will generate png's of reference graphs. Neat. There's other functionality as well, like: import objgraph;print(objgraph.show_most_common_types(limit=10)) will print the top 10 most common types in memory.
gc module - Interact directly with the garbage collector.
heapy - Heap analyzer. For example: from guppy import hpy; hp = hpy(); print(hp.heap()) will print the most common types, their memory usage, etc.
This is a very incomplete list, but hopefully it's a good start. | 0.249709 | false | 6 | 49 |
2008-11-18 18:39:05.350 | What are good ways to make my Python code run first time? | I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this? | Using assert statement liberally. | 0.126864 | false | 6 | 49 |
2008-11-18 18:39:05.350 | What are good ways to make my Python code run first time? | I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this? | All the really cool stuff is easily demonstrated in the interactive interpreter. I think this might be the "gold standard" for good design:
Can you exercise your class interactively?
If you can do stuff interactively, then you can write unittests and doctests with confidence that it's testable, simple, reliable.
And, more important, you can explore it interactively. There's nothing better than the instant gratification that comes from typing code and seeing exactly what happens.
The compiled language habits (write a bunch of stuff, debug a bunch of stuff, test a bunch of stuff) can be left behind. Instead, you can write a little bit of stuff, explore it, write a formal test and then attach your little bit of stuff to your growing final project.
You still do overall design. But you don't squander time writing code that may or may not work. In Python you write code that works. If you're not sure, you play with it interactively until you're sure. Then you write code that works. | 0.365009 | false | 6 | 49 |
2008-11-18 18:39:05.350 | What are good ways to make my Python code run first time? | I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this? | Test early and test often.
This doesn't necessarily mean to jump into the test driven design pool head first (though that's not such a bad idea). It just means, test your objects and methods as soon as you have something that works. Don't wait until you have a huge pile of code before doing testing.
Invest some time in learning a testing framework. If it's trivial for you to type in a test case you'll more likely do it. If you don't have any sort of framework testing can be a pain so you'll avoid it. So, establish some good habits early on and you'll have fewer problems down the road. | 0.176697 | false | 6 | 49 |
2008-11-18 19:51:54.423 | Calling Java (or python or perl) from a PHP script | I've been trying to build a simple prototype application in Django, and am reaching the point of giving up, sadly, as it's just too complicated (I know it would be worth it in the long-run, but I really just don't have enough time available -- I need something up and running in a few days). So, I'm now thinking of going with PHP instead, as it's the method for creating dynamic web content I'm most familiar with, and I know I can get something working quickly.
My application, while simple, is probably going to be doing some reasonably complex AI stuff, and it may be that libraries don't exist for what I need in PHP. So I'm wondering how easy / possible it is for a PHP script to "call" a Java program or Python script or a program or script in another language. It's not entirely clear to me what exactly I mean by "call" in this context, but I guess I probably mean that ideally I'd like to define a function in, let's say Java, and then be able to call it from PHP. If that's not possible, then I guess my best bet (assuming I do go with PHP) will be to pass control directly to the external program explicitly through a POST or GET to a CGI program or similar.
Feel free to convince me I should stick with Django, although I'm really at the point where I just can't figure out what model I need to produce the HTML form I want, which seems such a basic thing that I fear for my chances of doing anything more complex...
Alternatively, anyone who can offer any advice on linking PHP and other languages, that'll be grateful received. | "where I just can't figure out what model I need to produce the HTML form I want, which seems such a basic thing that I fear for my chances of doing anything more complex"
Common problem.
Root cause: Too much programming.
Solution. Do less programming. Seriously.
Define the Django model. Use the default admin pages to see if it's right. Fix the model. Regenerate the database. Look at the default admin pages. Repeat until the default admin pages work correctly and simply.
Once it's right in the default admin pages, you have a model that works. It's testable. And the automatic stuff is hooked up correctly. Choices are defined correctly. Computations are in the model mmethods. Queries work. Now you can start working on other presentations of the data.
Django generally starts (and ends) with the model. The forms, view and templates are derived from the model. | 1.2 | true | 1 | 50 |
2008-11-20 20:47:28.740 | With Python, how can I ensure that compression of a folder takes place within a particular folder? | I have been able to zip the contents of my folder. But I would like the zipped file to remain in the folder that was just compressed. For example, I've zipped a folder called test in my C: drive. But I would like my "test.zip" file to be contained in C:\test. How can I do this? Thanks in advance.
clarification of question with code example:
Someone kindly pointed out that my question is confusing, but for a python newbie a lot of things are confusing :) - my advance apologies if this question is too basic or the answer is obvious. I don't know how I can ensure that the resulting zip file is inside the folder that has been zipped. In other words, I would like the zip process to take place in 'basedir.' That way the user does not waste time searching for it somewhere on the C drive.
def zip_folder(basedir, zip_file):
z = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED)
for dirpath, dirnames, filenames in os.walk(basedir):
print "zipping files:"
for fn in filenames:
print fn
absfn = os.path.join(dirpath, fn)
z.write(absfn)
z.close | Whatever you pass as zip_file to your function will be the file that the ZipFile object will write to. So if you pass it a full path, then it will be put there. If you pass it just a filename, then it will be written to that filename under the current working path. It sounds like you just need to make sure that zip_file is an absolute path. | 1.2 | true | 1 | 51 |
2008-11-24 22:21:17.943 | Running a function periodically in twisted protocol | I am looking for a way to periodically send some data over all clients connected to a TCP port. I am looking at twisted python and I am aware of reactor.callLater. But how do I use it to send some data to all connected clients periodically ? The data sending logic is in Protocol class and it is instantiated by the reactor as needed. I don't know how to tie it from reactor to all protocol instances... | I'd imagine the easiest way to do that is to manage a list of clients in the protocol with connectionMade and connectionLost in the client and then use a LoopingCall to ask each client to send data.
That feels a little invasive, but I don't think you'd want to do it without the protocol having some control over the transmission/reception. Of course, I'd have to see your code to really know how it'd fit in well. Got a github link? :) | 0.545705 | false | 1 | 52 |
2008-11-26 06:20:40.703 | How do I skip processing the attachments of an email which is an attachment of a different email | using jython
I have a situation where emails come in with different attachments. Certain file types I process others I ignore and dont write to file.
I am caught in a rather nasty situation, because sometimes people send an email as an attachment, and that attached email has legal attachments.
What I want to do is skip that attached email and all its attachments.
using python/jythons std email lib how can i do this?
to make it clearer
I need to parse an email (named ROOT email), I want to get the attachments from this email using jython.
Next certain attachments are supported ie .pdf .doc etc
now it just so happens that, the clients send an email (ROOT email) with another email message (CHILD email) as an attachment, and in CHILD email it has .pdf attachments and such like.
What I need is: to get rid of any CHILD emails attached to the ROOT email AND the CHILD emails attachments. What happens is I walk over the whole email and it just parses every attachment, BOTH ROOT attachments and CHILD attachments as if they were ROOT attachments.
I cannot have this. I am only interested in ROOT attachements that are legal ie .pdf .doc. xls .rtf .tif .tiff
That should do for now, I have to run to catch a bus!
thanks! | Have you tried the get_payload( [i[, decode]]) method? Unlike walk it is not documented to recursively open attachments. | 0 | false | 1 | 53 |
2008-11-26 19:09:08.440 | Comparing XML in a unit test in Python | I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level). | Why are you examining the XML data at all?
The way to test object serialization is to create an instance of the object, serialize it, deserialize it into a new object, and compare the two objects. When you make a change that breaks serialization or deserialization, this test will fail.
The only thing checking the XML data is going to find for you is if your serializer is emitting a superset of what the deserializer requires, and the deserializer silently ignores stuff it doesn't expect.
Of course, if something else is going to be consuming the serialized data, that's another matter. But in that case, you ought to be thinking about establishing a schema for the XML and validating it. | 0.121841 | false | 2 | 54 |
2008-11-26 19:09:08.440 | Comparing XML in a unit test in Python | I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level). | The Java component dbUnit does a lot of XML comparisons, so you might find it useful to look at their approach (especially to find any gotchas that they may have already addressed). | 0 | false | 2 | 54 |
2008-12-05 12:02:54.363 | How do I submit a form given only the HTML source? | I would like to be able to submit a form in an HTML source (string). In other words I need at least the ability to generate POST parameters from a string containing HTML source of the form. This is needed in unit tests for a Django project. I would like a solution that possibly;
Uses only standard Python library and Django.
Allows parameter generation from a specific form if there is more than one form present.
Allows me to change the values before submission.
A solution that returns a (Django) form instance from a given form class is best. Because it would allow me to use validation. Ideally it would consume the source (which is a string), a form class, and optionally a form name and return the instance as it was before rendering.
NOTE: I am aware this is not an easy task, and probably the gains would hardly justify the effort needed. But I am just curious about how this can be done, in a practical and reliable way. If possible. | It is simple... and hard at the same time.
Disclaimer: I don't know much about Python and nothing at all about Django... So I give general, language agnostic advices...
If one of the above advices doesn't work for you, you might want to do it manually:
Load the page with an HTML parser, list the forms.
If the method attribute is POST (case insensitive), get the action attribute to get the URL of the request (can be relative).
In the form, get all input and select tags. The name (or id if no name) attributes are the keys of the request parameters. The value attributes (empty if absent) are the corresponding values.
For select, the value is the one of the selected option or the displayed text is no value attribute.
These names and values must be URL encoded in GET requests, but not in POST ones.
HTH. | 0.201295 | false | 1 | 55 |
2008-12-06 12:41:36.813 | Read file object as string in python | I'm using urllib2 to read in a page. I need to do a quick regex on the source and pull out a few variables but urllib2 presents as a file object rather than a string.
I'm new to python so I'm struggling to see how I use a file object to do this. Is there a quick way to convert this into a string? | You can use Python in interactive mode to search for solutions.
if f is your object, you can enter dir(f) to see all methods and attributes. There's one called read. Enter help(f.read) and it tells you that f.read() is the way to retrieve a string from an file object. | 1.2 | true | 1 | 56 |
2008-12-13 10:30:41.947 | Can you change a field label in the Django Admin application? | As the title suggests. I want to be able to change the label of a single field in the admin application. I'm aware of the Form.field attribute, but how do I get my Model or ModelAdmin to pass along that information? | Building on Javier's answer; if you need one label in forms (on the front-end) and another label on admin it is best to set internal (admin) one in the model and overwrite it on forms. Admin will of course use the label in the model field automatically. | 0.327599 | false | 1 | 57 |
2008-12-17 18:54:03.843 | Prevent ftplib from Downloading a File in Progress? | We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file and add it to the list.
We recently ran into an issue, where someone on the remote ftp side, will copy in a massive single file(>1GB) then the script will wake up see a new file and begin downloading the file that is being copied in.
What is the best way to check this? I was thinking of grabbing the file size waiting a few seconds checking the file size again and see if it has increased, if it hasn't then we download it. But since time is of the concern, we can't wait a few seconds for every single file set and see if it's file size has increased.
What would be the best way to go about this, currently everything is done via pythons ftplib, how can we do this aside from using the aforementioned method.
Yet again let me reiterate this, we have 0 control over the remote ftp sites.
Thanks.
UPDATE1:
I was thinking what if i tried to rename it... since we have full permissions on the ftp, if the file upload is in progress would the rename command fail?
We don't have any real options here... do we?
UPDATE2:
Well here's something interesting some of the ftps we tested on appear to automatically allocate the space once the transfer starts.
E.g. If i transfer a 200mb file to the ftp server. While the transfer is active if i connect to the ftp server and do a size while the upload is happening. It shows 200mb for the size. Even though the file is only like 10% complete.
Permissions also seem to be randomly set the FTP Server that comes with IIS sets the permissions AFTER the file is finished copying. While some of the other older ftp servers set it as soon as you send the file.
:'( | You can't know when the OS copy is done. It could slow down or wait.
For absolute certainty, you really need two files.
The massive file.
And a tiny trigger file.
They can mess with the massive file all they want. But when they touch the trigger file, you're downloading both.
If you can't get a trigger, you have to balance the time required to poll vs. the time required to download.
Do this.
Get a listing. Check timestamps.
Check sizes vs. previous size of file. If size isn't even close, it's being copied right now. Wait; loop on this step until size is close to previous size.
While you're not done:
a. Get the file.
b. Get a listing AGAIN. Check the size of the new listing, previous listing and your file. If they agree: you're done. If they don't agree: file changed while you were downloading; you're not done. | 0 | false | 4 | 58 |
2008-12-17 18:54:03.843 | Prevent ftplib from Downloading a File in Progress? | We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file and add it to the list.
We recently ran into an issue, where someone on the remote ftp side, will copy in a massive single file(>1GB) then the script will wake up see a new file and begin downloading the file that is being copied in.
What is the best way to check this? I was thinking of grabbing the file size waiting a few seconds checking the file size again and see if it has increased, if it hasn't then we download it. But since time is of the concern, we can't wait a few seconds for every single file set and see if it's file size has increased.
What would be the best way to go about this, currently everything is done via pythons ftplib, how can we do this aside from using the aforementioned method.
Yet again let me reiterate this, we have 0 control over the remote ftp sites.
Thanks.
UPDATE1:
I was thinking what if i tried to rename it... since we have full permissions on the ftp, if the file upload is in progress would the rename command fail?
We don't have any real options here... do we?
UPDATE2:
Well here's something interesting some of the ftps we tested on appear to automatically allocate the space once the transfer starts.
E.g. If i transfer a 200mb file to the ftp server. While the transfer is active if i connect to the ftp server and do a size while the upload is happening. It shows 200mb for the size. Even though the file is only like 10% complete.
Permissions also seem to be randomly set the FTP Server that comes with IIS sets the permissions AFTER the file is finished copying. While some of the other older ftp servers set it as soon as you send the file.
:'( | “Damn the torpedoes! Full speed ahead!”
Just download the file. If it is a large file then after the download completes wait as long as is reasonable for your scenario and continue the download from the point it stopped. Repeat until there is no more stuff to download. | 1.2 | true | 4 | 58 |
2008-12-17 18:54:03.843 | Prevent ftplib from Downloading a File in Progress? | We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file and add it to the list.
We recently ran into an issue, where someone on the remote ftp side, will copy in a massive single file(>1GB) then the script will wake up see a new file and begin downloading the file that is being copied in.
What is the best way to check this? I was thinking of grabbing the file size waiting a few seconds checking the file size again and see if it has increased, if it hasn't then we download it. But since time is of the concern, we can't wait a few seconds for every single file set and see if it's file size has increased.
What would be the best way to go about this, currently everything is done via pythons ftplib, how can we do this aside from using the aforementioned method.
Yet again let me reiterate this, we have 0 control over the remote ftp sites.
Thanks.
UPDATE1:
I was thinking what if i tried to rename it... since we have full permissions on the ftp, if the file upload is in progress would the rename command fail?
We don't have any real options here... do we?
UPDATE2:
Well here's something interesting some of the ftps we tested on appear to automatically allocate the space once the transfer starts.
E.g. If i transfer a 200mb file to the ftp server. While the transfer is active if i connect to the ftp server and do a size while the upload is happening. It shows 200mb for the size. Even though the file is only like 10% complete.
Permissions also seem to be randomly set the FTP Server that comes with IIS sets the permissions AFTER the file is finished copying. While some of the other older ftp servers set it as soon as you send the file.
:'( | If you are dealing with multiple files, you could get the list of all the sizes at once, wait ten seconds, and see which are the same. Whichever are still the same should be safe to download. | 0 | false | 4 | 58 |
2008-12-17 18:54:03.843 | Prevent ftplib from Downloading a File in Progress? | We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file and add it to the list.
We recently ran into an issue, where someone on the remote ftp side, will copy in a massive single file(>1GB) then the script will wake up see a new file and begin downloading the file that is being copied in.
What is the best way to check this? I was thinking of grabbing the file size waiting a few seconds checking the file size again and see if it has increased, if it hasn't then we download it. But since time is of the concern, we can't wait a few seconds for every single file set and see if it's file size has increased.
What would be the best way to go about this, currently everything is done via pythons ftplib, how can we do this aside from using the aforementioned method.
Yet again let me reiterate this, we have 0 control over the remote ftp sites.
Thanks.
UPDATE1:
I was thinking what if i tried to rename it... since we have full permissions on the ftp, if the file upload is in progress would the rename command fail?
We don't have any real options here... do we?
UPDATE2:
Well here's something interesting some of the ftps we tested on appear to automatically allocate the space once the transfer starts.
E.g. If i transfer a 200mb file to the ftp server. While the transfer is active if i connect to the ftp server and do a size while the upload is happening. It shows 200mb for the size. Even though the file is only like 10% complete.
Permissions also seem to be randomly set the FTP Server that comes with IIS sets the permissions AFTER the file is finished copying. While some of the other older ftp servers set it as soon as you send the file.
:'( | As you say you have 0 control over the servers and can't make your clients post trigger files as suggested by S. Lott, you must deal with the imperfect solution and risk incomplete file transmission, perhaps by waiting for a while and compare file sizes before and after.
You can try to rename as you suggested, but as you have 0 control you can't be sure that the ftp-server-administrator (or their successor) doesn't change platforms or ftp servers or restricts your permissions.
Sorry. | 0 | false | 4 | 58 |
2008-12-18 09:41:52.897 | Code not waiting for class initialization! | I have a block of code that basically intializes several classes, but they are placed in a sequential order, as later ones reference early ones.
For some reason the last one initializes before the first one...it seems to me there is some sort of threading going on. What I need to know is how can I stop it from doing this?
Is there some way to make a class init do something similar to sending a return value?
Or maybe I could use the class in an if statement of some sort to check if the class has already been initialized?
I'm a bit new to Python and am migrating from C, so I'm still getting used to the little differences like naming conventions. | Python upto 3.0 has a global lock, so everything is running in a single thread and in sequence.
My guess is that some side effect initializes the last class from a different place than you expect. Throw an exception in __init__ of that last class to see where it gets called. | 1.2 | true | 2 | 59 |
2008-12-18 09:41:52.897 | Code not waiting for class initialization! | I have a block of code that basically intializes several classes, but they are placed in a sequential order, as later ones reference early ones.
For some reason the last one initializes before the first one...it seems to me there is some sort of threading going on. What I need to know is how can I stop it from doing this?
Is there some way to make a class init do something similar to sending a return value?
Or maybe I could use the class in an if statement of some sort to check if the class has already been initialized?
I'm a bit new to Python and am migrating from C, so I'm still getting used to the little differences like naming conventions. | Spaces vs. Tabs issue...ugh. >.>
Well, atleast it works now. I admit that I kind of miss the braces from C instead of forced-indentation. It's quite handy as a prototyping language though. Maybe I'll grow to love it more when I get a better grasp of it. | 0 | false | 2 | 59 |
2008-12-18 21:23:50.017 | How to integrate the StringTemplate engine into the CherryPy web server | I love the StringTemplate engine, and I love the CherryPy web server, and I know that they can be integrated.
Who has done it? How?
EDIT: The TurboGears framework takes the CherryPy web server and bundles other related components such as a template engine, data access tools, JavaScript kit, etc. I am interested in MochiKit, demand CherryPy, but I don't want any other template engine than StringTemplate (architecture is critical--I don't want another broken/bad template engine).
Therefore, it would be acceptable to answer this question by addressing how to integrate StringTemplate with TurboGears.
It may also be acceptable to answer this question by addressing how to use CherryPy and StringTemplate in the Google App Engine.
Thanks. | Rob,
There's reason behind people's selection of tools. StringTemplate is not terribly popular for Python, there are templating engines that are much better supported and with a much wider audience. If you don't like Kid, there's also Django's templating, Jinja, Cheetah and others. Perhaps you can find in one of them the features you like so much in StringTemplate and live happily ever after. | 0 | false | 2 | 60 |
2008-12-18 21:23:50.017 | How to integrate the StringTemplate engine into the CherryPy web server | I love the StringTemplate engine, and I love the CherryPy web server, and I know that they can be integrated.
Who has done it? How?
EDIT: The TurboGears framework takes the CherryPy web server and bundles other related components such as a template engine, data access tools, JavaScript kit, etc. I am interested in MochiKit, demand CherryPy, but I don't want any other template engine than StringTemplate (architecture is critical--I don't want another broken/bad template engine).
Therefore, it would be acceptable to answer this question by addressing how to integrate StringTemplate with TurboGears.
It may also be acceptable to answer this question by addressing how to use CherryPy and StringTemplate in the Google App Engine.
Thanks. | Based on the tutorials for both, it looks pretty straightforward:
import stringtemplate
import cherrypy
class HelloWorld(object):
def index(self):
hello = stringtemplate.StringTemplate("Hello, $name$")
hello["name"] = "World"
return str(hello)
index.exposed = True
cherrypy.quickstart(HelloWorld())
You'll probably want to have the CherryPy functions find the StringTemplate's in some location on disk instead, but the general idea will be like this.
Django is conceptually similar: url's are mapped to python functions, and the python functions generally build up a context dictionary, render a template with that context object, and return the result. | 0.673066 | false | 2 | 60 |
2008-12-18 21:52:22.050 | How much slower is a wxWidget written in Python versus C++? | I'm looking into writing a wxWidget that displays a graphical node network, and therefore does a lot of drawing operations. I know that using Python to do it is going to be slower, but I'd rather get it working and port it later when its functional. Ideally, if the performance hit isn't too great, I'd prefer to keep the codebase in Python for easy updates.
What I'm wondering is how much slower should I expect things to go? I realize this is vague and open ended, but I just need a sense of what to expect. Will drawing 500 circles bog down? Will it be noticeable at all? What are your experiences? | For drawing, people have suggested PyGame. I like PyGame, its easy to work with and works well. Other choices would be Pyglet, or using PyOpenGL (you can most likely draw to a wx widget too, though I've never done it).
Personally, I'd do it in Python using whatever library I'm most familiar with (in my case, I'd use pygtk and cairo) and worry about performance only when it becomes a problem - then profile and optimize the bottleneck, if its Python code thats slow, I'll know which bits to run in C instead. | 0.135221 | false | 1 | 61 |
2008-12-22 02:25:02.243 | Prototype based object orientation. The good, the bad and the ugly? | I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and the shortcomings of such approach and the advantages compared to traditional OO.
The general notion that I got is that prototype based OO is basically programming with objects but no standard on how to use them whereas in normal OO there is a fixed predefined way to make and use objects.
In summary, what is the good, the bad and the ugly parts of such approach? | Okay, first of all, the prototype model isn't all that different in reality; Smalltalk uses a similar sort of scheme; the class is an object with the classes methods.
Looked at from the class POV, a class is really the equivalence class of objects with the same data, and all the same methods; you can look at adding a method to a prototype as creating a new subclass.
The implementation is simple, but makes it very difficult to do effective typechecking. | 0 | false | 2 | 62 |
2008-12-22 02:25:02.243 | Prototype based object orientation. The good, the bad and the ugly? | I come from classes object orientation languages and recently I have been learning those fancy dynamic languages (JavaScript, Python and Lua) and I want some tips about how to use OO in those languages. It would be useful to know the pitfalls and the shortcomings of such approach and the advantages compared to traditional OO.
The general notion that I got is that prototype based OO is basically programming with objects but no standard on how to use them whereas in normal OO there is a fixed predefined way to make and use objects.
In summary, what is the good, the bad and the ugly parts of such approach? | Classical inheritance is inherently flawed in terms of flexibility, in that we are saying "this object is of this type and no other". Some languages introduce multiple inheritance to alleviate this, but multiple inheritance has its own pitfalls, and so the benefits of pure composition over inheritance (which, in a statically typed language, is a runtime rather than a compile time mechanism) become clear.
Taking the concept of composition to this "pure" level, we can eliminate classical inheritance altogether along with static typing. By composing objects at runtime and using them as blueprints (the prototypal approach), we need never concern ourselves with boxing objects too tightly through inheritance, nor burden ourselves with the issues inherent in multiple inheritance approaches.
So prototypal means much more flexible development of modules.
Of course, it's quite another thing to say it's EASY to develop without static typing. IMO, it is not. | 0.081452 | false | 2 | 62 |
2008-12-22 22:37:08.520 | Using user input to find information in a Mysql database | I need to design a program using python that will ask the user for a barcode. Then, using this barcode, it will search a mysql to find its corresponding product.
I am a bit stuck on how to get started. Does anyone have any tips for me? | That is a very ambiguous question. What you want can be done in many ways depending on what you actually want to do.
How are your users going to enter the bar code? Are they going to use a bar code scanner? Are they entering the bar code numbers manually?
Is this going to run on a desktop/laptop computer or is it going to run on a handheld device?
Is the bar code scanner storing the bar codes for later retrieval or is it sending them directly to the computer. Will it send them through a USB cable or wireless? | 0 | false | 3 | 63 |
2008-12-22 22:37:08.520 | Using user input to find information in a Mysql database | I need to design a program using python that will ask the user for a barcode. Then, using this barcode, it will search a mysql to find its corresponding product.
I am a bit stuck on how to get started. Does anyone have any tips for me? | A barcode is simply a graphical representation of a series of characters (alphanumeric)
So if you have a method for users to enter this code (a barcode scanner), then its just an issue of querying the mysql database for the character string. | 0.101688 | false | 3 | 63 |
2008-12-22 22:37:08.520 | Using user input to find information in a Mysql database | I need to design a program using python that will ask the user for a barcode. Then, using this barcode, it will search a mysql to find its corresponding product.
I am a bit stuck on how to get started. Does anyone have any tips for me? | To start with, treat the barcode input as plain old text.
It has been quite a while since I worked with barcode scanners, but I doubt they have changed that much, the older ones used to just piggyback on the keyboard input, so from a programming perspective, the net result was a stream of characters in the keyboard buffer, either typed or scanned made no difference.
If the device you are targeting differs from that, you will need to write something to deal with that before you get to the database query.
If you have one of the devices to play with, plug it in, start notepad, start scanning some barcodes and see what happens. | 0 | false | 3 | 63 |
2008-12-23 22:37:51.123 | Interpreting Excel Currency Values | I am using python to read a currency value from excel. The returned from the range.Value method is a tuple that I don't know how to parse.
For example, the cell appears as $548,982, but in python the value is returned as (1, 1194857614).
How can I get the numerical amount from excel or how can I convert this tuple value into the numerical value?
Thanks! | I tried this with Excel 2007 and VBA. It is giving correct value.
1) Try pasting this value in a new excel workbook
2) Press Alt + F11. Gets you to VBA Editor.
3) Press Ctrl + G. Gets you to immediate window.
4) In the immediate window, type ?cells("a1").Value
here "a1" is the cell where you have pasted the value.
I am doubting that the cell has some value or character due to which it is interpreted this way.
Post your observations here. | 0 | false | 1 | 64 |
2009-01-01 00:55:16.753 | Python program to calculate harmonic series | Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4... | The harmonic series diverges, i.e. its sum is infinity..
edit: Unless you want partial sums, but you weren't really clear about that. | 0.147343 | false | 2 | 65 |
2009-01-01 00:55:16.753 | Python program to calculate harmonic series | Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4... | Just a footnote on the other answers that used floating point; starting with the largest divisor and iterating downward (toward the reciprocals with largest value) will put off accumulated round-off error as much as possible. | 0.183429 | false | 2 | 65 |
2009-01-03 19:37:41.127 | What versions of Python and wxPython correspond to each version of OSX? | I'd like to know what versions of Python and wxPython correspond to each version of OSX. I'm interested to know exactly how far back some of my apps will remain compatible on a mac before having to install newer versions of Python and wxPython. | Tiger shipped with Python 2.3.5 and wxPython 2.5.3, Leopard ships with python 2.5.1 and wxPython 2.8.4.
wxPython was not shipped with previous versions.
OSX Lion has 2.7.1 | 1.2 | true | 1 | 66 |
2009-01-08 05:45:02.847 | Using global variables in a function | How can I create or use a global variable in a function?
If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access? | If you want to refer to a global variable in a function, you can use the global keyword to declare which variables are global. You don't have to use it in all cases (as someone here incorrectly claims) - if the name referenced in an expression cannot be found in local scope or scopes in the functions in which this function is defined, it is looked up among global variables.
However, if you assign to a new variable not declared as global in the function, it is implicitly declared as local, and it can overshadow any existing global variable with the same name.
Also, global variables are useful, contrary to some OOP zealots who claim otherwise - especially for smaller scripts, where OOP is overkill. | 0.994161 | false | 2 | 67 |
2009-01-08 05:45:02.847 | Using global variables in a function | How can I create or use a global variable in a function?
If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access? | You're not actually storing the global in a local variable, just creating a local reference to the same object that your original global reference refers to. Remember that pretty much everything in Python is a name referring to an object, and nothing gets copied in usual operation.
If you didn't have to explicitly specify when an identifier was to refer to a predefined global, then you'd presumably have to explicitly specify when an identifier is a new local variable instead (for example, with something like the 'var' command seen in JavaScript). Since local variables are more common than global variables in any serious and non-trivial system, Python's system makes more sense in most cases.
You could have a language which attempted to guess, using a global variable if it existed or creating a local variable if it didn't. However, that would be very error-prone. For example, importing another module could inadvertently introduce a global variable by that name, changing the behaviour of your program. | 0.415447 | false | 2 | 67 |
2009-01-08 20:17:05.613 | Drag button between panels in wxPython | Does anyone know of an example where it is shown how to drag a button from one panel to another in wxPython?
I have created a bitmap button in a panel, and I would like to be able to drag it to a different panel and drop I there.
I haven't found any examples using buttons, just text and files.
I am using the latest version of Python and wxPython. | If you want to graphically represent the drag, one good way to do this is to create a borderless Frame that follows the mouse during a drag. You remove the button from your source Frame, temporarily put it in this "drag Frame", and then, when the user drops, add it to your destination Frame. | 1.2 | true | 1 | 68 |
2009-01-10 00:10:56.947 | Best way to poll a web service (eg, for a twitter app) | I need to poll a web service, in this case twitter's API, and I'm wondering what the conventional wisdom is on this topic. I'm not sure whether this is important, but I've always found feedback useful in the past.
A couple scenarios I've come up with:
The querying process starts every X seconds, eg a cron job runs a python script
A process continually loops and queries at each iteration, eg ... well, here is where I enter unfamiliar territory. Do I just run a python script that doesn't end?
Thanks for your advice.
ps - regarding the particulars of twitter: I know that it sends emails for following and direct messages, but sometimes one might want the flexibility of parsing @replies. In those cases, I believe polling is as good as it gets.
pps - twitter limits bots to 100 requests per 60 minutes. I don't know if this also limits web scraping or rss feed reading. Anyone know how easy or hard it is to be whitelisted?
Thanks again. | You should have a page that is like a Ping or Heartbeat page. The you have another process that "tickles" or hits that page, usually you can do this in your Control Panel of your web host, or use a cron if you have a local access. Then this script can keep statistics of how often it has polled in a database or some data store and then you poll the service as often as you really need to, of course limiting it to whatever the providers limit is. You definitely don't want to (and certainly don't want to rely) on a python scrip that "doesn't end." :) | 0 | false | 1 | 69 |
2009-01-10 23:57:46.473 | Programming Design Help - How to Structure a Sudoku Solver program? | I'm trying to create a sudoku solver program in Java (maybe Python).
I'm just wondering how I should go about structuring this...
Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class?
Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array?
And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object?
Thanks. | Don't over-engineer it. It's a 2-D array or maybe a Board class that represents a 2-D array at best. Have functions that calculate a given row/column and functions that let you access each square. Additional methods can be used validate that each sub-3x3 and row/column don't violate the required constraints. | 0.545705 | false | 5 | 70 |
2009-01-10 23:57:46.473 | Programming Design Help - How to Structure a Sudoku Solver program? | I'm trying to create a sudoku solver program in Java (maybe Python).
I'm just wondering how I should go about structuring this...
Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class?
Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array?
And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object?
Thanks. | Maybe a design that had a box per square, and another class to represent the puzzle itself that would have a collection of boxes, contain all the rules for box interactions, and control the overall game would be a good design. | 0 | false | 5 | 70 |
2009-01-10 23:57:46.473 | Programming Design Help - How to Structure a Sudoku Solver program? | I'm trying to create a sudoku solver program in Java (maybe Python).
I'm just wondering how I should go about structuring this...
Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class?
Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array?
And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object?
Thanks. | First, it looks like there are two kinds of cells.
Known calls; those with a fixed value, no choices.
Unknown cells; those with a set of candidate values that reduces down to a single final value.
Second, there are several groups of cells.
Horizontal rows and Vertical columns which must have one cell of each value. That constraint is used to remove values from various cells in the row or column.
3x3 blocks which must have one cell of each value. That constraint is used to remove values from various cells in the block.
Finally, there's the overall grid. This has several complementary views.
It's 81 cells.
The cells are also collected into a 3x3 grid of 3x3 blocks.
The cells are also collected into 9 columns.
The cells are also collected into 9 rows.
And you have a solver strategy object.
Each Unknown cell it set to having set( range(1,10) ) as the candidate values.
For each row, column and 3x3 block (27 different collections):
a. For each cell:
If it has definite value (Known cells and Unknown cells implement this differently): remove that value from all other cells in this grouping.
The above must be iterated until no changes are found.
At this point, you either have it solved (all cells report a definite value), or, you have some cells with multiple values. Now you have to engage in a sophisticated back-tracking solver to find a combination of the remaining values that "works". | 0 | false | 5 | 70 |
2009-01-10 23:57:46.473 | Programming Design Help - How to Structure a Sudoku Solver program? | I'm trying to create a sudoku solver program in Java (maybe Python).
I'm just wondering how I should go about structuring this...
Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class?
Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array?
And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object?
Thanks. | Well, I would use one class for the sudoku itself, with a 9 x 9 array and all the functionality to add numbers and detect errors in the pattern.
Another class will be used to solve the puzzle. | 0.101688 | false | 5 | 70 |
2009-01-10 23:57:46.473 | Programming Design Help - How to Structure a Sudoku Solver program? | I'm trying to create a sudoku solver program in Java (maybe Python).
I'm just wondering how I should go about structuring this...
Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class?
Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array?
And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object?
Thanks. | The simplest way to do it is to represent the board by a 2D 9x9 array. You'll want to have references to each row, column and 3x3 box as a separate object, so storing each cell in a String makes more sense (in Java) than using a primitive. With a String you can keep references to the same object in multiple containers. | 0.050976 | false | 5 | 70 |
2009-01-12 04:05:35.690 | Installing certain packages using virtualenv | So, I want to start using virtualenv this year. I like the no-site-packages option, that is nice. However I was wondering how to install certain packages into each virtualenv. For example, lets say I want to install django into each virtualenv... is this possible, and if so, how? Does buildout address this?
Well it's not so much django, more like the django applications... I dont mind installing a version of django into each virtualenv... i was just wondering if there was some intermediate option to 'no-site-packages' | If you want django to be installed on EACH virtualenv, you might as well install it in the site-packages directory? Just a thought. | 0.16183 | false | 2 | 71 |
2009-01-12 04:05:35.690 | Installing certain packages using virtualenv | So, I want to start using virtualenv this year. I like the no-site-packages option, that is nice. However I was wondering how to install certain packages into each virtualenv. For example, lets say I want to install django into each virtualenv... is this possible, and if so, how? Does buildout address this?
Well it's not so much django, more like the django applications... I dont mind installing a version of django into each virtualenv... i was just wondering if there was some intermediate option to 'no-site-packages' | The other option (one I've used) is to easy_install Django after you've created the virtual environment. This is easily scripted. The penalty you pay is waiting for Django installation in each of your virtual environments.
I'm with Toby, though: Unless there's a compelling reason why you have to have a separate copy of Django in each virtual environment, you should just consider installing it in your main Python area, and allowing each virtual environment to use it from there. | 0 | false | 2 | 71 |
2009-01-12 18:38:15.180 | Python: import the containing package | In a module residing inside a package, i have the need to use a function defined within the __init__.py of that package. how can i import the package within the module that resides within the package, so i can use that function?
Importing __init__ inside the module will not import the package, but instead a module named __init__, leading to two copies of things with different names...
Is there a pythonic way to do this? | In Django, the file manage.py has from django.core.management import execute_manager, but execute_manager is not a module. It is a function within the __init__.py module of the management directory. | 0.081452 | false | 3 | 72 |
2009-01-12 18:38:15.180 | Python: import the containing package | In a module residing inside a package, i have the need to use a function defined within the __init__.py of that package. how can i import the package within the module that resides within the package, so i can use that function?
Importing __init__ inside the module will not import the package, but instead a module named __init__, leading to two copies of things with different names...
Is there a pythonic way to do this? | If the package is named testmod and your init file is therefore testmod/__init__.py and your module within the package is submod.py then from within submod.py file, you should just be able to say import testmod and use whatever you want that's defined in testmod. | 0.386912 | false | 3 | 72 |
2009-01-12 18:38:15.180 | Python: import the containing package | In a module residing inside a package, i have the need to use a function defined within the __init__.py of that package. how can i import the package within the module that resides within the package, so i can use that function?
Importing __init__ inside the module will not import the package, but instead a module named __init__, leading to two copies of things with different names...
Is there a pythonic way to do this? | This doesn't exactly answer your question, but I'm going to suggest that you move the function outside of the __init__.py file, and into another module inside that package. You can then easily import that function into your other module. If you want, you can have an import statement in the __init__.py file that will import that function (when the package is imported) as well. | 0.999798 | false | 3 | 72 |
2009-01-12 21:11:44.310 | How to implement a python REPL that nicely handles asynchronous output? | I have a Python-based app that can accept a few commands in a simple read-eval-print-loop. I'm using raw_input('> ') to get the input. On Unix-based systems, I also import readline to make things behave a little better. All this is working fine.
The problem is that there are asynchronous events coming in, and I'd like to print output as soon as they happen. Unfortunately, this makes things look ugly. The "> " string doesn't show up again after the output, and if the user is halfway through typing something, it chops their text in half. It should probably redraw the user's text-in-progress after printing something.
This seems like it must be a solved problem. What's the proper way to do this?
Also note that some of my users are Windows-based.
TIA
Edit: The accepted answer works under Unixy platforms (when the readline module is available), but if anyone knows how to make this work under Windows, it would be much appreciated! | I think you have 2 basic options:
Synchronize your output (i.e. block until it comes back)
Separate your input and your (asyncronous) output, perhaps in two separate columns. | -0.067922 | false | 1 | 73 |
2009-01-13 16:21:17.920 | PIL vs RMagick/ruby-gd | For my next project I plan to create images with text and graphics. I'm comfortable with ruby, but interested in learning python. I figured this may be a good time because PIL looks like a great library to use. However, I don't know how it compares to what ruby has to offer (e.g. RMagick and ruby-gd). From what I can gather PIL had better documentation (does ruby-gd even have a homepage?) and more features. Just wanted to hear a few opinions to help me decide.
Thanks.
Vince | PIL is a good library, use it. ImageMagic (what RMagick wraps) is a very heavy library that should be avoided if possible. Its good for doing local processing of images, say, a batch photo editor, but way too processor inefficient for common image manipulation tasks for web.
EDIT: In response to the question, PIL supports drawing vector shapes. It can draw polygons, curves, lines, fills and text. I've used it in a project to produce rounded alpha corners to PNG images on the fly over the web. It essentially has most of the drawing features of GDI+ (in Windows) or GTK (in Gnome on Linux). | 0.740859 | false | 1 | 74 |
2009-01-14 20:17:06.353 | How are debug consoles implemented in Python? | I've seen a couple of Python IDE's (e.g. PyDev Extensions, WingIDE) that provide a debug console - an interactive terminal that runs in the context of the method where the breakpoint is. This lets you print members, call other methods and see the results, and redefine methods to try to fix bugs. Cool.
Can anyone tell me how this is implemented? I know there's the Code module, which provides an InteractiveConsole class, but I don't know how this can be run in the context of currently loaded code. I'm quite new to Python, so gentle assistance would be appreciated! | You could try looking at the python debugger pdb. It's like gdb in how you use it, but implemented in pure python. Have a look for pdb.py in your python install directory. | 0.454054 | false | 1 | 75 |
2009-01-14 22:57:53.610 | How to make a wx Toolbar buttons larger? | I've got a wx.Toolbar and I'd like to make the buttons larger. I've searched and can't seem to find any concrete documentation on how to do this.
I'm also wondering how well this will translate across platforms; what will happen to the buttons and icons on OSX? | Doesn't the size of the toolbar adapts itself automatically to the size of the bitmap icons? I think if you want a bigger toolbar, you need bigger bitmaps. | 0.265586 | false | 1 | 76 |
2009-01-15 13:21:14.040 | How can I deploy a Perl/Python/Ruby script without installing an interpreter? | I want to write a piece of software which is essentially a regex data scrubber. I am going to take a contact list in CSV and remove all non-word characters and such from the person's name.
This project has Perl written all over it but my client base is largely non-technical and installing Perl on Windows would not be worth it for them.
Any ideas on how I can use a Perl/Python/Ruby type language without all the headaches of getting the interpreter on their computer?
Thought about web for a second but it would not work for business reasons. | "installing Perl on Windows would not be worth it for them" Really? It's that complex?
Python has a simple .MSI that neatly installs itself with no muss or fuss.
A simple application program is just a few .py files, so, I don't see a big pain factor there.
You know your customers best.
I find that the following isn't so bad. And it's much easier to support, since your upgrades will just be a single .MSI with simple, easy-to-live with source.
1) double click this .MSI file to install Python (or Perl or whatever)
2) double click this other .MSI to install the good stuff | 0 | false | 1 | 77 |
2009-01-15 22:58:46.447 | How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage? | I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities.
I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely.
The problem is that I don't know where to start investigating how to do this. Let's say I have a script called:
file_arranger.py
What do I need to do to have a webpage execute that script? This isn't meant for public consumption, so anything lightweight would be great. For bonus points, what do I need to look into to provide the web user with the output from such scripts?
edit: The first answer made me realize I forgot to include that this is a Win2k3 system. | When setting this up, please be careful to restrict access to the scripts that take some action on your web server. It is not sufficient to place them in a directory where you just don't publish the URL, because sooner or later somebody will find them.
At the very least, put these scripts in a location that is password protected. You don't want just anybody out there on the internet being able to run your scripts. | 0 | false | 2 | 78 |
2009-01-15 22:58:46.447 | How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage? | I'm a hobbyist (and fairly new) programmer who has written several useful (to me) scripts in python to handle various system automation tasks that involve copying, renaming, and downloading files amongst other sundry activities.
I'd like to create a web page served from one of my systems that would merely present a few buttons which would allow me to initiate these scripts remotely.
The problem is that I don't know where to start investigating how to do this. Let's say I have a script called:
file_arranger.py
What do I need to do to have a webpage execute that script? This isn't meant for public consumption, so anything lightweight would be great. For bonus points, what do I need to look into to provide the web user with the output from such scripts?
edit: The first answer made me realize I forgot to include that this is a Win2k3 system. | A simple cgi script (or set of scripts) is all you need to get started. The other answers have covered how to do this so I won't repeat it; instead, I will stress that using plain text will get you a long way. Just output the header (print("Content-type: text/plain\n") plus print adds its own newline to give you the needed blank line) and then run your normal program.
This way, any normal output from your script gets sent to the browser and you don't have to worry about HTML, escaping, frameworks, anything. "Do the simplest thing that could possibly work."
This is especially appropriate for non-interactive private administrative tasks like you describe, and lets you use identical programs from a shell with a minimum of fuss. Your driver, the page with the buttons, can be a static HTML file with single-button forms. Or even a list of links.
To advance from there, look at the logging module (for example, sending INFO messages to the browser but not the command line, or easily categorizing messages by using different loggers, by configuring your handlers), and then start to consider template engines and frameworks.
Don't output your own HTML and skip to using one of the many existing libraries—it'll save a ton of headache even spending a bit of extra time to learn the library. Or at the very least encapsulate your output by effectively writing your own mini-engine. | 0.04532 | false | 2 | 78 |
2009-01-16 12:01:24.867 | How to check if a file can be created inside given directory on MS XP/Vista? | I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it.
I have created directory for test purposes, let's call it C:\foo.
I have following permissions to C:\foo:
Traversing directory/Execute file
Removing subfolders and files
Removing
Read permissions
Change permissions
Take ownership
I don't have any of the following permissions to C:\foo:
Full Control
File creation
Folder creation
I have tried following approaches, so far:
os.access('C:\foo', os.W_OK) == True
st = os.stat('C:\foo')
mode = st[stat.ST_MODE]
mode & stat.S_IWRITE == True
I believe that this is caused by the fact that I can rename folder, so it is changeable for me. But it's content - not.
Does anyone know how can I write code that will check for a given directory if current user has permissions to create file in that directory?
In brief - I want to check if current user has File creation and Folder creation permissions for given folder name.
EDIT: The need for such code arisen from the Test case no 3 from 'Certified for Windows Vista' program, which states:
The application must not allow the Least-Privileged user to save any files to Windows System directory in order to pass this test case.
Should this be understood as 'Application may try to save file in Windows System directory, but shouldn't crash on failure?' or rather 'Application has to perform security checks before trying to save file?'
Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%? | I wouldn't waste time and LOCs on checking for permissions. Ultimate test of file creation in Windows is the creation itself. Other factors may come into play (such as existing files (or worse, folders) with the same name, disk space, background processes. These conditions can even change between the time you make the initial check and the time you actually try to create your file.
So, if I had a scenario like that, I would just design my method to not lose any data in case of failure, to go ahead and try to create my file, and offer the user an option to change the selected directory and try again if creation fails. | 0.386912 | false | 2 | 79 |
2009-01-16 12:01:24.867 | How to check if a file can be created inside given directory on MS XP/Vista? | I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it.
I have created directory for test purposes, let's call it C:\foo.
I have following permissions to C:\foo:
Traversing directory/Execute file
Removing subfolders and files
Removing
Read permissions
Change permissions
Take ownership
I don't have any of the following permissions to C:\foo:
Full Control
File creation
Folder creation
I have tried following approaches, so far:
os.access('C:\foo', os.W_OK) == True
st = os.stat('C:\foo')
mode = st[stat.ST_MODE]
mode & stat.S_IWRITE == True
I believe that this is caused by the fact that I can rename folder, so it is changeable for me. But it's content - not.
Does anyone know how can I write code that will check for a given directory if current user has permissions to create file in that directory?
In brief - I want to check if current user has File creation and Folder creation permissions for given folder name.
EDIT: The need for such code arisen from the Test case no 3 from 'Certified for Windows Vista' program, which states:
The application must not allow the Least-Privileged user to save any files to Windows System directory in order to pass this test case.
Should this be understood as 'Application may try to save file in Windows System directory, but shouldn't crash on failure?' or rather 'Application has to perform security checks before trying to save file?'
Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%? | I recently wrote a App to pass a set of test to obtain the ISV status from Microsoft and I also add that condition.
The way I understood it was that if the user is Least Priveledge then he won't have permission to write in the system folders. So I approached the problem the the way Ishmaeel described. I try to create the file and catch the exception then inform the user that he doesn't have permission to write files to that directory.
In my understanding an Least-Priviledged user will not have the necessary permissions to write to those folders, if he has then he is not a Least-Priveledge user.
Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%?
In my opinion? Yes. | 1.2 | true | 2 | 79 |
2009-01-16 12:33:20.120 | Python Path | I am installing active python, django. I really dont know how to set the python path in vista environment system. first of all will it work in vista. | Remember that in addition to setting PYTHONPATH in your system environment, you'll also want to assign DJANGO_SETTINGS_MODULE. | 0 | false | 1 | 80 |
2009-01-20 03:43:14.223 | Python/Twisted - Sending to a specific socket object? | I have a "manager" process on a node, and several worker processes. The manager is the actual server who holds all of the connections to the clients. The manager accepts all incoming packets and puts them into a queue, and then the worker processes pull the packets out of the queue, process them, and generate a result. They send the result back to the manager (by putting them into another queue which is read by the manager), but here is where I get stuck: how do I send the result to a specific socket? When dealing with the processing of the packets on a single process, it's easy, because when you receive a packet you can reply to it by just grabbing the "transport" object in-context. But how would I do this with the method I'm using? | It sounds like you might need to keep a reference to the transport (or protocol) along with the bytes the just came in on that protocol in your 'event' object. That way responses that came in on a connection go out on the same connection.
If things don't need to be processed serially perhaps you should think about setting up functors that can handle the data in parallel to remove the need for queueing. Just keep in mind that you will need to protect critical sections of your code.
Edit:
Judging from your other question about evaluating your server design it would seem that processing in parallel may not be possible for your situation, so my first suggestion stands. | 1.2 | true | 1 | 81 |
2009-01-20 16:37:53.927 | Python with Netbeans 6.5 | Can you give me some links or explain how to configure an existing python project onto Netbeans?
I'm trying it these days and it continues to crash also code navigation doesn't work well and I've problems with debugging. Surely these problems are related to my low eperience about python and I need support also in trivial things as organizing source folders, imports ecc,, thank you very much.
Valerio | Python support is in beta, and as someone who works with NB for a past 2 years, I can say that even a release versions are buggy and sometimes crashes. Early Ruby support was also very shaky. | 0.386912 | false | 1 | 82 |
2009-01-21 07:14:19.397 | Python - Hits per minute implementation? | This seems like such a trivial problem, but I can't seem to pin how I want to do it. Basically, I want to be able to produce a figure from a socket server that at any time can give the number of packets received in the last minute. How would I do that?
I was thinking of maybe summing a dictionary that uses the current second as a key, and when receiving a packet it increments that value by one, as well as setting the second+1 key above it to 0, but this just seems sloppy. Any ideas? | When you say the last minute, do you mean the exact last seconds or the last full minute from x:00 to x:59? The latter will be easier to implement and would probably give accurate results. You have one prev variable holding the value of the hits for the previous minute. Then you have a current value that increments every time there is a new hit. You return the value of prev to the users. At the change of the minute you swap prev with current and reset current.
If you want higher analysis you could split the minute in 2 to 6 slices. You need a variable or list entry for every slice. Let's say you have 6 slices of 10 seconds. You also have an index variable pointing to the current slice (0..5). For every hit you increment a temp variable. When the slice is over, you replace the value of the indexed variable with the value of temp, reset temp and move the index forward. You return the sum of the slice variables to the users. | 1.2 | true | 3 | 83 |
2009-01-21 07:14:19.397 | Python - Hits per minute implementation? | This seems like such a trivial problem, but I can't seem to pin how I want to do it. Basically, I want to be able to produce a figure from a socket server that at any time can give the number of packets received in the last minute. How would I do that?
I was thinking of maybe summing a dictionary that uses the current second as a key, and when receiving a packet it increments that value by one, as well as setting the second+1 key above it to 0, but this just seems sloppy. Any ideas? | For what it's worth, your implementation above won't work if you don't receive a packet every second, as the next second entry won't necessarily be reset to 0.
Either way, afaik the "correct" way to do this, ala logs analysis, is to keep a limited record of all the queries you receive. So just chuck the query, time received etc. into a database, and then simple database queries will give you the use over a minute, or any minute in the past. Not sure whether this is too heavyweight for you, though. | 0.135221 | false | 3 | 83 |
2009-01-21 07:14:19.397 | Python - Hits per minute implementation? | This seems like such a trivial problem, but I can't seem to pin how I want to do it. Basically, I want to be able to produce a figure from a socket server that at any time can give the number of packets received in the last minute. How would I do that?
I was thinking of maybe summing a dictionary that uses the current second as a key, and when receiving a packet it increments that value by one, as well as setting the second+1 key above it to 0, but this just seems sloppy. Any ideas? | A common pattern for solving this in other languages is to let the thing being measured simply increment an integer. Then you leave it to the listening client to determine intervals and frequencies.
So you basically do not let the socket server know about stuff like "minutes", because that's a feature the observer calculates. Then you can also support multiple listeners with different interval resolution.
I suppose you want some kind of ring-buffer structure to do the rolling logging. | 0.386912 | false | 3 | 83 |
2009-01-21 19:40:34.663 | How can I return system information in Python? | Using Python, how can information such as CPU usage, memory usage (free, used, etc), process count, etc be returned in a generic manner so that the same code can be run on Linux, Windows, BSD, etc?
Alternatively, how could this information be returned on all the above systems with the code specific to that OS being run only if that OS is indeed the operating environment? | It looks like you want to get a lot more information than the standard Python library offers. If I were you, I would download the source code for 'ps' or 'top', or the Gnome/KDE version of the same, or any number of system monitoring/graphing programs which are more likely to have all the necessary Unix cross platform bits, see what they do, and then make the necessary native calls with ctypes.
It's trivial to detect the platform. For example with ctypes you might try to load libc.so, if that throws an exception try to load 'msvcrt.dll' and so on. Not to mention simply checking the operating system's name with os.name. Then just delegate calls to your new cross-platform API to the appropriate platform-specific (sorry) implementation.
When you're done, don't forget to upload the resulting package to pypi. | 0.058243 | false | 1 | 84 |
2009-01-22 23:25:40.950 | Organising a GUI application | This is going to be a generic question.
I am struggling in designing a GUI application, esp. with dealing with interactions between different parts.
I don't know how I should deal with shared state. On one hand, shared state is bad, and things should be as explicit as possible. On the other hand, not having shared state introduces unwanted coupling between components.
An example:
I want my application to be extendable in an Emacs/Vim sort of way, via scripts. Clearly, some sort of shared state needs to be modified, so that the GUI will use it. My initial plan was having a global "session" that is accessible from everywhere, but I'm not so sure about it.
One tricky use case is key bindings. I want the user to be able to specify custom keybindings from a script. Each keybinding maps to an arbitrary command, that receives the session as the only argument.
Now, the editor component captures keypresses. It has to have access to the keymappings, which are per-session, so it needs access to the session. Is coupling the editor to the session a good idea? Other components will also need to access the keybindings, so the session now becomes shared and can be a singleton...
Is there any good reading about designing GUI applications that goes beyond MVC?
This is Python and wxPython, FWIW.
[EDIT]: Added concrete usecase. | If you've looked at MVC you're probably moving in the right direction. MVC, MVP, Passive View, Supervising Controller. Those are all different ways, each with their own pros and cons, of accomplishing what you're after. I find that Passive View is the "ideal", but it causes you to introduce far too many widgets into your GUI interfaces (i.e. IInterface). In general I find that Supervising Controller is a good compromise. | 0.265586 | false | 2 | 85 |
2009-01-22 23:25:40.950 | Organising a GUI application | This is going to be a generic question.
I am struggling in designing a GUI application, esp. with dealing with interactions between different parts.
I don't know how I should deal with shared state. On one hand, shared state is bad, and things should be as explicit as possible. On the other hand, not having shared state introduces unwanted coupling between components.
An example:
I want my application to be extendable in an Emacs/Vim sort of way, via scripts. Clearly, some sort of shared state needs to be modified, so that the GUI will use it. My initial plan was having a global "session" that is accessible from everywhere, but I'm not so sure about it.
One tricky use case is key bindings. I want the user to be able to specify custom keybindings from a script. Each keybinding maps to an arbitrary command, that receives the session as the only argument.
Now, the editor component captures keypresses. It has to have access to the keymappings, which are per-session, so it needs access to the session. Is coupling the editor to the session a good idea? Other components will also need to access the keybindings, so the session now becomes shared and can be a singleton...
Is there any good reading about designing GUI applications that goes beyond MVC?
This is Python and wxPython, FWIW.
[EDIT]: Added concrete usecase. | In MVC, the Model stuff is the shared state of the information.
The Control stuff is the shared state of the GUI control settings and responses to mouse-clicks and what-not.
Your scripting angle can
1) Update the Model objects. This is good. The Control can be "Observers" of the model objects and the View be updated to reflect the observed changes.
2) Update the Control objects. This is not so good, but... The Control objects can then make appropriate changes to the Model and/or View.
I'm not sure what the problem is with MVC. Could you provide a more detailed design example with specific issues or concerns? | 0.135221 | false | 2 | 85 |
2009-01-23 16:16:33.017 | When printing an image, what determines how large it will appear on a page? | Using Python's Imaging Library I want to create a PNG file.
I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.
Is the resolution encoded in the image?
If so, how do I specify it?
And even if it is, does this have any relevance when it goes to the printer? | Printers have various resolutions in which they print. If you select a print resolution of 200 DPI for instance (or if it's set as default in the printer driver), then a 200 pixel image should be one inch in size. | 0.081452 | false | 4 | 86 |
2009-01-23 16:16:33.017 | When printing an image, what determines how large it will appear on a page? | Using Python's Imaging Library I want to create a PNG file.
I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.
Is the resolution encoded in the image?
If so, how do I specify it?
And even if it is, does this have any relevance when it goes to the printer? | Much is going to depend on the software you're using to print. If you're placing the image in a Word document, it will scale according to the DPI, up to the width of your page. If you're putting it on a web page, the DPI will not matter at all. | 0 | false | 4 | 86 |
2009-01-23 16:16:33.017 | When printing an image, what determines how large it will appear on a page? | Using Python's Imaging Library I want to create a PNG file.
I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.
Is the resolution encoded in the image?
If so, how do I specify it?
And even if it is, does this have any relevance when it goes to the printer? | Both image print size and resolution are relevant to printing an image of a specific scale and quality. Bear in mind that if the image is then included with a desktop publishing workspace (Word, InDesign) or even a web page, the image is then subject to any specified resolution in the parent document -- this won't necessarily alter the relative scale of the image in the case of desktop publishing programs but will alter image quality.
And yes, all images have a resolution property, which answers half your question - I don't know Python... | 0.081452 | false | 4 | 86 |
2009-01-23 16:16:33.017 | When printing an image, what determines how large it will appear on a page? | Using Python's Imaging Library I want to create a PNG file.
I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.
Is the resolution encoded in the image?
If so, how do I specify it?
And even if it is, does this have any relevance when it goes to the printer? | I found a very simple way to get dpi information into the png:
im.save('myfile.png',dpi=[600,600])
Unfortunately I did not find this documented anywhere and had to dig into the PIL source code. | 0.240117 | false | 4 | 86 |
2009-01-26 22:42:42.320 | Can a lambda function call itself recursively in Python? | A regular function can contain a call to itself in its definition, no problem. I can't figure out how to do it with a lambda function though for the simple reason that the lambda function has no name to refer back to. Is there a way to do it? How? | If you were truly masochistic, you might be able to do it using C extensions, but this exceeds the capability of a lambda (unnamed, anonymous) functon.
No. (for most values of no). | -0.081452 | false | 1 | 87 |
2009-01-28 13:39:54.740 | Inventory Control Across Multiple Servers .. Ideas? | We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it.
This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout.
Our inventory management system runs off a server in the office, while the three websites we currently have (only one actually sells things) runs off an outside source, obviously.
See my problem here? Basically, I am trying to think of ways I can create a central inventory control system that allows both the internal software and external websites to communicate so that inventory is always up to date and we are not selling something we don't have.
Our internal inventory tracking works great and flows well, but I have no idea on how I would implement a solid tracking system that can communicate between the two.
The software is all written in Python, but it does not matter as I am mostly looking for ideas and methods on how would this be implemented.
Thanks in advance for any answers, and I hope that made sense .. I can elaborate. | I don't see the problem... You have an application running on one server that manages your database locally. There's no reason a remote server can't also talk to that database.
Of course, if you don't have a database and are instead using a homegrown app to act as some sort of faux-database, I recommend that you refactor to use something sort of actual DB sooner rather than later. | 0 | false | 3 | 88 |
2009-01-28 13:39:54.740 | Inventory Control Across Multiple Servers .. Ideas? | We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it.
This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout.
Our inventory management system runs off a server in the office, while the three websites we currently have (only one actually sells things) runs off an outside source, obviously.
See my problem here? Basically, I am trying to think of ways I can create a central inventory control system that allows both the internal software and external websites to communicate so that inventory is always up to date and we are not selling something we don't have.
Our internal inventory tracking works great and flows well, but I have no idea on how I would implement a solid tracking system that can communicate between the two.
The software is all written in Python, but it does not matter as I am mostly looking for ideas and methods on how would this be implemented.
Thanks in advance for any answers, and I hope that made sense .. I can elaborate. | One possibility would be to expose a web service interface on your inventory management system that allows the transactions used by the web shopfront to be accessed remotely. With a reasonably secure VPN link or ssh tunnel type arrangement, the web shopfront could get stock levels, place orders or execute searches against the inventory system.
Notes:
You would still have to add a reasonable security layer to the inventory service in case the web shopfront was compromised.
You would have to make sure your inventory management application and server was big enough to handle the load, or could be reasonably easily scaled so it could do so.
Your SLA for the inventory application would need to be good enough to support the web shopfront. This probably means some sort of hot failover arrangement. | 1.2 | true | 3 | 88 |
2009-01-28 13:39:54.740 | Inventory Control Across Multiple Servers .. Ideas? | We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it.
This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout.
Our inventory management system runs off a server in the office, while the three websites we currently have (only one actually sells things) runs off an outside source, obviously.
See my problem here? Basically, I am trying to think of ways I can create a central inventory control system that allows both the internal software and external websites to communicate so that inventory is always up to date and we are not selling something we don't have.
Our internal inventory tracking works great and flows well, but I have no idea on how I would implement a solid tracking system that can communicate between the two.
The software is all written in Python, but it does not matter as I am mostly looking for ideas and methods on how would this be implemented.
Thanks in advance for any answers, and I hope that made sense .. I can elaborate. | I'm not sure if there is any one really good solution for your problem. I think the way you are doing it now works fine, but if you don't agree then I don't know what to tell you. | 0 | false | 3 | 88 |
2009-01-29 18:05:22.420 | Reversing a regular expression in Python | I want to reverse a regular expression. I.e. given a regular expression, I want to produce any string that will match that regex.
I know how to do this from a theoretical computer science background using a finite state machine, but I just want to know if someone has already written a library to do this. :)
I'm using Python, so I'd like a Python library.
To reiterate, I only want one string that will match the regex. Things like "." or ".*" would make an infinite amount of strings match the regex, but I don't care about all options.
I'm willing for this library to only work on a certain subset of regex. | Unless your regex is extremely simple (i.e. no stars or pluses), there will be infinitely many strings which match it. If your regex only involves concatenation and alternation, then you can expand each alternation into all of its possibilities, e.g. (foo|bar)(baz|quux) can be expanded into the list ['foobaz', 'fooquux', 'barbaz', 'barquux']. | 0.249709 | false | 1 | 89 |
2009-01-30 18:21:13.493 | What's a good way to keep track of class instance variables in Python? | I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a .h file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?
I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?
Edit: It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly. | First of all: class attributes, or instance attributes? Or both? =)
Usually you just add instance attributes in __init__, and class attributes in the class definition, often before method definitions... which should probably cover 90% of use cases.
If code adds attributes on the fly, it probably (hopefully :-) has good reasons for doing so... leveraging dynamic features, introspection, etc. Other than that, adding attributes this way is probably less common than you think. | 1.2 | true | 5 | 90 |
2009-01-30 18:21:13.493 | What's a good way to keep track of class instance variables in Python? | I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a .h file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?
I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?
Edit: It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly. | The easiest is to use an IDE. PyDev is a plugin for eclipse.
I'm not a full on expert in all ways pythonic, but in general I define my class members right under the class definition in python, so if I add members, they're all relative.
My personal opinion is that class members should be declared in one section, for this specific reason.
Local scoped variables, otoh, should be defined closest to when they are used (except in C--which I believe still requires variables to be declared at the beginning of a method). | 0 | false | 5 | 90 |
2009-01-30 18:21:13.493 | What's a good way to keep track of class instance variables in Python? | I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a .h file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?
I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?
Edit: It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly. | This is a common concern I hear from many programmers who come from a C, C++, or other statically typed language where variables are pre-declared. In fact it was one of the biggest concerns we heard when we were persuading programmers at our organization to abandon C for high-level programs and use Python instead.
In theory, yes you can add instance variables to an object at any time. Yes it can happen from typos, etc. In practice, it rarely results in a bug. When it does, the bugs are generally not hard to find.
As long as your classes are not bloated (1000 lines is pretty huge!) and you have ample unit tests, you should rarely run in to a real problem. In case you do, it's easy to drop to a Python console at almost any time and inspect things as much as you wish. | 0.081452 | false | 5 | 90 |
2009-01-30 18:21:13.493 | What's a good way to keep track of class instance variables in Python? | I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a .h file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?
I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?
Edit: It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly. | Instance variables should be initialized in the class's __init__() method. (In general)
If that's not possible. You can use __dict__ to get a dictionary of all instance variables of an object during runtime. If you really need to track this in documentation add a list of instance variables you are using into the docstring of the class. | 0.16183 | false | 5 | 90 |
2009-01-30 18:21:13.493 | What's a good way to keep track of class instance variables in Python? | I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a .h file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do you keep track of them all?
I'm picturing a scenario where I mistakenly add a new instance variable when I already had one - but it was 1000 lines away from where I was working. Are there standard practices for avoiding this?
Edit: It appears I created some confusion with the term "member variable." I really mean instance variable, and I've edited my question accordingly. | I would say, the standard practice to avoid this is to not write classes where you can be 1000 lines away from anything!
Seriously, that's way too much for just about any useful class, especially in a language that is as expressive as Python. Using more of what the Standard Library offers and abstracting away code into separate modules should help keeping your LOC count down.
The largest classes in the standard library have well below 100 lines! | 0.386912 | false | 5 | 90 |
2009-01-31 01:22:08.137 | How to make python gracefully fail? | I was just wondering how do you make python fail in a user defined way in all possible errors.
For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spits out an ugly error message and stop the whole process. However, I want it to just outputs the error to somewhere together with some context and then move on to the next item.
If anyone can help me with this it would be greatly appreciated!
Thanks a lot!
Jason | all possible errors
The other answers pretty much cover how to make your program gracefully fail, but I'd like to mention one thing -- You don't want to gracefully fail all errors. If you hide all your errors, you won't be shown those which signify that the logic of the program is wrong - namely errors you want to see.
So while it's important to catch your exceptions, make sure you know exactly which exceptions are actually being caught. | 0.16183 | false | 1 | 91 |
2009-02-01 03:37:44.480 | Can I log into a web application automatically using a users windows logon? | On the intranet at my part time job (not IT related) there are various web applications that we use that do not require logging in explicitly. We are required to login to Windows obviously, and that then authenticates us some how.
I'm wondering how this is done? Without worrying about security TOO much, how would I go about authenticating a user to a web application, utilizing the windows login information? I'd be using Python (and Django).
Are there limitations on how this can be achieved? For instance, would a specific browser be required? Would the application and intranet backend have to be hosted at the same location or at least have to communicate? Or is it simply getting the users Windows credentials, and passing that to the authentication software of the web application? | To the best of my knowledge the only browser that automatically passes your login credentials is Internet Explorer. To enable this feature select "Enable Integrated Windows Authentication" in the advanced Internet options dialog under the security section. This is usually enabled by default.
The web server will have to have the Anonymous user permission removed from the web application and enable windows authentication option checked. Simply add the users you want to have access to the web application to the file/folder permissions.
I have only tried this with IIS so I'm not sure if it will work on other web servers. | 0 | false | 1 | 92 |
2009-02-05 04:51:24.623 | Random name generator strategy - help me improve it | I have a small project I am doing in Python using web.py. It's a name generator, using 4 "parts" of a name (firstname, middlename, anothername, surname). Each part of the name is a collection of entites in a MySQL databse (name_part (id, part, type_id), and name_part_type (id, description)). Basic stuff, I guess.
My generator picks a random entry of each "type", and assembles a comical name. Right now, I am using select * from name_part where type_id=[something] order by rand() limit 1 to select a random entry of each type (so I also have 4 queries that run per pageview, I figured this was better than one fat query returning potentially hundreds of rows; if you have a suggestion for how to pull this off in one query w/o a sproc I'll listen).
Obviously I want to make this more random. Actually, I want to give it better coverage, not necessarily randomness. I want to make sure it's using as many possibilities as possible. That's what I am asking in this question, what sorts of strategies can I use to give coverage over a large random sample?
My idea, is to implement a counter column on each name_part, and increment it each time I use it. I would need some logic to then say like: "get a name_part that is less than the highest "counter" for this "name_part_type", unless there are none then pick a random one". I am not very good at SQL, is this kind of logic even possible? The only way I can think to do this would require up to 3 or 4 queries for each part of the name (so up to 12 queries per pageview).
Can I get some input on my logic here? Am I overthinking it? This actually sounds ideal for a stored procedure... but can you guys at least help me solve how to do it without a sproc? (I don't know if I can even use a sproc with the built-in database stuff of web.py).
I hope this isn't terribly dumb but thanks ahead of time.
edit: Aside from my specific problem I am still curious if there are any alternate strategies I can use that may be better. | I agree with your intuition that using a stored procedure is the right way to go, but then, I almost always try to implement database stuff in the database.
In your proc, I would introduce some kind of logic like say, there's only a 30% chance that returning the result will actually increment the counter. Just to increase the variability. | 0.201295 | false | 1 | 93 |
2009-02-05 21:19:20.087 | How to clear the interpreter console? | Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.
Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.
I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do.
Note: I'm running on Windows, so Ctrl+L doesn't work. | I am using Spyder (Python 2.7) and to clean the interpreter console I use either
%clear
that forces the command line to go to the top and I will not see the previous old commands.
or I click "option" on the Console environment and select "Restart kernel" that removes everything. | 0.013605 | false | 7 | 94 |
2009-02-05 21:19:20.087 | How to clear the interpreter console? | Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.
Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.
I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do.
Note: I'm running on Windows, so Ctrl+L doesn't work. | Quickest and easiest way without a doubt is Ctrl+L.
This is the same for OS X on the terminal. | 0.327599 | false | 7 | 94 |
2009-02-05 21:19:20.087 | How to clear the interpreter console? | Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.
Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.
I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do.
Note: I'm running on Windows, so Ctrl+L doesn't work. | If it is on mac, then a simple cmd + k should do the trick. | 0.027204 | false | 7 | 94 |
2009-02-05 21:19:20.087 | How to clear the interpreter console? | Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.
Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.
I've heard about doing a system call and either calling cls on Windows or clear on Linux, but I was hoping there was something I could command the interpreter itself to do.
Note: I'm running on Windows, so Ctrl+L doesn't work. | I found the simplest way is just to close the window and run a module/script to reopen the shell. | 0.013605 | false | 7 | 94 |