content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Sorting a string in array, making it sparsely populated
For example, say I have string like:
duck duck duck duck goose goose goose dog
And I want it to be as sparsely populated as possible, say in this case
duck goose duck goose dog duck goose duck
What sort of algorithm would you recommend? Snippets of code or general pointers would be useful, languages welcome Python, C++ and extra kudos if you have a way to do it in bash.
A:
I would sort the array by number of duplicates, starting from the most duplicated element, spread those elements as far apart as possible
in your example, duck is duplicated 4 times, so duck will be put in position n*8/4 for n from 0 to 3 inclusive.
Then put the next most repeated one (goose) in positions n*8/3 + 1 for n from 0 to 2 inclusive, If something is already placed there, just put it in the next empty spot. etc etc
A:
I think something like this is the general idea:
L = "duck duck duck duck goose goose goose dog ".split()
from itertools import cycle, islice, groupby
# from: http://docs.python.org/library/itertools.html#recipes
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
groups = [list(it) for k,it in groupby(sorted(L))]
# some extra print so you get the idea
print L
print groups
print list(roundrobin(*groups))
Output:
['dog', 'duck', 'duck', 'duck', 'duck', 'goose', 'goose', 'goose']
[['dog'], ['duck', 'duck', 'duck', 'duck'], ['goose', 'goose', 'goose']]
['dog', 'duck', 'goose', 'duck', 'goose', 'duck', 'goose', 'duck']
So you want some kind of round robin :-)
Well, round-robin is not perfect.
Here is the brute force (aka horribly inefficient) version of what you where thinking about.
# this is the function we want to maximize
def space_sum( L ):
""" return the sum of all spaces between all elements in L"""
unique = set(L)
def space(val):
""" count how many elements are between two val """
c = 0
# start with the first occurrence of val, then count
for x in L[1+L.index(val):]:
if x==val:
yield c
c = 0
else:
c += 1
return sum(sum(space(val)) for val in unique)
print max((space_sum(v), v) for v in permutations(L))
# there are tons of equally good solutions
print sorted(permutations(L), key=space_sum, reverse=True)[:100]
A:
How to measure sparsity actually? By the way a simple random shuffle may work.
A:
Sort you types by count.
Item Type 1 placed in the linked list. (Store middle link).
Next Item Type count = c total current list size = N.
Distribute Item 2 in c using 'bankers rounding' from the middle of the list.
Goto 2.
A:
There are good answers above about sorting and separating the most common strings the farthest. But if you have so much data that you can't sort or don't want to take the time, look into quasirandom numbers (http://mathworld.wolfram.com/QuasirandomSequence.html). There's a simple implementation of this in the Numerical Recipes book. These are numbers that "look" random, i.e., fill a space but try to avoid each other as much as possible. It's used a lot in applications where you want to "randomly" sample something, but rather than true random you want to sample the whole space efficiently.
A:
If I understood correctly your definition of “sparse”, this function should be exactly what you want:
# python ≥ 2.5
import itertools, heapq
def make_sparse(sequence):
grouped= sorted(sequence)
item_counts= []
for item, item_seq in itertools.groupby(grouped):
count= max(enumerate(item_seq))[0] + 1
item_counts.append( (-count, item) ) # negative count for heapq purposes
heapq.heapify(item_counts)
count1, item1= heapq.heappop(item_counts)
yield item1; count1+= 1
while True:
try:
count2, item2= heapq.heappop(item_counts)
except IndexError: # no other item remains
break
yield item2; count2+= 1
if count1 < 0:
heapq.heappush(item_counts, (count1, item1))
item1, count1= item2, count2
# loop is done, produce remaining item1 items
while count1 < 0:
yield item1; count1+= 1
if __name__ == "__main__":
# initial example
print list(make_sparse(
"duck duck duck duck goose goose goose dog".split()))
# updated example
print list(make_sparse([
'duck', 'duck', 'duck', 'duck', 'duck', 'duck',
'goose', 'goose', 'goose', 'goose', 'dog', 'dog']))
# now a hard case: item 'a' appears more than:
# > total_len//2 times if total_len is even
# > total_len//2+1 times if total_len is odd
print list(make_sparse("aaaaaabbcc"))
These examples produce this output:
['duck', 'goose', 'duck', 'goose', 'duck', 'dog', 'duck', 'goose']
['duck', 'goose', 'duck', 'goose', 'duck', 'dog', 'duck', 'goose', 'duck', 'dog', 'duck', 'goose']
['a', 'b', 'a', 'c', 'a', 'b', 'a', 'c', 'a', 'a']
A subtle note: in the first and second examples, reversing the output order might look more optimal.
| Sorting a string in array, making it sparsely populated | For example, say I have string like:
duck duck duck duck goose goose goose dog
And I want it to be as sparsely populated as possible, say in this case
duck goose duck goose dog duck goose duck
What sort of algorithm would you recommend? Snippets of code or general pointers would be useful, languages welcome Python, C++ and extra kudos if you have a way to do it in bash.
| [
"I would sort the array by number of duplicates, starting from the most duplicated element, spread those elements as far apart as possible\nin your example, duck is duplicated 4 times, so duck will be put in position n*8/4 for n from 0 to 3 inclusive.\nThen put the next most repeated one (goose) in positions n*8/3 + 1 for n from 0 to 2 inclusive, If something is already placed there, just put it in the next empty spot. etc etc\n",
"I think something like this is the general idea:\nL = \"duck duck duck duck goose goose goose dog \".split() \n\nfrom itertools import cycle, islice, groupby\n\n# from: http://docs.python.org/library/itertools.html#recipes\ndef roundrobin(*iterables):\n \"roundrobin('ABC', 'D', 'EF') --> A D E B F C\"\n # Recipe credited to George Sakkis\n pending = len(iterables)\n nexts = cycle(iter(it).next for it in iterables)\n while pending:\n try:\n for next in nexts:\n yield next()\n except StopIteration:\n pending -= 1\n nexts = cycle(islice(nexts, pending))\n\ngroups = [list(it) for k,it in groupby(sorted(L))]\n\n# some extra print so you get the idea\nprint L\nprint groups\nprint list(roundrobin(*groups))\n\nOutput:\n['dog', 'duck', 'duck', 'duck', 'duck', 'goose', 'goose', 'goose']\n[['dog'], ['duck', 'duck', 'duck', 'duck'], ['goose', 'goose', 'goose']]\n['dog', 'duck', 'goose', 'duck', 'goose', 'duck', 'goose', 'duck']\n\nSo you want some kind of round robin :-)\n\nWell, round-robin is not perfect. \nHere is the brute force (aka horribly inefficient) version of what you where thinking about. \n# this is the function we want to maximize\ndef space_sum( L ):\n \"\"\" return the sum of all spaces between all elements in L\"\"\"\n unique = set(L)\n def space(val):\n \"\"\" count how many elements are between two val \"\"\"\n c = 0\n # start with the first occurrence of val, then count\n for x in L[1+L.index(val):]: \n if x==val:\n yield c\n c = 0\n else:\n c += 1\n return sum(sum(space(val)) for val in unique)\n\nprint max((space_sum(v), v) for v in permutations(L))\n\n# there are tons of equally good solutions\nprint sorted(permutations(L), key=space_sum, reverse=True)[:100] \n\n",
"How to measure sparsity actually? By the way a simple random shuffle may work.\n",
"Sort you types by count.\n\nItem Type 1 placed in the linked list. (Store middle link).\nNext Item Type count = c total current list size = N.\n Distribute Item 2 in c using 'bankers rounding' from the middle of the list.\nGoto 2.\n\n",
"There are good answers above about sorting and separating the most common strings the farthest. But if you have so much data that you can't sort or don't want to take the time, look into quasirandom numbers (http://mathworld.wolfram.com/QuasirandomSequence.html). There's a simple implementation of this in the Numerical Recipes book. These are numbers that \"look\" random, i.e., fill a space but try to avoid each other as much as possible. It's used a lot in applications where you want to \"randomly\" sample something, but rather than true random you want to sample the whole space efficiently.\n",
"If I understood correctly your definition of “sparse”, this function should be exactly what you want:\n# python ≥ 2.5\nimport itertools, heapq\n\ndef make_sparse(sequence):\n grouped= sorted(sequence)\n item_counts= []\n for item, item_seq in itertools.groupby(grouped):\n count= max(enumerate(item_seq))[0] + 1\n item_counts.append( (-count, item) ) # negative count for heapq purposes\n heapq.heapify(item_counts)\n\n count1, item1= heapq.heappop(item_counts)\n yield item1; count1+= 1\n while True:\n try:\n count2, item2= heapq.heappop(item_counts)\n except IndexError: # no other item remains\n break\n yield item2; count2+= 1\n if count1 < 0:\n heapq.heappush(item_counts, (count1, item1))\n item1, count1= item2, count2\n\n # loop is done, produce remaining item1 items\n while count1 < 0:\n yield item1; count1+= 1\n\nif __name__ == \"__main__\":\n # initial example\n print list(make_sparse(\n \"duck duck duck duck goose goose goose dog\".split()))\n # updated example\n print list(make_sparse([\n 'duck', 'duck', 'duck', 'duck', 'duck', 'duck',\n 'goose', 'goose', 'goose', 'goose', 'dog', 'dog']))\n # now a hard case: item 'a' appears more than:\n # > total_len//2 times if total_len is even\n # > total_len//2+1 times if total_len is odd\n print list(make_sparse(\"aaaaaabbcc\"))\n\nThese examples produce this output:\n['duck', 'goose', 'duck', 'goose', 'duck', 'dog', 'duck', 'goose']\n['duck', 'goose', 'duck', 'goose', 'duck', 'dog', 'duck', 'goose', 'duck', 'dog', 'duck', 'goose']\n['a', 'b', 'a', 'c', 'a', 'b', 'a', 'c', 'a', 'a']\n\nA subtle note: in the first and second examples, reversing the output order might look more optimal.\n"
] | [
5,
3,
2,
2,
1,
1
] | [] | [] | [
"algorithm",
"bash",
"c++",
"python"
] | stackoverflow_0002897067_algorithm_bash_c++_python.txt |
Q:
How to connect to a LDAP server using a p12 certificate
I want to connect to a LDAP server using a .p12 certificate instead of using a username and password. The Java solution for this looks like
String ldapURL = "ldaps://"+host+":"+port;
System.setProperty("javax.net.ssl.keyStoreType", "PKCS12" );
System.setProperty("javax.net.ssl.keyStore",keystore);
System.setProperty("javax.net.ssl.keyStorePassword", keystorePassword);
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapURL);
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put(Context.REFERRAL, "follow");
try
{
// Create initial context
LdapContext ctx = new InitialLdapContext(env, null);
// Perform client authentication using TLS credentials
ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "EXTERNAL");
SearchControls ctls = new SearchControls();
// Specify the search filter to match
String filter = "(objectClass=*)";
// Search for objects using the filter
NamingEnumeration answer = ctx.search("ou="+elemType[i]+","+siteSpecificBaseDN, filter, ctls);
...
Can I do the same using python? I only could find examples showing how to connect to a LDAP server with python-ldap using a username and a password, but that is not what I need. If it is not possible using .p12 certificate, it would also help me, if there is a solution using x509 certificates (.pem format).
A:
If you use python-ldap, you can use the TLS options to set these parameters.
ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, "/path/to/trustedcerts.pem")
ldap.set_option(ldap.OPT_X_TLS_CERTFILE, "/path/to/usercert.pem")
ldap.set_option(ldap.OPT_X_TLS_KEYFILE, "/path/to/user.key.pem")
ds = ldap.initialize("ldaps://ldap.example.com:port/")
# If using START_TLS instead of ldaps:
# ds = ldap.initialize("ldap://ldap.example.com:port/")
# ds.start_tls_s()
In this case:
trustedcerts.pem is the equivalent of the trust store. It's a concatenation of the trusted certificates you want in PEM format. You could also use a directory with individual certificates with OPT_X_TLS_CACERTFILE, but I think it's not supported by GnuTLS, so it depends on which TLS library python-ldap and its OpenLDAP client library have been compiled against. More details on the underlying direcives in the OpenLDAP manual.
usercert.pem is your user certificate, in PEM format (you'll have to extract it from your PKCS#12 file)
user.key.pem is your private key (again, it needs to be extracted from the p12 file)
Certificate and key extraction from a PKCS#12 file can be done with OpenSSL using this:
openssl pkcs12 -in userstore.p12 -clcerts -nokeys -out usercert.pem
openssl pkcs12 -in userstore.p12 -nocerts -nodes -out user.key.pem
Note: if you extract the private key (in user.key.pem) this way (-nodes), it will not be password-protected, so you'll need to make sure this file is not readable by anyone else. I don't think OpenLDAP (and even less its Python binding) let you prompt for a password interactively to get around that problem, but I'm not sure.
A:
It looks like ldaptor can provide you with this functionality. It's built on top of twisted, which has support for SSL built into the twisted.internet.ssl module.
See: ldaptor.protocols.ldap.ldapclient.startTLS()
| How to connect to a LDAP server using a p12 certificate | I want to connect to a LDAP server using a .p12 certificate instead of using a username and password. The Java solution for this looks like
String ldapURL = "ldaps://"+host+":"+port;
System.setProperty("javax.net.ssl.keyStoreType", "PKCS12" );
System.setProperty("javax.net.ssl.keyStore",keystore);
System.setProperty("javax.net.ssl.keyStorePassword", keystorePassword);
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapURL);
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put(Context.REFERRAL, "follow");
try
{
// Create initial context
LdapContext ctx = new InitialLdapContext(env, null);
// Perform client authentication using TLS credentials
ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "EXTERNAL");
SearchControls ctls = new SearchControls();
// Specify the search filter to match
String filter = "(objectClass=*)";
// Search for objects using the filter
NamingEnumeration answer = ctx.search("ou="+elemType[i]+","+siteSpecificBaseDN, filter, ctls);
...
Can I do the same using python? I only could find examples showing how to connect to a LDAP server with python-ldap using a username and a password, but that is not what I need. If it is not possible using .p12 certificate, it would also help me, if there is a solution using x509 certificates (.pem format).
| [
"If you use python-ldap, you can use the TLS options to set these parameters.\nldap.set_option(ldap.OPT_X_TLS_CACERTFILE, \"/path/to/trustedcerts.pem\")\nldap.set_option(ldap.OPT_X_TLS_CERTFILE, \"/path/to/usercert.pem\")\nldap.set_option(ldap.OPT_X_TLS_KEYFILE, \"/path/to/user.key.pem\")\n\nds = ldap.initialize(\"ldaps://ldap.example.com:port/\")\n# If using START_TLS instead of ldaps:\n# ds = ldap.initialize(\"ldap://ldap.example.com:port/\")\n# ds.start_tls_s()\n\nIn this case:\n\ntrustedcerts.pem is the equivalent of the trust store. It's a concatenation of the trusted certificates you want in PEM format. You could also use a directory with individual certificates with OPT_X_TLS_CACERTFILE, but I think it's not supported by GnuTLS, so it depends on which TLS library python-ldap and its OpenLDAP client library have been compiled against. More details on the underlying direcives in the OpenLDAP manual.\nusercert.pem is your user certificate, in PEM format (you'll have to extract it from your PKCS#12 file)\nuser.key.pem is your private key (again, it needs to be extracted from the p12 file)\n\nCertificate and key extraction from a PKCS#12 file can be done with OpenSSL using this:\nopenssl pkcs12 -in userstore.p12 -clcerts -nokeys -out usercert.pem\nopenssl pkcs12 -in userstore.p12 -nocerts -nodes -out user.key.pem\n\nNote: if you extract the private key (in user.key.pem) this way (-nodes), it will not be password-protected, so you'll need to make sure this file is not readable by anyone else. I don't think OpenLDAP (and even less its Python binding) let you prompt for a password interactively to get around that problem, but I'm not sure.\n",
"It looks like ldaptor can provide you with this functionality. It's built on top of twisted, which has support for SSL built into the twisted.internet.ssl module.\nSee: ldaptor.protocols.ldap.ldapclient.startTLS()\n"
] | [
2,
0
] | [] | [] | [
"certificate",
"ldap",
"pkcs#12",
"python"
] | stackoverflow_0002193362_certificate_ldap_pkcs#12_python.txt |
Q:
What methods and tools do you use to design and analyze the workflow in a web application (for a tiny team)
Note: I use TRAC integrated with SVN, framework testing tools, an excellent mixture of staging servers, development servers, and other tools to speed development and keep track of tasks.
I am asking about the specific process of design, and even more specifically, the design of functionality and flow in a web application.
--- Original question ---
So far I spend a lot of time with my text editor open basically talking to myself, then coding for a while, then talking to myself again. When there is more than just me we do some whiteboarding, but that's about it.
What do you find works well, specifically for projects for very small teams or one-developer shows.
BTW I usually develop with Django, this last project also involves RabbitMQ and Orbited, plus a fair chunk of jquery-assisted JavaScript.
A:
Another mainly solo developer here. I recommend using a bug/issue tracker. I use TRAC (although I'm looking at alternatives). It might seem strange, since you're the one creating, assigning, and closing all tickets, but it really helps to plan out/prioritize development. I also use the wiki to organize my thoughts on the roadmap, main goals of each release, etc.
A:
+1 for a good question.
Web development is not much different to any other development.
P.20 of that venerable classic breaks a typical project down into 1/3 planning, 1/6 coding, 1/4 component test and 1/4 system test. I might catch some flak for that, YMMV and all, but that looks about right to me.
Whether or not you agree with the proportions, the message is "don't jump right in and code; think about it first (measure twice, cut once). How often have you jumped in and coded only to get near to "then end" and discover that you have a fundamental design flaw and have to through away much of your code & rewrite chunks more?
You need methodologies (Processes) and Tools, and each can necessitate the other.
Methodologies
Design it first! Gather requirements, make a system level design document then detailed design. If you are more than one, have these reviewed by someone (client can maybe review the high level docs?). If if you are alone, the simple act of writing it down forces you to slow down and think and will uncover problems. A good idea is to have a requirements traceability matrix to ensure that each requirement gets designed, implemented and tested somewhere.
After you review the high level design, you can being the detailed design, and after you review that, you can begin to implement. When the high level design is reviewed you can, in parallel, or later, produce a high level test spec. When the detailed level design is reviewed you can, in parallel, or later, produce unit test specs.
Note that test cases should be automated and should require no human interaction. Get into the habit of running regression tests after every code change - automate this if you can, with nightly build and or coupled with check-in to your version control system.
When everything is thoroughly unit tested, you can begin your system level testing.
Tools
At the very least you ought to be considering these:
A good IDE (WYSIWYG for web design), preferably with debugging capabilities, and it would be nice if it interfaced with your version control system, bug tracker, etc. A spill chuker is useful for websites ;-)
A project management tool to plan the project (Open Workbench does some nice Gantt charts)
A version control system.
A change request and bug tracker.
An automated test system.
An automated build system like Hudson (it may not seem relevant if you don't compile and link, but at least it can verify that all files exist and can schedule regression testing for you)
A backup system in case of disk crash, laptop loss, etc.
And if all that seems like too much "extra" to do, I was sceptical too once, until I saw that it actually saves time because you discover problems earlier when they cost less to fix. In fact, I am so sure of this that I do all of my personal one-man hobby projects this way. All of them.
A:
Pencils!
Seriously, we use JIRA to track work/issue, Confluence to track requirements before they're baked enough to put in JIRA.. Anything to scratch together wire-frames, etc. (Including OmniGraffle, and Pencils).
I find the combination of JIRA and Confluence for tracking chunks of work and longer-lived concepts and standards pretty darned effective.
| What methods and tools do you use to design and analyze the workflow in a web application (for a tiny team) | Note: I use TRAC integrated with SVN, framework testing tools, an excellent mixture of staging servers, development servers, and other tools to speed development and keep track of tasks.
I am asking about the specific process of design, and even more specifically, the design of functionality and flow in a web application.
--- Original question ---
So far I spend a lot of time with my text editor open basically talking to myself, then coding for a while, then talking to myself again. When there is more than just me we do some whiteboarding, but that's about it.
What do you find works well, specifically for projects for very small teams or one-developer shows.
BTW I usually develop with Django, this last project also involves RabbitMQ and Orbited, plus a fair chunk of jquery-assisted JavaScript.
| [
"Another mainly solo developer here. I recommend using a bug/issue tracker. I use TRAC (although I'm looking at alternatives). It might seem strange, since you're the one creating, assigning, and closing all tickets, but it really helps to plan out/prioritize development. I also use the wiki to organize my thoughts on the roadmap, main goals of each release, etc.\n",
"+1 for a good question.\nWeb development is not much different to any other development.\nP.20 of that venerable classic breaks a typical project down into 1/3 planning, 1/6 coding, 1/4 component test and 1/4 system test. I might catch some flak for that, YMMV and all, but that looks about right to me.\nWhether or not you agree with the proportions, the message is \"don't jump right in and code; think about it first (measure twice, cut once). How often have you jumped in and coded only to get near to \"then end\" and discover that you have a fundamental design flaw and have to through away much of your code & rewrite chunks more?\nYou need methodologies (Processes) and Tools, and each can necessitate the other.\nMethodologies\n\nDesign it first! Gather requirements, make a system level design document then detailed design. If you are more than one, have these reviewed by someone (client can maybe review the high level docs?). If if you are alone, the simple act of writing it down forces you to slow down and think and will uncover problems. A good idea is to have a requirements traceability matrix to ensure that each requirement gets designed, implemented and tested somewhere.\nAfter you review the high level design, you can being the detailed design, and after you review that, you can begin to implement. When the high level design is reviewed you can, in parallel, or later, produce a high level test spec. When the detailed level design is reviewed you can, in parallel, or later, produce unit test specs.\nNote that test cases should be automated and should require no human interaction. Get into the habit of running regression tests after every code change - automate this if you can, with nightly build and or coupled with check-in to your version control system.\nWhen everything is thoroughly unit tested, you can begin your system level testing.\n\nTools\nAt the very least you ought to be considering these: \n\nA good IDE (WYSIWYG for web design), preferably with debugging capabilities, and it would be nice if it interfaced with your version control system, bug tracker, etc. A spill chuker is useful for websites ;-) \nA project management tool to plan the project (Open Workbench does some nice Gantt charts) \nA version control system. \nA change request and bug tracker. \nAn automated test system. \nAn automated build system like Hudson (it may not seem relevant if you don't compile and link, but at least it can verify that all files exist and can schedule regression testing for you) \nA backup system in case of disk crash, laptop loss, etc. \n\nAnd if all that seems like too much \"extra\" to do, I was sceptical too once, until I saw that it actually saves time because you discover problems earlier when they cost less to fix. In fact, I am so sure of this that I do all of my personal one-man hobby projects this way. All of them.\n",
"Pencils!\nSeriously, we use JIRA to track work/issue, Confluence to track requirements before they're baked enough to put in JIRA.. Anything to scratch together wire-frames, etc. (Including OmniGraffle, and Pencils).\nI find the combination of JIRA and Confluence for tracking chunks of work and longer-lived concepts and standards pretty darned effective.\n"
] | [
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003081412_python.txt |
Q:
Portable version of pyCrypto? - Python
does a portable version of pyCrypto exist? would one be easy to create?
Help would be awesome!
A:
I still don't quite understand what you mean by portable or by using a "drag and drop" folder. But pre-built binaries for Windows can be found here.
| Portable version of pyCrypto? - Python | does a portable version of pyCrypto exist? would one be easy to create?
Help would be awesome!
| [
"I still don't quite understand what you mean by portable or by using a \"drag and drop\" folder. But pre-built binaries for Windows can be found here.\n"
] | [
1
] | [] | [] | [
"aes",
"django",
"portability",
"pycrypto",
"python"
] | stackoverflow_0003084142_aes_django_portability_pycrypto_python.txt |
Q:
python apt-get list upgrades
How can I get a list of upgrade packages available and write it to file using python?
When I run apt-get upgrade > output
it works in bash. I think I have to send the trap signal (Ctrl+C) in the python program.
Any suggestions on how to achieve this?
I tried this on the code now:
#!/usr/bin/env python
import subprocess
apt = subprocess.Popen([r"apt-get", "-V", "upgrade", ">", "/usr/src/python/upgrade.log"], stdin=subprocess.PIPE)
apt_stdin = apt.communicate()[0]
but it exits and does not write to the file.
This works but I am getting error when I port this to other Debian systems:
import apt
cache=apt.Cache()
cache.update()
cache.open(None)
cache.upgrade()
for pkg in cache.get_changes():
# print pkg.name, pkg.summary
fileHandle = open('/tmp/upgrade.log', 'a')
fileHandle.write(pkg.name + " - " + pkg.summary + "\n")
and the error....
/usr/lib/python2.5/site-packages/apt/__init__.py:18: FutureWarning: apt API not stable yet
warnings.warn("apt API not stable yet", FutureWarning)
Traceback (most recent call last):
File "apt-notify.py", line 13, in <module>
for pkg in cache.get_changes():
AttributeError: 'Cache' object has no attribute 'get_changes'
A:
Why not use the python-apt module eg.
import apt
cache=apt.Cache()
cache.update()
cache.open(None)
cache.upgrade()
for pkg in cache.getChanges():
print pkg.sourcePackageName, pkg.isUpgradeable
also read the link in badp's comment
A:
Use the Python module subprocess and close stdin to tell the child process that it should exit.
A:
Using > to redirect output to a file is something the shell does. Your (updated) code is passing the > to apt-get instead, which has no idea what to do with it. Adding shell=True to your invocation of subprocess.Popen will run the argument list through the shell first, which will make the redirect work.
| python apt-get list upgrades | How can I get a list of upgrade packages available and write it to file using python?
When I run apt-get upgrade > output
it works in bash. I think I have to send the trap signal (Ctrl+C) in the python program.
Any suggestions on how to achieve this?
I tried this on the code now:
#!/usr/bin/env python
import subprocess
apt = subprocess.Popen([r"apt-get", "-V", "upgrade", ">", "/usr/src/python/upgrade.log"], stdin=subprocess.PIPE)
apt_stdin = apt.communicate()[0]
but it exits and does not write to the file.
This works but I am getting error when I port this to other Debian systems:
import apt
cache=apt.Cache()
cache.update()
cache.open(None)
cache.upgrade()
for pkg in cache.get_changes():
# print pkg.name, pkg.summary
fileHandle = open('/tmp/upgrade.log', 'a')
fileHandle.write(pkg.name + " - " + pkg.summary + "\n")
and the error....
/usr/lib/python2.5/site-packages/apt/__init__.py:18: FutureWarning: apt API not stable yet
warnings.warn("apt API not stable yet", FutureWarning)
Traceback (most recent call last):
File "apt-notify.py", line 13, in <module>
for pkg in cache.get_changes():
AttributeError: 'Cache' object has no attribute 'get_changes'
| [
"Why not use the python-apt module eg.\nimport apt\ncache=apt.Cache()\ncache.update()\ncache.open(None)\ncache.upgrade()\nfor pkg in cache.getChanges():\n print pkg.sourcePackageName, pkg.isUpgradeable\n\nalso read the link in badp's comment\n",
"Use the Python module subprocess and close stdin to tell the child process that it should exit.\n",
"Using > to redirect output to a file is something the shell does. Your (updated) code is passing the > to apt-get instead, which has no idea what to do with it. Adding shell=True to your invocation of subprocess.Popen will run the argument list through the shell first, which will make the redirect work.\n"
] | [
3,
2,
0
] | [] | [] | [
"apt_get",
"python"
] | stackoverflow_0003092613_apt_get_python.txt |
Q:
growing python process memory over time
My python code process memory increases dynamically as it stores dynamic data in list, dictionary and tuples wherever necessary. Though all those dynamic data is cleared physically in their variables after then, the memory is not shooting down.
Hence i felt like there is a memory leak and i used gc.collect() method to collect all the unfreed memory. But i could not make the memory to minimum when there is no data in the variables.
A:
It's very hard, in general, for a process to "give memory back to the OS" (until the process terminates and the OS gets back all the memory, of course) because (in most implementation) what malloc returns is carved out of big blocks for efficiency, but the whole block can't be given back if any part of it is still in use -- so, most C standard libraries don't even try.
For a decent discussion in a Python context, see e.g. here. Evan Jones fixed some Python-specific issues as described here and here, but his patch is in the trunk since Python 2.5, so the problems you're observing are definitely with the system malloc package, not with Python per se. A 2.6-specific explanation is here and here.
A SO thread is here, where Hugh Allen in his answer quotes Firefox programmers to the extend that Mac OS X is a system where it's basically impossible for a process to give memory back to the OS.
So, only by terminating a process can you be sure to release its memory. For example, a long-running server, once in a while, could snapshot its state to disk and shut down (with a tiny watchdog process, system or custom, watching over it and restarting it). If you know that the next operation will take a lot of memory for a short time, often you can os.fork, do the memory-hungry work in the child process, and have results (if any) returned to the parent process via a pipe as the child process terminates. And so on, and so forth.
A:
How big are we talking? Python itself takes up some amount of memory.. up to maybe 30 or 40 MB I believe. If it is bigger than that and not getting collected, you have a memory leak. Only garbage with no references can be collected, somehow your extra stuff is still referenced. Do a memory profile and see what is going on.
| growing python process memory over time | My python code process memory increases dynamically as it stores dynamic data in list, dictionary and tuples wherever necessary. Though all those dynamic data is cleared physically in their variables after then, the memory is not shooting down.
Hence i felt like there is a memory leak and i used gc.collect() method to collect all the unfreed memory. But i could not make the memory to minimum when there is no data in the variables.
| [
"It's very hard, in general, for a process to \"give memory back to the OS\" (until the process terminates and the OS gets back all the memory, of course) because (in most implementation) what malloc returns is carved out of big blocks for efficiency, but the whole block can't be given back if any part of it is still in use -- so, most C standard libraries don't even try. \nFor a decent discussion in a Python context, see e.g. here. Evan Jones fixed some Python-specific issues as described here and here, but his patch is in the trunk since Python 2.5, so the problems you're observing are definitely with the system malloc package, not with Python per se. A 2.6-specific explanation is here and here.\nA SO thread is here, where Hugh Allen in his answer quotes Firefox programmers to the extend that Mac OS X is a system where it's basically impossible for a process to give memory back to the OS.\nSo, only by terminating a process can you be sure to release its memory. For example, a long-running server, once in a while, could snapshot its state to disk and shut down (with a tiny watchdog process, system or custom, watching over it and restarting it). If you know that the next operation will take a lot of memory for a short time, often you can os.fork, do the memory-hungry work in the child process, and have results (if any) returned to the parent process via a pipe as the child process terminates. And so on, and so forth.\n",
"How big are we talking? Python itself takes up some amount of memory.. up to maybe 30 or 40 MB I believe. If it is bigger than that and not getting collected, you have a memory leak. Only garbage with no references can be collected, somehow your extra stuff is still referenced. Do a memory profile and see what is going on.\n"
] | [
10,
0
] | [] | [] | [
"memory_management",
"python"
] | stackoverflow_0003097236_memory_management_python.txt |
Q:
How do I get the page content from PAMIE?
I'm using PAMIE to control IE to automatically browse to a list of URLs. I want to find which URLs return IE's malware warning and which ones don't. I'm new to PAMIE, and PAMIE's documentation is non-existent or cryptic at best. How can I get a page's content from PAMIE so I can work with it in Python?
A:
Browsing the CPamie.py file did the trick. Turns out, I didn't even need the page content - PAMIE's findText method lets you match any string on the page. Works great!
| How do I get the page content from PAMIE? | I'm using PAMIE to control IE to automatically browse to a list of URLs. I want to find which URLs return IE's malware warning and which ones don't. I'm new to PAMIE, and PAMIE's documentation is non-existent or cryptic at best. How can I get a page's content from PAMIE so I can work with it in Python?
| [
"Browsing the CPamie.py file did the trick. Turns out, I didn't even need the page content - PAMIE's findText method lets you match any string on the page. Works great!\n"
] | [
0
] | [] | [] | [
"pamie",
"python"
] | stackoverflow_0003073151_pamie_python.txt |
Q:
Waiting on event with Twisted and PB
I have a python app that uses multiple threads and I am curious about the best way to wait for something in python without burning cpu or locking the GIL.
my app uses twisted and I spawn a thread to run a long operation so I do not stomp on the reactor thread. This long operation also spawns some threads using twisted's deferToThread to do something else, and the original thread wants to wait for the results from the defereds.
What I have been doing is this
while self._waiting:
time.sleep( 0.01 )
which seemed to disrupt twisted PB's objects from receiving messages so I thought sleep was locking the GIL. Further investigation by the posters below revealed however that it does not.
There are better ways to wait on threads without blocking the reactor thread or python posted below.
A:
If you're already using Twisted, you should never need to "wait" like this.
As you've described it:
I spawn a thread to run a long operation ... This long operation also spawns some threads using twisted's deferToThread ...
That implies that you're calling deferToThread from your "long operation" thread, not from your main thread (the one where reactor.run() is running). As Jean-Paul Calderone already noted in a comment, you can only call Twisted APIs (such as deferToThread) from the main reactor thread.
The lock-up that you're seeing is a common symptom of not following this rule. It has nothing to do with the GIL, and everything to do with the fact that you have put Twisted's reactor into a broken state.
Based on your loose description of your program, I've tried to write a sample program that does what you're talking about based entirely on Twisted APIs, spawning all threads via Twisted and controlling them all from the main reactor thread.
import time
from twisted.internet import reactor
from twisted.internet.defer import gatherResults
from twisted.internet.threads import deferToThread, blockingCallFromThread
def workReallyHard():
"'Work' function, invoked in a thread."
time.sleep(0.2)
def longOperation():
for x in range(10):
workReallyHard()
blockingCallFromThread(reactor, startShortOperation, x)
result = blockingCallFromThread(reactor, gatherResults, shortOperations)
return 'hooray', result
def shortOperation(value):
workReallyHard()
return value * 100
shortOperations = []
def startShortOperation(value):
def done(result):
print 'Short operation complete!', result
return result
shortOperations.append(
deferToThread(shortOperation, value).addCallback(done))
d = deferToThread(longOperation)
def allDone(result):
print 'Long operation complete!', result
reactor.stop()
d.addCallback(allDone)
reactor.run()
Note that at the point in allDone where the reactor is stopped, you could fire off another "long operation" and have it start the process all over again.
A:
Have you tried condition variables? They are used like
condition = Condition()
def consumer_in_thread_A():
condition.acquire()
try:
while resource_not_yet_available:
condition.wait()
# Here, the resource is available and may be
# consumed
finally:
condition.release()
def produce_in_thread_B():
# ... create resource, whatsoever
condition.acquire()
try:
condition.notify_all()
finally:
condition.release()
Condition variables act as locks (acquire and release), but their main purpose is to provide the control mechanism which allows to wait for them to be notify-d or notify_all-d.
A:
I recently found out that calling
time.sleep( X ) will lock the GIL for
the entire time X and therefore freeze
ALL python threads for that time
period.
You found wrongly -- this is definitely not how it works. What's the source where you found this mis-information?
Anyway, then you clarify (in comments -- better edit your Q!) that you're using deferToThread and your problem with this is that...:
Well yes I defer the action to a
thread and give twisted a callback.
But the parent thread needs to wait
for the whole series of sub threads to
complete before it can move onto a new
set of sub threads to spawn
So use as the callback a method of an object with a counter -- start it at 0, increment it by one every time you're deferring-to-thread and decrement it by one in the callback method.
When the callback method sees that the decremented counter has gone back to 0, it knows that we're done waiting "for the whole series of sub threads to complete" and then the time has come to "move on to a new set of sub threads to spawn", and thus, in that case only, calls the "spawn a new set of sub threads" function or method -- it's that easy!
E.g. (net of typos &c as this is untested code, just to give you the idea)...:
class Waiter(object):
def __init__(self, what_next, *a, **k):
self.counter = 0
self.what_next = what_next
self.a = a
self.k = k
def one_more(self):
self.counter += 1
def do_wait(self, *dont_care):
self.counter -= 1
if self.counter == 0:
self.what_next(*self.a, **self.k)
def spawn_one_thread(waiter, long_calculation, *a, **k):
waiter.one_more()
d = threads.deferToThread(long_calculation, *a, **k)
d.addCallback(waiter.do_wait)
def spawn_all(waiter, list_of_lists_of_functions_args_and_kwds):
if not list_of_lists_of_functions_args_and_kwds:
return
if waiter is None:
waiter=Waiter(spawn_all, list_of_lists_of_functions_args_and_kwds)
this_time = list_of_list_of_functions_args_and_kwds.pop(0)
for f, a, k in this_time:
spawn_one_thread(waiter, f, *a, **k)
def start_it_all(list_of_lists_of_functions_args_and_kwds):
spawn_all(None, list_of_lists_of_functions_args_and_kwds)
A:
According to the Python source, time.sleep() does not hold the GIL.
http://code.python.org/hg/trunk/file/98e56689c59c/Modules/timemodule.c#l920
Note the use of Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS, as documented here:
http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock
A:
The threading module allows you to spawn a thread, which is then represented by a Thread object. That object has a join method that you can use to wait for the subthread to complete.
See http://docs.python.org/library/threading.html#module-threading
| Waiting on event with Twisted and PB | I have a python app that uses multiple threads and I am curious about the best way to wait for something in python without burning cpu or locking the GIL.
my app uses twisted and I spawn a thread to run a long operation so I do not stomp on the reactor thread. This long operation also spawns some threads using twisted's deferToThread to do something else, and the original thread wants to wait for the results from the defereds.
What I have been doing is this
while self._waiting:
time.sleep( 0.01 )
which seemed to disrupt twisted PB's objects from receiving messages so I thought sleep was locking the GIL. Further investigation by the posters below revealed however that it does not.
There are better ways to wait on threads without blocking the reactor thread or python posted below.
| [
"If you're already using Twisted, you should never need to \"wait\" like this.\nAs you've described it:\n\nI spawn a thread to run a long operation ... This long operation also spawns some threads using twisted's deferToThread ...\n\nThat implies that you're calling deferToThread from your \"long operation\" thread, not from your main thread (the one where reactor.run() is running). As Jean-Paul Calderone already noted in a comment, you can only call Twisted APIs (such as deferToThread) from the main reactor thread.\nThe lock-up that you're seeing is a common symptom of not following this rule. It has nothing to do with the GIL, and everything to do with the fact that you have put Twisted's reactor into a broken state.\nBased on your loose description of your program, I've tried to write a sample program that does what you're talking about based entirely on Twisted APIs, spawning all threads via Twisted and controlling them all from the main reactor thread.\nimport time\n\nfrom twisted.internet import reactor\nfrom twisted.internet.defer import gatherResults\nfrom twisted.internet.threads import deferToThread, blockingCallFromThread\n\ndef workReallyHard():\n \"'Work' function, invoked in a thread.\"\n time.sleep(0.2)\n\ndef longOperation():\n for x in range(10):\n workReallyHard()\n blockingCallFromThread(reactor, startShortOperation, x)\n result = blockingCallFromThread(reactor, gatherResults, shortOperations)\n return 'hooray', result\n\ndef shortOperation(value):\n workReallyHard()\n return value * 100\n\nshortOperations = []\n\ndef startShortOperation(value):\n def done(result):\n print 'Short operation complete!', result\n return result\n shortOperations.append(\n deferToThread(shortOperation, value).addCallback(done))\n\nd = deferToThread(longOperation)\ndef allDone(result):\n print 'Long operation complete!', result\n reactor.stop()\nd.addCallback(allDone)\n\nreactor.run()\n\nNote that at the point in allDone where the reactor is stopped, you could fire off another \"long operation\" and have it start the process all over again.\n",
"Have you tried condition variables? They are used like\ncondition = Condition()\n\ndef consumer_in_thread_A():\n condition.acquire()\n try:\n while resource_not_yet_available:\n condition.wait()\n # Here, the resource is available and may be \n # consumed\n finally:\n condition.release()\n\ndef produce_in_thread_B():\n # ... create resource, whatsoever\n condition.acquire()\n try:\n condition.notify_all()\n finally:\n condition.release()\n\nCondition variables act as locks (acquire and release), but their main purpose is to provide the control mechanism which allows to wait for them to be notify-d or notify_all-d.\n",
"\nI recently found out that calling\n time.sleep( X ) will lock the GIL for\n the entire time X and therefore freeze\n ALL python threads for that time\n period.\n\nYou found wrongly -- this is definitely not how it works. What's the source where you found this mis-information?\nAnyway, then you clarify (in comments -- better edit your Q!) that you're using deferToThread and your problem with this is that...:\n\nWell yes I defer the action to a\n thread and give twisted a callback.\n But the parent thread needs to wait\n for the whole series of sub threads to\n complete before it can move onto a new\n set of sub threads to spawn\n\nSo use as the callback a method of an object with a counter -- start it at 0, increment it by one every time you're deferring-to-thread and decrement it by one in the callback method.\nWhen the callback method sees that the decremented counter has gone back to 0, it knows that we're done waiting \"for the whole series of sub threads to complete\" and then the time has come to \"move on to a new set of sub threads to spawn\", and thus, in that case only, calls the \"spawn a new set of sub threads\" function or method -- it's that easy!\nE.g. (net of typos &c as this is untested code, just to give you the idea)...:\nclass Waiter(object):\n\n def __init__(self, what_next, *a, **k):\n self.counter = 0\n self.what_next = what_next\n self.a = a\n self.k = k\n\n def one_more(self):\n self.counter += 1\n\n def do_wait(self, *dont_care):\n self.counter -= 1\n if self.counter == 0:\n self.what_next(*self.a, **self.k)\n\n\ndef spawn_one_thread(waiter, long_calculation, *a, **k):\n waiter.one_more()\n d = threads.deferToThread(long_calculation, *a, **k)\n d.addCallback(waiter.do_wait)\n\ndef spawn_all(waiter, list_of_lists_of_functions_args_and_kwds):\n if not list_of_lists_of_functions_args_and_kwds:\n return\n if waiter is None:\n waiter=Waiter(spawn_all, list_of_lists_of_functions_args_and_kwds)\n this_time = list_of_list_of_functions_args_and_kwds.pop(0)\n for f, a, k in this_time:\n spawn_one_thread(waiter, f, *a, **k)\n\ndef start_it_all(list_of_lists_of_functions_args_and_kwds):\n spawn_all(None, list_of_lists_of_functions_args_and_kwds)\n\n",
"According to the Python source, time.sleep() does not hold the GIL.\nhttp://code.python.org/hg/trunk/file/98e56689c59c/Modules/timemodule.c#l920\nNote the use of Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS, as documented here:\nhttp://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock\n",
"The threading module allows you to spawn a thread, which is then represented by a Thread object. That object has a join method that you can use to wait for the subthread to complete.\nSee http://docs.python.org/library/threading.html#module-threading\n"
] | [
13,
5,
5,
2,
1
] | [] | [] | [
"multithreading",
"python",
"twisted"
] | stackoverflow_0003096241_multithreading_python_twisted.txt |
Q:
need help sending command to server by ssh python
I am trying to connect to the server via ssh and dump the "df- h" output in some text file.
p=pexpect.spawn('ssh some.some.com')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
print "I say yes"
p.sendline('yes')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
p.sendline("somesome")
p.expect(pexpect.EOF)
i = p.sendline('df -h > /home/test/output.txt')
print i
response = p.before
print response
print p.before
I am trying to connect to the server and dump the server data in some text file.
My problem is i = p.sendline('df -h > /home/test/output.txt') is not doing anything,
Basically my output file is empty.
Please help me out.
Thanks.
A:
You probably want to use paramiko to manage operations over an SSH connection.
A:
My problem is i = p.sendline('df -h >
/home/test/output.txt') is not doing
anything
Isn't it setting i to 29? Is that what you mean?
Basically my output file is empty.
How do you know that? Nothing in this code is checking whether that file exists on the remote machine.
Please help me out.
Does your user on the remote machine have permission to write to the /home/test directory there, indeed, does that directory even exist? You're really giving us too few hints at exactly what you're doing, in exactly what context, and what exactly happens as a result, to be of any help yet, except for peppering you with such questions hoping you'll eventually tell us the many crucial pieces of data you're simply omitting. Help us help you out!-)
A:
If you find yourself doing a lot of work over ssh to the same machines then you may want to look into something like func.
A:
It looks like you're using Python as a shell here. Why don't you just save the relevant commands in a bash file and run that in one command instead? I think that'd work out a lot better. I also recommend that you enable SSH publickey authentication, it works better than passwords. Use the subprocess module to spawn processes from inside Python.
I guess this advice isn't helpful if you actually need to do things this way for some reason.
| need help sending command to server by ssh python | I am trying to connect to the server via ssh and dump the "df- h" output in some text file.
p=pexpect.spawn('ssh some.some.com')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
print "I say yes"
p.sendline('yes')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
p.sendline("somesome")
p.expect(pexpect.EOF)
i = p.sendline('df -h > /home/test/output.txt')
print i
response = p.before
print response
print p.before
I am trying to connect to the server and dump the server data in some text file.
My problem is i = p.sendline('df -h > /home/test/output.txt') is not doing anything,
Basically my output file is empty.
Please help me out.
Thanks.
| [
"You probably want to use paramiko to manage operations over an SSH connection.\n",
"\nMy problem is i = p.sendline('df -h >\n /home/test/output.txt') is not doing\n anything\n\nIsn't it setting i to 29? Is that what you mean?\n\nBasically my output file is empty.\n\nHow do you know that? Nothing in this code is checking whether that file exists on the remote machine.\n\nPlease help me out.\n\nDoes your user on the remote machine have permission to write to the /home/test directory there, indeed, does that directory even exist? You're really giving us too few hints at exactly what you're doing, in exactly what context, and what exactly happens as a result, to be of any help yet, except for peppering you with such questions hoping you'll eventually tell us the many crucial pieces of data you're simply omitting. Help us help you out!-)\n",
"If you find yourself doing a lot of work over ssh to the same machines then you may want to look into something like func.\n",
"It looks like you're using Python as a shell here. Why don't you just save the relevant commands in a bash file and run that in one command instead? I think that'd work out a lot better. I also recommend that you enable SSH publickey authentication, it works better than passwords. Use the subprocess module to spawn processes from inside Python.\nI guess this advice isn't helpful if you actually need to do things this way for some reason.\n"
] | [
3,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003096938_python.txt |
Q:
Most efficient way to sort/categories objects in list based on object attribute
I have an unsorted list of objects that each have a end_date attribute.
The list just looks like [obj1, obj2, obj3, <...>] in no specific order.
I want to end up with a list that looks like this:
[["Saturday, May 5", [obj3, obj5]], ["Monday, May 7", [obj1, obj8, obj9]] ... etc ]
Basically just a list of lists, where the "key" is the date from the objects and the value for that key is a list of objects that have that date. Don't worry about the date formatting, that's just an easy datetime manipulation. I know it's relatively easy to do with a dictionary, but I need to end up with a list sorted by the keys, and you can't do this with dictionaries (at least not with Python 2.6 IIRC)
What is the most efficient way to do this? I've been muddling through some solutions with a bunch of for loops, but it seems like I'm going about it wrong.
A:
itertools.groupby(sorted(L, key=operator.attrgetter('end_date')),
key=operator.attrgetter('end_date'))
A:
You said you know how to get it to a dict. So, just sort the results:
d = ToDict(...)
sorted_values = sorted(((date,list) for date,list in d.iteritems()))
Should be O(n log n)
You can provide a sorting method to sorted as well, if you want to manipulate your date type. See a sorting in python overview.
A:
Put it into a dictionary, then use l=list(dictionary.iteritems()) to get the list and l.sort() to sort it
| Most efficient way to sort/categories objects in list based on object attribute | I have an unsorted list of objects that each have a end_date attribute.
The list just looks like [obj1, obj2, obj3, <...>] in no specific order.
I want to end up with a list that looks like this:
[["Saturday, May 5", [obj3, obj5]], ["Monday, May 7", [obj1, obj8, obj9]] ... etc ]
Basically just a list of lists, where the "key" is the date from the objects and the value for that key is a list of objects that have that date. Don't worry about the date formatting, that's just an easy datetime manipulation. I know it's relatively easy to do with a dictionary, but I need to end up with a list sorted by the keys, and you can't do this with dictionaries (at least not with Python 2.6 IIRC)
What is the most efficient way to do this? I've been muddling through some solutions with a bunch of for loops, but it seems like I'm going about it wrong.
| [
"itertools.groupby(sorted(L, key=operator.attrgetter('end_date')),\n key=operator.attrgetter('end_date'))\n\n",
"You said you know how to get it to a dict. So, just sort the results:\nd = ToDict(...)\nsorted_values = sorted(((date,list) for date,list in d.iteritems()))\n\nShould be O(n log n)\nYou can provide a sorting method to sorted as well, if you want to manipulate your date type. See a sorting in python overview.\n",
"Put it into a dictionary, then use l=list(dictionary.iteritems()) to get the list and l.sort() to sort it\n"
] | [
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003098485_django_python.txt |
Q:
date library, capable of calculating things like "every third tuesday"?
I'd like to find a library or command that given input like "every third tuesday" will provide a list of dates such as (2010-06-15, 2010-07-20, 2010-08-17), etc.
Something that can be called from python, unix command line, or a web api would be perfect.
A:
There's always dateutil.
Example below is based on ~unutbu's excellent answer to this very similar SO question:
>>> from datetime import date
>>> from dateutil import rrule, relativedelta
>>> every_third_tuesday = rrule.rrule(rrule.MONTHLY,
byweekday=relativedelta.TU(3),
dtstart=date.today(),
count=3)
>>> for tt in every_third_tuesday:
... print tt.date()
...
2010-07-20
2010-08-17
2010-09-21
A:
Try the calendar module. Here is a good writeup -- it is part of what you are asking for: http://www.doughellmann.com/PyMOTW/calendar/index.html
| date library, capable of calculating things like "every third tuesday"? | I'd like to find a library or command that given input like "every third tuesday" will provide a list of dates such as (2010-06-15, 2010-07-20, 2010-08-17), etc.
Something that can be called from python, unix command line, or a web api would be perfect.
| [
"There's always dateutil.\nExample below is based on ~unutbu's excellent answer to this very similar SO question:\n>>> from datetime import date\n>>> from dateutil import rrule, relativedelta\n>>> every_third_tuesday = rrule.rrule(rrule.MONTHLY, \n byweekday=relativedelta.TU(3), \n dtstart=date.today(), \n count=3)\n>>> for tt in every_third_tuesday:\n... print tt.date()\n... \n2010-07-20\n2010-08-17\n2010-09-21\n\n",
"Try the calendar module. Here is a good writeup -- it is part of what you are asking for: http://www.doughellmann.com/PyMOTW/calendar/index.html\n"
] | [
7,
1
] | [] | [] | [
"date",
"python"
] | stackoverflow_0003099007_date_python.txt |
Q:
ImportError: No module named Foundation
Hey all, I'm pretty new to python, so bear with me.
I want to write a simple script using some components of PyObjC. I'm running on Mac OS 10.5, so from what I've read, it's included.
However, opening up a simple python prompt and typing import Foundation gives me the error ImportError: No module named Foundation.
For reference, my sys.path is
['', '/var/hg/lib/python2.4/site-packages', '/Users/dmitri/lib/python',
'/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/PyObjC',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/PyObjC',
'/Users/dmitri', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages']
'/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/PyObjC', and '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/PyObjC', got in there because I was fooling around, but they don't seem to help me. The 2.4 version seems to exists but there, seems to be no folder with the aforementioned path in the 2.5 version.
A:
I found it - for some reason, it was located under /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python, so I had to just add that whole directory to my $PYTHONPATH
A:
Where is the module Foundation located? Assuming it's in the same place as PyObjC -- /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/ -- then you have to add /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/ to your $PYTHONPATH as well.
| ImportError: No module named Foundation | Hey all, I'm pretty new to python, so bear with me.
I want to write a simple script using some components of PyObjC. I'm running on Mac OS 10.5, so from what I've read, it's included.
However, opening up a simple python prompt and typing import Foundation gives me the error ImportError: No module named Foundation.
For reference, my sys.path is
['', '/var/hg/lib/python2.4/site-packages', '/Users/dmitri/lib/python',
'/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/PyObjC',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/PyObjC',
'/Users/dmitri', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages']
'/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/PyObjC', and '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/PyObjC', got in there because I was fooling around, but they don't seem to help me. The 2.4 version seems to exists but there, seems to be no folder with the aforementioned path in the 2.5 version.
| [
"I found it - for some reason, it was located under /System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python, so I had to just add that whole directory to my $PYTHONPATH\n",
"Where is the module Foundation located? Assuming it's in the same place as PyObjC -- /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/ -- then you have to add /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/ to your $PYTHONPATH as well.\n"
] | [
4,
0
] | [] | [] | [
"pyobjc",
"python"
] | stackoverflow_0003098932_pyobjc_python.txt |
Q:
It's possible to make a program that shows FPS (frame per second) in Python?
I was wondering...
It's possible to do it?
A simple console command based program that shows how are your FPS, for your currently running game/program?
A:
Short answer: Yes.
Long answer: Beside that it is much simpler to gather statistics when you have hooks inside the measured program, it is possible also to hook on lower level: directly to DirectX or OpenGL. Start your discovery from some existing posts. They are in C++ but that's another deal: you can use SWIG to interop between Python and C/C++.
As a proof. There is famous Fraps applications that does what you say.
A:
Short answer: No.
Long answer: Not without knowing the internals of the application, and without the application having the appropriate hooks to perform such a measurement.
A:
As long as you have the available bindings/hooks to read what that application is doing through whatever library it uses, yes.
Those counters are normally implemented as queries to a program drawing through OpenGL (or directX).
If it's an OGL app, pyOpenGL provides a decent amount of functionality, might be worth your time looking into it. I have no experience with directX, but I assume you might find similar bindings.
http://www.cs.man.ac.uk/~toby/frameratedisplayer.htm if you want a simple example to look at that does just that (assuming you're ok puzzling out very little C syntax)
| It's possible to make a program that shows FPS (frame per second) in Python? | I was wondering...
It's possible to do it?
A simple console command based program that shows how are your FPS, for your currently running game/program?
| [
"Short answer: Yes.\nLong answer: Beside that it is much simpler to gather statistics when you have hooks inside the measured program, it is possible also to hook on lower level: directly to DirectX or OpenGL. Start your discovery from some existing posts. They are in C++ but that's another deal: you can use SWIG to interop between Python and C/C++.\nAs a proof. There is famous Fraps applications that does what you say.\n",
"Short answer: No.\nLong answer: Not without knowing the internals of the application, and without the application having the appropriate hooks to perform such a measurement.\n",
"As long as you have the available bindings/hooks to read what that application is doing through whatever library it uses, yes.\nThose counters are normally implemented as queries to a program drawing through OpenGL (or directX).\nIf it's an OGL app, pyOpenGL provides a decent amount of functionality, might be worth your time looking into it. I have no experience with directX, but I assume you might find similar bindings.\nhttp://www.cs.man.ac.uk/~toby/frameratedisplayer.htm if you want a simple example to look at that does just that (assuming you're ok puzzling out very little C syntax)\n"
] | [
1,
0,
0
] | [] | [] | [
"frame_rate",
"python"
] | stackoverflow_0003098980_frame_rate_python.txt |
Q:
Are the two codes equivalent to each other?
i know ive asked similar questions like this before, but: Is this pseudocode here the same as my code? upper case variables are the variables in the pseudocode with " ' " and the values with conditions are all in lists, such as: all "s" conditions are in list "s", and " s' " conditions in list "S"
for i in xrange(t):
a = h0; b = h1; c = h2; d = h3; e = h4
A = h0; B = h1; C = h2; D = h3; E = h4
X = data[512*i:512*(i+1)] # the data is a binary string
X = [int(X[32*x:32*(x+1)],2) for x in xrange(16)]
for j in xrange(80):
a, e, d, c, b = e, d, ROL(c,10), b, ROL((a + F(b, c, d, j) + X[r[j]] + k[j/16])%(1<<32), s[j]) + e
A, E, D, C, B = E, D, ROL(C,10), B, ROL((A + F(B, C, D, 79-j) + X[R[j]] + K[j/16])%(1<<32), S[j]) + E
T = (h1+c+D)%(1<<32)
h1 = (h2+d+E)%(1<<32)
h2 = (h3+e+A)%(1<<32)
h3 = (h4+a+B)%(1<<32)
h4 = (h0+b+C)%(1<<32)
h0 = T
i have been working on this code (sporadically) for quite some time now and i for some reason have not been able to get this code to work properly. why??? im sure that the preprocessing of the data is correct, and yet, even when i copy other people's codes and translate them into python, the outputs are no where near correct at all
this part of the code should be correct:
def F(x,y,z,round):
if round<16:
return x ^ y ^ z
elif 16<=round<32:
return (x & y) | (~x & z)
elif 32<=round<48:
return (x | ~y) ^ z
elif 48<=round<64:
return (x & z) | (y & ~z)
elif 64<=round:
return x ^ (y | ~z)
h0 = 0x67452301; h1 = 0xEFCDAB89; h2 = 0x98BADCFE; h3 = 0x10325476; h4 = 0xC3D2E1F0
k = [0, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]
K = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0]
s = [ 11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,
7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,
11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,
11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,
9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]
S = [ 8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,
9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,
9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,
15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,
8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]
r = range(16) + [
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]
R = [ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]
A:
The pseudocode you point to defines a function f, constants K and K', selectors r and r', etc -- where are all of these things hiding in the code you're showing? You seem to be using them, but, how do we (and you) know they're right, without any inspection?
Your bug, after all, could be in all this code you're hiding from us.
A:
My suggestion would be to put the code into functions and unit test it. You have an expected output, and unit tests are a very useful way to verify that the code does what it's supposed to. For example, does your list comprehension result in a correct list?
I also suggest you read the Style Guide for Python, as your code is more complicated to read than it needs to be. For example, you have multiple statements on a single line.
| Are the two codes equivalent to each other? | i know ive asked similar questions like this before, but: Is this pseudocode here the same as my code? upper case variables are the variables in the pseudocode with " ' " and the values with conditions are all in lists, such as: all "s" conditions are in list "s", and " s' " conditions in list "S"
for i in xrange(t):
a = h0; b = h1; c = h2; d = h3; e = h4
A = h0; B = h1; C = h2; D = h3; E = h4
X = data[512*i:512*(i+1)] # the data is a binary string
X = [int(X[32*x:32*(x+1)],2) for x in xrange(16)]
for j in xrange(80):
a, e, d, c, b = e, d, ROL(c,10), b, ROL((a + F(b, c, d, j) + X[r[j]] + k[j/16])%(1<<32), s[j]) + e
A, E, D, C, B = E, D, ROL(C,10), B, ROL((A + F(B, C, D, 79-j) + X[R[j]] + K[j/16])%(1<<32), S[j]) + E
T = (h1+c+D)%(1<<32)
h1 = (h2+d+E)%(1<<32)
h2 = (h3+e+A)%(1<<32)
h3 = (h4+a+B)%(1<<32)
h4 = (h0+b+C)%(1<<32)
h0 = T
i have been working on this code (sporadically) for quite some time now and i for some reason have not been able to get this code to work properly. why??? im sure that the preprocessing of the data is correct, and yet, even when i copy other people's codes and translate them into python, the outputs are no where near correct at all
this part of the code should be correct:
def F(x,y,z,round):
if round<16:
return x ^ y ^ z
elif 16<=round<32:
return (x & y) | (~x & z)
elif 32<=round<48:
return (x | ~y) ^ z
elif 48<=round<64:
return (x & z) | (y & ~z)
elif 64<=round:
return x ^ (y | ~z)
h0 = 0x67452301; h1 = 0xEFCDAB89; h2 = 0x98BADCFE; h3 = 0x10325476; h4 = 0xC3D2E1F0
k = [0, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]
K = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0]
s = [ 11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,
7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,
11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,
11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,
9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]
S = [ 8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,
9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,
9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,
15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,
8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]
r = range(16) + [
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]
R = [ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]
| [
"The pseudocode you point to defines a function f, constants K and K', selectors r and r', etc -- where are all of these things hiding in the code you're showing? You seem to be using them, but, how do we (and you) know they're right, without any inspection?\nYour bug, after all, could be in all this code you're hiding from us.\n",
"My suggestion would be to put the code into functions and unit test it. You have an expected output, and unit tests are a very useful way to verify that the code does what it's supposed to. For example, does your list comprehension result in a correct list?\nI also suggest you read the Style Guide for Python, as your code is more complicated to read than it needs to be. For example, you have multiple statements on a single line.\n"
] | [
3,
0
] | [] | [] | [
"cryptography",
"hashcode",
"python",
"ripemd"
] | stackoverflow_0003097762_cryptography_hashcode_python_ripemd.txt |
Q:
What does this "for i in [...]" loop code do?
I am new to python,can anybody please explain the following syntax,
for i in [line.split('"') for line in open('a.txt')]:
......
......
......
A:
afile = open('a.txt')
for line in afile:
for field in line.split('"'):
# do something
There really isn't much good reason for crowding such a simple concept in such a hard to read expression.
A:
The file a.txt is opened and read line by line
For each line from the file, the line is split on the " characters --> we'll call these tokens.
The lines of code in the indented block presumably use these tokens somehow
In a nutshell, tis would parse the contents of a file into token delimited with either newline characters or quotation mark characters.
If the input file is:
ab"cdef"g
h"ijk"lmno"p
q
.. the program would would return the tokens:
ab
cdef
g\n
h
ijk
lmno
p\n
q\n
A:
After changing the extremely badly named i to fields, the original code is equivalent to:
file_handle = open('a.txt') # open the file
for line in file_handle: # iterate over lines in the file
fields = line.split('"') # split line into fields
# === End of equivalent code ===
# Now do something with fields, for example:
for field in fields:
# Now do something with field
Using a list comprehension in the manner of the original code is both obfuscatory and inefficient. As shown by the above equivalent code, there is no need for a list comprehension at all. The original code builds a temporary list, which is immediately iterated over and finally discarded, perhaps after occupying a large chunk of memory for a long time.
Note: the currently accepted answer is incorrect. (1) The original code does NOT produce a field/token at a time; each i will refer to a list of fields (2) fields are NOT separated by newlines; in fact the last field for each line (except perhaps the last line) will include a newline. See below.
If the input file is:
ab"cdef"g
h"ijk"lmno"p
q
then the "values" of i will be
['ab', 'cdef', 'g\n']
['h', 'ijk', 'lmno', 'p\n']
['q\n']
Aside: having fields separated by quotes is rather unusual, isn't it?
A:
Try run blocks in parts like this sample.
A:
Well, first off, what do you get if you run the code with a file a.txt as say:
"This", is a "test"
Here we "GO" again
"Quoted Line"
and no quotes?
['', 'This', ', is a ', 'test', '\n']
['Here we ', 'GO', ' again\n']
['', 'Quoted Line', '\n']
['and no quotes?\n']
So, you are getting a list for each line, where the line lists consist of the contents of the string divided by the quote " character.
So try running these:
for line in open('a.txt'):
print line
So, it will iterate over the lines of the file a.txt, which has been called with open.
for line in open("a.txt"):
line_parts = [line.split('"') for line in open('a.txt')]
print line_parts
That second line is what is referred to as a List Comprehension and will run the split method on each line of the file.
So, now that you see the output of these, you can hopefully see why it is doing what is it doing. Let me know if this makes any sense. I had a couple of drinks :)
A:
Other than judgment calls on whether that obfuscates or not, to understand it you need to look up list comprehension in python, and the functions used there.
List comprehension is a way to create lists that's both performance and character footprint efficient, at the cost of readability in some cases.
IE: you have a list [1,2,3], and you want one containing the same elements with 1 added to each, you could do something like
originalList = [1,2,3,4]
newList = [x+1 for x in originalList]
print newList
This gets even more interesting (and occasionally unreadable) when you introduce lambdas and multidimensionality.
With that in mind, to puzzle out that line of code you have to look at it backwards.
open() will get you the contents of the text file in this case.
So For line in open() catches the return, and iterates over it, giving you a line of the file for each iteration, which is the "x in originalList" part of the example basically.
The content of your iterator, in that list comprehension, being a string, has a split method, which is used there.
At the end of that segment between square brackets, you have a list of elements (coming from split) that were separated by '"' originally, and each of those is an entry in the list created by your list comprehension.
The result of that list comprehension is then iterated over again in that "for i in[]".
A:
It will read the file 'a.txt' line by line and split it using the delimiter '"'. The split will result in a list. Once reading is done the result of splitting is assigned to the 'i' i.e. a list of list.
Example:
Personal firewall "software may warn about the connection IDLE
Personal firewall "software" may warn about the connection IDLE
Personal "firewall" "software may warn about the" connection IDLE
Output:
['Personal firewall ', 'software may warn about the connection IDLE\n'] ['Personal firewall ', 'software', ' may warn about the connection IDLE\n'] ['Personal ', 'firewall', ' ', 'software may warn about the', ' connection IDLE\n']
| What does this "for i in [...]" loop code do? | I am new to python,can anybody please explain the following syntax,
for i in [line.split('"') for line in open('a.txt')]:
......
......
......
| [
"afile = open('a.txt')\nfor line in afile:\n for field in line.split('\"'):\n # do something\n\nThere really isn't much good reason for crowding such a simple concept in such a hard to read expression.\n",
"The file a.txt is opened and read line by line\nFor each line from the file, the line is split on the \" characters --> we'll call these tokens.\nThe lines of code in the indented block presumably use these tokens somehow\nIn a nutshell, tis would parse the contents of a file into token delimited with either newline characters or quotation mark characters.\nIf the input file is:\nab\"cdef\"g\nh\"ijk\"lmno\"p\nq\n\n.. the program would would return the tokens:\nab\ncdef\ng\\n\nh\nijk\nlmno\np\\n\nq\\n\n\n",
"After changing the extremely badly named i to fields, the original code is equivalent to:\nfile_handle = open('a.txt') # open the file\nfor line in file_handle: # iterate over lines in the file\n fields = line.split('\"') # split line into fields\n # === End of equivalent code ===\n # Now do something with fields, for example:\n for field in fields:\n # Now do something with field\n\nUsing a list comprehension in the manner of the original code is both obfuscatory and inefficient. As shown by the above equivalent code, there is no need for a list comprehension at all. The original code builds a temporary list, which is immediately iterated over and finally discarded, perhaps after occupying a large chunk of memory for a long time.\nNote: the currently accepted answer is incorrect. (1) The original code does NOT produce a field/token at a time; each i will refer to a list of fields (2) fields are NOT separated by newlines; in fact the last field for each line (except perhaps the last line) will include a newline. See below.\nIf the input file is:\nab\"cdef\"g\nh\"ijk\"lmno\"p\nq\n\nthen the \"values\" of i will be\n['ab', 'cdef', 'g\\n']\n['h', 'ijk', 'lmno', 'p\\n']\n['q\\n']\n\nAside: having fields separated by quotes is rather unusual, isn't it?\n",
"Try run blocks in parts like this sample.\n",
"Well, first off, what do you get if you run the code with a file a.txt as say:\n\"This\", is a \"test\"\nHere we \"GO\" again\n\"Quoted Line\"\nand no quotes?\n['', 'This', ', is a ', 'test', '\\n']\n['Here we ', 'GO', ' again\\n']\n['', 'Quoted Line', '\\n']\n['and no quotes?\\n']\nSo, you are getting a list for each line, where the line lists consist of the contents of the string divided by the quote \" character.\nSo try running these:\nfor line in open('a.txt'):\n print line\n\nSo, it will iterate over the lines of the file a.txt, which has been called with open.\nfor line in open(\"a.txt\"):\n line_parts = [line.split('\"') for line in open('a.txt')]\n print line_parts\n\nThat second line is what is referred to as a List Comprehension and will run the split method on each line of the file.\nSo, now that you see the output of these, you can hopefully see why it is doing what is it doing. Let me know if this makes any sense. I had a couple of drinks :)\n",
"Other than judgment calls on whether that obfuscates or not, to understand it you need to look up list comprehension in python, and the functions used there.\nList comprehension is a way to create lists that's both performance and character footprint efficient, at the cost of readability in some cases.\nIE: you have a list [1,2,3], and you want one containing the same elements with 1 added to each, you could do something like\noriginalList = [1,2,3,4]\nnewList = [x+1 for x in originalList]\nprint newList\n\nThis gets even more interesting (and occasionally unreadable) when you introduce lambdas and multidimensionality.\nWith that in mind, to puzzle out that line of code you have to look at it backwards.\nopen() will get you the contents of the text file in this case.\nSo For line in open() catches the return, and iterates over it, giving you a line of the file for each iteration, which is the \"x in originalList\" part of the example basically.\nThe content of your iterator, in that list comprehension, being a string, has a split method, which is used there.\nAt the end of that segment between square brackets, you have a list of elements (coming from split) that were separated by '\"' originally, and each of those is an entry in the list created by your list comprehension.\nThe result of that list comprehension is then iterated over again in that \"for i in[]\".\n",
"It will read the file 'a.txt' line by line and split it using the delimiter '\"'. The split will result in a list. Once reading is done the result of splitting is assigned to the 'i' i.e. a list of list.\n\nExample:\nPersonal firewall \"software may warn about the connection IDLE\nPersonal firewall \"software\" may warn about the connection IDLE\nPersonal \"firewall\" \"software may warn about the\" connection IDLE\n\n\nOutput:\n['Personal firewall ', 'software may warn about the connection IDLE\\n'] ['Personal firewall ', 'software', ' may warn about the connection IDLE\\n'] ['Personal ', 'firewall', ' ', 'software may warn about the', ' connection IDLE\\n']\n\n"
] | [
6,
4,
4,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003099041_python.txt |
Q:
set user session in django
<?php
session_start();
$_SESSION['username'] = "johndoe" // Must be already set
?>
How to write equivalent code for the above in django
A:
When SessionMiddleware is activated, each HttpRequest object – the first argument to any Django view function – will have a session attribute, which is a dictionary-like object. You can read it and write to it.
Read more ...
Example:
def login(request):
m = Member.objects.get(username=request.POST['username'])
if m.password == request.POST['password']:
request.session['member_id'] = m.id
return HttpResponse("You're logged in.")
else:
return HttpResponse("Your username and password didn't match.")
| set user session in django | <?php
session_start();
$_SESSION['username'] = "johndoe" // Must be already set
?>
How to write equivalent code for the above in django
| [
"\nWhen SessionMiddleware is activated, each HttpRequest object – the first argument to any Django view function – will have a session attribute, which is a dictionary-like object. You can read it and write to it.\n\nRead more ...\n\nExample: \ndef login(request):\n m = Member.objects.get(username=request.POST['username'])\n if m.password == request.POST['password']:\n request.session['member_id'] = m.id\n return HttpResponse(\"You're logged in.\")\n else:\n return HttpResponse(\"Your username and password didn't match.\")\n\n"
] | [
4
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0003099850_django_django_models_django_templates_django_views_python.txt |
Q:
Retrieving the Return Value of a Stackless Python Tasklet Bound Function?
Stackless Experts,
I have managed to create tasklets under Stackless Python (both from the Stackless and the C side).
It seems to me that in order to create a tasklet in Stackless, you bind an arbitrary Python callable (function) to the tasklet (as well as the required parameters), so the bound callable would be run as a tasklet. However, an arbitrary callable might actually have a return value that's important to the caller. But I have yet to see a way to retrieve the return value of the bound callable running as a tasklet.
On the pure Stackless Python side, I do see a usage idiom called Micromanaging, which wraps the original function with a managing function, which in turn could capture the return value of the original function and save it somewhere for use in some other context.
Unfortunately, my special use case involves creating a tasklet from the C (C++) side, binding to a (potentially blocking) Python callable which has an important return value to be used later. It seems that writing such a Micromanaging function on the C side is not very feasible, since I haven't found a way to turn a C function into a PyObject callable dynamically (not involving module table initialization, etc.), and using static stateless C function (I would assume the prototype has to be PyObject* (PyObject*, PyObject*)) is generally a bad idea under C++ world anyways.
The Stackless C API also seems not containing a proper function to retrieve the return value of a tasklet. Is it the only option that I have to write above mentioned Micromanaging function (could be stateful) in Python, and provide a way to retrieve the return value saved somewhere (in a stateful fashion, i.e. not using global variables)? Or there could be other options I could possibly explore?
Thank you very much,
Lin
P.S. I understand that on the C and operating system level programming, the return value of a thread function is only meaningful for exit code, and thread functions would have a strict function prototype, i.e. C functions have to abide by some strict rules to become runnable as/by a thread. And now we are talking about Python :)
A:
From Stackless.com:
"... But I have yet to see a way to retrieve the return value of the bound callable running as a tasklet. ..."
I do not know that there is one.
"...important return value to be used later. It seems that writing such a Micromanaging function on the C side is not very feasible, since I haven't ..."
The simplest way to do this would be to define the wrapping Python function code in C as a string, and to compile it into a function object that you can run as a tasklet. An example Python function follows, the C part I leave to you.
e.g.
def RunFunctionAndGetResult(chan, func, *args, **kwargs):
chan.send(func(*args, **kwargs))
Cheers,
Richard.
| Retrieving the Return Value of a Stackless Python Tasklet Bound Function? | Stackless Experts,
I have managed to create tasklets under Stackless Python (both from the Stackless and the C side).
It seems to me that in order to create a tasklet in Stackless, you bind an arbitrary Python callable (function) to the tasklet (as well as the required parameters), so the bound callable would be run as a tasklet. However, an arbitrary callable might actually have a return value that's important to the caller. But I have yet to see a way to retrieve the return value of the bound callable running as a tasklet.
On the pure Stackless Python side, I do see a usage idiom called Micromanaging, which wraps the original function with a managing function, which in turn could capture the return value of the original function and save it somewhere for use in some other context.
Unfortunately, my special use case involves creating a tasklet from the C (C++) side, binding to a (potentially blocking) Python callable which has an important return value to be used later. It seems that writing such a Micromanaging function on the C side is not very feasible, since I haven't found a way to turn a C function into a PyObject callable dynamically (not involving module table initialization, etc.), and using static stateless C function (I would assume the prototype has to be PyObject* (PyObject*, PyObject*)) is generally a bad idea under C++ world anyways.
The Stackless C API also seems not containing a proper function to retrieve the return value of a tasklet. Is it the only option that I have to write above mentioned Micromanaging function (could be stateful) in Python, and provide a way to retrieve the return value saved somewhere (in a stateful fashion, i.e. not using global variables)? Or there could be other options I could possibly explore?
Thank you very much,
Lin
P.S. I understand that on the C and operating system level programming, the return value of a thread function is only meaningful for exit code, and thread functions would have a strict function prototype, i.e. C functions have to abide by some strict rules to become runnable as/by a thread. And now we are talking about Python :)
| [
"From Stackless.com:\n\"... But I have yet to see a way to retrieve the return value of the bound callable running as a tasklet. ...\"\nI do not know that there is one.\n\"...important return value to be used later. It seems that writing such a Micromanaging function on the C side is not very feasible, since I haven't ...\"\nThe simplest way to do this would be to define the wrapping Python function code in C as a string, and to compile it into a function object that you can run as a tasklet. An example Python function follows, the C part I leave to you.\ne.g.\n def RunFunctionAndGetResult(chan, func, *args, **kwargs):\n chan.send(func(*args, **kwargs))\n\nCheers,\nRichard.\n"
] | [
1
] | [] | [] | [
"python",
"python_stackless",
"stackless"
] | stackoverflow_0003092614_python_python_stackless_stackless.txt |
Q:
GtkTreeView's row-activated and cursor-changed signals
I have a treeview and I am watching for the cursor-changed and row-activated signals. The problem is that in order to trigger the row-activate I first have to click on the row (triggering cursor-changed) and then do the double click, requiring 3 clicks.
Is there a way to respond to both signals with 2 clicks?
A:
It's not very clear what you're trying to achieve. I guess you're trying to respond to the user changing the selection in the treeview.
If this is the case, connect to the [changed][1] signal on the gtk.TreeSelection:
selection = treeview.get_selection()
selection.connect('changed', self.on_treeview_selection_changed)
As far as I can tell, this is not possible using the glade interface designer.
If, however, you are trying to do something else entirely, please add some more information.
A:
The cursor-changed signal is emitted even when single clicking on the same (selected) row. Still, the row-activated signal is emitted when you double click on a row, whether it was selected before the double click or not. Thus you don't need 3 clicks to trigger a row-activated.
As Jon mentioned, you want to connect to the selection's changed signal in stead of cursor-changed.
| GtkTreeView's row-activated and cursor-changed signals | I have a treeview and I am watching for the cursor-changed and row-activated signals. The problem is that in order to trigger the row-activate I first have to click on the row (triggering cursor-changed) and then do the double click, requiring 3 clicks.
Is there a way to respond to both signals with 2 clicks?
| [
"It's not very clear what you're trying to achieve. I guess you're trying to respond to the user changing the selection in the treeview.\nIf this is the case, connect to the [changed][1] signal on the gtk.TreeSelection:\nselection = treeview.get_selection()\nselection.connect('changed', self.on_treeview_selection_changed)\n\nAs far as I can tell, this is not possible using the glade interface designer.\nIf, however, you are trying to do something else entirely, please add some more information.\n",
"The cursor-changed signal is emitted even when single clicking on the same (selected) row. Still, the row-activated signal is emitted when you double click on a row, whether it was selected before the double click or not. Thus you don't need 3 clicks to trigger a row-activated.\nAs Jon mentioned, you want to connect to the selection's changed signal in stead of cursor-changed.\n"
] | [
4,
3
] | [] | [] | [
"gtk",
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0002256794_gtk_gtktreeview_pygtk_python.txt |
Q:
Running Python & Django on IIS
Is it possible to run Python & Django on IIS?
I am going to be a Lead Developer in some web design company and right now they are using classic ASP and ASP.NET.
As far as I can see ASP.NET MVC is not mature. Should I recommend Python & Django stack?
If it's not possible to run Python on IIS what do you think I should do? Stick with ASP.NET which I don't know? I don't know python well as well but I'm more comfortable with it.
Can I run IIS and Apache in parallel?
A:
There's two issue here, technological and psycological.
Technologically, yes, it's definitely possible. In fact, Django has a wiki article about this. Google also shows a lot of similar tutorials. Apache and IIS can also run on the same machine (I'm actually doing that right now from a development machine).
The bigger issue will be psycological, in the form of backlash you'll get from the other developers. I agree that Django kicks the pants off ASP.NET, but you're probably going to find that an ASP.NET shop is going to be married to ASP.NET and will likely ignore your suggestion to try anything else, much less Django.
A:
We've been running django on IIS for a couple of years using PyISAPIe. It's a fairly big site, about 150,000 users. We're moving to linux/apache though, partly cos PyISAPIe isn't great.
Case in point - WebKit browsers don't work well with it, it seems to mess up the chunking. That's tolerable for us as we are allowed to limit our users to FF/IE7+, but annoys me on a mac as I much prefer Safari to FF.
| Running Python & Django on IIS | Is it possible to run Python & Django on IIS?
I am going to be a Lead Developer in some web design company and right now they are using classic ASP and ASP.NET.
As far as I can see ASP.NET MVC is not mature. Should I recommend Python & Django stack?
If it's not possible to run Python on IIS what do you think I should do? Stick with ASP.NET which I don't know? I don't know python well as well but I'm more comfortable with it.
Can I run IIS and Apache in parallel?
| [
"There's two issue here, technological and psycological.\nTechnologically, yes, it's definitely possible. In fact, Django has a wiki article about this. Google also shows a lot of similar tutorials. Apache and IIS can also run on the same machine (I'm actually doing that right now from a development machine).\nThe bigger issue will be psycological, in the form of backlash you'll get from the other developers. I agree that Django kicks the pants off ASP.NET, but you're probably going to find that an ASP.NET shop is going to be married to ASP.NET and will likely ignore your suggestion to try anything else, much less Django.\n",
"We've been running django on IIS for a couple of years using PyISAPIe. It's a fairly big site, about 150,000 users. We're moving to linux/apache though, partly cos PyISAPIe isn't great. \nCase in point - WebKit browsers don't work well with it, it seems to mess up the chunking. That's tolerable for us as we are allowed to limit our users to FF/IE7+, but annoys me on a mac as I much prefer Safari to FF.\n"
] | [
7,
5
] | [] | [] | [
"apache",
"asp.net",
"asp.net_mvc",
"iis",
"python"
] | stackoverflow_0002112525_apache_asp.net_asp.net_mvc_iis_python.txt |
Q:
using link grammar parser
Is it adequate to use the link grammar parser to do POS tagging? How is the performance when it comes to informal english with a little of my country's lingo?
Does the link grammar parser also performs a subject-object relationship identification?
Doing POS tagging is the first step towards NER right?
A:
The link grammar parser provides some deep grammar information like connection between nouns and various kinds of post-noun modifiers (see M and many other).
However postprocess the resulting parse graph can be tedious, if you are only interested in tagging and/or NER, take a look at:
http://nlp.stanford.edu/software/tagger.shtml
http://nlp.stanford.edu/ner/index.shtml
Link grammar and the Stanford parser are two of the best current parser for English.
You should be able to get descent results.
| using link grammar parser | Is it adequate to use the link grammar parser to do POS tagging? How is the performance when it comes to informal english with a little of my country's lingo?
Does the link grammar parser also performs a subject-object relationship identification?
Doing POS tagging is the first step towards NER right?
| [
"The link grammar parser provides some deep grammar information like connection between nouns and various kinds of post-noun modifiers (see M and many other).\nHowever postprocess the resulting parse graph can be tedious, if you are only interested in tagging and/or NER, take a look at:\nhttp://nlp.stanford.edu/software/tagger.shtml\nhttp://nlp.stanford.edu/ner/index.shtml\nLink grammar and the Stanford parser are two of the best current parser for English.\nYou should be able to get descent results.\n"
] | [
3
] | [] | [] | [
"link_grammar",
"parsing",
"python"
] | stackoverflow_0003100219_link_grammar_parsing_python.txt |
Q:
how to read rss feed to gae-database
any gae-lib to do this
i think maybe jquery can do this too , yes ?
thanks
A:
Here is a list of Python RSS processing libraries available by searching "python rss" in google.com
A:
One option is to avoid the hassle of polling, error handling, parsing, handling invalid feeds, and so on and so forth, by making someone else do it for you. This blog post describes how you can use PubSubHubbub to do the bulk of the work on your behalf.
| how to read rss feed to gae-database | any gae-lib to do this
i think maybe jquery can do this too , yes ?
thanks
| [
"Here is a list of Python RSS processing libraries available by searching \"python rss\" in google.com\n",
"One option is to avoid the hassle of polling, error handling, parsing, handling invalid feeds, and so on and so forth, by making someone else do it for you. This blog post describes how you can use PubSubHubbub to do the bulk of the work on your behalf.\n"
] | [
1,
1
] | [] | [] | [
"google_app_engine",
"jquery",
"python",
"rss"
] | stackoverflow_0003098875_google_app_engine_jquery_python_rss.txt |
Q:
Libraries for manipulating multivariate polynomials
I need to write some code that deals with generating and manipulating multivariable polynomials. I'll outline my task with a simplified example.
Lets say I am given three expressions: 2x^2, 3y + 1, and 1z. I then need to multiply these together which would give me 6x^2yz + 2x^2z. Then I would like to find the partial derivatives of this expression with respect to x, y, and z. This would give me 12xyz + 4xz, 6x^2z, and 6x^2y + 2x^2.
My problem deals with doing simple manipulations like this on expressions containing thousands of variables and I need an easy way to do this systematically. I would really like to use python since I already have a lot of project related functionality completed using numpy/scipy/matplotlib, but if there is a robust toolbox out there in another language I am open to using that as well. I am doing university research so I am open to using Matlab as well.
I haven't been able to find any good python libraries that could do this for me easily and ideally would like something similar to the scipy polynomial routines that could work on multidimensional polynomials. Does anyone know of a good library that seems suitable for this problem and that would be easy to integrate into already existing python code?
Thanks!
Follow up: I spent a couple of days working with sympy which turned out to be very easy to use. However, it was much to slow for the size of the problem I am working on so I will now go explore matlab. To give an extremely rough estimate of the speed using a small sample size, it took approximately 5 seconds to calculate each of the partial derivatives of an order 2 polynomial containing 250 variables.
Follow up #2: I probably should have done this back when I was still working on this problem, but I might as well let everyone know that the matlab symbolic library was extremely comparable in speed to sympy. In other words, it was brutally slow for large computations. Both libraries were amazingly easy to work with, so for small computations I do highly recommend either.
To solve my problem I computed the gradients by hand, simplified them, and then used the patterns I found to hard code some values in my code. It was more work, but made my code exponentially faster and finally usable.
A:
Sympy is perfect for this: http://code.google.com/p/sympy/
Documentation: http://docs.sympy.org/
Examples of differentiation from the tutorial: http://docs.sympy.org/tutorial.html#differentiation
import sympy
x, y, z = sympy.symbols('xyz')
p1 = 2*x*x
p2 = 3*y + 1
p3 = z
p4 = p1*p2*p3
print p4
print p4.diff(x)
print p4.diff(y)
print p4.diff(z)
Output:
2*z*x**2*(1 + 3*y)
4*x*z*(1 + 3*y)
6*z*x**2
2*x**2*(1 + 3*y)
A:
If you are using MATLAB, then the symbolic TB works well, IF you have it. If not, then use my sympoly toolbox. Just download it from the file exchange.
sympoly x y z
A = 2*x^2; B = 3*y + 1;C = 1*z;
gradient(A*B*C)
ans =
Sympoly array has size = [1 3]
Sympoly array element [1 1]
4*x*z + 12*x*y*z
Sympoly array element [1 2]
6*x^2*z
Sympoly array element [1 3]
2*x^2 + 6*x^2*y
Note that this points out that you made a mistake in differentiating the result with respect to z in your question.
A:
Matlab and other tools you mention typically do numerical computing. You should consider using Mathematica or an alternative Computer Algebra System (CAS) for symbolic computation. See the wiki link: http://en.wikipedia.org/wiki/Comparison_of_computer_algebra_systems for a comparison of various CASs.
| Libraries for manipulating multivariate polynomials | I need to write some code that deals with generating and manipulating multivariable polynomials. I'll outline my task with a simplified example.
Lets say I am given three expressions: 2x^2, 3y + 1, and 1z. I then need to multiply these together which would give me 6x^2yz + 2x^2z. Then I would like to find the partial derivatives of this expression with respect to x, y, and z. This would give me 12xyz + 4xz, 6x^2z, and 6x^2y + 2x^2.
My problem deals with doing simple manipulations like this on expressions containing thousands of variables and I need an easy way to do this systematically. I would really like to use python since I already have a lot of project related functionality completed using numpy/scipy/matplotlib, but if there is a robust toolbox out there in another language I am open to using that as well. I am doing university research so I am open to using Matlab as well.
I haven't been able to find any good python libraries that could do this for me easily and ideally would like something similar to the scipy polynomial routines that could work on multidimensional polynomials. Does anyone know of a good library that seems suitable for this problem and that would be easy to integrate into already existing python code?
Thanks!
Follow up: I spent a couple of days working with sympy which turned out to be very easy to use. However, it was much to slow for the size of the problem I am working on so I will now go explore matlab. To give an extremely rough estimate of the speed using a small sample size, it took approximately 5 seconds to calculate each of the partial derivatives of an order 2 polynomial containing 250 variables.
Follow up #2: I probably should have done this back when I was still working on this problem, but I might as well let everyone know that the matlab symbolic library was extremely comparable in speed to sympy. In other words, it was brutally slow for large computations. Both libraries were amazingly easy to work with, so for small computations I do highly recommend either.
To solve my problem I computed the gradients by hand, simplified them, and then used the patterns I found to hard code some values in my code. It was more work, but made my code exponentially faster and finally usable.
| [
"Sympy is perfect for this: http://code.google.com/p/sympy/\nDocumentation: http://docs.sympy.org/\nExamples of differentiation from the tutorial: http://docs.sympy.org/tutorial.html#differentiation\nimport sympy\n\nx, y, z = sympy.symbols('xyz')\n\np1 = 2*x*x\np2 = 3*y + 1\np3 = z\n\np4 = p1*p2*p3\n\nprint p4\n\nprint p4.diff(x)\nprint p4.diff(y)\nprint p4.diff(z)\n\nOutput:\n2*z*x**2*(1 + 3*y)\n4*x*z*(1 + 3*y)\n6*z*x**2\n2*x**2*(1 + 3*y)\n\n",
"If you are using MATLAB, then the symbolic TB works well, IF you have it. If not, then use my sympoly toolbox. Just download it from the file exchange.\nsympoly x y z\nA = 2*x^2; B = 3*y + 1;C = 1*z;\ngradient(A*B*C)\n\nans =\nSympoly array has size = [1 3]\n\nSympoly array element [1 1]\n 4*x*z + 12*x*y*z\nSympoly array element [1 2]\n 6*x^2*z\nSympoly array element [1 3]\n 2*x^2 + 6*x^2*y\n\nNote that this points out that you made a mistake in differentiating the result with respect to z in your question.\n",
"Matlab and other tools you mention typically do numerical computing. You should consider using Mathematica or an alternative Computer Algebra System (CAS) for symbolic computation. See the wiki link: http://en.wikipedia.org/wiki/Comparison_of_computer_algebra_systems for a comparison of various CASs. \n"
] | [
9,
2,
1
] | [] | [] | [
"math",
"matlab",
"numpy",
"python",
"scipy"
] | stackoverflow_0003097464_math_matlab_numpy_python_scipy.txt |
Q:
issue while matching special char '\' in regular expression using '\\'
I have very simple python script to match some special characters like -,+,-,.
But Im not getting expected result while using regex \ to match a single '\' char.
import re
pat = r'[-+*\\]'
text = 'fdkjdfk\sdsdd'
if re.search(pat,text):
print re.search(pat,text).group()
else:
print "not found"
On running above code , it prints 'not found'
It seems I am doing some mistake here , any help appreciated !!!
A:
\ is an escape character.
Try escaping it:
text = 'fdkjdfk\\sdsdd'
| issue while matching special char '\' in regular expression using '\\' | I have very simple python script to match some special characters like -,+,-,.
But Im not getting expected result while using regex \ to match a single '\' char.
import re
pat = r'[-+*\\]'
text = 'fdkjdfk\sdsdd'
if re.search(pat,text):
print re.search(pat,text).group()
else:
print "not found"
On running above code , it prints 'not found'
It seems I am doing some mistake here , any help appreciated !!!
| [
"\\ is an escape character.\nTry escaping it:\ntext = 'fdkjdfk\\\\sdsdd' \n\n"
] | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003100580_python_regex.txt |
Q:
Datetime.now() abnormality - Python
I'm serving a Python app through Django. Within the app I'm storing the classic "created" field within a few tables.
This is how the field looks like within the Django form:
created = models.DateTimeField(blank=True, default=datetime.now())
Unfortunately, datetime.now() is not accurate. In fact in the database I have sets of rows with the exact same timestamp.
The datetime.now() value seems to change every 30-45 minutes.
My Django app is served on Windows Server 2005 behind IIS6.
Help would be amazing!
A:
This is a common newbie mistake, unfortunately. You have called the datetime.now() method in the definition - this means the default will be the time at which the definition was executed, ie when your server process starts up.
You need to pass the callable instead:
created = models.DateTimeField(blank=True, default=datetime.now)
ie without the calling brackets.
(Or, just use auto_now_add=True).
A:
because datetime.now() is being called when your module is initialised and that value is being used for the default.
You want to use the auto_now_add=True parameter
created = models.DateTimeField(auto_now_add=True)
edit: no need for 'blank' if you're setting the auto option.
A:
You don't have auto_now or auto_now_add fields set to True. Consequently, the default value is what's filled in on the form. When the form is sent to the browser. Of course there will be duplicates.
http://docs.djangoproject.com/en/1.2/ref/models/fields/#datetimefield
| Datetime.now() abnormality - Python | I'm serving a Python app through Django. Within the app I'm storing the classic "created" field within a few tables.
This is how the field looks like within the Django form:
created = models.DateTimeField(blank=True, default=datetime.now())
Unfortunately, datetime.now() is not accurate. In fact in the database I have sets of rows with the exact same timestamp.
The datetime.now() value seems to change every 30-45 minutes.
My Django app is served on Windows Server 2005 behind IIS6.
Help would be amazing!
| [
"This is a common newbie mistake, unfortunately. You have called the datetime.now() method in the definition - this means the default will be the time at which the definition was executed, ie when your server process starts up.\nYou need to pass the callable instead: \ncreated = models.DateTimeField(blank=True, default=datetime.now)\n\nie without the calling brackets. \n(Or, just use auto_now_add=True).\n",
"because datetime.now() is being called when your module is initialised and that value is being used for the default.\nYou want to use the auto_now_add=True parameter\ncreated = models.DateTimeField(auto_now_add=True)\n\nedit: no need for 'blank' if you're setting the auto option.\n",
"You don't have auto_now or auto_now_add fields set to True. Consequently, the default value is what's filled in on the form. When the form is sent to the browser. Of course there will be duplicates.\nhttp://docs.djangoproject.com/en/1.2/ref/models/fields/#datetimefield\n"
] | [
10,
6,
2
] | [] | [] | [
"datetime",
"django",
"django_models",
"iis",
"python"
] | stackoverflow_0003100612_datetime_django_django_models_iis_python.txt |
Q:
Wrapping C++ dynamic array with Python+ctypes, segfault
I wanted to wrap a small C++ code allocating an array with ctypes and there is something wrong with storing the address in a c_void_p object.
(Note: the pointers are intentionally cast to void*, 'cause later I want to do the allocation the same way for arrays of C++ objects, too.)
The C(++) functions to be wrapped:
void* test_alloc()
{
const int size = 100000000;
int* ptr = new int[size];
std::cout << "Allocated " << size * sizeof(int) << " bytes @ " <<
ptr << std::endl;
return static_cast<void*>(ptr);
}
void test_dealloc(void* ptr)
{
int* iptr = static_cast<int*>(ptr);
std::cout << "Trying to free array @ " << iptr << std::endl;
delete[] iptr;
}
The Python wrapper (assume the former functions are already imported with ctypes):
class TestAlloc(object):
def __init__(self):
self.pointer = ctypes.c_void_p(test_alloc())
print "self.pointer points to ", hex(self.pointer.value)
def __del__(self):
test_dealloc(self.pointer)
For small arrays (e.g. size = 10), it seems ok:
In [5]: t = TestAlloc()
Allocated 40 bytes @ 0x1f20ef0
self.pointer points to 0x1f20ef0
In [6]: del t
Trying to free array @ 0x1f20ef0
But if I want to allocate a large one (size = 100 000 000), problems occur:
In [2]: t = TestAlloc()
Allocated 400000000 bytes @ 0x7faec3b71010
self.pointer points to 0xffffffffc3b71010L
In [3]: del t
Trying to free array @ 0xffffffffc3b71010
Segmentation fault
The address stored in ctypes.c_void_p is obviously wrong, the upper 4 bytes are invalid.
Somehow 32-bit and 64-bit addresses are mixed, and with the large array allocation the memory manager (in this case) is forced to return an address not representable on 32 bits (thx TonJ).
Can someone please provide a workaround for this?
The code has been compiled with g++ 4.4.3 and run on Ubuntu Linux 10.04 x86_64 with 4G RAM. Python version is 2.6.5.
Thank you very much!
UPDATE:
I managed to solve the problem. I forgot to specify restype for test_alloc(). The default value for restype was ctypes.c_int, into which the 64-bit address did not fit. By also adding a test_alloc.restype = ctypes.c_void_p before the call of test_alloc() solved the problem.
A:
From just looking at it, it seems that the problem is not in the small/big array allocation, but in a mix of 32bit and 64bit addresses.
In your example, the address of the small array fits in 32 bits, but the address of the big array doesn't.
| Wrapping C++ dynamic array with Python+ctypes, segfault | I wanted to wrap a small C++ code allocating an array with ctypes and there is something wrong with storing the address in a c_void_p object.
(Note: the pointers are intentionally cast to void*, 'cause later I want to do the allocation the same way for arrays of C++ objects, too.)
The C(++) functions to be wrapped:
void* test_alloc()
{
const int size = 100000000;
int* ptr = new int[size];
std::cout << "Allocated " << size * sizeof(int) << " bytes @ " <<
ptr << std::endl;
return static_cast<void*>(ptr);
}
void test_dealloc(void* ptr)
{
int* iptr = static_cast<int*>(ptr);
std::cout << "Trying to free array @ " << iptr << std::endl;
delete[] iptr;
}
The Python wrapper (assume the former functions are already imported with ctypes):
class TestAlloc(object):
def __init__(self):
self.pointer = ctypes.c_void_p(test_alloc())
print "self.pointer points to ", hex(self.pointer.value)
def __del__(self):
test_dealloc(self.pointer)
For small arrays (e.g. size = 10), it seems ok:
In [5]: t = TestAlloc()
Allocated 40 bytes @ 0x1f20ef0
self.pointer points to 0x1f20ef0
In [6]: del t
Trying to free array @ 0x1f20ef0
But if I want to allocate a large one (size = 100 000 000), problems occur:
In [2]: t = TestAlloc()
Allocated 400000000 bytes @ 0x7faec3b71010
self.pointer points to 0xffffffffc3b71010L
In [3]: del t
Trying to free array @ 0xffffffffc3b71010
Segmentation fault
The address stored in ctypes.c_void_p is obviously wrong, the upper 4 bytes are invalid.
Somehow 32-bit and 64-bit addresses are mixed, and with the large array allocation the memory manager (in this case) is forced to return an address not representable on 32 bits (thx TonJ).
Can someone please provide a workaround for this?
The code has been compiled with g++ 4.4.3 and run on Ubuntu Linux 10.04 x86_64 with 4G RAM. Python version is 2.6.5.
Thank you very much!
UPDATE:
I managed to solve the problem. I forgot to specify restype for test_alloc(). The default value for restype was ctypes.c_int, into which the 64-bit address did not fit. By also adding a test_alloc.restype = ctypes.c_void_p before the call of test_alloc() solved the problem.
| [
"From just looking at it, it seems that the problem is not in the small/big array allocation, but in a mix of 32bit and 64bit addresses.\nIn your example, the address of the small array fits in 32 bits, but the address of the big array doesn't.\n"
] | [
1
] | [] | [] | [
"c++",
"ctypes",
"memory_management",
"python",
"segmentation_fault"
] | stackoverflow_0003100554_c++_ctypes_memory_management_python_segmentation_fault.txt |
Q:
Java equivalent of python's String partition
Java's string split(regex) function splits at all instances of the regex. Python's partition function only splits at the first instance of the given separator, and returns a tuple of {left,separator,right}.
How do I achieve what partition does in Java?
e.g.
"foo bar hello world".partition(" ")
should become
"foo", " ", "bar hello world"
Is there an external library which
provides this utility already?
how would I achieve it without
an external library?
And can it be achieved without an external library and without Regex?
NB. I'm not looking for split(" ",2) as it doesn't return the separator character.
A:
While not exactly what you want, there's a second version of split which takes a "limit" parameter, telling it the maximum number of partitions to split the string into.
So if you called (in Java):
"foo bar hello world".split(" ", 2);
You'd get the array:
["foo", "bar hello world"]
which is more or less what you want, except for the fact that the separator character isn't embedded at index 1. If you really need this last point, you'd need to do it yourself, but hopefully all you specifically wanted was the ability to limit the number of splits.
A:
The String.split(String regex, int limit) is close to what you want. From the documentation:
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.
If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.
If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.
If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Here's an example to show these differences (as seen on ideone.com):
static void dump(String[] ss) {
for (String s: ss) {
System.out.print("[" + s + "]");
}
System.out.println();
}
public static void main(String[] args) {
String text = "a-b-c-d---";
dump(text.split("-"));
// prints "[a][b][c][d]"
dump(text.split("-", 2));
// prints "[a][b-c-d---]"
dump(text.split("-", -1));
// [a][b][c][d][][][]
}
A partition that keeps the delimiter
If you need a similar functionality to the partition, and you also want to get the delimiter string that was matched by an arbitrary pattern, you can use Matcher, then taking substring at appropriate indices.
Here's an example (as seen on ideone.com):
static String[] partition(String s, String regex) {
Matcher m = Pattern.compile(regex).matcher(s);
if (m.find()) {
return new String[] {
s.substring(0, m.start()),
m.group(),
s.substring(m.end()),
};
} else {
throw new NoSuchElementException("Can't partition!");
}
}
public static void main(String[] args) {
dump(partition("james007bond111", "\\d+"));
// prints "[james][007][bond111]"
}
The regex \d+ of course is any digit character (\d) repeated one-or-more times (+).
A:
How about this:
String partition(String string, String separator) {
String[] parts = string.split(separator, 2);
return new String[] {parts[0], separator, parts[1]};
}
BTW, you have to add some input/result checks at this :)
A:
Use:
"foo bar hello world".split(" ",2)
By default the delimiter is whitespace
A:
Is there an external library which provides this utility already?
None that I know of.
how would I achieve it without an external library?
And can it be achieved without an external library and without Regex?
Sure, that's no problem at all; just use String.indexOf() and String.substring(). However, Java does not have tuple datatype, so you'll have to return an array, List or write your own result class.
| Java equivalent of python's String partition | Java's string split(regex) function splits at all instances of the regex. Python's partition function only splits at the first instance of the given separator, and returns a tuple of {left,separator,right}.
How do I achieve what partition does in Java?
e.g.
"foo bar hello world".partition(" ")
should become
"foo", " ", "bar hello world"
Is there an external library which
provides this utility already?
how would I achieve it without
an external library?
And can it be achieved without an external library and without Regex?
NB. I'm not looking for split(" ",2) as it doesn't return the separator character.
| [
"While not exactly what you want, there's a second version of split which takes a \"limit\" parameter, telling it the maximum number of partitions to split the string into.\nSo if you called (in Java):\n\"foo bar hello world\".split(\" \", 2);\n\nYou'd get the array:\n[\"foo\", \"bar hello world\"]\n\nwhich is more or less what you want, except for the fact that the separator character isn't embedded at index 1. If you really need this last point, you'd need to do it yourself, but hopefully all you specifically wanted was the ability to limit the number of splits.\n",
"The String.split(String regex, int limit) is close to what you want. From the documentation:\n\nThe limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.\n\nIf the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.\nIf n is non-positive then the pattern will be applied as many times as possible and the array can have any length.\n\nIf n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.\n\n\n\n\nHere's an example to show these differences (as seen on ideone.com):\nstatic void dump(String[] ss) {\n for (String s: ss) {\n System.out.print(\"[\" + s + \"]\");\n }\n System.out.println();\n}\npublic static void main(String[] args) {\n String text = \"a-b-c-d---\";\n\n dump(text.split(\"-\"));\n // prints \"[a][b][c][d]\"\n\n dump(text.split(\"-\", 2));\n // prints \"[a][b-c-d---]\"\n\n dump(text.split(\"-\", -1));\n // [a][b][c][d][][][]\n \n}\n\n\nA partition that keeps the delimiter\nIf you need a similar functionality to the partition, and you also want to get the delimiter string that was matched by an arbitrary pattern, you can use Matcher, then taking substring at appropriate indices.\nHere's an example (as seen on ideone.com):\nstatic String[] partition(String s, String regex) {\n Matcher m = Pattern.compile(regex).matcher(s);\n if (m.find()) {\n return new String[] {\n s.substring(0, m.start()),\n m.group(),\n s.substring(m.end()),\n };\n } else {\n throw new NoSuchElementException(\"Can't partition!\");\n }\n}\npublic static void main(String[] args) {\n dump(partition(\"james007bond111\", \"\\\\d+\"));\n // prints \"[james][007][bond111]\"\n}\n\nThe regex \\d+ of course is any digit character (\\d) repeated one-or-more times (+).\n",
"How about this:\nString partition(String string, String separator) {\n String[] parts = string.split(separator, 2);\n return new String[] {parts[0], separator, parts[1]};\n}\n\nBTW, you have to add some input/result checks at this :)\n",
"Use:\n\n\"foo bar hello world\".split(\" \",2)\n\nBy default the delimiter is whitespace\n",
"\nIs there an external library which provides this utility already?\n\nNone that I know of.\n\nhow would I achieve it without an external library?\n And can it be achieved without an external library and without Regex?\n\nSure, that's no problem at all; just use String.indexOf() and String.substring(). However, Java does not have tuple datatype, so you'll have to return an array, List or write your own result class.\n"
] | [
5,
5,
2,
0,
0
] | [] | [] | [
"java",
"python",
"split",
"string"
] | stackoverflow_0003100739_java_python_split_string.txt |
Q:
How to add abilities to strings in Python
This is more of a curiosity question than anything else. I'm new with Python and playing around with it. I've just looked at the base64 module. What if instead of doing:
import base64
string = 'Foo Bar'
encoded = base664.b64encode
I wanted to do something like:
>>> class b64string():
>>> <something>
>>>
>>> string = b64string('Foo Bar')
>>> string
'Foo Bar'
>>> string.encode64()
'Rm9vIEJhcg=='
>>> string
'Rm9vIEJhcg=='
>>> string.assign('QmFyIEZvbw==')
>>> string
'QmFyIEZvbw=='
>>> string.b64decode()
'Bar Foo'
>>> string
'Bar Foo'
Is there a simple, pythonic way to create that class?
I've begun with this:
>>> class b64string(base64):
... def __init__(self, v):
... self.value=v
And already I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)
And don't get me started on (just to see what would happen):
>>> class b64string(str, base64): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
I know how to do it manually by listing all of the attributes of base64 in a new class and calling them with the stored value as argument. But is there a neat, pythonic way to do this? Is it a bad idea to do it? The idea would be, if needed, to do it with many such modules and have "super strings" that would have as modules all the things I would need to do with them. Is that bad? Is it un-pythonic? If it is pythonic, how is it done?
A:
I don't think creating such complex string-like classes is a good idea, but if you really want to, here's a simple snippet that runs your examples.
First, we define a class that's a generic string-wrapper. Its core is a __getattr__ function that forwards every method call to a given self.module, adding self.string as the first parameter and remembering the result on self.string.
import base64
class ModuledString(object):
def __init__(self, string):
self.string = string
def __getattr__(self, attrname):
def func(*args, **kwargs):
result = getattr(self.module, attrname)(self.string, *args, **kwargs)
self.string = result
return result
return func
def __str__(self):
return str(self.string)
Creating a string-wrapper with base64 capabilities is then easy:
class B64String(ModuledString):
module = base64
if __name__ == '__main__':
string = B64String('Foo Bar')
print string
# 'Foo Bar'
print string.b64encode()
# 'Rm9vIEJhcg=='
print string
# 'Rm9vIEJhcg=='
string.string = 'QmFyIEZvbw=='
print string
# 'QmFyIEZvbw=='
print string.b64decode()
# 'Bar Foo'
Note that the above examples work only because b64encode and b64decode take a string as the first argument and return a string as the result (there is no validation in my __getattr__ function). A random function from some random module would probably raise some kind of exception. So, after all, it would be better to restrict the usage to a predefined set of functions from a given module, but it should be easy now.
I repeat, I don't recommend using such code in any serious project, only for fun.
| How to add abilities to strings in Python | This is more of a curiosity question than anything else. I'm new with Python and playing around with it. I've just looked at the base64 module. What if instead of doing:
import base64
string = 'Foo Bar'
encoded = base664.b64encode
I wanted to do something like:
>>> class b64string():
>>> <something>
>>>
>>> string = b64string('Foo Bar')
>>> string
'Foo Bar'
>>> string.encode64()
'Rm9vIEJhcg=='
>>> string
'Rm9vIEJhcg=='
>>> string.assign('QmFyIEZvbw==')
>>> string
'QmFyIEZvbw=='
>>> string.b64decode()
'Bar Foo'
>>> string
'Bar Foo'
Is there a simple, pythonic way to create that class?
I've begun with this:
>>> class b64string(base64):
... def __init__(self, v):
... self.value=v
And already I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
module.__init__() takes at most 2 arguments (3 given)
And don't get me started on (just to see what would happen):
>>> class b64string(str, base64): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
I know how to do it manually by listing all of the attributes of base64 in a new class and calling them with the stored value as argument. But is there a neat, pythonic way to do this? Is it a bad idea to do it? The idea would be, if needed, to do it with many such modules and have "super strings" that would have as modules all the things I would need to do with them. Is that bad? Is it un-pythonic? If it is pythonic, how is it done?
| [
"I don't think creating such complex string-like classes is a good idea, but if you really want to, here's a simple snippet that runs your examples.\nFirst, we define a class that's a generic string-wrapper. Its core is a __getattr__ function that forwards every method call to a given self.module, adding self.string as the first parameter and remembering the result on self.string.\nimport base64\n\nclass ModuledString(object):\n def __init__(self, string):\n self.string = string\n\n def __getattr__(self, attrname):\n def func(*args, **kwargs):\n result = getattr(self.module, attrname)(self.string, *args, **kwargs)\n self.string = result\n return result\n return func\n\n def __str__(self):\n return str(self.string)\n\nCreating a string-wrapper with base64 capabilities is then easy:\nclass B64String(ModuledString):\n module = base64\n\nif __name__ == '__main__':\n string = B64String('Foo Bar')\n print string\n # 'Foo Bar'\n print string.b64encode()\n # 'Rm9vIEJhcg=='\n print string\n # 'Rm9vIEJhcg=='\n string.string = 'QmFyIEZvbw=='\n print string\n # 'QmFyIEZvbw=='\n print string.b64decode()\n # 'Bar Foo'\n\nNote that the above examples work only because b64encode and b64decode take a string as the first argument and return a string as the result (there is no validation in my __getattr__ function). A random function from some random module would probably raise some kind of exception. So, after all, it would be better to restrict the usage to a predefined set of functions from a given module, but it should be easy now.\nI repeat, I don't recommend using such code in any serious project, only for fun.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003100789_python.txt |
Q:
Extracting some HTML tag values in Python
How to get a value of nested <b> HTML tag in Python using regular expressions?
<a href="/model.xml?hid=90971&modelid=4636873&show-uid=678650012772883921" class="b-offers__name"><b>LG</b> X110</a>
# => LG X110
A:
You don't.
Regular Expressions are not well suited to deal with the nested structure of HTML. Use an HTML parser instead.
A:
Don't use regular expressions for parsing HTML. Use an HTML parser like BeautifulSoup. Just look how easy it is:
from BeautifulSoup import BeautifulSoup
html = r'<a href="removed because it was too long"><b>LG</b> X110</a>'
soup = BeautifulSoup(html)
print ''.join(soup.findAll(text=True))
# LG X110
A:
Try this...
<a.*<b>(.*)</b>(.*)</a>
$1 and $2 should be what you want, or whatever means Python has for printing captured groups.
A:
Your question was very hard to understand, but from the given output example it looks like you want to strip everything within < and > from the input text. That can be done like so:
import re
input_text = '<a bob>i <b>c</b></a>'
output_text = re.sub('<[^>]*>', '', input_text)
print output_text
Which gives you:
i c
If that is not what you want, please clarify.
Please note that the regular expression approach for parsing XML is very brittle. For instance, the above example would break on the input <a name="b>c">hey</a>. (> is a valid character in a attribute value: see XML specs)
A:
+1 for Jens's answer. lxml is a good library you can use to actually parse this in a robust fashion. If you'd prefer something in the standard library, you can use sax, dom or elementree.
| Extracting some HTML tag values in Python | How to get a value of nested <b> HTML tag in Python using regular expressions?
<a href="/model.xml?hid=90971&modelid=4636873&show-uid=678650012772883921" class="b-offers__name"><b>LG</b> X110</a>
# => LG X110
| [
"You don't. \nRegular Expressions are not well suited to deal with the nested structure of HTML. Use an HTML parser instead.\n",
"Don't use regular expressions for parsing HTML. Use an HTML parser like BeautifulSoup. Just look how easy it is:\nfrom BeautifulSoup import BeautifulSoup\nhtml = r'<a href=\"removed because it was too long\"><b>LG</b> X110</a>'\nsoup = BeautifulSoup(html)\nprint ''.join(soup.findAll(text=True))\n# LG X110\n\n",
"Try this...\n<a.*<b>(.*)</b>(.*)</a>\n\n$1 and $2 should be what you want, or whatever means Python has for printing captured groups.\n",
"Your question was very hard to understand, but from the given output example it looks like you want to strip everything within < and > from the input text. That can be done like so:\nimport re\ninput_text = '<a bob>i <b>c</b></a>'\noutput_text = re.sub('<[^>]*>', '', input_text)\nprint output_text\n\nWhich gives you:\ni c\n\nIf that is not what you want, please clarify.\nPlease note that the regular expression approach for parsing XML is very brittle. For instance, the above example would break on the input <a name=\"b>c\">hey</a>. (> is a valid character in a attribute value: see XML specs)\n",
"+1 for Jens's answer. lxml is a good library you can use to actually parse this in a robust fashion. If you'd prefer something in the standard library, you can use sax, dom or elementree.\n"
] | [
7,
6,
1,
1,
0
] | [] | [] | [
"html",
"parsing",
"python",
"regex"
] | stackoverflow_0003100896_html_parsing_python_regex.txt |
Q:
python: trouble printing short utf-encoded strings
(The following is using Python 2.6.1)
I have 2 strings:
>>> a = u'\u05e8\u05db\u05e1'
>>> b = u'\u05e8\u05db\u05e1 \u05d4\u05d9\u05d0 \u05de\u05d0\u05d9\u05e8\u05d4 \u05d1\u05e4\u05e0\u05e1'
I encode them:
>>> ua = a.encode('utf-8')
>>> ub = b.encode('utf-8')
>>> ua
'\xd7\xa8\xd7\x9b\xd7\xa1'
>>> ub
'\xd7\xa8\xd7\x9b\xd7\xa1 \xd7\x94\xd7\x99\xd7\x90 \xd7\x9e\xd7\x90\xd7\x99\xd7\xa8\xd7\x94 \xd7\x91\xd7\xa4\xd7\xa0\xd7\xa1'
and try to print:
>>> print ua
רכס
>>> print ub
רכס היא מאירה בפנס
Why does ub print in Hebrew characters while ua doesn't? ua is just the first few characters of ub, so it seems as though string length is somehow the problem, which is weird.
(For the record, this came up trying to parse a webpage with BeautifulSoup -- I couldn't tell why some paragraphs came out readably while others didn't.)
A:
Must be something with your terminal settings; ua prints three Hebrew characters on my terminal (Terminal.app on OS X), exactly the rightmost three characters of ub. (Since Hebrew is a right-to-left script, the rightmost three characters are the first three).
For the record, I've tried it with Python 2.6.1.
| python: trouble printing short utf-encoded strings | (The following is using Python 2.6.1)
I have 2 strings:
>>> a = u'\u05e8\u05db\u05e1'
>>> b = u'\u05e8\u05db\u05e1 \u05d4\u05d9\u05d0 \u05de\u05d0\u05d9\u05e8\u05d4 \u05d1\u05e4\u05e0\u05e1'
I encode them:
>>> ua = a.encode('utf-8')
>>> ub = b.encode('utf-8')
>>> ua
'\xd7\xa8\xd7\x9b\xd7\xa1'
>>> ub
'\xd7\xa8\xd7\x9b\xd7\xa1 \xd7\x94\xd7\x99\xd7\x90 \xd7\x9e\xd7\x90\xd7\x99\xd7\xa8\xd7\x94 \xd7\x91\xd7\xa4\xd7\xa0\xd7\xa1'
and try to print:
>>> print ua
רכס
>>> print ub
רכס היא מאירה בפנס
Why does ub print in Hebrew characters while ua doesn't? ua is just the first few characters of ub, so it seems as though string length is somehow the problem, which is weird.
(For the record, this came up trying to parse a webpage with BeautifulSoup -- I couldn't tell why some paragraphs came out readably while others didn't.)
| [
"Must be something with your terminal settings; ua prints three Hebrew characters on my terminal (Terminal.app on OS X), exactly the rightmost three characters of ub. (Since Hebrew is a right-to-left script, the rightmost three characters are the first three).\nFor the record, I've tried it with Python 2.6.1.\n"
] | [
1
] | [] | [] | [
"python",
"python_2.x",
"unicode"
] | stackoverflow_0003101100_python_python_2.x_unicode.txt |
Q:
How to pad all the numbers in a string
I've got lots of address style strings and I want to sort them in a rational way.
I'm looking to pad all the numbers in a string so that: "Flat 12A High Rise" becomes "Flat 00012A High Rise", there may be multiple numbers in the string.
So far I've got:
def pad_numbers_in_string(string, padding=5):
numbers = re.findall("\d+", string)
padded_string = ''
for number in numbers:
parts = string.partition(number)
string = parts[2]
padded_string += "%s%s" % (parts[0], parts[1].zfill(padding))
padded_string += string
return padded_string
Can that be improved - looks pugly to me!
A:
Instead of changing your data to accommodate your sorting algorithm, change your sorting algorithm to accommodate your data.
See Sorting For Humans: Natural Sort Order on Coding Horror:
import re
def sort_nicely( l ):
""" Sort the given list in the way that humans expect.
"""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
l.sort( key=alphanum_key )
A:
How about this?
re.sub('\d+', lambda x:x.group().zfill(padding), s)
Example:
>>> s = "Flat 12A High Rise 101B"
>>> padding = 5
>>> re.sub('\d+', lambda x:x.group().zfill(padding), s)
'Flat 00012A High Rise 00101B'
>>>
| How to pad all the numbers in a string | I've got lots of address style strings and I want to sort them in a rational way.
I'm looking to pad all the numbers in a string so that: "Flat 12A High Rise" becomes "Flat 00012A High Rise", there may be multiple numbers in the string.
So far I've got:
def pad_numbers_in_string(string, padding=5):
numbers = re.findall("\d+", string)
padded_string = ''
for number in numbers:
parts = string.partition(number)
string = parts[2]
padded_string += "%s%s" % (parts[0], parts[1].zfill(padding))
padded_string += string
return padded_string
Can that be improved - looks pugly to me!
| [
"Instead of changing your data to accommodate your sorting algorithm, change your sorting algorithm to accommodate your data.\nSee Sorting For Humans: Natural Sort Order on Coding Horror:\nimport re \n\ndef sort_nicely( l ): \n \"\"\" Sort the given list in the way that humans expect. \n \"\"\" \n convert = lambda text: int(text) if text.isdigit() else text \n alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] \n l.sort( key=alphanum_key ) \n\n",
"How about this?\nre.sub('\\d+', lambda x:x.group().zfill(padding), s)\n\nExample:\n>>> s = \"Flat 12A High Rise 101B\"\n>>> padding = 5\n>>> re.sub('\\d+', lambda x:x.group().zfill(padding), s)\n'Flat 00012A High Rise 00101B'\n>>> \n\n"
] | [
9,
8
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003101778_python_string.txt |
Q:
Stack recommendations for small/medium-sized web application in Python
I'm looking for some recommendations for a python web application. We have some memory restrictions and we try to keep it small and lean.
We thought about using WSGI (and a python webserver) and build the rest ourself. We already have a template engine we'd like to use, but we are open for some suggestions regarding the whole request handling (the controller).
The application has to run in a single process and the requests have to be processed with multiple threads.
We've looked at django, but we are a not sure if it fits into our memory budget.
Your feedback is very welcome!
Cheers,
Reto
A:
I've been using Werkzeug because it's more a small collection of really useful components than a whole framework. It runs behind a wsgi server of your choice (and comes with a built-in one). If you want something even easier, Flask might be worth a look. Also, you might want to bookmark the rather speedy Jinja in case your template engine doesn't pan out. Those folks over at pocoo.org have been releasing some nice stuff.
A:
You can run an django application in 20 mb memory easily. probably a django application will use less memory than 20mb.
I want to advise you to check webpy and cherrypy
but I'm big fan of django. if you have 20 mb memory to run application, django will give you everythig it has.
A:
I'd go for bottle. It has all the conciseness of web.py but with some nice routing features.
A:
You could take a look at Twisted, which has a module twisted.web. That seems to be fairly light-weight. I'm currently using it, and with a simple app it starts almost instantaneously, so it can't be all that resource intensive :)
I don't know whether Twisted uses different threads.
A:
webpy (http://webpy.org/) is a very minimal memory footprint but highly usable framework. But it all depends on how complex your application is going to be.
A:
Also please take a look at WHIFF. It's tiny and very flexible whiff documentation
| Stack recommendations for small/medium-sized web application in Python | I'm looking for some recommendations for a python web application. We have some memory restrictions and we try to keep it small and lean.
We thought about using WSGI (and a python webserver) and build the rest ourself. We already have a template engine we'd like to use, but we are open for some suggestions regarding the whole request handling (the controller).
The application has to run in a single process and the requests have to be processed with multiple threads.
We've looked at django, but we are a not sure if it fits into our memory budget.
Your feedback is very welcome!
Cheers,
Reto
| [
"I've been using Werkzeug because it's more a small collection of really useful components than a whole framework. It runs behind a wsgi server of your choice (and comes with a built-in one). If you want something even easier, Flask might be worth a look. Also, you might want to bookmark the rather speedy Jinja in case your template engine doesn't pan out. Those folks over at pocoo.org have been releasing some nice stuff.\n",
"You can run an django application in 20 mb memory easily. probably a django application will use less memory than 20mb. \nI want to advise you to check webpy and cherrypy\nbut I'm big fan of django. if you have 20 mb memory to run application, django will give you everythig it has.\n",
"I'd go for bottle. It has all the conciseness of web.py but with some nice routing features.\n",
"You could take a look at Twisted, which has a module twisted.web. That seems to be fairly light-weight. I'm currently using it, and with a simple app it starts almost instantaneously, so it can't be all that resource intensive :)\nI don't know whether Twisted uses different threads.\n",
"webpy (http://webpy.org/) is a very minimal memory footprint but highly usable framework. But it all depends on how complex your application is going to be. \n",
"Also please take a look at WHIFF. It's tiny and very flexible whiff documentation\n"
] | [
3,
2,
2,
1,
0,
0
] | [] | [] | [
"python",
"wsgi"
] | stackoverflow_0002847593_python_wsgi.txt |
Q:
Python ctypes.WinDLL error , _dlopen(self._name, mode) can't be found
ctypes.WinDLL("C:\Program Files\AHSDK\bin\ahscript.dll")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\ctypes\__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
WindowsError: [Error 126] The specified module could not be found
How can I solve it? I found the _dlopen in C:\Python26\lib\ctypes\__init__.py, but I really don't know how to solve it.
A:
Backslashes are an escape character within strings, as demonstrated in the example below:
>>> print "C:\Program Files\AHSDK\bin\ahscript.dll"
C:\Program Files\AHSDinhscript.dll
You can solve the problem by placing an r before the string, which prevents the backslash from working as an escape character:
ctypes.WinDLL(r"C:\Program Files\AHSDK\bin\ahscript.dll")
Alternately, you could escape the backslashes:
ctypes.WinDLL("C:\\Program Files\\AHSDK\\bin\\ahscript.dll")
| Python ctypes.WinDLL error , _dlopen(self._name, mode) can't be found | ctypes.WinDLL("C:\Program Files\AHSDK\bin\ahscript.dll")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\ctypes\__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
WindowsError: [Error 126] The specified module could not be found
How can I solve it? I found the _dlopen in C:\Python26\lib\ctypes\__init__.py, but I really don't know how to solve it.
| [
"Backslashes are an escape character within strings, as demonstrated in the example below:\n>>> print \"C:\\Program Files\\AHSDK\\bin\\ahscript.dll\"\nC:\\Program Files\\AHSDinhscript.dll\n\nYou can solve the problem by placing an r before the string, which prevents the backslash from working as an escape character:\nctypes.WinDLL(r\"C:\\Program Files\\AHSDK\\bin\\ahscript.dll\")\n\nAlternately, you could escape the backslashes:\nctypes.WinDLL(\"C:\\\\Program Files\\\\AHSDK\\\\bin\\\\ahscript.dll\")\n\n"
] | [
8
] | [] | [] | [
"ctypes",
"dll",
"dllimport",
"python",
"windows"
] | stackoverflow_0003101981_ctypes_dll_dllimport_python_windows.txt |
Q:
Any smarter/faster/ligher replacement for this line of code?
file = [float(line.partition(' ')[0]) for line in file]
the file is object of open file...
thnq
A:
Smarter would be to not shadow file.
A:
For measurement of speed, see the Python standard library module timeit:
$ python -m timeit -s 'f = file("/tmp/numbers.txt")' '[float(line.partition(" ")[0]) for line in f]'
10000000 loops, best of 3: 0.123 usec per loop
$ python -m timeit -s 'f = file("/tmp/numbers.txt")' '[float(line.split(" ")[0]) for line in f]'
10000000 loops, best of 3: 0.132 usec per loop
$ python -m timeit -s 'f = file("/tmp/numbers.txt")' '[float(line.split(" ", 1)[0]) for line in f]'
10000000 loops, best of 3: 0.127 usec per loop
partition seems to be faster than split, at least. I can't think of a faster way right now, so well done.
A:
It depends what you are going to do with the list once it has been created. If you are just going to iterate through it then it may be better to use a generator expression so that you do not load the entire file into memory at once. If the file is large this could result in page swapping or out of memory errors.
I have read through the related questions you posted, and can see no information on what problem you are trying to solve or what you are going to do with the data once you have read it. If you give us some more context then we may be able to give more specific and helpful answers.
A:
If you're only interested in everything that comes before the first space (and assuming there always is one), you can try using string index:
[float(line[:line.index(" ")]) for line in f]
Borrowing Lars's tests, it runs faster than partition:
rbp@apfelstrudel ~$ python -m timeit -s 'f = open("/tmp/numbers.txt")' '[float(line.partition(" ")[0]) for line in f]'
10000000 loops, best of 3: 0.192 usec per loop
rbp@apfelstrudel ~$ python -m timeit -s 'f = open("/tmp/numbers.txt")' '[float(line[:line.index(" ")]) for line in f]'
10000000 loops, best of 3: 0.181 usec per loop
Also, of course, if you exchange the outer square brackets for parenthesis, you'll get a generator expression, which doesn't generate all the results straight away. Depending on how you'll use this, it may fit into the "smarter" category :)
Edited to add:
... Although, since SilentGhost mentioned this is py3k, the speed difference is not relevant then:
rbp@apfelstrudel ~$ python3 -m timeit -s 'f = open("/tmp/numbers.txt")' '[float(line[:line.index(" ")]) for line in f]'
100000 loops, best of 3: 10.9 usec per loop
rbp@apfelstrudel ~$ python3 -m timeit -s 'f = open("/tmp/numbers.txt")' '[float(line.partition(" ")[0]) for line in f]'
100000 loops, best of 3: 11 usec per loop
But I still think index is better, as it clearly shows what you mean (as opposed to partition, which gives you two additional values that you throw away immediately)
| Any smarter/faster/ligher replacement for this line of code? | file = [float(line.partition(' ')[0]) for line in file]
the file is object of open file...
thnq
| [
"Smarter would be to not shadow file.\n",
"For measurement of speed, see the Python standard library module timeit:\n$ python -m timeit -s 'f = file(\"/tmp/numbers.txt\")' '[float(line.partition(\" \")[0]) for line in f]'\n10000000 loops, best of 3: 0.123 usec per loop\n$ python -m timeit -s 'f = file(\"/tmp/numbers.txt\")' '[float(line.split(\" \")[0]) for line in f]'\n10000000 loops, best of 3: 0.132 usec per loop\n$ python -m timeit -s 'f = file(\"/tmp/numbers.txt\")' '[float(line.split(\" \", 1)[0]) for line in f]'\n10000000 loops, best of 3: 0.127 usec per loop\n\npartition seems to be faster than split, at least. I can't think of a faster way right now, so well done.\n",
"It depends what you are going to do with the list once it has been created. If you are just going to iterate through it then it may be better to use a generator expression so that you do not load the entire file into memory at once. If the file is large this could result in page swapping or out of memory errors.\nI have read through the related questions you posted, and can see no information on what problem you are trying to solve or what you are going to do with the data once you have read it. If you give us some more context then we may be able to give more specific and helpful answers.\n",
"If you're only interested in everything that comes before the first space (and assuming there always is one), you can try using string index:\n[float(line[:line.index(\" \")]) for line in f]\n\nBorrowing Lars's tests, it runs faster than partition:\nrbp@apfelstrudel ~$ python -m timeit -s 'f = open(\"/tmp/numbers.txt\")' '[float(line.partition(\" \")[0]) for line in f]'\n10000000 loops, best of 3: 0.192 usec per loop\nrbp@apfelstrudel ~$ python -m timeit -s 'f = open(\"/tmp/numbers.txt\")' '[float(line[:line.index(\" \")]) for line in f]'\n10000000 loops, best of 3: 0.181 usec per loop\n\nAlso, of course, if you exchange the outer square brackets for parenthesis, you'll get a generator expression, which doesn't generate all the results straight away. Depending on how you'll use this, it may fit into the \"smarter\" category :)\nEdited to add:\n... Although, since SilentGhost mentioned this is py3k, the speed difference is not relevant then:\nrbp@apfelstrudel ~$ python3 -m timeit -s 'f = open(\"/tmp/numbers.txt\")' '[float(line[:line.index(\" \")]) for line in f]'\n100000 loops, best of 3: 10.9 usec per loop\nrbp@apfelstrudel ~$ python3 -m timeit -s 'f = open(\"/tmp/numbers.txt\")' '[float(line.partition(\" \")[0]) for line in f]'\n100000 loops, best of 3: 11 usec per loop\n\nBut I still think index is better, as it clearly shows what you mean (as opposed to partition, which gives you two additional values that you throw away immediately)\n"
] | [
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003099565_python.txt |
Q:
Python : How to import a module if I have its path as a string?
Lets say I have path to a module in a string module_to_be_imported = 'a.b.module'
How can I import it ?
A:
>>> m = __import__('xml.sax')
>>> m.__name__
'xml'
>>> m = __import__('xml.sax', fromlist=[''])
>>> m.__name__
'xml.sax'
A:
You can use the build-in __import__ function. For example:
import sys
myconfigfile = sys.argv[1]
try:
config = __import__(myconfigfile)
for i in config.__dict__:
print i
except ImportError:
print "Unable to import configuration file %s" % (myconfigfile,)
For more information, see:
Python Documentation
Python.org - [Python Wpg] Import a module using a string
A:
x = __import__('a.b.module', fromlist=[''])
Reference
| Python : How to import a module if I have its path as a string? | Lets say I have path to a module in a string module_to_be_imported = 'a.b.module'
How can I import it ?
| [
">>> m = __import__('xml.sax')\n>>> m.__name__\n'xml'\n>>> m = __import__('xml.sax', fromlist=[''])\n>>> m.__name__\n'xml.sax'\n\n",
"You can use the build-in __import__ function. For example:\nimport sys\n\nmyconfigfile = sys.argv[1]\n\ntry:\n config = __import__(myconfigfile)\n for i in config.__dict__:\n print i \nexcept ImportError:\n print \"Unable to import configuration file %s\" % (myconfigfile,)\n\nFor more information, see:\n\nPython Documentation\nPython.org - [Python Wpg] Import a module using a string\n\n",
"x = __import__('a.b.module', fromlist=[''])\n\nReference\n"
] | [
6,
3,
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0003102252_import_python.txt |
Q:
python - gtk treeview - liststore with real-time update
i am having a issue with treeview liststore trying to get a real-time update, and I created a example to simulate what I'd like to do.
I want liststore1 updated each loop.
http://img204.imageshack.us/i/capturadetela5.png/
it should update the treeview column 'speed' and give to it a different number every second,
something like a download manager.
import gtk
import gtk.glade
import random
builder = gtk.Builder()
builder.add_from_file('ttt.glade')
window = builder.get_object('window1')
treeview = builder.get_object('treeview1')
store = builder.get_object('liststore1')
column_n = ['File','Size','Speed']
rendererText = gtk.CellRendererText()
for i in range(10):
foo = random.randint(100,256)
list_ = [('arquivo1.tar.gz', '10MB', '%s k/s' % foo)]
for x,y in zip(column_n,range(3)):
column = gtk.TreeViewColumn(x, rendererText, text=y)
column.set_sort_column_id(0)
treeview.append_column(column)
for list_index in list_:
store.append([list_index[0],list_index[1],list_index[2]])
window.show_all()
A:
If that's your full code, you're missing the GTK main loop invocation.
You need to do two things (in this order)
1 - Connect your window's destroy signal to a function that calls gtk.main_quit()
def on_destroy(widget, user_data=None):
# Exit the app
gtk.main_quit()
window.connect('destroy', on_destroy)
2 - Start the GTK main loop:
gtk.main()
This is where your app is effectively launched, and it will appear to hang at this line until gtk.main_quit() is called.
More generally... you should clean up the code a bit there :) Look at the "Hello World" demo from the PyGTK tutorial - it basically covers those points and more in greater detail. You'll find that following their general structure for things helps immensely.
If you want timed updates, look at the functions timeout_add and timeout_add_seconds - depending on your version of PyGTK/PyGobject these will be in the glib or gobject modules.
(Incidentally, GTKBuilder XML files typically have the .ui extension, even though Glade doesn't know it.)
| python - gtk treeview - liststore with real-time update | i am having a issue with treeview liststore trying to get a real-time update, and I created a example to simulate what I'd like to do.
I want liststore1 updated each loop.
http://img204.imageshack.us/i/capturadetela5.png/
it should update the treeview column 'speed' and give to it a different number every second,
something like a download manager.
import gtk
import gtk.glade
import random
builder = gtk.Builder()
builder.add_from_file('ttt.glade')
window = builder.get_object('window1')
treeview = builder.get_object('treeview1')
store = builder.get_object('liststore1')
column_n = ['File','Size','Speed']
rendererText = gtk.CellRendererText()
for i in range(10):
foo = random.randint(100,256)
list_ = [('arquivo1.tar.gz', '10MB', '%s k/s' % foo)]
for x,y in zip(column_n,range(3)):
column = gtk.TreeViewColumn(x, rendererText, text=y)
column.set_sort_column_id(0)
treeview.append_column(column)
for list_index in list_:
store.append([list_index[0],list_index[1],list_index[2]])
window.show_all()
| [
"If that's your full code, you're missing the GTK main loop invocation.\nYou need to do two things (in this order)\n1 - Connect your window's destroy signal to a function that calls gtk.main_quit()\ndef on_destroy(widget, user_data=None):\n # Exit the app\n gtk.main_quit()\n\nwindow.connect('destroy', on_destroy)\n\n2 - Start the GTK main loop:\ngtk.main()\n\nThis is where your app is effectively launched, and it will appear to hang at this line until gtk.main_quit() is called.\nMore generally... you should clean up the code a bit there :) Look at the \"Hello World\" demo from the PyGTK tutorial - it basically covers those points and more in greater detail. You'll find that following their general structure for things helps immensely.\nIf you want timed updates, look at the functions timeout_add and timeout_add_seconds - depending on your version of PyGTK/PyGobject these will be in the glib or gobject modules.\n(Incidentally, GTKBuilder XML files typically have the .ui extension, even though Glade doesn't know it.)\n"
] | [
2
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003102464_pygtk_python.txt |
Q:
Mysql database Import Error in python
i have installed python 2.6.4. i have downloaded mysql database module. but i don't know where to place that module in python package. when i execute the program it shows import error "no module named mysql db". please tell me where to place the module.
A:
it's case-sensitive, module name is 'MySQLdb'
yed@rublan ~/skript $ python
Python 2.6.5 (release26-maint, Jun 19 2010, 18:42:45)
[GCC 4.4.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>> print dir(MySQLdb)
['BINARY', 'Binary', 'Connect', 'Connection', 'DATE', 'DATETIME', 'DBAPISet', 'DataError', 'DatabaseError', 'Date', 'DateFromTicks', 'Error', 'FIELD_TYPE', 'IntegrityError', 'InterfaceError', 'InternalError', 'MySQLError', 'NULL', 'NUMBER', 'NotSupportedError', 'OperationalError', 'ProgrammingError', 'ROWID', 'STRING', 'TIME', 'TIMESTAMP', 'Time', 'TimeFromTicks', 'Timestamp', 'TimestampFromTicks', 'Warning', '__all__', '__author__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__revision__', '__version__', '_mysql', 'apilevel', 'connect', 'connection', 'constants', 'debug', 'escape', 'escape_dict', 'escape_sequence', 'escape_string', 'get_client_info', 'paramstyle', 'release', 'result', 'server_end', 'server_init', 'string_literal', 'test_DBAPISet_set_equality', 'test_DBAPISet_set_equality_membership', 'test_DBAPISet_set_inequality', 'test_DBAPISet_set_inequality_membership', 'thread_safe', 'threadsafety', 'times', 'version_info']
| Mysql database Import Error in python | i have installed python 2.6.4. i have downloaded mysql database module. but i don't know where to place that module in python package. when i execute the program it shows import error "no module named mysql db". please tell me where to place the module.
| [
"it's case-sensitive, module name is 'MySQLdb'\nyed@rublan ~/skript $ python\nPython 2.6.5 (release26-maint, Jun 19 2010, 18:42:45) \n[GCC 4.4.4] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import MySQLdb\n>>> print dir(MySQLdb)\n['BINARY', 'Binary', 'Connect', 'Connection', 'DATE', 'DATETIME', 'DBAPISet', 'DataError', 'DatabaseError', 'Date', 'DateFromTicks', 'Error', 'FIELD_TYPE', 'IntegrityError', 'InterfaceError', 'InternalError', 'MySQLError', 'NULL', 'NUMBER', 'NotSupportedError', 'OperationalError', 'ProgrammingError', 'ROWID', 'STRING', 'TIME', 'TIMESTAMP', 'Time', 'TimeFromTicks', 'Timestamp', 'TimestampFromTicks', 'Warning', '__all__', '__author__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__revision__', '__version__', '_mysql', 'apilevel', 'connect', 'connection', 'constants', 'debug', 'escape', 'escape_dict', 'escape_sequence', 'escape_string', 'get_client_info', 'paramstyle', 'release', 'result', 'server_end', 'server_init', 'string_literal', 'test_DBAPISet_set_equality', 'test_DBAPISet_set_equality_membership', 'test_DBAPISet_set_inequality', 'test_DBAPISet_set_inequality_membership', 'thread_safe', 'threadsafety', 'times', 'version_info']\n\n"
] | [
3
] | [] | [] | [
"installation",
"mysql",
"python"
] | stackoverflow_0003102528_installation_mysql_python.txt |
Q:
Controlling Music and Video in Python
I'm trying to write a karaoke program in python. Every karaoke software has basic functionality like seeking in the video as well as modulating the pitch of music by half steps. What are some modules that I can use to permit this functionality?
I'm going to use wxPython to write the gui portion if that makes a difference!
A:
Honestly you might want to take a look at PyGame - it has fairly robust libraries for handling stuff like music and movies: http://www.pygame.org/docs/
A:
wxPython has a built in media controller, wx.MediaCtrl, which can play both audio and video. It has most of the basic functionality built in, like seek, pause, etc. I've found it very easy and reliable.
| Controlling Music and Video in Python | I'm trying to write a karaoke program in python. Every karaoke software has basic functionality like seeking in the video as well as modulating the pitch of music by half steps. What are some modules that I can use to permit this functionality?
I'm going to use wxPython to write the gui portion if that makes a difference!
| [
"Honestly you might want to take a look at PyGame - it has fairly robust libraries for handling stuff like music and movies: http://www.pygame.org/docs/\n",
"wxPython has a built in media controller, wx.MediaCtrl, which can play both audio and video. It has most of the basic functionality built in, like seek, pause, etc. I've found it very easy and reliable.\n"
] | [
2,
0
] | [] | [] | [
"python",
"video",
"wxpython"
] | stackoverflow_0003100976_python_video_wxpython.txt |
Q:
sound way to feed commands to twisted ssh after reactor.run()
Guys this is a question about python twisted ssh lib.
All sample code even production code I saw acting as a ssh client based on twisted.conch.ssh are all interacting with server in such a mode:
prepare some commands to run remotely;
define call backs;
kick off reactor then suspend for new feedback;
After the reactor.run(), I never found people tried to deliver commands to sshd, the script just sit their waiting. I think it'll be possible to fork or spawn stuffs to send commands. However since one of twisted's strengths is its de-multiplexing mechanism so it doesn't have to fork to process incoming requests when running as a server. May I say it is a reasonable requirement not to fork (as a client script) to continuously send requests to server?
Any thought on this ?
TIA.
A:
joefis' answer is basically sound, but I bet some examples would be helpful. First, there are a few ways you can have some code run right after the reactor starts.
This one is pretty straightforward:
def f():
print "the reactor is running now"
reactor.callWhenRunning(f)
Another way is to use timed events, although there's probably no reason to do it this way instead of using callWhenRunning:
reactor.callLater(0, f)
You can also use the underlying API which callWhenRunning is implemented in terms of:
reactor.addSystemEventTrigger('after', 'startup', f)
You can also use services. This is a bit more involved, since it involves using using twistd(1) (or something else that's going to hook the service system up to the reactor). But you can write a class like this:
from twisted.application.service import Service
class ThingDoer(Service):
def startService(self):
print "The reactor is running now."
And then write a .tac file like this:
from twisted.application.service import Application
from thatmodule import ThingDoer
application = Application("Do Things")
ThingDoer().setServiceParent(application)
And finally, you can run this .tac file using twistd(1):
$ twistd -ny thatfile.tac
Of course, this only tells you how to do one thing after the reactor is running, which isn't exactly what you're asking. It's the same idea, though - you define some event handler and ask to receive an event by having that handler called; when it is called, you get to do stuff. The same idea applies to anything you do with Conch.
You can see this in the Conch examples, for example in sshsimpleclient.py we have:
class CatChannel(channel.SSHChannel):
name = 'session'
def openFailed(self, reason):
print 'echo failed', reason
def channelOpen(self, ignoredData):
self.data = ''
d = self.conn.sendRequest(self, 'exec', common.NS('cat'), wantReply = 1)
d.addCallback(self._cbRequest)
def _cbRequest(self, ignored):
self.write('hello conch\n')
self.conn.sendEOF(self)
def dataReceived(self, data):
self.data += data
def closed(self):
print 'got data from cat: %s' % repr(self.data)
self.loseConnection()
reactor.stop()
In this example, channelOpen is the event handler called when a new channel is opened. It sends a request to the server. It gets back a Deferred, to which it attaches a callback. That callback is an event handler which will be called when the request succeeds (in this case, when cat has been executed). _cbRequest is the callback it attaches, and that method takes the next step - writing some bytes to the channel and then closing it. Then there's the dataReceived event handler, which is called when bytes are received over the chnanel, and the closed event handler, called when the channel is closed.
So you can see four different event handlers here, some of which are starting operations that will eventually trigger a later event handler.
So to get back to your question about doing one thing after another, if you wanted to open two cat channels, one after the other, then in the closed event handler could open a new channel (instead of stopping the reactor as it does in this example).
A:
You're trying to put a square peg in a round hole. Everything in Twisted is asynchronous, so you have to think about the sequence of events differently. You can't say "here are 10 operations to be run one after the other" that's serial thinking.
In Twisted you issue the first command and register a callback that will be triggered when it completes. When that callback occurs you issue the 2nd command and register a callback that will be triggered when that completes. And so on and so on.
| sound way to feed commands to twisted ssh after reactor.run() | Guys this is a question about python twisted ssh lib.
All sample code even production code I saw acting as a ssh client based on twisted.conch.ssh are all interacting with server in such a mode:
prepare some commands to run remotely;
define call backs;
kick off reactor then suspend for new feedback;
After the reactor.run(), I never found people tried to deliver commands to sshd, the script just sit their waiting. I think it'll be possible to fork or spawn stuffs to send commands. However since one of twisted's strengths is its de-multiplexing mechanism so it doesn't have to fork to process incoming requests when running as a server. May I say it is a reasonable requirement not to fork (as a client script) to continuously send requests to server?
Any thought on this ?
TIA.
| [
"joefis' answer is basically sound, but I bet some examples would be helpful. First, there are a few ways you can have some code run right after the reactor starts.\nThis one is pretty straightforward:\ndef f():\n print \"the reactor is running now\"\n\nreactor.callWhenRunning(f)\n\nAnother way is to use timed events, although there's probably no reason to do it this way instead of using callWhenRunning:\nreactor.callLater(0, f)\n\nYou can also use the underlying API which callWhenRunning is implemented in terms of:\nreactor.addSystemEventTrigger('after', 'startup', f)\n\nYou can also use services. This is a bit more involved, since it involves using using twistd(1) (or something else that's going to hook the service system up to the reactor). But you can write a class like this:\nfrom twisted.application.service import Service\n\nclass ThingDoer(Service):\n def startService(self):\n print \"The reactor is running now.\"\n\nAnd then write a .tac file like this:\nfrom twisted.application.service import Application\n\nfrom thatmodule import ThingDoer\n\napplication = Application(\"Do Things\")\nThingDoer().setServiceParent(application)\n\nAnd finally, you can run this .tac file using twistd(1):\n$ twistd -ny thatfile.tac\n\nOf course, this only tells you how to do one thing after the reactor is running, which isn't exactly what you're asking. It's the same idea, though - you define some event handler and ask to receive an event by having that handler called; when it is called, you get to do stuff. The same idea applies to anything you do with Conch.\nYou can see this in the Conch examples, for example in sshsimpleclient.py we have:\nclass CatChannel(channel.SSHChannel):\n name = 'session'\n\n def openFailed(self, reason):\n print 'echo failed', reason\n\n def channelOpen(self, ignoredData):\n self.data = ''\n d = self.conn.sendRequest(self, 'exec', common.NS('cat'), wantReply = 1)\n d.addCallback(self._cbRequest) \n\n def _cbRequest(self, ignored):\n self.write('hello conch\\n')\n self.conn.sendEOF(self)\n\n def dataReceived(self, data):\n self.data += data\n\n def closed(self):\n print 'got data from cat: %s' % repr(self.data)\n self.loseConnection()\n reactor.stop()\n\nIn this example, channelOpen is the event handler called when a new channel is opened. It sends a request to the server. It gets back a Deferred, to which it attaches a callback. That callback is an event handler which will be called when the request succeeds (in this case, when cat has been executed). _cbRequest is the callback it attaches, and that method takes the next step - writing some bytes to the channel and then closing it. Then there's the dataReceived event handler, which is called when bytes are received over the chnanel, and the closed event handler, called when the channel is closed.\nSo you can see four different event handlers here, some of which are starting operations that will eventually trigger a later event handler.\nSo to get back to your question about doing one thing after another, if you wanted to open two cat channels, one after the other, then in the closed event handler could open a new channel (instead of stopping the reactor as it does in this example).\n",
"You're trying to put a square peg in a round hole. Everything in Twisted is asynchronous, so you have to think about the sequence of events differently. You can't say \"here are 10 operations to be run one after the other\" that's serial thinking.\nIn Twisted you issue the first command and register a callback that will be triggered when it completes. When that callback occurs you issue the 2nd command and register a callback that will be triggered when that completes. And so on and so on.\n"
] | [
4,
0
] | [] | [] | [
"python",
"ssh",
"twisted"
] | stackoverflow_0003102098_python_ssh_twisted.txt |
Q:
Use latin characters in appengine
How can store latin characters in appengine? (e.g. "peña") when I want to store this I get this error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in position 2: ordinal not in range(128)
I can change the Ñ by N, but, there not another and better way?
And if i encode the value, how can print "Peña" again?
A:
GAE stores strings in unicode. Perhaps encode your string in unicode before saving it.
value = "peña"
value.encode("utf8")
A:
From the error ("Unicode Decode Error"), it seems you could have more luck using Unicode - I'd try UTF-8.
| Use latin characters in appengine | How can store latin characters in appengine? (e.g. "peña") when I want to store this I get this error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in position 2: ordinal not in range(128)
I can change the Ñ by N, but, there not another and better way?
And if i encode the value, how can print "Peña" again?
| [
"GAE stores strings in unicode. Perhaps encode your string in unicode before saving it.\nvalue = \"peña\"\n\nvalue.encode(\"utf8\")\n\n",
"From the error (\"Unicode Decode Error\"), it seems you could have more luck using Unicode - I'd try UTF-8.\n"
] | [
2,
0
] | [] | [] | [
"google_app_engine",
"latin1",
"python",
"string"
] | stackoverflow_0003102856_google_app_engine_latin1_python_string.txt |
Q:
Why are Google API queries through simplejson returning "responseData": null?
I'm trying to screenscrape the first result of a Google search using Python and simplejson, but I can't access the search results the way that many examples online demonstrate. Here's a snippet:
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % (query)
search_results = urllib.urlopen(url)
json = simplejson.load(search_results)
try:
results = json['responseData']['results'] # always fails at this line
first_result = results[0]
except:
print "attempt to set results failed"
When I go to http://ajax.googleapis.com/ajax/services/search/web?v=1.0&stackoverflow (or anything else substituted for the %s) in a browser, it displays the line "{"responseData": null, "responseDetails": "clip sweeping", "responseStatus": 204}." Is there some other way to access the results of a Google search in Python besides trying to use the apparently empty responseData?
A:
You missed the &q=. You also should consider using an api-key. http://code.google.com/intl/de/apis/ajaxsearch/documentation/. Besides that plain string contaction wont work, you need to escape the parameter.
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q= ' + urllib.quote_plus(query)
| Why are Google API queries through simplejson returning "responseData": null? | I'm trying to screenscrape the first result of a Google search using Python and simplejson, but I can't access the search results the way that many examples online demonstrate. Here's a snippet:
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % (query)
search_results = urllib.urlopen(url)
json = simplejson.load(search_results)
try:
results = json['responseData']['results'] # always fails at this line
first_result = results[0]
except:
print "attempt to set results failed"
When I go to http://ajax.googleapis.com/ajax/services/search/web?v=1.0&stackoverflow (or anything else substituted for the %s) in a browser, it displays the line "{"responseData": null, "responseDetails": "clip sweeping", "responseStatus": 204}." Is there some other way to access the results of a Google search in Python besides trying to use the apparently empty responseData?
| [
"You missed the &q=. You also should consider using an api-key. http://code.google.com/intl/de/apis/ajaxsearch/documentation/. Besides that plain string contaction wont work, you need to escape the parameter. \n url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q= ' + urllib.quote_plus(query)\n\n"
] | [
2
] | [] | [] | [
"ajax",
"google_search_api",
"python",
"simplejson"
] | stackoverflow_0003103116_ajax_google_search_api_python_simplejson.txt |
Q:
not getting output from parmiko/ssh command
I am using paramiko/ssh/python to attempt to run a command on a remote server. When I ssh manually and run the command in question, I get the results I want. But if I use the python (co-opted from another thread on this site) below, there is no returned data. If I modify the command to be something more basic like 'pwd' or 'ls' I can then get the output. Any help is appreciated.
Thanks,
Matt
import paramiko
import time
import sys, os, select
import select
hostname='10.15.27.166'
hostport=22
cmd='tail -f /x/web/mlog.txt' #works
#cmd='customexe -args1 -args2' #doesn't work
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect(hostname=hostname, username=username, password=password)
transport = client.get_transport()
channel = transport.open_session()
channel.exec_command(cmd)
while True:
rl, wl, xl = select.select([channel],[],[],0.0)
if len(rl) > 0:
# Must be stdout
print channel.recv(1024)
time.sleep(1)
A:
I found a fix, though not necessarily the root cause: When paramiko created the ssh connection, it did not run my bash_profile in my home directory on the remote server. So, I copied the commands from the bash_profile into the cmd variable and thus loaded various environment variables that I thought would have loaded automatically. Then the command "customexe ..." returned output as expected.
| not getting output from parmiko/ssh command | I am using paramiko/ssh/python to attempt to run a command on a remote server. When I ssh manually and run the command in question, I get the results I want. But if I use the python (co-opted from another thread on this site) below, there is no returned data. If I modify the command to be something more basic like 'pwd' or 'ls' I can then get the output. Any help is appreciated.
Thanks,
Matt
import paramiko
import time
import sys, os, select
import select
hostname='10.15.27.166'
hostport=22
cmd='tail -f /x/web/mlog.txt' #works
#cmd='customexe -args1 -args2' #doesn't work
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect(hostname=hostname, username=username, password=password)
transport = client.get_transport()
channel = transport.open_session()
channel.exec_command(cmd)
while True:
rl, wl, xl = select.select([channel],[],[],0.0)
if len(rl) > 0:
# Must be stdout
print channel.recv(1024)
time.sleep(1)
| [
"I found a fix, though not necessarily the root cause: When paramiko created the ssh connection, it did not run my bash_profile in my home directory on the remote server. So, I copied the commands from the bash_profile into the cmd variable and thus loaded various environment variables that I thought would have loaded automatically. Then the command \"customexe ...\" returned output as expected.\n"
] | [
1
] | [] | [] | [
"paramiko",
"python",
"ssh"
] | stackoverflow_0003049134_paramiko_python_ssh.txt |
Q:
How does this Python decorator work?
I was looking at some lazy loading property decorators in Python and happened across this example (http://code.activestate.com/recipes/363602-lazy-property-evaluation/):
class Lazy(object):
def __init__(self, calculate_function):
self._calculate = calculate_function
def __get__(self, obj, _=None):
if obj is None:
return self
value = self._calculate(obj)
setattr(obj, self._calculate.func_name, value)
return value
# Sample use:
class SomeClass(object):
@Lazy
def someprop(self):
print 'Actually calculating value'
return 13
o = SomeClass()
o.someprop
o.someprop
My question is, how does this work? My understanding of decorators is that they must be callable (so either a function or a call that implements __call__), but Lazy here clearly is not and if I try Lazy(someFunc)() it raises an exception as expected. What am I missing?
A:
When an attribute named someprop is accessed on instance o of class SomeClass, if SomeClass contains a descriptor named o, then that descriptor's class's __get__ method is used. For more on descriptors, see this guide. Don't let the fact that Lazy is here used, syntactically, as a decorator, blind you to the fact that its instances are descriptors, because Lazy itself has a __get__ method.
The decorator syntax
@Lazy
def someprop(self):
...
is no more, and no less, than syntax sugar for:
def someprop(self):
...
someprop = Lazy(someprop)
The constraints on Lazy are no different when it's used with decorator syntax or directly: it must accept someprop (a function) as its argument -- no constraints whatsoever on what it returns. Here, Lazy is a class so it returns an instance of itself, and has a __get__ special method so that instance is a descriptor (so said method gets called when the someprop attribute is accessed on the instance o of class SomeClass) -- that's all there is to it, no more, and no less.
| How does this Python decorator work? | I was looking at some lazy loading property decorators in Python and happened across this example (http://code.activestate.com/recipes/363602-lazy-property-evaluation/):
class Lazy(object):
def __init__(self, calculate_function):
self._calculate = calculate_function
def __get__(self, obj, _=None):
if obj is None:
return self
value = self._calculate(obj)
setattr(obj, self._calculate.func_name, value)
return value
# Sample use:
class SomeClass(object):
@Lazy
def someprop(self):
print 'Actually calculating value'
return 13
o = SomeClass()
o.someprop
o.someprop
My question is, how does this work? My understanding of decorators is that they must be callable (so either a function or a call that implements __call__), but Lazy here clearly is not and if I try Lazy(someFunc)() it raises an exception as expected. What am I missing?
| [
"When an attribute named someprop is accessed on instance o of class SomeClass, if SomeClass contains a descriptor named o, then that descriptor's class's __get__ method is used. For more on descriptors, see this guide. Don't let the fact that Lazy is here used, syntactically, as a decorator, blind you to the fact that its instances are descriptors, because Lazy itself has a __get__ method.\nThe decorator syntax\n @Lazy\n def someprop(self):\n ...\n\nis no more, and no less, than syntax sugar for:\n def someprop(self):\n ...\n someprop = Lazy(someprop)\n\nThe constraints on Lazy are no different when it's used with decorator syntax or directly: it must accept someprop (a function) as its argument -- no constraints whatsoever on what it returns. Here, Lazy is a class so it returns an instance of itself, and has a __get__ special method so that instance is a descriptor (so said method gets called when the someprop attribute is accessed on the instance o of class SomeClass) -- that's all there is to it, no more, and no less.\n"
] | [
8
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0003103463_decorator_python.txt |
Q:
What is the Python equivalent of java.util.zip.Inflater?
I have a Java program that opens a socket connection to a server that streams Zip compressed data. I read(bytebuffer) from the stream, setInput(bytebuffer) on the zip object, and inflate(outputbuffer) to get my uncompressed data.
What would be the equivalent in python?
Here is the java code:
byte[] compressedBytes = new byte[1024];
int bytesRead = inputStream.read(compressedBytes);
zip.setInput(compressedBytes, 0, bytesRead);
zip.inflate(uncompressedBytes, 0, 1024);
Or, to summarize, I need a streaming inflate (not file based) zip option for python.
A:
Have a look at zlib.decompressobj(). I think that should give you what you want. See http://docs.python.org/library/zlib.html
A:
You're looking for the zlib module. java.util.zip is actually an implementation using zlib, not Zip(aka PKZIP).
| What is the Python equivalent of java.util.zip.Inflater? | I have a Java program that opens a socket connection to a server that streams Zip compressed data. I read(bytebuffer) from the stream, setInput(bytebuffer) on the zip object, and inflate(outputbuffer) to get my uncompressed data.
What would be the equivalent in python?
Here is the java code:
byte[] compressedBytes = new byte[1024];
int bytesRead = inputStream.read(compressedBytes);
zip.setInput(compressedBytes, 0, bytesRead);
zip.inflate(uncompressedBytes, 0, 1024);
Or, to summarize, I need a streaming inflate (not file based) zip option for python.
| [
"Have a look at zlib.decompressobj(). I think that should give you what you want. See http://docs.python.org/library/zlib.html\n",
"You're looking for the zlib module. java.util.zip is actually an implementation using zlib, not Zip(aka PKZIP).\n"
] | [
1,
1
] | [] | [] | [
"python",
"zip"
] | stackoverflow_0003103719_python_zip.txt |
Q:
Does ctypes provide anything for enums and flags?
I have an API I'd like to use from python. That API contains flags and enums implemented with #define.
// it's just almost C so don't bother adding the typedef and parenthesis diarrhea here.
routine(API_SOMETHING | API_OTHERTHING)
stuff = getflags()
? stuff & API_SOMETHING
action(API_INTERESTING)
mode = getaction()
? mode == INTERESTING
If ignoring everything else except enums and flags now, my bindings should translate this to:
routine(["something", "otherthing"])
stuff = getflags()
if 'something' in stuff
action('interesting')
mode = getaction()
if mode == 'interesting'
Does ctypes provide mechanisms to do this straight out? If not then just tell about your 'usual' tool for handling flags and enums in python bindings.
A:
Why don't you use c_uint for the enum parameter and then use a mapping like this (enums are usually unsigned integer values):
in C:
typedef enum {
MY_VAR = 1,
MY_OTHERVAR = 2
} my_enum_t;
and in Python:
class MyEnum():
__slots__ = ('MY_VAR', 'MY_OTHERVAR')
MY_VAR = 1
MY_OTHERVAR = 2
myfunc.argtypes = [c_uint, ...]
You can then pass MyEnum fields to the function.
If you want a string representation for the enumerated values, you can use a dictionary in the MyEnum class.
A:
I'm a bit disappointed to answer to this question myself. Especially since I found it all from the f* manual.
http://docs.python.org/library/ctypes.html#calling-functions-with-your-own-custom-data-types
To complete my answer, I'll write some code that does wrap an item.
from ctypes import CDLL, c_uint, c_char_p
class Flag(object):
flags = [(0x1, 'fun'), (0x2, 'toy')]
@classmethod
def from_param(cls, data):
return c_uint(encode_flags(self.flags, data))
libc = CDLL('libc.so.6')
printf = libc.printf
printf.argtypes = [c_char_p, Flag]
printf("hello %d\n", ["fun", "toy"])
encode_flags transforms that nifty list into an integer.
| Does ctypes provide anything for enums and flags? | I have an API I'd like to use from python. That API contains flags and enums implemented with #define.
// it's just almost C so don't bother adding the typedef and parenthesis diarrhea here.
routine(API_SOMETHING | API_OTHERTHING)
stuff = getflags()
? stuff & API_SOMETHING
action(API_INTERESTING)
mode = getaction()
? mode == INTERESTING
If ignoring everything else except enums and flags now, my bindings should translate this to:
routine(["something", "otherthing"])
stuff = getflags()
if 'something' in stuff
action('interesting')
mode = getaction()
if mode == 'interesting'
Does ctypes provide mechanisms to do this straight out? If not then just tell about your 'usual' tool for handling flags and enums in python bindings.
| [
"Why don't you use c_uint for the enum parameter and then use a mapping like this (enums are usually unsigned integer values):\nin C:\ntypedef enum {\n MY_VAR = 1,\n MY_OTHERVAR = 2\n} my_enum_t;\n\nand in Python:\nclass MyEnum():\n __slots__ = ('MY_VAR', 'MY_OTHERVAR')\n\n MY_VAR = 1\n MY_OTHERVAR = 2\n\n\nmyfunc.argtypes = [c_uint, ...]\n\nYou can then pass MyEnum fields to the function.\nIf you want a string representation for the enumerated values, you can use a dictionary in the MyEnum class.\n",
"I'm a bit disappointed to answer to this question myself. Especially since I found it all from the f* manual.\nhttp://docs.python.org/library/ctypes.html#calling-functions-with-your-own-custom-data-types\nTo complete my answer, I'll write some code that does wrap an item.\nfrom ctypes import CDLL, c_uint, c_char_p\n\nclass Flag(object):\n flags = [(0x1, 'fun'), (0x2, 'toy')]\n @classmethod\n def from_param(cls, data):\n return c_uint(encode_flags(self.flags, data))\n\nlibc = CDLL('libc.so.6')\nprintf = libc.printf\nprintf.argtypes = [c_char_p, Flag]\n\nprintf(\"hello %d\\n\", [\"fun\", \"toy\"])\n\nencode_flags transforms that nifty list into an integer.\n"
] | [
3,
3
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003100704_ctypes_python.txt |
Q:
How do I install .pl plugins for nagios?
I am trying to install the "check_mssql_sproc.pl" plug in for nagios. Where and how do I install it?
A:
Add the command definition to your nagios/etc/objects/commands.cfg
Where the pl file is actually installed doesnt matter... just make sure you can run it from the command line and set it up like that in your commands.cfg
| How do I install .pl plugins for nagios? | I am trying to install the "check_mssql_sproc.pl" plug in for nagios. Where and how do I install it?
| [
"Add the command definition to your nagios/etc/objects/commands.cfg\nWhere the pl file is actually installed doesnt matter... just make sure you can run it from the command line and set it up like that in your commands.cfg\n"
] | [
3
] | [] | [] | [
"nagios",
"plugins",
"python"
] | stackoverflow_0003104267_nagios_plugins_python.txt |
Q:
What is the space complexity of HashTable, Array, ArrayList, LinkedList etc(if anything more)
I want to know the space complexities of the basic data structures in popular languages.
A:
All of these have space complexity O(n). All that changes is the coefficient, and that is completely dependent on the implementation. Especially when you start getting into things like pre-allocating space to reduce time complexity.
For instance, array list structures generally pre-allocate extra space. Therefore, their exact complexity for a number of objects is actually a range which is completely dependent on implementation and how they were created and used. For instance, if I write an array list that always allocates three extra spaces whenever more space is necessary, and always deallocates down to three open spaces when there's more than 5 open spaces, then actual complexity for n will be [n, n + 5] + overhead.
The big differences in choosing between these items when programming is usually ease-of-use and how well it fits with how you will be using it. For example, linked lists are horrible for random access, but great at iteration.
A:
For Java: (Aproximates)
Memory O(x) | General Case
Array | n | n
ArrayList | n | 2 * n
LinkedList| n | n * (node size)
HashTable | n | ~n
Map | n | (n * key_size) + n
A:
Virtually all data structures with a non-trivial size are on the ORDER of n.
Array = exactly n
ArrayList = betweenn and k*n (default k=2)
LinkedList = exactly n
HashTable = worst is n/k (default k is .75)
| What is the space complexity of HashTable, Array, ArrayList, LinkedList etc(if anything more) | I want to know the space complexities of the basic data structures in popular languages.
| [
"All of these have space complexity O(n). All that changes is the coefficient, and that is completely dependent on the implementation. Especially when you start getting into things like pre-allocating space to reduce time complexity.\nFor instance, array list structures generally pre-allocate extra space. Therefore, their exact complexity for a number of objects is actually a range which is completely dependent on implementation and how they were created and used. For instance, if I write an array list that always allocates three extra spaces whenever more space is necessary, and always deallocates down to three open spaces when there's more than 5 open spaces, then actual complexity for n will be [n, n + 5] + overhead.\nThe big differences in choosing between these items when programming is usually ease-of-use and how well it fits with how you will be using it. For example, linked lists are horrible for random access, but great at iteration.\n",
"For Java: (Aproximates)\n\n Memory O(x) | General Case\nArray | n | n\nArrayList | n | 2 * n\nLinkedList| n | n * (node size)\nHashTable | n | ~n\nMap | n | (n * key_size) + n\n\n",
"Virtually all data structures with a non-trivial size are on the ORDER of n.\n\nArray = exactly n \nArrayList = betweenn and k*n (default k=2) \nLinkedList = exactly n \nHashTable = worst is n/k (default k is .75)\n\n"
] | [
3,
2,
1
] | [] | [] | [
"c#",
"c++",
"java",
"javascript",
"python"
] | stackoverflow_0003104281_c#_c++_java_javascript_python.txt |
Q:
Getting a WxPython panel item to expand
I have a WxPython frame containing a single item, such as:
class Panel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.text = wx.StaticText(self, label='Panel 1')
I have a frame containing several panels, including this one, and dimensions are ruled by sizers.
I would like this StaticText to expand.
Using a BoxSizer containing just the text and setting the wx.EXPAND flag does the trick, but it seems silly to use a sizer just for one item.
Any simpler solution?
(I could just add the StaticText to the parent frame's sizer directly, but for my design it makes more sense to start with a frame directly.)
I just realized that when creating a BoxSizer with one item doesn't work with wx.VERTICAL:
class Panel1(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.BackgroundColour = 'red'
sizer = wx.BoxSizer(wx.VERTICAL)
self.Sizer = sizer
self.list = wx.ListBox(self, choices=[str(i) for i in xrange(100)])
sizer.Add(self.list, 0, wx.EXPAND)
sizer.Fit(self)
Of course it's ok with one item, but what if I want to add an item vertically later and still make both of them expand (e.g. when the user's window is expanded)?
Edit: ah, I just found out that proportion must be used in order to make boxsizers grow in both ways. (i.e., replace 0 with 1 in BoxSizer.Add's call.)
A:
A wx.Frame will automatically do this if it only has one child. However, a wx.Panel will not do this automatically. You're stuck using a sizer. If you find yourself doing it a lot, just make a convenience function:
def expanded(widget, padding=0):
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(widget, 1, wx.EXPAND|wx.ALL, padding)
return sizer
class Panel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.text = wx.StaticText(self, label='Panel 1')
self.SetSizer(expanded(self.text))
I threw the padding attribute in there as an extra bonus. Feel free to use it or ditch it.
| Getting a WxPython panel item to expand | I have a WxPython frame containing a single item, such as:
class Panel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.text = wx.StaticText(self, label='Panel 1')
I have a frame containing several panels, including this one, and dimensions are ruled by sizers.
I would like this StaticText to expand.
Using a BoxSizer containing just the text and setting the wx.EXPAND flag does the trick, but it seems silly to use a sizer just for one item.
Any simpler solution?
(I could just add the StaticText to the parent frame's sizer directly, but for my design it makes more sense to start with a frame directly.)
I just realized that when creating a BoxSizer with one item doesn't work with wx.VERTICAL:
class Panel1(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.BackgroundColour = 'red'
sizer = wx.BoxSizer(wx.VERTICAL)
self.Sizer = sizer
self.list = wx.ListBox(self, choices=[str(i) for i in xrange(100)])
sizer.Add(self.list, 0, wx.EXPAND)
sizer.Fit(self)
Of course it's ok with one item, but what if I want to add an item vertically later and still make both of them expand (e.g. when the user's window is expanded)?
Edit: ah, I just found out that proportion must be used in order to make boxsizers grow in both ways. (i.e., replace 0 with 1 in BoxSizer.Add's call.)
| [
"A wx.Frame will automatically do this if it only has one child. However, a wx.Panel will not do this automatically. You're stuck using a sizer. If you find yourself doing it a lot, just make a convenience function:\ndef expanded(widget, padding=0):\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(widget, 1, wx.EXPAND|wx.ALL, padding)\n return sizer\n\nclass Panel(wx.Panel):\n def __init__(self, parent):\n wx.Panel.__init__(self, parent)\n self.text = wx.StaticText(self, label='Panel 1')\n self.SetSizer(expanded(self.text))\n\nI threw the padding attribute in there as an extra bonus. Feel free to use it or ditch it.\n"
] | [
8
] | [] | [] | [
"frame",
"python",
"sizer",
"wxpython"
] | stackoverflow_0003104323_frame_python_sizer_wxpython.txt |
Q:
Selecting data from Google App Engine datastore by field value
I'm just staring off with GAE. So like many I'm used to standard SQL.
Typically when you want to select data that has a certain field value you use:
SELECT <columns> FROM <table> WHERE <column> = <wanted value>
Is the correct way to do this in GAE
<Model Class>.all().filter('<column> =', <wanted value>)
Or is there a more efficient way?
EDIT: Also I should note in this particular case I only want one result returned. So is there another command so that it doesn't keep looking after if finds a result?
A:
Your code is pretty close to what you're looking for - it constructs a Query object which can be used to query the datastore. To actually get a result, you'll need to execute the query. To get a single result, you'll want to use the get() method:
result = <Model Class>.all().filter('<column> =', <wanted value>).get()
A:
You probably want Model.gql('where column = :value', value=something) which returns a GqlQuery upon which a GqlQuery.get() returns a single item.
| Selecting data from Google App Engine datastore by field value | I'm just staring off with GAE. So like many I'm used to standard SQL.
Typically when you want to select data that has a certain field value you use:
SELECT <columns> FROM <table> WHERE <column> = <wanted value>
Is the correct way to do this in GAE
<Model Class>.all().filter('<column> =', <wanted value>)
Or is there a more efficient way?
EDIT: Also I should note in this particular case I only want one result returned. So is there another command so that it doesn't keep looking after if finds a result?
| [
"Your code is pretty close to what you're looking for - it constructs a Query object which can be used to query the datastore. To actually get a result, you'll need to execute the query. To get a single result, you'll want to use the get() method:\nresult = <Model Class>.all().filter('<column> =', <wanted value>).get()\n\n",
"You probably want Model.gql('where column = :value', value=something) which returns a GqlQuery upon which a GqlQuery.get() returns a single item.\n"
] | [
6,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003104400_google_app_engine_python.txt |
Q:
Python/django inherit from 2 classes
In my django project I have 2 variations of users. One subclasses User class from django.auth and second uses almost the same fields but is not a real user (so it doesn't inherit from User). Is there a way to create a FieldUser class (that stores fields only) and for RealUser subclass both FieldUser and User, but for FakeUser subclass only FieldUser ?
A:
sure, I've used multiple inheritance in django models, it works fine.
sounds like you want to setup an abstract class for FieldUser:
class FieldUser(models.Model):
field1 = models.IntegerField()
field2 = models.CharField() #etc
class Meta:
abstract=True #abstract class does not create a db table
class RealUser(FieldUser, auth.User):
pass #abstract nature is not inherited, will create its own table to go with the user table
class FakeUser(FieldUser):
pass #again, will create its own table
| Python/django inherit from 2 classes | In my django project I have 2 variations of users. One subclasses User class from django.auth and second uses almost the same fields but is not a real user (so it doesn't inherit from User). Is there a way to create a FieldUser class (that stores fields only) and for RealUser subclass both FieldUser and User, but for FakeUser subclass only FieldUser ?
| [
"sure, I've used multiple inheritance in django models, it works fine.\nsounds like you want to setup an abstract class for FieldUser:\nclass FieldUser(models.Model):\n field1 = models.IntegerField()\n field2 = models.CharField() #etc\n class Meta:\n abstract=True #abstract class does not create a db table\n\nclass RealUser(FieldUser, auth.User):\n pass #abstract nature is not inherited, will create its own table to go with the user table\n\nclass FakeUser(FieldUser):\n pass #again, will create its own table\n\n"
] | [
4
] | [] | [] | [
"django",
"django_users",
"python"
] | stackoverflow_0003104463_django_django_users_python.txt |
Q:
google-app-engine full-text-search ,which is better , "google custom search" or whoosh
this is whoosh
so ,did you know which is better ?
thanks
A:
Google Custom Search Engine won't search over your models unless they are published fairly completely on a page which Google has crawled and indexed. Think of CSE as a very configurable search engine over existing Google search results.
Whoosh appears to be a better fit if you want to search over models in your datastore. Another option for this functionality is Bill Katz's SearchableModel.
| google-app-engine full-text-search ,which is better , "google custom search" or whoosh | this is whoosh
so ,did you know which is better ?
thanks
| [
"Google Custom Search Engine won't search over your models unless they are published fairly completely on a page which Google has crawled and indexed. Think of CSE as a very configurable search engine over existing Google search results.\nWhoosh appears to be a better fit if you want to search over models in your datastore. Another option for this functionality is Bill Katz's SearchableModel.\n"
] | [
2
] | [] | [] | [
"full_text_search",
"google_app_engine",
"python",
"whoosh"
] | stackoverflow_0003104828_full_text_search_google_app_engine_python_whoosh.txt |
Q:
Concatenate tuples in empty dict
errors = {}
#errorexample
errors['id'] += ('error1',)
errors['id'] += ('error2',)
#works but ugly
errors['id'] = ('error1',)
errors['id'] += ('error2',)
If 'error1' is not present it will fail. Do I really have to extend dict?
A:
Use a collections.defaultdict instead of a plain dict -- this kind of convenience, after all, is exactly what the default-dict type was introduced for:
>>> import collections
>>> errors = collections.defaultdict(tuple)
>>> errors['id'] += ('error1',)
>>> errors['id'] += ('error2',)
>>> errors['id']
('error1', 'error2')
A:
import collections
errors = collections.defaultdict(tuple)
A:
>>> from collections import defaultdict
>>> errors = defaultdict (tuple)
>>> errors['id'] += ('blargh',)
>>> errors['id']
('blargh',)
| Concatenate tuples in empty dict | errors = {}
#errorexample
errors['id'] += ('error1',)
errors['id'] += ('error2',)
#works but ugly
errors['id'] = ('error1',)
errors['id'] += ('error2',)
If 'error1' is not present it will fail. Do I really have to extend dict?
| [
"Use a collections.defaultdict instead of a plain dict -- this kind of convenience, after all, is exactly what the default-dict type was introduced for:\n>>> import collections\n>>> errors = collections.defaultdict(tuple)\n>>> errors['id'] += ('error1',)\n>>> errors['id'] += ('error2',)\n>>> errors['id']\n('error1', 'error2')\n\n",
"import collections\nerrors = collections.defaultdict(tuple)\n\n",
">>> from collections import defaultdict\n>>> errors = defaultdict (tuple)\n>>> errors['id'] += ('blargh',)\n>>> errors['id']\n('blargh',)\n\n"
] | [
4,
3,
1
] | [] | [] | [
"dictionary",
"error_handling",
"list",
"python",
"tuples"
] | stackoverflow_0003105215_dictionary_error_handling_list_python_tuples.txt |
Q:
Using C++ from Python? (not boost)
I'm currently using boost-python to wrap a small C++ library and make it usable from Python. However, I'd like to stop using boost (mainly due to reasons relating to building/linking). So what other options are there?
Is there something that's equally convenient to use?
A:
There's Riverbank's SIP, Beazley's Swig, and Scott's/Dubois'/Furnish's Cxx. See also this page with other potentially relevant projects (but no direct answer to your immediate needs, I believe).
A:
Take a look at SWIG.
A:
Cython's syntax is very Pythonic, breaking the rules only where necessary.
| Using C++ from Python? (not boost) | I'm currently using boost-python to wrap a small C++ library and make it usable from Python. However, I'd like to stop using boost (mainly due to reasons relating to building/linking). So what other options are there?
Is there something that's equally convenient to use?
| [
"There's Riverbank's SIP, Beazley's Swig, and Scott's/Dubois'/Furnish's Cxx. See also this page with other potentially relevant projects (but no direct answer to your immediate needs, I believe).\n",
"Take a look at SWIG.\n",
"Cython's syntax is very Pythonic, breaking the rules only where necessary.\n"
] | [
2,
2,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0003105258_c++_python.txt |
Q:
Python: Printing Unicode to File
file = open('unicode.txt', 'wb')
for i in range(10):
file.write(str(unichr(i) ))
What i would like to do is to print all of the Unicode values to a text file
A:
somefile = codecs.open('unicode.txt', 'wb', someencoding)
for i in range(10):
somefile.write(unichr(i))
| Python: Printing Unicode to File | file = open('unicode.txt', 'wb')
for i in range(10):
file.write(str(unichr(i) ))
What i would like to do is to print all of the Unicode values to a text file
| [
"somefile = codecs.open('unicode.txt', 'wb', someencoding)\n\nfor i in range(10):\n somefile.write(unichr(i))\n\n"
] | [
2
] | [
"You shouldn't need the str() call around unichr(i). Python unicode objects are printable. \nThis:\nfile = open('unicode.txt', 'wb')\nfor i in range(10):\n file.write(unichr(i))\n\nSeems to work for me, it prints 0x0000, 0x0001, 0x0002, etc. to the text file. \n"
] | [
-1
] | [
"python",
"unicode"
] | stackoverflow_0003104983_python_unicode.txt |
Q:
index a list in a Python for loop
I'm making a for loop within a for loop. I'm looping through a list and finding a specific string that contains a regular expression pattern. Once I find the line, I need to search to find the next line of a certain pattern. I need to store both lines to be able to parse out the time for them. I've created a counter to keep track of the index number of the list as the outer for loop works. Can I use a construction like this to find the second line I need?
index = 0
for lineString in summaryList:
match10secExp = re.search('taking 10 sec. exposure', lineString)
if match10secExp:
startPlate = lineString
for line in summaryList[index:index+10]:
matchExposure = re.search('taking \d\d\d sec. exposure', line)
if matchExposure:
endPlate = line
break
index = index + 1
The code runs, but I'm not getting the result I'm looking for.
Thanks.
A:
matchExposure = re.search('taking \d\d\d sec. exposure', lineString)
should probably be
matchExposure = re.search('taking \d\d\d sec. exposure', line)
A:
Depending on your exact needs, you can just use an iterator on the list, or two of them as mae by itertools.tee. I.e., if you want to search lines following the first pattern only for the second pattern, a single iterator will do:
theiter = iter(thelist)
for aline in theiter:
if re.search(somestart, aline):
for another in theiter:
if re.search(someend, another):
yield aline, another # or print, whatever
break
This will not search lines from aline to the ending another for somestart, only for someend. If you need to search them for both purposes, i.e., leave theiter itself intact for the outer loop, that's where tee can help:
for aline in theiter:
if re.search(somestart, aline):
_, anotheriter = itertools.tee(iter(thelist))
for another in anotheriter:
if re.search(someend, another):
yield aline, another # or print, whatever
break
This is an exception to the general rule about tee which the docs give:
Once tee() has made a split, the
original iterable should not be used
anywhere else; otherwise, the iterable
could get advanced without the tee
objects being informed.
because the advancing of theiter and that of anotheriter occur in disjoint parts of the code, and anotheriter is always rebuilt afresh when needed (so the advancement of theiter in the meantime is not relevant).
| index a list in a Python for loop | I'm making a for loop within a for loop. I'm looping through a list and finding a specific string that contains a regular expression pattern. Once I find the line, I need to search to find the next line of a certain pattern. I need to store both lines to be able to parse out the time for them. I've created a counter to keep track of the index number of the list as the outer for loop works. Can I use a construction like this to find the second line I need?
index = 0
for lineString in summaryList:
match10secExp = re.search('taking 10 sec. exposure', lineString)
if match10secExp:
startPlate = lineString
for line in summaryList[index:index+10]:
matchExposure = re.search('taking \d\d\d sec. exposure', line)
if matchExposure:
endPlate = line
break
index = index + 1
The code runs, but I'm not getting the result I'm looking for.
Thanks.
| [
"matchExposure = re.search('taking \\d\\d\\d sec. exposure', lineString)\n\nshould probably be\nmatchExposure = re.search('taking \\d\\d\\d sec. exposure', line)\n\n",
"Depending on your exact needs, you can just use an iterator on the list, or two of them as mae by itertools.tee. I.e., if you want to search lines following the first pattern only for the second pattern, a single iterator will do:\ntheiter = iter(thelist)\n\nfor aline in theiter:\n if re.search(somestart, aline):\n for another in theiter:\n if re.search(someend, another):\n yield aline, another # or print, whatever\n break\n\nThis will not search lines from aline to the ending another for somestart, only for someend. If you need to search them for both purposes, i.e., leave theiter itself intact for the outer loop, that's where tee can help:\nfor aline in theiter:\n if re.search(somestart, aline):\n _, anotheriter = itertools.tee(iter(thelist))\n for another in anotheriter:\n if re.search(someend, another):\n yield aline, another # or print, whatever\n break\n\nThis is an exception to the general rule about tee which the docs give:\n\nOnce tee() has made a split, the\n original iterable should not be used\n anywhere else; otherwise, the iterable\n could get advanced without the tee\n objects being informed.\n\nbecause the advancing of theiter and that of anotheriter occur in disjoint parts of the code, and anotheriter is always rebuilt afresh when needed (so the advancement of theiter in the meantime is not relevant).\n"
] | [
1,
1
] | [] | [] | [
"nested_loops",
"python"
] | stackoverflow_0003105482_nested_loops_python.txt |
Q:
Running subversion under apache and mod_python
My Apache server runs on some non-default (not-root) account. When it tries to run a python script which in turn executes a subversion check-out command, 'svn checkout' fails with the following error message:
svn: Can't open file '/root/.subversion/servers': Permission denied
At the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well.
Apache server 2.2.6 with mod_python 3.2.8 runs on Fedora Core 6 machine.
Can anybody help me out? Thanks a lot.
A:
It sounds like the environment you apache process is running under is a little unusual. For whatever reason, svn seems to think the user configuration files it needs are in /root. You can avoid having svn use the root versions of the files by specifying on the command line which config directory to use, like so:
svn --config-dir /home/myuser/.subversion checkout http://example.com/path
While not fixing your enviornment, it will at least allow you to have your script run properly...
A:
Try granting the Apache user (the user that the apache service is running under) r+w permissions on that file.
A:
Doesn't Apache's error log give you a clue?
Maybe it has to do with SELinux. Check /var/log/audit/audit.log and adjust your SELinux configuration accordingly, if the audit.log file indicates that it's SELinux which denies Apache access.
A:
The Permission Denied error is showing that the script is running with root credentials, because it's looking in root's home dir for files.
I suggest you change the hook script to something that does:
id > /tmp/id
so that you can check the results of that to make sure what the uid/gid and euid/egid are. You will probably find it's not actually running as the user you think it is.
My first guess, like Troels, was also SELinux, but that would only be my guess if you are absolutely sure the script through Apache is running with exactly the same user/group as your manual test.
A:
Well, thanks to all who answered the question. Anyway, I think I solved the mistery.
SELinux is completely disabled on the machine, so the problem is definitely in 'svn co' not being able to found config_dir for the user account it runs under.
Apache / mod_python doesn't read in shell environment of the user account which apache is running on. Thus for examle no $HOME is seen by mod_python when apache
is running under some real user ( not nobody )
Now 'svn co' has a flag --config-dir which points to configuration directory to read params from. By default it is $HOME/.subversion, i.e. it corresponds to the user account home directory. Apparently when no $HOME exists mod_python goes to root home dir ( /root) and tries to fiddle with .subversion content over there - which is obviously
fails miserably.
putting
SetEnv HOME /home/qa
into the /etc/httpd/conf/httpd.conf doesn't solve the problem because of SetEnv having nothing to do with shell environment - it only sets apache related environment
Likewise PythonOption - sets only mod_python related variables which can be read with req.get_options() after that
Running 'svn co --config-dir /home/ ...' definitely gives a workaround for running from within mod_python, but gets in the way of those who will try to run the script from command line.
So the proposed ( and working) solution is to set HOME environment variable prior to starting appache.
For example in /etc/init.d/httpd script
QAHOME=/home/qa
...
HOME=$QAHOME LANG=$HTTPD_LANG daemon $httpd $OPTIONS
A:
What is happening is apache is being started with the environment variables of root, so it thinks that it should find its config files in /root/. This is NOT the case.
what happens is if you do sudo apache2ctl start, it pulls your $HOME variable from the sudo $HOME=/root/
I have just found a solution to this problem myself (although with mod_perl, but same thing)
run this command (if its apache 1, remove the 2):
sudo /etc/init.d/apache2 stop
sudo /etc/init.d/apache2 start
When /etc/init.d/apache2 starts apache, it sets all the proper environment variables that apache should be running under.
| Running subversion under apache and mod_python | My Apache server runs on some non-default (not-root) account. When it tries to run a python script which in turn executes a subversion check-out command, 'svn checkout' fails with the following error message:
svn: Can't open file '/root/.subversion/servers': Permission denied
At the same time running that python script with subversion checkout command inside from command line under the same user account goes on perfectly well.
Apache server 2.2.6 with mod_python 3.2.8 runs on Fedora Core 6 machine.
Can anybody help me out? Thanks a lot.
| [
"It sounds like the environment you apache process is running under is a little unusual. For whatever reason, svn seems to think the user configuration files it needs are in /root. You can avoid having svn use the root versions of the files by specifying on the command line which config directory to use, like so:\nsvn --config-dir /home/myuser/.subversion checkout http://example.com/path\n\nWhile not fixing your enviornment, it will at least allow you to have your script run properly...\n",
"Try granting the Apache user (the user that the apache service is running under) r+w permissions on that file.\n",
"Doesn't Apache's error log give you a clue?\nMaybe it has to do with SELinux. Check /var/log/audit/audit.log and adjust your SELinux configuration accordingly, if the audit.log file indicates that it's SELinux which denies Apache access.\n",
"The Permission Denied error is showing that the script is running with root credentials, because it's looking in root's home dir for files.\nI suggest you change the hook script to something that does:\nid > /tmp/id\n\nso that you can check the results of that to make sure what the uid/gid and euid/egid are. You will probably find it's not actually running as the user you think it is.\nMy first guess, like Troels, was also SELinux, but that would only be my guess if you are absolutely sure the script through Apache is running with exactly the same user/group as your manual test.\n",
"Well, thanks to all who answered the question. Anyway, I think I solved the mistery. \nSELinux is completely disabled on the machine, so the problem is definitely in 'svn co' not being able to found config_dir for the user account it runs under.\nApache / mod_python doesn't read in shell environment of the user account which apache is running on. Thus for examle no $HOME is seen by mod_python when apache \nis running under some real user ( not nobody ) \nNow 'svn co' has a flag --config-dir which points to configuration directory to read params from. By default it is $HOME/.subversion, i.e. it corresponds to the user account home directory. Apparently when no $HOME exists mod_python goes to root home dir ( /root) and tries to fiddle with .subversion content over there - which is obviously\nfails miserably.\nputting \nSetEnv HOME /home/qa \ninto the /etc/httpd/conf/httpd.conf doesn't solve the problem because of SetEnv having nothing to do with shell environment - it only sets apache related environment\nLikewise PythonOption - sets only mod_python related variables which can be read with req.get_options() after that\nRunning 'svn co --config-dir /home/ ...' definitely gives a workaround for running from within mod_python, but gets in the way of those who will try to run the script from command line.\nSo the proposed ( and working) solution is to set HOME environment variable prior to starting appache.\nFor example in /etc/init.d/httpd script \n QAHOME=/home/qa\n ...\n HOME=$QAHOME LANG=$HTTPD_LANG daemon $httpd $OPTIONS\n\n",
"What is happening is apache is being started with the environment variables of root, so it thinks that it should find its config files in /root/. This is NOT the case.\nwhat happens is if you do sudo apache2ctl start, it pulls your $HOME variable from the sudo $HOME=/root/\nI have just found a solution to this problem myself (although with mod_perl, but same thing)\nrun this command (if its apache 1, remove the 2):\nsudo /etc/init.d/apache2 stop\nsudo /etc/init.d/apache2 start\n\nWhen /etc/init.d/apache2 starts apache, it sets all the proper environment variables that apache should be running under.\n"
] | [
5,
0,
0,
0,
0,
0
] | [] | [] | [
"apache",
"python",
"svn"
] | stackoverflow_0000133860_apache_python_svn.txt |
Q:
Python: shutil.copytree , lack of ignore arg in python 2.5
Short of essentially rewriting copytree to accept an ignore callback, what is a simple way to achieve this in versions prior to python 2.6? (I don't want to stray from my debian packages)
A:
You can copy the source for copytree from the 2.6 tree, and put it into your project's source tree.
| Python: shutil.copytree , lack of ignore arg in python 2.5 | Short of essentially rewriting copytree to accept an ignore callback, what is a simple way to achieve this in versions prior to python 2.6? (I don't want to stray from my debian packages)
| [
"You can copy the source for copytree from the 2.6 tree, and put it into your project's source tree.\n"
] | [
0
] | [] | [] | [
"copytree",
"python",
"python_2.5",
"shutil"
] | stackoverflow_0003105747_copytree_python_python_2.5_shutil.txt |
Q:
Google App Engine/Python - Change logging formatting
How can one change the formatting of output from the logging module in Google App Engine?
I've tried, e.g.:
log_format = "* %(asctime)s %(levelname)-8s %(message)s"
date_format = "%a, %d %b %Y %H:%M:%S"
console = logging.StreamHandler()
fr = logging.Formatter(log_format)
console.setFormatter(fr)
logger = logging.getLogger()
logger.addFilter(SuperfluousFilter())
logger.addHandler(console)
logger.setLevel(logging.DEBUG)
console.setLevel(logging.DEBUG)
logging.error("Reconfiguring logging")
However this results in duplicate logging output: One with the logging handler from google/appengine/tools/dev_appserver.py (or somewhere in the Google code), and one from my new StreamHandler above. The above code outputs:
ERROR 2010-06-23 20:46:18,871 initialize.py:38] Reconfiguring logging
2010-06-23 20:46:18,871 ERROR Reconfiguring logging
Where the top line is clearly from dev_appserver.py, the bottom line from my code.
So I guess the corollary question is: How can change the formatting of Google App Engine, yet avoid the duplicate output?
Thank you for reading.
Brian
A:
Here is one way you can change the logging format without duplicating output:
# directly access the default handler and set its format directly
logging.getLogger().handlers[0].setFormatter(fr)
This is a bit of a hack because you have to directly access the handlers list stored in the root logger. The problem is GAE automatically uses logging before your code is ever run - this creates a default handler. Unfortunately, I don't see how you can get a reference to this handler without directly accessing the handlers list as above.
| Google App Engine/Python - Change logging formatting | How can one change the formatting of output from the logging module in Google App Engine?
I've tried, e.g.:
log_format = "* %(asctime)s %(levelname)-8s %(message)s"
date_format = "%a, %d %b %Y %H:%M:%S"
console = logging.StreamHandler()
fr = logging.Formatter(log_format)
console.setFormatter(fr)
logger = logging.getLogger()
logger.addFilter(SuperfluousFilter())
logger.addHandler(console)
logger.setLevel(logging.DEBUG)
console.setLevel(logging.DEBUG)
logging.error("Reconfiguring logging")
However this results in duplicate logging output: One with the logging handler from google/appengine/tools/dev_appserver.py (or somewhere in the Google code), and one from my new StreamHandler above. The above code outputs:
ERROR 2010-06-23 20:46:18,871 initialize.py:38] Reconfiguring logging
2010-06-23 20:46:18,871 ERROR Reconfiguring logging
Where the top line is clearly from dev_appserver.py, the bottom line from my code.
So I guess the corollary question is: How can change the formatting of Google App Engine, yet avoid the duplicate output?
Thank you for reading.
Brian
| [
"Here is one way you can change the logging format without duplicating output:\n# directly access the default handler and set its format directly\nlogging.getLogger().handlers[0].setFormatter(fr)\n\nThis is a bit of a hack because you have to directly access the handlers list stored in the root logger. The problem is GAE automatically uses logging before your code is ever run - this creates a default handler. Unfortunately, I don't see how you can get a reference to this handler without directly accessing the handlers list as above.\n"
] | [
11
] | [] | [] | [
"google_app_engine",
"logging",
"python"
] | stackoverflow_0003105521_google_app_engine_logging_python.txt |
Q:
Retrieving a method by using string of method's name? Python
I'm wondering if it's possible in Python to find a method in a different function by using it's string name.
In one function, I pass in a method:
def register(methods):
for m in methods:
messageType = m.__name__
python_client_socket.send(messageType)
register(Foo)
In a different method that takes in the string that was sent over, I want to be able to associate a number with the method in a dictionary ( i.e. methodDict = {1: Foo, 2:Bar, etc...} )
Is there a way in Python to find the method from the string?
A:
If you're certain of the method name (do not use this with arbitrary input):
getattr(someobj, methodDict[someval])
A:
This accomplishes that type of "if it's defined use it, otherwise let the user know it's not ready yet" feel.
if hasattr(self, method):
getattr(self, method)()
else:
print 'No method %s.' % method
A:
Although other answers are correct that getattr is the way to get a method from a string, if you're prepopulating a dictionary with method names don't forget that methods themselves are first-class objects in Python and can equally well be stored in dictionaries, from where they can be called directly:
methodDict[number]()
A:
globals() will return a dictionary of all local-ish methods and other variables. To launch a known method from a string you could do:
known_method_string = 'foo'
globals()[known_method_string]()
Edit: If you're calling this from a object perspective, getattr(...) is probably better.
A:
method = getattr(someobj, method_name, None)
if method is None:
# complain
pass
else:
someobj.method(arg0, arg1, ...)
If you are doing something like processing an XML stream, you could bypass the getattr and have a dictionary mapping tags to methods directly.
| Retrieving a method by using string of method's name? Python | I'm wondering if it's possible in Python to find a method in a different function by using it's string name.
In one function, I pass in a method:
def register(methods):
for m in methods:
messageType = m.__name__
python_client_socket.send(messageType)
register(Foo)
In a different method that takes in the string that was sent over, I want to be able to associate a number with the method in a dictionary ( i.e. methodDict = {1: Foo, 2:Bar, etc...} )
Is there a way in Python to find the method from the string?
| [
"If you're certain of the method name (do not use this with arbitrary input):\ngetattr(someobj, methodDict[someval])\n\n",
"This accomplishes that type of \"if it's defined use it, otherwise let the user know it's not ready yet\" feel.\nif hasattr(self, method):\n getattr(self, method)()\nelse:\n print 'No method %s.' % method\n\n",
"Although other answers are correct that getattr is the way to get a method from a string, if you're prepopulating a dictionary with method names don't forget that methods themselves are first-class objects in Python and can equally well be stored in dictionaries, from where they can be called directly:\nmethodDict[number]()\n\n",
"globals() will return a dictionary of all local-ish methods and other variables. To launch a known method from a string you could do:\nknown_method_string = 'foo'\nglobals()[known_method_string]()\n\nEdit: If you're calling this from a object perspective, getattr(...) is probably better.\n",
"method = getattr(someobj, method_name, None)\nif method is None:\n # complain\n pass\nelse:\n someobj.method(arg0, arg1, ...)\n\nIf you are doing something like processing an XML stream, you could bypass the getattr and have a dictionary mapping tags to methods directly.\n"
] | [
6,
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003105684_python.txt |
Q:
Boost-Python raw pointers constructors
I am trying to expose a C++ library to python using boost-python. The library actually wraps an underlying C api, so uses raw pointers a lot.
// implementation of function that creates a Request object
inline Request Service::createRequest(const char* operation) const
{
blpapi_Request_t *request;
ExceptionUtil::throwOnError(
blpapi_Service_createRequest(d_handle, &request, operation)
);
return Request(request);
}
// request.h
class Request {
blpapi_Request_t *d_handle;
Element d_elements;
Request& operator=(const Request& rhs); // not implemented
public:
explicit Request(blpapi_Request_t *handle);
Request(RequestRef ref);
Request(Request &src);
};
// request.cpp
BOOST_PYTHON_MODULE(request)
{
class_<blpapi_Request_t>;
class_<Request, boost::noncopyable>("Request", init<blpapi_Request_t *>())
.def(init<Request&>())
;
}
Although request.cpp compiles successfully, when I try and use the object I get the following error:
// error output
TypeError: No to_python (by-value) converter found for C++ type: class Request
In-order to call this the python code looks like:
from session import *
from service import *
from request import *
so = SessionOptions()
so.setServerHost('localhost')
so.setServerPort(8194)
session = Session(so)
# start sesssion
if not session.start():
print 'Failed to start session'
raise Exception
if not session.openService('//blp/refdata'):
print 'Failed to open service //blp/refdata'
raise Exception
service = session.getService('//blp/refdata')
request = service.createRequest('ReferenceDataRequest')
The other objects (SessionOptions, Session, Service) etc are also c++ objects that I have successfully created boost-python wrappers for.
As I understand from the boost-python docs this has something to do with passing a raw pointer around, but I don't really understand what else I should do ...
A:
Your class_<blpapi_Request_t>; does not declare anything; is that code the correct version?
If so, then update it:
class_<blpapi_Request_t>("blpapi_Request_t");
That said, what that error indicates is that you are trying to use the Request object with an automatic conversion to a python object which has not been defined.
The reason you get this error is because you have wrapped Request as boost::noncopyable, then provided a factory method which returns a Request object by value; the boost::noncopyable means no copy constructors are generated and therefore there's no automatic to-python converter.
Two ways out of this: one is to remove the noncopyable hint; the other would be to register a converter which takes a C++ Request and returns a Python Request object. Do you really need the noncopyable semantics for Request?
| Boost-Python raw pointers constructors | I am trying to expose a C++ library to python using boost-python. The library actually wraps an underlying C api, so uses raw pointers a lot.
// implementation of function that creates a Request object
inline Request Service::createRequest(const char* operation) const
{
blpapi_Request_t *request;
ExceptionUtil::throwOnError(
blpapi_Service_createRequest(d_handle, &request, operation)
);
return Request(request);
}
// request.h
class Request {
blpapi_Request_t *d_handle;
Element d_elements;
Request& operator=(const Request& rhs); // not implemented
public:
explicit Request(blpapi_Request_t *handle);
Request(RequestRef ref);
Request(Request &src);
};
// request.cpp
BOOST_PYTHON_MODULE(request)
{
class_<blpapi_Request_t>;
class_<Request, boost::noncopyable>("Request", init<blpapi_Request_t *>())
.def(init<Request&>())
;
}
Although request.cpp compiles successfully, when I try and use the object I get the following error:
// error output
TypeError: No to_python (by-value) converter found for C++ type: class Request
In-order to call this the python code looks like:
from session import *
from service import *
from request import *
so = SessionOptions()
so.setServerHost('localhost')
so.setServerPort(8194)
session = Session(so)
# start sesssion
if not session.start():
print 'Failed to start session'
raise Exception
if not session.openService('//blp/refdata'):
print 'Failed to open service //blp/refdata'
raise Exception
service = session.getService('//blp/refdata')
request = service.createRequest('ReferenceDataRequest')
The other objects (SessionOptions, Session, Service) etc are also c++ objects that I have successfully created boost-python wrappers for.
As I understand from the boost-python docs this has something to do with passing a raw pointer around, but I don't really understand what else I should do ...
| [
"Your class_<blpapi_Request_t>; does not declare anything; is that code the correct version?\nIf so, then update it:\nclass_<blpapi_Request_t>(\"blpapi_Request_t\");\n\nThat said, what that error indicates is that you are trying to use the Request object with an automatic conversion to a python object which has not been defined.\nThe reason you get this error is because you have wrapped Request as boost::noncopyable, then provided a factory method which returns a Request object by value; the boost::noncopyable means no copy constructors are generated and therefore there's no automatic to-python converter.\nTwo ways out of this: one is to remove the noncopyable hint; the other would be to register a converter which takes a C++ Request and returns a Python Request object. Do you really need the noncopyable semantics for Request?\n"
] | [
1
] | [] | [] | [
"boost",
"c++",
"pointers",
"python"
] | stackoverflow_0003100341_boost_c++_pointers_python.txt |
Q:
Is it possible to make Python etags a bit smarter with emacs?
I work on my Django project with emacs. In my virtualenv "postactivate" script I have the following simple command:
find -L . -type f -name "*.py" | xargs etags -e > /dev/null 2>&1 &
The TAGS file generates just fine but the system seems rather dumb. When the cursor is a model filter call, e.g.
MyModel.objects.filter(...)
and I hit M-., sometimes emacs takes me place where MyModel is imported at the time of the file (the actual import statement). I only ever want to visit class, method, and function definitions.
Is there a way to make etags smarter?
Thanks,
Ryan Kaskel
A:
Getting correct module analysis with a language like python is very hard, due to his dynamic nature the best way to get correct information is doing static analysis or heuristics.
Currently the best I've found is exploring methods with the ropemacs extension that has great features like code assist (quite smart) and calltips.
Unfortunately it's not easy to get it right with ropemacs, you should install first pymacs and then configure install various rope libraries. (I'm working on a packaged version of it)
Another package that would statically analyze your python code and produce "smarter tags" would be something like pysmell, but I haven't used it extensively
| Is it possible to make Python etags a bit smarter with emacs? | I work on my Django project with emacs. In my virtualenv "postactivate" script I have the following simple command:
find -L . -type f -name "*.py" | xargs etags -e > /dev/null 2>&1 &
The TAGS file generates just fine but the system seems rather dumb. When the cursor is a model filter call, e.g.
MyModel.objects.filter(...)
and I hit M-., sometimes emacs takes me place where MyModel is imported at the time of the file (the actual import statement). I only ever want to visit class, method, and function definitions.
Is there a way to make etags smarter?
Thanks,
Ryan Kaskel
| [
"Getting correct module analysis with a language like python is very hard, due to his dynamic nature the best way to get correct information is doing static analysis or heuristics.\nCurrently the best I've found is exploring methods with the ropemacs extension that has great features like code assist (quite smart) and calltips.\nUnfortunately it's not easy to get it right with ropemacs, you should install first pymacs and then configure install various rope libraries. (I'm working on a packaged version of it)\nAnother package that would statically analyze your python code and produce \"smarter tags\" would be something like pysmell, but I haven't used it extensively\n"
] | [
3
] | [] | [] | [
"django",
"emacs",
"python",
"tags"
] | stackoverflow_0002964906_django_emacs_python_tags.txt |
Q:
Python pass in variable assignments through a function wrapper
So I know that you can wrap a function around another function by doing the following.
def foo(a=4,b=3):
return a+b
def bar(func,args):
return func(*args)
so if I then called
bar(foo,[2,3])
the return value would be 5.
I am wondering is there a way to use bar to call foo with foo(b=12) where bar would return 16?
Does this make sense? Thank you so much for your time ahead of time! And sorry for asking so many questions.
A:
This requires the **kwargs (keyword arguments) syntax.
def foo(a=4, b=3):
return a+b
def bar(func, *args, **kwargs):
return func(*args, **kwargs)
print bar(foo, b=12) # prints 16
Where *args is any number of positional arguments, **kwargs is all the named arguments that were passed in.
And of course, they are only *args and **kwargs by convention; you could name them *panda and **grilled_cheese for all Python cares.
A:
Yep, you can also pass a dict in addition to (or instead of) the list:
def bar(func, args=[], kwargs={}):
return func(*args, **kwargs)
bar(foo, {'b':12})
| Python pass in variable assignments through a function wrapper | So I know that you can wrap a function around another function by doing the following.
def foo(a=4,b=3):
return a+b
def bar(func,args):
return func(*args)
so if I then called
bar(foo,[2,3])
the return value would be 5.
I am wondering is there a way to use bar to call foo with foo(b=12) where bar would return 16?
Does this make sense? Thank you so much for your time ahead of time! And sorry for asking so many questions.
| [
"This requires the **kwargs (keyword arguments) syntax.\ndef foo(a=4, b=3):\n return a+b\ndef bar(func, *args, **kwargs):\n return func(*args, **kwargs)\n\nprint bar(foo, b=12) # prints 16\n\nWhere *args is any number of positional arguments, **kwargs is all the named arguments that were passed in.\nAnd of course, they are only *args and **kwargs by convention; you could name them *panda and **grilled_cheese for all Python cares.\n",
"Yep, you can also pass a dict in addition to (or instead of) the list:\ndef bar(func, args=[], kwargs={}):\n return func(*args, **kwargs)\n\nbar(foo, {'b':12})\n\n"
] | [
11,
4
] | [] | [] | [
"argument_passing",
"function",
"python",
"variables"
] | stackoverflow_0003106216_argument_passing_function_python_variables.txt |
Q:
Vector Class - emulating numeric type
I have a python class
class Vector2D(object):
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def mag(self):
return sqrt(self.x**2 + self.y**2)
...
I want to be able to multiply vectors together like vector1 * vector2, so I added
def __mul__(self, v):
return Vector2D(self.x * v.x, self.y * v.y)
But I also want to use new_vector = some_vector * 2 and return a new vector like so
def __mul__(self, factor):
return Vector2D(self.x * factor, self.y * factor)
How do I do both?
A:
Check to see if v is a Vector2D, and if not pass it to float() and multiply appropriately.
A:
There is no function overload in Python, you have to do it manually.
class Vector(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __mul__(self, k):
if type(k) == float or type(k) == int:
return Vector(self.x * k, self.y * k)
if type(k) == Vector:
return Vector(self.x * k.x, self.y * k.y)
raise "What the hell!?"
def __str__(self):
return "<%f, %f>" % (self.x, self.y)
print Vector(1, 2) * Vector(3, 4)
print Vector(1, 2) * 5
A:
I'm not incredible with Python, but I'm pretty sure you just write one function and check the type of the second argument.
By the way, why are you multiplying vectors by just multiplying their components? That seems entirely useless.
A:
Consider that you might want to use numpy for this sort of data.
| Vector Class - emulating numeric type | I have a python class
class Vector2D(object):
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def mag(self):
return sqrt(self.x**2 + self.y**2)
...
I want to be able to multiply vectors together like vector1 * vector2, so I added
def __mul__(self, v):
return Vector2D(self.x * v.x, self.y * v.y)
But I also want to use new_vector = some_vector * 2 and return a new vector like so
def __mul__(self, factor):
return Vector2D(self.x * factor, self.y * factor)
How do I do both?
| [
"Check to see if v is a Vector2D, and if not pass it to float() and multiply appropriately.\n",
"There is no function overload in Python, you have to do it manually.\nclass Vector(object):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n def __mul__(self, k):\n if type(k) == float or type(k) == int:\n return Vector(self.x * k, self.y * k)\n if type(k) == Vector:\n return Vector(self.x * k.x, self.y * k.y)\n raise \"What the hell!?\"\n def __str__(self):\n return \"<%f, %f>\" % (self.x, self.y)\n\n\nprint Vector(1, 2) * Vector(3, 4)\nprint Vector(1, 2) * 5\n\n",
"I'm not incredible with Python, but I'm pretty sure you just write one function and check the type of the second argument.\nBy the way, why are you multiplying vectors by just multiplying their components? That seems entirely useless.\n",
"Consider that you might want to use numpy for this sort of data.\n"
] | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003106534_python.txt |
Q:
Any productive way to install a bunch of packages
I had one machine with my commonly used python package installed.
and i would like to install the same package on another machine or same machine with different python version. I would like to know whether pip or easy-install or some other method can let me install those packages in a batch. When i use perl, it has something like a bundle package, how to do that in python?
A:
Pip has some great features for this.
It lets you save all requirements from an environment in a file using pip freeze > reqs.txt
You can then later do : pip install -r reqs.txt and you'll get the same exact environnement.
You can also bundle several libraries into a .pybundle file with the command pip bundle MyApp.pybundle -r reqs.txt, and later install it with pip install MyApp.pybundle.
I guess that's what you're looking for :)
A:
I keep a requirements.txt file in one of my repositories that has all my basic python requirements and use PIP to install them on any new machine.
Each of my projects also has it's own requirements.txt file that contains all of it's dependencies for use w/virtualenv.
| Any productive way to install a bunch of packages | I had one machine with my commonly used python package installed.
and i would like to install the same package on another machine or same machine with different python version. I would like to know whether pip or easy-install or some other method can let me install those packages in a batch. When i use perl, it has something like a bundle package, how to do that in python?
| [
"Pip has some great features for this.\nIt lets you save all requirements from an environment in a file using pip freeze > reqs.txt\nYou can then later do : pip install -r reqs.txt and you'll get the same exact environnement.\nYou can also bundle several libraries into a .pybundle file with the command pip bundle MyApp.pybundle -r reqs.txt, and later install it with pip install MyApp.pybundle.\nI guess that's what you're looking for :)\n",
"I keep a requirements.txt file in one of my repositories that has all my basic python requirements and use PIP to install them on any new machine.\nEach of my projects also has it's own requirements.txt file that contains all of it's dependencies for use w/virtualenv.\n"
] | [
9,
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0003106736_pip_python.txt |
Q:
Determine user connecting a local socket with Python
If Python, if you are developing a system service that communicates with user applications through sockets, and you want to treat sockets connected by different users differently, how would you go about that?
If I know that all connecting sockets will be from localhost, is there a way to lookup through the OS (either on windows or linux) which user is making the connection request?
A:
On Linux and other unixy system, you can use the ident service.
I'm not sure if Windows offers something similar.
A:
Unfortunately, at this point in time the python libraries don't support the usual SCM_CREDENTIALS method of passing credentials along a Unix socket.
You'll need to use an "ugly" method as described in another answer to find it.
A:
On Linux you can get the source (i.e. client-side) port of the socket and parse the output of the lsof(8) utility searching for who is using that port.
Here's the manual page.
| Determine user connecting a local socket with Python | If Python, if you are developing a system service that communicates with user applications through sockets, and you want to treat sockets connected by different users differently, how would you go about that?
If I know that all connecting sockets will be from localhost, is there a way to lookup through the OS (either on windows or linux) which user is making the connection request?
| [
"On Linux and other unixy system, you can use the ident service.\nI'm not sure if Windows offers something similar.\n",
"Unfortunately, at this point in time the python libraries don't support the usual SCM_CREDENTIALS method of passing credentials along a Unix socket.\nYou'll need to use an \"ugly\" method as described in another answer to find it.\n",
"On Linux you can get the source (i.e. client-side) port of the socket and parse the output of the lsof(8) utility searching for who is using that port. \nHere's the manual page.\n"
] | [
3,
1,
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0003105705_python_sockets.txt |
Q:
How to set element's id in Python's xml.dom.minidom?
How to? Created a document and an element:
import xml.dom.minidom as d
a=d.Document()
b=a.createElement('test')
setIdAttribute doesn't work :(
b.setIdAttribute('something')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/xml/dom/minidom.py", line 835, in setIdAttribute
self.setIdAttributeNode(idAttr)
File "/usr/lib/python2.6/xml/dom/minidom.py", line 843, in setIdAttributeNode
raise xml.dom.NotFoundErr()
xml.dom.NotFoundErr
And if I set this by hand, getElementById can't find it.
b.setAttribute('id', 'something')
a.getElementById('something')
What I have to do?
A:
Two things are wrong here.
Document.getElementById will only find elements that are actually in the document. Here you've created b but not actually added it to the document. (It's exactly the same in JavaScript.)
You have to mark id as an ID attribute using setIdAttribute. (There's no need to do this in JavaScript because in HTML documents, attributes named id are automatically considered to be ID attributes, logically enough. But XML does not automatically treat attributes named id as IDs; you can either explicitly declare that they are in your DTD or call setIdAttribute individually for every ID attribute. And I am not sure the DTD thing will work with minidom, which is not a full DOM implementation.)
Like so:
import xml.dom.minidom as d
a = d.Document()
b = a.createElement('test')
a.appendChild(b)
b.setAttribute('id', 'x')
b.setIdAttribute('id')
After that, getElementById works:
>>> a.getElementById('x')
<DOM Element: test at 0xb77712ec>
A:
Adding the name of the id attribute to the DTD should help. For example, if you want every to set the id as the id attribute for all <div> elements, you can set up your DTD as follows:
<!DOCTYPE div [<!ATTLIST div id ID #IMPLIED>]>
This is a working example:
>>> from xml.dom.minidom import parse, parseString
>>> data='<!DOCTYPE div [<!ATTLIST div id ID #IMPLIED>]><div><div id="foo">FOO word</div><div id="bar">BAR word</div></div>'
>>> x=parseString(data)
>>> x.getElementById('foo')
<DOM Element: div at 0x1126440>
>>> x.getElementById('foo').toxml()
u'<div id="foo">FOO word</div>'
| How to set element's id in Python's xml.dom.minidom? | How to? Created a document and an element:
import xml.dom.minidom as d
a=d.Document()
b=a.createElement('test')
setIdAttribute doesn't work :(
b.setIdAttribute('something')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/xml/dom/minidom.py", line 835, in setIdAttribute
self.setIdAttributeNode(idAttr)
File "/usr/lib/python2.6/xml/dom/minidom.py", line 843, in setIdAttributeNode
raise xml.dom.NotFoundErr()
xml.dom.NotFoundErr
And if I set this by hand, getElementById can't find it.
b.setAttribute('id', 'something')
a.getElementById('something')
What I have to do?
| [
"Two things are wrong here.\n\nDocument.getElementById will only find elements that are actually in the document. Here you've created b but not actually added it to the document. (It's exactly the same in JavaScript.)\nYou have to mark id as an ID attribute using setIdAttribute. (There's no need to do this in JavaScript because in HTML documents, attributes named id are automatically considered to be ID attributes, logically enough. But XML does not automatically treat attributes named id as IDs; you can either explicitly declare that they are in your DTD or call setIdAttribute individually for every ID attribute. And I am not sure the DTD thing will work with minidom, which is not a full DOM implementation.)\n\nLike so:\nimport xml.dom.minidom as d\na = d.Document()\nb = a.createElement('test')\na.appendChild(b)\nb.setAttribute('id', 'x')\nb.setIdAttribute('id')\n\nAfter that, getElementById works:\n>>> a.getElementById('x')\n<DOM Element: test at 0xb77712ec>\n\n",
"Adding the name of the id attribute to the DTD should help. For example, if you want every to set the id as the id attribute for all <div> elements, you can set up your DTD as follows:\n<!DOCTYPE div [<!ATTLIST div id ID #IMPLIED>]>\nThis is a working example:\n>>> from xml.dom.minidom import parse, parseString \n>>> data='<!DOCTYPE div [<!ATTLIST div id ID #IMPLIED>]><div><div id=\"foo\">FOO word</div><div id=\"bar\">BAR word</div></div>'\n>>> x=parseString(data)\n>>> x.getElementById('foo')\n<DOM Element: div at 0x1126440>\n>>> x.getElementById('foo').toxml()\nu'<div id=\"foo\">FOO word</div>'\n\n"
] | [
8,
2
] | [] | [] | [
"dom",
"minidom",
"python",
"xml"
] | stackoverflow_0001971186_dom_minidom_python_xml.txt |
Q:
currying functions in python in a loop
So here is some code that simplifies what I've been working on:
vars = {
'a':'alice',
'b':'bob',
}
cnames = ['charlie', 'cindy']
commands = []
for c in cnames:
kwargs = dict(vars)
kwargs['c'] = c
print kwargs
commands.append(lambda:a_function(**kwargs))
print commands
def a_function(a=None, b=None, c=None):
print a
print b
print c
for c in commands:
print "run for "+ repr(c)
c()
And here is its output:
{'a': 'alice', 'c': 'charlie', 'b': 'bob'}
{'a': 'alice', 'c': 'cindy', 'b': 'bob'}
[<function <lambda> at 0x1001e9a28>, <function <lambda> at 0x1001e9e60>]
run for <function <lambda> at 0x1001e9a28>
alice
bob
cindy
run for <function <lambda> at 0x1001e9e60>
alice
bob
cindy
I would expect to get charlie, then cindy, why is cindy being displayed twice?
A:
You're encountering a classic binding-time problem, and @Mike's solution is the classic one. A good alternative is to write a higher order function:
def makecall(kwargs):
def callit():
return a_function(**kwargs)
return callit
and use commands.append(makecall(kwargs)) in your loop. Both solutions work on the same principle (by forcing early binding through passage of an argument -- a plain argument in my case, a default value for a named argument in @Mike's); the choice is just a matter of style or elegance (me, while I tolerate lambda in super-simple cases, as long as the subtlest complication intervenes I vastly prefer good old def;-).
A:
A function's body isn't ran until the function is called. When you do lambda: a_function(**kwargs), kwargs isn't looked up until you actually call the function. At that point it's assigned to the last one you made in the loop.
One solution that gets the result you want would be to do commands.append(lambda kwargs=kwargs: a_function(**kwargs))
| currying functions in python in a loop | So here is some code that simplifies what I've been working on:
vars = {
'a':'alice',
'b':'bob',
}
cnames = ['charlie', 'cindy']
commands = []
for c in cnames:
kwargs = dict(vars)
kwargs['c'] = c
print kwargs
commands.append(lambda:a_function(**kwargs))
print commands
def a_function(a=None, b=None, c=None):
print a
print b
print c
for c in commands:
print "run for "+ repr(c)
c()
And here is its output:
{'a': 'alice', 'c': 'charlie', 'b': 'bob'}
{'a': 'alice', 'c': 'cindy', 'b': 'bob'}
[<function <lambda> at 0x1001e9a28>, <function <lambda> at 0x1001e9e60>]
run for <function <lambda> at 0x1001e9a28>
alice
bob
cindy
run for <function <lambda> at 0x1001e9e60>
alice
bob
cindy
I would expect to get charlie, then cindy, why is cindy being displayed twice?
| [
"You're encountering a classic binding-time problem, and @Mike's solution is the classic one. A good alternative is to write a higher order function:\ndef makecall(kwargs):\n def callit():\n return a_function(**kwargs)\n return callit\n\nand use commands.append(makecall(kwargs)) in your loop. Both solutions work on the same principle (by forcing early binding through passage of an argument -- a plain argument in my case, a default value for a named argument in @Mike's); the choice is just a matter of style or elegance (me, while I tolerate lambda in super-simple cases, as long as the subtlest complication intervenes I vastly prefer good old def;-).\n",
"A function's body isn't ran until the function is called. When you do lambda: a_function(**kwargs), kwargs isn't looked up until you actually call the function. At that point it's assigned to the last one you made in the loop.\nOne solution that gets the result you want would be to do commands.append(lambda kwargs=kwargs: a_function(**kwargs))\n"
] | [
5,
4
] | [] | [] | [
"currying",
"lambda",
"python"
] | stackoverflow_0003107231_currying_lambda_python.txt |
Q:
Python input that ends without showing a newline
Is there an python function similar to raw_input but that doesn't show a newline when you press enter. For example, when you press enter in a Forth prompt it doesn't show a newline.
Edit:
If I use the code:
data = raw_input('Prompt: ')
print data
than the output could be:
Prompt: Hello
Hello
because it printed a newline when I pressed enter. I want a function similar to raw_input that doesn't show the newline. So if the function I wanted was called special_input and I used the code:
data = special_input('Prompt: ')
print data
than the output would be something like:
Prompt: Hello Hello
A:
Yes, there are other ways to read a line like raw_input
You can use sys.stdin():
import sys
line = sys.stdin.readline()
Or if you want to get a password you can also use getpass.getpass():
import getpass
line = getpass.getpass()
But if you want something more fancy you will need to use curses
| Python input that ends without showing a newline | Is there an python function similar to raw_input but that doesn't show a newline when you press enter. For example, when you press enter in a Forth prompt it doesn't show a newline.
Edit:
If I use the code:
data = raw_input('Prompt: ')
print data
than the output could be:
Prompt: Hello
Hello
because it printed a newline when I pressed enter. I want a function similar to raw_input that doesn't show the newline. So if the function I wanted was called special_input and I used the code:
data = special_input('Prompt: ')
print data
than the output would be something like:
Prompt: Hello Hello
| [
"Yes, there are other ways to read a line like raw_input\nYou can use sys.stdin():\nimport sys\nline = sys.stdin.readline()\n\nOr if you want to get a password you can also use getpass.getpass():\nimport getpass\nline = getpass.getpass()\n\nBut if you want something more fancy you will need to use curses\n"
] | [
3
] | [] | [] | [
"newline",
"python",
"textinput"
] | stackoverflow_0003105971_newline_python_textinput.txt |
Q:
Is there a more pythonic way to access the child elements of parents using lxml
I am poking at XBRL documents trying to get my head around how to effectively extract and use the data. One thing I have been struggling with is making sure I use the context information correctly. Below is a snippet from one of the documents I am playing with (this is from Mattel's latest 10-K)
I want to be able to efficiently collect the context key value pairs as they are important to help align the 'real' data' Here is an example of a context element
- <context id="eol_PE6050----0910-K0010_STD_0_20091231_0">
- <entity>
<identifier scheme="http://www.sec.gov/CIK">0000063276</identifier>
</entity>
- <period>
<instant>2009-12-31</instant>
</period>
</context>
When I started this I thought that if there was a parent-child relationship I should be able to get the attributes, keys, values and text of all the children directly from applying a method (?) to the parent. But the children retain their independence though they can be found from the parent. What I mean is that if the children have attributes, keys, values and or text those constructs cannot be directly accessed from the parent instead you have to determine/identify the children and from the children access the data or metadata that is needed.
I am not fully certain why this block of code is a good starting point:
from lxml import etree
test_tree=etree.parse(r'c:\temp\test_xml\mat-20091231.xml')
tree_list=[p for p in test_tree.getiterator()
so my tree_list is a list of the elements that were determined to exist in my xml file
Because there were only 664 items in my tree_list I made the very bad assumption that all of the elements within a parent were subsumed in the parent so I kept trying to access the entity, period and instant by referencing just those elements (not their children)
for each in tree_list:
if 'context' in each.tag:
contextlist.append(each)
That is I kept applying different methods to the items in the contextlist and got really frustrated. Finally while I was writing out the question I was trying to get some help figuring out what method would give me the entity and period I just decided to try
children=[c for c in contextlist[0].iterchildren()]
so my list children has all of the children from the first item in my contextlist
One of the children is the entity element, the other is the period element
Now, it should be that each of those children have a child, the entity element has an identifier child element and the period element has an instant child element
This is getting much more complicated than it seemed this morning.
I have to know the details that are reported by the context elements to correctly evaluate and operate on the real data. It seems like I have to test each of the children of the context elements Is there a faster more efficient way to get those values? Rephrased, is there a way to have some element and create a data structure that contains all of its children, and grandchildren etc without having to do a fair amount of try else statements
Once I have them I can start building a data dictionary and assign data elements to particular entries based on the context. So getting the context elements efficiently and completely is critical to my task.
A:
Using the element-tree interface (which lxml also supports), getiterator iterates over all the nodes in the subtree rooted at the current element.
So, [list(c.getiterator()) for c in contextlist] gives you the list of lists you want (or you may want to keep c in the resulting list to avoid having to zip it with contextlist later, i.e. diretly make a list of tuples [(c, list(c.getiterator())) for c in contextlist], depending on your intended use).
Note in passing that a listcomp of the exact form [x for x in whatever] never makes much sense -- use list(whatever), instead, to turn whatever other iterable into a list.
| Is there a more pythonic way to access the child elements of parents using lxml | I am poking at XBRL documents trying to get my head around how to effectively extract and use the data. One thing I have been struggling with is making sure I use the context information correctly. Below is a snippet from one of the documents I am playing with (this is from Mattel's latest 10-K)
I want to be able to efficiently collect the context key value pairs as they are important to help align the 'real' data' Here is an example of a context element
- <context id="eol_PE6050----0910-K0010_STD_0_20091231_0">
- <entity>
<identifier scheme="http://www.sec.gov/CIK">0000063276</identifier>
</entity>
- <period>
<instant>2009-12-31</instant>
</period>
</context>
When I started this I thought that if there was a parent-child relationship I should be able to get the attributes, keys, values and text of all the children directly from applying a method (?) to the parent. But the children retain their independence though they can be found from the parent. What I mean is that if the children have attributes, keys, values and or text those constructs cannot be directly accessed from the parent instead you have to determine/identify the children and from the children access the data or metadata that is needed.
I am not fully certain why this block of code is a good starting point:
from lxml import etree
test_tree=etree.parse(r'c:\temp\test_xml\mat-20091231.xml')
tree_list=[p for p in test_tree.getiterator()
so my tree_list is a list of the elements that were determined to exist in my xml file
Because there were only 664 items in my tree_list I made the very bad assumption that all of the elements within a parent were subsumed in the parent so I kept trying to access the entity, period and instant by referencing just those elements (not their children)
for each in tree_list:
if 'context' in each.tag:
contextlist.append(each)
That is I kept applying different methods to the items in the contextlist and got really frustrated. Finally while I was writing out the question I was trying to get some help figuring out what method would give me the entity and period I just decided to try
children=[c for c in contextlist[0].iterchildren()]
so my list children has all of the children from the first item in my contextlist
One of the children is the entity element, the other is the period element
Now, it should be that each of those children have a child, the entity element has an identifier child element and the period element has an instant child element
This is getting much more complicated than it seemed this morning.
I have to know the details that are reported by the context elements to correctly evaluate and operate on the real data. It seems like I have to test each of the children of the context elements Is there a faster more efficient way to get those values? Rephrased, is there a way to have some element and create a data structure that contains all of its children, and grandchildren etc without having to do a fair amount of try else statements
Once I have them I can start building a data dictionary and assign data elements to particular entries based on the context. So getting the context elements efficiently and completely is critical to my task.
| [
"Using the element-tree interface (which lxml also supports), getiterator iterates over all the nodes in the subtree rooted at the current element.\nSo, [list(c.getiterator()) for c in contextlist] gives you the list of lists you want (or you may want to keep c in the resulting list to avoid having to zip it with contextlist later, i.e. diretly make a list of tuples [(c, list(c.getiterator())) for c in contextlist], depending on your intended use).\nNote in passing that a listcomp of the exact form [x for x in whatever] never makes much sense -- use list(whatever), instead, to turn whatever other iterable into a list.\n"
] | [
3
] | [] | [] | [
"lxml",
"python",
"xbrl"
] | stackoverflow_0003106658_lxml_python_xbrl.txt |
Q:
Really simple way to deal with XML in Python?
Musing over a recently asked question, I started to wonder if there is a really simple way to deal with XML documents in Python. A pythonic way, if you will.
Perhaps I can explain best if i give example: let's say the following - which i think is a good example of how XML is (mis)used in web services - is the response i get from http request to http://www.google.com/ig/api?weather=94043
<xml_api_reply version="1">
<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
<forecast_information>
<city data="Mountain View, CA"/>
<postal_code data="94043"/>
<latitude_e6 data=""/>
<longitude_e6 data=""/>
<forecast_date data="2010-06-23"/>
<current_date_time data="2010-06-24 00:02:54 +0000"/>
<unit_system data="US"/>
</forecast_information>
<current_conditions>
<condition data="Sunny"/>
<temp_f data="68"/>
<temp_c data="20"/>
<humidity data="Humidity: 61%"/>
<icon data="/ig/images/weather/sunny.gif"/>
<wind_condition data="Wind: NW at 19 mph"/>
</current_conditions>
...
<forecast_conditions>
<day_of_week data="Sat"/>
<low data="59"/>
<high data="75"/>
<icon data="/ig/images/weather/partly_cloudy.gif"/>
<condition data="Partly Cloudy"/>
</forecast_conditions>
</weather>
</xml_api_reply>
After loading/parsing such document, i would like to be able to access the information as simple as say
>>> xml['xml_api_reply']['weather']['forecast_information']['city'].data
'Mountain View, CA'
or
>>> xml.xml_api_reply.weather.current_conditions.temp_f['data']
'68'
From what I saw so far, seems that ElementTree is the closest to what I dream of. But it's not there, there is still some fumbling to do when consuming XML. OTOH, what I am thinking is not that complicated - probably just thin veneer on top of a parser - and yet it can decrease annoyance of dealing with XML. Is there such a magic? (And if not - why?)
PS. Note I have tried BeautifulSoup already and while I like its approach, it has real issues with empty <element/>s - see below in comments for examples.
A:
lxml has been mentioned. You might also check out lxml.objectify for some really simple manipulation.
>>> from lxml import objectify
>>> tree = objectify.fromstring(your_xml)
>>> tree.weather.attrib["module_id"]
'0'
>>> tree.weather.forecast_information.city.attrib["data"]
'Mountain View, CA'
>>> tree.weather.forecast_information.postal_code.attrib["data"]
'94043'
A:
You want a thin veneer? That's easy to cook up. Try the following trivial wrapper around ElementTree as a start:
# geetree.py
import xml.etree.ElementTree as ET
class GeeElem(object):
"""Wrapper around an ElementTree element. a['foo'] gets the
attribute foo, a.foo gets the first subelement foo."""
def __init__(self, elem):
self.etElem = elem
def __getitem__(self, name):
res = self._getattr(name)
if res is None:
raise AttributeError, "No attribute named '%s'" % name
return res
def __getattr__(self, name):
res = self._getelem(name)
if res is None:
raise IndexError, "No element named '%s'" % name
return res
def _getelem(self, name):
res = self.etElem.find(name)
if res is None:
return None
return GeeElem(res)
def _getattr(self, name):
return self.etElem.get(name)
class GeeTree(object):
"Wrapper around an ElementTree."
def __init__(self, fname):
self.doc = ET.parse(fname)
def __getattr__(self, name):
if self.doc.getroot().tag != name:
raise IndexError, "No element named '%s'" % name
return GeeElem(self.doc.getroot())
def getroot(self):
return self.doc.getroot()
You invoke it so:
>>> import geetree
>>> t = geetree.GeeTree('foo.xml')
>>> t.xml_api_reply.weather.forecast_information.city['data']
'Mountain View, CA'
>>> t.xml_api_reply.weather.current_conditions.temp_f['data']
'68'
A:
Take a look at Amara 2, particularly the Bindery part of this tutorial.
It works in a way pretty similar to what you describe.
On the other hand. ElementTree's find*() methods can give you 90% of that and are packaged with Python.
A:
I highly recommend lxml.etree and xpath to parse and analyse your data. Here is a complete example. I have truncated the xml to make it easier to read.
import lxml.etree
s = """<?xml version="1.0" encoding="utf-8"?>
<xml_api_reply version="1">
<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
<forecast_information>
<city data="Mountain View, CA"/> <forecast_date data="2010-06-23"/>
</forecast_information>
<forecast_conditions>
<day_of_week data="Sat"/>
<low data="59"/>
<high data="75"/>
<icon data="/ig/images/weather/partly_cloudy.gif"/>
<condition data="Partly Cloudy"/>
</forecast_conditions>
</weather>
</xml_api_reply>"""
tree = lxml.etree.fromstring(s)
for weather in tree.xpath('/xml_api_reply/weather'):
print weather.find('forecast_information/city/@data')[0]
print weather.find('forecast_information/forecast_date/@data')[0]
print weather.find('forecast_conditions/low/@data')[0]
print weather.find('forecast_conditions/high/@data')[0]
A:
If you don't mind using a 3rd party library, then BeautifulSoup will do almost exactly what you ask for:
>>> from BeautifulSoup import BeautifulStoneSoup
>>> soup = BeautifulStoneSoup('''<snip>''')
>>> soup.xml_api_reply.weather.current_conditions.temp_f['data']
u'68'
A:
I believe that the built in python xml module will do the trick. Look at "xml.parsers.expat"
xml.parsers.expat
A:
I found the following python-simplexml module, which in the attempts of the author to get something close to SimpleXML from PHP is indeed a small wrapper around ElementTree. It's under 100 lines but seems to do what was requested:
>>> import SimpleXml
>>> x = SimpleXml.parse(urllib.urlopen('http://www.google.com/ig/api?weather=94043'))
>>> print x.weather.current_conditions.temp_f['data']
58
A:
The suds project provides a Web Services client library that works almost exactly as you describe -- provide it a wsdl and then use factory methods to create the defined types (and process the responses too!).
| Really simple way to deal with XML in Python? | Musing over a recently asked question, I started to wonder if there is a really simple way to deal with XML documents in Python. A pythonic way, if you will.
Perhaps I can explain best if i give example: let's say the following - which i think is a good example of how XML is (mis)used in web services - is the response i get from http request to http://www.google.com/ig/api?weather=94043
<xml_api_reply version="1">
<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
<forecast_information>
<city data="Mountain View, CA"/>
<postal_code data="94043"/>
<latitude_e6 data=""/>
<longitude_e6 data=""/>
<forecast_date data="2010-06-23"/>
<current_date_time data="2010-06-24 00:02:54 +0000"/>
<unit_system data="US"/>
</forecast_information>
<current_conditions>
<condition data="Sunny"/>
<temp_f data="68"/>
<temp_c data="20"/>
<humidity data="Humidity: 61%"/>
<icon data="/ig/images/weather/sunny.gif"/>
<wind_condition data="Wind: NW at 19 mph"/>
</current_conditions>
...
<forecast_conditions>
<day_of_week data="Sat"/>
<low data="59"/>
<high data="75"/>
<icon data="/ig/images/weather/partly_cloudy.gif"/>
<condition data="Partly Cloudy"/>
</forecast_conditions>
</weather>
</xml_api_reply>
After loading/parsing such document, i would like to be able to access the information as simple as say
>>> xml['xml_api_reply']['weather']['forecast_information']['city'].data
'Mountain View, CA'
or
>>> xml.xml_api_reply.weather.current_conditions.temp_f['data']
'68'
From what I saw so far, seems that ElementTree is the closest to what I dream of. But it's not there, there is still some fumbling to do when consuming XML. OTOH, what I am thinking is not that complicated - probably just thin veneer on top of a parser - and yet it can decrease annoyance of dealing with XML. Is there such a magic? (And if not - why?)
PS. Note I have tried BeautifulSoup already and while I like its approach, it has real issues with empty <element/>s - see below in comments for examples.
| [
"lxml has been mentioned. You might also check out lxml.objectify for some really simple manipulation.\n>>> from lxml import objectify\n>>> tree = objectify.fromstring(your_xml)\n>>> tree.weather.attrib[\"module_id\"]\n'0'\n>>> tree.weather.forecast_information.city.attrib[\"data\"]\n'Mountain View, CA'\n>>> tree.weather.forecast_information.postal_code.attrib[\"data\"]\n'94043'\n\n",
"You want a thin veneer? That's easy to cook up. Try the following trivial wrapper around ElementTree as a start:\n# geetree.py\nimport xml.etree.ElementTree as ET\n\nclass GeeElem(object):\n \"\"\"Wrapper around an ElementTree element. a['foo'] gets the\n attribute foo, a.foo gets the first subelement foo.\"\"\"\n def __init__(self, elem):\n self.etElem = elem\n\n def __getitem__(self, name):\n res = self._getattr(name)\n if res is None:\n raise AttributeError, \"No attribute named '%s'\" % name\n return res\n\n def __getattr__(self, name):\n res = self._getelem(name)\n if res is None:\n raise IndexError, \"No element named '%s'\" % name\n return res\n\n def _getelem(self, name):\n res = self.etElem.find(name)\n if res is None:\n return None\n return GeeElem(res)\n\n def _getattr(self, name):\n return self.etElem.get(name)\n\nclass GeeTree(object):\n \"Wrapper around an ElementTree.\"\n def __init__(self, fname):\n self.doc = ET.parse(fname)\n\n def __getattr__(self, name):\n if self.doc.getroot().tag != name:\n raise IndexError, \"No element named '%s'\" % name\n return GeeElem(self.doc.getroot())\n\n def getroot(self):\n return self.doc.getroot()\n\nYou invoke it so:\n>>> import geetree\n>>> t = geetree.GeeTree('foo.xml')\n>>> t.xml_api_reply.weather.forecast_information.city['data']\n'Mountain View, CA'\n>>> t.xml_api_reply.weather.current_conditions.temp_f['data']\n'68'\n\n",
"Take a look at Amara 2, particularly the Bindery part of this tutorial.\nIt works in a way pretty similar to what you describe.\nOn the other hand. ElementTree's find*() methods can give you 90% of that and are packaged with Python.\n",
"I highly recommend lxml.etree and xpath to parse and analyse your data. Here is a complete example. I have truncated the xml to make it easier to read.\nimport lxml.etree\n\ns = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xml_api_reply version=\"1\">\n <weather module_id=\"0\" tab_id=\"0\" mobile_row=\"0\" mobile_zipped=\"1\" row=\"0\" section=\"0\" >\n <forecast_information>\n <city data=\"Mountain View, CA\"/> <forecast_date data=\"2010-06-23\"/>\n </forecast_information>\n <forecast_conditions>\n <day_of_week data=\"Sat\"/>\n <low data=\"59\"/>\n <high data=\"75\"/>\n <icon data=\"/ig/images/weather/partly_cloudy.gif\"/>\n <condition data=\"Partly Cloudy\"/>\n </forecast_conditions>\n </weather>\n</xml_api_reply>\"\"\"\n\ntree = lxml.etree.fromstring(s)\nfor weather in tree.xpath('/xml_api_reply/weather'):\n print weather.find('forecast_information/city/@data')[0]\n print weather.find('forecast_information/forecast_date/@data')[0]\n print weather.find('forecast_conditions/low/@data')[0]\n print weather.find('forecast_conditions/high/@data')[0]\n\n",
"If you don't mind using a 3rd party library, then BeautifulSoup will do almost exactly what you ask for:\n>>> from BeautifulSoup import BeautifulStoneSoup\n>>> soup = BeautifulStoneSoup('''<snip>''')\n>>> soup.xml_api_reply.weather.current_conditions.temp_f['data']\nu'68'\n\n",
"I believe that the built in python xml module will do the trick. Look at \"xml.parsers.expat\"\nxml.parsers.expat\n",
"I found the following python-simplexml module, which in the attempts of the author to get something close to SimpleXML from PHP is indeed a small wrapper around ElementTree. It's under 100 lines but seems to do what was requested:\n>>> import SimpleXml\n>>> x = SimpleXml.parse(urllib.urlopen('http://www.google.com/ig/api?weather=94043'))\n>>> print x.weather.current_conditions.temp_f['data']\n58\n\n",
"The suds project provides a Web Services client library that works almost exactly as you describe -- provide it a wsdl and then use factory methods to create the defined types (and process the responses too!).\n"
] | [
17,
9,
4,
4,
2,
1,
1,
0
] | [
"If you haven't already, I'd suggest looking into the DOM API for Python. DOM is a pretty widely used XML interpretation system, so it should be pretty robust.\nIt's probably a little more complicated than what you describe, but that comes from its attempts to preserve all the information implicit in XML markup rather than from bad design.\n"
] | [
-1
] | [
"python",
"xml"
] | stackoverflow_0003106480_python_xml.txt |
Q:
Python string format character for __unicode__?
Firstly, is there one?
If not, is there a nice way to force something like
print '%s' % obj
to call obj.__unicode__ instead of obj.__str__?
A:
Just use a unicode format string, rather than having a byte string in that role:
>>> class X(object):
... def __str__(self): return 'str'
... def __unicode__(self): return u'unicode'
...
>>> x = X()
>>> print u'%s' % x
unicode
A:
No. It wouldn't make sense for this to be the case.
print (u"%s" % obj).encode(some_encoding) will use obj.__unicode__.
A:
Firstly, is there one?
Sure (sort of). A unicode format string will convert the format values to unicode, implying that obj.__unicode__ will be called (reference).
u'this is a %s' % ('unicode string')
Aside from the above, there's no particular reason why you couldn't be explicit:
print '%s' % (unicode(obj))
| Python string format character for __unicode__? | Firstly, is there one?
If not, is there a nice way to force something like
print '%s' % obj
to call obj.__unicode__ instead of obj.__str__?
| [
"Just use a unicode format string, rather than having a byte string in that role:\n>>> class X(object):\n... def __str__(self): return 'str'\n... def __unicode__(self): return u'unicode'\n... \n>>> x = X()\n>>> print u'%s' % x\nunicode\n\n",
"No. It wouldn't make sense for this to be the case.\nprint (u\"%s\" % obj).encode(some_encoding) will use obj.__unicode__.\n",
"\nFirstly, is there one?\n\nSure (sort of). A unicode format string will convert the format values to unicode, implying that obj.__unicode__ will be called (reference). \nu'this is a %s' % ('unicode string')\n\nAside from the above, there's no particular reason why you couldn't be explicit: \nprint '%s' % (unicode(obj))\n\n"
] | [
4,
1,
0
] | [] | [] | [
"python",
"string",
"syntax",
"unicode"
] | stackoverflow_0003107235_python_string_syntax_unicode.txt |
Q:
What a base controller that will look for a session cookie, and if present, set the User object
I want to use a custom base controller for my wep application that has a User object as a property, and a boolean IsLoggedIn property.
In the constructor of the base controller (or whatever event I need to do this in??) I want to look for a session cookie, if present, load the user and set the User object and set the IsLoggedIn property to true.
I'm very new to pylons so any guidance would be appreciated.
A:
Also you can use before method of controller like this:
class MyControllerWithUserProperty(BaseController):
def __before__(self, action, **params):
# check the cookies
# ...
self.user = <user object>
# set others properties
# ...
A:
In your code that is responsible for logging user in, after verification of user name and password you can store user id in session and make redirect:
session['user_id'] = authenticated_user.id
session.save()
h.redirect_to('/')
and then, in BaseController.init assign user instance to controller's property like this:
self.user = session.get('user_id') and Session.query(User).get(session['user_id'])
This way if user is authenticated you get his instance in self.user. Otherwise self.user is going to be None.
And to logout someone just remove 'user_id' from Pylons' session:
del session['user_id']
PS: I've made some assumptions such as that you are using SQLAlchemy for database backend, but you get the point
| What a base controller that will look for a session cookie, and if present, set the User object | I want to use a custom base controller for my wep application that has a User object as a property, and a boolean IsLoggedIn property.
In the constructor of the base controller (or whatever event I need to do this in??) I want to look for a session cookie, if present, load the user and set the User object and set the IsLoggedIn property to true.
I'm very new to pylons so any guidance would be appreciated.
| [
"Also you can use before method of controller like this:\nclass MyControllerWithUserProperty(BaseController):\n\n def __before__(self, action, **params):\n # check the cookies\n # ...\n\n self.user = <user object>\n\n # set others properties\n # ...\n\n",
"In your code that is responsible for logging user in, after verification of user name and password you can store user id in session and make redirect:\nsession['user_id'] = authenticated_user.id\nsession.save()\nh.redirect_to('/')\n\nand then, in BaseController.init assign user instance to controller's property like this:\nself.user = session.get('user_id') and Session.query(User).get(session['user_id'])\n\nThis way if user is authenticated you get his instance in self.user. Otherwise self.user is going to be None.\nAnd to logout someone just remove 'user_id' from Pylons' session:\ndel session['user_id']\n\nPS: I've made some assumptions such as that you are using SQLAlchemy for database backend, but you get the point\n"
] | [
2,
0
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003087207_pylons_python.txt |
Q:
Template tags like Django with Mako and Pylons
For my site need some "widgets" that elaborate output from various data models, because this widgets are visible in any page is possible with mako to retrieve the data without pass (and elaborate) every time with render() in controllers?
A:
May be you need use helpers
in lib/helpers.py
def tweets(**params):
context = {}
return render('tweets.mako', context)
In you page template do this to render you tweets widget:
h.tweets()
A:
It sounds like you're looking for some combination of FormAlchemy, ToscaWidgets and/or Sprox. I would check out those three.
Also, you might read Chapter 6 of http://pylonsbook.com/en/1.1/ . It helped me a bunch; maybe you'll get something out of it as well.
| Template tags like Django with Mako and Pylons | For my site need some "widgets" that elaborate output from various data models, because this widgets are visible in any page is possible with mako to retrieve the data without pass (and elaborate) every time with render() in controllers?
| [
"May be you need use helpers\nin lib/helpers.py\ndef tweets(**params):\n context = {}\n return render('tweets.mako', context)\n\nIn you page template do this to render you tweets widget:\n h.tweets()\n\n",
"It sounds like you're looking for some combination of FormAlchemy, ToscaWidgets and/or Sprox. I would check out those three.\nAlso, you might read Chapter 6 of http://pylonsbook.com/en/1.1/ . It helped me a bunch; maybe you'll get something out of it as well.\n"
] | [
2,
0
] | [] | [] | [
"mako",
"pylons",
"python"
] | stackoverflow_0003081193_mako_pylons_python.txt |
Q:
Python script reading from a csv file
"Type","Name","Description","Designation","First-term assessment","Second-term assessment","Total"
"Subject","Nick","D1234","F4321",10,19,29
"Unit","HTML","D1234-1","F4321",18,,
"Topic","Tags","First Term","F4321",18,,
"Subtopic","Review of representation of HTML",,,,,
All the above are the value from an excel sheet , which is converted to csv and that is the one shown above
The header as you notice contains seven coulmns,the data below them vary,
I have this script to generate these from python script,the script is below
from django.db import transaction
import sys
import csv
import StringIO
file = sys.argv[1]
no_cols_flag=0
flag=0
header_arr=[]
print file
f = open(file, 'r')
while (f.readline() != ""):
for i in [line.split(',') for line in open(file)]: # split on the separator
print "==========================================================="
row_flag=0
row_d=""
for j in i: # for each token in the split string
row_flag=1
print j
if j:
no_cols_flag=no_cols_flag+1
data=j.strip()
print j
break
How to modify the above script to say that this data belongs to a particular column header..
thanks..
A:
You're importing the csv module but never use it. Why?
If you do
import csv
reader = csv.reader(open(file, "rb"), dialect="excel") # Python 2.x
# Python 3: reader = csv.reader(open(file, newline=""), dialect="excel")
you get a reader object that will contain all you need; the first row will contain the headers, and the subsequent rows will contain the data in the corresponding places.
Even better might be (if I understand you correctly):
import csv
reader = csv.DictReader(open(file, "rb"), dialect="excel") # Python 2.x
# Python 3: reader = csv.DictReader(open(file, newline=""), dialect="excel")
This DictReader can be iterated over, returning a sequence of dicts that use the column header as keys and the following data as values, so
for row in reader:
print(row)
will output
{'Name': 'Nick', 'Designation': 'F4321', 'Type': 'Subject', 'Total': '29', 'First-term assessment': '10', 'Second-term assessment': '19', 'Description': 'D1234'}
{'Name': 'HTML', 'Designation': 'F4321', 'Type': 'Unit', 'Total': '', 'First-term assessment': '18', 'Second-term assessment': '', 'Description': 'D1234-1'}
{'Name': 'Tags', 'Designation': 'F4321', 'Type': 'Topic', 'Total': '', 'First-term assessment': '18', 'Second-term assessment': '', 'Description': 'First Term'}
{'Name': 'Review of representation of HTML', 'Designation': '', 'Type': 'Subtopic', 'Total': '', 'First-term assessment': '', 'Second-term assessment': '', 'Description': ''}
| Python script reading from a csv file | "Type","Name","Description","Designation","First-term assessment","Second-term assessment","Total"
"Subject","Nick","D1234","F4321",10,19,29
"Unit","HTML","D1234-1","F4321",18,,
"Topic","Tags","First Term","F4321",18,,
"Subtopic","Review of representation of HTML",,,,,
All the above are the value from an excel sheet , which is converted to csv and that is the one shown above
The header as you notice contains seven coulmns,the data below them vary,
I have this script to generate these from python script,the script is below
from django.db import transaction
import sys
import csv
import StringIO
file = sys.argv[1]
no_cols_flag=0
flag=0
header_arr=[]
print file
f = open(file, 'r')
while (f.readline() != ""):
for i in [line.split(',') for line in open(file)]: # split on the separator
print "==========================================================="
row_flag=0
row_d=""
for j in i: # for each token in the split string
row_flag=1
print j
if j:
no_cols_flag=no_cols_flag+1
data=j.strip()
print j
break
How to modify the above script to say that this data belongs to a particular column header..
thanks..
| [
"You're importing the csv module but never use it. Why?\nIf you do\nimport csv\nreader = csv.reader(open(file, \"rb\"), dialect=\"excel\") # Python 2.x\n# Python 3: reader = csv.reader(open(file, newline=\"\"), dialect=\"excel\")\n\nyou get a reader object that will contain all you need; the first row will contain the headers, and the subsequent rows will contain the data in the corresponding places. \nEven better might be (if I understand you correctly):\nimport csv\nreader = csv.DictReader(open(file, \"rb\"), dialect=\"excel\") # Python 2.x\n# Python 3: reader = csv.DictReader(open(file, newline=\"\"), dialect=\"excel\")\n\nThis DictReader can be iterated over, returning a sequence of dicts that use the column header as keys and the following data as values, so\nfor row in reader:\n print(row)\n\nwill output\n{'Name': 'Nick', 'Designation': 'F4321', 'Type': 'Subject', 'Total': '29', 'First-term assessment': '10', 'Second-term assessment': '19', 'Description': 'D1234'}\n{'Name': 'HTML', 'Designation': 'F4321', 'Type': 'Unit', 'Total': '', 'First-term assessment': '18', 'Second-term assessment': '', 'Description': 'D1234-1'}\n{'Name': 'Tags', 'Designation': 'F4321', 'Type': 'Topic', 'Total': '', 'First-term assessment': '18', 'Second-term assessment': '', 'Description': 'First Term'}\n{'Name': 'Review of representation of HTML', 'Designation': '', 'Type': 'Subtopic', 'Total': '', 'First-term assessment': '', 'Second-term assessment': '', 'Description': ''}\n\n"
] | [
11
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003107793_csv_python.txt |
Q:
Shortcut to testing PHP code
Having a python interpreter is really useful as it lets you quickly type in few commands and verify output; making it easier to understand syntax.
However, in PHP, every time I want to try something out I have to - create a PHP script, save it, run it in my browser.
Is there a shortcut that I am missing out on for PHP that would make things simpler?
A:
You can run php CLI in interactive mode ;)
php -a
in interactive mode you need to type the script with start and end tags
<?php echo 'Hello!'; ?>
A:
Use PHP Designer. It will make your job much easier.
A:
Or you could use phpUnit , unit testing for php
| Shortcut to testing PHP code | Having a python interpreter is really useful as it lets you quickly type in few commands and verify output; making it easier to understand syntax.
However, in PHP, every time I want to try something out I have to - create a PHP script, save it, run it in my browser.
Is there a shortcut that I am missing out on for PHP that would make things simpler?
| [
"You can run php CLI in interactive mode ;)\nphp -a \n\nin interactive mode you need to type the script with start and end tags \n<?php echo 'Hello!'; ?>\n\n",
"Use PHP Designer. It will make your job much easier.\n",
"Or you could use phpUnit , unit testing for php\n"
] | [
3,
2,
1
] | [] | [] | [
"interpreter",
"php",
"python",
"shortcut"
] | stackoverflow_0003108009_interpreter_php_python_shortcut.txt |
Q:
Scipy sparse triangular matrix?
I am using Scipy to construct a large, sparse (250k X 250k) co-occurrence matrix using scipy.sparse.lil_matrix. Co-occurrence matrices are triangular; that is, M[i,j] == M[j,i]. Since it would be highly inefficient (and in my case, impossible) to store all the data twice, I'm currently storing data at the coordinate (i,j) where i is always smaller than j. So in other words, I have a value stored at (2,3) and no value stored at (3,2), even though (3,2) in my model should be equal to (2,3). (See the matrix below for an example)
My problem is that I need to be able to randomly extract the data corresponding to a given index, but, at least the way, I'm currently doing it, half the data is in the row and half is in the column, like so:
M =
[1 2 3 4
0 5 6 7
0 0 8 9
0 0 0 10]
So, given the above matrix, I want to be able to do a query like M[1], and get back [2,5,6,7]. I have two questions:
1) Is there a more efficient (preferably built-in) way to do this than first querying the row, and then the column, and then concatenating the two? This is bad because whether I use CSC (column-based) or CSR (row-based) internal representation, one of the two queries is highly inefficient.
2) Am I even using the right part of Scipy? I have seen a few functions in the Scipy library that mention triangular matrices, but they seem to revolve around getting triangular matrices from a full matrix. In my case, (I think) I already have a triangular matrix, and want to manipulate it.
Many thanks.
A:
I would say that you can't have the cake and eat it too: if you want efficient storage, you cannot store full rows (as you say); if you want efficient row access, I'd say that you have to store full rows.
While real performances depend on your application, you could check whether the following approach works for you:
You use Scipy's sparse matrices for efficient storage.
You automatically symmetrize your matrix (there is a small recipe on StackOverflow, that works at least on regular matrices).
You can then access its rows (or columns); whether this is efficient depends on the implementation of sparse matrices…
| Scipy sparse triangular matrix? | I am using Scipy to construct a large, sparse (250k X 250k) co-occurrence matrix using scipy.sparse.lil_matrix. Co-occurrence matrices are triangular; that is, M[i,j] == M[j,i]. Since it would be highly inefficient (and in my case, impossible) to store all the data twice, I'm currently storing data at the coordinate (i,j) where i is always smaller than j. So in other words, I have a value stored at (2,3) and no value stored at (3,2), even though (3,2) in my model should be equal to (2,3). (See the matrix below for an example)
My problem is that I need to be able to randomly extract the data corresponding to a given index, but, at least the way, I'm currently doing it, half the data is in the row and half is in the column, like so:
M =
[1 2 3 4
0 5 6 7
0 0 8 9
0 0 0 10]
So, given the above matrix, I want to be able to do a query like M[1], and get back [2,5,6,7]. I have two questions:
1) Is there a more efficient (preferably built-in) way to do this than first querying the row, and then the column, and then concatenating the two? This is bad because whether I use CSC (column-based) or CSR (row-based) internal representation, one of the two queries is highly inefficient.
2) Am I even using the right part of Scipy? I have seen a few functions in the Scipy library that mention triangular matrices, but they seem to revolve around getting triangular matrices from a full matrix. In my case, (I think) I already have a triangular matrix, and want to manipulate it.
Many thanks.
| [
"I would say that you can't have the cake and eat it too: if you want efficient storage, you cannot store full rows (as you say); if you want efficient row access, I'd say that you have to store full rows.\nWhile real performances depend on your application, you could check whether the following approach works for you:\n\nYou use Scipy's sparse matrices for efficient storage.\nYou automatically symmetrize your matrix (there is a small recipe on StackOverflow, that works at least on regular matrices).\nYou can then access its rows (or columns); whether this is efficient depends on the implementation of sparse matrices…\n\n"
] | [
2
] | [] | [] | [
"matrix",
"python",
"scipy"
] | stackoverflow_0003107073_matrix_python_scipy.txt |
Q:
Python httplib.HTTPSConnection and password
I use httplib.HTTPSConnection with private key:
h = httplib.HTTPSConnection(url, key_file='../cert/priv.pem', cert_file='../cert/srv_test.crt')
Then I am asked to enter the password to that private key. Is there any option to enter such password not from user input (console) but from other source (code, environment)? Maybe something like in Java:
-Djavax.net.ssl.keyStorePassword=my_secret_passwd
A:
The private key file is loaded in Python's _ssl module (the part that's written in C). From _ssl.c, line 333:
ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, SSL_FILETYPE_PEM);
This is an OpenSSL function which loads the given key file. If a password is provided, it will call a password callback function. As that function defaults to asking the user, you will have to override it using SSL_CTX_set_default_passwd_cb_userdata. Unfortunately, this function is not included in the standard library or M2Crypto (Python OpenSSL wrapper), but you can find it in pyopenssl.
In order to create a socket from a password-protected key file, you would have to do something like:
from OpenSSL import SSL
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.set_passwd_cb(lambda *unused: "yourpassword")
ctx.use_privatekey_file(keyFilename)
ctx.use_certificate_file(certFilename)
someSocket = SSL.Connection(ctx, socket.socket())
Creating a HTTPS connection is a bit harder and I don't know how to do it with pyopenssl, but there's an example provided in pyopenssl's source code (test_ssl.py:242).
| Python httplib.HTTPSConnection and password | I use httplib.HTTPSConnection with private key:
h = httplib.HTTPSConnection(url, key_file='../cert/priv.pem', cert_file='../cert/srv_test.crt')
Then I am asked to enter the password to that private key. Is there any option to enter such password not from user input (console) but from other source (code, environment)? Maybe something like in Java:
-Djavax.net.ssl.keyStorePassword=my_secret_passwd
| [
"The private key file is loaded in Python's _ssl module (the part that's written in C). From _ssl.c, line 333:\nret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, SSL_FILETYPE_PEM);\n\nThis is an OpenSSL function which loads the given key file. If a password is provided, it will call a password callback function. As that function defaults to asking the user, you will have to override it using SSL_CTX_set_default_passwd_cb_userdata. Unfortunately, this function is not included in the standard library or M2Crypto (Python OpenSSL wrapper), but you can find it in pyopenssl.\nIn order to create a socket from a password-protected key file, you would have to do something like:\nfrom OpenSSL import SSL\nctx = SSL.Context(SSL.SSLv23_METHOD)\nctx.set_passwd_cb(lambda *unused: \"yourpassword\")\nctx.use_privatekey_file(keyFilename)\nctx.use_certificate_file(certFilename)\nsomeSocket = SSL.Connection(ctx, socket.socket())\n\nCreating a HTTPS connection is a bit harder and I don't know how to do it with pyopenssl, but there's an example provided in pyopenssl's source code (test_ssl.py:242).\n"
] | [
4
] | [] | [] | [
"httplib",
"https",
"passwords",
"python",
"ssl"
] | stackoverflow_0003108067_httplib_https_passwords_python_ssl.txt |
Q:
Django url.py without method names
In my Django project, my url.py module looks something like this:
urlpatterns = patterns('',
(r'^$', 'web.views.home.index'),
(r'^home/index', 'web.views.home.index'),
(r'^home/login', 'web.views.home.login'),
(r'^home/logout', 'web.views.home.logout'),
(r'^home/register', 'web.views.home.register'),
)
Is there a way to simplify this so that I don't need an entry for every method in my view? Something like this would be nice:
urlpatterns = patterns('',
(r'^$', 'web.views.home.index'),
(r'^home/(?<method_name>.*)', 'web.views.home.(?P=method_name)'),
)
UPDATE
Now that I know at least one way to do this, is this sort of thing recommended? Or is there a good reason to explicitly create a mapping for each individual method?
A:
You could use a class-based view with a dispatcher method:
class MyView(object):
def __call__(self, method_name):
if hasattr(self, method_name):
return getattr(self, method_name)()
def index(self):
...etc...
and your urls.py would look like this:
from web.views import MyView
urlpatterns = patterns('',
(r'^$', 'web.views.home.index'),
(r'^home/(?<method_name>.*)', MyView()),
)
A:
May be something like that:
import web.views.home as views_list
urlpatterns = patterns('',
(r'^$', 'web.views.home.index'),
*[(r'^home/%s' % i, 'web.views.home.%s' % i) for i in dir(views_list)]
)
| Django url.py without method names | In my Django project, my url.py module looks something like this:
urlpatterns = patterns('',
(r'^$', 'web.views.home.index'),
(r'^home/index', 'web.views.home.index'),
(r'^home/login', 'web.views.home.login'),
(r'^home/logout', 'web.views.home.logout'),
(r'^home/register', 'web.views.home.register'),
)
Is there a way to simplify this so that I don't need an entry for every method in my view? Something like this would be nice:
urlpatterns = patterns('',
(r'^$', 'web.views.home.index'),
(r'^home/(?<method_name>.*)', 'web.views.home.(?P=method_name)'),
)
UPDATE
Now that I know at least one way to do this, is this sort of thing recommended? Or is there a good reason to explicitly create a mapping for each individual method?
| [
"You could use a class-based view with a dispatcher method:\nclass MyView(object):\n def __call__(self, method_name):\n if hasattr(self, method_name):\n return getattr(self, method_name)()\n\n\n def index(self):\n ...etc...\n\nand your urls.py would look like this:\nfrom web.views import MyView\nurlpatterns = patterns('',\n (r'^$', 'web.views.home.index'),\n (r'^home/(?<method_name>.*)', MyView()),\n)\n\n",
"May be something like that:\nimport web.views.home as views_list\nurlpatterns = patterns('',\n (r'^$', 'web.views.home.index'),\n *[(r'^home/%s' % i, 'web.views.home.%s' % i) for i in dir(views_list)]\n)\n\n"
] | [
3,
2
] | [] | [] | [
"django",
"python",
"url",
"url_pattern"
] | stackoverflow_0003106992_django_python_url_url_pattern.txt |
Q:
MySQLdb install problem
I need to install MySQLdb.
I write:
$ tar xfz MySQL-python-1.2.1.tar.gz
$ cd MySQL-python-1.2.1
$ python setup.py build #it is ok
$ su root setup.py install #return list of errors
error list:
setup.py: line 3: import: command not
found
setup.py: line 4: import: command not
found-
setup.py: line 5: from: command not
found-
setup.py: line 7: syntax error
nearunexpected token '('-
setup.py: line 7: 'if not
hasattr(sys, "hexversion") or
sys.hexversion < 0x02030000:'
What's wrong?
A:
You forgot an important word in your example: "python"
$ su root python setup.py install
| MySQLdb install problem | I need to install MySQLdb.
I write:
$ tar xfz MySQL-python-1.2.1.tar.gz
$ cd MySQL-python-1.2.1
$ python setup.py build #it is ok
$ su root setup.py install #return list of errors
error list:
setup.py: line 3: import: command not
found
setup.py: line 4: import: command not
found-
setup.py: line 5: from: command not
found-
setup.py: line 7: syntax error
nearunexpected token '('-
setup.py: line 7: 'if not
hasattr(sys, "hexversion") or
sys.hexversion < 0x02030000:'
What's wrong?
| [
"You forgot an important word in your example: \"python\"\n$ su root python setup.py install\n\n"
] | [
1
] | [] | [] | [
"installation",
"mysql",
"python"
] | stackoverflow_0003108239_installation_mysql_python.txt |
Q:
python httplib: getting the outgoing request headers
I do:
con = HTTPConnection(SERVER_NAME)
con.request('GET', PATH, HEADERS)
resp = con.getresponse()
For debugging reasons, I want to see the request I used (it's fields, path, method,..). I would expect there to be some sort of con.getRequest() or something of the sort but didn't find anything. Ideas?
A:
Try
con.setdebuglevel(1)
That will enable debugging output, which among other things, will print out all the data it sends.
If you only want to get the headers and request line, not the request body (or any other debugging output), you can subclass HTTPConnection and override the _output method, which is called by the class itself to produce output (except for the request body). You'd want to do something like this:
class MyHTTPConnection(HTTPConnection):
def _output(self, s):
print repr(s)
super(MyHTTPConnection, self)._output(s)
For more details on how that works and possible alternatives, have a look at the httplib source code.
| python httplib: getting the outgoing request headers | I do:
con = HTTPConnection(SERVER_NAME)
con.request('GET', PATH, HEADERS)
resp = con.getresponse()
For debugging reasons, I want to see the request I used (it's fields, path, method,..). I would expect there to be some sort of con.getRequest() or something of the sort but didn't find anything. Ideas?
| [
"Try\ncon.setdebuglevel(1)\n\nThat will enable debugging output, which among other things, will print out all the data it sends.\nIf you only want to get the headers and request line, not the request body (or any other debugging output), you can subclass HTTPConnection and override the _output method, which is called by the class itself to produce output (except for the request body). You'd want to do something like this:\nclass MyHTTPConnection(HTTPConnection):\n def _output(self, s):\n print repr(s)\n super(MyHTTPConnection, self)._output(s)\n\nFor more details on how that works and possible alternatives, have a look at the httplib source code.\n"
] | [
3
] | [] | [] | [
"httpconnection",
"httplib",
"python"
] | stackoverflow_0003108488_httpconnection_httplib_python.txt |
Q:
Lets say I have a string...how do I convert that to a datetime?
s = "June 19, 2010"
How do I conver that to a datetime object?
A:
There's also the very good dateutil library, that can parse also stranger cases:
from dateutil.parsers import parse
d = parse(s)
A:
Use datetime.strptime. It takes the string to convert and a format code as arguments. The format code depends on the format of the string you want to convert, of course; details are in the documentation.
For the example in the question, you could do this:
from datetime import datetime
d = datetime.strptime(s, '%B %d, %Y')
A:
As of python 2.5 you have the method datetime.strptime():
http://docs.python.org/library/datetime.html
dt = datetime.strptime("June 19, 2010", "%B %d, %Y")
if your locale is EN.
A:
Use datetime.datetime.strptime:
>>> import datetime
>>> s = "June 19, 2010"
>>> datetime.datetime.strptime(s,"%B %d, %Y")
datetime.datetime(2010, 6, 19, 0, 0)
| Lets say I have a string...how do I convert that to a datetime? | s = "June 19, 2010"
How do I conver that to a datetime object?
| [
"There's also the very good dateutil library, that can parse also stranger cases:\nfrom dateutil.parsers import parse\nd = parse(s)\n\n",
"Use datetime.strptime. It takes the string to convert and a format code as arguments. The format code depends on the format of the string you want to convert, of course; details are in the documentation.\nFor the example in the question, you could do this:\nfrom datetime import datetime\nd = datetime.strptime(s, '%B %d, %Y')\n\n",
"As of python 2.5 you have the method datetime.strptime():\nhttp://docs.python.org/library/datetime.html\ndt = datetime.strptime(\"June 19, 2010\", \"%B %d, %Y\")\n\nif your locale is EN.\n",
"Use datetime.datetime.strptime:\n>>> import datetime\n>>> s = \"June 19, 2010\"\n>>> datetime.datetime.strptime(s,\"%B %d, %Y\")\ndatetime.datetime(2010, 6, 19, 0, 0)\n\n"
] | [
2,
1,
0,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0003108532_datetime_python.txt |
Q:
How to open a file on app engine patch?
I tried to read a file in a view like this:
def foo(request):
f = open('foo.txt', 'r')
data = f.read()
return HttpResponse(data)
I tried to place the foo.txt in almost every folder in the project but it still returns
[Errno 2] No such file or directory:
'foo.txt'
So does anybody knows how to open a file in app engine patch? Where should i place the files i wish to open? many thanks.
I'm using app-engine-patch 1.1beta1
A:
In App Engine, patch or otherwise, you should be able to open (read-only) any file that gets uploaded with your app's sources. Is 'foo.txt' in the same directory as the py file? Does it get uploaded (what does your app.yaml say?)?
A:
Put './' in front of your file path:
f = open('./foo.txt')
If you don't, it will still work in App Engine Launcher 1.3.4, which could be confusing, but once you upload it, you'll get an error.
Also it seems that you shouldn't mention the file (or its dir) you want to access in app.yaml. I'm including css, js and html in my app this way.
A:
You should try f = open('./foo.txt', 'r')
| How to open a file on app engine patch? | I tried to read a file in a view like this:
def foo(request):
f = open('foo.txt', 'r')
data = f.read()
return HttpResponse(data)
I tried to place the foo.txt in almost every folder in the project but it still returns
[Errno 2] No such file or directory:
'foo.txt'
So does anybody knows how to open a file in app engine patch? Where should i place the files i wish to open? many thanks.
I'm using app-engine-patch 1.1beta1
| [
"In App Engine, patch or otherwise, you should be able to open (read-only) any file that gets uploaded with your app's sources. Is 'foo.txt' in the same directory as the py file? Does it get uploaded (what does your app.yaml say?)?\n",
"Put './' in front of your file path:\nf = open('./foo.txt')\n\nIf you don't, it will still work in App Engine Launcher 1.3.4, which could be confusing, but once you upload it, you'll get an error.\nAlso it seems that you shouldn't mention the file (or its dir) you want to access in app.yaml. I'm including css, js and html in my app this way.\n",
"You should try f = open('./foo.txt', 'r')\n"
] | [
2,
1,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0001077691_django_google_app_engine_python.txt |
Q:
Django signals file, cannot import model names
I have such file order:
project/
app/
models.py
signals.py
I am keeping signals inside signals.py as it should be. and at the top of the signals.py file, I include myapp models as I do queries in these signals with
from myproject.myapp.models import Foo
However it doesnt seem to find it, as I run the server or validate from manage.py, it gives this error:
from myproject.myapp.models import Foo
ImportError: cannot import name Foo
I am using Django 1.2.1.
A:
Most likely you have a circular dependency. Does your models.py import the signals? If so, this can't work as both modules now depend on each other. You may need to import the models within a function in the signals file, rather than at the top level.
| Django signals file, cannot import model names | I have such file order:
project/
app/
models.py
signals.py
I am keeping signals inside signals.py as it should be. and at the top of the signals.py file, I include myapp models as I do queries in these signals with
from myproject.myapp.models import Foo
However it doesnt seem to find it, as I run the server or validate from manage.py, it gives this error:
from myproject.myapp.models import Foo
ImportError: cannot import name Foo
I am using Django 1.2.1.
| [
"Most likely you have a circular dependency. Does your models.py import the signals? If so, this can't work as both modules now depend on each other. You may need to import the models within a function in the signals file, rather than at the top level.\n"
] | [
15
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003108694_django_django_models_python.txt |
Q:
Problem executing script using Python and subprocces.call yet works in Bash
For the first time, I am asking a little bit of help over here as I am more of a ServerFault person.
I am doing some scripting in Python and I've been loving the language so far yet I have this little problem which is keeping my script from working.
Here is the code line in question :
subprocess.call('xen-create-image --hostname '+nom+' --memory '+memory+' --partitions=/root/scripts/part.tmp --ip '+ip+' --netmask '+netmask+' --gateway '+gateway+' --passwd',shell=True)
I have tried the same thing with os.popen. All the variables are correctly set.
When I execute the command in question in my regular Linux shell, it works perfectly fine but when I execute it using my Python scripts, I get bizarre errors. I even replaced subprocess.call() by the print function to make sure I am using the exact output of the command.
I went looking into environment variables of my shell but they are pretty much the same... I'll post the error I am getting but I'm not sure it's relevant to my problem.
Use of uninitialized value $lines[0] in substitution (s///) at /usr/share/perl5/Config/IniFiles.pm line 614.
Use of uninitialized value $_ in pattern match (m//) at /usr/share/perl5/Config/IniFiles.pm line 628.
I am not a Python expert so I'm most likely missing something here.
Thank you in advance for your help,
Antoine
EDIT
Following miax's advice, I stopped using shell=True. Instead I took a look at the Python documentation for subprocess and used the following piece of code :
cmd = 'xen-create-image --hostname '+nom+' --memory '+memory+' --partitions=/root/scripts/part.tmp --ip '+ip+' --netmask '+netmask+' --gateway '+gateway+' --passwd'
args = shlex.split(cmd)
subprocess.call(args)
Sadly, it doesn't change anything...
EDIT2
I have used the tip given by miax but I still get the above error... Here is the code that I have used.
cmd = ['xen-create-image', '--hostname', nom, '--memory', memory, '--partitions=/root/scripts/part.tmp', '--ip', ip, '--netmask', netmask, '--gateway', gateway, '--passwd']
subprocess.call(cmd)
This is really strange... The exact command works fine when I run it in the regular shell...
A:
You (in most cases) don't want to use subprocess with shell=True.
Pass it a list of arguments to the command. That is
more secure: Imagine a user manages to pass foo; rm -rf /; echo as some of the values.
more reliable: Imagine one of the strings contains a $ or something – it will be expanded by the shell and replaced by the content of that environment variable.
Without knowing your code and xen-create-image, I assume that is the cause of your problem.
PS: Be sure to look if the exit code of the command is zero, and act appropriately if not. (If you are certain that it will always be zero, use check_call, which raises if it does not; that way you'll at least have a defined behavior if it fails.)
A:
In your Edit2 example which is failing, you think you are giving the following options to xen-create-image:
--hostname
--memory
--partitions=...
etc
... but you are actually specifying the following options:
--hostnamespace
space--memoryspace
space--partitions=...
etc
You have this line:
cmd = ['xen-create-image', '--hostname ', nom, ' --memory ', memory, ' --partitions=/root/scripts/part.tmp', ' --ip ', ip, ' --netmask ', netmask, ' --gateway ', gateway, ' --passwd']
But you need to take out the extra spaces:
cmd = ['xen-create-image', '--hostname', nom, '--memory', memory, '--partitions=/root/scripts/part.tmp', '--ip', ip, '--netmask', netmask, '--gateway', gateway, '--passwd']
A:
You need to print the command you are using:
cmd = 'xen-create-image --hostname '+nom+' --memory '+memory+' --partitions=/root/scripts/part.tmp --ip '+ip+' --netmask '+netmask+' --gateway '+gateway+' --passwd'
print "COMMAND:", cmd
And then paste the command into your shell to make sure it is exactly the same.
A:
Does the xen-create-image script start with a hashbang? That is, is the first line something like
#!/bin/sh
? That is one thing to check. Another is that you can try to call your command as:
cmd = ['/bin/sh', '-c', 'xen-create-image --hostname %s --memory %s --partitions=/root/scripts/part.tmp --ip %s --netmask %s --gateway %s --passwd' % (nom, memory, ip, netmask, gateway)]
subprocess.call(cmd, shell=False)
You might want to print cmd to verify this is the command you intend to run (i.e. check the substitutions).
| Problem executing script using Python and subprocces.call yet works in Bash | For the first time, I am asking a little bit of help over here as I am more of a ServerFault person.
I am doing some scripting in Python and I've been loving the language so far yet I have this little problem which is keeping my script from working.
Here is the code line in question :
subprocess.call('xen-create-image --hostname '+nom+' --memory '+memory+' --partitions=/root/scripts/part.tmp --ip '+ip+' --netmask '+netmask+' --gateway '+gateway+' --passwd',shell=True)
I have tried the same thing with os.popen. All the variables are correctly set.
When I execute the command in question in my regular Linux shell, it works perfectly fine but when I execute it using my Python scripts, I get bizarre errors. I even replaced subprocess.call() by the print function to make sure I am using the exact output of the command.
I went looking into environment variables of my shell but they are pretty much the same... I'll post the error I am getting but I'm not sure it's relevant to my problem.
Use of uninitialized value $lines[0] in substitution (s///) at /usr/share/perl5/Config/IniFiles.pm line 614.
Use of uninitialized value $_ in pattern match (m//) at /usr/share/perl5/Config/IniFiles.pm line 628.
I am not a Python expert so I'm most likely missing something here.
Thank you in advance for your help,
Antoine
EDIT
Following miax's advice, I stopped using shell=True. Instead I took a look at the Python documentation for subprocess and used the following piece of code :
cmd = 'xen-create-image --hostname '+nom+' --memory '+memory+' --partitions=/root/scripts/part.tmp --ip '+ip+' --netmask '+netmask+' --gateway '+gateway+' --passwd'
args = shlex.split(cmd)
subprocess.call(args)
Sadly, it doesn't change anything...
EDIT2
I have used the tip given by miax but I still get the above error... Here is the code that I have used.
cmd = ['xen-create-image', '--hostname', nom, '--memory', memory, '--partitions=/root/scripts/part.tmp', '--ip', ip, '--netmask', netmask, '--gateway', gateway, '--passwd']
subprocess.call(cmd)
This is really strange... The exact command works fine when I run it in the regular shell...
| [
"You (in most cases) don't want to use subprocess with shell=True.\nPass it a list of arguments to the command. That is\n\nmore secure: Imagine a user manages to pass foo; rm -rf /; echo as some of the values.\nmore reliable: Imagine one of the strings contains a $ or something – it will be expanded by the shell and replaced by the content of that environment variable.\n\nWithout knowing your code and xen-create-image, I assume that is the cause of your problem.\nPS: Be sure to look if the exit code of the command is zero, and act appropriately if not. (If you are certain that it will always be zero, use check_call, which raises if it does not; that way you'll at least have a defined behavior if it fails.)\n",
"In your Edit2 example which is failing, you think you are giving the following options to xen-create-image:\n\n--hostname\n--memory\n--partitions=...\netc\n\n... but you are actually specifying the following options:\n\n--hostnamespace\nspace--memoryspace\nspace--partitions=...\netc\n\nYou have this line:\ncmd = ['xen-create-image', '--hostname ', nom, ' --memory ', memory, ' --partitions=/root/scripts/part.tmp', ' --ip ', ip, ' --netmask ', netmask, ' --gateway ', gateway, ' --passwd']\n\nBut you need to take out the extra spaces:\ncmd = ['xen-create-image', '--hostname', nom, '--memory', memory, '--partitions=/root/scripts/part.tmp', '--ip', ip, '--netmask', netmask, '--gateway', gateway, '--passwd']\n\n",
"You need to print the command you are using:\ncmd = 'xen-create-image --hostname '+nom+' --memory '+memory+' --partitions=/root/scripts/part.tmp --ip '+ip+' --netmask '+netmask+' --gateway '+gateway+' --passwd'\nprint \"COMMAND:\", cmd\n\nAnd then paste the command into your shell to make sure it is exactly the same.\n",
"Does the xen-create-image script start with a hashbang? That is, is the first line something like\n#!/bin/sh\n\n? That is one thing to check. Another is that you can try to call your command as:\ncmd = ['/bin/sh', '-c', 'xen-create-image --hostname %s --memory %s --partitions=/root/scripts/part.tmp --ip %s --netmask %s --gateway %s --passwd' % (nom, memory, ip, netmask, gateway)]\nsubprocess.call(cmd, shell=False)\n\nYou might want to print cmd to verify this is the command you intend to run (i.e. check the substitutions).\n"
] | [
2,
0,
0,
0
] | [] | [] | [
"bash",
"python",
"subprocess",
"xen"
] | stackoverflow_0002908935_bash_python_subprocess_xen.txt |
Q:
How can I import the enviroment variables of a completed process in python?
I need to write a python script that launches a shell script and import the environment variables AFTER a script is completed.
Immagine you have a shell script "a.sh":
export MYVAR="test"
In python I would like to do something like:
import os
env={}
os.spawnlpe(os.P_WAIT,'sh', 'sh', 'a.sh',env)
print env
and get:
{'MYVAR'="test"}
Is that possible?
A:
Nope, any changes made to environment variables in a subprocess stay in that subprocess. (As far as I know, that is) When the subprocess terminates, its environment is lost.
I'd suggest getting the shell script to print its environment, or at least the variables you care about, to its standard output (or standard error, or it could write them to a file), and you can read that output from Python.
A:
I agree with David's post.
Perl has a Shell::Source module which does this. It works by running the script you want in a subprocess appended with an env which produces a list of variable value pairs separated by an = symbol. You can parse this and "import" the environment into your process. The module is worth looking at if you need this kind of behaviour.
| How can I import the enviroment variables of a completed process in python? | I need to write a python script that launches a shell script and import the environment variables AFTER a script is completed.
Immagine you have a shell script "a.sh":
export MYVAR="test"
In python I would like to do something like:
import os
env={}
os.spawnlpe(os.P_WAIT,'sh', 'sh', 'a.sh',env)
print env
and get:
{'MYVAR'="test"}
Is that possible?
| [
"Nope, any changes made to environment variables in a subprocess stay in that subprocess. (As far as I know, that is) When the subprocess terminates, its environment is lost.\nI'd suggest getting the shell script to print its environment, or at least the variables you care about, to its standard output (or standard error, or it could write them to a file), and you can read that output from Python.\n",
"I agree with David's post. \nPerl has a Shell::Source module which does this. It works by running the script you want in a subprocess appended with an env which produces a list of variable value pairs separated by an = symbol. You can parse this and \"import\" the environment into your process. The module is worth looking at if you need this kind of behaviour. \n"
] | [
5,
0
] | [] | [] | [
"environment_variables",
"python",
"shell",
"unix"
] | stackoverflow_0003108951_environment_variables_python_shell_unix.txt |
Q:
Dynamically generating a generator function from a blob of text
(Simplified from an excessively verbose question I posted earlier!)
Given a Python string containing valid Python code that contains a "yield" statement, how can I construct a generator that exec's that string?
For example, given the string:
code_string = """for x in range(0, 10):
yield x
"""
I want to construct a generator f that executes code_string such that (in this particular example):
assert(list(f()) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Note that code_string is arbitrary, so this assertion is only valid for the example above. code_string can contain any valid python code that contains a yield statement.
Thanks!
Edit:
The first solution I thought of was to just munge "def f():" into the string and indent each line programmatically. However, that fails if code_string uses different indentation. I was hoping there were some little-known functools kung-fu that can construct a function from a blob of text.
Edit2:
I also tried an exec inside a function like so:
code = "for x in range(0, 10): yield x"
def f():
exec code in globals(), locals()
This results in "SyntaxError: 'yield' outside function"
Solved: I stand corrected, indentation is relative, so this works:
code_string = """for x in range(0, 10):
yield x
"""
exec "def f():\n" + [(" " + line) for line in code_string.split('\n')]) + "\n"
assert list(f()) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
A:
What do you care what indentation is used within the function? Indentation is relative and does not have to be consistent. Tack "def f():\n" on the front, add a single space to each line in your function and exec it, and you're done. This works just as well as your answer:
exec "def f():\n " + " \n".join(code_string.splitlines()) + "\n"
(Sorry to hear your pyparsing solution was too complicated. It sounds like you were trying to recreate a full Python grammar just to add a feature or two to the language. In this case, instead of parsing the whole thing using parseString, you can just add some specialized syntax, define a pyparsing expression for just that syntax, write a parse action that creates Python code from it, and use transformString to search and replace the special syntax with the corresponding Python behavior. Then you can exec or compile the whole transformed module, with just a little bit of pyparsing.)
A:
Try:
exec( """def f():
for x in range(0, 10):
yield x
""" )
for x in f():
print x
| Dynamically generating a generator function from a blob of text | (Simplified from an excessively verbose question I posted earlier!)
Given a Python string containing valid Python code that contains a "yield" statement, how can I construct a generator that exec's that string?
For example, given the string:
code_string = """for x in range(0, 10):
yield x
"""
I want to construct a generator f that executes code_string such that (in this particular example):
assert(list(f()) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Note that code_string is arbitrary, so this assertion is only valid for the example above. code_string can contain any valid python code that contains a yield statement.
Thanks!
Edit:
The first solution I thought of was to just munge "def f():" into the string and indent each line programmatically. However, that fails if code_string uses different indentation. I was hoping there were some little-known functools kung-fu that can construct a function from a blob of text.
Edit2:
I also tried an exec inside a function like so:
code = "for x in range(0, 10): yield x"
def f():
exec code in globals(), locals()
This results in "SyntaxError: 'yield' outside function"
Solved: I stand corrected, indentation is relative, so this works:
code_string = """for x in range(0, 10):
yield x
"""
exec "def f():\n" + [(" " + line) for line in code_string.split('\n')]) + "\n"
assert list(f()) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
| [
"What do you care what indentation is used within the function? Indentation is relative and does not have to be consistent. Tack \"def f():\\n\" on the front, add a single space to each line in your function and exec it, and you're done. This works just as well as your answer:\nexec \"def f():\\n \" + \" \\n\".join(code_string.splitlines()) + \"\\n\" \n\n(Sorry to hear your pyparsing solution was too complicated. It sounds like you were trying to recreate a full Python grammar just to add a feature or two to the language. In this case, instead of parsing the whole thing using parseString, you can just add some specialized syntax, define a pyparsing expression for just that syntax, write a parse action that creates Python code from it, and use transformString to search and replace the special syntax with the corresponding Python behavior. Then you can exec or compile the whole transformed module, with just a little bit of pyparsing.)\n",
"Try:\nexec( \"\"\"def f():\n for x in range(0, 10):\n yield x\n\"\"\" )\n\n\nfor x in f():\n print x\n\n"
] | [
2,
1
] | [] | [] | [
"generator",
"python"
] | stackoverflow_0003105458_generator_python.txt |
Q:
Django Model/Database design for subclasses
Ok, i'm shit at describing. Here's a relationship diag.
In Django i've made my models like:
from django.db import models
from datetime import datetime
class Survey(models.Model):
name = models.CharField(max_length=100)
pub_date = models.DateTimeField('date published',default=datetime.now)
def __unicode__(self):
return self.name
# This model should be abstracted by a more specific model
class Section(models.Model):
survey = models.ForeignKey(Survey)
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
# Models for supporting the 'ratings' mode
class RatingSection(Section):
pass
class RatingQuestion(models.Model):
section = models.ForeignKey(RatingSection)
name = models.CharField(max_length=255)
def __unicode__(self):
return self.name
class RatingAnswer(models.Model):
section = models.ForeignKey(RatingSection)
name = models.CharField(max_length=60)
def __unicode__(self):
return self.name
class RatingVotes(models.Model):
question = models.ForeignKey(RatingQuestion)
answer = models.ForeignKey(RatingAnswer)
votes = models.PositiveIntegerField(default=0)
def __unicode__(self):
return self.votes + self.answer.name + ' votes for ' + self.question.name
# Models for supporting the 'multichoice' mode
class MultiChoiceSection(Section):
can_select_multiple = models.BooleanField()
class MultiChoiceQuestion(models.Model):
section = models.ForeignKey(MultiChoiceSection)
name = models.CharField(max_length=255)
def __unicode__(self):
return self.name
class MultiChoiceAnswer(models.Model):
section = models.ForeignKey(MultiChoiceSection)
name = models.CharField(max_length=60)
votes = models.PositiveIntegerField(default=0)
def __unicode__(self):
return self.name
The problem is that I'm almost certain that's not the right way to do it, and even if it is, I can't work out how to allow the admin area in Django to display a selection to the user asking what sub-type of section they want.
What would be the best way to structure models of this sort?
A:
You could have one section class as well, having an attribute type that could either be rating or multiplechoice - which would be rendered in the admin then as select box.
But I think you should have a look at Django's possibility to create abstract models: http://docs.djangoproject.com/en/dev/topics/db/models/#id6
class Section(models.Model):
survey = models.ForeignKey(Survey)
name = models.CharField(max_length=100)
class Meta:
abstract = True # no db table created for this model
def __unicode__(self):
return self.name
class RatingSection(Section):
pass
class MultiChoiceSection(Section):
can_select_multiple = models.BooleanField()
| Django Model/Database design for subclasses | Ok, i'm shit at describing. Here's a relationship diag.
In Django i've made my models like:
from django.db import models
from datetime import datetime
class Survey(models.Model):
name = models.CharField(max_length=100)
pub_date = models.DateTimeField('date published',default=datetime.now)
def __unicode__(self):
return self.name
# This model should be abstracted by a more specific model
class Section(models.Model):
survey = models.ForeignKey(Survey)
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
# Models for supporting the 'ratings' mode
class RatingSection(Section):
pass
class RatingQuestion(models.Model):
section = models.ForeignKey(RatingSection)
name = models.CharField(max_length=255)
def __unicode__(self):
return self.name
class RatingAnswer(models.Model):
section = models.ForeignKey(RatingSection)
name = models.CharField(max_length=60)
def __unicode__(self):
return self.name
class RatingVotes(models.Model):
question = models.ForeignKey(RatingQuestion)
answer = models.ForeignKey(RatingAnswer)
votes = models.PositiveIntegerField(default=0)
def __unicode__(self):
return self.votes + self.answer.name + ' votes for ' + self.question.name
# Models for supporting the 'multichoice' mode
class MultiChoiceSection(Section):
can_select_multiple = models.BooleanField()
class MultiChoiceQuestion(models.Model):
section = models.ForeignKey(MultiChoiceSection)
name = models.CharField(max_length=255)
def __unicode__(self):
return self.name
class MultiChoiceAnswer(models.Model):
section = models.ForeignKey(MultiChoiceSection)
name = models.CharField(max_length=60)
votes = models.PositiveIntegerField(default=0)
def __unicode__(self):
return self.name
The problem is that I'm almost certain that's not the right way to do it, and even if it is, I can't work out how to allow the admin area in Django to display a selection to the user asking what sub-type of section they want.
What would be the best way to structure models of this sort?
| [
"You could have one section class as well, having an attribute type that could either be rating or multiplechoice - which would be rendered in the admin then as select box.\nBut I think you should have a look at Django's possibility to create abstract models: http://docs.djangoproject.com/en/dev/topics/db/models/#id6\nclass Section(models.Model):\n survey = models.ForeignKey(Survey)\n name = models.CharField(max_length=100)\n\n class Meta:\n abstract = True # no db table created for this model\n\n def __unicode__(self):\n return self.name\n\n\nclass RatingSection(Section):\n pass\n\nclass MultiChoiceSection(Section):\n can_select_multiple = models.BooleanField()\n\n"
] | [
0
] | [] | [] | [
"database_design",
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0003103685_database_design_django_django_admin_django_models_python.txt |
Q:
Django Admin - Displaying Intermediary Fields for M2M Models
We have a Django app which contains a list of newspaper articles. Each article has a m2m relationship with both a "spokesperson", as well as a "firm" (company mentioned in the article).
At the moment, the Add Article page for creating new Articles is quite close to what we want - it's just the stock Django Admin, and we're using filter_horizontal for setting the two m2m relationships.
The next step was to add a "rating" field as an intermediary field on each m2m relationship.
So, an example of our models.py
class Article(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField()
entry_date = models.DateField(auto_now_add=True)
abstract = models.TextField() # Can we restrict this to 450 characters?
category = models.ForeignKey(Category)
subject = models.ForeignKey(Subject)
weekly_summary = models.BooleanField(help_text = 'Should this article be included in the weekly summary?')
source_publication = models.ForeignKey(Publication)
page_number = models.CharField(max_length=30)
article_softcopy = models.FileField(upload_to='article_scans', null=True, blank=True, help_text='Optionally upload a soft-copy (scan) of the article.')
url = models.URLField(null=True, blank=True, help_text = 'Enter a URL for the article. Include the protocl (e.g. http)')
firm = models.ManyToManyField(Firm, null=True, blank=True, through='FirmRating')
spokesperson = models.ManyToManyField(Spokeperson, null=True, blank=True, through='SpokespersonRating')
def __unicode__(self):
return self.title
class Firm(models.Model):
name = models.CharField(max_length=50, unique=True)
homepage = models.URLField(verify_exists=False, help_text='Enter the homepage of the firm. Include the protocol (e.g. http)')
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
class Spokeperson(models.Model):
title = models.CharField(max_length=100)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __unicode__(self):
return self.first_name + ' ' + self.last_name
class Meta:
ordering = ['last_name', 'first_name']
class FirmRating(models.Model):
firm = models.ForeignKey(Firm)
article = models.ForeignKey(Article)
rating = models.IntegerField()
class SpokespersonRating(models.Model):
firm = models.ForeignKey(Spokesperson)
article = models.ForeignKey(Article)
rating = models.IntegerField()
The issue here is that once we change our Firm and Spokesperson field to "through" and use intermediaries, our Add Article page no longer has a filter_horizontal control to add Firms/Spokeperson relationships to the Article - they completely disappear. You can't see them at all. I have no idea why this is.
I was hoping for there to be some way to keep using the cool filter_horizontal widget to set the relationship, and somehow just embed another field below that for setting the rating. However, I'm not sure how to do this whilst still leveraging off the Django admin.
I saw a writeup here about overriding a single widget in Django admin:
http://www.fictitiousnonsense.com/archives/22
However, I'm not sure if that method is still valid, and I'm not sure about applying it to here, with a FK to a intermediary model (it's basically an inline then?).
Surely there's an easy way of doing all this?
Cheers,
Victor
A:
The problem is that the admin's method formfield_for_manytomany in django.contrib.admin.options doesn't return a form field for manytomany fields with an intermediary model! http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/options.py#L157
You would have to override this method in your ModelAdmin:
def formfield_for_manytomany(self, db_field, request=None, **kwargs):
"""
Get a form Field for a ManyToManyField.
"""
# If it uses an intermediary model that isn't auto created, don't show
# a field in admin.
if not db_field.rel.through._meta.auto_created:
return None # return something suitable for your needs here!
db = kwargs.get('using')
if db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel, using=db)
kwargs['help_text'] = ''
elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
| Django Admin - Displaying Intermediary Fields for M2M Models | We have a Django app which contains a list of newspaper articles. Each article has a m2m relationship with both a "spokesperson", as well as a "firm" (company mentioned in the article).
At the moment, the Add Article page for creating new Articles is quite close to what we want - it's just the stock Django Admin, and we're using filter_horizontal for setting the two m2m relationships.
The next step was to add a "rating" field as an intermediary field on each m2m relationship.
So, an example of our models.py
class Article(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField()
entry_date = models.DateField(auto_now_add=True)
abstract = models.TextField() # Can we restrict this to 450 characters?
category = models.ForeignKey(Category)
subject = models.ForeignKey(Subject)
weekly_summary = models.BooleanField(help_text = 'Should this article be included in the weekly summary?')
source_publication = models.ForeignKey(Publication)
page_number = models.CharField(max_length=30)
article_softcopy = models.FileField(upload_to='article_scans', null=True, blank=True, help_text='Optionally upload a soft-copy (scan) of the article.')
url = models.URLField(null=True, blank=True, help_text = 'Enter a URL for the article. Include the protocl (e.g. http)')
firm = models.ManyToManyField(Firm, null=True, blank=True, through='FirmRating')
spokesperson = models.ManyToManyField(Spokeperson, null=True, blank=True, through='SpokespersonRating')
def __unicode__(self):
return self.title
class Firm(models.Model):
name = models.CharField(max_length=50, unique=True)
homepage = models.URLField(verify_exists=False, help_text='Enter the homepage of the firm. Include the protocol (e.g. http)')
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
class Spokeperson(models.Model):
title = models.CharField(max_length=100)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __unicode__(self):
return self.first_name + ' ' + self.last_name
class Meta:
ordering = ['last_name', 'first_name']
class FirmRating(models.Model):
firm = models.ForeignKey(Firm)
article = models.ForeignKey(Article)
rating = models.IntegerField()
class SpokespersonRating(models.Model):
firm = models.ForeignKey(Spokesperson)
article = models.ForeignKey(Article)
rating = models.IntegerField()
The issue here is that once we change our Firm and Spokesperson field to "through" and use intermediaries, our Add Article page no longer has a filter_horizontal control to add Firms/Spokeperson relationships to the Article - they completely disappear. You can't see them at all. I have no idea why this is.
I was hoping for there to be some way to keep using the cool filter_horizontal widget to set the relationship, and somehow just embed another field below that for setting the rating. However, I'm not sure how to do this whilst still leveraging off the Django admin.
I saw a writeup here about overriding a single widget in Django admin:
http://www.fictitiousnonsense.com/archives/22
However, I'm not sure if that method is still valid, and I'm not sure about applying it to here, with a FK to a intermediary model (it's basically an inline then?).
Surely there's an easy way of doing all this?
Cheers,
Victor
| [
"The problem is that the admin's method formfield_for_manytomany in django.contrib.admin.options doesn't return a form field for manytomany fields with an intermediary model! http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/options.py#L157 \nYou would have to override this method in your ModelAdmin:\ndef formfield_for_manytomany(self, db_field, request=None, **kwargs):\n \"\"\"\n Get a form Field for a ManyToManyField.\n \"\"\"\n # If it uses an intermediary model that isn't auto created, don't show\n # a field in admin.\n if not db_field.rel.through._meta.auto_created:\n return None # return something suitable for your needs here!\n db = kwargs.get('using')\n\n if db_field.name in self.raw_id_fields:\n kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel, using=db)\n kwargs['help_text'] = ''\n elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):\n kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))\n\n"
] | [
8
] | [] | [] | [
"django",
"m2m",
"python"
] | stackoverflow_0003108257_django_m2m_python.txt |
Q:
Django, creating user with add user permission
I have gone through a strange behavior while creating a user, using Django admin interface.
I have to create a user which can add other users, but for that Django requires two permissions i.e. add user and change user. But when I gave user the change permission, its even able to change the superuser of the site.
What I want is to create a user which can only create other users.
Please suggest.
Thanks in advance.
A:
This isn't supported by default in Django. You could subclass the normal UserAdmin and make your own, that disables the "superuser"-checkbox for non-superusers:
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.contrib import admin
class MyUserAdmin(UserAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
field = super(MyUserAdmin, self).formfield_for_dbfield(db_field, **kwargs)
user = kwargs['request'].user
if not user.is_superuser:
if db_field.name == 'is_superuser':
field.widget.attrs = {'disabled': 'disabled'}
return field
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
| Django, creating user with add user permission | I have gone through a strange behavior while creating a user, using Django admin interface.
I have to create a user which can add other users, but for that Django requires two permissions i.e. add user and change user. But when I gave user the change permission, its even able to change the superuser of the site.
What I want is to create a user which can only create other users.
Please suggest.
Thanks in advance.
| [
"This isn't supported by default in Django. You could subclass the normal UserAdmin and make your own, that disables the \"superuser\"-checkbox for non-superusers:\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.contrib.auth.models import User\nfrom django.contrib import admin\n\nclass MyUserAdmin(UserAdmin):\n\n def formfield_for_dbfield(self, db_field, **kwargs):\n field = super(MyUserAdmin, self).formfield_for_dbfield(db_field, **kwargs)\n user = kwargs['request'].user\n if not user.is_superuser:\n if db_field.name == 'is_superuser':\n field.widget.attrs = {'disabled': 'disabled'}\n return field\n\nadmin.site.unregister(User)\nadmin.site.register(User, MyUserAdmin)\n\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003109335_django_python.txt |
Q:
Generate a waveform image from an audio file
Building a python application that converts raw audio files into wave using sox on a linux system. I want it to be able to generate an image (PNG or Jpeg) of the audio waveform pattern but I am unable to find a command line tool or python package that will do this. Not being an experience Python programmer my options are limited.
There are several linux applications available that require a running desktop (Gtk) which I do not have. These are useless.
http://www.baudline.com
http://quickplot.sourceforge.net/
GnuPlot and Octave seem to only be able to produce spectrograph's which is not what I am trying to do.
Any ideas?
A:
If you can get the raw audio data as a list of numbers, you can use matplotlib to draw your waveform as a chart. The code would look something like this:
matplotlib.pyplot.plot(raw_audio_data)
| Generate a waveform image from an audio file | Building a python application that converts raw audio files into wave using sox on a linux system. I want it to be able to generate an image (PNG or Jpeg) of the audio waveform pattern but I am unable to find a command line tool or python package that will do this. Not being an experience Python programmer my options are limited.
There are several linux applications available that require a running desktop (Gtk) which I do not have. These are useless.
http://www.baudline.com
http://quickplot.sourceforge.net/
GnuPlot and Octave seem to only be able to produce spectrograph's which is not what I am trying to do.
Any ideas?
| [
"If you can get the raw audio data as a list of numbers, you can use matplotlib to draw your waveform as a chart. The code would look something like this:\nmatplotlib.pyplot.plot(raw_audio_data)\n\n"
] | [
4
] | [] | [] | [
"audio",
"linux",
"python",
"sox"
] | stackoverflow_0003109260_audio_linux_python_sox.txt |
Q:
C++ or Python (maybe else) to create GUI for console application in C
I have a Visual C console application (created in VC++2008EE) and I need to add GUI to it.
One idea was to invoke the console app as a subprocess and communicate with it using stdin and stdout. I tried to do that with Python subprocess module - but it deadlocks (probably because my console app is running continuously). As I understood from http://www.python.org/dev/peps/pep-3145/ it is not possible now to integrate continiously running console application with python subprocess module.
The other idea (more strait-forward probably) was to add a form to this console application project. But as I try to do it VS convers the project to one with "Common Language Runtime support" whatever it means, ads the form, a cpp file for form - and it's not compiling anymore saying:
Command line error D8016 : '/MTd' and '/clr' command-line options are incompatible
error BK1506 : cannot open file '.\Debug\Form_TEST.sbr': No such file or directory
No idea what it means. I have never dealed with C++, but I have used C and Python some time.
What would you recommend?
A:
If you own the code for the console app, don't mess around trying to talk to it using input and output streams. Extract the logic of your console app into a library, and call that library from a GUI of your choice - either Windows.Forms from C#, Python GTK, ordinary GTK.
A:
The reason that VS turns your application to CLR type is becuase it accidently thinks that you want to use winforms which are part of the .NET framework and the only way to use them is if your project is .NET as well.
You do have other options:
1. Add MFC GUI - native C++ GUI
2. better yet create a new .NET project (C#/VB.NET) with the desirect GUI and call your C/C++ dll using P-Invoke or COM interop
| C++ or Python (maybe else) to create GUI for console application in C | I have a Visual C console application (created in VC++2008EE) and I need to add GUI to it.
One idea was to invoke the console app as a subprocess and communicate with it using stdin and stdout. I tried to do that with Python subprocess module - but it deadlocks (probably because my console app is running continuously). As I understood from http://www.python.org/dev/peps/pep-3145/ it is not possible now to integrate continiously running console application with python subprocess module.
The other idea (more strait-forward probably) was to add a form to this console application project. But as I try to do it VS convers the project to one with "Common Language Runtime support" whatever it means, ads the form, a cpp file for form - and it's not compiling anymore saying:
Command line error D8016 : '/MTd' and '/clr' command-line options are incompatible
error BK1506 : cannot open file '.\Debug\Form_TEST.sbr': No such file or directory
No idea what it means. I have never dealed with C++, but I have used C and Python some time.
What would you recommend?
| [
"If you own the code for the console app, don't mess around trying to talk to it using input and output streams. Extract the logic of your console app into a library, and call that library from a GUI of your choice - either Windows.Forms from C#, Python GTK, ordinary GTK. \n",
"The reason that VS turns your application to CLR type is becuase it accidently thinks that you want to use winforms which are part of the .NET framework and the only way to use them is if your project is .NET as well.\nYou do have other options:\n1. Add MFC GUI - native C++ GUI\n2. better yet create a new .NET project (C#/VB.NET) with the desirect GUI and call your C/C++ dll using P-Invoke or COM interop\n"
] | [
5,
1
] | [] | [] | [
"c",
"c++",
"console_application",
"python",
"user_interface"
] | stackoverflow_0003109565_c_c++_console_application_python_user_interface.txt |
Q:
dynamic module creation
I'd like to dynamically create a module from a dictionary, and I'm wondering if adding an element to sys.modules is really the best way to do this. EG
context = { a: 1, b: 2 }
import types
test_context_module = types.ModuleType('TestContext', 'Module created to provide a context for tests')
test_context_module.__dict__.update(context)
import sys
sys.modules['TestContext'] = test_context_module
My immediate goal in this regard is to be able to provide a context for timing test execution:
import timeit
timeit.Timer('a + b', 'from TestContext import *')
It seems that there are other ways to do this, since the Timer constructor takes objects as well as strings. I'm still interested in learning how to do this though, since a) it has other potential applications; and b) I'm not sure exactly how to use objects with the Timer constructor; doing so may prove to be less appropriate than this approach in some circumstances.
EDITS/REVELATIONS/PHOOEYS/EUREKA:
I've realized that the example code relating to running timing tests won't actually work, because import * only works at the module level, and the context in which that statement is executed is that of a function in the testit module. In other words, the globals dictionary used when executing that code is that of __main__, since that's where I was when I wrote the code in the interactive shell. So that rationale for figuring this out is a bit botched, but it's still a valid question.
I've discovered that the code run in the first set of examples has the undesirable effect that the namespace in which the newly created module's code executes is that of the module in which it was declared, not its own module. This is like way weird, and could lead to all sorts of unexpected rattlesnakeic sketchiness. So I'm pretty sure that this is not how this sort of thing is meant to be done, if it is in fact something that the Guido doth shine upon.
The similar-but-subtly-different case of dynamically loading a module from a file that is not in python's include path is quite easily accomplished using imp.load_source('NewModuleName', 'path/to/module/module_to_load.py'). This does load the module into sys.modules. However this doesn't really answer my question, because really, what if you're running python on an embedded platform with no filesystem?
I'm battling a considerable case of information overload at the moment, so I could be mistaken, but there doesn't seem to be anything in the imp module that's capable of this.
But the question, essentially, at this point is how to set the global (ie module) context for an object. Maybe I should ask that more specifically? And at a larger scope, how to get Python to do this while shoehorning objects into a given module?
A:
Hmm, well one thing I can tell you is that the timeit function actually executes its code using the module's global variables. So in your example, you could write
import timeit
timeit.a = 1
timeit.b = 2
timeit.Timer('a + b').timeit()
and it would work. But that doesn't address your more general problem of defining a module dynamically.
Regarding the module definition problem, it's definitely possible and I think you've stumbled on to pretty much the best way to do it. For reference, the gist of what goes on when Python imports a module is basically the following:
module = imp.new_module(name)
execfile(file, module.__dict__)
That's kind of the same thing you do, except that you load the contents of the module from an existing dictionary instead of a file. (I don't know of any difference between types.ModuleType and imp.new_module other than the docstring, so you can probably use them interchangeably) What you're doing is somewhat akin to writing your own importer, and when you do that, you can certainly expect to mess with sys.modules.
As an aside, even if your import * thing was legal within a function, you might still have problems because oddly enough, the statement you pass to the Timer doesn't seem to recognize its own local variables. I invoked a bit of Python voodoo by the name of extract_context() (it's a function I wrote) to set a and b at the local scope and ran
print timeit.Timer('print locals(); a + b', 'sys.modules["__main__"].extract_context()').timeit()
Sure enough, the printout of locals() included a and b:
{'a': 1, 'b': 2, '_timer': <built-in function time>, '_it': repeat(None, 999999), '_t0': 1277378305.3572791, '_i': None}
but it still complained NameError: global name 'a' is not defined. Weird.
| dynamic module creation | I'd like to dynamically create a module from a dictionary, and I'm wondering if adding an element to sys.modules is really the best way to do this. EG
context = { a: 1, b: 2 }
import types
test_context_module = types.ModuleType('TestContext', 'Module created to provide a context for tests')
test_context_module.__dict__.update(context)
import sys
sys.modules['TestContext'] = test_context_module
My immediate goal in this regard is to be able to provide a context for timing test execution:
import timeit
timeit.Timer('a + b', 'from TestContext import *')
It seems that there are other ways to do this, since the Timer constructor takes objects as well as strings. I'm still interested in learning how to do this though, since a) it has other potential applications; and b) I'm not sure exactly how to use objects with the Timer constructor; doing so may prove to be less appropriate than this approach in some circumstances.
EDITS/REVELATIONS/PHOOEYS/EUREKA:
I've realized that the example code relating to running timing tests won't actually work, because import * only works at the module level, and the context in which that statement is executed is that of a function in the testit module. In other words, the globals dictionary used when executing that code is that of __main__, since that's where I was when I wrote the code in the interactive shell. So that rationale for figuring this out is a bit botched, but it's still a valid question.
I've discovered that the code run in the first set of examples has the undesirable effect that the namespace in which the newly created module's code executes is that of the module in which it was declared, not its own module. This is like way weird, and could lead to all sorts of unexpected rattlesnakeic sketchiness. So I'm pretty sure that this is not how this sort of thing is meant to be done, if it is in fact something that the Guido doth shine upon.
The similar-but-subtly-different case of dynamically loading a module from a file that is not in python's include path is quite easily accomplished using imp.load_source('NewModuleName', 'path/to/module/module_to_load.py'). This does load the module into sys.modules. However this doesn't really answer my question, because really, what if you're running python on an embedded platform with no filesystem?
I'm battling a considerable case of information overload at the moment, so I could be mistaken, but there doesn't seem to be anything in the imp module that's capable of this.
But the question, essentially, at this point is how to set the global (ie module) context for an object. Maybe I should ask that more specifically? And at a larger scope, how to get Python to do this while shoehorning objects into a given module?
| [
"Hmm, well one thing I can tell you is that the timeit function actually executes its code using the module's global variables. So in your example, you could write\nimport timeit\ntimeit.a = 1\ntimeit.b = 2\ntimeit.Timer('a + b').timeit()\n\nand it would work. But that doesn't address your more general problem of defining a module dynamically.\nRegarding the module definition problem, it's definitely possible and I think you've stumbled on to pretty much the best way to do it. For reference, the gist of what goes on when Python imports a module is basically the following:\nmodule = imp.new_module(name)\nexecfile(file, module.__dict__)\n\nThat's kind of the same thing you do, except that you load the contents of the module from an existing dictionary instead of a file. (I don't know of any difference between types.ModuleType and imp.new_module other than the docstring, so you can probably use them interchangeably) What you're doing is somewhat akin to writing your own importer, and when you do that, you can certainly expect to mess with sys.modules.\nAs an aside, even if your import * thing was legal within a function, you might still have problems because oddly enough, the statement you pass to the Timer doesn't seem to recognize its own local variables. I invoked a bit of Python voodoo by the name of extract_context() (it's a function I wrote) to set a and b at the local scope and ran\nprint timeit.Timer('print locals(); a + b', 'sys.modules[\"__main__\"].extract_context()').timeit()\n\nSure enough, the printout of locals() included a and b:\n{'a': 1, 'b': 2, '_timer': <built-in function time>, '_it': repeat(None, 999999), '_t0': 1277378305.3572791, '_i': None}\n\nbut it still complained NameError: global name 'a' is not defined. Weird.\n"
] | [
4
] | [] | [] | [
"dynamic",
"module",
"python",
"timing"
] | stackoverflow_0002931950_dynamic_module_python_timing.txt |
Q:
Django Form Display Meta
I am still on Django tutorial and currently here:
def display_meta(request):
values = request.META.items()
values.sort()
html = []
for k, v in values:
html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
return HttpResponse('<table>%s</table>' % '\n'.join(html))
I understand what it is meant to do:
Display the Meta Data on a Http request in a html document.
What I dont understand is in
for k, v in values:
what k, v are standing for.
Any suggestions?
Thanks a lot
L.
A:
Is the method of iterating a Python dictionary {'key':value, ...}
k is the key and v is its value.
| Django Form Display Meta | I am still on Django tutorial and currently here:
def display_meta(request):
values = request.META.items()
values.sort()
html = []
for k, v in values:
html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
return HttpResponse('<table>%s</table>' % '\n'.join(html))
I understand what it is meant to do:
Display the Meta Data on a Http request in a html document.
What I dont understand is in
for k, v in values:
what k, v are standing for.
Any suggestions?
Thanks a lot
L.
| [
"Is the method of iterating a Python dictionary {'key':value, ...}\nk is the key and v is its value.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003109741_python.txt |
Q:
How to delete specific tags
I have the following XML file:
<book>
<bookname child="test">
<text> Works </text>
<text> Doesn't work </text>
</bookname>
</book>
This is just a one block, there are more than one <bookname> tags. I need to iterate through the whole document and remove specific <text> tags. How do I do that?
My approach is to create an ElementTree first and then get an Element instance using ElementTree.getroot(). Then I use Element.clear(). Is this approach ok? I had want to use Element.remove() but I can't get it to work. Can anyone provide me with a sample syntax.
Thank you for the help!
A:
Just call parentNode.remove(childNode). Something like this:
>>> etree.tostring(tree)
'<book> <bookname child="test"> <text> Works </text> <text> Doesnt work </text> </bookname></book>'
>>> bookname=tree[0]
>>> text2=bookname[1]
>>> bookname.remove(text2)
>>> etree.tostring(tree)
'<book> <bookname child="test"> <text> Works </text> </bookname></book>'
>>>
Here I take the bookname node and ask it to remove it's second child.
For finding the nodes you want to remove, I'd use xpath
| How to delete specific tags | I have the following XML file:
<book>
<bookname child="test">
<text> Works </text>
<text> Doesn't work </text>
</bookname>
</book>
This is just a one block, there are more than one <bookname> tags. I need to iterate through the whole document and remove specific <text> tags. How do I do that?
My approach is to create an ElementTree first and then get an Element instance using ElementTree.getroot(). Then I use Element.clear(). Is this approach ok? I had want to use Element.remove() but I can't get it to work. Can anyone provide me with a sample syntax.
Thank you for the help!
| [
"Just call parentNode.remove(childNode). Something like this:\n>>> etree.tostring(tree)\n'<book> <bookname child=\"test\"> <text> Works </text> <text> Doesnt work </text> </bookname></book>'\n>>> bookname=tree[0]\n>>> text2=bookname[1]\n>>> bookname.remove(text2)\n>>> etree.tostring(tree)\n'<book> <bookname child=\"test\"> <text> Works </text> </bookname></book>'\n>>>\n\nHere I take the bookname node and ask it to remove it's second child. \nFor finding the nodes you want to remove, I'd use xpath\n"
] | [
1
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0003109794_lxml_python.txt |
Q:
How to define the "MODULE DOCS" for display with pydoc?
The pydoc documentation of some Python modules (like math and sys) has a "MODULE DOCS" section that contains a useful link to some HTML documentation:
Help on module math:
NAME
math
FILE
/sw/lib/python2.6/lib-dynload/math.so
MODULE DOCS
/sw/share/doc/python26/html/math.html
How can such a section be included in your own modules?
More generally, is there a place where the variables recognized by pydoc are documented?
I was not able to find this in the source because the math module is a shared library, on my machine (OS X), and the sys module is built in Python… Any help would be much appreciated!
A:
After looking in the code of the pydoc module, I think that the "MODULE DOCS" link is only available for standard modules, not custom ones.
Here is the relevant code:
def getdocloc(self, object):
"""Return the location of module docs or None"""
try:
file = inspect.getabsfile(object)
except TypeError:
file = '(built-in)'
docloc = os.environ.get("PYTHONDOCS",
"http://docs.python.org/library")
basedir = os.path.join(sys.exec_prefix, "lib",
"python"+sys.version[0:3])
if (isinstance(object, type(os)) and
(object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
'marshal', 'posix', 'signal', 'sys',
'thread', 'zipimport') or
(file.startswith(basedir) and
not file.startswith(os.path.join(basedir, 'site-packages'))))):
if docloc.startswith("http://"):
docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__)
else:
docloc = os.path.join(docloc, object.__name__ + ".html")
else:
docloc = None
return docloc
A return value of None is interpreted as an empty "MODULE DOCS" section.
A:
Module documentation is probably the docstring of the module. This is a plain text (or restructured text) string occurring at the top of your module. Here is an example.
"""
Module documentation.
"""
def bar():
print "HEllo"
This is for pure Python modules.
For compiled extension modules (like math), You pass the module docstring (as a Python string) as the 3rd argument to Py_InitModule3 when you're initialising your module. That will make the string the module docstring. You can see this being done in the source for the math module here.
| How to define the "MODULE DOCS" for display with pydoc? | The pydoc documentation of some Python modules (like math and sys) has a "MODULE DOCS" section that contains a useful link to some HTML documentation:
Help on module math:
NAME
math
FILE
/sw/lib/python2.6/lib-dynload/math.so
MODULE DOCS
/sw/share/doc/python26/html/math.html
How can such a section be included in your own modules?
More generally, is there a place where the variables recognized by pydoc are documented?
I was not able to find this in the source because the math module is a shared library, on my machine (OS X), and the sys module is built in Python… Any help would be much appreciated!
| [
"After looking in the code of the pydoc module, I think that the \"MODULE DOCS\" link is only available for standard modules, not custom ones.\nHere is the relevant code:\ndef getdocloc(self, object):\n \"\"\"Return the location of module docs or None\"\"\"\n\n try:\n file = inspect.getabsfile(object)\n except TypeError:\n file = '(built-in)'\n\n docloc = os.environ.get(\"PYTHONDOCS\",\n \"http://docs.python.org/library\")\n basedir = os.path.join(sys.exec_prefix, \"lib\",\n \"python\"+sys.version[0:3])\n if (isinstance(object, type(os)) and\n (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',\n 'marshal', 'posix', 'signal', 'sys',\n 'thread', 'zipimport') or\n (file.startswith(basedir) and\n not file.startswith(os.path.join(basedir, 'site-packages'))))):\n if docloc.startswith(\"http://\"):\n docloc = \"%s/%s\" % (docloc.rstrip(\"/\"), object.__name__)\n else:\n docloc = os.path.join(docloc, object.__name__ + \".html\")\n else:\n docloc = None\n return docloc\n\nA return value of None is interpreted as an empty \"MODULE DOCS\" section.\n",
"Module documentation is probably the docstring of the module. This is a plain text (or restructured text) string occurring at the top of your module. Here is an example.\n\"\"\"\nModule documentation.\n\"\"\"\n\ndef bar():\n print \"HEllo\"\n\nThis is for pure Python modules. \nFor compiled extension modules (like math), You pass the module docstring (as a Python string) as the 3rd argument to Py_InitModule3 when you're initialising your module. That will make the string the module docstring. You can see this being done in the source for the math module here.\n"
] | [
3,
0
] | [] | [] | [
"module",
"pydoc",
"python"
] | stackoverflow_0003078735_module_pydoc_python.txt |
Q:
Python: problem processing a string
I have a string as follows:
names = "name:fred, name:wilma, name:barney, name2:gauss, name2:riemann"
let's say the string names has name and name2 attributes.
How do I write a function, is_name_attribute(), that checks if a value is a name attribute? That is is_name_attribute('fred') should return True, whereas is_name_attribute('gauss') should return False.
Also, how do I create a comma separated string comprising of only the name attributes i.e.,
"fred, wilma, barney"
A:
Something like this:
>>> names = "name:fred, name:wilma, name:barney, name2:gauss, name2:riemann"
>>> pairs = [x.split(':') for x in names.split(", ")]
>>> attrs = [x[1] for x in pairs if x[0]=='name']
>>> attrs
['fred', 'wilma', 'barney']
>>> def is_name_attribute(x):
... return x in attrs
...
>>> is_name_attribute('fred')
True
>>> is_name_attribute('gauss')
False
A:
There are other ways of doing this (as you'll see from the answers) but perhaps it's time to learn some Python list magic.
>>> names = "name:fred, name:wilma, name:barney, name2:gauss, name2:riemann"
>>> names_list = [pair.split(':') for pair in names.split(', ')]
>>> names_list
[['name', 'fred'], ['name', 'wilma'], ['name', 'barney'], ['name2', 'gauss'], ['name2', 'riemann']]
From there, it's just a case of checking. If you're looking for a certain name:
for pair in names_list:
if pair[0] == 'name' and pair[1] == 'fred':
return true
return false
And joining just the name versions:
>>> new_name_list = ','.join([pair[1] for pair in names_list if pair[0] == 'name'])
>>> new_name_list
'fred,wilma,barney'
A:
Simple regexp matching:
>>> names = re.compile ('name:([^,]+)', 'g')
>>> names2 = re.compile ('name2:([^,]+)', 'g')
>>> str = "name:fred, name:wilma, name:barney, name2:gauss, name2:riemann"
>>> 'fred' in names.findall(str)
True
>>> names.findall(str)
['fred', 'wilma', 'barney']
| Python: problem processing a string | I have a string as follows:
names = "name:fred, name:wilma, name:barney, name2:gauss, name2:riemann"
let's say the string names has name and name2 attributes.
How do I write a function, is_name_attribute(), that checks if a value is a name attribute? That is is_name_attribute('fred') should return True, whereas is_name_attribute('gauss') should return False.
Also, how do I create a comma separated string comprising of only the name attributes i.e.,
"fred, wilma, barney"
| [
"Something like this:\n>>> names = \"name:fred, name:wilma, name:barney, name2:gauss, name2:riemann\"\n>>> pairs = [x.split(':') for x in names.split(\", \")]\n>>> attrs = [x[1] for x in pairs if x[0]=='name']\n>>> attrs \n['fred', 'wilma', 'barney']\n>>> def is_name_attribute(x):\n... return x in attrs\n...\n>>> is_name_attribute('fred')\nTrue\n>>> is_name_attribute('gauss')\nFalse\n\n",
"There are other ways of doing this (as you'll see from the answers) but perhaps it's time to learn some Python list magic.\n>>> names = \"name:fred, name:wilma, name:barney, name2:gauss, name2:riemann\"\n>>> names_list = [pair.split(':') for pair in names.split(', ')]\n>>> names_list\n[['name', 'fred'], ['name', 'wilma'], ['name', 'barney'], ['name2', 'gauss'], ['name2', 'riemann']]\n\nFrom there, it's just a case of checking. If you're looking for a certain name:\nfor pair in names_list:\n if pair[0] == 'name' and pair[1] == 'fred':\n return true\nreturn false\n\nAnd joining just the name versions:\n>>> new_name_list = ','.join([pair[1] for pair in names_list if pair[0] == 'name'])\n>>> new_name_list\n'fred,wilma,barney'\n\n",
"Simple regexp matching:\n>>> names = re.compile ('name:([^,]+)', 'g')\n>>> names2 = re.compile ('name2:([^,]+)', 'g')\n>>> str = \"name:fred, name:wilma, name:barney, name2:gauss, name2:riemann\"\n>>> 'fred' in names.findall(str)\nTrue\n>>> names.findall(str)\n['fred', 'wilma', 'barney']\n\n"
] | [
5,
0,
0
] | [
"I think writing als this stuff in a String is not the best solution, but:\nimport re\n\nnames = \"name:fred, name:wilma, name:barney, name2:gauss, name2:riemann\"\n\ndef is_name_attribute(names, name):\n list = names.split()\n compiler = re.compile('^name:(.*)$')\n for line in list:\n line = line.replace(',','')\n match = compiler.match(line)\n if match:\n if name == match.group(1):\n return True\n return False\n\ndef commaseperated(names):\n list = names.split()\n compiler = re.compile('^name:(.*)$')\n commasep = \"\"\n for line in list:\n line = line.replace(',','')\n match = compiler.match(line)\n if match:\n commasep += match.group(1) + ', '\n return commasep[:-2]\n\nprint is_name_attribute(names, 'fred')\nprint is_name_attribute(names, 'gauss')\nprint commaseperated(names)\n\n"
] | [
-1
] | [
"data_structures",
"python",
"string"
] | stackoverflow_0003110053_data_structures_python_string.txt |
Q:
UnicodeEncodeError: 'ascii' codec can't encode character when trying a HTTP POST in Python
I'm trying to do a HTTP POST with a unicode string (u'\xe4\xf6\xfc') as a parameter in Python, but I receive the following error:
UnicodeEncodeError: 'ascii' codec can't encode character
This is to the code used to make the HTTP POST (with httplib2)
http = httplib2.Http()
userInfo = [('Name', u'\xe4\xf6\xfc')]
data = urlencode(userInfo)
resp, content = http.request(url, 'POST', body=data)
Any ideas on how to solve this?
A:
You cannot POST Python Unicode objects directly. You should encode it as a UTF-8 string first:
name = u'\xe4\xf6\xfc'.encode('utf-8')
userInfo = [('Name', name)]
| UnicodeEncodeError: 'ascii' codec can't encode character when trying a HTTP POST in Python | I'm trying to do a HTTP POST with a unicode string (u'\xe4\xf6\xfc') as a parameter in Python, but I receive the following error:
UnicodeEncodeError: 'ascii' codec can't encode character
This is to the code used to make the HTTP POST (with httplib2)
http = httplib2.Http()
userInfo = [('Name', u'\xe4\xf6\xfc')]
data = urlencode(userInfo)
resp, content = http.request(url, 'POST', body=data)
Any ideas on how to solve this?
| [
"You cannot POST Python Unicode objects directly. You should encode it as a UTF-8 string first:\nname = u'\\xe4\\xf6\\xfc'.encode('utf-8')\nuserInfo = [('Name', name)]\n\n"
] | [
13
] | [] | [] | [
"ascii",
"http_post",
"python",
"unicode"
] | stackoverflow_0003110104_ascii_http_post_python_unicode.txt |
Q:
How to open write reserved excel file in python with win32com?
I'm trying to open a write-protected ms excel 2007 file using win32com in python -- I know the password. I can open it with user input of the password into the excel dialog box. I want to be able to open the file without any user interaction. I've tried the following, but it still pops up the dialog box.
app.Workbooks.Open("filename.xls", WriteResPassword="secret")
Any ideas what I'm doing wrong please?
Thanks,
Dave.
A:
I can get the above code to work if I don't try to use named function parameters. I.e. the following works:
app.Workbooks.Open("filename.xls", 2, True, None, None, "secret")
| How to open write reserved excel file in python with win32com? | I'm trying to open a write-protected ms excel 2007 file using win32com in python -- I know the password. I can open it with user input of the password into the excel dialog box. I want to be able to open the file without any user interaction. I've tried the following, but it still pops up the dialog box.
app.Workbooks.Open("filename.xls", WriteResPassword="secret")
Any ideas what I'm doing wrong please?
Thanks,
Dave.
| [
"I can get the above code to work if I don't try to use named function parameters. I.e. the following works:\napp.Workbooks.Open(\"filename.xls\", 2, True, None, None, \"secret\")\n\n"
] | [
3
] | [] | [] | [
"excel",
"python",
"win32com"
] | stackoverflow_0002887339_excel_python_win32com.txt |
Q:
Algorithm to calculate percent difference between two blobs of text
I've been researching on finding an efficient solution to this. I've looked into diffing engines (google's diff-match-patch, python's diff) and some some longest common chain algorithms.
I was hoping on getting you guys suggestions on how to solve this issue. Any algorithm or library in particular you would like to recommend?
A:
I don't know what "longest common [[chain? substring?]]" has to do with "percent difference", especially after seeing in a comment that you expect a very small % difference between two strings that differ by one character in the middle (so their longest common substring is about one half of the strings' length).
Ignoring the "longest common" strangeness, and defining "percent difference" as the edit distance between the strings divided by the max length (times 100 of course;-), what about:
def levenshtein_distance(first, second):
"""Find the Levenshtein distance between two strings."""
if len(first) > len(second):
first, second = second, first
if len(second) == 0:
return len(first)
first_length = len(first) + 1
second_length = len(second) + 1
distance_matrix = [[0] * second_length for x in range(first_length)]
for i in range(first_length):
distance_matrix[i][0] = i
for j in range(second_length):
distance_matrix[0][j]=j
for i in xrange(1, first_length):
for j in range(1, second_length):
deletion = distance_matrix[i-1][j] + 1
insertion = distance_matrix[i][j-1] + 1
substitution = distance_matrix[i-1][j-1]
if first[i-1] != second[j-1]:
substitution += 1
distance_matrix[i][j] = min(insertion, deletion, substitution)
return distance_matrix[first_length-1][second_length-1]
def percent_diff(first, second):
return 100*levenshtein_distance(a, b) / float(max(len(a), len(b)))
a = "the quick brown fox"
b = "the quick vrown fox"
print '%.2f' % percent_diff(a, b)
The Levenshtein function is from Stavros' blog. The result in this case would be 5.26 (percent difference).
A:
In addition to difflib and other common subsequence libraries, if it's natural language text, you might look into stemming, which normalizes words to their root form. You can find several implementations in the Natural Language Toolkit ( http://www.nltk.org/ ) library. You can also compare blobs of natural language text more semantically by using N-Grams ( http://en.wikipedia.org/wiki/N-gram ).
A:
Longest common chain? Perhaps this will help then: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
A:
Another area of interest might be the Levenshtein distance described here.
| Algorithm to calculate percent difference between two blobs of text | I've been researching on finding an efficient solution to this. I've looked into diffing engines (google's diff-match-patch, python's diff) and some some longest common chain algorithms.
I was hoping on getting you guys suggestions on how to solve this issue. Any algorithm or library in particular you would like to recommend?
| [
"I don't know what \"longest common [[chain? substring?]]\" has to do with \"percent difference\", especially after seeing in a comment that you expect a very small % difference between two strings that differ by one character in the middle (so their longest common substring is about one half of the strings' length).\nIgnoring the \"longest common\" strangeness, and defining \"percent difference\" as the edit distance between the strings divided by the max length (times 100 of course;-), what about:\ndef levenshtein_distance(first, second):\n \"\"\"Find the Levenshtein distance between two strings.\"\"\"\n if len(first) > len(second):\n first, second = second, first\n if len(second) == 0:\n return len(first)\n first_length = len(first) + 1\n second_length = len(second) + 1\n distance_matrix = [[0] * second_length for x in range(first_length)]\n for i in range(first_length):\n distance_matrix[i][0] = i\n for j in range(second_length):\n distance_matrix[0][j]=j\n for i in xrange(1, first_length):\n for j in range(1, second_length):\n deletion = distance_matrix[i-1][j] + 1\n insertion = distance_matrix[i][j-1] + 1\n substitution = distance_matrix[i-1][j-1]\n if first[i-1] != second[j-1]:\n substitution += 1\n distance_matrix[i][j] = min(insertion, deletion, substitution)\n return distance_matrix[first_length-1][second_length-1]\n\ndef percent_diff(first, second):\n return 100*levenshtein_distance(a, b) / float(max(len(a), len(b)))\n\na = \"the quick brown fox\"\nb = \"the quick vrown fox\"\nprint '%.2f' % percent_diff(a, b)\n\nThe Levenshtein function is from Stavros' blog. The result in this case would be 5.26 (percent difference).\n",
"In addition to difflib and other common subsequence libraries, if it's natural language text, you might look into stemming, which normalizes words to their root form. You can find several implementations in the Natural Language Toolkit ( http://www.nltk.org/ ) library. You can also compare blobs of natural language text more semantically by using N-Grams ( http://en.wikipedia.org/wiki/N-gram ).\n",
"Longest common chain? Perhaps this will help then: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem\n",
"Another area of interest might be the Levenshtein distance described here.\n"
] | [
6,
2,
1,
0
] | [] | [] | [
"algorithm",
"python",
"string"
] | stackoverflow_0003106994_algorithm_python_string.txt |
Q:
Django template doesn't render a Variable's method
I am obviously victim of some dark magic...
Here is a template that I render :
context = Context({'my_cube': c})
template = Template(
'{% load cube_templatetags %}'
'{{ my_cube|inspect }} {{ my_cube.measure }}'
)
Here is the implementation of the inspect filter :
def inspect_object(obj):
return obj.measure()
Here is what the rendering gives me :
>>> template.render(context)
u'6 None'
Does anyone know why the hell does the {{ my_cube.measure }} is not rendered properly, while obviously the function call is successful ???
NB : the measure function does no magic, no internal state is changed, I tested and it gives the same result each time, I also tested to put the inspect before the {{ cube.measure }}.... doesn't change anything. I have absolutely no clue on what's going on...
EDIT :
I know where it seems to be coming from. But it is still strange. For some reason, my object's attribute are not resolved by template.Variable :
>>> Variable('measure').resolve(c) == None
True
>>> Variable('testitesti').resolve(c) == None
True
>>> c.testitesti()
68
#implementation of testitesti :
def testitesti(self):
return 68
A:
Well... I found the damn thing !
The object I was trying to render had a __getitem__ method that was just empty, so dictionnary indexing worked on this object (no error thrown), so of course the function call was not made !
A:
Inspect is being registered as a filter, yep? I'm assuming so else the whole template would choke. Is there a possible reserved word clash? inspect is a pretty loaded term, after all. Have you tried renaming that filter to something else?
| Django template doesn't render a Variable's method | I am obviously victim of some dark magic...
Here is a template that I render :
context = Context({'my_cube': c})
template = Template(
'{% load cube_templatetags %}'
'{{ my_cube|inspect }} {{ my_cube.measure }}'
)
Here is the implementation of the inspect filter :
def inspect_object(obj):
return obj.measure()
Here is what the rendering gives me :
>>> template.render(context)
u'6 None'
Does anyone know why the hell does the {{ my_cube.measure }} is not rendered properly, while obviously the function call is successful ???
NB : the measure function does no magic, no internal state is changed, I tested and it gives the same result each time, I also tested to put the inspect before the {{ cube.measure }}.... doesn't change anything. I have absolutely no clue on what's going on...
EDIT :
I know where it seems to be coming from. But it is still strange. For some reason, my object's attribute are not resolved by template.Variable :
>>> Variable('measure').resolve(c) == None
True
>>> Variable('testitesti').resolve(c) == None
True
>>> c.testitesti()
68
#implementation of testitesti :
def testitesti(self):
return 68
| [
"Well... I found the damn thing !\nThe object I was trying to render had a __getitem__ method that was just empty, so dictionnary indexing worked on this object (no error thrown), so of course the function call was not made !\n",
"Inspect is being registered as a filter, yep? I'm assuming so else the whole template would choke. Is there a possible reserved word clash? inspect is a pretty loaded term, after all. Have you tried renaming that filter to something else?\n"
] | [
2,
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003109951_django_django_templates_python.txt |
Q:
Why type(classInstance) is returning 'instance'?
I have a method that accepts a parameter that can be of several types, and has to do one thing or other depending on the type, but if I check the type of said parameter, I don't get the 'real' type, I always get <type 'instance'>, and that is messing up with my comparisons.
I have something like:
from classes import Class1
from classes import Class2
# Both classes are declared in the same file.
# I don't know if that can be a problem #
# ... #
def foo(parameter)
if (type(parameter) == type(Class1()):
# ... #
elif (type(parameter) == type(Class2()):
# ... #
And as type(parameter) returns <type 'instance'> and type(Class1()) is <type 'instance'> as well, it turns out that even if the parameter is an instance of Class2, it is going into the first comparison...
By the way, str(parameter.__class__) properly shows classes.Class1 . I guess I could always use that, but I would like to understand what's going on... I have made tenths of comparisons like this and all them worked properly...
Thank you!! :)
A:
Old-style classes do that. Derive your classes from object in their definitions.
A:
you should really use isinstance:
In [26]: def foo(param):
....: print type(param)
....: print isinstance(param, Class1)
....:
In [27]: foo(x)
<type 'instance'>
True
Type is better for built-in types.
A:
The fact that type(x) returns the same type object for all instances x of legacy, aka old-style, classes, is one of many infuriating defects of those kinds of classes -- unfortunately they have to stay (and be the default for a class without base) in Python 2.* for reasons of backwards compatibility.
Nevertheless, don't use old-style classes unless you're forced to maintain a bunch of old, legacy code (without a good test suite to give you the confidence to try and switch kind o classes). When a class has no "natural" bases, subclass it from object rather than from nothing. Alternatively, your module, at the top, can set
__metaclass__ = type
which changes the default from the crufty, legacy old-style classes, to the shiny bright new-style ones -- while explicitly inheriting from object is usually preferred ("explicit is better than implicit"), the module-global setting of __metaclass__ may feel "less invasive" to existing old modules where you're switching from old to new classes, so it's offered as a possibility.
| Why type(classInstance) is returning 'instance'? | I have a method that accepts a parameter that can be of several types, and has to do one thing or other depending on the type, but if I check the type of said parameter, I don't get the 'real' type, I always get <type 'instance'>, and that is messing up with my comparisons.
I have something like:
from classes import Class1
from classes import Class2
# Both classes are declared in the same file.
# I don't know if that can be a problem #
# ... #
def foo(parameter)
if (type(parameter) == type(Class1()):
# ... #
elif (type(parameter) == type(Class2()):
# ... #
And as type(parameter) returns <type 'instance'> and type(Class1()) is <type 'instance'> as well, it turns out that even if the parameter is an instance of Class2, it is going into the first comparison...
By the way, str(parameter.__class__) properly shows classes.Class1 . I guess I could always use that, but I would like to understand what's going on... I have made tenths of comparisons like this and all them worked properly...
Thank you!! :)
| [
"Old-style classes do that. Derive your classes from object in their definitions.\n",
"you should really use isinstance:\nIn [26]: def foo(param):\n ....: print type(param)\n ....: print isinstance(param, Class1)\n ....:\n\nIn [27]: foo(x)\n<type 'instance'>\nTrue\n\nType is better for built-in types.\n",
"The fact that type(x) returns the same type object for all instances x of legacy, aka old-style, classes, is one of many infuriating defects of those kinds of classes -- unfortunately they have to stay (and be the default for a class without base) in Python 2.* for reasons of backwards compatibility.\nNevertheless, don't use old-style classes unless you're forced to maintain a bunch of old, legacy code (without a good test suite to give you the confidence to try and switch kind o classes). When a class has no \"natural\" bases, subclass it from object rather than from nothing. Alternatively, your module, at the top, can set\n__metaclass__ = type\n\nwhich changes the default from the crufty, legacy old-style classes, to the shiny bright new-style ones -- while explicitly inheriting from object is usually preferred (\"explicit is better than implicit\"), the module-global setting of __metaclass__ may feel \"less invasive\" to existing old modules where you're switching from old to new classes, so it's offered as a possibility.\n"
] | [
16,
10,
9
] | [] | [] | [
"class",
"instance",
"python",
"types"
] | stackoverflow_0003110624_class_instance_python_types.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.