Q_CreationDate
stringlengths 23
23
| Title
stringlengths 11
149
| Question
stringlengths 25
6.53k
| Answer
stringlengths 15
5.1k
| Score
float64 -1
1.2
| Is_accepted
bool 2
classes | N_answers
int64 1
17
| Q_Id
int64 0
6.76k
|
---|---|---|---|---|---|---|---|
2010-01-07 17:01:27.297 | Looking for a payment gateway | I'm looking for a payment gateway company so we can avoid tiresome PCI-DSS certification and its associated expenses. I'll get this out the way now, I don't want Paypal. It does what I want but it's really not a company I want to trust with any sort of money.
It needs to support the following flow:
User performs actions on our site, generating an amount that needs to be paid.
Our server contacts the gateway asynchronously (no hidden inputs) and tells it about the user, how much they need to pay. The gateway returns a URL and perhaps a tentative transaction ID.
Our server stores the transaction ID and redirects the user to the URL provided by the gateway.
The user fills out their payment details on the remote server.
When they have completed that, the gateway asynchronously contacts our server with the outcome, transaction id, etc and forwards them back to us (at a predestined URL).
We can show the user their order is complete/failed/etc. Fin.
If at all possible, UK or EU based and developer friendly.
We don't need any concept of a shopping basket as we have that all handled in our code already.
We have (or at least will have by launch) a proper merchant banking account - so cover services like Paypay aren't needed.
If their API covers Python (we're using Django) explicitly, all the better but I think I'm capable enough to decipher any other examples and transcode them into Python myself. | It sounds like you want something like Worldpay or even Google Checkout. But it all depends what your turnover is, because these sorts of providers (who host the payment page themselves), tend to take a percentage of every transaction, rather than a fixed monthly fee that you can get from elsewhere.
The other thing to consider is, if you have any way of taking orders over the phone, and the phone operators need to take customers' credit card details, then your whole internal network will need to be PCI compliant, too.
If you JUST need it for a website, then that makes it easier. If you have a low turnover, then check out the sites mentioned above. If you have a high turnover, then it may work out more cost effective in the long run to get PCI-DSS certified and still keep control of credit card transactions in-house, giving you more flexibility, and cheaper transaction costs. | 0.16183 | false | 3 | 389 |
2010-01-07 17:01:27.297 | Looking for a payment gateway | I'm looking for a payment gateway company so we can avoid tiresome PCI-DSS certification and its associated expenses. I'll get this out the way now, I don't want Paypal. It does what I want but it's really not a company I want to trust with any sort of money.
It needs to support the following flow:
User performs actions on our site, generating an amount that needs to be paid.
Our server contacts the gateway asynchronously (no hidden inputs) and tells it about the user, how much they need to pay. The gateway returns a URL and perhaps a tentative transaction ID.
Our server stores the transaction ID and redirects the user to the URL provided by the gateway.
The user fills out their payment details on the remote server.
When they have completed that, the gateway asynchronously contacts our server with the outcome, transaction id, etc and forwards them back to us (at a predestined URL).
We can show the user their order is complete/failed/etc. Fin.
If at all possible, UK or EU based and developer friendly.
We don't need any concept of a shopping basket as we have that all handled in our code already.
We have (or at least will have by launch) a proper merchant banking account - so cover services like Paypay aren't needed.
If their API covers Python (we're using Django) explicitly, all the better but I think I'm capable enough to decipher any other examples and transcode them into Python myself. | I just finished something exactly like this using First Data Global Gateway (don't really want to provide a link, can find with Google). There's no Python API because their interface is nothing but http POST.
You have the choice of gathering credit card info yourself before posting the form to their server, as long as the connection is SSL and the referring URL is known to them (meaning it's your form but you can't store or process the data first).
In the FDGG gateway "terminal interface" you configure your URL endpoints for authorization accepted/failed and it will POST transaction information.
I can't say it was fun and their "test" mode was buggy but it works. Sorry, don't know if it's available in UK/EU but it's misnamed if it isn't :) | 0.16183 | false | 3 | 389 |
2010-01-07 17:01:27.297 | Looking for a payment gateway | I'm looking for a payment gateway company so we can avoid tiresome PCI-DSS certification and its associated expenses. I'll get this out the way now, I don't want Paypal. It does what I want but it's really not a company I want to trust with any sort of money.
It needs to support the following flow:
User performs actions on our site, generating an amount that needs to be paid.
Our server contacts the gateway asynchronously (no hidden inputs) and tells it about the user, how much they need to pay. The gateway returns a URL and perhaps a tentative transaction ID.
Our server stores the transaction ID and redirects the user to the URL provided by the gateway.
The user fills out their payment details on the remote server.
When they have completed that, the gateway asynchronously contacts our server with the outcome, transaction id, etc and forwards them back to us (at a predestined URL).
We can show the user their order is complete/failed/etc. Fin.
If at all possible, UK or EU based and developer friendly.
We don't need any concept of a shopping basket as we have that all handled in our code already.
We have (or at least will have by launch) a proper merchant banking account - so cover services like Paypay aren't needed.
If their API covers Python (we're using Django) explicitly, all the better but I think I'm capable enough to decipher any other examples and transcode them into Python myself. | You might want to take a look at Adyen (www.adyen.com). They are European and provide a whole lot of features and a very friendly interface. They don't charge a monthly or set up fee and seem to be reasonably priced per transaction.
Their hosted payments page can be completely customised which was an amazing improvement for us. | 1.2 | true | 3 | 389 |
2010-01-07 17:18:28.730 | Running Different Django Versions But Sharing Authentication | Brand new to django. We have a legacy django project using django 0.96x that does authentication, ldap, etc., and it's pretty involved so we don't want to rewrite that code.
We want to add a forum solution (off the shelf) but all of the ones I've seen so far require django 1.x
I'm trying to figure out how to get this working and I've narrowed it down to the following:
Use an old forum solution that works w/django 0.96 (does this exist?)
Try to patch a forum solution to make it "backwards compatible" with 0.96 (possible nightmare)
Use two different djangos: 0.96 and 1.x and (since we're using Apache w/mod_python) have two different Location directives; adjust PYTHONPATH for each appropriately (or use virtualenv, etc.)
But will option #3 even work? I don't know enough about how django.contrib.auth and friends work so if I run two different versions of django will the user stay logged in? I didn't mention trying to patch our 0.96 project to bring it to 1.x but we don't really have the time to do that.
Any suggestions? | It's possible, but it may be pretty painful to do option #3.
How about Option 4: bite the bullet and upgrade to Django 1.1.1. I did this with a couple of 0.97pre sites and it took less time than I thought it would. The biggest pain was dealing with admin stuff. Instead of going with separate admin.py files, we simply put the Admin classes directly below the Model classes.
I use Mercurial for my DVCS and I just cloned, hacked, merged and it worked. It took about 3-5 hours per site and that included some custom template tag munging. | 1.2 | true | 3 | 390 |
2010-01-07 17:18:28.730 | Running Different Django Versions But Sharing Authentication | Brand new to django. We have a legacy django project using django 0.96x that does authentication, ldap, etc., and it's pretty involved so we don't want to rewrite that code.
We want to add a forum solution (off the shelf) but all of the ones I've seen so far require django 1.x
I'm trying to figure out how to get this working and I've narrowed it down to the following:
Use an old forum solution that works w/django 0.96 (does this exist?)
Try to patch a forum solution to make it "backwards compatible" with 0.96 (possible nightmare)
Use two different djangos: 0.96 and 1.x and (since we're using Apache w/mod_python) have two different Location directives; adjust PYTHONPATH for each appropriately (or use virtualenv, etc.)
But will option #3 even work? I don't know enough about how django.contrib.auth and friends work so if I run two different versions of django will the user stay logged in? I didn't mention trying to patch our 0.96 project to bring it to 1.x but we don't really have the time to do that.
Any suggestions? | A user's login status is stored using sessions. As far as I can tell from comparing trunk to the 0.96 source, the sessions are committed to a cookie the same way, and auth stores the user ID and backend the same way, so as long as the two apps use the same session storage and are on the same domain, it should work. (Just to be safe, I wouldn't use secure cookies in case the backend logic has changed - I didn't check out that part.)
However, 0.96 did not feature pluggable session stores like modern Django does. Probably, to get a current version of Django to work with your 0.96 sessions, you would need to write a session backend for the current Django that connects to the 0.96 database and manipulates the sessions there. I'm not sure how well that would work, though. | 0 | false | 3 | 390 |
2010-01-07 17:18:28.730 | Running Different Django Versions But Sharing Authentication | Brand new to django. We have a legacy django project using django 0.96x that does authentication, ldap, etc., and it's pretty involved so we don't want to rewrite that code.
We want to add a forum solution (off the shelf) but all of the ones I've seen so far require django 1.x
I'm trying to figure out how to get this working and I've narrowed it down to the following:
Use an old forum solution that works w/django 0.96 (does this exist?)
Try to patch a forum solution to make it "backwards compatible" with 0.96 (possible nightmare)
Use two different djangos: 0.96 and 1.x and (since we're using Apache w/mod_python) have two different Location directives; adjust PYTHONPATH for each appropriately (or use virtualenv, etc.)
But will option #3 even work? I don't know enough about how django.contrib.auth and friends work so if I run two different versions of django will the user stay logged in? I didn't mention trying to patch our 0.96 project to bring it to 1.x but we don't really have the time to do that.
Any suggestions? | It's possible to expose Django 0.96 tables to 1.1 - you can use unmanaged models wrapped around database VIEWs. In other words you issue:
CREATE VIEW auth_user AS SELECT * from django096db.auth_user;
(and similar cmd for other tables)
and then you have Django 1.1 synchronized with 0.96 (assuming 0.96 tables are compatible with 1.1, I haven't checked that). | 0 | false | 3 | 390 |
2010-01-12 04:28:37.153 | Creating waitable objects in Python | I more or less know how to use select() to take a list of sockets, and only return the ones that are ready to read/write something. The project I'm working on now has a class called 'user'. Each 'user' object contains its own socket. What I would like to do is pass a list of users to a select(), and get back a list of only the users where user.socket is ready to read/write. Any thoughts on where to start on this?
Edit: Changed switch() to select(). I need to proofread better. | You should have your User class implement a fileno(self) method which returns self.thesocket.fileno() -- that's the way to make select work on your own classes (sockets only on windows, arbitrary files on Unix-like systems). Not sure what switch is supposed to me -- don't recognize it as a standard library (or built-in) Python concept...? | 1.2 | true | 1 | 391 |
2010-01-15 00:04:59.403 | key/value (general) and tokyo cabinet (python tc-specific) question | i have been in the RDBMS world for many years now but wish to explore the whole nosql movement. so here's my first question:
is it bad practice to have the possibility of duplicate keys? for example, an address book keyed off of last name (most probably search item?) could have multiple entities. is it bad practice to use the last name then? is the key supposed to be the most "searchable" definition of the entity? are there any resources for "best practices" in this whole new world (for me)?
i'm intrigued by tokyo cabinet (and specifically the tc interface) but don't know how to iterate through different entities that have the same key (e.g. see above). i can only get the first entity. anyway, thanks in advance for the help | This depend on no-sql implementation. Cassandra, for example, allows range queries, so you could model data to do queries on last name, or with full name (starting with last name, then first name).
Beyond this, many simpler key-value stores would indeed require you to store a list structure (or such) for multi-valued entries. Whether this is feasible or not depends on expected number of "duplicates" -- with last name, number could be rather high I presume, so it does not sound like an ideal model for many cases. | 1.2 | true | 1 | 392 |
2010-01-15 05:46:23.317 | Not showing focus in wxPython? | I don't know if this is a stupid question, but is there any way to not show focus in wxPython? For example, I built a simple GUI with a few buttons and I don't want the dotted rectangle to show up on the button I have just clicked.
If I remember correctly in Excel VBA you could just set TakeFocusOnClick tag to False. What would be the equivalent in wxPython? | You could also give the focus to another control in your event handler for the buttons. Just call the SetFocus() method on any other control. This might make your application more usable as a side effect if you for example return focus to a text field that is likely to be typed in next. | 0 | false | 1 | 393 |
2010-01-15 19:08:22.297 | How to speedup python unittest on muticore machines? | I'm using python unittest in order to test some other external application but it takes too much time to run the test one by one.
I would like to know how can I speedup this process by using the power of multi-cores.
Can I tweak unittest to execute tests in parallel? How?
This question is not able python GIL limitation because in fact not the python code takes time but the external application that I execute, currently via os.system(). | As the @vinay-sajip suggested, a few non-core python packages like py.test and nose provided parallel execution of unit tests via multiprocessing lib right out of the box.
However, one thing to consider is that if you are testing a web app with database backend and majority of your test cases are relying on connecting to the same test database, then your unit test execution speed is bottlenecked on the DB not I/O per se. And using multiprocess won't speed it up.
Given that each unit test case requires an independent setup of the database schema + data, you cannot scale out the execution speed only on CPU but restricted with a single test database connection to a single test database server (otherwise the state of the data may interfere with other other while parallel executing each test case so on and so forth). | 0 | false | 1 | 394 |
2010-01-16 09:27:22.083 | Generating non-repeating random numbers in Python | Ok this is one of those trickier than it sounds questions so I'm turning to stack overflow because I can't think of a good answer. Here is what I want: I need Python to generate a simple a list of numbers from 0 to 1,000,000,000 in random order to be used for serial numbers (using a random number so that you can't tell how many have been assigned or do timing attacks as easily, i.e. guessing the next one that will come up). These numbers are stored in a database table (indexed) along with the information linked to them. The program generating them doesn't run forever so it can't rely on internal state.
No big deal right? Just generate a list of numbers, shove them into an array and use Python "random.shuffle(big_number_array)" and we're done. Problem is I'd like to avoid having to store a list of numbers (and thus read the file, pop one off the top, save the file and close it). I'd rather generate them on the fly. Problem is that the solutions I can think of have problems:
1) Generate a random number and then check if it has already been used. If it has been used generate a new number, check, repeat as needed until I find an unused one. Problem here is that I may get unlucky and generate a lot of used numbers before getting one that is unused. Possible fix: use a very large pool of numbers to reduce the chances of this (but then I end up with silly long numbers).
2) Generate a random number and then check if it has already been used. If it has been used add or subtract one from the number and check again, keep repeating until I hit an unused number. Problem is this is no longer a random number as I have introduced bias (eventually I will get clumps of numbers and you'd be able to predict the next number with a better chance of success).
3) Generate a random number and then check if it has already been used. If it has been used add or subtract another randomly generated random number and check again, problem is we're back to simply generating random numbers and checking as in solution 1.
4) Suck it up and generate the random list and save it, have a daemon put them into a Queue so there are numbers available (and avoid constantly opening and closing a file, batching it instead).
5) Generate much larger random numbers and hash them (i.e. using MD5) to get a smaller numeric value, we should rarely get collisions, but I end up with larger than needed numbers again.
6) Prepend or append time based information to the random number (i.e. unix timestamp) to reduce chances of a collision, again I get larger numbers than I need.
Anyone have any clever ideas that will reduce the chances of a "collision" (i.e. generating a random number that is already taken) but will also allow me to keep the number "small" (i.e. less than a billion (or a thousand million for your europeans =)).
Answer and why I accepted it:
So I will simply go with 1, and hope it's not an issue, however if it is I will go with the deterministic solution of generating all the numbers and storing them so that there is a guarentee of getting a new random number, and I can use "small" numbers (i.e. 9 digits instead of an MD5/etc.). | You can run 1) without running into the problem of too many wrong random numbers if you just decrease the random interval by one each time.
For this method to work, you will need to save the numbers already given (which you want to do anyway) and also save the quantity of numbers taken.
It is pretty obvious that, after having collected 10 numbers, your pool of possible random numbers will have been decreased by 10. Therefore, you must not choose a number between 1 and 1.000.000 but between 1 an 999.990. Of course this number is not the real number but only an index (unless the 10 numbers collected have been 999.991, 999.992, …); you’d have to count now from 1 omitting all the numbers already collected.
Of course, your algorithm should be smarter than just counting from 1 to 1.000.000 but I hope you understand the method.
I don’t like drawing random numbers until I get one which fits either. It just feels wrong. | 0.024005 | false | 5 | 395 |
2010-01-16 09:27:22.083 | Generating non-repeating random numbers in Python | Ok this is one of those trickier than it sounds questions so I'm turning to stack overflow because I can't think of a good answer. Here is what I want: I need Python to generate a simple a list of numbers from 0 to 1,000,000,000 in random order to be used for serial numbers (using a random number so that you can't tell how many have been assigned or do timing attacks as easily, i.e. guessing the next one that will come up). These numbers are stored in a database table (indexed) along with the information linked to them. The program generating them doesn't run forever so it can't rely on internal state.
No big deal right? Just generate a list of numbers, shove them into an array and use Python "random.shuffle(big_number_array)" and we're done. Problem is I'd like to avoid having to store a list of numbers (and thus read the file, pop one off the top, save the file and close it). I'd rather generate them on the fly. Problem is that the solutions I can think of have problems:
1) Generate a random number and then check if it has already been used. If it has been used generate a new number, check, repeat as needed until I find an unused one. Problem here is that I may get unlucky and generate a lot of used numbers before getting one that is unused. Possible fix: use a very large pool of numbers to reduce the chances of this (but then I end up with silly long numbers).
2) Generate a random number and then check if it has already been used. If it has been used add or subtract one from the number and check again, keep repeating until I hit an unused number. Problem is this is no longer a random number as I have introduced bias (eventually I will get clumps of numbers and you'd be able to predict the next number with a better chance of success).
3) Generate a random number and then check if it has already been used. If it has been used add or subtract another randomly generated random number and check again, problem is we're back to simply generating random numbers and checking as in solution 1.
4) Suck it up and generate the random list and save it, have a daemon put them into a Queue so there are numbers available (and avoid constantly opening and closing a file, batching it instead).
5) Generate much larger random numbers and hash them (i.e. using MD5) to get a smaller numeric value, we should rarely get collisions, but I end up with larger than needed numbers again.
6) Prepend or append time based information to the random number (i.e. unix timestamp) to reduce chances of a collision, again I get larger numbers than I need.
Anyone have any clever ideas that will reduce the chances of a "collision" (i.e. generating a random number that is already taken) but will also allow me to keep the number "small" (i.e. less than a billion (or a thousand million for your europeans =)).
Answer and why I accepted it:
So I will simply go with 1, and hope it's not an issue, however if it is I will go with the deterministic solution of generating all the numbers and storing them so that there is a guarentee of getting a new random number, and I can use "small" numbers (i.e. 9 digits instead of an MD5/etc.). | I think you are overestimating the problems with approach 1). Unless you have hard-realtime requirements just checking by random choice terminates rather fast. The probability of needing more than a number of iterations decays exponentially. With 100M numbers outputted (10% fillfactor) you'll have one in billion chance of requiring more than 9 iterations. Even with 50% of numbers taken you'll on average need 2 iterations and have one in a billion chance of requiring more than 30 checks. Or even the extreme case where 99% of the numbers are already taken might still be reasonable - you'll average a 100 iterations and have 1 in a billion change of requiring 2062 iterations | 0.119475 | false | 5 | 395 |
2010-01-16 09:27:22.083 | Generating non-repeating random numbers in Python | Ok this is one of those trickier than it sounds questions so I'm turning to stack overflow because I can't think of a good answer. Here is what I want: I need Python to generate a simple a list of numbers from 0 to 1,000,000,000 in random order to be used for serial numbers (using a random number so that you can't tell how many have been assigned or do timing attacks as easily, i.e. guessing the next one that will come up). These numbers are stored in a database table (indexed) along with the information linked to them. The program generating them doesn't run forever so it can't rely on internal state.
No big deal right? Just generate a list of numbers, shove them into an array and use Python "random.shuffle(big_number_array)" and we're done. Problem is I'd like to avoid having to store a list of numbers (and thus read the file, pop one off the top, save the file and close it). I'd rather generate them on the fly. Problem is that the solutions I can think of have problems:
1) Generate a random number and then check if it has already been used. If it has been used generate a new number, check, repeat as needed until I find an unused one. Problem here is that I may get unlucky and generate a lot of used numbers before getting one that is unused. Possible fix: use a very large pool of numbers to reduce the chances of this (but then I end up with silly long numbers).
2) Generate a random number and then check if it has already been used. If it has been used add or subtract one from the number and check again, keep repeating until I hit an unused number. Problem is this is no longer a random number as I have introduced bias (eventually I will get clumps of numbers and you'd be able to predict the next number with a better chance of success).
3) Generate a random number and then check if it has already been used. If it has been used add or subtract another randomly generated random number and check again, problem is we're back to simply generating random numbers and checking as in solution 1.
4) Suck it up and generate the random list and save it, have a daemon put them into a Queue so there are numbers available (and avoid constantly opening and closing a file, batching it instead).
5) Generate much larger random numbers and hash them (i.e. using MD5) to get a smaller numeric value, we should rarely get collisions, but I end up with larger than needed numbers again.
6) Prepend or append time based information to the random number (i.e. unix timestamp) to reduce chances of a collision, again I get larger numbers than I need.
Anyone have any clever ideas that will reduce the chances of a "collision" (i.e. generating a random number that is already taken) but will also allow me to keep the number "small" (i.e. less than a billion (or a thousand million for your europeans =)).
Answer and why I accepted it:
So I will simply go with 1, and hope it's not an issue, however if it is I will go with the deterministic solution of generating all the numbers and storing them so that there is a guarentee of getting a new random number, and I can use "small" numbers (i.e. 9 digits instead of an MD5/etc.). | Do you need this to be cryptographically secure or just hard to guess? How bad are collisions? Because if it needs to be cryptographically strong and have zero collisions, it is, sadly, impossible. | 0 | false | 5 | 395 |
2010-01-16 09:27:22.083 | Generating non-repeating random numbers in Python | Ok this is one of those trickier than it sounds questions so I'm turning to stack overflow because I can't think of a good answer. Here is what I want: I need Python to generate a simple a list of numbers from 0 to 1,000,000,000 in random order to be used for serial numbers (using a random number so that you can't tell how many have been assigned or do timing attacks as easily, i.e. guessing the next one that will come up). These numbers are stored in a database table (indexed) along with the information linked to them. The program generating them doesn't run forever so it can't rely on internal state.
No big deal right? Just generate a list of numbers, shove them into an array and use Python "random.shuffle(big_number_array)" and we're done. Problem is I'd like to avoid having to store a list of numbers (and thus read the file, pop one off the top, save the file and close it). I'd rather generate them on the fly. Problem is that the solutions I can think of have problems:
1) Generate a random number and then check if it has already been used. If it has been used generate a new number, check, repeat as needed until I find an unused one. Problem here is that I may get unlucky and generate a lot of used numbers before getting one that is unused. Possible fix: use a very large pool of numbers to reduce the chances of this (but then I end up with silly long numbers).
2) Generate a random number and then check if it has already been used. If it has been used add or subtract one from the number and check again, keep repeating until I hit an unused number. Problem is this is no longer a random number as I have introduced bias (eventually I will get clumps of numbers and you'd be able to predict the next number with a better chance of success).
3) Generate a random number and then check if it has already been used. If it has been used add or subtract another randomly generated random number and check again, problem is we're back to simply generating random numbers and checking as in solution 1.
4) Suck it up and generate the random list and save it, have a daemon put them into a Queue so there are numbers available (and avoid constantly opening and closing a file, batching it instead).
5) Generate much larger random numbers and hash them (i.e. using MD5) to get a smaller numeric value, we should rarely get collisions, but I end up with larger than needed numbers again.
6) Prepend or append time based information to the random number (i.e. unix timestamp) to reduce chances of a collision, again I get larger numbers than I need.
Anyone have any clever ideas that will reduce the chances of a "collision" (i.e. generating a random number that is already taken) but will also allow me to keep the number "small" (i.e. less than a billion (or a thousand million for your europeans =)).
Answer and why I accepted it:
So I will simply go with 1, and hope it's not an issue, however if it is I will go with the deterministic solution of generating all the numbers and storing them so that there is a guarentee of getting a new random number, and I can use "small" numbers (i.e. 9 digits instead of an MD5/etc.). | I'd rethink the problem itself... You don't seem to be doing anything sequential with the numbers... and you've got an index on the column which has them. Do they actually need to be numbers?
Consider a sha hash... you don't actually need the entire thing. Do what git or other url shortening services do, and take first 3/4/5 characters of the hash. Given that each character now has 36 possible values instead of 10, you have 2,176,782,336 combinations instead of 999,999 combinations (for six digits). Combine that with a quick check on whether the combination exists (a pure index query) and a seed like a timestamp + random number and it should do for almost any situation. | 0 | false | 5 | 395 |
2010-01-16 09:27:22.083 | Generating non-repeating random numbers in Python | Ok this is one of those trickier than it sounds questions so I'm turning to stack overflow because I can't think of a good answer. Here is what I want: I need Python to generate a simple a list of numbers from 0 to 1,000,000,000 in random order to be used for serial numbers (using a random number so that you can't tell how many have been assigned or do timing attacks as easily, i.e. guessing the next one that will come up). These numbers are stored in a database table (indexed) along with the information linked to them. The program generating them doesn't run forever so it can't rely on internal state.
No big deal right? Just generate a list of numbers, shove them into an array and use Python "random.shuffle(big_number_array)" and we're done. Problem is I'd like to avoid having to store a list of numbers (and thus read the file, pop one off the top, save the file and close it). I'd rather generate them on the fly. Problem is that the solutions I can think of have problems:
1) Generate a random number and then check if it has already been used. If it has been used generate a new number, check, repeat as needed until I find an unused one. Problem here is that I may get unlucky and generate a lot of used numbers before getting one that is unused. Possible fix: use a very large pool of numbers to reduce the chances of this (but then I end up with silly long numbers).
2) Generate a random number and then check if it has already been used. If it has been used add or subtract one from the number and check again, keep repeating until I hit an unused number. Problem is this is no longer a random number as I have introduced bias (eventually I will get clumps of numbers and you'd be able to predict the next number with a better chance of success).
3) Generate a random number and then check if it has already been used. If it has been used add or subtract another randomly generated random number and check again, problem is we're back to simply generating random numbers and checking as in solution 1.
4) Suck it up and generate the random list and save it, have a daemon put them into a Queue so there are numbers available (and avoid constantly opening and closing a file, batching it instead).
5) Generate much larger random numbers and hash them (i.e. using MD5) to get a smaller numeric value, we should rarely get collisions, but I end up with larger than needed numbers again.
6) Prepend or append time based information to the random number (i.e. unix timestamp) to reduce chances of a collision, again I get larger numbers than I need.
Anyone have any clever ideas that will reduce the chances of a "collision" (i.e. generating a random number that is already taken) but will also allow me to keep the number "small" (i.e. less than a billion (or a thousand million for your europeans =)).
Answer and why I accepted it:
So I will simply go with 1, and hope it's not an issue, however if it is I will go with the deterministic solution of generating all the numbers and storing them so that there is a guarentee of getting a new random number, and I can use "small" numbers (i.e. 9 digits instead of an MD5/etc.). | The standard Linear Congruential random number generator's seed sequence CANNOT repeat until the full set of numbers from the starting seed value have been generated. Then it MUST repeat precisely.
The internal seed is often large (48 or 64 bits). The generated numbers are smaller (32 bits usually) because the entire set of bits are not random. If you follow the seed values they will form a distinct non-repeating sequence.
The question is essentially one of locating a good seed that generates "enough" numbers. You can pick a seed, and generate numbers until you get back to the starting seed. That's the length of the sequence. It may be millions or billions of numbers.
There are some guidelines in Knuth for picking suitable seeds that will generate very long sequences of unique numbers. | 0.095744 | false | 5 | 395 |
2010-01-16 13:58:20.070 | DB a table for the category and another table for the subcategory with similar fields, why? | I recently joined a new company and the development team was in the progress of a project to rebuild the database categories structure as follows:
if we have category and subcategory for items, like food category and italian food category in food category.
They were building a table for each category, instead of having one table and a link to the category id.
Now we have a table called food
and another table called food_italian
and both tables contain the same fields.
I have asked around and it seems that some DBA prefers this design. I would like to know why? and how this design can improve the performance? | First, the most obvious answer is that you should ask them, not us, since I can tell you this, that design seems bogus deluxe.
The only reason I can come up with is that you have inexperienced DBA's that does not know how to performance-tune a database, and seems to think that a table with less rows will always vastly outperform a table with more rows.
With good indices, that need not be the case. | 0.386912 | false | 1 | 396 |
2010-01-18 05:30:36.243 | How would I discover the memory used by an application through a python script? | Recently I've found myself testing an aplication in Froglogic's Squish, using Python to create test scripts. Just the other day, the question of how much memory the program is using has come up, and I've found myself unable to answer it.
It seems reasonable to assume that there's a way to query the os (windows 7) API for the information, but I've no idea where to begin. Does anyone know how I'd go about this? | Remember that Squish allows remote testing of the application. A system parameter queried via Python directly will only apply to the case of local testing.
An approach that works in either case is to call the currentApplicationContext() function that will give you a handle to the Application Under Test. It has a usedMemory property you can query. I don't recall which process property exactly is being queried but it should provide a rough indication. | 0 | false | 2 | 397 |
2010-01-18 05:30:36.243 | How would I discover the memory used by an application through a python script? | Recently I've found myself testing an aplication in Froglogic's Squish, using Python to create test scripts. Just the other day, the question of how much memory the program is using has come up, and I've found myself unable to answer it.
It seems reasonable to assume that there's a way to query the os (windows 7) API for the information, but I've no idea where to begin. Does anyone know how I'd go about this? | In command line: tasklist /FO LIST and parse the results?
Sorry, I don't know a Pythonic way. =P | -0.135221 | false | 2 | 397 |
2010-01-18 10:55:11.800 | populating data from xml file to a sqlite database using python | I have a question related to some guidances to solve a problem. I have with me an xml file, I have to populate it into a database system (whatever, it might be sqlite, mysql) using scripting language: Python.
Does anyone have any idea on how to proceed?
Which technologies I need to read further?
Which environments I have to install?
Any tutorials on the same topic?
I already tried to parse xml using both by tree-based and sax method in other language, but to start with Python, I don't know where to start. I already know how to design the database I need.
Another question, is Python alone possible of executing database ddl queries? | If you are accustomed to DOM (tree) access to xml from other language, you may find useful these standard library modules (and their respective docs):
xml.dom
xml.dom.minidom
To save tha data to DB, you can use standard module sqlite3 or look for binding to mysql. Or you may wish to use something more abstract, like SQLAlchemy or Django's ORM. | 0.101688 | false | 1 | 398 |
2010-01-18 15:17:06.783 | How can I determine if a python script is executed from crontab? | I would like to know how can I determine if a python script is executed from crontab?
I don't want a solution that will require adding a parameter because I want to be able to detect this even from an imported module (not the main script). | Not quite what you asked, but maybe what you want is os.isatty(sys.stdout.fileno()), which tells if stdout is connected to (roughly speaking) a terminal. It will be false if you pipe the output to a file or another process, or if the process is run from cron. | 1.2 | true | 4 | 399 |
2010-01-18 15:17:06.783 | How can I determine if a python script is executed from crontab? | I would like to know how can I determine if a python script is executed from crontab?
I don't want a solution that will require adding a parameter because I want to be able to detect this even from an imported module (not the main script). | If you want to detect this from an imported module, I would have the main program set a global variable in the module, which would output different things depending on the value of this global variable (and have the main program decide how to set the variable through a flag that you would use in your crontab). This is quite robust (comparing to studying PPIDs). | 0 | false | 4 | 399 |
2010-01-18 15:17:06.783 | How can I determine if a python script is executed from crontab? | I would like to know how can I determine if a python script is executed from crontab?
I don't want a solution that will require adding a parameter because I want to be able to detect this even from an imported module (not the main script). | An easier workaround would be to pass a flag to the script only from the crontab, like --crontab, and then just check for that flag. | 0.067922 | false | 4 | 399 |
2010-01-18 15:17:06.783 | How can I determine if a python script is executed from crontab? | I would like to know how can I determine if a python script is executed from crontab?
I don't want a solution that will require adding a parameter because I want to be able to detect this even from an imported module (not the main script). | Set an environment variable at the cron command invocation. That works even within a module, as you can just check os.getenv(). | 0.327599 | false | 4 | 399 |
2010-01-18 23:31:34.390 | Streaming Ironpython output to my editor | We embed ironpython in our app sob that scripts can be executed in the context of our application.
I use Python.CreateEngine() and ScriptScope.Execute() to execute python scripts.
We have out own editor(written in C#) that can load ironpython scripts and run it.
There are 2 problems I need to solve.
If I have a print statement in ironpython script, how can i show it my editor(how will I tell python engine to redirect output to some handler in my C# code)
I plan to use unittest.py for running unittest. When I run the following
runner = unittest.TextTestRunner()
runner.run(testsuite)
the output is redirected to standard output but need a way for it to be redirected to my C# editor output window so that user can see the results.
This question might be related to 1
Any help is appreciated
G | You can provide a custom Stream or TextWriter which will be used for all output. You can provide those by using one of the ScriptRuntime.IO.SetOutput overloads. Your implementation of Stream or TextWriter should receive the strings and then output them to your editor window (potentially marshalling back onto the UI thread if you're running the script on a 2ndary execution thread). | 0.673066 | false | 1 | 400 |
2010-01-19 04:35:22.960 | What is the maximum packet size a python socket can handle? | i am new to network programming in python. I wanted to know that what is the maximum size packet we can transmit or receive on python socket? and how to find out it? | I don't think there's any Python-specific limits. UDP packets have a theoretical limit of circa 65kb and TCP no upper limit, but you'll have flow control problems if you use packets much more than a few kilobytes. | 0.135221 | false | 1 | 401 |
2010-01-21 03:58:43.267 | Limit a single record in model for django app? | I want use a model to save the system setting for a django app, So I want to limit the model can only have one record, how to do the limit? | An easy way is to use the setting's name as the primary key in the settings table. There can't be more than one record with the same primary key, so that will allow both Django and the database to guarantee integrity. | 1.2 | true | 1 | 402 |
2010-01-23 01:06:04.163 | Can Someone Explain Threads to Me? | I have been considering adding threaded procedures to my application to speed up execution, but the problem is that I honestly have no idea how to use threads, or what is considered "thread safe". For example, how does a game engine utilize threads in its rendering processes, or in what contexts would threads only be considered nothing but a hindrance? Can someone point the way to some resources to help me learn more or explain here? | There are four things you should know about threads.
Threads are like processes, but they share memory.
Threads often have hardware, OS, and language support, which might make them better than processes.
There are lots of fussy little things that threads need to support (like locks and semaphores) so they don't get the memory they share into an inconsistent state. This makes them a little difficult to use.
Locking isn't automatic (in the languages I know), so you have to be very careful with the memory they (implicitly) share. | 0.081452 | false | 5 | 403 |
2010-01-23 01:06:04.163 | Can Someone Explain Threads to Me? | I have been considering adding threaded procedures to my application to speed up execution, but the problem is that I honestly have no idea how to use threads, or what is considered "thread safe". For example, how does a game engine utilize threads in its rendering processes, or in what contexts would threads only be considered nothing but a hindrance? Can someone point the way to some resources to help me learn more or explain here? | Well someone will probably answer this better, but threads are for the purpose of having background processing that won't freeze the user interface. You don't want to stop accepting keyboard input or mouse input, and tell the user, "just a moment, I want to finish this computation, it will only be a few more seconds." (And yet its amazing how many times commercial programs do this.
As far as thread safe, it means a function that does not have some internal saved state. If it did you couldn't have multiple threads using it simutaneously.
As far as thread programming you just have to start doing it, and then you'll start encountering various issues unique to thread programming, for example simultaneuous access to data, in which case you have to decide to use some syncronization method such as critical sections or mutexes or something else, each one having slightly different nuances in their behavior.
As far as the differences between processes and threads (which you didn't ask) processes are an OS level entity, whereas threads are associated with a program. In certain instances your program may want to create a process rather than a thread. | 0.040794 | false | 5 | 403 |
2010-01-23 01:06:04.163 | Can Someone Explain Threads to Me? | I have been considering adding threaded procedures to my application to speed up execution, but the problem is that I honestly have no idea how to use threads, or what is considered "thread safe". For example, how does a game engine utilize threads in its rendering processes, or in what contexts would threads only be considered nothing but a hindrance? Can someone point the way to some resources to help me learn more or explain here? | This is a very broad topic. But here are the things I would want to know if I knew nothing about threads:
They are units of execution within a single process that happen "in parallel" - what this means is that the current unit of execution in the processor switches rapidly. This can be achieved via different means. Switching is called "context switching", and there is some overhead associated with this.
They can share memory! This is where problems can occur. I talk about this more in depth in a later bullet point.
The benefit of parallelizing your application is that logic that uses different parts of the machine can happen simultaneously. That is, if part of your process is I/O-bound and part of it is CPU-bound, the I/O intensive operation doesn't have to wait until the CPU-intensive operation is done. Some languages also allow you to run threads at the same time if you have a multicore processor (and thus parallelize CPU-intensive operations as well), though this is not always the case.
Thread-safe means that there are no race conditions, which is the term used for problems that occur when the execution of your process depends on timing (something you don't want to rely on). For example, if you have threads A and B both incrementing a shared counter C, you could see the case where A reads the value of C, then B reads the value of C, then A overwrites C with C+1, then B overwrites C with C+1. Notice that C only actually increments once!
A couple of common ways avoid race conditions include synchronization, which excludes mutual access to shared state, or just not having any shared state at all. But this is just the tip of the iceberg - thread-safety is quite a broad topic.
I hope that helps! Understand that this was a very quick introduction to something that requires a good bit of learning. I would recommend finding a resource about multithreading in your preferred language, whatever that happens to be, and giving it a thorough read. | 1.2 | true | 5 | 403 |
2010-01-23 01:06:04.163 | Can Someone Explain Threads to Me? | I have been considering adding threaded procedures to my application to speed up execution, but the problem is that I honestly have no idea how to use threads, or what is considered "thread safe". For example, how does a game engine utilize threads in its rendering processes, or in what contexts would threads only be considered nothing but a hindrance? Can someone point the way to some resources to help me learn more or explain here? | Threads don't speed up applications. Algorithms speed up applications. Threads can be used in algorithms, if appropriate. | 0.040794 | false | 5 | 403 |
2010-01-23 01:06:04.163 | Can Someone Explain Threads to Me? | I have been considering adding threaded procedures to my application to speed up execution, but the problem is that I honestly have no idea how to use threads, or what is considered "thread safe". For example, how does a game engine utilize threads in its rendering processes, or in what contexts would threads only be considered nothing but a hindrance? Can someone point the way to some resources to help me learn more or explain here? | Threads are simply a way of executing multiple things simultaneously (assuming that the platform on which they are being run is capable of parallel execution). Thread safety is simply (well, nothing with threads is truly simple) making sure that the threads don't affect each other in harmful ways.
In general, you are unlikely to see systems use multiple threads for rendering graphics on the screen due to the multiple performance implications and complexity issues that may arise from that. Other tasks related to state management (or AI) can potentially be moved to separate threads however. | 0.040794 | false | 5 | 403 |
2010-01-23 13:27:09.017 | python threading/fork? | I'm making a python script that needs to do 3 things simultaneously.
What is a good way to achieve this as do to what i've heard about the GIL i'm not so lean into using threads anymore.
2 of the things that the script needs to do will be heavily active, they will have lots of work to do and then i need to have the third thing reporting to the user over a socket when he asks (so it will be like a tiny server) about the status of the other 2 processes.
Now my question is what would be a good way to achieve this? I don't want to have three different script and also due to GIL using threads i think i won't get much performance and i'll make things worse.
Is there a fork() for python like in C so from my script so fork 2 processes that will do their job and from the main process to report to the user? And how can i communicate from the forked processes with the main process?
LE:: to be more precise 1thread should get email from a imap server and store them into a database, another thread should get messages from db that needs to be sent and then send them and the main thread should be a tiny http server that will just accept one url and will show the status of those two threads in json format. So are threads oK? will the work be done simultaneously or due to the gil there will be performance issues? | The GIL is really only something to care about if you want to do multiprocessing, that is spread the load over several cores/processors. If that is the case, and it kinda sounds like it from your description, use multiprocessing.
If you just need to do three things "simultaneously" in that way that you need to wait in the background for things to happen, then threads are just fine. That's what threads are for in the first place. 8-I) | 0.386912 | false | 1 | 404 |
2010-01-23 19:12:57.393 | how to generate permutations of array in python? | i have an array of 27 elements,and i don't want to generate all permutations of array (27!)
i need 5000 randomly choosed permutations,any tip will be useful... | You may want the itertools.permutations() function. Gotta love that itertools module!
NOTE: New in 2.6 | 0.067922 | false | 1 | 405 |
2010-01-24 17:17:40.100 | TextMate and Django Integration - Supporting {% %} markup | I have installed a TextMate bundle that I believe enables the ability for automatic closing of the "{{" markup (so that it will automatically close the markup with "}}"), but this does not seem to be possible with the other markup that uses "{%" and "%}".
So, I was wondering if anyone out there knows how to get TextMate to add the automatic closing tags for the {% %} just like is already done with {{ }}.
Any help is appreciated! | I don't think that's possible, but the Django bundle for TextMate does allow you to insert the opening and closing tags in one go, placing the cursor in the middle, with ctrl-% (ctrl-shift-5).
Click the Bundles -> Python Django Templates menu to see all the shortcuts that are available. | 0.201295 | false | 2 | 406 |
2010-01-24 17:17:40.100 | TextMate and Django Integration - Supporting {% %} markup | I have installed a TextMate bundle that I believe enables the ability for automatic closing of the "{{" markup (so that it will automatically close the markup with "}}"), but this does not seem to be possible with the other markup that uses "{%" and "%}".
So, I was wondering if anyone out there knows how to get TextMate to add the automatic closing tags for the {% %} just like is already done with {{ }}.
Any help is appreciated! | It's possible - the Rails bundle does this for ERB (<% automatically gets closing %> tags).
So that's a place you could go look. | 0.386912 | false | 2 | 406 |
2010-01-26 18:19:45.357 | Stored Procedures in Python for PostgreSQL | we are still pretty new to Postgres and came from Microsoft Sql Server.
We are wanting to write some stored procedures now. Well, after struggling to get something more complicated than a hello world to work in pl/pgsql, we decided it's better if we are going to learn a new language we might as well learn Python because we got the same query working in it in about 15 minutes(note, none of us actually know python).
So I have some questions about it in comparison to pl/psql.
Is pl/Pythonu slower than pl/pgsql?
Is there any kind of "good" reference for how to write good stored procedures using it? Five short pages in the Postgres documentation doesn't really tell us enough.
What about query preparation? Should it always be used?
If we use the SD and GD arrays for a lot of query plans, will it ever get too full or have a negative impact on the server? Will it automatically delete old values if it gets too full?
Is there any hope of it becoming a trusted language?
Also, our stored procedure usage is extremely light. Right now we only have 4, but we are still trying to convert little bits of code over from Sql Server specific syntax(such as variables, which can't be used in Postgres outside of stored procedures) | Depends on what operations you're doing.
Well, combine that with a general Python documentation, and that's about what you have.
No. Again, depends on what you're doing. If you're only going to run a query once, no point in preparing it separately.
If you are using persistent connections, it might. But they get cleared out whenever a connection is closed.
Not likely. Sandboxing is broken in Python and AFAIK nobody is really interested in fixing it. I heard someone say that python-on-parrot may be the most viable way, once we have pl/parrot (which we don't yet).
Bottom line though - if your stored procedures are going to do database work, use pl/pgsql. Only use pl/python if you are going to do non-database stuff, such as talking to external libraries. | 1.2 | true | 1 | 407 |
2010-01-28 05:19:13.613 | how to find time at particular timezone from anywhere | I need to know the current time at CDT when my Python script is run. However this script will be run in multiple different timezones so a simple offset won't work.
I only need a solution for Linux, but a cross platform solution would be ideal. | You can use time.gmtime() to get time GMT (UTC) from any machine no matter the timezone, then you can apply your offset. | 1.2 | true | 1 | 408 |
2010-01-30 17:48:45.377 | How can I create my own corpus in the Python Natural Language Toolkit? | I have recently expanded the names corpus in nltk and would like to know how I can turn the two files I have (male.txt, female.txt) in to a corpus so I can access them using the existing nltk.corpus methods. Does anyone have any suggestions?
Many thanks,
James. | Came to understand how corpus reading works by looking at the source code in nltk.corpus and then looking at the corpora (located in /home/[user]/nltk_data/corpora/names - this will probably be in My Documents for XP and somewhere in User for Win7 users).
The structure of the corpus and its related function will give a good understanding of how to use the different corpora available in NLTK.
In my case I looked at the names variable in nltk.corpus' source code and was interested in the WordListCorpusReader function as the names corpus is simply a list of words. | 0.135221 | false | 2 | 409 |
2010-01-30 17:48:45.377 | How can I create my own corpus in the Python Natural Language Toolkit? | I have recently expanded the names corpus in nltk and would like to know how I can turn the two files I have (male.txt, female.txt) in to a corpus so I can access them using the existing nltk.corpus methods. Does anyone have any suggestions?
Many thanks,
James. | Alex is right, start with the docs, and figure out which corpus reader will work for your corpus. The simple instantiate it, given the path to your corpus file(s). As you'll see in the docs, the builtin corpora are simply instances of particular corpus reader classes. Look thru the code in the nltk.corpus package should be helpful as well. | 0 | false | 2 | 409 |
2010-01-31 20:37:42.613 | What is the keyboard shortcut to run all unit tests in the current project in PyDev + Eclipse? | I know Ctrl + F9 runs a single file.
How to run them all?
If there is no such thing, how to bind one keyboard shortcut to it? | Go to the preferences and type in keys to get to the keyboard shortcut definition page (I think it's called keys... sorry not on my dev machine right now). In this dialog you can search for commands. See if there is a run all tests command (it might help to find the run tests you are currently using first). If there is check out the shortcut or define your own. | 0.135221 | false | 1 | 410 |
2010-02-01 19:19:42.847 | Using Jython with Django? | I am planning to use Jython with Django. I want to know how stable the Jython project is, how easy to use it is, and how large its developer community is. | I have not used Django with Jython, so I can't speak to that specific issue, but I've used Jython for other things and I've found it quite stable of late, and just as easy as plain Python. I believe the "core committers" in Jython are substantially fewer than in C-Python (maybe 1/3 the number or less), if that's what you mean by "developer community", but I'm not quite sure what's the point in asking about this -- are you considering joining either developer community (Jython or Core Python) and wondering where you could have the best impact?
If that's the case, I think the key issue isn't really how many others are already helping out, but, "what do you bring to the party" -- if you're a JVM wizard, or an expert at any important Java framework, you could be a real boon to the Jython community while that same skill would help much less in the C-Python community; vice versa, if you're a wizard, say, with autoconfigure and C-coded system calls, that would be precious for the C-Python community, but not as useful for the Jython community. | 0.386912 | false | 2 | 411 |
2010-02-01 19:19:42.847 | Using Jython with Django? | I am planning to use Jython with Django. I want to know how stable the Jython project is, how easy to use it is, and how large its developer community is. | I use Jython in testing and rapid-development.
From my point of view it is stable. | 0.265586 | false | 2 | 411 |
2010-02-03 04:56:52.453 | How to find length of digits in an integer? | In Python, how do you find the number of digits in an integer? | If you want the length of an integer as in the number of digits in the integer, you can always convert it to string like str(133) and find its length like len(str(123)). | 1.2 | true | 2 | 412 |
2010-02-03 04:56:52.453 | How to find length of digits in an integer? | In Python, how do you find the number of digits in an integer? | Assuming you are asking for the largest number you can store in an integer, the value is implementation dependent. I suggest that you don't think in that way when using python. In any case, quite a large value can be stored in a python 'integer'. Remember, Python uses duck typing!
Edit:
I gave my answer before the clarification that the asker wanted the number of digits. For that, I agree with the method suggested by the accepted answer. Nothing more to add! | 0.029146 | false | 2 | 412 |
2010-02-03 08:54:56.693 | Rebuilding PIL with FreeType | Previously I got a suggedtion to Install the FreeType dev files and rebuild PIL again.
but I have no idea how to do it.
any help will be thanked for | You do it exactly the same way as you did before, but now with the FreeType-dev files installed. | 0 | false | 1 | 413 |
2010-02-03 21:52:53.457 | Python class has method "set", how to reference builtin set type? | If you have a method called "set" in a class and want to create a standard builtin "set" object somewhere else in the class, Python seems to reference the method when I do that. How can you be more specific to let Python know you mean the builtin "set", not the method "set"? More specifically, set() is being created in an _____exit_____ function. | Usually method names are disambiguated from global names because you have to prefix self..
So self.set() invokes your class method and set() invokes the global set.
If this doesn't help, perhaps post the code you're having trouble with. | 0.16183 | false | 3 | 414 |
2010-02-03 21:52:53.457 | Python class has method "set", how to reference builtin set type? | If you have a method called "set" in a class and want to create a standard builtin "set" object somewhere else in the class, Python seems to reference the method when I do that. How can you be more specific to let Python know you mean the builtin "set", not the method "set"? More specifically, set() is being created in an _____exit_____ function. | You can refer to built-in set as __builtins__.set. | 0.16183 | false | 3 | 414 |
2010-02-03 21:52:53.457 | Python class has method "set", how to reference builtin set type? | If you have a method called "set" in a class and want to create a standard builtin "set" object somewhere else in the class, Python seems to reference the method when I do that. How can you be more specific to let Python know you mean the builtin "set", not the method "set"? More specifically, set() is being created in an _____exit_____ function. | Object attributes are always accessed via a reference, so there is no way for an object attribute to shadow a builtin. | 0.240117 | false | 3 | 414 |
2010-02-04 17:02:37.263 | Need a way to count entities in GAE datastore that meet a certain condition? (over 1000 entities) | I'm building an app on GAE that needs to report on events occurring. An event has a type and I also need to report by event type.
For example, say there is an event A, B and C. They occur periodically at random. User logs in and creates a set of entities to which those events can be attributed. When the user comes back to check the status, I need to be able to tell how many events of A, B and/or C occurred during a specific time range, say a day or a month.
The 1000 limit is throwing a wrench into how I would normally do it. I don't need to retrieve all of the entities and present them to the user, but I do need to show the total count for a specific date range. Any suggestions?
I'm a bit of python/GAE noob... | Results of datastore count() queries
and offsets for all datastore queries
are no longer capped at 1000.
Since Version 1.3.6 | 0.201295 | false | 1 | 415 |
2010-02-05 13:44:51.623 | How to write dynamic Django models? | what i want, is to receive advices to define a re-usefull Product model, for a shopping site app, nowadays I know that the store is going to commerce with "clothing", so the product model will have a "season or collections" relationship, but in the future I should use that app to commerce with X product, e.g: "cars" which have "mechanical specifications" relationships.
So Im thinking in metamodels, creating a generic model defined by key/values, but, how to make the relationships?.
But, you are the experts community and I hope you help me to see beyond. | One, popular, option would be to use something like tags. So you'd have the stuff that's common to all items, like an item ID, name, description, price. Then you'd have some more generic tags or described tags in another table, associated with those items. You could have a tag that represents the season, or automobile specifications, etc...
Of course, it really depends on how you design the system to cope with that additional information. | 0 | false | 1 | 416 |
2010-02-05 16:55:56.177 | Detect 64bit OS (windows) in Python | Does anyone know how I would go about detected what bit version Windows is under Python. I need to know this as a way of using the right folder for Program Files.
Many thanks | There should be a directory under Windows 64bit, a Folder called \Windows\WinSxS64 for 64 bit, under Windows 32bit, it's WinSxS. | -0.037089 | false | 4 | 417 |
2010-02-05 16:55:56.177 | Detect 64bit OS (windows) in Python | Does anyone know how I would go about detected what bit version Windows is under Python. I need to know this as a way of using the right folder for Program Files.
Many thanks | I guess you should look in os.environ['PROGRAMFILES'] for the program files folder. | 0.607538 | false | 4 | 417 |
2010-02-05 16:55:56.177 | Detect 64bit OS (windows) in Python | Does anyone know how I would go about detected what bit version Windows is under Python. I need to know this as a way of using the right folder for Program Files.
Many thanks | Many of these proposed solutions, such as platform.architecture(), fail because their results depend on whether you are running 32-bit or 64-bit Python.
The only reliable method I have found is to check for the existence of os.environ['PROGRAMFILES(X86)'], which is unfortunately hackish. | 0.11086 | false | 4 | 417 |
2010-02-05 16:55:56.177 | Detect 64bit OS (windows) in Python | Does anyone know how I would go about detected what bit version Windows is under Python. I need to know this as a way of using the right folder for Program Files.
Many thanks | You should be using environment variables to access this. The program files directory is stored in the environment variable PROGRAMFILES on x86 Windows, the 32-bit program files is directory is stored in the PROGRAMFILES(X86) environment variable, these can be accessed by using os.environ('PROGRAMFILES').
Use sys.getwindowsversion() or the existence of PROGRAMFILES(X86) (if 'PROGRAMFILES(X86)' in os.environ) to determine what version of Windows you are using. | 0.055601 | false | 4 | 417 |
2010-02-06 03:57:19.137 | Building an Inference Engine in Python | I am seeking direction and attempting to label this problem:
I am attempting to build a simple inference engine (is there a better name?) in Python which will take a string and -
1 - create a list of tokens by simply creating a list of white space separated values
2 - categorise these tokens, using regular expressions
3 - Use a higher level set of rules to make decisions based on the categorisations
Example:
"90001" - one token, matches the zipcode regex, a rule exists for a string containing just a zipcode causes a certain behaviour to occur
"30 + 14" - three tokens, regexs for numerical value and mathematical operators match, a rule exists for a numerical value followed by a mathematical operator followed by another numerical value causes a certain behaviour to occur
I'm struggling with how best to do step #3, the higher level set of rules. I'm sure that some framework must exist. Any ideas? Also, how would you characterise this problem? Rule based system, expert system, inference engine, something else?
Thanks! | It looks like you search for "grammar inference" (grammar induction) library. | 0.386912 | false | 1 | 418 |
2010-02-06 04:04:50.827 | How to implement an efficient infinite generator of prime numbers in Python? | This is not a homework, I am just curious.
INFINITE is the key word here.
I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.
So, the answer cannot be as naive as "Just do a Sieve".
First of all, you do not know how many consecutive primes will be consumed. Well, suppose you could concoct 100 of them at a time. Would you use the same Sieve approach as well as the frequency of prime numbers formula?
I prefer non-concurrent approach.
Thank you for reading (and writing ;) )! | Do a segmented sieve, where the size of a segment is determined by available memory or the maximal size of a bitset.
For each segment represent the numbers in some interval [n; n + segment_size) as a bit set and sieve with all prime numbers below the square root of the upper bound.
Using a bit set uses less memory than a hash table or tree data structure, because you are working with dense sets of numbers. | 0.201295 | false | 1 | 419 |
2010-02-06 15:27:43.583 | how do people normally deal with class variables in django? | I can't see any provision for this in the django docs, so how do people go about doing this.
My specific case is this.
I have a shopping cart, each cart instance has an invoice number field, however the invoice number is only generated if the cart goes to a paid status, so not all shopping cart instances will have an invoice number. I want all invoice numbers to be sequential with no gaps between them, so the default pk isn't perfect in this case, so I want a class variable that acts as a counter for the invoice numbers, and is accessable by all instances. | The default primary key will already be a unique monotonic integer (even in SQLite if you don't delete any records), so you can just use that for it. | 1.2 | true | 1 | 420 |
2010-02-08 15:58:51.017 | Making your own statements | Is there a way to define new statements like def, with, for of my own in Python? Of course, I don't mean to override the existing statements, only create some of my own.
If so, how do I do it? Can you point me to good docs on the subject? | There are programming languages that let you do this (Tcl, for example), but Python isn't one of those languages. | 0.081452 | false | 3 | 421 |
2010-02-08 15:58:51.017 | Making your own statements | Is there a way to define new statements like def, with, for of my own in Python? Of course, I don't mean to override the existing statements, only create some of my own.
If so, how do I do it? Can you point me to good docs on the subject? | You can't (re)define language keywords without rewriting a compiler/interpreter/etc. What you could do perhaps is write a something like a DSL (domain-specific language) and something that translates your keyword statements into proper python statements, which might be an easier route. | 0.240117 | false | 3 | 421 |
2010-02-08 15:58:51.017 | Making your own statements | Is there a way to define new statements like def, with, for of my own in Python? Of course, I don't mean to override the existing statements, only create some of my own.
If so, how do I do it? Can you point me to good docs on the subject? | No, you cannot add new syntax within a Python program. The only way to alter the language is to edit and recompile the grammar file and supporting C code, to obtain a new altered interpreter, compiler and runtime. | 1.2 | true | 3 | 421 |
2010-02-09 08:48:47.107 | cross-platform html widget for pygtk | I'm trying to write a small gui app in pygtk which needs an html-rendering widget. I'd like to be able to use it in a windows environment.
Currently I'm using pywebkitgtk on my GNU/Linux system, and it works extremely well, but it seems it's not possible to use this on Windows at this time.
Can anyone give me any suggestions on how to proceed? Do I need to work out how to embed IE using COM objects under Windows, and stick with pywebkitgtk on GNU/Linux?
I'm at an early stage, and am prepared to jettison pygtk in favour of another toolkit, say pyqt, if it affords a simpler solution (though I'd sooner stick with pygtk if possible). | In my experience, having developed cross-platform applications with both PyQt and PyGTK, you should consider moving to PyQt. It comes with a browser widget by default which runs fine on all platforms, and support for non-Linux platforms is outstanding compared to PyGTK. For PyGTK, you will have to be prepared building PyGObject/PyCairo/PyGTK, or even the full stack, yourself on Windows and Mac OS X. | 1.2 | true | 1 | 422 |
2010-02-09 14:13:16.810 | Django: Setting one page as the main page | I'm a newbie at Django and I want to do something that I'm not sure how to do.
I have a model SimplePage, which simply stands for a webpage that is visible on the website and whose contents can be edited in the admin. (I think this is similar to FlatPage.)
So I have a bunch of SimplePages for my site, and I want one of them to be the main page. (a.k.a. the index page.) I know how to make it available on the url /. But I also want it to receive slightly different processing. (It contains different page elements than the other pages.)
What would be a good way to mark a page as the main page? I considered adding a boolean field is_main_page to the SimplePage model, but how could I assure that only one page could be marked as the main page? | Create MAIN_PAGE setting inside settings.py with primary key. Then create view main_page nad retrieve the main_page object from the database using the setting.
EDIT:
You can also do it like this: add a model, which will reference a SimplePage and point to the main page. In main page view, you will retrieve the wanted SimplePage and it can be easily changed by anyone in django admin. | 1.2 | true | 1 | 423 |
2010-02-10 02:38:08.953 | how do I iterate over a "gslist" in Python? | Let's say I get a glib gpointer to a glib gslist and would like to iterate over the latter, how would I do it?
I don't even know how to get to the gslist with the gpointer for starters!
Update: I found a workaround - the python bindings in this instance wasn't complete so I had to find another solution. | How is glib exposed to Python in your application? Via SWIG, ctypes or something else?
You should basically use glib's own functions to iterate over a list. Something like g_slist_foreach. Just pass it the pointer and its other parameters to do the job. Again, this heavily depends on how you access glib in your Python application. | 1.2 | true | 1 | 424 |
2010-02-10 12:54:40.400 | PHP / cURL problem opening remote file | We have a script which pulls some XML from a remote server. If this script is running on any server other than production, it works.
Upload it to production however, and it fails. It is using cURL for the request but it doesn't matter how we do it - fopen, file_get_contents, sockets - it just times out. This also happens if I use a Python script to request the URL.
The same script, supplied with another URL to query, works - every time. Obviously it doesn't return the XML we're looking for but it DOES return SOMETHINg - it CAN connect to the remote server.
If this URL is requested via the command line using, for example, curl or wget, again, data is returned. It's not the data we're looking for (in fact, it returns an empty root element) but something DOES come back.
Interestingly, if we strip out query string elements from the URL (the full URL has 7 query string elements and runs to about 450 characters in total) the script will return the same empty XML response. Certain combinations of the query string will once again cause the script to time out.
This, as you can imagine, has me utterly baffled - it seems to work in every circumstance EXCEPT the one it needs to work in. We can get a response on our dev servers, we can get a response on the command line, we can get a response if we drop certain QS elements - we just can't get the response we want with the correct URL on the LIVE server.
Does anyone have any suggestions at all? I'm at my wits end! | Run Wireshark and see how far the request goes. Could be a firewall issue, a DNS resolution problem, among other things.
Also, try bumping your curl timeout to something much higher, like 300s, and see how it goes. | 0.386912 | false | 1 | 425 |
2010-02-11 19:39:15.890 | Associative Matrices? | I'm working on a project where I need to store a matrix of numbers indexed by two string keys. The matrix is not jagged, i.e. if a column key exists for any row then it should exist for all rows. Similarly, if a row key exists for any column then it should exist for all columns.
The obvious way to express this is with an associative array of associative arrays, but this is both awkward and inefficient, and it doesn't enforce the non-jaggedness property. Do any popular programming languages provide an associative matrix either built into the language or as part of their standard libraries? If so, how do they work, both at the API and implementation level? I'm using Python and D for this project, but examples in other languages would still be useful because I would be able to look at the API and figure out the best way to implement something similar in Python or D. | Why not just use a standard matrix, but then have two dictionaries - one that converts the row keys to row indices and one that converts the columns keys to columns indices. You could make your own structure that would work this way fairly easily I think. You just make a class that contains the matrix and the two dictionaries and go from there. | 1.2 | true | 1 | 426 |
2010-02-12 03:40:16.957 | How to improve the throughput of request_logs on Google App Engine | Downloading logs from App Engine is nontrivial. Requests are batched; appcfg.py does not use normal file IO but rather a temporary file (in reverse chronological order) which it ultimately appends to the local log file; when appending, the need to find the "sentinel" makes log rotation difficult since one must leave enough old logs for appcfg.py to remember where it left off. Finally, Google deletes old logs after some time (20 minutes for the app I use).
As an app scales, and the log generation rate grows, how can one increase the speed of fetching the logs so that appcfg.py does not fall behind? | You can increase the per-request batch size of logs. In the latest SDK (1.3.1), check out google_appengine/google/appengine/tools/appcfg.py around like 861 (RequestLogLines method of LogsRequester class). You can modify the "limit" parameter.
I am using 1000 and it works pretty well. | 1.2 | true | 1 | 427 |
2010-02-13 00:12:37.200 | How do I interact with MATLAB from Python? | A friend asked me about creating a small web interface that accepts some inputs, sends them to MATLAB for number crunching and outputs the results. I'm a Python/Django developer by trade, so I can handle the web interface, but I am clueless when it comes to MATLAB. Specifically:
I'd really like to avoid hosting this on a Windows server. Any issues getting MATLAB running in Linux with scripts created on Windows?
Should I be looking into shelling out commands or compiling it to C and using ctypes to interact with it?
If compiling is the way to go, is there anything I should know about getting it compiled and working in Python? (It's been a long time since I've compiled or worked with C)
Any suggestions, tips, or tricks on how to pull this off? | Regarding OS compatibility, if you use the matlab version for Linux, the scripts written in windows should work without any changes.
If possible, you may also consider the possibility of doing everything with python. Scipy/numpy with Matplotlib provide a complete Matlab replacement. | 0.101688 | false | 1 | 428 |
2010-02-13 08:47:09.740 | Recommended Django Deployment | Short version: How do you deploy your Django servers? What application server, front-end (if any, and by front-end I mean reverse proxy), and OS do you run it on? Any input would be greatly appreciated, I'm quite a novice when it comes to Python and even more as a server administrator.
Long version:
I'm migrating between server hosts, so much for weekends... it's not all bad, though. I have the opportunity to move to a different, possibly better "deployment" of Django.
Currently I'm using Django through Tornado's WSGI interface with an nginx front-end on Debian Lenny. I'm looking to move into the Rackspace Cloud so I've been given quite a few choices when it comes to OS:
Debian 5.0 (Lenny)
FC 11 or 12
Ubuntu 9.10 or 8.04 (LTS)
CentOS 5.4
Gentoo 10.1
Arch Linux 2009.02
What I've gathered is this:
Linux Distributions
Debian and CentOS are very slow to release non-bugfix updates of software, since they focus mainly on stability. Is this good or bad? I can see stability being a good thing, but the fact that I can't get Python 2.6 without quite a headache of replacing Python 2.4 is kind of a turn-off--and if I do, then I'm stuck when it comes to ever hoping to use apt/yum to install a Python library (it'll try to reinstall Python 2.4).
Ubuntu and Fedora seem very... ready to go. Almost too ready to go, it's like everything it already done. I like to tinker with things and I prefer to know what's installed and how it's configured versus hitting the ground running with a "cookie-cutter" setup (no offense intended, it's just the best way to describe what I'm trying to say). I've been playing around with Fedora and I was pleasently surprised to find that pycurl, simplejson and a bunch of other libraries were already installed; that raised the question, though, what else is installed? I run a tight ship on a very small VPS, I prefer to run only what I need.
Then there's Gentoo... I've managed to install Gentoo on my desktop (took a week, almost) and ended up throwing it out after quite a few events where I wanted to do something and had to spend 45 minutes recompiling software with new USE flags so I can parse PNG's through PIL. I've wondered though, is Gentoo good for something "static" like a server? I know exactly what I'm going to be doing on my server, so USE flags will change next to never. It optimizes compiles to fit the needs of what you tell it to, and nothing more--something I could appreciate running on minimal RAM and HDD space. I've heard, though, that Gentoo has a tendency to break when you attempt to update the software on it... that more than anything else has kept me away from it for now.
I don't know anything about Arch Linux. Any opinions on this distro would be appreciated.
Web Server
I've been using Tornado and I can safely say it's been the biggest hassle to get running. I had to write my own script to prefork it since, at the time I setup this server, I was probably around 10% of Tornado's user-base (not counting FriendFeed). I have to then setup another "watchdog" program to make sure those forks don't misbehave. The good part is, though, it uses around 40MB of RAM to run all 7 of my Django powered sites; I liked that, I liked that a lot.
I've been using nginx as a front-end to Tornado, I could run nginx right in front of Django FastCGI workers, but those don't have the reliability of Tornado when you crank up the concurrency level. This isn't really an option for me, but I figured I might as well list it.
There's also Apache, which Django recommends you use through mod_wsgi. I personally don't like Apache that much, I understand it's very, very, very mature and what not, but it just seems so... fat, compared to nginx and lighttpd. Apache/mod_python isn't even an option, as I have very limited RAM.
Segue to Lighttpd! Not much to say here, I've never used it. I've heard you can run it in front of Apache/mod_wsgi or run it in front of Django FastCGI workers, also. I've heard it has minor memory leaking issues, I'm sure that could be solved with a cron job, though.
What I'm looking for is what you have seen as the "best" deployment of Django for your needs. Any input or clarifications of what I've said above would be more than welcome. | At the place I rent server, they have shaved down the Ubuntu images to bare minimum. Presumably because they had to make a special image anyway with just the right drivers and such in it, but I don't know exactly.
They have even removed wget and nano. So you get all the apt-get goodness and not a whole lot of "cookie-cutter" OS.
Just saying this because I would imagine that this is the way it is done almost everywhere and therefore playing around with a normal Ubuntu-server install will not provide you with the right information to make your decision.
Other than that, I agree with the others, that it is not much of a lock-in so you could just try something.
On the webserver-side I would suggest taking a look at cherokee, if have not done so already.
It might not be your cup of joe, but there is no harm in trying it.
I prefer the easy setup of both Ubuntu and Cherokee. Although I play around with a lot of things for fun, I prefer these for my business. I have other things to do than manage servers, so any solution that helps me do it faster, is just good. If these projects are mostly for fun then this will most likely not apply since you won't get a whole lot of experience from these easy-setup-with-nice-gui-and-very-helpfull-wizards | 0.296905 | false | 3 | 429 |
2010-02-13 08:47:09.740 | Recommended Django Deployment | Short version: How do you deploy your Django servers? What application server, front-end (if any, and by front-end I mean reverse proxy), and OS do you run it on? Any input would be greatly appreciated, I'm quite a novice when it comes to Python and even more as a server administrator.
Long version:
I'm migrating between server hosts, so much for weekends... it's not all bad, though. I have the opportunity to move to a different, possibly better "deployment" of Django.
Currently I'm using Django through Tornado's WSGI interface with an nginx front-end on Debian Lenny. I'm looking to move into the Rackspace Cloud so I've been given quite a few choices when it comes to OS:
Debian 5.0 (Lenny)
FC 11 or 12
Ubuntu 9.10 or 8.04 (LTS)
CentOS 5.4
Gentoo 10.1
Arch Linux 2009.02
What I've gathered is this:
Linux Distributions
Debian and CentOS are very slow to release non-bugfix updates of software, since they focus mainly on stability. Is this good or bad? I can see stability being a good thing, but the fact that I can't get Python 2.6 without quite a headache of replacing Python 2.4 is kind of a turn-off--and if I do, then I'm stuck when it comes to ever hoping to use apt/yum to install a Python library (it'll try to reinstall Python 2.4).
Ubuntu and Fedora seem very... ready to go. Almost too ready to go, it's like everything it already done. I like to tinker with things and I prefer to know what's installed and how it's configured versus hitting the ground running with a "cookie-cutter" setup (no offense intended, it's just the best way to describe what I'm trying to say). I've been playing around with Fedora and I was pleasently surprised to find that pycurl, simplejson and a bunch of other libraries were already installed; that raised the question, though, what else is installed? I run a tight ship on a very small VPS, I prefer to run only what I need.
Then there's Gentoo... I've managed to install Gentoo on my desktop (took a week, almost) and ended up throwing it out after quite a few events where I wanted to do something and had to spend 45 minutes recompiling software with new USE flags so I can parse PNG's through PIL. I've wondered though, is Gentoo good for something "static" like a server? I know exactly what I'm going to be doing on my server, so USE flags will change next to never. It optimizes compiles to fit the needs of what you tell it to, and nothing more--something I could appreciate running on minimal RAM and HDD space. I've heard, though, that Gentoo has a tendency to break when you attempt to update the software on it... that more than anything else has kept me away from it for now.
I don't know anything about Arch Linux. Any opinions on this distro would be appreciated.
Web Server
I've been using Tornado and I can safely say it's been the biggest hassle to get running. I had to write my own script to prefork it since, at the time I setup this server, I was probably around 10% of Tornado's user-base (not counting FriendFeed). I have to then setup another "watchdog" program to make sure those forks don't misbehave. The good part is, though, it uses around 40MB of RAM to run all 7 of my Django powered sites; I liked that, I liked that a lot.
I've been using nginx as a front-end to Tornado, I could run nginx right in front of Django FastCGI workers, but those don't have the reliability of Tornado when you crank up the concurrency level. This isn't really an option for me, but I figured I might as well list it.
There's also Apache, which Django recommends you use through mod_wsgi. I personally don't like Apache that much, I understand it's very, very, very mature and what not, but it just seems so... fat, compared to nginx and lighttpd. Apache/mod_python isn't even an option, as I have very limited RAM.
Segue to Lighttpd! Not much to say here, I've never used it. I've heard you can run it in front of Apache/mod_wsgi or run it in front of Django FastCGI workers, also. I've heard it has minor memory leaking issues, I'm sure that could be solved with a cron job, though.
What I'm looking for is what you have seen as the "best" deployment of Django for your needs. Any input or clarifications of what I've said above would be more than welcome. | Update your question to remove the choices that don't work. If it has Python 2.4, and an installation is a headache, just take it off the list, and update the question to list the real candidates. Only list the ones that actually fit your requirements. (You don't say what your requirements are, but minimal upgrades appears to be important.)
Toss a coin.
When choosing between two platforms which meet your requirements (which you haven't identified) tossing a coin is the absolute best way to choose.
If you're not sure if something matches your requirements, it's often good to enumerate what you value. So far, the only thing in the question that you seem to value is "no installations". Beyond that, I can only guess at what requirements you actually have.
Once you've identified the set of features you're looking for, feel free to toss a coin.
Note that Linux distributions all have more-or-less the same open-source code base. Choosing among them is a preference for packaging, support and selection of pre-integrated elements of the existing Linux code base. Just toss a coin.
Choosing among web front-ends is entirely a question of what features you require. Find all the web front-ends that meet your requirements and toss a coin to choose among them.
None of these are "lock-in" decisions. If you don't like the linux distro you chose initially, you can simply chose another. They all have the same basic suite of apps and the same API's. The choice is merely a matter of preference.
Don't like the web server you chose? At the end of the mod_wsgi pipe, they all appear the same to your Django app (plus or minus a few config changes). Don't like lighttpd? Switch to nginx or Apache -- your Django app doesn't change. So there's no lock-in and no negative consequences to making a sub-optimal choice.
When there's no down-side risk, just toss a coin. | 0.386912 | false | 3 | 429 |
2010-02-13 08:47:09.740 | Recommended Django Deployment | Short version: How do you deploy your Django servers? What application server, front-end (if any, and by front-end I mean reverse proxy), and OS do you run it on? Any input would be greatly appreciated, I'm quite a novice when it comes to Python and even more as a server administrator.
Long version:
I'm migrating between server hosts, so much for weekends... it's not all bad, though. I have the opportunity to move to a different, possibly better "deployment" of Django.
Currently I'm using Django through Tornado's WSGI interface with an nginx front-end on Debian Lenny. I'm looking to move into the Rackspace Cloud so I've been given quite a few choices when it comes to OS:
Debian 5.0 (Lenny)
FC 11 or 12
Ubuntu 9.10 or 8.04 (LTS)
CentOS 5.4
Gentoo 10.1
Arch Linux 2009.02
What I've gathered is this:
Linux Distributions
Debian and CentOS are very slow to release non-bugfix updates of software, since they focus mainly on stability. Is this good or bad? I can see stability being a good thing, but the fact that I can't get Python 2.6 without quite a headache of replacing Python 2.4 is kind of a turn-off--and if I do, then I'm stuck when it comes to ever hoping to use apt/yum to install a Python library (it'll try to reinstall Python 2.4).
Ubuntu and Fedora seem very... ready to go. Almost too ready to go, it's like everything it already done. I like to tinker with things and I prefer to know what's installed and how it's configured versus hitting the ground running with a "cookie-cutter" setup (no offense intended, it's just the best way to describe what I'm trying to say). I've been playing around with Fedora and I was pleasently surprised to find that pycurl, simplejson and a bunch of other libraries were already installed; that raised the question, though, what else is installed? I run a tight ship on a very small VPS, I prefer to run only what I need.
Then there's Gentoo... I've managed to install Gentoo on my desktop (took a week, almost) and ended up throwing it out after quite a few events where I wanted to do something and had to spend 45 minutes recompiling software with new USE flags so I can parse PNG's through PIL. I've wondered though, is Gentoo good for something "static" like a server? I know exactly what I'm going to be doing on my server, so USE flags will change next to never. It optimizes compiles to fit the needs of what you tell it to, and nothing more--something I could appreciate running on minimal RAM and HDD space. I've heard, though, that Gentoo has a tendency to break when you attempt to update the software on it... that more than anything else has kept me away from it for now.
I don't know anything about Arch Linux. Any opinions on this distro would be appreciated.
Web Server
I've been using Tornado and I can safely say it's been the biggest hassle to get running. I had to write my own script to prefork it since, at the time I setup this server, I was probably around 10% of Tornado's user-base (not counting FriendFeed). I have to then setup another "watchdog" program to make sure those forks don't misbehave. The good part is, though, it uses around 40MB of RAM to run all 7 of my Django powered sites; I liked that, I liked that a lot.
I've been using nginx as a front-end to Tornado, I could run nginx right in front of Django FastCGI workers, but those don't have the reliability of Tornado when you crank up the concurrency level. This isn't really an option for me, but I figured I might as well list it.
There's also Apache, which Django recommends you use through mod_wsgi. I personally don't like Apache that much, I understand it's very, very, very mature and what not, but it just seems so... fat, compared to nginx and lighttpd. Apache/mod_python isn't even an option, as I have very limited RAM.
Segue to Lighttpd! Not much to say here, I've never used it. I've heard you can run it in front of Apache/mod_wsgi or run it in front of Django FastCGI workers, also. I've heard it has minor memory leaking issues, I'm sure that could be solved with a cron job, though.
What I'm looking for is what you have seen as the "best" deployment of Django for your needs. Any input or clarifications of what I've said above would be more than welcome. | Personally I find one of the BSD systems far superior to Linux distros for server related tasks. Give OpenBSD or perhaps FreeBSD a chance. Once you do you´ll never go back. | 0 | false | 3 | 429 |
2010-02-15 09:42:17.037 | How to read from stdin or from a file if no data is piped in Python? | I have a CLI script and want it to read data from a file. It should be able to read it in two ways :
cat data.txt | ./my_script.py
./my_script.py data.txt
—a bit like grep, for example.
What I know:
sys.argv and optparse let me read any args and options easily.
sys.stdin let me read data piped in
fileinput make the full process automatic
Unfortunately:
using fileinput uses stdin and any args as input. So I can't use options that are not filenames as it tries to open them.
sys.stdin.readlines() works fine, but if I don't pipe any data, it hangs until I enter Ctrl + D
I don't know how to implement "if nothing in stdin, read from a file in args" because stdin is always True in a boolean context.
I'd like a portable way to do this if possible. | There is no reliable way to detect if sys.stdin is connected to anything, nor is it appropriate do so (e.g., the user wants to paste the data in). Detect the presence of a filename as an argument, and use stdin if none is found. | 0.201295 | false | 1 | 430 |
2010-02-15 19:11:23.243 | Can you auto hide frames/dialogs using wxPython? | I would like to create an application that has 3-4 frames (or windows) where each frame is attached/positioned to a side of the screen (like a task bar). When a frame is inactive I would like it to auto hide (just like the Windows task bar does; or the dock in OSX). When I move my mouse pointer to the position on the edge of the screen where the frame is hidden, I would like it to come back into focus.
The application is written in Python (using wxPython for the basic GUI aspects). Does anyone know how to do this in Python? I'm guessing it's probably OS dependent? If so, I'd like to focus on Windows first.
I don't do GUI programming very often so my apologies if this makes no sense at all. | I think you could easily just make a window that is the same size as the desktop then do some while looping for an inactivity variable based on mouse position, then thread off a timer for loop for the 4 inactivity variables. I'd personally design it so that when they reach 0 from 15, they change size and position to become tabular and create a button on them to reactivate. lots of technical work on this one, but easily done if you figure it out | 0 | false | 2 | 431 |
2010-02-15 19:11:23.243 | Can you auto hide frames/dialogs using wxPython? | I would like to create an application that has 3-4 frames (or windows) where each frame is attached/positioned to a side of the screen (like a task bar). When a frame is inactive I would like it to auto hide (just like the Windows task bar does; or the dock in OSX). When I move my mouse pointer to the position on the edge of the screen where the frame is hidden, I would like it to come back into focus.
The application is written in Python (using wxPython for the basic GUI aspects). Does anyone know how to do this in Python? I'm guessing it's probably OS dependent? If so, I'd like to focus on Windows first.
I don't do GUI programming very often so my apologies if this makes no sense at all. | Personally, I would combine the EVT_ENTER_WINDOW and EVT_LEAVE_WINDOW that FogleBird mentioned with a wx.Timer. Then whenever it the frame or dialog is inactive for x seconds, you would just call its Hide() method. | 0 | false | 2 | 431 |
2010-02-16 04:06:23.740 | Subscription web/desktop app [PYTHON] | Firstly pardon me if i've yet again failed to title my question correctly.
I am required to build an app to manage magazine subscriptions. The client wants to enter subscriber data and then receive alerts at pre-set intervals such as when the subscription of a subscriber is about to expire and also the option to view all subscriber records at any time. Also needed is the facility to send an SMS/e-mail to particular subscribers reminding them for subscription renewal.
I am very familiar with python but this will be my first real project. I have decided to build it as a web app using django, allowing the admin user the ability to view/add/modify all records and others to subscribe. What options do I have for integrating an online payment service? Also how do I manage the SMS alert functionality? Any other pointers/suggestions would be welcome.
Thank You | I'd like to comment on the SMS alert part.
First, I have to admit that I'm not familiar with Django, but I assume it to be just like most other web frameworks: request based. This might be your first problem, as the alert service needs to run independently of requests. You could of course hack together something to externally trigger a request once a day... :-)
Now for the SMS part: much depends on how you plan to implement this. If you are going with an SMS provider, there are many to choose from that let you send SMS with a simple HTTP request. I wouldn't recommend the other approach, namely using a real cellphone or SMS modem and take care of the delivery yourself: it is way too cumbersome and you have to take into account a lot more issues: e.g. retry message transmission for handsets that are turned off or aren't able to receive SMS because their memory is full. Your friendly SMS provider will probably take care of this. | 0 | false | 1 | 432 |
2010-02-16 20:15:09.090 | Program web applications in python without a framework? | I am just starting Python and I was wondering how I would go about programming web applications without the need of a framework. I am an experienced PHP developer but I have an urge to try out Python and I usually like to write from scratch without the restriction of a framework like flask or django to name a few. | One of the lightest-weight frameworks is mod_wsgi. Anything less is going to be a huge amount of work parsing HTTP requests to find headers and URI's and methods and parsing the GET or POST query/data association, handling file uploads, cookies, etc.
As it is, mod_wsgi will only handle the basics of request parsing and framing up results.
Sessions, cookies, using a template generator for your response pages will be a surprising amount of work.
Once you've started down that road, you may find that a little framework support goes a long way. | 0.265586 | false | 1 | 433 |
2010-02-17 16:20:52.410 | Help for novice choosing between Java and Python for app with sql db | I'm going to write my first non-Access project, and I need advice on choosing the platform. I will be installing it on multiple friends' and family's computers, so (since I'm sure many, many platforms would suffice just fine for my app), my highest priority has two parts: 1) ease of install for the non-technical user and, 2) minimizing compatibility problems. I want to be able to fix bugs and make changes and roll them out without having to troubleshoot OS and program conflicts on their computers (or at least keeping those things to the absolute minimum-this is why these concerns are my highest priority in choosing a platform.)
I have narrowed it down to Python or Java. I like Java's use of the JVM, which seems like would serve to protect against incompatibilities on individual computers nicely. And I've heard a lot of good things about Python, but I don't know how much more prone to incompatibilities it is vs Java. In case it is important, I know the app will definitely use some flavor of a free server-enabled SQL db (server-enabled because I want to be able to run the app from multiple computers), but I don't know which to use yet. I thought I could decide that next.
My experience level: I've taken a C++ (console app only) class and done some VBA in Access, but mostly I'm going to have to jump in and learn as I go. So of course I don't know much about all of this. I'm not in the computer field, this is just a hobby.
So, which would be better for this app, Java or Python?
(In case it comes up, I don't want to make it browser-based at all. I've dealt with individual computers' browser settings breaking programs, and that goes against part 2 of my top priority - maximum compatibility.)
Thank you.
Update: It will need a gui, and I'd like to be able to do a little bit of customization on it (or use a non-standard, or maybe a non-built-in one) to make it pop a little.
Update 2: Truthfully, I really am only concerned with Windows computers. I am considering Java only for its reliability as a platform. | If you're going to install only (or mostly) on Windows, I'd go with .Net.
If you have experience with C++, then C# would be natural to you, but if you're comfortable with VBA, you can try VB.NET, but if you prefer Python, then there is IronPython or can give a try to IronRuby, but the best of all is you can mix them all as they apply to different parts of your project.
In the database area you'll have excellent integration with SQL Server Express, and in the GUI area, Swing can't beat the ease of use of WinForms nor the sophistication of WPF/Silverlight.
As an added bonus, you can have your application automatically updated with ClickOnce. | 1.2 | true | 2 | 434 |
2010-02-17 16:20:52.410 | Help for novice choosing between Java and Python for app with sql db | I'm going to write my first non-Access project, and I need advice on choosing the platform. I will be installing it on multiple friends' and family's computers, so (since I'm sure many, many platforms would suffice just fine for my app), my highest priority has two parts: 1) ease of install for the non-technical user and, 2) minimizing compatibility problems. I want to be able to fix bugs and make changes and roll them out without having to troubleshoot OS and program conflicts on their computers (or at least keeping those things to the absolute minimum-this is why these concerns are my highest priority in choosing a platform.)
I have narrowed it down to Python or Java. I like Java's use of the JVM, which seems like would serve to protect against incompatibilities on individual computers nicely. And I've heard a lot of good things about Python, but I don't know how much more prone to incompatibilities it is vs Java. In case it is important, I know the app will definitely use some flavor of a free server-enabled SQL db (server-enabled because I want to be able to run the app from multiple computers), but I don't know which to use yet. I thought I could decide that next.
My experience level: I've taken a C++ (console app only) class and done some VBA in Access, but mostly I'm going to have to jump in and learn as I go. So of course I don't know much about all of this. I'm not in the computer field, this is just a hobby.
So, which would be better for this app, Java or Python?
(In case it comes up, I don't want to make it browser-based at all. I've dealt with individual computers' browser settings breaking programs, and that goes against part 2 of my top priority - maximum compatibility.)
Thank you.
Update: It will need a gui, and I'd like to be able to do a little bit of customization on it (or use a non-standard, or maybe a non-built-in one) to make it pop a little.
Update 2: Truthfully, I really am only concerned with Windows computers. I am considering Java only for its reliability as a platform. | The largest issue I can think of is the need to install an interpreter.
With Java, a lot of people will already have that interpreter installed, although you won't necessarily know which version. It may be wise to include the installer for Java with the program.
With Python, you're going to have to install the interpreter on each computer, too.
One commenter mentioned .NET. .NET 2.0 has a fairly high likelyhood of being installed than either Java or Python on Windows machines. The catch is that you can't (easily) install it on OSX or Linux. | 0.081452 | false | 2 | 434 |
2010-02-19 08:41:25.437 | How to open a Pyqt 3.3 ui file with QtDesigner 4? | I've a PyQt 4 installed (I can't find PyQt 3 for Windows) and I would like to open a QtDesigner ui file which has been created with QtDesigner 3.3.
When I open this file I've the following message:
Please use uic3 -convert to convert to Qt4
Unfortunately, I don't see the uic3 tool in the bin folder of my install.
Does anybody know how can I can convert this file to QtDesigner 4?
Additional quastion: Where to download PyQy3 binaries for Windows?
Thanks in advance | Try finding pyuic3 or rather pyuic4. Since you are using PyQt all your qt tools have py in front (like pyrcc4 or pyuicc4).
I am not sure, that there are pyqt3 binaries for windows. Are you sure that Phil Thompson did PyQt3 also for windows at the time? If so, they would be on riverbank site, I guess, but I can't find them there. Tried compiling the source yourself? | 0.201295 | false | 1 | 435 |
2010-02-19 13:28:51.633 | how to have global variables among different modules in Python | I investigated that scope of global variables in python is limited to the module. But I need the scope to be global among different modules. Is there such a thing? I played around __builtin__ but no luck.
thanks in advance! | Python does not support globals shared between several modules: this is a feature. Code that implicitly modifies variables used far away is confusing and unmaintainable. The real solution is to encapsulate all state within a class and pass its instance to anything that has to modify it. This can make code clearer, more maintainable, more testable, more modular, and more expendable. | 0.386912 | false | 2 | 436 |
2010-02-19 13:28:51.633 | how to have global variables among different modules in Python | I investigated that scope of global variables in python is limited to the module. But I need the scope to be global among different modules. Is there such a thing? I played around __builtin__ but no luck.
thanks in advance! | Scopes beyond the local must be written to via a reference to the scope, or after a global or nonlocal (3.x+) directive. | 0 | false | 2 | 436 |
2010-02-19 16:31:00.477 | Scripting language for trading strategy development | I'm currently working on a component of a trading product that will allow a quant or strategy developer to write their own custom strategies. I obviously can't have them write these strategies in natively compiled languages (or even a language that compiles to a bytecode to run on a vm) since their dev/test cycles have to be on the order of minutes.
I've looked at lua, python, ruby so far and really enjoyed all of them so far, but still found them a little "low level" for my target users. Would I need to somehow write my own parser + interpreter to support a language with a minimum of support for looping, simple arithmatic, logical expression evaluation, or is there another recommendation any of you may have? Thanks in advance. | Existing languages are "a little "low level" for my target users."
Yet, all you need is "a minimum of support for looping, simple arithmatic, logical expression evaluation"
I don't get the problem. You only want a few features. What's wrong with the list of languages you provided? They actually offer those features?
What's the disconnect? Feel free to update your question to expand on what the problem is. | 0 | false | 5 | 437 |
2010-02-19 16:31:00.477 | Scripting language for trading strategy development | I'm currently working on a component of a trading product that will allow a quant or strategy developer to write their own custom strategies. I obviously can't have them write these strategies in natively compiled languages (or even a language that compiles to a bytecode to run on a vm) since their dev/test cycles have to be on the order of minutes.
I've looked at lua, python, ruby so far and really enjoyed all of them so far, but still found them a little "low level" for my target users. Would I need to somehow write my own parser + interpreter to support a language with a minimum of support for looping, simple arithmatic, logical expression evaluation, or is there another recommendation any of you may have? Thanks in advance. | Define the language first -- if possible, use the pseudo-language called EBN, it's very simple (see the Wikipedia entry).
Then once you have that, pick the language. Almost certainly you will want to use a DSL. Ruby and Lua are both really good at that, IMO.
Once you start working on it, you may find that you go back to your definition and tweak it. But that's the right order to do things, I think. | 0 | false | 5 | 437 |
2010-02-19 16:31:00.477 | Scripting language for trading strategy development | I'm currently working on a component of a trading product that will allow a quant or strategy developer to write their own custom strategies. I obviously can't have them write these strategies in natively compiled languages (or even a language that compiles to a bytecode to run on a vm) since their dev/test cycles have to be on the order of minutes.
I've looked at lua, python, ruby so far and really enjoyed all of them so far, but still found them a little "low level" for my target users. Would I need to somehow write my own parser + interpreter to support a language with a minimum of support for looping, simple arithmatic, logical expression evaluation, or is there another recommendation any of you may have? Thanks in advance. | I would use Common Lisp, which supports rapid development (you have a running image and can compile/recompile individual functions) and tailoring the language to your domain. You would provide functions and macros as building blocks to express strategies, and the whole language would be available to the user for combining these. | 0 | false | 5 | 437 |
2010-02-19 16:31:00.477 | Scripting language for trading strategy development | I'm currently working on a component of a trading product that will allow a quant or strategy developer to write their own custom strategies. I obviously can't have them write these strategies in natively compiled languages (or even a language that compiles to a bytecode to run on a vm) since their dev/test cycles have to be on the order of minutes.
I've looked at lua, python, ruby so far and really enjoyed all of them so far, but still found them a little "low level" for my target users. Would I need to somehow write my own parser + interpreter to support a language with a minimum of support for looping, simple arithmatic, logical expression evaluation, or is there another recommendation any of you may have? Thanks in advance. | This might be a bit simplistic, but a lot of quant users are used to working with Excel & VBA macros. Would something like VBSCript be usable, as they may have some experience in this area. | 0 | false | 5 | 437 |
2010-02-19 16:31:00.477 | Scripting language for trading strategy development | I'm currently working on a component of a trading product that will allow a quant or strategy developer to write their own custom strategies. I obviously can't have them write these strategies in natively compiled languages (or even a language that compiles to a bytecode to run on a vm) since their dev/test cycles have to be on the order of minutes.
I've looked at lua, python, ruby so far and really enjoyed all of them so far, but still found them a little "low level" for my target users. Would I need to somehow write my own parser + interpreter to support a language with a minimum of support for looping, simple arithmatic, logical expression evaluation, or is there another recommendation any of you may have? Thanks in advance. | Custom-made modules are going to be needed, no matter what you choose, that define your firm's high level constructs.
Here are some of the needs I envision -- you may have some of these covered already: a way to get current positions, current and historical quotes, previous performance data, etc... into the application. Define/backtest/send various kinds of orders (limit/market/stop, what exchange, triggers) or parameters of options, etc... You probably are going to need multiple sandboxes for testing as well as the real thing.
Quants want to be able to do matrix operations, stochastic calculus, PDEs.
If you wanted to do it in python, loading NumPy would be a start.
You could also start with a proprietary system designed to do mathematical financial research such as something built on top of Mathematica or Matlab. | 0.037089 | false | 5 | 437 |
2010-02-19 20:51:01.430 | How do quickly search through a .csv file in Python | I'm reading a 6 million entry .csv file with Python, and I want to be able to search through this file for a particular entry.
Are there any tricks to search the entire file? Should you read the whole thing into a dictionary or should you perform a search every time? I tried loading it into a dictionary but that took ages so I'm currently searching through the whole file every time which seems wasteful.
Could I possibly utilize that the list is alphabetically ordered? (e.g. if the search word starts with "b" I only search from the line that includes the first word beginning with "b" to the line that includes the last word beginning with "b")
I'm using import csv.
(a side question: it is possible to make csv go to a specific line in the file? I want to make the program start at a random line)
Edit: I already have a copy of the list as an .sql file as well, how could I implement that into Python? | You can't go directly to a specific line in the file because lines are variable-length, so the only way to know when line #n starts is to search for the first n newlines. And it's not enough to just look for '\n' characters because CSV allows newlines in table cells, so you really do have to parse the file anyway. | 0.067922 | false | 2 | 438 |
2010-02-19 20:51:01.430 | How do quickly search through a .csv file in Python | I'm reading a 6 million entry .csv file with Python, and I want to be able to search through this file for a particular entry.
Are there any tricks to search the entire file? Should you read the whole thing into a dictionary or should you perform a search every time? I tried loading it into a dictionary but that took ages so I'm currently searching through the whole file every time which seems wasteful.
Could I possibly utilize that the list is alphabetically ordered? (e.g. if the search word starts with "b" I only search from the line that includes the first word beginning with "b" to the line that includes the last word beginning with "b")
I'm using import csv.
(a side question: it is possible to make csv go to a specific line in the file? I want to make the program start at a random line)
Edit: I already have a copy of the list as an .sql file as well, how could I implement that into Python? | my idea is to use python zodb module to store dictionaty type data and then create new csv file using that data structure. do all your operation at that time. | 0 | false | 2 | 438 |
2010-02-19 21:23:47.400 | Building a wiki application? | I'm building this app in Python with Django.
I would like to give parts of the site wiki like functionality,
but I don't know how to go on about reliability and security.
Make sure that good content is not ruined
Check for quality
Prevent spam from invading the site
The items requiring wiki like functionality are just a few: a couple of text fields.
Can anyone help on this one?
Would be very much appreciated. :) | Assuming that there will be a community of users you can provide good tools for them to spot problems and easily undo damage. The most important of these is to provide a Recent Changes page that summarizes recent edits. Then each page that can be edited should retain prior versions of the page that can be used to replace any damaging edit. This makes it easier to undo damage than it is to damage things.
Then think about how you are going to handle either locking resources or handling simultaneous edits.
If you can tie edits to users you can provide some administrative functions for undoing all edits by a particular user, and banning that user.
Checking for quality would be tied to the particular data that your application is using. | 0.135221 | false | 2 | 439 |
2010-02-19 21:23:47.400 | Building a wiki application? | I'm building this app in Python with Django.
I would like to give parts of the site wiki like functionality,
but I don't know how to go on about reliability and security.
Make sure that good content is not ruined
Check for quality
Prevent spam from invading the site
The items requiring wiki like functionality are just a few: a couple of text fields.
Can anyone help on this one?
Would be very much appreciated. :) | Make sure that good content is not ruined = version each edit and allow roll-backs.
Check for quality = get people to help with that
Prevent spam from invading the site = get people to help with that, require login, add a captcha if need be, use nofollow for all links | 0.135221 | false | 2 | 439 |
2010-02-19 21:32:25.673 | Problem with asyn icmp ping | I'm writing service in python that async ping domains. So it must be able to ping many ip's at the same time. I wrote it on epoll ioloop, but have problem with packets loss.
When there are many simultaneous ICMP requests much part of replies on them didn't reach my servise. What may cause this situation and how i can make my service ping many hosts at the same time without packet loss?
Thanks) | A problem you might be having is due to the fact that ICMP is layer 3 of the OSI model and does not use a port for communication. In short, ICMP isn't really designed for this. The desired behavior is still possible but perhaps the IP Stack you are using is getting in the way and if this is on a Windows system then 100% sure this is your problem. I would fire up Wireshark to make sure you are actually getting incoming packets, if this is the case then I would use libpcap to track in ICMP replies. If the problem is with sending then you'll have to use raw sockets and build your own ICMP packets. | 1.2 | true | 1 | 440 |
2010-02-20 22:12:01.857 | Specifying python interpreter from virtualenv in emacs | Today I've been trying to bring more of the Python related modes into
my Emacs configuration but I haven't had much luck.
First what I've noticed is that depending on how Emacs is
launched (terminal vs from the desktop), the interpreter it decides to
use is different.
launched from KDE menu: M-! which python gives /usr/bin/python
launched from terminal: M-! which python gives ~/local/bin/python
I can kind of accept this since I have my .bashrc appending
~/local/bin to the path and I guess KDE ignores that by default. I can
work around this, however what I don't understand is then if I
activate a virtualenv, I would expect M-! which python to point to
~/project.env/bin/python however it still points to ~/local/bin/python.
Thus when I M-x py-shell, I get ~/local/bin/python so if I try to
M-x py-execute-buffer on a module that resides in a package in the
virtualenv, py-shell will complain about not knowing about modules
also in the virtualenv.
Setting py-python-command to "~/project.env/bin/python" seems to have no
effect after everything is loaded.
So I guess the overall crux of my question is, how does one get all
the python related emacs stuff pointing at the right interpreter? | So it seems that python-shell does the right thing by picking up the environment settings, whereas py-shell does not. python-shell is provided by python.el and py-shell is provided by python-mode.el , There's bug reports etc related to this, so I'm just not going to use py-shell for now. Figured I'd close the loop on this in case the google machine considers this a high ranking item for one reason or another. | 1.2 | true | 1 | 441 |
2010-02-21 18:50:17.927 | Exchange Oauth Request Token for Access Token fails Google API | I am having trouble exchanging my Oauth request token for an Access Token. My Python application successfully asks for a Request Token and then redirects to the Google login page asking to grant access to my website. When I grant access I retrieve a 200 status code but exchanging this authorized request token for an access token gives me a 'The token is invalid' message.
The Google Oauth documentation says: "Google redirects with token and verifier regardless of whether the token has been authorized." so it seems that authorizing the request token fails but then I am not sure how I should get an authorized request token. Any suggestions? | When you're exchanging for the access token, the oauth_verifier parameter is required. If you don't provide that parameter, then google will tell you that the token is invalid. | 1.2 | true | 1 | 442 |
2010-02-22 13:27:00.007 | How to handle user mangement in Django for groups that has same access but different rules? | Background information:
I have created an internal site for a company. Most of the work has gone into making calculation tools that their sale persons can use to make offers for clients. Create pdf offers and contracts that can be downloaded, compare prices etc. All of this is working fine.
Now their sale persons have been divided into two groups.
One group is sale personal that is hired by the company.
The other group is persons a company themselves.
The question:
My challenge now is, that I in some cases need to display different things depending on the type of sales person. Some of the rules for the calculation tools will have different rules as to which numbers will be allowed etc. But a big part of the site will still be the same for both groups.
What I would like to know, is if there is a good way of handling this problem?
My own thoughts:
I thought about managing this by using the groups that is available in contrib.auth. That way I could keep a single code base, but would have to make rules a lot of different places. Rules for validating forms to check if the numbers entered is allowed, will depend on the group the user is in. Some things will have different names, or the workflow might be a bit different. Some tools will only be available to one of the groups. This seems like a quick solution here and now, but if the two groups will need to change more and more, it seems like this would quickly become hard to manage.
I also thought about making two different sites. The idea here was to create apps that both groups use, so I only would need to make the code for that 1 place. Then I could make the custom parts for each site and wouldn't need to check for the user in most templates and views. But I'm not sure if this is a good way to go about things. It will create a lot of extra work, and if the two groups can use a lot of the same code, this might not really be needed.
The biggest concern is that I don't really know how this evolve, so it could end up with the two groups being entire different or with only very few differences. What I would like to do, is write some code that can support both scenarios so I wont end up regretting my choice a half year from now.
So, how do you handle this case of user management. I'm looking for ideas techniques or reusable apps that address this problem, not a ready made solution.
Clarifications:
My issue is not pure presentation that can be done with templates, but also that certain calculation tools (a form that is filled out) will have different rules/validation applied to them, and in some cases the calculations done will also be different. So they might see the same form, but wont be allowed to enter the same numbers, and the same numbers might not give the same result. | If I'm understanding you correctly, it seems like you want to have two different groups have access to all the same views, but they will see different numbers. You can achieve this effect by making separate templates for the different groups, and then loading the appropriate template for each view depending on the group of the current user.
Similarly you can use a context processor to put the current group into the context for every view, and then put conditionals in the templates to select which numbers to show.
The other option is to have two separate sets of views for the two different groups. Then use decorators on the views to make sure the groups only go to the views that are for them. | 0 | false | 1 | 443 |
2010-02-22 13:49:20.610 | How do I store a dict/list in a database? | If I have a dictionary full of nested stuff, how do I store that in a database, as a string? and then, convert it back to a dictionary when I'm ready to parse?
Edit: I just want to convert it to a string...and then back to a dictionary. | There are any number of serialization methods out there, JSON is readable, reasonably compact, supported natively, and portable. I prefer it over pickle, since the latter can execute arbitrary code and potentially introduce security holes, and because of its portability.
Depending on your data's layout, you may also be able to use your ORM to directly map the data into database constructs. | 0.16183 | false | 3 | 444 |
2010-02-22 13:49:20.610 | How do I store a dict/list in a database? | If I have a dictionary full of nested stuff, how do I store that in a database, as a string? and then, convert it back to a dictionary when I'm ready to parse?
Edit: I just want to convert it to a string...and then back to a dictionary. | You have two options
use a standard serialization format (json, xml, yaml, ...)
pros: you can access with a any language that can parse those formats (on the worst case you can write your own parser)
cons: could be slower to save and load the data (this depends of the implementation mostly)
use cPickle:
pros: easy to use, fast and native python way to do serialization.
cons: only python based apps can have access to the data. | 0.081452 | false | 3 | 444 |
2010-02-22 13:49:20.610 | How do I store a dict/list in a database? | If I have a dictionary full of nested stuff, how do I store that in a database, as a string? and then, convert it back to a dictionary when I'm ready to parse?
Edit: I just want to convert it to a string...and then back to a dictionary. | Options:
1) Pickling
2) XML
3) JSON
others I am sure. It has a lot to do on how much portability means to you. | 0.3154 | false | 3 | 444 |
2010-02-22 18:17:39.080 | Python: How to Access Linux Paths | Using Python, how does one parse/access files with Linux-specific features, like "~/.mozilla/firefox/*.default"? I've tried this, but it doesn't work.
Thanks | It's important to remember:
use of the tilde ~ expands the home directory as per Poke's answer
use of the forward slash / is the separator for linux / *nix directories
by default, *nix systems such as linux for example has a wild card globbing in the shell, for instance echo *.* will return back all files that match the asterisk dot asterisk (as per Will McCutcheon's answer!) | 0.201295 | false | 1 | 445 |
2010-02-22 21:22:10.427 | python logging to database | I'm seeking a way to let the python logger module to log to database and falls back to file system when the db is down.
So basically 2 things: How to let the logger log to database and how to make it fall to file logging when the db is down. | Old question, but dropping this for others. If you want to use python logging, you can add two handlers. One for writing to file, a rotating file handler. This is robust, and can be done regardless if the dB is up or not.
The other one can write to another service/module, like a pymongo integration.
Look up logging.config on how to setup your handlers from code or json. | 0.16183 | false | 1 | 446 |
2010-02-22 23:18:29.530 | How do I find missing dates in a list of sorted dates? | In Python how do I find all the missing days in a sorted list of dates? | Put the dates in a set and then iterate from the first date to the last using datetime.timedelta(), checking for containment in the set each time. | 0.04532 | false | 1 | 447 |
2010-02-23 12:08:12.327 | print_r functionality in iPython | Is there a way to get PHP-like print_r(object) funcionality in iPython?
I know I can use '?' to get info about an object, but how do I view the values of the object? | dir(object) will give you all its attribute names. | 0.201295 | false | 1 | 448 |