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: Could use some help with this soundex coding The US census bureau uses a special encoding called “soundex” to locate information about a person. The soundex is an encoding of surnames (last names) based on the way a surname sounds rather than the way it is spelled. Surnames that sound the same, but are spelled differently, like SMITH and SMYTH, have the same code and are filed together. The soundex coding system was developed so that you can find a surname even though it may have been recorded under various spellings. In this lab you will design, code, and document a program that produces the soundex code when input with a surname. A user will be prompted for a surname, and the program should output the corresponding code. Basic Soundex Coding Rules Every soundex encoding of a surname consists of a letter and three numbers. The letter used is always the first letter of the surname. The numbers are assigned to the remaining letters of the surname according to the soundex guide shown below. Zeroes are added at the end if necessary to always produce a four-character code. Additional letters are disregarded. Soundex Coding Guide Soundex assigns a number for various consonants. Consonants that sound alike are assigned the same number: Number Consonants 1 B, F, P, V 2 C, G, J, K, Q, S, X, Z 3 D, T 4 L 5 M, N 6 R Soundex disregards the letters A, E, I, O, U, H, W, and Y. There are 3 additional Soundex Coding Rules that are followed. A good program design would implement these each as one or more separate functions. Rule 1. Names With Double Letters If the surname has any double letters, they should be treated as one letter. For example: Gutierrez is coded G362 (G, 3 for the T, 6 for the first R, second R ignored, 2 for the Z). Rule 2. Names with Letters Side-by-Side that have the Same Soundex Code Number If the surname has different letters side-by-side that have the same number in the soundex coding guide, they should be treated as one letter. Examples: Pfister is coded as P236 (P, F ignored since it is considered same as P, 2 for the S, 3 for the T, 6 for the R). Jackson is coded as J250 (J, 2 for the C, K ignored same as C, S ignored same as C, 5 for the N, 0 added). Rule 3. Consonant Separators 3.a. If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Example: Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded. 3.b. If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right is not coded. Example: *Ashcraft is coded A261 (A, 2 for the S, C ignored since same as S with H in between, 6 for the R, 1 for the F). It is not coded A226. So far this is my code: surname = raw_input("Please enter surname:") outstring = "" outstring = outstring + surname[0] for i in range (1, len(surname)): nextletter = surname[i] if nextletter in ['B','F','P','V']: outstring = outstring + '1' elif nextletter in ['C','G','J','K','Q','S','X','Z']: outstring = outstring + '2' elif nextletter in ['D','T']: outstring = outstring + '3' elif nextletter in ['L']: outstring = outstring + '4' elif nextletter in ['M','N']: outstring = outstring + '5' elif nextletter in ['R']: outstring = outstring + '6' print outstring The code sufficiently does what it is asked to, I am just not sure how to code the three rules. That is where I need help. So, any help is appreciated. A: A few hints: By using an array where each Soundex code is stored and indexed by the ASCII value (or a value in a shorter numeric range derived thereof) of the letter it corresponds to, you will both make the code for efficient and more readable. This is a very common technique: understand, use and reuse ;-) As you parse the input string, you need keep track of (or compare with) the letter previously handled to ignore repeating letters, and handle other the rules. (implement each of these these in a separate function as hinted in the write-up). The idea could be to introduce a function in charge of -maybe- adding the soundex code for the current letter of the input being processed. This function would in turn call each of the "rules" functions, possibly quiting early based on the return values of some rules. In other words, replace the systematic... outstring = outstring + c # btw could be += ...with outstring += AppendCodeIfNeeded(c) beware that this multi-function structure is overkill for such trivial logic, but it is not a bad idea to do it for practice. A: Here are some small hints on general Python stuff. 0) You can use a for loop to loop over any sequence, and a string counts as a sequence. So you can write: for nextletter in surname[1:]: # do stuff This is easier to write and easier to understand than computing an index and indexing the surname. 1) You can use the += operator to append strings. Instead of x = x + 'a' you can write x += 'a' As for help with your specific problem, you will want to keep track of the previous letter. If your assignment had a rule that said "two 'z' characters in a row should be coded as 99" you could add code like this: def rule_two_z(prevletter, curletter): if prevletter.lower() == 'z' and curletter.lower() == 'z': return 99 else: return -1 prevletter = surname[0] for curletter in surname[1:]: code = rule_two_z(prevletter, curletter) if code < 0: # do something else here outstring += str(code) prevletter = curletter Hmmm, you were writing your code to return string integers like '3', while I wrote my code to return an actual integer and then call str() on it before adding it to the string. Either way is probably fine. Good luck!
Could use some help with this soundex coding
The US census bureau uses a special encoding called “soundex” to locate information about a person. The soundex is an encoding of surnames (last names) based on the way a surname sounds rather than the way it is spelled. Surnames that sound the same, but are spelled differently, like SMITH and SMYTH, have the same code and are filed together. The soundex coding system was developed so that you can find a surname even though it may have been recorded under various spellings. In this lab you will design, code, and document a program that produces the soundex code when input with a surname. A user will be prompted for a surname, and the program should output the corresponding code. Basic Soundex Coding Rules Every soundex encoding of a surname consists of a letter and three numbers. The letter used is always the first letter of the surname. The numbers are assigned to the remaining letters of the surname according to the soundex guide shown below. Zeroes are added at the end if necessary to always produce a four-character code. Additional letters are disregarded. Soundex Coding Guide Soundex assigns a number for various consonants. Consonants that sound alike are assigned the same number: Number Consonants 1 B, F, P, V 2 C, G, J, K, Q, S, X, Z 3 D, T 4 L 5 M, N 6 R Soundex disregards the letters A, E, I, O, U, H, W, and Y. There are 3 additional Soundex Coding Rules that are followed. A good program design would implement these each as one or more separate functions. Rule 1. Names With Double Letters If the surname has any double letters, they should be treated as one letter. For example: Gutierrez is coded G362 (G, 3 for the T, 6 for the first R, second R ignored, 2 for the Z). Rule 2. Names with Letters Side-by-Side that have the Same Soundex Code Number If the surname has different letters side-by-side that have the same number in the soundex coding guide, they should be treated as one letter. Examples: Pfister is coded as P236 (P, F ignored since it is considered same as P, 2 for the S, 3 for the T, 6 for the R). Jackson is coded as J250 (J, 2 for the C, K ignored same as C, S ignored same as C, 5 for the N, 0 added). Rule 3. Consonant Separators 3.a. If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Example: Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded. 3.b. If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right is not coded. Example: *Ashcraft is coded A261 (A, 2 for the S, C ignored since same as S with H in between, 6 for the R, 1 for the F). It is not coded A226. So far this is my code: surname = raw_input("Please enter surname:") outstring = "" outstring = outstring + surname[0] for i in range (1, len(surname)): nextletter = surname[i] if nextletter in ['B','F','P','V']: outstring = outstring + '1' elif nextletter in ['C','G','J','K','Q','S','X','Z']: outstring = outstring + '2' elif nextletter in ['D','T']: outstring = outstring + '3' elif nextletter in ['L']: outstring = outstring + '4' elif nextletter in ['M','N']: outstring = outstring + '5' elif nextletter in ['R']: outstring = outstring + '6' print outstring The code sufficiently does what it is asked to, I am just not sure how to code the three rules. That is where I need help. So, any help is appreciated.
[ "A few hints:\n\nBy using an array where each Soundex code is stored and indexed by the ASCII value (or a value in a shorter numeric range derived thereof) of the letter it corresponds to, you will both make the code for efficient and more readable. This is a very common technique: understand, use and reuse ;-)\nAs you parse the input string, you need keep track of (or compare with) the letter previously handled to ignore repeating letters, and handle other the rules. (implement each of these these in a separate function as hinted in the write-up). The idea could be to introduce a function in charge of -maybe- adding the soundex code for the current letter of the input being processed. This function would in turn call each of the \"rules\" functions, possibly quiting early based on the return values of some rules. In other words, replace the systematic...\n\n\n outstring = outstring + c # btw could be +=\n...with\n outstring += AppendCodeIfNeeded(c)\n\n\nbeware that this multi-function structure is overkill for such trivial logic, but it is not a bad idea to do it for practice.\n\n", "Here are some small hints on general Python stuff.\n0) You can use a for loop to loop over any sequence, and a string counts as a sequence. So you can write:\nfor nextletter in surname[1:]:\n # do stuff\n\nThis is easier to write and easier to understand than computing an index and indexing the surname.\n1) You can use the += operator to append strings. Instead of\nx = x + 'a'\n\nyou can write\nx += 'a'\n\nAs for help with your specific problem, you will want to keep track of the previous letter. If your assignment had a rule that said \"two 'z' characters in a row should be coded as 99\" you could add code like this:\ndef rule_two_z(prevletter, curletter):\n if prevletter.lower() == 'z' and curletter.lower() == 'z':\n return 99\n else:\n return -1\n\n\nprevletter = surname[0]\nfor curletter in surname[1:]:\n code = rule_two_z(prevletter, curletter)\n if code < 0:\n # do something else here\n outstring += str(code)\n prevletter = curletter\n\nHmmm, you were writing your code to return string integers like '3', while I wrote my code to return an actual integer and then call str() on it before adding it to the string. Either way is probably fine.\nGood luck!\n" ]
[ 0, 0 ]
[]
[]
[ "python", "soundex" ]
stackoverflow_0001562438_python_soundex.txt
Q: Python - Overwriting __getattribute__ for an instance? This one seems a bit tricky to me. Sometime ago I already managed to overwrite an instance's method with something like: def my_method(self, attr): pass instancemethod = type(self.method_to_overwrite) self.method_to_overwrite = instancemethod(my_method, self, self.__class__) which worked very well for me; but now I'm trying to overwrite an instance's __getattribute__() function, which doesn't work for me for the reason the method seems to be <type 'method-wrapper'> Is it possible to do anything about that? I couldn't find any decent Python documentation on method-wrapper. A: You want to override the attribute lookup algorithm on an per instance basis? Without knowing why you are trying to do this, I would hazard a guess that there is a cleaner less convoluted way of doing what you need to do. If you really need to then as Aaron said, you'll need to install a redirecting __getattribute__ handler on the class because Python looks up special methods only on the class, ignoring anything defined on the instance. You also have to be extra careful about not getting into infinite recursion: class FunkyAttributeLookup(object): def __getattribute__(self, key): try: # Lookup the per instance function via objects attribute lookup # to avoid infinite recursion. getter = object.__getattribute__(self, 'instance_getattribute') return getter(key) except AttributeError: return object.__getattribute__(self, key) f = FunkyAttributeLookup() f.instance_getattribute = lambda attr: attr.upper() print(f.foo) # FOO Also, if you are overriding methods on your instance, you don't need to instanciate the method object yourself, you can either use the descriptor protocol on functions that generates the methods or just curry the self argument. #descriptor protocol self.method_to_overwrite = my_method.__get__(self, type(self)) # or curry from functools import partial self.method_to_overwrite = partial(my_method, self) A: You can't overwrite special methods at instance level. For new-style classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary. A: There are a couple of methods which you can't overwrite and __getattribute__() is one of them. A: I believe method-wrapper is a wrapper around a method written in C.
Python - Overwriting __getattribute__ for an instance?
This one seems a bit tricky to me. Sometime ago I already managed to overwrite an instance's method with something like: def my_method(self, attr): pass instancemethod = type(self.method_to_overwrite) self.method_to_overwrite = instancemethod(my_method, self, self.__class__) which worked very well for me; but now I'm trying to overwrite an instance's __getattribute__() function, which doesn't work for me for the reason the method seems to be <type 'method-wrapper'> Is it possible to do anything about that? I couldn't find any decent Python documentation on method-wrapper.
[ "You want to override the attribute lookup algorithm on an per instance basis? Without knowing why you are trying to do this, I would hazard a guess that there is a cleaner less convoluted way of doing what you need to do. If you really need to then as Aaron said, you'll need to install a redirecting __getattribute__ handler on the class because Python looks up special methods only on the class, ignoring anything defined on the instance.\nYou also have to be extra careful about not getting into infinite recursion:\nclass FunkyAttributeLookup(object):\n def __getattribute__(self, key):\n try:\n # Lookup the per instance function via objects attribute lookup\n # to avoid infinite recursion.\n getter = object.__getattribute__(self, 'instance_getattribute')\n return getter(key)\n except AttributeError:\n return object.__getattribute__(self, key)\n\nf = FunkyAttributeLookup()\nf.instance_getattribute = lambda attr: attr.upper()\nprint(f.foo) # FOO\n\nAlso, if you are overriding methods on your instance, you don't need to instanciate the method object yourself, you can either use the descriptor protocol on functions that generates the methods or just curry the self argument.\n #descriptor protocol\n self.method_to_overwrite = my_method.__get__(self, type(self))\n # or curry\n from functools import partial\n self.method_to_overwrite = partial(my_method, self)\n\n", "You can't overwrite special methods at instance level. For new-style classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.\n", "There are a couple of methods which you can't overwrite and __getattribute__() is one of them.\n", "I believe method-wrapper is a wrapper around a method written in C. \n" ]
[ 6, 4, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001560853_django_python.txt
Q: How to encrypt text into a image using python I was wondering how can someone use python to encrypt text into an image. A: Google search for "python steganography" and you find some stuff. Here's a Python library module: stepic
How to encrypt text into a image using python
I was wondering how can someone use python to encrypt text into an image.
[ "Google search for \"python steganography\" and you find some stuff.\nHere's a Python library module: stepic\n" ]
[ 7 ]
[]
[]
[ "python", "steganography" ]
stackoverflow_0001562664_python_steganography.txt
Q: How to make complex contains queries in Django? I need to make query like this: WHERE Comment like '%ev% 3628%' or Comment like '%ew% 3628%' the number '3628' is a parametr. So I've tried in my view: First try: wherestr = "Comment like '%%ev%% %s%%' or Comment like '%%ew%% %s%%'" % (rev_number, rev_number) comment_o = Issuecomments.objects.extra(where=[wherestr]) but I've got: TypeError at /comments_by_rev/3628/ not enough arguments for format string Request Method: GET Request URL: http://127.0.0.1:8001/comments_by_rev/3628/ Exception Type: TypeError Exception Value: not enough arguments for format string Second try: comment = IssuetrackerIssuecomments.objects.filter(Q(comment__contains=rev_number), Q(comment__contains='ew') | Q(comment__contains='ev')) but its not excactly the same. Have you people of wisdom any idea how to accomplish this? A: You need something similar to this: from django.db.models import Q def myview(request): query = "hi" #string to search for items = self.filter(Q(comment__contains=query) | Q(comment__contains=query)) ... Just make sure the query string is properly escaped. A: You almost got it right... The problem is that your % are being subsituted twice. Django actually has a way of passing parameters in the extra clause like this wherestr = "Comment like '%%ev%% %s%%' or Comment like '%%ew%% %s%%'" params = (rev_number, rev_number) comment_o = Issuecomments.objects.extra(where=[wherestr], params=[params]) This is a better way of passing the parameters as it won't leave you open to SQL injection attacks like your way will. A: Take a look at http://docs.djangoproject.com/en/dev/ref/models/querysets/, specifically icontains: Case-insensitive containment test. Example: Entry.objects.get(headline__icontains='Lennon') SQL equivalent: SELECT ... WHERE headline ILIKE '%Lennon%'; Since you're looking for a pattern like %%ev%% or %%ew%%, consider the IREGEX or REGEX versions as well? Lastly, consider performing the search differently...perhaps parse out the interesting parts of the message and put them in their own indexed columns for querying later. You'll regret doing this search once the table gets large:).
How to make complex contains queries in Django?
I need to make query like this: WHERE Comment like '%ev% 3628%' or Comment like '%ew% 3628%' the number '3628' is a parametr. So I've tried in my view: First try: wherestr = "Comment like '%%ev%% %s%%' or Comment like '%%ew%% %s%%'" % (rev_number, rev_number) comment_o = Issuecomments.objects.extra(where=[wherestr]) but I've got: TypeError at /comments_by_rev/3628/ not enough arguments for format string Request Method: GET Request URL: http://127.0.0.1:8001/comments_by_rev/3628/ Exception Type: TypeError Exception Value: not enough arguments for format string Second try: comment = IssuetrackerIssuecomments.objects.filter(Q(comment__contains=rev_number), Q(comment__contains='ew') | Q(comment__contains='ev')) but its not excactly the same. Have you people of wisdom any idea how to accomplish this?
[ "You need something similar to this:\nfrom django.db.models import Q\n\ndef myview(request):\n query = \"hi\" #string to search for\n items = self.filter(Q(comment__contains=query) | Q(comment__contains=query))\n ...\n\nJust make sure the query string is properly escaped.\n", "You almost got it right... The problem is that your % are being subsituted twice. Django actually has a way of passing parameters in the extra clause like this\nwherestr = \"Comment like '%%ev%% %s%%' or Comment like '%%ew%% %s%%'\"\nparams = (rev_number, rev_number)\ncomment_o = Issuecomments.objects.extra(where=[wherestr], params=[params])\n\nThis is a better way of passing the parameters as it won't leave you open to SQL injection attacks like your way will.\n", "Take a look at http://docs.djangoproject.com/en/dev/ref/models/querysets/, specifically\nicontains: Case-insensitive containment test.\nExample: Entry.objects.get(headline__icontains='Lennon')\nSQL equivalent: SELECT ... WHERE headline ILIKE '%Lennon%';\nSince you're looking for a pattern like %%ev%% or %%ew%%, consider the IREGEX or REGEX versions as well?\nLastly, consider performing the search differently...perhaps parse out the interesting parts of the message and put them in their own indexed columns for querying later. You'll regret doing this search once the table gets large:).\n" ]
[ 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001557850_django_python.txt
Q: Python procedure return values In Python it's possible to create a procedure that has no explicit return. i.e.: def test(val): if 0 == val: return 8 Further, it's possible to assign the results of that function to a variable: >>> a = test(7) >>> print `a` 'None' Why the heck is that? What language logic is behind that baffling design decision? Why doesn't that simply raise a compiler error? EDIT: Yes, I realise that it works that way. Thanks. My question is WHY? It seems like such a sure fire way to introduce subtle bugs into your code. And it seems, as was mentioned below by e-satis, to go against the very wise pythonic adage that "explicit is better then implicit". So, what's up with this? Is it just a design oversight or a simplifying assumption or a deliberate, considered decision? EDIT: Would everyone agree that expressing the intent this way is much better: def test(val): if 0 == val: return 8 else: return None If so, why would Python prefer the former style to raising a compile time exception? EDIT: S.Lott brings up the point explicitly (and others do too, his just seems most clear to me) that this behaviour is a result of the fact that Python is a dynamic language and therefor can't check at compile time, the run time behaviour of the system. Since there is no distinction between procedures (those functions that return no values) and functions (those that do), that there is nothing to enforce at compile time. Which means that when we come to run-time behaviour, we either have a catastrophic failure in some cases (we throw an exception) or we silently fail assuming that the programmer knew what they were doing and understood the default behaviour. The pythonic way is to do the latter, the C-style way is to do the former. That seems to make sense as a good reason to do it that way. S.Lott's clear justification is buried in the comments to the accepted answer so I thought it best to summarise here. I'll hold off on accepting the answer for a bit to see if S.Lott makes an official answer. Otherwise, I'll give the points to SilentGhost. A: While every function might not have an explicit return it will have an implicit one, that is None, which incidentally is a normal Python object. Further, functions often return None explicitly. I suppose returning None implicitly is just an ease-of-use optimisation. P.S. I wonder what you propose compile would do in the following case: def t(): if True: return 'ham' P.P.S. return statement indicates that something needs to be returned, be it None, 42 or 'spam'. Some functions, however, don't really return anything, like list.sort or __init__, therefore it would be an overhead to require a return None statement at the end of each __init__. A: Python never checks for human misbehavior. The language philosophy is to assume that programmers are grown up adults and know what they are doing. Since : Python is an autodocumented language, so you'll know in a blink what returns a function; Python uses duck typing, so getting None by default can ease dynamic function call a lot. Returning None make more senss than raising an error. E.G : function_stack = [func1, func2, func3] for f in function_stack : a = f() if a is not None : # do something No matter if f is f() is a function or a procedure. There is no such thing in Python. You can apply all the function, and process output if there is any. A: Heh. Coming at it from a Java perspective, your question is obvious. It should throw an error. But if you came at it from a Perl perspective, it's not obvious at all. You're setting a variable to no value, big deal. It's all about the typing. Like Java, Python is strongly typed, but unlike Java, it is also dynamically typed. Most dynamically typed languages allow shenanigans like this. A: It's beautiful ... It returns None in the case where val != 0 which to me make sense. Python 2.6.1 (r261:67515, Jun 18 2009, 17:24:16) [GCC 3.3.3 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def test(val): ... if 0 == val: ... return 8 ... >>> a = test(8) >>> print a None >>> print test(0) 8 >>> Do you have any arguments why you think the behavior is wrong? You can use c++ if you need strong compile time type checking but for python it seems extremely flexible and I assume that's what you want when you selected python for your task. A: What compiler? The bytecode compiler checks your code for syntax on import, but syntax doesn't include "check all paths for a return". So when test() gets called at runtime, and the value of x isn't 0 and we just fall out of the function, what should we do? return 0? Why not -1, or "", or -infinity? So a nice neutral value should always be returned in the absence of an explicit return statement - and that value is None. This is a standard feature of the language - welcome to Python! A: It's because of the dynamic typing. You don't have to make the distinction between, say, turbo pascal's procedure and function. They are all function, they return None by default, which is logically correct. If you don't say anything it returns nothing, None. I hope it make more sense now-
Python procedure return values
In Python it's possible to create a procedure that has no explicit return. i.e.: def test(val): if 0 == val: return 8 Further, it's possible to assign the results of that function to a variable: >>> a = test(7) >>> print `a` 'None' Why the heck is that? What language logic is behind that baffling design decision? Why doesn't that simply raise a compiler error? EDIT: Yes, I realise that it works that way. Thanks. My question is WHY? It seems like such a sure fire way to introduce subtle bugs into your code. And it seems, as was mentioned below by e-satis, to go against the very wise pythonic adage that "explicit is better then implicit". So, what's up with this? Is it just a design oversight or a simplifying assumption or a deliberate, considered decision? EDIT: Would everyone agree that expressing the intent this way is much better: def test(val): if 0 == val: return 8 else: return None If so, why would Python prefer the former style to raising a compile time exception? EDIT: S.Lott brings up the point explicitly (and others do too, his just seems most clear to me) that this behaviour is a result of the fact that Python is a dynamic language and therefor can't check at compile time, the run time behaviour of the system. Since there is no distinction between procedures (those functions that return no values) and functions (those that do), that there is nothing to enforce at compile time. Which means that when we come to run-time behaviour, we either have a catastrophic failure in some cases (we throw an exception) or we silently fail assuming that the programmer knew what they were doing and understood the default behaviour. The pythonic way is to do the latter, the C-style way is to do the former. That seems to make sense as a good reason to do it that way. S.Lott's clear justification is buried in the comments to the accepted answer so I thought it best to summarise here. I'll hold off on accepting the answer for a bit to see if S.Lott makes an official answer. Otherwise, I'll give the points to SilentGhost.
[ "While every function might not have an explicit return it will have an implicit one, that is None, which incidentally is a normal Python object. Further, functions often return None explicitly.\nI suppose returning None implicitly is just an ease-of-use optimisation.\nP.S. I wonder what you propose compile would do in the following case:\ndef t():\n if True:\n return 'ham'\n\nP.P.S. return statement indicates that something needs to be returned, be it None, 42 or 'spam'. Some functions, however, don't really return anything, like list.sort or __init__, therefore it would be an overhead to require a return None statement at the end of each __init__.\n", "Python never checks for human misbehavior. The language philosophy is to assume that programmers are grown up adults and know what they are doing.\nSince :\n\nPython is an autodocumented language, so you'll know in a blink what returns a function;\nPython uses duck typing, so getting None by default can ease dynamic function call a lot.\n\nReturning None make more senss than raising an error.\nE.G : \nfunction_stack = [func1, func2, func3]\nfor f in function_stack :\n a = f()\n if a is not None :\n # do something\n\nNo matter if f is f() is a function or a procedure. There is no such thing in Python. You can apply all the function, and process output if there is any.\n", "Heh. Coming at it from a Java perspective, your question is obvious. It should throw an error.\nBut if you came at it from a Perl perspective, it's not obvious at all. You're setting a variable to no value, big deal.\nIt's all about the typing. Like Java, Python is strongly typed, but unlike Java, it is also dynamically typed. Most dynamically typed languages allow shenanigans like this.\n", "It's beautiful ...\nIt returns None in the case where val != 0 which to me make sense.\nPython 2.6.1 (r261:67515, Jun 18 2009, 17:24:16)\n[GCC 3.3.3 (SuSE Linux)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> def test(val):\n... if 0 == val:\n... return 8\n...\n>>> a = test(8)\n>>> print a\nNone\n>>> print test(0)\n8\n>>>\n\nDo you have any arguments why you think the behavior is wrong?\nYou can use c++ if you need strong compile time type checking but for python it seems extremely flexible and I assume that's what you want when you selected python for your task.\n", "What compiler? The bytecode compiler checks your code for syntax on import, but syntax doesn't include \"check all paths for a return\". So when test() gets called at runtime, and the value of x isn't 0 and we just fall out of the function, what should we do? return 0? Why not -1, or \"\", or -infinity? So a nice neutral value should always be returned in the absence of an explicit return statement - and that value is None. This is a standard feature of the language - welcome to Python!\n", "It's because of the dynamic typing.\nYou don't have to make the distinction between, say, turbo pascal's procedure and function. They are all function, they return None by default, which is logically correct. If you don't say anything it returns nothing, None.\nI hope it make more sense now-\n" ]
[ 28, 12, 8, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001563074_python.txt
Q: URLs stored in database for Django site I've produced a few Django sites but up until now I have been mapping individual views and URLs in urls.py. Now I've tried to create a small custom CMS but I'm having trouble with the URLs. I have a database table (SQLite3) which contains code for the pages like a column for header, one for right menu, one for content.... so on, so on. I also have a column for the URL. How do I get Django to call the information in the database table from the URL stored in the column rather than having to code a view and the URL for every page (which obviously defeats the purpose of a CMS)? If someone can just point me at the right part of the docs or a site which explains this it would help a lot. Thanks all. A: You dont have to to it in the flatpage-way For models, that should be addressable, I do this: In urls.py I have a url-mapping like url(r'(?P<slug>[a-z1-3_]{1,})/$','cms.views.category_view', name="category-view") in this case the regular expression (?P<slug>[a-z1-3_]{1,}) will return a variable called slug and send it to my view cms.views.category_view. In that view I query like this: @render_to('category.html') def category_view(request, slug): return {'cat':Category.objects.get(slug=slug)} (Note: I am using the annoying-decorator render_to – it is the same as render_to_response, just shorter) Edit This should be covered by the tutorial. Here you find the url-configuration and dispatching in every detail. The djangobook also covers it. And check pythons regex module. Of course you can use this code. A: Your question is a little bit twisted, but I think what you're asking for is something similar to how django.contrib.flatpages handles this. Basically it uses middleware to catch the 404 error and then looks to see if any of the flatpages have a URL field that matches. We did this on one site where all of the URLs were made "search engine friendly". We overrode the save() method, munged the title into this_is_the_title.html (or whatever) and then stored that in a separate table that had a URL => object class/id mapping.ng (this means it is listed before flatpages in the middleware list).
URLs stored in database for Django site
I've produced a few Django sites but up until now I have been mapping individual views and URLs in urls.py. Now I've tried to create a small custom CMS but I'm having trouble with the URLs. I have a database table (SQLite3) which contains code for the pages like a column for header, one for right menu, one for content.... so on, so on. I also have a column for the URL. How do I get Django to call the information in the database table from the URL stored in the column rather than having to code a view and the URL for every page (which obviously defeats the purpose of a CMS)? If someone can just point me at the right part of the docs or a site which explains this it would help a lot. Thanks all.
[ "You dont have to to it in the flatpage-way\nFor models, that should be addressable, I do this:\nIn urls.py I have a url-mapping like\n url(r'(?P<slug>[a-z1-3_]{1,})/$','cms.views.category_view', name=\"category-view\")\n\nin this case the regular expression (?P<slug>[a-z1-3_]{1,}) will return a variable called slug and send it to my view cms.views.category_view. In that view I query like this:\n@render_to('category.html')\ndef category_view(request, slug):\n return {'cat':Category.objects.get(slug=slug)}\n\n(Note: I am using the annoying-decorator render_to – it is the same as render_to_response, just shorter)\nEdit This should be covered by the tutorial. Here you find the url-configuration and dispatching in every detail. The djangobook also covers it. And check pythons regex module.\nOf course you can use this code. \n", "Your question is a little bit twisted, but I think what you're asking for is something similar to how django.contrib.flatpages handles this. Basically it uses middleware to catch the 404 error and then looks to see if any of the flatpages have a URL field that matches.\nWe did this on one site where all of the URLs were made \"search engine friendly\". We overrode the save() method, munged the title into this_is_the_title.html (or whatever) and then stored that in a separate table that had a URL => object class/id mapping.ng (this means it is listed before flatpages in the middleware list).\n" ]
[ 6, 1 ]
[]
[]
[ "content_management_system", "database", "django", "python", "url" ]
stackoverflow_0001563088_content_management_system_database_django_python_url.txt
Q: Python library/framework to write an application that sends emails periodically I am considering to write an application that would covert the comments in reddit threads (example) to emails. The idea is to parse the reddit json data (example) and send new comments as plain EMails to subscribed users. One of the users can be gmane, so you can also read the comments over there. The motivation for writing this tool is to read reddit comments in our favorite EMail client (with filters and what not) without having to refresh the reddit thread. Which library/framework is best suited for this task? To get it done faster? With minimal code? A: I would go with AppEngine to tackle this: integrated cron + email support. A: I've used Flexget to parse RSS feeds and email them. You can get ideas from there. A: Lamson aims to be an 'email app framework' (taking after the recent developments in web app frameworks). It seems like it would be a good fit for the problem you describe.
Python library/framework to write an application that sends emails periodically
I am considering to write an application that would covert the comments in reddit threads (example) to emails. The idea is to parse the reddit json data (example) and send new comments as plain EMails to subscribed users. One of the users can be gmane, so you can also read the comments over there. The motivation for writing this tool is to read reddit comments in our favorite EMail client (with filters and what not) without having to refresh the reddit thread. Which library/framework is best suited for this task? To get it done faster? With minimal code?
[ "I would go with AppEngine to tackle this: integrated cron + email support.\n", "I've used Flexget to parse RSS feeds and email them.\nYou can get ideas from there.\n", "Lamson aims to be an 'email app framework' (taking after the recent developments in web app frameworks). It seems like it would be a good fit for the problem you describe.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "email", "frameworks", "python", "reddit" ]
stackoverflow_0001563468_email_frameworks_python_reddit.txt
Q: Install custom modules in a python virtual enviroment I am doing some pylons work in a virtual python enviorment, I want to use MySQL with SQLalchemy but I can't install the MySQLdb module on my virtual enviorment, I can't use easyinstall because I am using a version that was compiled for python 2.6 in a .exe format, I tried running the install from inside the virtual enviorment but that did not work, any sugestions? A: Ok Got it all figured out, After I installed the module on my normal python 2.6 install I went into my Python26 folder and low and behold I happened to find a file called MySQL-python-wininst which happened to be a list of all of the installed module files. Basicly it was two folders called MySQLdb and another called MySQL_python-1.2.2-py2.6.egg-info as well as three other files: _mysql.pyd, _mysql_exceptions.py, _mysql_exceptions.pyc. So I went into the folder where they were located (Python26/Lib/site-packages) and copied them to virtualenv's site-packages folder (env/Lib/site-packages) and the module was fully functional! Note: All paths are the defaults
Install custom modules in a python virtual enviroment
I am doing some pylons work in a virtual python enviorment, I want to use MySQL with SQLalchemy but I can't install the MySQLdb module on my virtual enviorment, I can't use easyinstall because I am using a version that was compiled for python 2.6 in a .exe format, I tried running the install from inside the virtual enviorment but that did not work, any sugestions?
[ "Ok Got it all figured out, After I installed the module on my normal python 2.6 install I went into my Python26 folder and low and behold I happened to find a file called MySQL-python-wininst which happened to be a list of all of the installed module files. Basicly it was two folders called MySQLdb and another called MySQL_python-1.2.2-py2.6.egg-info as well as three other files: _mysql.pyd, _mysql_exceptions.py, _mysql_exceptions.pyc. So I went into the folder where they were located (Python26/Lib/site-packages) and copied them to virtualenv's site-packages folder (env/Lib/site-packages) and the module was fully functional!\nNote: All paths are the defaults\n" ]
[ 0 ]
[]
[]
[ "module", "mysql", "pylons", "python", "virtualenv" ]
stackoverflow_0001557972_module_mysql_pylons_python_virtualenv.txt
Q: Retrieving and displaying UTF-8 from a .CSV in Python Basically I have been having real fun with this today. I have this data file called test.csv which is encoded as UTF-8: "Nguyễn", 0.500 "Trần", 0.250 "Lê", 0.250 Now I am attempting to read it with this code and it displays all funny like this: Trần Now I have gone through all the Python docs for 2.6 which is the one I use and I can't get the wrapper to work along with all the ideas on the internet which I am assuming are all very correct just not being applied properly by yours truly. On the plus side I have learnt that not all fonts will display those characters correctly anyway something I hadn't even thought of previously and have learned a lot about Unicode etc so it certainly was not wasted time. If anyone could point out where I went wrong I would be most grateful. Here is the code updated as per request below that returns this error - Traceback (most recent call last): File "surname_generator.py", line 39, in probfamilynames = [(familyname,float(prob)) for familyname,prob in unicode_csv_reader(open(familynamelist))] File "surname_generator.py", line 27, in unicode_csv_reader for row in csv_reader: File "surname_generator.py", line 33, in utf_8_encoder yield line.encode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128) from random import random import csv class ChooseFamilyName(object): def __init__(self, probs): self._total_prob = 0. self._familyname_levels = [] for familyname, prob in probs: self._total_prob += prob self._familyname_levels.append((self._total_prob, familyname)) return def pickfamilyname(self): pickfamilyname = self._total_prob * random() for level, familyname in self._familyname_levels: if level >= pickfamilyname: return familyname print "pickfamilyname error" return def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs): csv_reader = csv.reader(utf_8_encoder(unicode_csv_data), dialect=dialect, **kwargs) for row in csv_reader: # decode UTF-8 back to Unicode, cell by cell: yield [unicode(cell, 'utf-8') for cell in row] def utf_8_encoder(unicode_csv_data): for line in unicode_csv_data: yield line.encode('utf-8') familynamelist = 'familyname_vietnam.csv' a = 0 while a < 10: a = a + 1 probfamilynames = [(familyname,float(prob)) for familyname,prob in unicode_csv_reader(open(familynamelist))] familynamepicker = ChooseFamilyName(probfamilynames) print(familynamepicker.pickfamilyname()) A: unicode_csv_reader(open(familynamelist)) is trying to pass non-unicode data (byte strings with utf-8 encoding) to a function you wrote expecting unicode data. You could solve the problem with codecs.open (from standard library module codecs), but that's to roundabout: the codecs would be doing utf8->unicode for you, then your code would be doing unicode->utf8, what's the point? Instead, define a function more like this one...: def encoded_csv_reader_to_unicode(encoded_csv_data, coding='utf-8', dialect=csv.excel, **kwargs): csv_reader = csv.reader(encoded_csv_data, dialect=dialect, **kwargs) for row in csv_reader: yield [unicode(cell, coding) for cell in row] and use encoded_csv_reader_to_unicode(open(familynamelist)). A: Your current problem is that you have been given a bum steer with the csv_unicode_reader thingy. As the name suggests, and as the documentation states explicitly: """(unicode_csv_reader() below is a generator that wraps csv.reader to handle Unicode CSV data (a list of Unicode strings). """ You don't have unicode strings, you have str strings encoded in UTF-8. Suggestion: blow away the csv_unicode_reader stuff. Get each row plainly and simply as though it was encoded in ascii. Then convert each row to unicode: unicode_row = [field.decode('utf8') for field in str_row] Getting back to your original problem: (1) To get help with fonts etc, you need to say what platform you are running on and what software you are using to display the unicode strings. (2) If you want platform-independent ways of inspecting your data, look at the repr() built-in function, and the name function in the unicodedata module.
Retrieving and displaying UTF-8 from a .CSV in Python
Basically I have been having real fun with this today. I have this data file called test.csv which is encoded as UTF-8: "Nguyễn", 0.500 "Trần", 0.250 "Lê", 0.250 Now I am attempting to read it with this code and it displays all funny like this: Trần Now I have gone through all the Python docs for 2.6 which is the one I use and I can't get the wrapper to work along with all the ideas on the internet which I am assuming are all very correct just not being applied properly by yours truly. On the plus side I have learnt that not all fonts will display those characters correctly anyway something I hadn't even thought of previously and have learned a lot about Unicode etc so it certainly was not wasted time. If anyone could point out where I went wrong I would be most grateful. Here is the code updated as per request below that returns this error - Traceback (most recent call last): File "surname_generator.py", line 39, in probfamilynames = [(familyname,float(prob)) for familyname,prob in unicode_csv_reader(open(familynamelist))] File "surname_generator.py", line 27, in unicode_csv_reader for row in csv_reader: File "surname_generator.py", line 33, in utf_8_encoder yield line.encode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128) from random import random import csv class ChooseFamilyName(object): def __init__(self, probs): self._total_prob = 0. self._familyname_levels = [] for familyname, prob in probs: self._total_prob += prob self._familyname_levels.append((self._total_prob, familyname)) return def pickfamilyname(self): pickfamilyname = self._total_prob * random() for level, familyname in self._familyname_levels: if level >= pickfamilyname: return familyname print "pickfamilyname error" return def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs): csv_reader = csv.reader(utf_8_encoder(unicode_csv_data), dialect=dialect, **kwargs) for row in csv_reader: # decode UTF-8 back to Unicode, cell by cell: yield [unicode(cell, 'utf-8') for cell in row] def utf_8_encoder(unicode_csv_data): for line in unicode_csv_data: yield line.encode('utf-8') familynamelist = 'familyname_vietnam.csv' a = 0 while a < 10: a = a + 1 probfamilynames = [(familyname,float(prob)) for familyname,prob in unicode_csv_reader(open(familynamelist))] familynamepicker = ChooseFamilyName(probfamilynames) print(familynamepicker.pickfamilyname())
[ "unicode_csv_reader(open(familynamelist)) is trying to pass non-unicode data (byte strings with utf-8 encoding) to a function you wrote expecting unicode data. You could solve the problem with codecs.open (from standard library module codecs), but that's to roundabout: the codecs would be doing utf8->unicode for you, then your code would be doing unicode->utf8, what's the point?\nInstead, define a function more like this one...:\ndef encoded_csv_reader_to_unicode(encoded_csv_data,\n coding='utf-8',\n dialect=csv.excel,\n **kwargs):\n csv_reader = csv.reader(encoded_csv_data,\n dialect=dialect,\n **kwargs)\n for row in csv_reader:\n yield [unicode(cell, coding) for cell in row]\n\nand use encoded_csv_reader_to_unicode(open(familynamelist)).\n", "Your current problem is that you have been given a bum steer with the csv_unicode_reader thingy. As the name suggests, and as the documentation states explicitly: \n\"\"\"(unicode_csv_reader() below is a generator that wraps csv.reader to handle Unicode CSV data (a list of Unicode strings). \"\"\"\nYou don't have unicode strings, you have str strings encoded in UTF-8.\nSuggestion: blow away the csv_unicode_reader stuff. Get each row plainly and simply as though it was encoded in ascii. Then convert each row to unicode:\nunicode_row = [field.decode('utf8') for field in str_row]\n\nGetting back to your original problem:\n(1) To get help with fonts etc, you need to say what platform you are running on and what software you are using to display the unicode strings.\n(2) If you want platform-independent ways of inspecting your data, look at the repr() built-in function, and the name function in the unicodedata module.\n" ]
[ 1, 0 ]
[ "There's the unicode_csv_reader demo in the python docs:\nhttp://docs.python.org/library/csv.html\n" ]
[ -2 ]
[ "csv", "python", "utf_8" ]
stackoverflow_0001561833_csv_python_utf_8.txt
Q: Bundle additional executables with py2exe I have a python script that calls out to two Sysinternals tools (sigcheck and accesschk). Is there a way I can bundle these executables into a py2exe so that subprocess.Popen can see it when it runs? Full explanation: My script is made to execute over a network share (S:\share\my_script.exe) and it makes hundreds of calls to sigcheck and accesscheck. If sigcheck and accesschk also reside on the server, they seem to get transferred to the host, called once, transferred the the host again, called a second time, on and on until the almost 400-500 calls are complete. I can probably fall back to copying these two executables to the host (C:) and then deleting them when I'm done... how would you solve this problem? A: I could be wrong about this, but I don't believe this is what py2exe was intended for. It's more about what you're distributing than about how you're distributing. I think what you may be looking for is the option to create a windows installer. You could probably add the executables as data files or scripts using distutils. arggg Why can't my data_files just get bundled into the zipfile? I've started using paver for this kind of thing. It makes it really easy to override commands or create new commands that will allow you to put some new files into the sdist.
Bundle additional executables with py2exe
I have a python script that calls out to two Sysinternals tools (sigcheck and accesschk). Is there a way I can bundle these executables into a py2exe so that subprocess.Popen can see it when it runs? Full explanation: My script is made to execute over a network share (S:\share\my_script.exe) and it makes hundreds of calls to sigcheck and accesscheck. If sigcheck and accesschk also reside on the server, they seem to get transferred to the host, called once, transferred the the host again, called a second time, on and on until the almost 400-500 calls are complete. I can probably fall back to copying these two executables to the host (C:) and then deleting them when I'm done... how would you solve this problem?
[ "I could be wrong about this, but I don't believe this is what py2exe was intended for. It's more about what you're distributing than about how you're distributing. I think what you may be looking for is the option to create a windows installer. You could probably add the executables as data files or scripts using distutils.\n\narggg Why can't my data_files just get bundled into the zipfile?\n\nI've started using paver for this kind of thing. It makes it really easy to override commands or create new commands that will allow you to put some new files into the sdist.\n" ]
[ 2 ]
[]
[]
[ "bundle", "executable", "py2exe", "python" ]
stackoverflow_0001563948_bundle_executable_py2exe_python.txt
Q: List of tuples to Numpy recarray Given a list of tuples, where each tuple represents a row in a table, e.g. tab = [('a',1),('b',2)] Is there an easy way to convert this to a record array? I tried np.recarray(tab,dtype=[('name',str),('value',int)]) which doesn't seem to work. A: try np.rec.fromrecords(tab) rec.array([('a', 1), ('b', 2)], dtype=[('f0', '|S1'), ('f1', '<i4')])
List of tuples to Numpy recarray
Given a list of tuples, where each tuple represents a row in a table, e.g. tab = [('a',1),('b',2)] Is there an easy way to convert this to a record array? I tried np.recarray(tab,dtype=[('name',str),('value',int)]) which doesn't seem to work.
[ "try\nnp.rec.fromrecords(tab)\n\nrec.array([('a', 1), ('b', 2)], \n dtype=[('f0', '|S1'), ('f1', '<i4')])\n\n" ]
[ 4 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001564000_numpy_python.txt
Q: Performance difference on insert-sort in C and python I was curious about the performance of insert-sort using C and python but the results I've got just make me think if I've done something wrong. I suspected that C would be faster, but not that much. I've profiled both codes and the insert-sort function is the place where the time is most spent. Here is the C function: void insert_sort (vec_t * vec) { int j; for (j = 1 ; j < vec->n ; j++){ int key = vec->v[j]; int i = j - 1; while (i >= 0 && vec->v[i] > key){ vec->v[i+1] = vec->v[i]; i--; } vec->v[i+1] = key; } } Here is the python function: def insert_sort (ln): for j in range(1, len(ln)): key = ln[j] i = j-1 while i >= 0 and ln[i] > key: ln[i+1] = ln[i] i-=1 ln[i+1] = key The test was made with 10000 integers, each one randomly generated between 0 and 10000. The results for the time spent in each function was: C time: 0.13 seconds python time: 8.104 seconds Am I doing something wrong here? Like I said, I expected to see the C code being faster, but not that faster. I don't want to use built-in functions or whatsoever. I would like to implement the algorithm. Is there a pythonic way to doing things that I could use in the insert-sort? A: Python is a dynamic language and the standard implementation uses an interpreter to evaluate code. This means that where the compiled C code can escape with a single machine instruction, for instance assigning to vec->v[i+1], Python's interpreter has to look up the sequence variable from the local scope, look up its class, find the item setting method on the class, call that method. Similarly for the compare, addition. Not to mention that executing almost every bytecode results in an indirect branch mispredict in the CPU that causes a pipeline bubble. This is the sort of code that would benefit a lot from JIT compilation to native code and runtime type specialization, like unladen-swallow and PyPy are starting to do. Otherwise the code is pretty much pythonic in the sense that if one needs to implement insertion sort, this is how one would do it in Python. It's also very unpythonic because you should use the very efficient built-in sort. A: My first thought was that the laptop I have at hand right now, a Macbook Pro, must be comparable to but slightly better than your machine -- I don't have enough of your surrounding code to try your C example (what's a vec_t, etc, etc), but running the Python you coded gives me: $ python -mtimeit -s'import inso' 'inso.insort(inso.li)' 10 loops, best of 3: 7.21 msec per loop vs your 8.1 seconds. That's with you code put in insort.py, preceded by: import random li = [random.randrange(10000) for _ in xrange(10000)] array doesn't help -- actually slows things down a bit. Then I installed psyco, the Python JIT helper (x86-only, 32-bit only), further added: import psyco psyco.full() and got: $ python -mtimeit -s'import inso' 'inso.insort(inso.li)' 10 loops, best of 3: 207 usec per loop so a speedup of about 7.21 / 0.000207 = 34830 times -- vs the 8.04 / 0.13 = 62 times that surprised you so much;-). Of course, the problem is that after the first time, the list is already sorted, so insort becomes must faster. You didn't give us enough of the surrounding test harness to know exactly what you measured. A more realisting example (where the actual list isn't touched so it stays disordered, only a copy is sorted...), without psyco: $ python -mtimeit -s'import inso' 'inso.insort(list(inso.li))' 10 loops, best of 3: 13.8 sec per loop Oops -- so your machine's WAY faster than a Macbook Pro (remembers, core don't count: we're using only one here;-) -- wow... or else, you're mismeasuring. Anyway, WITH psyco: $ python -mtimeit -s'import inso' 'inso.insort(list(inso.li))' 10 loops, best of 3: 456 msec per loop So psyco's speedup is only 13.8 / 0.456, 30 times -- about half as much as the 60+ times you get with pure-C coding. IOW, you'd expect python + psyco to be twice as slow as pure C. That's a more realistic and typical assessment. If you we writing reasonably high-level code, psyco's speedup of it would degrade from (say) 30 times down to much less -- but so would C's advantage over Python. For example, $ python -mtimeit -s'import inso' 'sorted(inso.li)' 100 loops, best of 3: 8.72 msec per loop without psyco (in this case, psyco actually -- marginally -- slows down the execution;-), so that's another factor of 52 over psyco, 1582 overall over non-psyco insort. But, when for some reason or other you have to write extremely low-level algorithms in python, rather than using the wealth of support from the builtins and stdlib, psyco can help reduce the pain. Another point is, when you benchmark, please post ALL code so others can see exactly what you're doing (and possibly spot gotchas) -- your "scaffolding" is as tricky and likely to hide traps, as the code you think you're measuring!-) A: So, here are some lessons you should take away from this: Interpreted Python is on the slow side. Don't try to write your own FFT, MPEG encoder, etc. in Python. Even slow interpreted Python is probably fast enough for small problems. An 8 second run time is not horrible, and it would take you much longer to write and debug the C than the Python, so if you are writing something to run once, Python wins. For speed in Python, try to rely on built-in features and C modules. Let someone else's C code do the heavy lifting. I worked on an embedded device where we did our work in Python; despite the slow embedded processor, the performance was decent, because C library modules were doing most of the work. For fun and education, please repeat your Python test, this time using the built-in .sort() method on a list; it probably won't be quite as fast as the C, but it will be close. (Although for really large data sets, it will beat the C, because insertion sort sucks. If you rewrote the C to use the C library qsort() function, that would be the speed champ.) A common Python design "pattern" is: first, write your app in Python. If it is fast enough, stop; you are done. Second, try to rewrite to improve speed; see if there is a C module you can use, for example. If it is still not fast enough, consider writing your own C module; or, write a C program, using the Python prototype code as the basis for your design. A: What method did you use to measure the time? Doing this sort of thing, I find python is at least 30 times slower than C The C compiler may be able to use some optimisations that Python doesn't even attempt If might be interesting to try psyco, that type of code is well suited to it. building on Alex's answer, I tried cython. In his case cython turns the for loop and everything into pure C, so now I can compare C, python and psyco now i have this insort.py import psyco import random li = [random.randrange(10000) for _ in xrange(10000)] def insort (ln): for j in range(1, len(ln)): key = ln[j] i = j-1 while i >= 0 and ln[i] > key: ln[i+1] = ln[i] i-=1 ln[i+1] = key #psyco.bind(insort) import pyximport; pyximport.install() import pyxinsort def pyx_setup(): pyxinsort.setup(li) def pyx_insort(): pyxinsort.insort(li) and this pyxinsort.pyx cdef int ln[10000] def insort(li): cdef int i,j,key for j in range(1, len(li)): key = ln[j] i = j-1 while i >= 0 and ln[i] > key: ln[i+1] = ln[i] i-=1 ln[i+1] = key def setup(li): cdef int i for i in range(1, len(li)): ln[i]=li[i] The code for insort is virtually identical. li is passed in for its length. ln is the array that is sorted and is prepopulated by setup, so I can isolate building the list from the sort python $ python2.5 -mtimeit -s'import inso' 'list(inso.li)' 10000 loops, best of 3: 84.5 usec per loop $ python2.5 -mtimeit -s'import inso' 'inso.insort(list(inso.li))' 10 loops, best of 3: 21.9 sec per loop psyco $ python2.5 -mtimeit -s'import inso' 'list(inso.li)' 10000 loops, best of 3: 85.6 usec per loop $ python2.5 -mtimeit -s'import inso' 'inso.insort(list(inso.li))' 10 loops, best of 3: 578 msec per loop cython ( this is running exactly the same algorithm converted to C and compiled ) $ python2.5 -mtimeit -s'import inso' 'inso.pyx_setup()' 10000 loops, best of 3: 141 usec per loop $ python2.5 -mtimeit -s'import inso' 'inso.pyx_setup();inso.pyx_insort()' 10 loops, best of 3: 46.6 msec per loop cython beats psyco by a factor of 16 and Python by a factor of 470! For completeness, i've included the corresponding piece of C code generated by cython for (__pyx_v_j = 1; __pyx_v_j < __pyx_1; __pyx_v_j+=1) { __pyx_v_key = (__pyx_v_9pyxinsort_ln[__pyx_v_j]); __pyx_v_i = (__pyx_v_j - 1); while (1) { __pyx_2 = (__pyx_v_i >= 0); if (__pyx_2) { __pyx_2 = ((__pyx_v_9pyxinsort_ln[__pyx_v_i]) > __pyx_v_key); } if (!__pyx_2) break; (__pyx_v_9pyxinsort_ln[(__pyx_v_i + 1)]) = (__pyx_v_9pyxinsort_ln[__pyx_v_i]); __pyx_v_i -= 1; } (__pyx_v_9pyxinsort_ln[(__pyx_v_i + 1)]) = __pyx_v_key; }
Performance difference on insert-sort in C and python
I was curious about the performance of insert-sort using C and python but the results I've got just make me think if I've done something wrong. I suspected that C would be faster, but not that much. I've profiled both codes and the insert-sort function is the place where the time is most spent. Here is the C function: void insert_sort (vec_t * vec) { int j; for (j = 1 ; j < vec->n ; j++){ int key = vec->v[j]; int i = j - 1; while (i >= 0 && vec->v[i] > key){ vec->v[i+1] = vec->v[i]; i--; } vec->v[i+1] = key; } } Here is the python function: def insert_sort (ln): for j in range(1, len(ln)): key = ln[j] i = j-1 while i >= 0 and ln[i] > key: ln[i+1] = ln[i] i-=1 ln[i+1] = key The test was made with 10000 integers, each one randomly generated between 0 and 10000. The results for the time spent in each function was: C time: 0.13 seconds python time: 8.104 seconds Am I doing something wrong here? Like I said, I expected to see the C code being faster, but not that faster. I don't want to use built-in functions or whatsoever. I would like to implement the algorithm. Is there a pythonic way to doing things that I could use in the insert-sort?
[ "Python is a dynamic language and the standard implementation uses an interpreter to evaluate code. This means that where the compiled C code can escape with a single machine instruction, for instance assigning to vec->v[i+1], Python's interpreter has to look up the sequence variable from the local scope, look up its class, find the item setting method on the class, call that method. Similarly for the compare, addition. Not to mention that executing almost every bytecode results in an indirect branch mispredict in the CPU that causes a pipeline bubble.\nThis is the sort of code that would benefit a lot from JIT compilation to native code and runtime type specialization, like unladen-swallow and PyPy are starting to do.\nOtherwise the code is pretty much pythonic in the sense that if one needs to implement insertion sort, this is how one would do it in Python. It's also very unpythonic because you should use the very efficient built-in sort.\n", "My first thought was that the laptop I have at hand right now, a Macbook Pro, must be comparable to but slightly better than your machine -- I don't have enough of your surrounding code to try your C example (what's a vec_t, etc, etc), but running the Python you coded gives me:\n$ python -mtimeit -s'import inso' 'inso.insort(inso.li)'\n10 loops, best of 3: 7.21 msec per loop\n\nvs your 8.1 seconds. That's with you code put in insort.py, preceded by:\nimport random\nli = [random.randrange(10000) for _ in xrange(10000)]\n\narray doesn't help -- actually slows things down a bit. Then I installed psyco, the Python JIT helper (x86-only, 32-bit only), further added:\nimport psyco\npsyco.full()\n\nand got:\n$ python -mtimeit -s'import inso' 'inso.insort(inso.li)'\n10 loops, best of 3: 207 usec per loop\n\nso a speedup of about 7.21 / 0.000207 = 34830 times -- vs the 8.04 / 0.13 = 62 times that surprised you so much;-).\nOf course, the problem is that after the first time, the list is already sorted, so insort becomes must faster. You didn't give us enough of the surrounding test harness to know exactly what you measured. A more realisting example (where the actual list isn't touched so it stays disordered, only a copy is sorted...), without psyco:\n$ python -mtimeit -s'import inso' 'inso.insort(list(inso.li))'\n10 loops, best of 3: 13.8 sec per loop\n\nOops -- so your machine's WAY faster than a Macbook Pro (remembers, core don't count: we're using only one here;-) -- wow... or else, you're mismeasuring. Anyway, WITH psyco:\n$ python -mtimeit -s'import inso' 'inso.insort(list(inso.li))'\n10 loops, best of 3: 456 msec per loop\n\nSo psyco's speedup is only 13.8 / 0.456, 30 times -- about half as much as the 60+ times you get with pure-C coding. IOW, you'd expect python + psyco to be twice as slow as pure C. That's a more realistic and typical assessment.\nIf you we writing reasonably high-level code, psyco's speedup of it would degrade from (say) 30 times down to much less -- but so would C's advantage over Python. For example,\n$ python -mtimeit -s'import inso' 'sorted(inso.li)'\n100 loops, best of 3: 8.72 msec per loop\n\nwithout psyco (in this case, psyco actually -- marginally -- slows down the execution;-), so that's another factor of 52 over psyco, 1582 overall over non-psyco insort.\nBut, when for some reason or other you have to write extremely low-level algorithms in python, rather than using the wealth of support from the builtins and stdlib, psyco can help reduce the pain.\nAnother point is, when you benchmark, please post ALL code so others can see exactly what you're doing (and possibly spot gotchas) -- your \"scaffolding\" is as tricky and likely to hide traps, as the code you think you're measuring!-)\n", "So, here are some lessons you should take away from this:\n\nInterpreted Python is on the slow side. Don't try to write your own FFT, MPEG encoder, etc. in Python.\nEven slow interpreted Python is probably fast enough for small problems. An 8 second run time is not horrible, and it would take you much longer to write and debug the C than the Python, so if you are writing something to run once, Python wins.\nFor speed in Python, try to rely on built-in features and C modules. Let someone else's C code do the heavy lifting. I worked on an embedded device where we did our work in Python; despite the slow embedded processor, the performance was decent, because C library modules were doing most of the work.\n\nFor fun and education, please repeat your Python test, this time using the built-in .sort() method on a list; it probably won't be quite as fast as the C, but it will be close. (Although for really large data sets, it will beat the C, because insertion sort sucks. If you rewrote the C to use the C library qsort() function, that would be the speed champ.)\nA common Python design \"pattern\" is: first, write your app in Python. If it is fast enough, stop; you are done. Second, try to rewrite to improve speed; see if there is a C module you can use, for example. If it is still not fast enough, consider writing your own C module; or, write a C program, using the Python prototype code as the basis for your design.\n", "What method did you use to measure the time?\nDoing this sort of thing, I find python is at least 30 times slower than C\nThe C compiler may be able to use some optimisations that Python doesn't even attempt \nIf might be interesting to try psyco, that type of code is well suited to it.\nbuilding on Alex's answer, I tried cython. In his case cython turns the for loop and everything into pure C, so now I can compare C, python and psyco \nnow i have this insort.py\n\nimport psyco\nimport random\nli = [random.randrange(10000) for _ in xrange(10000)]\n\ndef insort (ln):\n for j in range(1, len(ln)):\n key = ln[j]\n i = j-1\n while i >= 0 and ln[i] > key:\n ln[i+1] = ln[i]\n i-=1\n ln[i+1] = key\n\n#psyco.bind(insort)\n\nimport pyximport; pyximport.install()\nimport pyxinsort\n\ndef pyx_setup():\n pyxinsort.setup(li)\n\ndef pyx_insort():\n pyxinsort.insort(li)\n\n\nand this pyxinsort.pyx\n\ncdef int ln[10000]\n\ndef insort(li):\n cdef int i,j,key\n for j in range(1, len(li)):\n key = ln[j]\n i = j-1\n while i >= 0 and ln[i] > key:\n ln[i+1] = ln[i]\n i-=1\n ln[i+1] = key\n\ndef setup(li):\n cdef int i\n for i in range(1, len(li)):\n ln[i]=li[i]\n\n\nThe code for insort is virtually identical. li is passed in for its length. ln is the array that is sorted and is prepopulated by setup, so I can isolate building the list from the sort\npython\n\n$ python2.5 -mtimeit -s'import inso' 'list(inso.li)'\n10000 loops, best of 3: 84.5 usec per loop\n$ python2.5 -mtimeit -s'import inso' 'inso.insort(list(inso.li))'\n10 loops, best of 3: 21.9 sec per loop\n\npsyco\n\n$ python2.5 -mtimeit -s'import inso' 'list(inso.li)'\n10000 loops, best of 3: 85.6 usec per loop\n$ python2.5 -mtimeit -s'import inso' 'inso.insort(list(inso.li))'\n10 loops, best of 3: 578 msec per loop\n\ncython ( this is running exactly the same algorithm converted to C and compiled )\n\n$ python2.5 -mtimeit -s'import inso' 'inso.pyx_setup()'\n10000 loops, best of 3: 141 usec per loop\n$ python2.5 -mtimeit -s'import inso' 'inso.pyx_setup();inso.pyx_insort()'\n10 loops, best of 3: 46.6 msec per loop\n\ncython beats psyco by a factor of 16 and Python by a factor of 470!\nFor completeness, i've included the corresponding piece of C code generated by cython\n\n for (__pyx_v_j = 1; __pyx_v_j < __pyx_1; __pyx_v_j+=1) {\n __pyx_v_key = (__pyx_v_9pyxinsort_ln[__pyx_v_j]);\n __pyx_v_i = (__pyx_v_j - 1);\n while (1) {\n __pyx_2 = (__pyx_v_i >= 0);\n if (__pyx_2) {\n __pyx_2 = ((__pyx_v_9pyxinsort_ln[__pyx_v_i]) > __pyx_v_key);\n }\n if (!__pyx_2) break;\n (__pyx_v_9pyxinsort_ln[(__pyx_v_i + 1)]) = (__pyx_v_9pyxinsort_ln[__pyx_v_i]);\n __pyx_v_i -= 1;\n }\n (__pyx_v_9pyxinsort_ln[(__pyx_v_i + 1)]) = __pyx_v_key;\n }\n\n" ]
[ 13, 5, 4, 2 ]
[ "What's wrong with:\nln.sort()\n\n" ]
[ -3 ]
[ "c", "performance", "profiling", "python" ]
stackoverflow_0001561596_c_performance_profiling_python.txt
Q: non-blocking read/log from an http stream I have a client that connects to an HTTP stream and logs the text data it consumes. I send the streaming server an HTTP GET request... The server replies and continuously publishes data... It will either publish text or send a ping (text) message regularly... and will never close the connection. I need to read and log the data it consumes in a non-blocking manner. I am doing something like this: import urllib2 req = urllib2.urlopen(url) for dat in req: with open('out.txt', 'a') as f: f.write(dat) My questions are: will this ever block when the stream is continuous? how much data is read in each chunk and can it be specified/tuned? is this the best way to read/log an http stream? A: Hey, that's three questions in one! ;-) It could block sometimes - even if your server is generating data quite quickly, network bottlenecks could in theory cause your reads to block. Reading the URL data using "for dat in req" will mean reading a line at a time - not really useful if you're reading binary data such as an image. You get better control if you use chunk = req.read(size) which can of course block. Whether it's the best way depends on specifics not available in your question. For example, if you need to run with no blocking calls whatever, you'll need to consider a framework like Twisted. If you don't want blocking to hold you up and don't want to use Twisted (which is a whole new paradigm compared to the blocking way of doing things), then you can spin up a thread to do the reading and writing to file, while your main thread goes on its merry way: def func(req): #code the read from URL stream and write to file here ... t = threading.Thread(target=func) t.start() # will execute func in a separate thread ... t.join() # will wait for spawned thread to die Obviously, I've omitted error checking/exception handling etc. but hopefully it's enough to give you the picture. A: You're using too high-level an interface to have good control about such issues as blocking and buffering block sizes. If you're not willing to go all the way to an async interface (in which case twisted, already suggested, is hard to beat!), why not httplib, which is after all in the standard library? HTTPResponse instance .read(amount) method is more likely to block for no longer than needed to read amount bytes, than the similar method on the object returned by urlopen (although admittedly there are no documented specs about that on either module, hmmm...). A: Another option is to use the socket module directly. Establish a connection, send the HTTP request, set the socket to non-blocking mode, and then read the data with socket.recv() handling 'Resource temporarily unavailable' exceptions (which means that there is nothing to read). A very rough example is this: import socket, time BUFSIZE = 1024 s = socket.socket() s.connect(('localhost', 1234)) s.send('GET /path HTTP/1.0\n\n') s.setblocking(False) running = True while running: try: print "Attempting to read from socket..." while True: data = s.recv(BUFSIZE) if len(data) == 0: # remote end closed print "Remote end closed" running = False break print "Received %d bytes: %r" % (len(data), data) except socket.error, e: if e[0] != 11: # Resource temporarily unavailable print e raise # perform other program tasks print "Sleeping..." time.sleep(1) However, urllib.urlopen() has some benefits if the web server redirects, you need URL based basic authentication etc. You could make use of the select module which will tell you when there is data to read. A: Yes when you catch up with the server it will block until the server produces more data Each dat will be one line including the newline on the end twisted is a good option I would swap the with and for around in your example, do you really want to open and close the file for every line that arrives?
non-blocking read/log from an http stream
I have a client that connects to an HTTP stream and logs the text data it consumes. I send the streaming server an HTTP GET request... The server replies and continuously publishes data... It will either publish text or send a ping (text) message regularly... and will never close the connection. I need to read and log the data it consumes in a non-blocking manner. I am doing something like this: import urllib2 req = urllib2.urlopen(url) for dat in req: with open('out.txt', 'a') as f: f.write(dat) My questions are: will this ever block when the stream is continuous? how much data is read in each chunk and can it be specified/tuned? is this the best way to read/log an http stream?
[ "Hey, that's three questions in one! ;-)\nIt could block sometimes - even if your server is generating data quite quickly, network bottlenecks could in theory cause your reads to block.\nReading the URL data using \"for dat in req\" will mean reading a line at a time - not really useful if you're reading binary data such as an image. You get better control if you use\nchunk = req.read(size)\n\nwhich can of course block.\nWhether it's the best way depends on specifics not available in your question. For example, if you need to run with no blocking calls whatever, you'll need to consider a framework like Twisted. If you don't want blocking to hold you up and don't want to use Twisted (which is a whole new paradigm compared to the blocking way of doing things), then you can spin up a thread to do the reading and writing to file, while your main thread goes on its merry way:\ndef func(req):\n #code the read from URL stream and write to file here\n\n...\n\nt = threading.Thread(target=func)\nt.start() # will execute func in a separate thread\n...\nt.join() # will wait for spawned thread to die\n\nObviously, I've omitted error checking/exception handling etc. but hopefully it's enough to give you the picture.\n", "You're using too high-level an interface to have good control about such issues as blocking and buffering block sizes. If you're not willing to go all the way to an async interface (in which case twisted, already suggested, is hard to beat!), why not httplib, which is after all in the standard library? HTTPResponse instance .read(amount) method is more likely to block for no longer than needed to read amount bytes, than the similar method on the object returned by urlopen (although admittedly there are no documented specs about that on either module, hmmm...). \n", "Another option is to use the socket module directly. Establish a connection, send the HTTP request, set the socket to non-blocking mode, and then read the data with socket.recv() handling 'Resource temporarily unavailable' exceptions (which means that there is nothing to read). A very rough example is this:\nimport socket, time\n\nBUFSIZE = 1024\n\ns = socket.socket()\ns.connect(('localhost', 1234))\ns.send('GET /path HTTP/1.0\\n\\n')\ns.setblocking(False)\n\nrunning = True\n\nwhile running:\n try:\n print \"Attempting to read from socket...\"\n while True:\n data = s.recv(BUFSIZE)\n if len(data) == 0: # remote end closed\n print \"Remote end closed\"\n running = False\n break\n print \"Received %d bytes: %r\" % (len(data), data)\n except socket.error, e:\n if e[0] != 11: # Resource temporarily unavailable\n print e\n raise\n\n # perform other program tasks\n print \"Sleeping...\"\n time.sleep(1)\n\nHowever, urllib.urlopen() has some benefits if the web server redirects, you need URL based basic authentication etc. You could make use of the select module which will tell you when there is data to read.\n", "Yes when you catch up with the server it will block until the server produces more data\nEach dat will be one line including the newline on the end\ntwisted is a good option\nI would swap the with and for around in your example, do you really want to open and close the file for every line that arrives?\n" ]
[ 6, 3, 2, 1 ]
[]
[]
[ "http", "logging", "python", "urllib2" ]
stackoverflow_0001557175_http_logging_python_urllib2.txt
Q: How does the Jinja2 "recursive" tag actually work? I'm trying to write a very simple, tree-walking template in jinja2, using some custom objects with overloaded special methods (getattr, getitem, etc) It seems straightforward, and the equivalent python walk of the tree works fine, but there's something about the way that Jinja's recursion works that I don't understand. The code is shown below: from jinja2 import Template class Category(object): def __init__(self, name): self.name = name self.items = {} self.children = True def __iter__(self): return iter(self.items) def add(self, key, item): self.items[key] = item return item def __getitem__(self, item): return self.items[item] def __getattr__(self, attr): try: return self.items[attr] except KeyError: raise AttributeError(attr) def __str__(self): return "<Category '%s'>" % self.name template = ''' <saved_data> {% for key in category recursive %} {% set item = category[key] %} {% if item.children %} <category name="{{key}}"> {{ loop(item) }} </category> {% else %} <item name="{{ key }}" value="{{ item }}" /> {% endif %} {% endfor %} </saved_data> ''' b = Category('root') c = b.add("numbers", Category('numbers')) c.add("one", 1) c.add("two", 2) c.add("three", 3) d = b.add("letters", Category('letters')) d.add('ay','a') d.add('bee','b') d.add('cee','c') e = d.add("bools", Category('bools')) e.add('tru', True) e.add('fals', False) def walk(c, depth=0): for key in c: item = c[key] print (' '*depth) + str(item) if hasattr(item, 'children'): walk(item, depth+3) print "Python walking the tree:" walk(b) print "" print "Jinja2 Walking the tree:" t = Template(template) print t.render(category = b) The template is raising an exception as if the recursion didn't actually take place. The inner call is made, but somehow the reference to 'category' still refers to the parent. What gives here? There must be something very fundamental I'm missing about how these recursive templates are supposed to work. (Or something very fundamentally silly that I'm doing that I just can't see. A: As I see from your code you understand recursive correctly, except one thing: it does replace iterable in the for statement, but doesn't update variable (category in your code) originally used in it. Thus, you nested loop iterates through children, but set tag lookups in original category, not one passed to the loop(). I suggest changing __iter__() method to return self.items.iteritems() and template to: <saved_data> {% for key, item in category recursive %} {% if item.children %} <category name="{{key}}"> {{ loop(item) }} </category> {% else %} <item name="{{ key }}" value="{{ item }}" /> {% endif %} {% endfor %} </saved_data>
How does the Jinja2 "recursive" tag actually work?
I'm trying to write a very simple, tree-walking template in jinja2, using some custom objects with overloaded special methods (getattr, getitem, etc) It seems straightforward, and the equivalent python walk of the tree works fine, but there's something about the way that Jinja's recursion works that I don't understand. The code is shown below: from jinja2 import Template class Category(object): def __init__(self, name): self.name = name self.items = {} self.children = True def __iter__(self): return iter(self.items) def add(self, key, item): self.items[key] = item return item def __getitem__(self, item): return self.items[item] def __getattr__(self, attr): try: return self.items[attr] except KeyError: raise AttributeError(attr) def __str__(self): return "<Category '%s'>" % self.name template = ''' <saved_data> {% for key in category recursive %} {% set item = category[key] %} {% if item.children %} <category name="{{key}}"> {{ loop(item) }} </category> {% else %} <item name="{{ key }}" value="{{ item }}" /> {% endif %} {% endfor %} </saved_data> ''' b = Category('root') c = b.add("numbers", Category('numbers')) c.add("one", 1) c.add("two", 2) c.add("three", 3) d = b.add("letters", Category('letters')) d.add('ay','a') d.add('bee','b') d.add('cee','c') e = d.add("bools", Category('bools')) e.add('tru', True) e.add('fals', False) def walk(c, depth=0): for key in c: item = c[key] print (' '*depth) + str(item) if hasattr(item, 'children'): walk(item, depth+3) print "Python walking the tree:" walk(b) print "" print "Jinja2 Walking the tree:" t = Template(template) print t.render(category = b) The template is raising an exception as if the recursion didn't actually take place. The inner call is made, but somehow the reference to 'category' still refers to the parent. What gives here? There must be something very fundamental I'm missing about how these recursive templates are supposed to work. (Or something very fundamentally silly that I'm doing that I just can't see.
[ "As I see from your code you understand recursive correctly, except one thing: it does replace iterable in the for statement, but doesn't update variable (category in your code) originally used in it. Thus, you nested loop iterates through children, but set tag lookups in original category, not one passed to the loop(). \nI suggest changing __iter__() method to return self.items.iteritems() and template to:\n<saved_data>\n{% for key, item in category recursive %}\n {% if item.children %}\n <category name=\"{{key}}\">\n {{ loop(item) }}\n </category>\n {% else %}\n <item name=\"{{ key }}\" value=\"{{ item }}\" />\n {% endif %}\n{% endfor %}\n</saved_data>\n\n" ]
[ 8 ]
[]
[]
[ "jinja2", "python", "recursion", "templates" ]
stackoverflow_0001563276_jinja2_python_recursion_templates.txt
Q: python expression for this: max_value = max(firstArray) that is not in secondArray I wasn't sure if there was any good way of doing this. But I thought I'd give stackoverflow a try :) I have a list/array with integers, and a second array also with integers. I want to find the max value from the first list, but the value can not be in the second array. Is there any "fancy" way in python to put this down to one expression? max_value = max(firstArray) that is not in secondArray A: Use sets to get the values in firstArray that are not in secondArray: max_value = max(set(firstArray) - set(secondArray)) A: Here's one way: max_value = [x for x in sorted(first) if x not in second][0] It's less efficient than sorting then using a for loop to test if elements are in the second array, but it fits on one line nicely!
python expression for this: max_value = max(firstArray) that is not in secondArray
I wasn't sure if there was any good way of doing this. But I thought I'd give stackoverflow a try :) I have a list/array with integers, and a second array also with integers. I want to find the max value from the first list, but the value can not be in the second array. Is there any "fancy" way in python to put this down to one expression? max_value = max(firstArray) that is not in secondArray
[ "Use sets to get the values in firstArray that are not in secondArray:\nmax_value = max(set(firstArray) - set(secondArray))\n\n", "Here's one way:\nmax_value = [x for x in sorted(first) if x not in second][0]\n\nIt's less efficient than sorting then using a for loop to test if elements are in the second array, but it fits on one line nicely!\n" ]
[ 12, 1 ]
[]
[]
[ "expression", "python" ]
stackoverflow_0001565095_expression_python.txt
Q: Extracting substrings at specified positions How to extract substrings from a string at specified positions For e.g.: ‘ABCDEFGHIJKLM’. I have To extract the substring from 3 to 6 and 8 to 10. Required output: DEFG, IJK Thanks in advance. A: Here you go myString = 'ABCDEFGHIJKLM' first = myString[3:7] # => DEFG second = myString[8:11] # => IJK In the slicing syntax, the first number is inclusive and the second is excluded. You can read more about String slicing from python docs A: Look into Python's concept called sequence slicing! A: a = "ABCDEFGHIJKLM" print a[3:7], a[8:11] --> DEFG IJK A: s = 'ABCDEFGHIJKLM' print s[3:7] print s[8:11] A: >>> 'ABCDEFGHIJKLM'[3:7] 'DEFG' >>> 'ABCDEFGHIJKLM'[8:11] 'IJK' You might want to read a tutorial or beginners book. A: In alternative you can use operator.itemgetter: >>> import operator >>> s = 'ABCDEFGHIJKLM' >>> f = operator.itemgetter(3,4,5,6,7,8,9,10,11) >>> f(s) ('D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L')
Extracting substrings at specified positions
How to extract substrings from a string at specified positions For e.g.: ‘ABCDEFGHIJKLM’. I have To extract the substring from 3 to 6 and 8 to 10. Required output: DEFG, IJK Thanks in advance.
[ "Here you go\nmyString = 'ABCDEFGHIJKLM'\nfirst = myString[3:7] # => DEFG\nsecond = myString[8:11] # => IJK\n\nIn the slicing syntax, the first number is inclusive and the second is excluded.\nYou can read more about String slicing from python docs\n", "Look into Python's concept called sequence slicing!\n", "a = \"ABCDEFGHIJKLM\"\nprint a[3:7], a[8:11]\n\n--> DEFG IJK\n", "s = 'ABCDEFGHIJKLM'\nprint s[3:7]\nprint s[8:11]\n\n", ">>> 'ABCDEFGHIJKLM'[3:7]\n'DEFG'\n>>> 'ABCDEFGHIJKLM'[8:11]\n'IJK'\n\nYou might want to read a tutorial or beginners book.\n", "In alternative you can use operator.itemgetter:\n>>> import operator\n>>> s = 'ABCDEFGHIJKLM'\n>>> f = operator.itemgetter(3,4,5,6,7,8,9,10,11)\n>>> f(s)\n('D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L')\n\n" ]
[ 8, 3, 3, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001564414_python.txt
Q: How to get multiple properties at the same time? I am using Appscript - a Python interface to AppleScript - in a project of mine that basically gets data from a Mac application. Here is a sample code: asobj = app('Things').to_dos()[0] self.id = asobj.id() self.name = asobj.name() self.status = asobj.status() Every invocation of the properties (id, name, status) does inter-process call and hence it is slow .. especially when you do the same for thousands of the objects. Is there a way to get multiple properties at the same time via AppleScript's Python interface (appscript)? A: I'm not 100% sure how this would be expressed in Python, but most Applescript objects support a "properties" property which will return a dictionary containing key/value pairs for each of the supported properties of that object. I'm guessing that calling asobj.properties() would return an appropriate data structure from which you can then retrieve any individual properties you want. A: If you have a large number of elements, it will be quicker to grab your properties like this: ref = app('Things').to_dos ids = ref.id() names = ref.name() statuses = ref.status() and then use Python's zip() function to rearrange them as needed. The appscript documentation has a chapter on optimisation techniques that explains this in more detail. You should also grab copies of the ASDictionary and ASTranslate tools from the appscript website if you've not already done so. ASTranslate will help you convert application commands from AppleScript to appscript syntax. ASDictionary will export application dictionaries in appscript-style format and also enables appscript's built-in help() method, allowing you to explore application dictionaries interactively (much more powerful than dir()).
How to get multiple properties at the same time?
I am using Appscript - a Python interface to AppleScript - in a project of mine that basically gets data from a Mac application. Here is a sample code: asobj = app('Things').to_dos()[0] self.id = asobj.id() self.name = asobj.name() self.status = asobj.status() Every invocation of the properties (id, name, status) does inter-process call and hence it is slow .. especially when you do the same for thousands of the objects. Is there a way to get multiple properties at the same time via AppleScript's Python interface (appscript)?
[ "I'm not 100% sure how this would be expressed in Python, but most Applescript objects support a \"properties\" property which will return a dictionary containing key/value pairs for each of the supported properties of that object. I'm guessing that calling asobj.properties() would return an appropriate data structure from which you can then retrieve any individual properties you want.\n", "If you have a large number of elements, it will be quicker to grab your properties like this:\nref = app('Things').to_dos\nids = ref.id()\nnames = ref.name()\nstatuses = ref.status()\n\nand then use Python's zip() function to rearrange them as needed. The appscript documentation has a chapter on optimisation techniques that explains this in more detail.\nYou should also grab copies of the ASDictionary and ASTranslate tools from the appscript website if you've not already done so. ASTranslate will help you convert application commands from AppleScript to appscript syntax. ASDictionary will export application dictionaries in appscript-style format and also enables appscript's built-in help() method, allowing you to explore application dictionaries interactively (much more powerful than dir()).\n" ]
[ 3, 0 ]
[]
[]
[ "macos", "py_appscript", "python", "sourceforge_appscript" ]
stackoverflow_0001557910_macos_py_appscript_python_sourceforge_appscript.txt
Q: Python: imports at the beginning of the main program & PEP 8 The PEP 8 recommends that modules be imported at the beginning of programs. Now, I feel that importing some of them at the beginning of the main program (i.e., after if __name__ == '__main__') makes sense. For instance, if the main program reads arguments from the command line, I tend to do import sys at the beginning of the main program: this way, sys does not have to be imported when the code is used as a module, since there is no need, in this case, for command line argument access. How bad is this infringement to PEP 8? should I refrain from doing this? or would it be reasonable to amend PEP 8? A: I can't really tell you how bad this is to do. However, I've greatly improved performance (response time, load) for a web app by importing certain libraries only at the first usage. BTW, the following is also from PEP 8: But most importantly: know when to be inconsistent -- sometimes the style guide just doesn't apply. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask! A: In general I don't think there's much harm in late importing for modules that may not be needed. However sys I would definitely import early, at the top. It's such a common module that it's quite likely you might use sys elsewhere in your script and not notice that it's not always imported. sys is also one of the modules that always gets loaded by Python itself, so you are not saving any module startup time by avoiding the import (not that there's much startup for sys anyway). A: I would recommend you to do what you feel is most appropriate when there is nothing in PEP about your concern. A: Importing sys doesn't really take that long that I would worry about it. Some modules do take longer however. I don't think sys really clogs up the namespace very much. I wouldn't use a variable or class called sys regardless. If you think it's doing more harm than good to have it at the top, by all means do it however you like. PEP 8 is just a guide line and lots of code you see does not conform to it. A: The issue isn't performance. The issue is clarity. Your "main" program is only a main program today. Tomorrow, it may be a library included in some higher-level main program. Later, it will be just one module in a bigger package. Since your "main" program's life may change, you have two responses. Isolate the "main" things inside if __name__ == "__main__". This is not a grotesque violation of PEP-8. This is a reasonable way to package things. Try to limit the number of features in your "main" program scripts. Try to keep them down to imports and the if __name__ == "__main__" stuff. If your main script is small, then your import question goes away.
Python: imports at the beginning of the main program & PEP 8
The PEP 8 recommends that modules be imported at the beginning of programs. Now, I feel that importing some of them at the beginning of the main program (i.e., after if __name__ == '__main__') makes sense. For instance, if the main program reads arguments from the command line, I tend to do import sys at the beginning of the main program: this way, sys does not have to be imported when the code is used as a module, since there is no need, in this case, for command line argument access. How bad is this infringement to PEP 8? should I refrain from doing this? or would it be reasonable to amend PEP 8?
[ "I can't really tell you how bad this is to do.\nHowever, I've greatly improved performance (response time, load) for a web app by importing certain libraries only at the first usage.\nBTW, the following is also from PEP 8:\n\nBut most importantly: know when to be\n inconsistent -- sometimes the style \n guide just doesn't apply. When in\n doubt, use your best judgment. Look\n at other examples and decide what\n looks best. And don't hesitate to\n ask!\n\n", "In general I don't think there's much harm in late importing for modules that may not be needed.\nHowever sys I would definitely import early, at the top. It's such a common module that it's quite likely you might use sys elsewhere in your script and not notice that it's not always imported. sys is also one of the modules that always gets loaded by Python itself, so you are not saving any module startup time by avoiding the import (not that there's much startup for sys anyway).\n", "I would recommend you to do what you feel is most appropriate when there is nothing in PEP about your concern.\n", "Importing sys doesn't really take that long that I would worry about it. Some modules do take longer however.\nI don't think sys really clogs up the namespace very much. I wouldn't use a variable or class called sys regardless.\nIf you think it's doing more harm than good to have it at the top, by all means do it however you like. PEP 8 is just a guide line and lots of code you see does not conform to it.\n", "The issue isn't performance.\nThe issue is clarity.\nYour \"main\" program is only a main program today. Tomorrow, it may be a library included in some higher-level main program. Later, it will be just one module in a bigger package. \nSince your \"main\" program's life may change, you have two responses.\n\nIsolate the \"main\" things inside if __name__ == \"__main__\". This is not a grotesque violation of PEP-8. This is a reasonable way to package things.\nTry to limit the number of features in your \"main\" program scripts. Try to keep them down to imports and the if __name__ == \"__main__\" stuff. If your main script is small, then your import question goes away.\n\n" ]
[ 9, 6, 2, 2, 2 ]
[]
[]
[ "import", "pep", "pep8", "program_entry_point", "python" ]
stackoverflow_0001565173_import_pep_pep8_program_entry_point_python.txt
Q: CMake output name for dynamic-loaded library? I'm trying to write cmake rules to build dynamic-loaded library for python using boost.python on linux. I'd like to use 'foo' for python module name. So, the library must be called foo.so. But by default, cmake uses standard rules for library naming, so if I write add_library(foo foo.cpp) I will get libfoo.so on output. Even set_target_properties(foo PROPERTIES OUTPUT_NAME "foobar") will create libfoobar.so. How to change this behavior? A: You can unset the prefix with this line: set_target_properties(foo PROPERTIES PREFIX "") A: The prefix "lib" is a convention for unix/linux and is exploited widely by compilers (e.g. when you link you write -lfoo). I don't know if you can force cmake to create foo.so instead of libfoo.so, but maybe you can use "libfoo" for python module. Another option is to create install target in cmake ,which will renmae libfoo.so to foo.so
CMake output name for dynamic-loaded library?
I'm trying to write cmake rules to build dynamic-loaded library for python using boost.python on linux. I'd like to use 'foo' for python module name. So, the library must be called foo.so. But by default, cmake uses standard rules for library naming, so if I write add_library(foo foo.cpp) I will get libfoo.so on output. Even set_target_properties(foo PROPERTIES OUTPUT_NAME "foobar") will create libfoobar.so. How to change this behavior?
[ "You can unset the prefix with this line:\nset_target_properties(foo PROPERTIES PREFIX \"\")\n\n", "The prefix \"lib\" is a convention for unix/linux and is exploited widely by compilers (e.g. when you link you write -lfoo). \nI don't know if you can force cmake to create foo.so instead of libfoo.so, but maybe you can use \"libfoo\" for python module. Another option is to create install target in cmake ,which will renmae libfoo.so to foo.so\n" ]
[ 57, 1 ]
[]
[]
[ "boost_python", "cmake", "python", "shared_libraries" ]
stackoverflow_0001564696_boost_python_cmake_python_shared_libraries.txt
Q: python csv help Sometimes I need to parse string that is CSV, but I am having trouble whit quoted comas. As this code demonstrated. I am using python 2.4 import csv for row in csv.reader(['one",f",two,three']): print row i get 4 elements ['one"', 'f"', 'two', 'three'] but I would like to get this ['one", f"', 'two', 'three'] or 3 elements even if I try to use quotechar = '"' option (this is according to documentation default) still the same, how can I ignore coma in quotes? Edit: Thank you all for answers obviously I mistaken my input for CSV, et the end I parsed strig for key values (NAME,DESCR...) This is input NAME: "2801 chassis", DESCR: "2801 chassis, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx A: Actually the result you get is correct—your CSV syntax is wrong. If you want to quote commas or other characters in a CSV value, you have to use quotes surrounding the whole value, not parts of it. If a value does not start with the quote character, Python's CSV implementation does not assume the value is quoted. So, instead of using one",f",two,three you should be using "one,f",two,three A: You can get the csv module to tell you, just feed your desired output into the writer In [1]: import sys,csv In [2]: csv.writer(sys.stdout).writerow(['one", f"', 'two', 'three']) "one"", f""",two,three In [3]: csv.reader(['"one"", f""",two,three']).next() Out[3]: ['one", f"', 'two', 'three'] A: Your input string is not really CSV. Instead your input contains the column name in each row. If your input looks like this: NAME: "2801 chassis", DESCR: "2801 chassis, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx NAME: "2802 wroomer", DESCR: "2802 wroomer, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx NAME: "2803 foobars", DESCR: "2803 foobars, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx The simplest you can do is probably to filter out the column names first, in the whole file. That would then give you a CSV file you can parse. But that assumes each line has the same columns in the same order. However, if the data is not that consistent, you might want to parse it based on the names. Perhaps it looks like this: NAME: "2801 chassis", PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx, DESCR: "2801 chassis, Hw Serial#: xxxxxxx, Hw Revision: 6.0" NAME: "2802 wroomer", DESCR: "2802 wroomer, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx NAME: "2803 foobars", VID: V03 ,PID: CISCO2801 ,SN: xxxxxxxxx Or something. In that case I'd parse each line by looking for the first ':', split out the column head from that, then parse the value (including looking for quotes), and then continue with the rest of the line. Something like this (completely untested code): def parseline(line): result = {} while ':' in line: column, rest = line.split(':',1) column = column.strip() rest = rest.strip() if rest[0] in ('"', '"'): # It's quoted. quotechar = rest[0] end = rest.find(quotechar, 1) # Find the end of the quote value = rest[1:end] end = rest.find(',', end) # Find the next comma else: #Not quoted, just find the next comma: end = rest.find(',', 1) # Find the end of the value value = rest[0:end] result[column] = value line = rest[end+1:] line.strip() return result
python csv help
Sometimes I need to parse string that is CSV, but I am having trouble whit quoted comas. As this code demonstrated. I am using python 2.4 import csv for row in csv.reader(['one",f",two,three']): print row i get 4 elements ['one"', 'f"', 'two', 'three'] but I would like to get this ['one", f"', 'two', 'three'] or 3 elements even if I try to use quotechar = '"' option (this is according to documentation default) still the same, how can I ignore coma in quotes? Edit: Thank you all for answers obviously I mistaken my input for CSV, et the end I parsed strig for key values (NAME,DESCR...) This is input NAME: "2801 chassis", DESCR: "2801 chassis, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx
[ "Actually the result you get is correct—your CSV syntax is wrong.\nIf you want to quote commas or other characters in a CSV value, you have to use quotes surrounding the whole value, not parts of it. If a value does not start with the quote character, Python's CSV implementation does not assume the value is quoted.\nSo, instead of using\none\",f\",two,three\n\nyou should be using\n\"one,f\",two,three\n\n", "You can get the csv module to tell you, just feed your desired output into the writer\nIn [1]: import sys,csv\n\nIn [2]: csv.writer(sys.stdout).writerow(['one\", f\"', 'two', 'three']) \n\"one\"\", f\"\"\",two,three\n\nIn [3]: csv.reader(['\"one\"\", f\"\"\",two,three']).next() \nOut[3]: ['one\", f\"', 'two', 'three']\n\n", "Your input string is not really CSV. Instead your input contains the column name in each row. If your input looks like this:\nNAME: \"2801 chassis\", DESCR: \"2801 chassis, Hw Serial#: xxxxxxx, Hw Revision: 6.0\",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx\nNAME: \"2802 wroomer\", DESCR: \"2802 wroomer, Hw Serial#: xxxxxxx, Hw Revision: 6.0\",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx\nNAME: \"2803 foobars\", DESCR: \"2803 foobars, Hw Serial#: xxxxxxx, Hw Revision: 6.0\",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx\n\nThe simplest you can do is probably to filter out the column names first, in the whole file. That would then give you a CSV file you can parse. But that assumes each line has the same columns in the same order.\nHowever, if the data is not that consistent, you might want to parse it based on the names. Perhaps it looks like this:\nNAME: \"2801 chassis\", PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx, DESCR: \"2801 chassis, Hw Serial#: xxxxxxx, Hw Revision: 6.0\"\nNAME: \"2802 wroomer\", DESCR: \"2802 wroomer, Hw Serial#: xxxxxxx, Hw Revision: 6.0\",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx\nNAME: \"2803 foobars\", VID: V03 ,PID: CISCO2801 ,SN: xxxxxxxxx\n\nOr something. In that case I'd parse each line by looking for the first ':', split out the column head from that, then parse the value (including looking for quotes), and then continue with the rest of the line. Something like this (completely untested code):\ndef parseline(line):\n result = {}\n while ':' in line:\n column, rest = line.split(':',1)\n column = column.strip()\n rest = rest.strip()\n if rest[0] in ('\"', '\"'): # It's quoted.\n quotechar = rest[0]\n end = rest.find(quotechar, 1) # Find the end of the quote\n value = rest[1:end]\n end = rest.find(',', end) # Find the next comma\n else: #Not quoted, just find the next comma:\n end = rest.find(',', 1) # Find the end of the value\n value = rest[0:end]\n result[column] = value\n line = rest[end+1:]\n line.strip()\n return result\n\n" ]
[ 6, 3, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0001565566_csv_python.txt
Q: Python newbie - Understanding class functions If you take the following simple class: class AltString: def __init__(self, str = "", size = 0): self._contents = str self._size = size self._list = [str] def append(self, str): self._list.append(str) def output(self): return "".join(self._list) And I successfully invoke the class instance using: as = AltString("String1") as.append("String2") as.append("String3") When I then invoke the output function using as.output instead of a string being returned, I get the following instead: unbound method AltString.output if I call it using as.output() I get the following error: TypeError: unbound method output() must be called with AltString instance as first argument (got nothing instead) What I am not doing right? A: as is a bad variable name, it is reserved keyword in Python. don't name your variables like this. once you fix it, everything else will be alright. of course you should be doing: alt_str.output() edit: I was able to replicate your error messages when trying to apply output to the class: AltString.output, then: AltString.output(). You should be applying the method to the instance of the class instead. alt_str = AltString('spam') alt_str.output() A: 'as' and 'str' are keywords, don't shadow them by defining variables with the same name. A: Your example is confirmed to work as you expect in python 2.4 >>> from x import * >>> as = AltString("String1") >>> as.append("bubu") >>> >>> as.output() 'String1bubu' In python 2.5 it should also work, but will raise a warning about the use of as, which will become a reserved keyword in python 2.6. I don't really understand why you obtain such error messages. If you are using python 2.6 it should probably produce a syntax error. A: I ran the following code : class AltString: def __init__(self, str = "", size = 0): self._contents = str self._size = size self._list = [str] def append(self, str): self._list.append(str) def output(self): return "".join(self._list) a = AltString("String1") a.append("String2") a.append("String3") print a.output() And it worked perfectly. The only flow I can see is that you use "as", which is a reserved keyword. A: Just tried your code in Python 2.6.2 and the line as = AltString("String1") doesn't work because "as" is a reserved keyword (see here) but if I use another name it works perfectly.
Python newbie - Understanding class functions
If you take the following simple class: class AltString: def __init__(self, str = "", size = 0): self._contents = str self._size = size self._list = [str] def append(self, str): self._list.append(str) def output(self): return "".join(self._list) And I successfully invoke the class instance using: as = AltString("String1") as.append("String2") as.append("String3") When I then invoke the output function using as.output instead of a string being returned, I get the following instead: unbound method AltString.output if I call it using as.output() I get the following error: TypeError: unbound method output() must be called with AltString instance as first argument (got nothing instead) What I am not doing right?
[ "as is a bad variable name, it is reserved keyword in Python. don't name your variables like this. once you fix it, everything else will be alright. of course you should be doing: \nalt_str.output()\n\nedit: I was able to replicate your error messages when trying to apply output to the class: AltString.output, then: AltString.output(). You should be applying the method to the instance of the class instead.\nalt_str = AltString('spam')\nalt_str.output()\n\n", "'as' and 'str' are keywords, don't shadow them by defining variables with the same name.\n", "Your example is confirmed to work as you expect in python 2.4\n>>> from x import *\n>>> as = AltString(\"String1\")\n>>> as.append(\"bubu\")\n>>> \n>>> as.output()\n'String1bubu'\n\nIn python 2.5 it should also work, but will raise a warning about the use of as, which will become a reserved keyword in python 2.6. \nI don't really understand why you obtain such error messages. If you are using python 2.6 it should probably produce a syntax error.\n", "I ran the following code :\nclass AltString:\n\n def __init__(self, str = \"\", size = 0):\n self._contents = str\n self._size = size\n self._list = [str]\n\n def append(self, str):\n self._list.append(str)\n\n def output(self):\n return \"\".join(self._list)\n\n\na = AltString(\"String1\")\n\na.append(\"String2\")\n\na.append(\"String3\")\n\n\nprint a.output() \n\nAnd it worked perfectly. The only flow I can see is that you use \"as\", which is a reserved keyword.\n", "Just tried your code in Python 2.6.2 and the line\nas = AltString(\"String1\")\n\ndoesn't work because \"as\" is a reserved keyword (see here) but if I use another name it works perfectly.\n" ]
[ 8, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001566314_python.txt
Q: What is an "app" in Django? According to the documentation: An app is a Web application that does something -- e.g., a weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects. However, what are other examples of what makes an "app"? A: What makes an app (for us) is one thing: An App Is The Unit Of Reuse If we might want to split it off to use somewhere else, it's an app. If it has a reusable data model, it's an app. User Profiles: App. Customers: App. Customer Statistical History (this is hard to explain without providing too many details): App. Reporting: App. Actuarial Analysis: App. Vendor API's for data gathering: App. If it is unique and will never be reused (i.e., customer specific) it's an app that depends on other apps. Data Loads are customer specific. Each is an app that builds on an existing pair of apps (Batch Uploads, and Statistical History) A: Django apps are bundles of reusable functionality. When starting off it's easy to just use one custom app for your project, but the "Django way" is to break it up into separate apps that each only do one thing. You can take a look at django.contrib for examples of really well made reusable apps. A recent example of mine: a client needed a way to import CSV data into the Django models. The easiest way would be to just add a model with a FileField and write a quick parser for the specific format of what they are uploading. That would work fine until the format changed and I had to go make the parser match. But this is a commonly repeated task (importing data) and unrelated to the existing app (managing that data) so I broke it out on its own. This pluggable app can import data for any active model. Now the next time a client needs import functionality I just add this code to installed_apps and run syncdb. It's a judgement call when to break out an app onto its own, but the rule of thumb for me is if I'm likely to do something again I'll take the extra time to make it a generic app. That means I've created some tiny apps (some just contain a template tag), but it's little overhead for the future gains. A: User management could very well be an app, if you are not going to use Django's built in user framework. It has user interfaces and defined models for stored data, and it is really separate from the Blog or the Wiki application (although the information will be shared). As long as both applications are in the same 'project' they should use the same settings for the DB. You should be able to by just making sure the proper models are imported where you are trying to use them. See this link for a little more information.
What is an "app" in Django?
According to the documentation: An app is a Web application that does something -- e.g., a weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects. However, what are other examples of what makes an "app"?
[ "What makes an app (for us) is one thing:\nAn App Is The Unit Of Reuse\nIf we might want to split it off to use somewhere else, it's an app. \nIf it has a reusable data model, it's an app. User Profiles: App. Customers: App. Customer Statistical History (this is hard to explain without providing too many details): App. Reporting: App. Actuarial Analysis: App. Vendor API's for data gathering: App.\nIf it is unique and will never be reused (i.e., customer specific) it's an app that depends on other apps. Data Loads are customer specific. Each is an app that builds on an existing pair of apps (Batch Uploads, and Statistical History)\n", "Django apps are bundles of reusable functionality. When starting off it's easy to just use one custom app for your project, but the \"Django way\" is to break it up into separate apps that each only do one thing. You can take a look at django.contrib for examples of really well made reusable apps.\nA recent example of mine: a client needed a way to import CSV data into the Django models. The easiest way would be to just add a model with a FileField and write a quick parser for the specific format of what they are uploading. That would work fine until the format changed and I had to go make the parser match. But this is a commonly repeated task (importing data) and unrelated to the existing app (managing that data) so I broke it out on its own. This pluggable app can import data for any active model. Now the next time a client needs import functionality I just add this code to installed_apps and run syncdb.\nIt's a judgement call when to break out an app onto its own, but the rule of thumb for me is if I'm likely to do something again I'll take the extra time to make it a generic app. That means I've created some tiny apps (some just contain a template tag), but it's little overhead for the future gains.\n", "User management could very well be an app, if you are not going to use Django's built in user framework.\nIt has user interfaces and defined models for stored data, and it is really separate from the Blog or the Wiki application (although the information will be shared).\nAs long as both applications are in the same 'project' they should use the same settings for the DB. You should be able to by just making sure the proper models are imported where you are trying to use them.\nSee this link for a little more information.\n" ]
[ 14, 5, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001563457_django_python.txt
Q: Separating Models and Request Handlers In Google App Engine I'd like to move my models to a separate directory, similar to the way it's done with Rails to cut down on code clutter. Is there any way to do this easily? Thanks, Collin A: I assume you're using the basic webkit and not Django or something fancy. In that case just create a subdirectory called models. Put any python files you use for your models in here. Create also one blank file in this folder called __init__.py. Then in your main.py or "controller" or what have you, put: import models at the top. You just created a python package. A: Brandon's answer is what I do. Furthermore, I rather like Rails's custom of one model per file. I don't stick to it completely but that is my basic pattern, especially since Python tends to encourage more-but-simpler lines of code than Ruby. So what I do is I make models a package too: models/ models/__init__.py models/user.py models/item.py models/blog_post.py In the main .py files I put my basic class definition, plus perhaps some helper functions (Python's module system makes it much safer to keep quickie helper functions coupled to the class definition). And my __init__.py stitches them all together: """The application models""" from user import User from item import Item from blog_post import BlogPost It's slightly redundant but I have lots of control of the namespace.
Separating Models and Request Handlers In Google App Engine
I'd like to move my models to a separate directory, similar to the way it's done with Rails to cut down on code clutter. Is there any way to do this easily? Thanks, Collin
[ "I assume you're using the basic webkit and not Django or something fancy. In that case just create a subdirectory called models. Put any python files you use for your models in here. Create also one blank file in this folder called __init__.py.\nThen in your main.py or \"controller\" or what have you, put:\nimport models\n\nat the top.\nYou just created a python package.\n", "Brandon's answer is what I do. Furthermore, I rather like Rails's custom of one model per file. I don't stick to it completely but that is my basic pattern, especially since Python tends to encourage more-but-simpler lines of code than Ruby.\nSo what I do is I make models a package too:\nmodels/\nmodels/__init__.py\nmodels/user.py\nmodels/item.py\nmodels/blog_post.py\n\nIn the main .py files I put my basic class definition, plus perhaps some helper functions (Python's module system makes it much safer to keep quickie helper functions coupled to the class definition). And my __init__.py stitches them all together:\n\"\"\"The application models\"\"\"\nfrom user import User\nfrom item import Item\nfrom blog_post import BlogPost\n\nIt's slightly redundant but I have lots of control of the namespace.\n" ]
[ 7, 1 ]
[]
[]
[ "google_app_engine", "model", "python" ]
stackoverflow_0000652449_google_app_engine_model_python.txt
Q: Is there a dictionary that contains the function's parameters in Python? I'd like to be able to get a dictionary of all the parameters passed to a function. def myfunc( param1, param2, param3 ): print 'Param1=%(param1)s, Param2=%(param2)s Param3=%(param3)' % __method_param_dict__ So my question is does the dictionary method_param_dict exist, and if so what is it called. Thanks A: A solution for your specific example: def myfunc(param1, param2, param3): dict_param = locals() But be sure to have a look at this article for a complete explanation of the possiblities (args, kwargs, mixed etc...) A: If you need to do that, you should use *args and **kwargs. def foo(*args, **kwargs): print args print kwargs foo(1,2,3,four=4,five=5) # prints [1,2,3] and {'four':4, 'five':5} Using locals() is also a possibility and will allow you to iterate through the names of position arguments, but you must remember to access it before defining any new names in the scope, and you should be aware that it will include self for methods. A: You can do: def myfunc(*args, **kwargs): # Now "args" is a list containing the parameters passed print args[0], args[1], args[2] # And "kwargs" is a dictionary mapping the parameter names passed to their values for key, value in kwargs.items(): print key, value A: If you want to accept variable parameters, you can use *args and **kwargs. *args is a list of all non-keyword parameters. **kwargs is a dictionary of all keyword parameters. So: def myfunc(*args, **kwargs): if args: print args if kwargs: print kwargs >>> myfunc('hello', 'goodbye') ('hello', 'goodbye') >>> myfunc(param1='hello', param2='goodbye') {'param1': 'param2', 'param2': 'goodbye'}
Is there a dictionary that contains the function's parameters in Python?
I'd like to be able to get a dictionary of all the parameters passed to a function. def myfunc( param1, param2, param3 ): print 'Param1=%(param1)s, Param2=%(param2)s Param3=%(param3)' % __method_param_dict__ So my question is does the dictionary method_param_dict exist, and if so what is it called. Thanks
[ "A solution for your specific example:\ndef myfunc(param1, param2, param3):\n dict_param = locals()\n\nBut be sure to have a look at this article for a complete explanation of the possiblities (args, kwargs, mixed etc...)\n", "If you need to do that, you should use *args and **kwargs.\ndef foo(*args, **kwargs):\n print args\n print kwargs\n\nfoo(1,2,3,four=4,five=5)\n# prints [1,2,3] and {'four':4, 'five':5}\n\nUsing locals() is also a possibility and will allow you to iterate through the names of position arguments, but you must remember to access it before defining any new names in the scope, and you should be aware that it will include self for methods.\n", "You can do:\ndef myfunc(*args, **kwargs):\n # Now \"args\" is a list containing the parameters passed\n print args[0], args[1], args[2]\n\n # And \"kwargs\" is a dictionary mapping the parameter names passed to their values\n for key, value in kwargs.items():\n print key, value\n\n", "If you want to accept variable parameters, you can use *args and **kwargs. \n*args is a list of all non-keyword parameters. **kwargs is a dictionary of all keyword parameters. So:\ndef myfunc(*args, **kwargs):\n if args:\n print args\n if kwargs:\n print kwargs\n\n\n>>> myfunc('hello', 'goodbye')\n('hello', 'goodbye')\n\n>>> myfunc(param1='hello', param2='goodbye')\n{'param1': 'param2', 'param2': 'goodbye'}\n\n" ]
[ 7, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001566878_python.txt
Q: Why is BeautifulSoup modifying my self-closing elements? This is the script I have: import BeautifulSoup if __name__ == "__main__": data = """ <root> <obj id="3"/> <obj id="5"/> <obj id="3"/> </root> """ soup = BeautifulSoup.BeautifulStoneSoup(data) print soup When ran, this prints: <root> <obj id="3"></obj> <obj id="5"></obj> <obj id="3"></obj> </root> I'd like it to keep the same structure. How can I do that? A: From the Beautiful Soup documentation: The most common shortcoming of BeautifulStoneSoup is that it doesn't know about self-closing tags. HTML has a fixed set of self-closing tags, but with XML it depends on what the DTD says. You can tell BeautifulStoneSoup that certain tags are self-closing by passing in their names as the selfClosingTags argument to the constructor
Why is BeautifulSoup modifying my self-closing elements?
This is the script I have: import BeautifulSoup if __name__ == "__main__": data = """ <root> <obj id="3"/> <obj id="5"/> <obj id="3"/> </root> """ soup = BeautifulSoup.BeautifulStoneSoup(data) print soup When ran, this prints: <root> <obj id="3"></obj> <obj id="5"></obj> <obj id="3"></obj> </root> I'd like it to keep the same structure. How can I do that?
[ "From the Beautiful Soup documentation:\n\nThe most common shortcoming of BeautifulStoneSoup is that it doesn't know about self-closing tags. HTML has a fixed set of self-closing tags, but with XML it depends on what the DTD says. You can tell BeautifulStoneSoup that certain tags are self-closing by passing in their names as the selfClosingTags argument to the constructor\n\n" ]
[ 7 ]
[]
[]
[ "beautifulsoup", "python", "xml" ]
stackoverflow_0001567402_beautifulsoup_python_xml.txt
Q: Wrapping an interactive command line application in a Python script I am interested in controlling an interactive CLI application from Python calls. I guess at the most basic level I need a Python script that will start a CLI application on the host operating system. Pipe anything from standard input to the CLI application, and then pipe any output from the CLI application to standard output. From this base, it should be pretty straightforward to do some processing on the input and output. To be honest, I probably just need a pointer on what the technique is called. I have no idea what I need to be searching for. A: Maybe you want something from Subprocess (MOTW). I use code like this to make calls out to the shell: from subprocess import Popen, PIPE ## shell out, prompt def shell(args, input_=''): ''' uses subprocess pipes to call out to the shell. args: args to the command input: stdin returns stdout, stderr ''' p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate(input=input_) return stdout, stderr A: Does PExpect fits your needs?
Wrapping an interactive command line application in a Python script
I am interested in controlling an interactive CLI application from Python calls. I guess at the most basic level I need a Python script that will start a CLI application on the host operating system. Pipe anything from standard input to the CLI application, and then pipe any output from the CLI application to standard output. From this base, it should be pretty straightforward to do some processing on the input and output. To be honest, I probably just need a pointer on what the technique is called. I have no idea what I need to be searching for.
[ "Maybe you want something from Subprocess (MOTW).\nI use code like this to make calls out to the shell:\nfrom subprocess import Popen, PIPE\n\n## shell out, prompt\ndef shell(args, input_=''):\n ''' uses subprocess pipes to call out to the shell.\n \n args: args to the command\n input: stdin\n \n returns stdout, stderr\n '''\n p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n stdout, stderr = p.communicate(input=input_)\n return stdout, stderr\n\n", "Does PExpect fits your needs?\n" ]
[ 16, 11 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0001567371_command_line_python.txt
Q: Validate XML against DTD using python on google app engine I've got validation working on client side using lxml, but I'm not quite sure how to get it work on Google App Engine, since it doesn't have the lxml package. I tried copying the whole lxml folder and place it in the root of my Google application, but it seems like it cannot use it properly. I'm guessing it has to do with the compiled .so-files and such. Is there a way to get lxml to work on Google App Engine? If not, is there any other library that you can use to validate XML against DTD that works on Google App Engine? A: Compiled C extensions (like lxml) will not work on Google App Engine. PyXML is no longer maintained, but it does have a pure-Python XML validator. See this code snippet for an example.
Validate XML against DTD using python on google app engine
I've got validation working on client side using lxml, but I'm not quite sure how to get it work on Google App Engine, since it doesn't have the lxml package. I tried copying the whole lxml folder and place it in the root of my Google application, but it seems like it cannot use it properly. I'm guessing it has to do with the compiled .so-files and such. Is there a way to get lxml to work on Google App Engine? If not, is there any other library that you can use to validate XML against DTD that works on Google App Engine?
[ "Compiled C extensions (like lxml) will not work on Google App Engine.\nPyXML is no longer maintained, but it does have a pure-Python XML validator. See this code snippet for an example.\n" ]
[ 1 ]
[]
[]
[ "dtd", "google_app_engine", "python", "validation", "xml" ]
stackoverflow_0001566951_dtd_google_app_engine_python_validation_xml.txt
Q: Python and random keys of 21 char max I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ? For now i use 'userid[:10]' + creation time: ddhhmmss + random 3 chars. Thanks, A: If I read your question correctly, you want to generate some arbitrary identifier token which must be 21 characters max. Does it need to be highly resistant to guessing? The example you gave isn't "crytographically strong" in that it can be guessed by searching well less than 1/2 of the entire possible keyspace. You don't say if the characters can be all 256 ASCII characters, or if it needs to be limited to, say, printable ASCII (33-127, inclusive), or some smaller range. There is a Python module designed for UUIDs (Universals Unique IDentifiers). You likely want uuid4 which generates a random UUID, and uses OS support if available (on Linux, Mac, FreeBSD, and likely others). >>> import uuid >>> u = uuid.uuid4() >>> u UUID('d94303e7-1be4-49ef-92f2-472bc4b4286d') >>> u.bytes '\xd9C\x03\xe7\x1b\xe4I\xef\x92\xf2G+\xc4\xb4(m' >>> len(u.bytes) 16 >>> 16 random bytes is very unguessable, and there's no need to use the full 21 bytes your API allows, if all you want is to have an unguessable opaque identifier. If you can't use raw bytes like that, which is probably a bad idea because it's harder to use in logs and other debug messages and harder to compare by eye, then convert the bytes into something a bit more readable, like using base-64 encoding, with the result chopped down to 21 (or whatever) bytes: >>> u.bytes.encode("base64") '2UMD5xvkSe+S8kcrxLQobQ==\n' >>> len(u.bytes.encode("base64")) 25 >>> u.bytes.encode("base64")[:21] '2UMD5xvkSe+S8kcrxLQob' >>> This gives you an extremely high quality random string of length 21. You might not like the '+' or '/' which can be in a base-64 string, since without proper escaping that might interfere with URLs. Since you already think to use "random 3 chars", I don't think this is a worry of yours. If it is, you could replace those characters with something else ('-' and '.' might work), or remove them if present. As others have pointed out, you could use .encode("hex") and get the hex equivalent, but that's only 4 bits of randomness/character * 21 characters max gives you 84 bits of randomness instead of twice that. Every bit doubles your keyspace, making the theoretical search space much, much smaller. By a factor of 2E24 smaller. Your keyspace is still 2E24 in size, even with hex encoding, so I think it's more a theoretical concern. I wouldn't worry about people doing brute force attacks against your system. Edit: P.S.: The uuid.uuid4 function uses libuuid if available. That gets its entropy from os.urandom (if available) otherwise from the current time and the local ethernet MAC address. If libuuid is not available then the uuid.uuid4 function gets the bytes directly from os.urandom (if available) otherwise it uses the random module. The random module uses a default seed based on os.urandom (if available) otherwise a value based on the current time. Probing takes place for every function call, so if you don't have os.urandom then the overhead is a bit bigger than you might expect. Take home message? If you know you have os.urandom then you could do os.urandom(16).encode("base64")[:21] but if you don't want to worry about its availability then use the uuid module. A: The hexadecimal representation of MD5 has very poor randomness: you only get 4 bits of entropy per character. Use random characters, something like: import random import string "".join([random.choice(string.ascii_letters + string.digits + ".-") for i in xrange(21)]) In the choice put all the acceptable characters. While using a real hash function such as SHA1 will also get you nice results if used correctly, the added complexity and CPU consumption seems not justified for your needs. You only want a random string. A: Why not take first 21 chars from md5 or SHA1 hash? A: The base64 module can do URL-safe encoding. So, if needed, instead of u.bytes.encode("base64") you could do import base64 token = base64.urlsafe_b64encode(u.bytes) and, conveniently, to convert back u = uuid.UUID(bytes=base64.urlsafe_b64decode(token)) A: Characters, or bytes? If it takes arbitrary strings, you can just use the bytes and not worry about expanding to readable characters (for which base64 would be better than hex anyway). MD5 generates 16 chars if you don't use the hexadecimal expansion of it. SHA1 generates 20 under the same condition. >>> import hashlib >>> len(hashlib.md5('foobar').digest()) 16 >>> len(hashlib.sha1('foobar').digest()) 20 Few extra bytes are needed after that.
Python and random keys of 21 char max
I am using an api which takes a name of 21 char max to represent an internal session which has a lifetime of around "two days". I would like the name not to be meaningfull using some kind of hasing ? md5 generates 40 chars, is there something else i could use ? For now i use 'userid[:10]' + creation time: ddhhmmss + random 3 chars. Thanks,
[ "If I read your question correctly, you want to generate some arbitrary identifier token which must be 21 characters max. Does it need to be highly resistant to guessing? The example you gave isn't \"crytographically strong\" in that it can be guessed by searching well less than 1/2 of the entire possible keyspace. \nYou don't say if the characters can be all 256 ASCII characters, or if it needs to be limited to, say, printable ASCII (33-127, inclusive), or some smaller range.\nThere is a Python module designed for UUIDs (Universals Unique IDentifiers). You likely want uuid4 which generates a random UUID, and uses OS support if available (on Linux, Mac, FreeBSD, and likely others).\n>>> import uuid\n>>> u = uuid.uuid4()\n>>> u\nUUID('d94303e7-1be4-49ef-92f2-472bc4b4286d')\n>>> u.bytes\n'\\xd9C\\x03\\xe7\\x1b\\xe4I\\xef\\x92\\xf2G+\\xc4\\xb4(m'\n>>> len(u.bytes)\n16\n>>> \n\n16 random bytes is very unguessable, and there's no need to use the full 21 bytes your API allows, if all you want is to have an unguessable opaque identifier.\nIf you can't use raw bytes like that, which is probably a bad idea because it's harder to use in logs and other debug messages and harder to compare by eye, then convert the bytes into something a bit more readable, like using base-64 encoding, with the result chopped down to 21 (or whatever) bytes:\n>>> u.bytes.encode(\"base64\")\n'2UMD5xvkSe+S8kcrxLQobQ==\\n'\n>>> len(u.bytes.encode(\"base64\")) \n25\n>>> u.bytes.encode(\"base64\")[:21]\n'2UMD5xvkSe+S8kcrxLQob'\n>>> \n\nThis gives you an extremely high quality random string of length 21.\nYou might not like the '+' or '/' which can be in a base-64 string, since without proper escaping that might interfere with URLs. Since you already think to use \"random 3 chars\", I don't think this is a worry of yours. If it is, you could replace those characters with something else ('-' and '.' might work), or remove them if present.\nAs others have pointed out, you could use .encode(\"hex\") and get the hex equivalent, but that's only 4 bits of randomness/character * 21 characters max gives you 84 bits of randomness instead of twice that. Every bit doubles your keyspace, making the theoretical search space much, much smaller. By a factor of 2E24 smaller.\nYour keyspace is still 2E24 in size, even with hex encoding, so I think it's more a theoretical concern. I wouldn't worry about people doing brute force attacks against your system.\nEdit:\nP.S.: The uuid.uuid4 function uses libuuid if available. That gets its entropy from os.urandom (if available) otherwise from the current time and the local ethernet MAC address. If libuuid is not available then the uuid.uuid4 function gets the bytes directly from os.urandom (if available) otherwise it uses the random module. The random module uses a default seed based on os.urandom (if available) otherwise a value based on the current time. Probing takes place for every function call, so if you don't have os.urandom then the overhead is a bit bigger than you might expect.\nTake home message? If you know you have os.urandom then you could do \nos.urandom(16).encode(\"base64\")[:21]\n\nbut if you don't want to worry about its availability then use the uuid module.\n", "The hexadecimal representation of MD5 has very poor randomness: you only get 4 bits of entropy per character.\nUse random characters, something like:\nimport random\nimport string\n\"\".join([random.choice(string.ascii_letters + string.digits + \".-\")\n for i in xrange(21)])\n\nIn the choice put all the acceptable characters.\nWhile using a real hash function such as SHA1 will also get you nice results if used correctly, the added complexity and CPU consumption seems not justified for your needs. You only want a random string.\n", "Why not take first 21 chars from md5 or SHA1 hash?\n", "The base64 module can do URL-safe encoding. So, if needed, instead of \nu.bytes.encode(\"base64\")\n\nyou could do\nimport base64\n\ntoken = base64.urlsafe_b64encode(u.bytes)\n\nand, conveniently, to convert back\nu = uuid.UUID(bytes=base64.urlsafe_b64decode(token))\n\n", "Characters, or bytes? If it takes arbitrary strings, you can just use the bytes and not worry about expanding to readable characters (for which base64 would be better than hex anyway).\nMD5 generates 16 chars if you don't use the hexadecimal expansion of it. SHA1 generates 20 under the same condition.\n>>> import hashlib\n>>> len(hashlib.md5('foobar').digest())\n16\n>>> len(hashlib.sha1('foobar').digest())\n20\n\nFew extra bytes are needed after that.\n" ]
[ 23, 4, 2, 2, 0 ]
[]
[]
[ "encryption", "key", "python" ]
stackoverflow_0000621649_encryption_key_python.txt
Q: finding substring Thanks in advance. I have a string: A = 'asdfghjklmn' How can I get a substring having a maximum length which is a multiple of three? A: You can use slice notation and integer arithmetic. >>> a = 'asdfghjklmn' >>> a[:len(a)//3*3] 'asdfghjkl' >>> len(a) 11 >>> len(a[:len(a)//3*3]) 9 In general, n//k*k will yield the largest multiple of k less than or equal to n. A: It seems like you're looking for something like this: >>> A = 'asdfghjklmn' >>> mult, _ = divmod(len(A), 3) >>> A[:mult*3] 'asdfghjkl' here resulting string will have length which is multiple of three and it will be the longest possible substring of A with such length. A: Yet another example: >>> A = '12345678' >>> A[:len(A) - len(A)%3] '123456' >>> A: Is this what you want? A = 'asdfghjklmn' A[0:(len(A)/3)*3] 'asdfghjkl' A: With the foreword that it will never be as efficient as the ones that actually use math to find the longest multiple-of-3-substring, here's a way to do it using regular expressions: >>> re.findall("^(?:.{3})*", "asdfghjklmn")[0] 'asdfghjkl' Changing the 3 quantifier will allow you to get different multiples.
finding substring
Thanks in advance. I have a string: A = 'asdfghjklmn' How can I get a substring having a maximum length which is a multiple of three?
[ "You can use slice notation and integer arithmetic.\n>>> a = 'asdfghjklmn'\n>>> a[:len(a)//3*3]\n'asdfghjkl' \n>>> len(a)\n11\n>>> len(a[:len(a)//3*3])\n9\n\nIn general, n//k*k will yield the largest multiple of k less than or equal to n.\n", "It seems like you're looking for something like this:\n>>> A = 'asdfghjklmn'\n>>> mult, _ = divmod(len(A), 3)\n>>> A[:mult*3]\n'asdfghjkl'\n\nhere resulting string will have length which is multiple of three and it will be the longest possible substring of A with such length.\n", "Yet another example:\n>>> A = '12345678'\n>>> A[:len(A) - len(A)%3]\n'123456'\n>>> \n\n", "Is this what you want?\nA = 'asdfghjklmn'\nA[0:(len(A)/3)*3]\n'asdfghjkl'\n\n", "With the foreword that it will never be as efficient as the ones that actually use math to find the longest multiple-of-3-substring, here's a way to do it using regular expressions:\n>>> re.findall(\"^(?:.{3})*\", \"asdfghjklmn\")[0]\n'asdfghjkl'\n\nChanging the 3 quantifier will allow you to get different multiples.\n" ]
[ 4, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001567607_python.txt
Q: Should I keep my Python code at 2.x or migrate to 3.x if I plan to eventually use Jython? I have a large infrastructure that is written in Python 2.6, and I recently took a stab at porting to 3.1 (was much smoother than I expected) despite the lack of backwards compatibility. I eventually want to integrate some of this Python code with a lot of Java based code that we have, and was thinking about giving Jython a try. However, from looking at the Jython tutorials, all the examples are in 2.6 syntax (e.g., print is not yet a function). Does/will Jython support Python 3.x syntax at present or in the near future? Or should I roll back to 2.6 if I want to eventually use Jython? A: Jython will not support Python 3.x in the near future. For your code, I recommend to keep it in 2.x form, such that 3.x support becomes available by merely running 2to3 (i.e. with no further source changes). IOW, port to 3.x in a way so that the code remains compatible with 2.x. A: I would expect that the developers will be working towards compatability with 3.0 at this point. Since they released 2.5 in june I'd hope for a 3.0 version no earlier than Jan.-Mar. 2010, but given their slow release cycle, it could be a while. A: With time 2.x will be surpassed by the new features of his 3.x. If you wish to programming in Python in the future then "the sooner = the better"
Should I keep my Python code at 2.x or migrate to 3.x if I plan to eventually use Jython?
I have a large infrastructure that is written in Python 2.6, and I recently took a stab at porting to 3.1 (was much smoother than I expected) despite the lack of backwards compatibility. I eventually want to integrate some of this Python code with a lot of Java based code that we have, and was thinking about giving Jython a try. However, from looking at the Jython tutorials, all the examples are in 2.6 syntax (e.g., print is not yet a function). Does/will Jython support Python 3.x syntax at present or in the near future? Or should I roll back to 2.6 if I want to eventually use Jython?
[ "Jython will not support Python 3.x in the near future. For your code, I recommend to keep it in 2.x form, such that 3.x support becomes available by merely running 2to3 (i.e. with no further source changes). IOW, port to 3.x in a way so that the code remains compatible with 2.x.\n", "I would expect that the developers will be working towards compatability with 3.0 at this point. Since they released 2.5 in june I'd hope for a 3.0 version no earlier than Jan.-Mar. 2010, but given their slow release cycle, it could be a while.\n", "With time 2.x will be surpassed by the new features of his 3.x. If you wish to programming in Python in the future then \"the sooner = the better\"\n" ]
[ 5, 0, 0 ]
[]
[]
[ "jython", "python" ]
stackoverflow_0001566411_jython_python.txt
Q: Decrypt MD5 hash Is there any way to decrypt the encrypted MD5 string, given the key? A: MD5 is a one-way hash. It cannot be decrypted. The closest thing to decrypting an MD5 hash would be to do a lookup against a pre-generated rainbow table. Also, I'm not sure what you mean by "I have the key". There is no "key" in an MD5 hash. Perhaps you are thinking of a salt? If your data has a salt value incorporated prior to hashing, the rainbow table approach probably won't be practical anyway. A: Try Google (see Using Google To Crack MD5 Passwords) or an online DB of MD5 hashes like md5(); or GDATA (the last one contains 1,133,766,035 unique entries). A: MD5 is not a encryption algorithm, it is a hashing algorithm. Read up on MD5 and Crytographic Hash Functions. To create a MD5 hash of a string in Python you do as follows: import hashlib m = hashlib.md5() m.update("String to Hash") echo m.digest() # '\xed\xa5\x8bA-nU\xa2\xee\xbb[_s\x130\xbd' echo m.hexdigest() # its more common to show hashes as a hex string # 'eda58b412d6e55a2eebb5b5f731330bd' A: Message-Digest algorithm 5 is a widely-used cryptographic hash function with a 128-bit hash value. Encryption has 2 way : encrypt - decript, hash has one way - there is no decryption possible. BUT with database hash IS POSSIBLE to solve this issue. See this sites : www.rednoize.com – 50,709,274 Hash in database www.md5oogle.com – 6,353,625 Hash in database www.hashmash.com – 1,611,191 Hash in database www.gdataonline.com 1,155,613 Hash in database www.md5decryption.com – 872,145 Hash in database www.md5decrypter.com – 583,441 Hash in database www.md5decrypter.co.uk – 41,568,541 Hash in database www.macrosoftware.ro – 5,403 Hash in database A: MD5 is an asymmetric hash -- not an encryption mechanism. You can't "decrypt" an MD5. If you know the hashed contents are limited to a (short) set of possibilities, you can use a Rainbow Table to attempt to brute-force reverse the hash, but this will not work in the general case.
Decrypt MD5 hash
Is there any way to decrypt the encrypted MD5 string, given the key?
[ "MD5 is a one-way hash. It cannot be decrypted. The closest thing to decrypting an MD5 hash would be to do a lookup against a pre-generated rainbow table. Also, I'm not sure what you mean by \"I have the key\". There is no \"key\" in an MD5 hash. Perhaps you are thinking of a salt? If your data has a salt value incorporated prior to hashing, the rainbow table approach probably won't be practical anyway.\n", "Try Google (see Using Google To Crack MD5 Passwords) or an online DB of MD5 hashes like md5(); or GDATA (the last one contains 1,133,766,035 unique entries).\n", "MD5 is not a encryption algorithm, it is a hashing algorithm. Read up on MD5 and Crytographic Hash Functions.\nTo create a MD5 hash of a string in Python you do as follows:\nimport hashlib\nm = hashlib.md5()\nm.update(\"String to Hash\")\necho m.digest()\n# '\\xed\\xa5\\x8bA-nU\\xa2\\xee\\xbb[_s\\x130\\xbd'\necho m.hexdigest() # its more common to show hashes as a hex string\n# 'eda58b412d6e55a2eebb5b5f731330bd'\n\n", "Message-Digest algorithm 5 is a widely-used cryptographic hash function with a 128-bit hash value. Encryption has 2 way : encrypt - decript, hash has one way - there is no decryption possible.\nBUT with database hash IS POSSIBLE to solve this issue.\nSee this sites :\nwww.rednoize.com – 50,709,274 Hash in database\nwww.md5oogle.com – 6,353,625 Hash in database\nwww.hashmash.com – 1,611,191 Hash in database\nwww.gdataonline.com 1,155,613 Hash in database\nwww.md5decryption.com – 872,145 Hash in database\nwww.md5decrypter.com – 583,441 Hash in database\nwww.md5decrypter.co.uk – 41,568,541 Hash in database\nwww.macrosoftware.ro – 5,403 Hash in database\n", "MD5 is an asymmetric hash -- not an encryption mechanism. You can't \"decrypt\" an MD5. If you know the hashed contents are limited to a (short) set of possibilities, you can use a Rainbow Table to attempt to brute-force reverse the hash, but this will not work in the general case.\n" ]
[ 22, 5, 4, 4, 2 ]
[]
[]
[ "cracking", "cryptography", "md5", "python" ]
stackoverflow_0001562064_cracking_cryptography_md5_python.txt
Q: How can I view a text representation of an lxml element? If I'm parsing an XML document using lxml, is it possible to view a text representation of an element? I tried to do : print repr(node) but this outputs <Element obj at b743c0> What can I use to see the node like it exists in the XML file? Is there some to_xml method or something? A: From http://lxml.de/tutorial.html#serialisation >>> root = etree.XML('<root><a><b/></a></root>') >>> etree.tostring(root) b'<root><a><b/></a></root>' >>> print(etree.tostring(root, xml_declaration=True)) <?xml version='1.0' encoding='ASCII'?> <root><a><b/></a></root> >>> print(etree.tostring(root, encoding='iso-8859-1')) <?xml version='1.0' encoding='iso-8859-1'?> <root><a><b/></a></root> >>> print(etree.tostring(root, pretty_print=True)) <root> <a> <b/> </a> </root>
How can I view a text representation of an lxml element?
If I'm parsing an XML document using lxml, is it possible to view a text representation of an element? I tried to do : print repr(node) but this outputs <Element obj at b743c0> What can I use to see the node like it exists in the XML file? Is there some to_xml method or something?
[ "From http://lxml.de/tutorial.html#serialisation\n>>> root = etree.XML('<root><a><b/></a></root>')\n\n>>> etree.tostring(root)\nb'<root><a><b/></a></root>'\n\n>>> print(etree.tostring(root, xml_declaration=True))\n<?xml version='1.0' encoding='ASCII'?>\n<root><a><b/></a></root>\n\n>>> print(etree.tostring(root, encoding='iso-8859-1'))\n<?xml version='1.0' encoding='iso-8859-1'?>\n<root><a><b/></a></root>\n\n>>> print(etree.tostring(root, pretty_print=True))\n<root>\n <a>\n <b/>\n </a>\n</root>\n\n" ]
[ 45 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0001567903_lxml_python_xml.txt
Q: deleting an object in a loop that runs through the range of the list? I have a list composed of [start position, stop position, [sample names with those positions]] My goal is to remove the duplicates with exact start and stop positions and just add the extra sample to the sample names section. The problem I'm encountering is that when I delete from the list, I end up with an out of range error, because it's not recalculating the len(list) within the loops. for g in range (len(list)) : for n in range(len(list)): #compares the start and stop position of one line to the start and stop of another line if (list[g][0]==list[n+1][0] and list[g][1]==[n+1][1]) #adds new sample numbers to first start and stop entry with duplication labels1=list[g][2] labels2=list[n+1][2] labels=labels1+labels2 list[g][2]=labels #now delete the extra line del list[n+1] A: I not sure I understand what you want, but it might be this: from collections import defaultdict d = defaultdict(list) for start, stop, samples in L1: d[start, stop].extend(samples) L2 = [[start, stop, samples] for (start, stop), samples in d.items()] Which will take L1: L1 = [ [1, 5, ["a", "b", "c"]], [3, 4, ["d", "e"]], [1, 5, ["f"]] ] and make L2: L2 = [ [1, 5, ["a", "b", "c", "f"]], [3, 4, ["d", "e"]] ] Please note that this does not guarantee the same order of the elements in L2 as in L1, but from the looks of your question, that doesn't matter. A: Your loops should not be for loops, they should be while loop with an increment step. I guess you can just manually check the condition within your for loop (continue if it's not met), but a while loop makes more sense, imo. A: Here is truppo's answer, re-written to preserve the order of entries from L1. It has a few other small changes, such as using a plain dict instead of a defaultdict, and using explicit tuples instead of packing and unpacking them on the fly. L1 = [ [1, 5, ["a", "b", "c"]], [3, 4, ["d", "e"]], [1, 5, ["f"]] ] d = {} oplist = [] # order-preserving list for start, stop, samples in L1: tup = (start, stop) # make a tuple out of start/stop pair if tup in d: d[tup].extend(samples) else: d[tup] = samples oplist.append(tup) L2 = [[tup[0], tup[1], d[tup]] for tup in oplist] print L2 # prints: [[1, 5, ['a', 'b', 'c', 'f']], [3, 4, ['d', 'e']]] A: I've just put together a nice little list comprehension that does pretty much what you did, except without the nasty del s. from functools import reduce from operator import add from itertools import groupby data = [ [1, 1, [2, 3, 4]], [1, 1, [5, 7, 8]], [1, 3, [2, 8, 5]], [2, 3, [1, 7, 9]], [2, 3, [3, 8, 5]], ] data.sort() print( [[key[0], key[1], reduce(add, (i[2] for i in iterator))] for key, iterator in groupby(data, lambda item: item[:2]) ] )
deleting an object in a loop that runs through the range of the list?
I have a list composed of [start position, stop position, [sample names with those positions]] My goal is to remove the duplicates with exact start and stop positions and just add the extra sample to the sample names section. The problem I'm encountering is that when I delete from the list, I end up with an out of range error, because it's not recalculating the len(list) within the loops. for g in range (len(list)) : for n in range(len(list)): #compares the start and stop position of one line to the start and stop of another line if (list[g][0]==list[n+1][0] and list[g][1]==[n+1][1]) #adds new sample numbers to first start and stop entry with duplication labels1=list[g][2] labels2=list[n+1][2] labels=labels1+labels2 list[g][2]=labels #now delete the extra line del list[n+1]
[ "I not sure I understand what you want, but it might be this:\nfrom collections import defaultdict\nd = defaultdict(list)\nfor start, stop, samples in L1:\n d[start, stop].extend(samples)\nL2 = [[start, stop, samples] for (start, stop), samples in d.items()]\n\nWhich will take L1:\nL1 = [ [1, 5, [\"a\", \"b\", \"c\"]], [3, 4, [\"d\", \"e\"]], [1, 5, [\"f\"]] ]\n\nand make L2:\nL2 = [ [1, 5, [\"a\", \"b\", \"c\", \"f\"]], [3, 4, [\"d\", \"e\"]] ]\n\nPlease note that this does not guarantee the same order of the elements in L2 as in L1, but from the looks of your question, that doesn't matter.\n", "Your loops should not be for loops, they should be while loop with an increment step. I guess you can just manually check the condition within your for loop (continue if it's not met), but a while loop makes more sense, imo.\n", "Here is truppo's answer, re-written to preserve the order of entries from L1. It has a few other small changes, such as using a plain dict instead of a defaultdict, and using explicit tuples instead of packing and unpacking them on the fly.\nL1 = [ [1, 5, [\"a\", \"b\", \"c\"]], [3, 4, [\"d\", \"e\"]], [1, 5, [\"f\"]] ]\n\n\nd = {}\noplist = [] # order-preserving list\n\nfor start, stop, samples in L1:\n tup = (start, stop) # make a tuple out of start/stop pair\n if tup in d:\n d[tup].extend(samples)\n else:\n d[tup] = samples\n oplist.append(tup)\n\nL2 = [[tup[0], tup[1], d[tup]] for tup in oplist]\n\nprint L2\n# prints: [[1, 5, ['a', 'b', 'c', 'f']], [3, 4, ['d', 'e']]]\n\n", "I've just put together a nice little list comprehension that does pretty much what you did, except without the nasty del s.\nfrom functools import reduce\nfrom operator import add\nfrom itertools import groupby\n\ndata = [\n [1, 1, [2, 3, 4]],\n [1, 1, [5, 7, 8]],\n [1, 3, [2, 8, 5]],\n [2, 3, [1, 7, 9]],\n [2, 3, [3, 8, 5]],\n]\n\ndata.sort()\nprint(\n [[key[0], key[1], reduce(add, (i[2] for i in iterator))]\n for key, iterator in groupby(data, lambda item: item[:2])\n ]\n)\n\n" ]
[ 3, 2, 1, 0 ]
[]
[]
[ "for_loop", "list", "python" ]
stackoverflow_0001567669_for_loop_list_python.txt
Q: What is a good example of an __eq__ method for a collection class? I'm working on a collection class that I want to create an __eq__ method for. It's turning out to be more nuanced than I thought it would be and I've noticed several intricacies as far as how the built-in collection classes work. What would really help me the most is a good example. Are there any pure Python implementations of an __eq__ method either in the standard library or in any third-party libraries? A: Parts are hard. Parts should be simple delegation. def __eq__( self, other ): if len(self) != len(other): # Can we continue? If so, what rule applies? Pad shorter? Truncate longer? else: return all( self[i] == other[i] for i in range(len(self)) ) A: Take a look at "collections.py". The latest version (from version control) implements an OrderedDict with an __eq__. There's also an __eq__ in sets.py
What is a good example of an __eq__ method for a collection class?
I'm working on a collection class that I want to create an __eq__ method for. It's turning out to be more nuanced than I thought it would be and I've noticed several intricacies as far as how the built-in collection classes work. What would really help me the most is a good example. Are there any pure Python implementations of an __eq__ method either in the standard library or in any third-party libraries?
[ "Parts are hard. Parts should be simple delegation.\ndef __eq__( self, other ):\n if len(self) != len(other):\n # Can we continue? If so, what rule applies? Pad shorter? Truncate longer?\n else:\n return all( self[i] == other[i] for i in range(len(self)) )\n\n", "Take a look at \"collections.py\". The latest version (from version control) implements an OrderedDict with an __eq__. There's also an __eq__ in sets.py\n" ]
[ 7, 1 ]
[]
[]
[ "api", "collections", "equality", "python" ]
stackoverflow_0001560245_api_collections_equality_python.txt
Q: Python's libxml2 can't parse unicode strings OK, the docs for Python's libxml2 bindings are really ****. My problem: An XML document is stored in a string variable in Python. The string is a instance of Unicode, and there are non-ASCII characters in it. I want to parse it with libxml2, looking something like this: # -*- coding: utf-8 -*- import libxml2 DOC = u"""<?xml version="1.0" encoding="UTF-8"?> <data> <something>Bäääh!</something> </data> """ xml_doc = libxml2.parseDoc(DOC) with this result: Traceback (most recent call last): File "test.py", line 13, in <module> xml_doc = libxml2.parseDoc(DOC) File "c:\Python26\lib\site-packages\libxml2.py", line 1237, in parseDoc ret = libxml2mod.xmlParseDoc(cur) UnicodeEncodeError: 'ascii' codec can't encode characters in position 46-48: ordinal not in range(128) The point is the u"..." declaration. If I replace it with a simple "..", then everything is ok. Unfortunately it doesn't work in my setup, because DOC will definitely be a Unicode instance. Has anyone an idea how libxml2 can be brought to parse UTF-8 encoded strings? A: It should be # -*- coding: utf-8 -*- import libxml2 DOC = u"""<?xml version="1.0" encoding="UTF-8"?> <data> <something>Bäääh!</something> </data> """.encode("UTF-8") xml_doc = libxml2.parseDoc(DOC) The .encode("UTF-8") is needed to get the binary representation of the unicode string with the utf8 encoding. A: XML is a binary format, despite of looking like a text. An encoding is specified in the beginning of the XML file in order to decode the XML bytes into the text. What you should do is to pass str, not unicode to your library: xml_doc = libxml2.parseDoc(DOC.encode("UTF-8")) (Although some tricks are possible with site.setencoding if you are interested in reading or writing unicode strings with automatic conversion via locale.) Edit: The Unicode article by Joel Spolsky is good guide to string characters vs. bytes, encodings, etc.
Python's libxml2 can't parse unicode strings
OK, the docs for Python's libxml2 bindings are really ****. My problem: An XML document is stored in a string variable in Python. The string is a instance of Unicode, and there are non-ASCII characters in it. I want to parse it with libxml2, looking something like this: # -*- coding: utf-8 -*- import libxml2 DOC = u"""<?xml version="1.0" encoding="UTF-8"?> <data> <something>Bäääh!</something> </data> """ xml_doc = libxml2.parseDoc(DOC) with this result: Traceback (most recent call last): File "test.py", line 13, in <module> xml_doc = libxml2.parseDoc(DOC) File "c:\Python26\lib\site-packages\libxml2.py", line 1237, in parseDoc ret = libxml2mod.xmlParseDoc(cur) UnicodeEncodeError: 'ascii' codec can't encode characters in position 46-48: ordinal not in range(128) The point is the u"..." declaration. If I replace it with a simple "..", then everything is ok. Unfortunately it doesn't work in my setup, because DOC will definitely be a Unicode instance. Has anyone an idea how libxml2 can be brought to parse UTF-8 encoded strings?
[ "It should be\n# -*- coding: utf-8 -*-\nimport libxml2\n\nDOC = u\"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<data>\n <something>Bäääh!</something>\n</data>\n\"\"\".encode(\"UTF-8\")\n\nxml_doc = libxml2.parseDoc(DOC)\n\nThe .encode(\"UTF-8\") is needed to get the binary representation of the unicode string with the utf8 encoding.\n", "XML is a binary format, despite of looking like a text. An encoding is specified in the beginning of the XML file in order to decode the XML bytes into the text.\nWhat you should do is to pass str, not unicode to your library:\nxml_doc = libxml2.parseDoc(DOC.encode(\"UTF-8\"))\n\n(Although some tricks are possible with site.setencoding if you are interested in reading or writing unicode strings with automatic conversion via locale.)\nEdit: The Unicode article by Joel Spolsky is good guide to string characters vs. bytes, encodings, etc.\n" ]
[ 9, 6 ]
[]
[]
[ "libxml2", "python", "unicode", "xml" ]
stackoverflow_0001569076_libxml2_python_unicode_xml.txt
Q: RPC for multiprocessing, design issues what's a good way to do rpc across multiprocessing.Process'es ? I am also open to design advise on the following architecture: Process A * 10, Process B * 1. Each process A has to check with proces B on whether a particular item needs to be queried. So I was thinking of implementing multiprocessing.Pipe() object for all the As, and then have B listen to each of them. However, I realize that Multiprocessing.Pipe.recv is BLOCKING. so I don't really know how I can go about doing this. (if I use a loop to check which one has things sent through the other end that the loop will be blocked). There are suggestions for me to use twisted, but I am not sure how I should go about doing this in twisted: Should I create a defer on each pipe.handler from all the processes A and then when recv() receives something it goes on and complete a certain routine? I know personally twisted does not mix well with multiprocessing, but I have done some testing on twisted that are child processes of an multiprocessing implementation and I think this time it's workable. Any recommendations? A: Personally, I always tend to lean towards socket-based RPC, because that frees me from the confine of a single node if and when I need to expand more. Twisted offers a great way to handle socket-based communications, but of course there are other alternatives too. HTTP 1.1 is a great "transport" layer to use for such purposes, as it typically passes firewalls easily, is easily migrated into HTTPS if and when you need security, too. As for payloads over it, I may be somewhat of an eccentric for favoring JSON, but I've had a great time with it compared with XML or many other encodings. Though I have to admit that, now that Google's protobufs have been open-sourced, they're tempting too (especially as they ARE what we use internally, almost exclusively -- one sure gets used to them;-). Pity no specific RPC implementation of protobufs over HTTP has been open-sourced... but it's not THAT hard to cook up one for yourself;-). A: I'm satisfied with using REST-ful transaction design. This means using HTTP instead of pipes. If Process B has a queue of things for the various Process A's to do, it would work like this. Process B is an HTTP server, with RESTful URI's that handle queries from process A's. B is implemented using Python wsgiref or werkzeug or some other WSGI implementation. Mostly, B responds to GET requests from A. Each GET request takes the next thing off the queue and responds with it. Since B will have multiple concurrent requests, some kind of single-threaded queue is essential. The easiest way to assure this is to assure that the WSGI server is single-threaded. Each request is relatively fast, so single-threaded processing works out quite nicely. B has to have it's queue loaded, so it probably also responds to POST requests to enqueue things, too. Process A is an HTTP client, making requests of the RESTful URI's that Process B provides. A is implemented using urllib2 to make requests of B. A makes GET requests of B to get the next thing from the queue. A: Have you looked at MPI? http://en.wikipedia.org/wiki/Message_Passing_Interface. It is broadly available on UNIX/Linux/etc. I believe it can be had on Windows. Basically it provides all the plumbing that you'll have to build on top of RPC mechanisms, and it has many years of development and refinement behind it. It is a spec for an API, originally done in C so works with C++ too, and there are Python implementations of it out there too.
RPC for multiprocessing, design issues
what's a good way to do rpc across multiprocessing.Process'es ? I am also open to design advise on the following architecture: Process A * 10, Process B * 1. Each process A has to check with proces B on whether a particular item needs to be queried. So I was thinking of implementing multiprocessing.Pipe() object for all the As, and then have B listen to each of them. However, I realize that Multiprocessing.Pipe.recv is BLOCKING. so I don't really know how I can go about doing this. (if I use a loop to check which one has things sent through the other end that the loop will be blocked). There are suggestions for me to use twisted, but I am not sure how I should go about doing this in twisted: Should I create a defer on each pipe.handler from all the processes A and then when recv() receives something it goes on and complete a certain routine? I know personally twisted does not mix well with multiprocessing, but I have done some testing on twisted that are child processes of an multiprocessing implementation and I think this time it's workable. Any recommendations?
[ "Personally, I always tend to lean towards socket-based RPC, because that frees me from the confine of a single node if and when I need to expand more. Twisted offers a great way to handle socket-based communications, but of course there are other alternatives too. HTTP 1.1 is a great \"transport\" layer to use for such purposes, as it typically passes firewalls easily, is easily migrated into HTTPS if and when you need security, too. As for payloads over it, I may be somewhat of an eccentric for favoring JSON, but I've had a great time with it compared with XML or many other encodings. Though I have to admit that, now that Google's protobufs have been open-sourced, they're tempting too (especially as they ARE what we use internally, almost exclusively -- one sure gets used to them;-). Pity no specific RPC implementation of protobufs over HTTP has been open-sourced... but it's not THAT hard to cook up one for yourself;-).\n", "I'm satisfied with using REST-ful transaction design.\nThis means using HTTP instead of pipes.\nIf Process B has a queue of things for the various Process A's to do, it would work like this.\nProcess B is an HTTP server, with RESTful URI's that handle queries from process A's. B is implemented using Python wsgiref or werkzeug or some other WSGI implementation.\nMostly, B responds to GET requests from A. Each GET request takes the next thing off the queue and responds with it. Since B will have multiple concurrent requests, some kind of single-threaded queue is essential. The easiest way to assure this is to assure that the WSGI server is single-threaded. Each request is relatively fast, so single-threaded processing works out quite nicely.\nB has to have it's queue loaded, so it probably also responds to POST requests to enqueue things, too.\nProcess A is an HTTP client, making requests of the RESTful URI's that Process B provides. A is implemented using urllib2 to make requests of B. A makes GET requests of B to get the next thing from the queue.\n", "Have you looked at MPI? http://en.wikipedia.org/wiki/Message_Passing_Interface.\nIt is broadly available on UNIX/Linux/etc. I believe it can be had on Windows. Basically it provides all the plumbing that you'll have to build on top of RPC mechanisms, and it has many years of development and refinement behind it. It is a spec for an API, originally done in C so works with C++ too, and there are Python implementations of it out there too.\n" ]
[ 6, 1, 1 ]
[]
[]
[ "multiprocessing", "python", "rpc" ]
stackoverflow_0001353055_multiprocessing_python_rpc.txt
Q: Inserting two related objects fail in SQLAlchemy I'm getting the (probably trivial) error, but completely clueless about the possible causes. I want to insert two object in the DB using SQLAlchemy. Those objects are related, here are the declarations. Class User: class User(Base): __tablename__ = 'cp_user' id = Column(Integer, Sequence('id_seq'), primary_key=True) # ... more properties Class Picture (user may have many of them): class Picture(Base): __tablename__ = 'picture' id = Column(Integer, Sequence('id_seq'), primary_key=True) authorId = Column('author_id', Integer, ForeignKey('cp_user.id')) author = relation(User, primaryjoin = authorId == User.id) # ... more properties I'm trying to insert the new picture after I've fetched the right user from the DB, or just created it: s = newSession() user = s.query(User.name).filter("...some filter here...").first() if not(user): user = User() s.add(user) s.commit() picture = Picture() picture.author = user s.add(picture) s.commit() This fails with the exception: AttributeError: 'RowTuple' object has no attribute '_sa_instance_state' I tried moving assignment of the author to the constructor -- same error. I can't assign IDs directly -- this breaks the idea of ORM. What do I do wrong? A: Your code fails if the not(user) branch is not taken. You query User.name which is a column and not a bound object. user = s.query(User).filter("...some filter here...").first() An object gets it's id designed as soon as it is transmitted to the database. You are doing this in the branch with a commit. This is probably not what you want. You should issue a flush. Read the docs on the difference. Also you should not need to commit the newly created user. If you assign a user object to a relation, this should be handled transparently. Every commit closes a transaction, which can be quite costly (locking, disk seeks, etc)
Inserting two related objects fail in SQLAlchemy
I'm getting the (probably trivial) error, but completely clueless about the possible causes. I want to insert two object in the DB using SQLAlchemy. Those objects are related, here are the declarations. Class User: class User(Base): __tablename__ = 'cp_user' id = Column(Integer, Sequence('id_seq'), primary_key=True) # ... more properties Class Picture (user may have many of them): class Picture(Base): __tablename__ = 'picture' id = Column(Integer, Sequence('id_seq'), primary_key=True) authorId = Column('author_id', Integer, ForeignKey('cp_user.id')) author = relation(User, primaryjoin = authorId == User.id) # ... more properties I'm trying to insert the new picture after I've fetched the right user from the DB, or just created it: s = newSession() user = s.query(User.name).filter("...some filter here...").first() if not(user): user = User() s.add(user) s.commit() picture = Picture() picture.author = user s.add(picture) s.commit() This fails with the exception: AttributeError: 'RowTuple' object has no attribute '_sa_instance_state' I tried moving assignment of the author to the constructor -- same error. I can't assign IDs directly -- this breaks the idea of ORM. What do I do wrong?
[ "Your code fails if the not(user) branch is not taken.\nYou query User.name which is a column and not a bound object.\nuser = s.query(User).filter(\"...some filter here...\").first()\n\nAn object gets it's id designed as soon as it is transmitted to the database. You are doing this in the branch with a commit. This is probably not what you want. You should issue a flush. Read the docs on the difference.\nAlso you should not need to commit the newly created user. If you assign a user object to a relation, this should be handled transparently.\nEvery commit closes a transaction, which can be quite costly (locking, disk seeks, etc)\n" ]
[ 5 ]
[]
[]
[ "orm", "python", "sql", "sqlalchemy" ]
stackoverflow_0001569112_orm_python_sql_sqlalchemy.txt
Q: App Engine Python how to handle urls? I just want to ask a simple question, as I don't imagine how to do it. In the app.yaml, when I want to declare query string parameter, how do I do it? For example, to make a multi language site, I create the url in this format: mysite.com/english/aboutus mysite.com/italiano/aboutus and in app.yaml the script to handle them are - url: /english/aboutus script: index.py - url: /italiano/aboutus script: index.py In which way can I determine the difference between these two urls, and how to handle them in index.py? I know this is simple question, I could look around for references, but it might help for others in stackoverflow.com as well. A: I remember doing something like this: in app.yaml put - url: /(.*)/(.*)/? script: main.py and in main.py class MainHandler(webapp.RequestHandler): def get(self, Urlpart1, Urlpart2): def main(): application = webapp.WSGIApplication([('/(.*)/(.*)/', MainHandler), ('/(.*)/(.*)', MainHandler)], debug=True) where Urlparts are words between slashes A: Instead you could use the webapp framework to handle the URL's. For example, in index.py application = webapp.WSGIApplication( [('/english', EnglishHandler)], [('/italiano', ItalianHandler)], debug=True) More information can be found here. http://code.google.com/appengine/docs/python/gettingstarted/usingwebapp.html A: The SCRIPT_NAME environ entry contains the path under which your script was invoked. Haven't tested this in GAE specifically, but it's something WSGI inherited from CGI. language= environ['SCRIPT_NAME'][1:].split('/', 1)[0] if language not in ('english', 'italiano'): language= 'english' A: There're 39 human languages supported. Best way seems comply via lib/django/django/conf/locale/ Here's an app that translates all engines messages via parameter hl=[languageCode] [code disposable]2
App Engine Python how to handle urls?
I just want to ask a simple question, as I don't imagine how to do it. In the app.yaml, when I want to declare query string parameter, how do I do it? For example, to make a multi language site, I create the url in this format: mysite.com/english/aboutus mysite.com/italiano/aboutus and in app.yaml the script to handle them are - url: /english/aboutus script: index.py - url: /italiano/aboutus script: index.py In which way can I determine the difference between these two urls, and how to handle them in index.py? I know this is simple question, I could look around for references, but it might help for others in stackoverflow.com as well.
[ "I remember doing something like this:\nin app.yaml put\n- url: /(.*)/(.*)/?\n script: main.py\n\nand in main.py\nclass MainHandler(webapp.RequestHandler):\n def get(self, Urlpart1, Urlpart2):\n\ndef main():\n application = webapp.WSGIApplication([('/(.*)/(.*)/', MainHandler),\n ('/(.*)/(.*)', MainHandler)], \n debug=True)\n\nwhere Urlparts are words between slashes \n", "Instead you could use the webapp framework to handle the URL's.\nFor example, in index.py\napplication = webapp.WSGIApplication(\n [('/english', EnglishHandler)],\n [('/italiano', ItalianHandler)],\n debug=True)\n\nMore information can be found here. http://code.google.com/appengine/docs/python/gettingstarted/usingwebapp.html\n", "The SCRIPT_NAME environ entry contains the path under which your script was invoked. Haven't tested this in GAE specifically, but it's something WSGI inherited from CGI.\nlanguage= environ['SCRIPT_NAME'][1:].split('/', 1)[0]\nif language not in ('english', 'italiano'):\n language= 'english'\n\n", "There're 39 human languages supported. Best way seems comply via lib/django/django/conf/locale/\nHere's an app that translates all engines messages via parameter hl=[languageCode]\n[code disposable]2\n" ]
[ 4, 2, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001499485_google_app_engine_python.txt
Q: Library to read a MySQL dump? I am looking for a library that will allow me to read a mysql dump. I don't want to have to create a MySQL database and import the library and use the MySQL API. I would prefer simply a library that can parse the mysql dump format. I prefer a python library, but other scripting languages are okay. A: Import into MySQL and dump using --xml seems to be the best option. I wrote up the reasoning in this blog post: Use flag –xml when you run mysqldump A: I came across sqldump.py while looking for something similar - might be of use...
Library to read a MySQL dump?
I am looking for a library that will allow me to read a mysql dump. I don't want to have to create a MySQL database and import the library and use the MySQL API. I would prefer simply a library that can parse the mysql dump format. I prefer a python library, but other scripting languages are okay.
[ "Import into MySQL and dump using --xml seems to be the best option.\nI wrote up the reasoning in this blog post: Use flag –xml when you run mysqldump\n", "I came across sqldump.py while looking for something similar - might be of use...\n" ]
[ 5, 1 ]
[]
[]
[ "api", "mysql", "mysqldump", "python" ]
stackoverflow_0001568838_api_mysql_mysqldump_python.txt
Q: How to use Python to log into Facebook/Myspace and crawl the content? Right now, I can crawl regular pages using urllib2. request = urllib2.Request('http://stackoverflow.com') request.add_header('User-Agent',random.choice(agents)) response = urllib2.urlopen(request) htmlSource = response.read() print htmlSource However...I would like to simulate a POST (or fake sessions)? so that I can go into Facebook and crawl. How do I do that? A: You'll need to keep the cookie your site of choice sends you when you log in; that's what keeps your session. With urllib2, you do this by creating an Opener object that supports cookie processing: import urllib2, cookielib jar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) With this opener, you can do requests, either GET or POST: content = opener.open(urllib2.Request( "http://social.netwo.rk/login", "user=foo&pass=bar") ).read() As there's a second parameter to urllib2.Request, it'll be a POST request -- if that's None, you end up with a GET request. You can also add HTTP headers, either with .add_header or by handing the constructor a dictionary (or a tuple-tuple) of headers. Read the manual for urllib2.Request for more information. That should get you started! Good luck. (ps: If you don't need read access to the cookies, you can just omit creating the cookie jar yourself; the HTTPCookieProcessor will do it for you.) A: The Mechanize library is an easy way to emulate a browser in Python. A: You can do POST requests by first encoding the data using urllib, and then sending the request using urllib2 just as you are doing now. This is explained in this article. A: OR you may use PyCurl as a choice...
How to use Python to log into Facebook/Myspace and crawl the content?
Right now, I can crawl regular pages using urllib2. request = urllib2.Request('http://stackoverflow.com') request.add_header('User-Agent',random.choice(agents)) response = urllib2.urlopen(request) htmlSource = response.read() print htmlSource However...I would like to simulate a POST (or fake sessions)? so that I can go into Facebook and crawl. How do I do that?
[ "You'll need to keep the cookie your site of choice sends you when you log in; that's what keeps your session. With urllib2, you do this by creating an Opener object that supports cookie processing:\nimport urllib2, cookielib\njar = cookielib.CookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))\n\nWith this opener, you can do requests, either GET or POST:\ncontent = opener.open(urllib2.Request(\n \"http://social.netwo.rk/login\",\n \"user=foo&pass=bar\")\n).read()\n\nAs there's a second parameter to urllib2.Request, it'll be a POST request -- if that's None, you end up with a GET request. You can also add HTTP headers, either with .add_header or by handing the constructor a dictionary (or a tuple-tuple) of headers. Read the manual for urllib2.Request for more information.\nThat should get you started! Good luck.\n(ps: If you don't need read access to the cookies, you can just omit creating the cookie jar yourself; the HTTPCookieProcessor will do it for you.)\n", "The Mechanize library is an easy way to emulate a browser in Python.\n", "You can do POST requests by first encoding the data using urllib, and then sending the request using urllib2 just as you are doing now.\nThis is explained in this article.\n", "OR you may use PyCurl as a choice...\n" ]
[ 7, 4, 1, 1 ]
[]
[]
[ "authentication", "post", "python", "session", "web_crawler" ]
stackoverflow_0001569206_authentication_post_python_session_web_crawler.txt
Q: How to create a custom 404 page for my Django/Apache? I know that you use .htaccess in the document-root directory in standard Apache. What if I use Django? Can someone give me step by step how to create a custom 404 page? A: The default 404 handler calls 404.html . You could edit that if you don't need anything fancy or can override the 404 handler by setting the handler404 view -- more here
How to create a custom 404 page for my Django/Apache?
I know that you use .htaccess in the document-root directory in standard Apache. What if I use Django? Can someone give me step by step how to create a custom 404 page?
[ "The default 404 handler calls 404.html . You could edit that if you don't need anything fancy or can override the 404 handler by setting the handler404 view -- more here\n" ]
[ 14 ]
[]
[]
[ "apache", "django", "python" ]
stackoverflow_0001569682_apache_django_python.txt
Q: Relative imports from __init__ in multi-file Django apps I have a Django project located at /var/django/project/ where /var/django/ is in the PATH within that project I have: ___init__.py manage.py utils/ __init__.py tools.py utils/__init__.py contains a function named get_preview utils/tools.py contains a function named get_related How can utils/__init__.py import get_related from utils/tools.py? How can utils/tools.py import get_preview from utils/__init_.py? I have tried relative imports as well as static imports but seem to get an error in tools.py when I try to from project.utils import get_preview A: You can't (and shouldn't). You are structuring your code very poorly if files in your module are referencing code in the __init__.py associated with it. Either move both functions into __init__.py or both of them out of __init__.py or put them into separate modules. Those are your only options. A: Yeah, this is bad structure. You gotta watch out here with creating a circular import between the two files. About circular imports. A: You can do it, you just need to make one of the imports happen at runtime to avoid the circular import. For example, __init__.py: from project.utils.tools import get_related def get_preview(): # ... and tools.py: def get_related(): from project.utils import get_preview # ... get_preview()
Relative imports from __init__ in multi-file Django apps
I have a Django project located at /var/django/project/ where /var/django/ is in the PATH within that project I have: ___init__.py manage.py utils/ __init__.py tools.py utils/__init__.py contains a function named get_preview utils/tools.py contains a function named get_related How can utils/__init__.py import get_related from utils/tools.py? How can utils/tools.py import get_preview from utils/__init_.py? I have tried relative imports as well as static imports but seem to get an error in tools.py when I try to from project.utils import get_preview
[ "You can't (and shouldn't). You are structuring your code very poorly if files in your module are referencing code in the __init__.py associated with it. Either move both functions into __init__.py or both of them out of __init__.py or put them into separate modules. Those are your only options.\n", "Yeah, this is bad structure. You gotta watch out here with creating a circular import between the two files. \nAbout circular imports.\n", "You can do it, you just need to make one of the imports happen at runtime to avoid the circular import.\nFor example, __init__.py:\nfrom project.utils.tools import get_related\n\ndef get_preview():\n # ...\n\nand tools.py:\ndef get_related():\n from project.utils import get_preview\n # ...\n get_preview()\n\n" ]
[ 2, 2, 0 ]
[]
[]
[ "django", "import", "python" ]
stackoverflow_0001569703_django_import_python.txt
Q: Django - how can I get permalink to work with "throwaway" slug I'm trying to add slugs to the url in my django app, much like SO does. Currently, I have pages that work just fine with a url like this: http://example.com/foo/123/ I'd like to add 'slugified' urls like so: http://example.com/foo/123/foo-name-here I can get it to work just fine, by simply modifying the urlconf and adding a throwaway value to the view function: #urls.py ulpatterns = patterns('project.app.views', url(r'^foo/(?P<foo_id>\d+)/(?P<name_slug>\w+)/$', 'foo_detail', name='foo_detail'), ) #views.py: def foo_detail(request, foo_id, name_slug): # stuff here, name slug is just discarded Visting the url with the slug works just fine. However, my problem is when I am using @models.permalink. For my Foo model, I used to have the following, which worked just fine: @models.permalink def get_absolute_url(self): return ('foo_detail', [str(self.id),]) However, after my change, whenever I call {{ foo.get_absolute_url }} in my templates, the result is always an empty string. I have tried the following two replacements for get_absolute_url, neither of which is working: from django.template.defaultfilters import slugify # attempt 1 @models.permalink def get_absolute_url(self): return ('foo_detail', [str(self.id), slugify(self.name)]) # attempt 2 @models.permalink def get_absolute_url(self): return ('foo_detail', (), { 'foo_id': str(self.id), 'name_slug': slugify(self.name), }) Note that if I add a print slugify(self.name) before returning, the slugified name is showing up in the console just fine. When invoking {{ foo.get_absolute_url }} in my templates, the result is always an empty string, and I don't get any errors. I know I could replace the method with return '/foo/%s/%s' % (str(self.id), slugify(self.name)), but I'm trying to get the permalink working so that my URL is only defined in one place. What am I doing wrong? A: One thing to check for, because I also ran into this problem: (?P<name_slug>\w+) Is slugify adding hyphens anywhere? If so the regex won't match, hypens are a non-word character. To fix use [\w-]+ or similar.
Django - how can I get permalink to work with "throwaway" slug
I'm trying to add slugs to the url in my django app, much like SO does. Currently, I have pages that work just fine with a url like this: http://example.com/foo/123/ I'd like to add 'slugified' urls like so: http://example.com/foo/123/foo-name-here I can get it to work just fine, by simply modifying the urlconf and adding a throwaway value to the view function: #urls.py ulpatterns = patterns('project.app.views', url(r'^foo/(?P<foo_id>\d+)/(?P<name_slug>\w+)/$', 'foo_detail', name='foo_detail'), ) #views.py: def foo_detail(request, foo_id, name_slug): # stuff here, name slug is just discarded Visting the url with the slug works just fine. However, my problem is when I am using @models.permalink. For my Foo model, I used to have the following, which worked just fine: @models.permalink def get_absolute_url(self): return ('foo_detail', [str(self.id),]) However, after my change, whenever I call {{ foo.get_absolute_url }} in my templates, the result is always an empty string. I have tried the following two replacements for get_absolute_url, neither of which is working: from django.template.defaultfilters import slugify # attempt 1 @models.permalink def get_absolute_url(self): return ('foo_detail', [str(self.id), slugify(self.name)]) # attempt 2 @models.permalink def get_absolute_url(self): return ('foo_detail', (), { 'foo_id': str(self.id), 'name_slug': slugify(self.name), }) Note that if I add a print slugify(self.name) before returning, the slugified name is showing up in the console just fine. When invoking {{ foo.get_absolute_url }} in my templates, the result is always an empty string, and I don't get any errors. I know I could replace the method with return '/foo/%s/%s' % (str(self.id), slugify(self.name)), but I'm trying to get the permalink working so that my URL is only defined in one place. What am I doing wrong?
[ "One thing to check for, because I also ran into this problem:\n(?P<name_slug>\\w+)\n\nIs slugify adding hyphens anywhere? If so the regex won't match, hypens are a non-word character. To fix use [\\w-]+ or similar.\n" ]
[ 7 ]
[]
[]
[ "django", "django_urls", "permalinks", "python" ]
stackoverflow_0001569837_django_django_urls_permalinks_python.txt
Q: How to install matplotlib without gcc errors? I downloaded the source and untarred it. sudo python setup.py install And below are the errors I get. By the way, Numpy is installed. src/_image.cpp:5:17: error: png.h: No such file or directory src/_image.cpp: In member function 'Py::Object Image::write_png(const Py::Tuple&)': src/_image.cpp:646: error: 'png_structp' was not declared in this scope src/_image.cpp:646: error: expected `;' before 'png_ptr' src/_image.cpp:647: error: 'png_infop' was not declared in this scope src/_image.cpp:647: error: expected `;' before 'info_ptr' src/_image.cpp:648: error: aggregate 'png_color_8_struct sig_bit' has incomplete type and cannot be defined src/_image.cpp:649: error: 'png_uint_32' was not declared in this scope src/_image.cpp:649: error: expected `;' before 'row' src/_image.cpp:652: error: 'png_bytep' was not declared in this scope src/_image.cpp:652: error: 'row_pointers' was not declared in this scope src/_image.cpp:652: error: expected type-specifier before 'png_bytep' src/_image.cpp:652: error: expected `;' before 'png_bytep' src/_image.cpp:654: error: 'row' was not declared in this scope src/_image.cpp:660: error: type '<type error>' argument given to 'delete', expected pointer src/_image.cpp:665: error: 'png_ptr' was not declared in this scope src/_image.cpp:665: error: 'PNG_LIBPNG_VER_STRING' was not declared in this scope src/_image.cpp:665: error: 'png_create_write_struct' was not declared in this scope src/_image.cpp:669: error: type '<type error>' argument given to 'delete', expected pointer src/_image.cpp:673: error: 'info_ptr' was not declared in this scope src/_image.cpp:673: error: 'png_create_info_struct' was not declared in this scope src/_image.cpp:677: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:678: error: type '<type error>' argument given to 'delete', expected pointer src/_image.cpp:685: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:686: error: type '<type error>' argument given to 'delete', expected pointer src/_image.cpp:690: error: 'png_init_io' was not declared in this scope src/_image.cpp:693: error: 'PNG_COLOR_TYPE_RGB_ALPHA' was not declared in this scope src/_image.cpp:693: error: 'PNG_INTERLACE_NONE' was not declared in this scope src/_image.cpp:694: error: 'PNG_COMPRESSION_TYPE_BASE' was not declared in this scope src/_image.cpp:694: error: 'PNG_FILTER_TYPE_BASE' was not declared in this scope src/_image.cpp:694: error: 'png_set_IHDR' was not declared in this scope src/_image.cpp:703: error: 'png_set_sBIT' was not declared in this scope src/_image.cpp:705: error: 'png_write_info' was not declared in this scope src/_image.cpp:706: error: 'png_write_image' was not declared in this scope src/_image.cpp:707: error: 'png_write_end' was not declared in this scope src/_image.cpp:708: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:711: error: type '<type error>' argument given to 'delete', expected pointer src/_image.cpp: In member function 'Py::Object _image_module::readpng(const Py::Tuple&)': src/_image.cpp:860: error: 'png_byte' was not declared in this scope src/_image.cpp:860: error: expected `;' before 'header' src/_image.cpp:866: error: 'header' was not declared in this scope src/_image.cpp:868: error: 'header' was not declared in this scope src/_image.cpp:868: error: 'png_sig_cmp' was not declared in this scope src/_image.cpp:873: error: 'png_structp' was not declared in this scope src/_image.cpp:873: error: expected `;' before 'png_ptr' src/_image.cpp:875: error: 'png_ptr' was not declared in this scope src/_image.cpp:878: error: 'png_infop' was not declared in this scope src/_image.cpp:878: error: expected `;' before 'info_ptr' src/_image.cpp:879: error: 'info_ptr' was not declared in this scope src/_image.cpp:882: error: 'png_ptr' was not declared in this scope src/_image.cpp:882: error: 'png_jmpbuf' was not declared in this scope src/_image.cpp:885: error: 'png_ptr' was not declared in this scope src/_image.cpp:885: error: 'png_init_io' was not declared in this scope src/_image.cpp:886: error: 'png_set_sig_bytes' was not declared in this scope src/_image.cpp:888: error: 'info_ptr' was not declared in this scope src/_image.cpp:888: error: 'png_read_info' was not declared in this scope src/_image.cpp:890: error: 'png_uint_32' was not declared in this scope src/_image.cpp:890: error: expected `;' before 'width' src/_image.cpp:891: error: expected `;' before 'height' src/_image.cpp:894: error: 'PNG_COLOR_TYPE_GRAY' was not declared in this scope src/_image.cpp:895: error: 'PNG_COLOR_TYPE_GRAY_ALPHA' was not declared in this scope src/_image.cpp:896: error: 'png_set_gray_to_rgb' was not declared in this scope src/_image.cpp:897: error: 'PNG_COLOR_TYPE_PALETTE' was not declared in this scope src/_image.cpp:898: error: 'png_set_palette_to_rgb' was not declared in this scope src/_image.cpp:902: error: 'png_set_strip_16' was not declared in this scope src/_image.cpp:905: error: 'png_set_interlace_handling' was not declared in this scope src/_image.cpp:906: error: 'png_read_update_info' was not declared in this scope src/_image.cpp:908: error: 'PNG_COLOR_TYPE_RGBA' was not declared in this scope src/_image.cpp:909: error: 'PNG_COLOR_TYPE_RGB' was not declared in this scope src/_image.cpp:915: error: 'png_jmpbuf' was not declared in this scope src/_image.cpp:918: error: 'png_bytep' was not declared in this scope src/_image.cpp:918: error: 'row_pointers' was not declared in this scope src/_image.cpp:918: error: expected type-specifier before 'png_bytep' src/_image.cpp:918: error: expected `;' before 'png_bytep' src/_image.cpp:919: error: expected `;' before 'row' src/_image.cpp:921: error: 'row' was not declared in this scope src/_image.cpp:921: error: 'height' was not declared in this scope src/_image.cpp:922: error: expected type-specifier before 'png_byte' src/_image.cpp:922: error: expected `;' before 'png_byte' src/_image.cpp:924: error: 'png_read_image' was not declared in this scope src/_image.cpp:929: error: 'height' was not declared in this scope src/_image.cpp:930: error: 'width' was not declared in this scope src/_image.cpp:936: error: expected `;' before 'y' src/_image.cpp:936: error: 'y' was not declared in this scope src/_image.cpp:938: error: expected `;' before 'x' src/_image.cpp:938: error: 'x' was not declared in this scope src/_image.cpp:940: error: 'ptr' was not declared in this scope src/_image.cpp:951: error: 'png_read_end' was not declared in this scope src/_image.cpp:952: error: 'png_infopp_NULL' was not declared in this scope src/_image.cpp:952: error: 'png_destroy_read_struct' was not declared in this scope src/_image.cpp:956: error: type '<type error>' argument given to 'delete', expected pointer error: command 'gcc' failed with exit status 1 A: Those particular errors stem from the lack of the development package for libpng. If you use Debian/Ubuntu, try apt-get install libpng-dev first. A: if you are apt-based try $ sudo apt-get build-dep matplotlib A: You don't need to compile from source: sudo apt-get install python-matplotlib The easy way out.
How to install matplotlib without gcc errors?
I downloaded the source and untarred it. sudo python setup.py install And below are the errors I get. By the way, Numpy is installed. src/_image.cpp:5:17: error: png.h: No such file or directory src/_image.cpp: In member function 'Py::Object Image::write_png(const Py::Tuple&)': src/_image.cpp:646: error: 'png_structp' was not declared in this scope src/_image.cpp:646: error: expected `;' before 'png_ptr' src/_image.cpp:647: error: 'png_infop' was not declared in this scope src/_image.cpp:647: error: expected `;' before 'info_ptr' src/_image.cpp:648: error: aggregate 'png_color_8_struct sig_bit' has incomplete type and cannot be defined src/_image.cpp:649: error: 'png_uint_32' was not declared in this scope src/_image.cpp:649: error: expected `;' before 'row' src/_image.cpp:652: error: 'png_bytep' was not declared in this scope src/_image.cpp:652: error: 'row_pointers' was not declared in this scope src/_image.cpp:652: error: expected type-specifier before 'png_bytep' src/_image.cpp:652: error: expected `;' before 'png_bytep' src/_image.cpp:654: error: 'row' was not declared in this scope src/_image.cpp:660: error: type '<type error>' argument given to 'delete', expected pointer src/_image.cpp:665: error: 'png_ptr' was not declared in this scope src/_image.cpp:665: error: 'PNG_LIBPNG_VER_STRING' was not declared in this scope src/_image.cpp:665: error: 'png_create_write_struct' was not declared in this scope src/_image.cpp:669: error: type '<type error>' argument given to 'delete', expected pointer src/_image.cpp:673: error: 'info_ptr' was not declared in this scope src/_image.cpp:673: error: 'png_create_info_struct' was not declared in this scope src/_image.cpp:677: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:678: error: type '<type error>' argument given to 'delete', expected pointer src/_image.cpp:685: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:686: error: type '<type error>' argument given to 'delete', expected pointer src/_image.cpp:690: error: 'png_init_io' was not declared in this scope src/_image.cpp:693: error: 'PNG_COLOR_TYPE_RGB_ALPHA' was not declared in this scope src/_image.cpp:693: error: 'PNG_INTERLACE_NONE' was not declared in this scope src/_image.cpp:694: error: 'PNG_COMPRESSION_TYPE_BASE' was not declared in this scope src/_image.cpp:694: error: 'PNG_FILTER_TYPE_BASE' was not declared in this scope src/_image.cpp:694: error: 'png_set_IHDR' was not declared in this scope src/_image.cpp:703: error: 'png_set_sBIT' was not declared in this scope src/_image.cpp:705: error: 'png_write_info' was not declared in this scope src/_image.cpp:706: error: 'png_write_image' was not declared in this scope src/_image.cpp:707: error: 'png_write_end' was not declared in this scope src/_image.cpp:708: error: 'png_destroy_write_struct' was not declared in this scope src/_image.cpp:711: error: type '<type error>' argument given to 'delete', expected pointer src/_image.cpp: In member function 'Py::Object _image_module::readpng(const Py::Tuple&)': src/_image.cpp:860: error: 'png_byte' was not declared in this scope src/_image.cpp:860: error: expected `;' before 'header' src/_image.cpp:866: error: 'header' was not declared in this scope src/_image.cpp:868: error: 'header' was not declared in this scope src/_image.cpp:868: error: 'png_sig_cmp' was not declared in this scope src/_image.cpp:873: error: 'png_structp' was not declared in this scope src/_image.cpp:873: error: expected `;' before 'png_ptr' src/_image.cpp:875: error: 'png_ptr' was not declared in this scope src/_image.cpp:878: error: 'png_infop' was not declared in this scope src/_image.cpp:878: error: expected `;' before 'info_ptr' src/_image.cpp:879: error: 'info_ptr' was not declared in this scope src/_image.cpp:882: error: 'png_ptr' was not declared in this scope src/_image.cpp:882: error: 'png_jmpbuf' was not declared in this scope src/_image.cpp:885: error: 'png_ptr' was not declared in this scope src/_image.cpp:885: error: 'png_init_io' was not declared in this scope src/_image.cpp:886: error: 'png_set_sig_bytes' was not declared in this scope src/_image.cpp:888: error: 'info_ptr' was not declared in this scope src/_image.cpp:888: error: 'png_read_info' was not declared in this scope src/_image.cpp:890: error: 'png_uint_32' was not declared in this scope src/_image.cpp:890: error: expected `;' before 'width' src/_image.cpp:891: error: expected `;' before 'height' src/_image.cpp:894: error: 'PNG_COLOR_TYPE_GRAY' was not declared in this scope src/_image.cpp:895: error: 'PNG_COLOR_TYPE_GRAY_ALPHA' was not declared in this scope src/_image.cpp:896: error: 'png_set_gray_to_rgb' was not declared in this scope src/_image.cpp:897: error: 'PNG_COLOR_TYPE_PALETTE' was not declared in this scope src/_image.cpp:898: error: 'png_set_palette_to_rgb' was not declared in this scope src/_image.cpp:902: error: 'png_set_strip_16' was not declared in this scope src/_image.cpp:905: error: 'png_set_interlace_handling' was not declared in this scope src/_image.cpp:906: error: 'png_read_update_info' was not declared in this scope src/_image.cpp:908: error: 'PNG_COLOR_TYPE_RGBA' was not declared in this scope src/_image.cpp:909: error: 'PNG_COLOR_TYPE_RGB' was not declared in this scope src/_image.cpp:915: error: 'png_jmpbuf' was not declared in this scope src/_image.cpp:918: error: 'png_bytep' was not declared in this scope src/_image.cpp:918: error: 'row_pointers' was not declared in this scope src/_image.cpp:918: error: expected type-specifier before 'png_bytep' src/_image.cpp:918: error: expected `;' before 'png_bytep' src/_image.cpp:919: error: expected `;' before 'row' src/_image.cpp:921: error: 'row' was not declared in this scope src/_image.cpp:921: error: 'height' was not declared in this scope src/_image.cpp:922: error: expected type-specifier before 'png_byte' src/_image.cpp:922: error: expected `;' before 'png_byte' src/_image.cpp:924: error: 'png_read_image' was not declared in this scope src/_image.cpp:929: error: 'height' was not declared in this scope src/_image.cpp:930: error: 'width' was not declared in this scope src/_image.cpp:936: error: expected `;' before 'y' src/_image.cpp:936: error: 'y' was not declared in this scope src/_image.cpp:938: error: expected `;' before 'x' src/_image.cpp:938: error: 'x' was not declared in this scope src/_image.cpp:940: error: 'ptr' was not declared in this scope src/_image.cpp:951: error: 'png_read_end' was not declared in this scope src/_image.cpp:952: error: 'png_infopp_NULL' was not declared in this scope src/_image.cpp:952: error: 'png_destroy_read_struct' was not declared in this scope src/_image.cpp:956: error: type '<type error>' argument given to 'delete', expected pointer error: command 'gcc' failed with exit status 1
[ "Those particular errors stem from the lack of the development package for libpng.\nIf you use Debian/Ubuntu, try apt-get install libpng-dev first.\n", "if you are apt-based try\n$ sudo apt-get build-dep matplotlib\n", "You don't need to compile from source:\n \n sudo apt-get install python-matplotlib\n \nThe easy way out.\n" ]
[ 20, 9, 4 ]
[]
[]
[ "installation", "matplotlib", "python" ]
stackoverflow_0001570495_installation_matplotlib_python.txt
Q: Pylons/Formencode With Multiple Checkboxes I ran up against a few problems with Pylons/Formencode today when it came to validating multiple checkboxes. As a bit of background I have something like this in my Mako template: <input type="checkbox" name="Project" value="1">Project 1</input> <input type="checkbox" name="Project" value="2">Project 2</input> <input type="checkbox" name="Project" value="3">Project 3</input> <input type="checkbox" name="Project" value="4">Project 4</input> <input type="checkbox" name="Project" value="5">Project 5</input> In my validation schema I had something like this (please forgive any errors - I don't have the exact code infront of me): Project = formencode.foreach.ForEach(formencode.validators.Int()) I was expecting to get a list back of checked items (sounds reasonable, right?) but instead I got a list with a single item despite having all boxes checked. Am I doing this wrong or is what I want to get back even possible? I have written a hack around it with onclicks for each checkbox item that appends the checked item to an array which is then posted back in JSON format - this is ugly and a pain since I have to repopulate all the fields myself if validation fails. Anyone have any ideas? A: maybe using formencode.validators.Set: >>> Set.to_python(None) [] >>> Set.to_python('this') ['this'] >>> Set.to_python(('this', 'that')) ['this', 'that'] >>> s = Set(use_set=True) >>> s.to_python(None) set([]) >>> s.to_python('this') set(['this']) >>> s.to_python(('this',)) set(['this'])
Pylons/Formencode With Multiple Checkboxes
I ran up against a few problems with Pylons/Formencode today when it came to validating multiple checkboxes. As a bit of background I have something like this in my Mako template: <input type="checkbox" name="Project" value="1">Project 1</input> <input type="checkbox" name="Project" value="2">Project 2</input> <input type="checkbox" name="Project" value="3">Project 3</input> <input type="checkbox" name="Project" value="4">Project 4</input> <input type="checkbox" name="Project" value="5">Project 5</input> In my validation schema I had something like this (please forgive any errors - I don't have the exact code infront of me): Project = formencode.foreach.ForEach(formencode.validators.Int()) I was expecting to get a list back of checked items (sounds reasonable, right?) but instead I got a list with a single item despite having all boxes checked. Am I doing this wrong or is what I want to get back even possible? I have written a hack around it with onclicks for each checkbox item that appends the checked item to an array which is then posted back in JSON format - this is ugly and a pain since I have to repopulate all the fields myself if validation fails. Anyone have any ideas?
[ "maybe using formencode.validators.Set:\n>>> Set.to_python(None)\n[]\n>>> Set.to_python('this')\n['this']\n>>> Set.to_python(('this', 'that'))\n['this', 'that']\n>>> s = Set(use_set=True)\n>>> s.to_python(None)\nset([])\n>>> s.to_python('this')\nset(['this'])\n>>> s.to_python(('this',))\nset(['this'])\n\n" ]
[ 2 ]
[ "redrockettt,\nHave you looked at the docstring to variabledecode? It suggests you use something like:\n<input type=\"checkbox\" name=\"Project-1\" value=\"1\">Project 1</input>\n<input type=\"checkbox\" name=\"Project-2\" value=\"2\">Project 2</input>\n<input type=\"checkbox\" name=\"Project-3\" value=\"3\">Project 3</input>\n\nCheck out the text in variabledecode.py, or pasted here.\n" ]
[ -1 ]
[ "formencode", "pylons", "python", "validation" ]
stackoverflow_0001565035_formencode_pylons_python_validation.txt
Q: In Python, how do I transform a string into a file? There is a read-only library function that takes a file as an argument. But I have a string. How do I convert a string to a file, that if you read the file it will return this string? I don't want to write to disk. A: The StringIO module: >>> import StringIO >>> f = StringIO.StringIO("foo") >>> f.read() 'foo' The cStringIO module has the same interface, and is faster, but can't deal with Unicode strings that have non-ASCII characters. StringIO documentation A: what do you want? if you want to read from file just use: file('/path/to/file').read() or open('/path/to/file','r').read() if you want to read string,just do as suggest by Phil
In Python, how do I transform a string into a file?
There is a read-only library function that takes a file as an argument. But I have a string. How do I convert a string to a file, that if you read the file it will return this string? I don't want to write to disk.
[ "The StringIO module:\n>>> import StringIO\n>>> f = StringIO.StringIO(\"foo\")\n>>> f.read()\n'foo'\n\nThe cStringIO module has the same interface, and is faster, but can't deal with Unicode strings that have non-ASCII characters.\nStringIO documentation\n", "what do you want?\nif you want to read from file just use:\nfile('/path/to/file').read()\n\nor\nopen('/path/to/file','r').read()\n\nif you want to read string,just do as suggest by Phil\n" ]
[ 15, 0 ]
[]
[]
[ "file", "python", "string", "types" ]
stackoverflow_0001570230_file_python_string_types.txt
Q: Displaying the Length of Individual Sequences in File I have a file that contains two sequences. I have a program that could read all sequences, combine them together, and display the length of both sequences together. Now I want to display the length individually. The two sequences are separated by the symbol >. Example: SEQ1 >ATGGGACTAGCAGT SEQ2 >AGGATGATGAGTGA Program: #!usr/bin/python import re fh=open('clostp1.fa','r') count=0 content=fh.readlines() fh.close() seq='' patt=re.compile('>(.*?)') for item in content: m=patt.match(item) if not m: s=item.replace('\n','') seq=seq+s seq=seq.replace('\s','') print seq print 'The length of the coding sequence of the bacillus' print len(seq) A: for line in open("clostp1.fa"): name, sequence = map(str.strip,line.split('>')) print "The length of %s is %s"%(name, len(sequence)) A: If I understood correctly, you want to print out each individual sequence followed by its length, right? I believe you just have a function to return the sequences and later do what ever yuo want with them. #!usr/bin/python import re def get_content(file): """ Returns a dict with the name of the seq and its value """ result = {} for current_line in open(file): name, value = line.strip().split(">") result[name] = value return result You get the dict and then print what ever you need to print. A: for line in open("clostp1.fa"): name, _, seq = line.partition('>') name, seq = name.rstrip(), seq.rstrip() print("The length of {} is {}".format(name, len(seq))) partition is more appropriate here then split. you need to rstrip each individual part, and formatting syntax will work in py3.1, use print("The length of {0} is {1}".format(name, len(seq))) to make it work in py2.6. A: import re pattern = re.compile('(?P<seqname>\w*)\s*>\s*(?P<seqval>\w*)') for item in open('clostp1.fa','r').readlines(): m = pattern.match(item) if m: print "sequence name: %s - %s length" % (m.groupdict()['seqname'],len(m.groupdict()['seqval']))
Displaying the Length of Individual Sequences in File
I have a file that contains two sequences. I have a program that could read all sequences, combine them together, and display the length of both sequences together. Now I want to display the length individually. The two sequences are separated by the symbol >. Example: SEQ1 >ATGGGACTAGCAGT SEQ2 >AGGATGATGAGTGA Program: #!usr/bin/python import re fh=open('clostp1.fa','r') count=0 content=fh.readlines() fh.close() seq='' patt=re.compile('>(.*?)') for item in content: m=patt.match(item) if not m: s=item.replace('\n','') seq=seq+s seq=seq.replace('\s','') print seq print 'The length of the coding sequence of the bacillus' print len(seq)
[ "for line in open(\"clostp1.fa\"):\n name, sequence = map(str.strip,line.split('>'))\n print \"The length of %s is %s\"%(name, len(sequence))\n\n", "If I understood correctly, you want to print out each individual sequence followed by its length, right? I believe you just have a function to return the sequences and later do what ever yuo want with them.\n#!usr/bin/python\nimport re\n\ndef get_content(file):\n \"\"\"\n Returns a dict with the name of the seq and its value\n \"\"\"\n result = {}\n for current_line in open(file):\n name, value = line.strip().split(\">\")\n result[name] = value\n return result\n\nYou get the dict and then print what ever you need to print.\n", "for line in open(\"clostp1.fa\"):\n name, _, seq = line.partition('>')\n name, seq = name.rstrip(), seq.rstrip()\n print(\"The length of {} is {}\".format(name, len(seq)))\n\npartition is more appropriate here then split. you need to rstrip each individual part, and formatting syntax will work in py3.1, use\nprint(\"The length of {0} is {1}\".format(name, len(seq)))\n\nto make it work in py2.6.\n", "import re\npattern = re.compile('(?P<seqname>\\w*)\\s*>\\s*(?P<seqval>\\w*)')\nfor item in open('clostp1.fa','r').readlines():\n m = pattern.match(item)\n if m:\n print \"sequence name: %s - %s length\" % (m.groupdict()['seqname'],len(m.groupdict()['seqval']))\n\n" ]
[ 4, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001570873_python.txt
Q: Vim, Python and curses I wrote a small python script for vim that uses the curses library. When I try to call the function curses complains about: Traceback (most recent call last): File "<string>", line 9, in <module> File "/usr/lib/python2.6/curses/__init__.py", line 33, in initscr fd=_sys.__stdout__.fileno()) _curses.error: setupterm: could not find terminal Don't know how to solve this Edit: GVIM complains Vim works fine A: I'm not very sure about the context, but "GVIM complains Vim works fine" is very insightful: curses are used in the console, gvim is run in a X window, thus there's no console.
Vim, Python and curses
I wrote a small python script for vim that uses the curses library. When I try to call the function curses complains about: Traceback (most recent call last): File "<string>", line 9, in <module> File "/usr/lib/python2.6/curses/__init__.py", line 33, in initscr fd=_sys.__stdout__.fileno()) _curses.error: setupterm: could not find terminal Don't know how to solve this Edit: GVIM complains Vim works fine
[ "I'm not very sure about the context, but \"GVIM complains Vim works fine\" is very insightful: curses are used in the console, gvim is run in a X window, thus there's no console.\n" ]
[ 7 ]
[]
[]
[ "curses", "python", "vim" ]
stackoverflow_0001571032_curses_python_vim.txt
Q: Average difference between dates in Python I have a series of datetime objects and would like to calculate the average delta between them. For example, if the input was (2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00), then the average delta would be exactly 00:10:00, or 10 minutes. Any suggestions on how to calculate this using Python? A: As far as algorithms go, that's an easy one. Just find the max and min datetimes, take the difference, and divide by the number of datetimes you looked at. If you have an array a of datetimes, you can do: mx = max(a) mn = min(a) avg = (mx-mn)/(len(a)-1) to get back the average difference. EDIT: fixed the off-by-one error A: Say a is your list sumdeltas = timedelta(seconds=0) i = 1 while i < len(a): sumdeltas += a[i-1] - a[i] i = i + 1 avg_delta = sumdeltas / (len(a) - 1) This will indeed average your deltas together. A: Since you seem to be throwing out the 20 minute delta between times 1 and 3 in your example, I'd say you should just sort the list of datetimes, add up the deltas between adjacent times, then divide by n-1. Do you have any code you can share with us, so we can help you debug it? A: You can subtract each successive date from the one prior (resulting in a timedelta object which represents the difference in days, seconds). You can then average the timedelta objects to find your answer. A: small clarification from datetime import timedelta def avg(a): numdeltas = len(a) - 1 sumdeltas = timedelta(seconds=0) i = 1 while i < len(a): delta = abs(a[i] - a[i-1]) try: sumdeltas += delta except: raise i += 1 avg = sumdeltas / numdeltas return avg
Average difference between dates in Python
I have a series of datetime objects and would like to calculate the average delta between them. For example, if the input was (2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00), then the average delta would be exactly 00:10:00, or 10 minutes. Any suggestions on how to calculate this using Python?
[ "As far as algorithms go, that's an easy one. Just find the max and min datetimes, take the difference, and divide by the number of datetimes you looked at.\nIf you have an array a of datetimes, you can do:\nmx = max(a)\nmn = min(a)\navg = (mx-mn)/(len(a)-1)\n\nto get back the average difference.\nEDIT: fixed the off-by-one error\n", "Say a is your list\nsumdeltas = timedelta(seconds=0)\ni = 1\nwhile i < len(a):\n sumdeltas += a[i-1] - a[i]\n i = i + 1\n\navg_delta = sumdeltas / (len(a) - 1)\n\nThis will indeed average your deltas together.\n", "Since you seem to be throwing out the 20 minute delta between times 1 and 3 in your example, I'd say you should just sort the list of datetimes, add up the deltas between adjacent times, then divide by n-1.\nDo you have any code you can share with us, so we can help you debug it?\n", "You can subtract each successive date from the one prior (resulting in a timedelta object which represents the difference in days, seconds). You can then average the timedelta objects to find your answer.\n", "small clarification\nfrom datetime import timedelta\n\ndef avg(a):\n numdeltas = len(a) - 1\n sumdeltas = timedelta(seconds=0)\n\n i = 1\n while i < len(a):\n delta = abs(a[i] - a[i-1])\n try:\n sumdeltas += delta\n except:\n raise\n i += 1\n avg = sumdeltas / numdeltas\n return avg\n\n" ]
[ 13, 3, 2, 0, 0 ]
[]
[]
[ "algorithm", "datetime", "python" ]
stackoverflow_0000179716_algorithm_datetime_python.txt
Q: Choose Python version for egg installation or install parallel versions of site-package Via fink install I put the following Python version on my Mac OS X computer: python2.3, python2.4, python2.5, python2.6. Further, python is alias for python2.6 on my system. I want to install an egg, e.g. easy_install networkx-0.36-py2.5.egg, where I have to use python 2.5 instead of version 2.6. Is this possible without changing the python alias? Can you tell me, whether and how I can install networkx-0.36-py2.5 and networkx-1.0rc1-py2.6 in parallel? How can I install a site-package in a way, that it is available for different Python versions? A: easy_install is part of the setuptools package. Fink has separate setuptools packages for python 2.5 and python 2.6: fink install setuptools-py25 setuptools-py26 You can then download and install networkx to both versions: /sw/bin/easy_install-2.5 networkx /sw/bin/easy_install-2.6 networkx If you need a particular version of the package: /sw/bin/easy_install-2.5 networkx==0.36 /sw/bin/easy_install-2.6 networkx==0.36 A: Edit: Read Ned Deily's answer before you read this one 1. On my system I have different easy_install script for each python version: /usr/bin/easy_install-2.5 /usr/bin/easy_install-2.6 The contents of the 2.6 version looks like this: #!/System/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python import sys sys.argv[0] = sys.argv[0].replace('-2.6', '') # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==0.6c9','console_scripts','easy_install' __requires__ = 'setuptools==0.6c9' import sys from pkg_resources import load_entry_point sys.exit( load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')() ) Now, if you not already have those scripts on you machine, you could create those by using the above as template. Just change the first line so it points to the right python interpreter. Probably something like: #!/sw/bin/python23 And change the third line to match the current script name; meaning, if the script is called easy_install-2.3, then it should look like this: sys.argv[0] = sys.argv[0].replace('-2.3', '') And of course if you are not using setuptools version 0.6c9 than you will have to change this, too. An alternative is to run the easy_install script as an argument of the right python version. Like this: $ python23 /some/path/easy_install networkx-0.36-py2.5.egg 2. Each python version has a different site-lib, so they are independent from each other. You can install different modules and versions for different python versions 3. You could make the env variable PYTHONPATH point to a common directory or add a common directory to sys.path in your scripts. But be aware that some modules work only with certain python versions and include C code that has to be compiled for each python version...
Choose Python version for egg installation or install parallel versions of site-package
Via fink install I put the following Python version on my Mac OS X computer: python2.3, python2.4, python2.5, python2.6. Further, python is alias for python2.6 on my system. I want to install an egg, e.g. easy_install networkx-0.36-py2.5.egg, where I have to use python 2.5 instead of version 2.6. Is this possible without changing the python alias? Can you tell me, whether and how I can install networkx-0.36-py2.5 and networkx-1.0rc1-py2.6 in parallel? How can I install a site-package in a way, that it is available for different Python versions?
[ "easy_install is part of the setuptools package. Fink has separate setuptools packages for python 2.5 and python 2.6:\nfink install setuptools-py25 setuptools-py26\n\nYou can then download and install networkx to both versions:\n/sw/bin/easy_install-2.5 networkx\n/sw/bin/easy_install-2.6 networkx\n\nIf you need a particular version of the package:\n/sw/bin/easy_install-2.5 networkx==0.36\n/sw/bin/easy_install-2.6 networkx==0.36\n\n", "Edit: Read Ned Deily's answer before you read this one\n\n1.\nOn my system I have different easy_install script for each python version:\n\n/usr/bin/easy_install-2.5\n/usr/bin/easy_install-2.6\n\nThe contents of the 2.6 version looks like this:\n#!/System/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python\nimport sys\nsys.argv[0] = sys.argv[0].replace('-2.6', '')\n# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==0.6c9','console_scripts','easy_install'\n__requires__ = 'setuptools==0.6c9'\nimport sys\nfrom pkg_resources import load_entry_point\n\nsys.exit(\n load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')()\n)\n\nNow, if you not already have those scripts on you machine, you could create those by using the above as template. Just change the first line so it points to the right python interpreter. Probably something like:\n#!/sw/bin/python23\n\nAnd change the third line to match the current script name; meaning, if the script is called easy_install-2.3, then it should look like this:\nsys.argv[0] = sys.argv[0].replace('-2.3', '')\n\nAnd of course if you are not using setuptools version 0.6c9 than you will have to change this, too.\n\nAn alternative is to run the easy_install script as an argument of the right python version. Like this:\n$ python23 /some/path/easy_install networkx-0.36-py2.5.egg\n\n2.\nEach python version has a different site-lib, so they are independent from each other. You can install different modules and versions for different python versions\n3.\nYou could make the env variable PYTHONPATH point to a common directory or add a common directory to sys.path in your scripts. But be aware that some modules work only with certain python versions and include C code that has to be compiled for each python version...\n" ]
[ 3, 2 ]
[]
[]
[ "easy_install", "egg", "python" ]
stackoverflow_0001571047_easy_install_egg_python.txt
Q: Iterating through a list in Python I am trying to iterate through a list and take each part of the list, encode it and join the result up when it is all done. As an example, I have a string which produces a list with each element being 16 characters in length. message = (u'sixteen-letters.sixteen-letters.sixteen-letters.sixteen-letters.') result = split16(message, 16) msg = ';'.join(encode(result.pop(0)) for i in result) The encode function takes a 16 byte string and returns the result. However with the way it is written, it only encodes half of the elements in the list. If I try comprehension: result = [encode(split16(message, 16) for message in list_of_messages)] result = ''.join(result) It results in the whole list being sent at once. What I need to do is send each element to the encode function separately, get the result then join them together. Is there an easy way of achieving this? A: Are you trying to do something like this? ';'.join(encode(i) for i in message.split('.')) of course it could be just ';'.join(encode(i) for i in result) if your split16 function complicated enough. A: I am a bit confused about what you are exactly trying to do, which is compounded by a missing paren in the code you posted: result = [encode(split16(message, 16) for message in list_of_messages] Should that be: result = [encode(split16(message, 16) for message in list_of_messages)] or: result = [encode(split16(message, 16)) for message in list_of_messages] I think the second will do what you want. This code: msg = ';'.join(encode(result.pop(0)) for i in result) is failing because at every step you are iterating through result, but shortening it at every step with pop. It should just be: msg = ';'.join(encode(i) for i in result) A: I'm not quite clear what you are after, but msg=";".join(map(encode,(message[i:i+16] for i in range(0,len(message),16))))
Iterating through a list in Python
I am trying to iterate through a list and take each part of the list, encode it and join the result up when it is all done. As an example, I have a string which produces a list with each element being 16 characters in length. message = (u'sixteen-letters.sixteen-letters.sixteen-letters.sixteen-letters.') result = split16(message, 16) msg = ';'.join(encode(result.pop(0)) for i in result) The encode function takes a 16 byte string and returns the result. However with the way it is written, it only encodes half of the elements in the list. If I try comprehension: result = [encode(split16(message, 16) for message in list_of_messages)] result = ''.join(result) It results in the whole list being sent at once. What I need to do is send each element to the encode function separately, get the result then join them together. Is there an easy way of achieving this?
[ "Are you trying to do something like this?\n';'.join(encode(i) for i in message.split('.'))\n\nof course it could be just \n';'.join(encode(i) for i in result)\n\nif your split16 function complicated enough.\n", "I am a bit confused about what you are exactly trying to do, which is compounded by a missing paren in the code you posted:\nresult = [encode(split16(message, 16) for message in list_of_messages]\n\nShould that be:\nresult = [encode(split16(message, 16) for message in list_of_messages)] \n\nor:\nresult = [encode(split16(message, 16)) for message in list_of_messages] \n\nI think the second will do what you want.\nThis code:\nmsg = ';'.join(encode(result.pop(0)) for i in result)\n\nis failing because at every step you are iterating through result, but shortening it at every step with pop. It should just be:\nmsg = ';'.join(encode(i) for i in result)\n\n", "I'm not quite clear what you are after, but\nmsg=\";\".join(map(encode,(message[i:i+16] for i in range(0,len(message),16))))\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0001571651_list_list_comprehension_python.txt
Q: Select specific child elements with BeautifulSoup I'm reading up on BeautifulSoup to screen-scrape some pretty heavy html pages. Going through the documentation of BeautifulSoup I can't seem to find a easy way to select child elements. Given the html: <div id="top"> <div>Content</div> <div> <div>Content I Want</div> </div> </div> I want a easy way to to get the "Content I Want" given I have the object top. Coming to BeautifulSoup I thought it would be easy, and something like topobj.nodes[1].nodes[0].string. Instead I only see variables and functions that also return the elements together with text nodes, comments and so on. Am I missing something? Or do I really need to resort to a long form using .find() or even worse using list comphrensions on the .contents variable. The reason is that I don't trust the whitespace of the webpage to be the same so I want to ignore it and only traverse on elements. A: You are more flexible with find, and to get what you want you just need to run: node = p.find('div', text="Content I Want") But since it might not be how you want to get there, following options might suit you better: xml = """<div id="top"><div>Content</div><div><div>Content I Want</div></div></div>""" from BeautifulSoup import BeautifulSoup p = BeautifulSoup(xml) # returns a list of texts print p.div.div.findNextSibling().div.contents # returns a list of texts print p.div.div.findNextSibling().div(text=True) # join (and strip) the values print ''.join(s.strip() for s in p.div.div.findNextSibling().div(text=True))
Select specific child elements with BeautifulSoup
I'm reading up on BeautifulSoup to screen-scrape some pretty heavy html pages. Going through the documentation of BeautifulSoup I can't seem to find a easy way to select child elements. Given the html: <div id="top"> <div>Content</div> <div> <div>Content I Want</div> </div> </div> I want a easy way to to get the "Content I Want" given I have the object top. Coming to BeautifulSoup I thought it would be easy, and something like topobj.nodes[1].nodes[0].string. Instead I only see variables and functions that also return the elements together with text nodes, comments and so on. Am I missing something? Or do I really need to resort to a long form using .find() or even worse using list comphrensions on the .contents variable. The reason is that I don't trust the whitespace of the webpage to be the same so I want to ignore it and only traverse on elements.
[ "You are more flexible with find, and to get what you want you just need to run:\nnode = p.find('div', text=\"Content I Want\")\n\nBut since it might not be how you want to get there, following options might suit you better:\nxml = \"\"\"<div id=\"top\"><div>Content</div><div><div>Content I Want</div></div></div>\"\"\"\nfrom BeautifulSoup import BeautifulSoup\np = BeautifulSoup(xml)\n\n# returns a list of texts\nprint p.div.div.findNextSibling().div.contents\n# returns a list of texts\nprint p.div.div.findNextSibling().div(text=True)\n# join (and strip) the values\nprint ''.join(s.strip() for s in p.div.div.findNextSibling().div(text=True))\n\n" ]
[ 2 ]
[]
[]
[ "beautifulsoup", "html_parsing", "python" ]
stackoverflow_0001571699_beautifulsoup_html_parsing_python.txt
Q: Clojure equivalent to Python's lxml library? I'm looking for the Clojure/Java equivalent to Python's lxml library. I've used it a ton in the past for parsing all sorts of html (as a replacement for BeautifulSoup) and it's great to be able to use the same elementtree api for xml as well -- really a trusted friend! Can anyone recommend a similar Java/Clojure library? About lxml lxml is an xml and html processing library based off of libxml2. It handles broken html pages very well so it is excellent for screen scraping tasks. It also implements the ElementTree api, so the xml/html structure is represented as a tree object with full support for xpath and css selectors among other things. It also has some really handy utility functions such as the "cleaner" module which will strip out unwanted tags from the "soup" (ie script tags, style tags, etc...). So it is simple to use, robust, and VERY fast...! A: Enlive: http://github.com/cgrand/enlive I've used it for screen-scraping and it works quite well for that. It uses a CSS selector like syntax for getting at elements in the document. A: For Java (and thus usable from Clojure) is the tagsoup-library, which, like lxml, is a tolerant parser for faulty SGML-variants. Clojure has a bundled namespace clojure.xml, but this will only work with valid XML.
Clojure equivalent to Python's lxml library?
I'm looking for the Clojure/Java equivalent to Python's lxml library. I've used it a ton in the past for parsing all sorts of html (as a replacement for BeautifulSoup) and it's great to be able to use the same elementtree api for xml as well -- really a trusted friend! Can anyone recommend a similar Java/Clojure library? About lxml lxml is an xml and html processing library based off of libxml2. It handles broken html pages very well so it is excellent for screen scraping tasks. It also implements the ElementTree api, so the xml/html structure is represented as a tree object with full support for xpath and css selectors among other things. It also has some really handy utility functions such as the "cleaner" module which will strip out unwanted tags from the "soup" (ie script tags, style tags, etc...). So it is simple to use, robust, and VERY fast...!
[ "Enlive: http://github.com/cgrand/enlive\nI've used it for screen-scraping and it works quite well for that. It uses a CSS selector like syntax for getting at elements in the document.\n", "For Java (and thus usable from Clojure) is the tagsoup-library, which, like lxml, is a tolerant parser for faulty SGML-variants.\nClojure has a bundled namespace clojure.xml, but this will only work with valid XML.\n" ]
[ 8, 5 ]
[]
[]
[ "clojure", "java", "lxml", "python" ]
stackoverflow_0001569223_clojure_java_lxml_python.txt
Q: How do I request data securely via Google OAuth? Until recently users of my site were able to import data from Google, via OAuth. However, recently they have received the warning below, in a yellow box, when authorising (although the import still works). I've also noticed this same warning on Facebook's GMail authenticator! What's changed / am I missing? This website is registered with Google to make authorization requests, but has not been configured to send requests securely. If you grant access but you did not initiate this request at www.foo.com, it may be possible for other users of www.foo.com to access your data. We recommend you deny access unless you are certain that you initiated this request directly with www.foo.com. (The site is written in Zope/Python, but the step/documentation I'm missing is more important) A: Did you try Googling the error message? Doing so took me to this page, which states: Registered with enhanced security: Registered applications with a security certificate on file can use secure tokens. The Access Request page removes cautions, displaying this message: " Google is not affiliated with , and we recommend that you grant access only if you trust the site." See their docs, step 4, "Upload a security certificate" for more details.
How do I request data securely via Google OAuth?
Until recently users of my site were able to import data from Google, via OAuth. However, recently they have received the warning below, in a yellow box, when authorising (although the import still works). I've also noticed this same warning on Facebook's GMail authenticator! What's changed / am I missing? This website is registered with Google to make authorization requests, but has not been configured to send requests securely. If you grant access but you did not initiate this request at www.foo.com, it may be possible for other users of www.foo.com to access your data. We recommend you deny access unless you are certain that you initiated this request directly with www.foo.com. (The site is written in Zope/Python, but the step/documentation I'm missing is more important)
[ "Did you try Googling the error message? Doing so took me to this page, which states:\n\nRegistered with enhanced security: Registered applications with a security certificate on file can use secure tokens. The Access Request page removes cautions, displaying this message: \" Google is not affiliated with , and we recommend that you grant access only if you trust the site.\"\n\nSee their docs, step 4, \"Upload a security certificate\" for more details.\n" ]
[ 1 ]
[]
[]
[ "oauth", "python" ]
stackoverflow_0001572450_oauth_python.txt
Q: Python Vs C - Handling environment variable in Windows I see a variation in output between C and python code in Windows trying to get the same functionality. The c code ( similar to unix shell scripts ) shows the TEST1 environment variable in 'test.bat.output' with its value as empty string whereas the python code removes this environment variable. Is there a way to ask Python not to remove the environment variable from environ table when it is empty? C #include <windows.h> main() { DWORD dwRet; char pszOldVal[1024] = "abc"; if(! SetEnvironmentVariable("TEST1", "")) puts("Error\n"); // _putenv("TEST1="); // GetEnvironmentVariable("TEST1", pszOldVal, dwRet); system("cmd /c test.bat >test.bat.output"); } Python import os os.environ['TEST1'] = "" os.environ['TEST2'] = "karthik" os.system("cmd /c test.bat > test.bat.output.python") -Karthik A: Cross-platform compatibility between Windows and "most everybody else" (operating systems derived or inspired from Unix) is often hard to get, especially in the innumerable corner cases that inevitably arise (e.g., as in this question, "does setting an environment variable to empty mean unsetting it"). Sometimes it's just easier to access Windows specific functionality directly rather than trying to stretch the "cross-platform" functionality. While the traditional way to access Windows-specific functionality from Python is the win32all extension package, in recent Python versions the ctypes standard library module offers an alternative with the advantage of requiring no installation of C coded extensions. An interesting project is jaraco.windows, a set of pure-Python code on top of ctypes to make Windows operations easier and smoother. For example, if you work with the environment and/or the registry, the environ.py module offers a nice set of functions and classes with a more Pythonic feel to them than the bare win32 API as accessed by the underlying ctypes (e.g., get an exception with a readable error message in it in case of errors, rather than having to check return codes &c). A: Yes empty values are not being put into environ, but interesting thing is calling SetEnvironmentVariable from win32api or ctypes module has same affect as os.environ though win32api.SetEnvironmentVariable would be calling the same function as in C . So are you sure you get different result in C code? import win32api import os win32api.SetEnvironmentVariable("TEST1", "") # or # import ctypes # ctypes.windll.kernel32.SetEnvironmentVariable("TEST1", "") os.system("echo %TEST1%") A: This is a possible answer. I don't have a Windows system handy to test with, so I don't really know what this code will do, but what happens if you do this: import os, subprocess myenv = {} myenv.update(os.environ) myenv['TEST1'] = "" myenv['TEST2'] = "karthik" subprocess.Popen(('cmd', '/c', 'test.bat'), stdout=file("test.bat.output.python", 'w'), env=myenv).wait() In my opinion, you might be encountering a Python bug of some kind. Especially if the code I just gave works. Also, testing your code under Unix does work. The environment ends up with an empty environment variable in it.
Python Vs C - Handling environment variable in Windows
I see a variation in output between C and python code in Windows trying to get the same functionality. The c code ( similar to unix shell scripts ) shows the TEST1 environment variable in 'test.bat.output' with its value as empty string whereas the python code removes this environment variable. Is there a way to ask Python not to remove the environment variable from environ table when it is empty? C #include <windows.h> main() { DWORD dwRet; char pszOldVal[1024] = "abc"; if(! SetEnvironmentVariable("TEST1", "")) puts("Error\n"); // _putenv("TEST1="); // GetEnvironmentVariable("TEST1", pszOldVal, dwRet); system("cmd /c test.bat >test.bat.output"); } Python import os os.environ['TEST1'] = "" os.environ['TEST2'] = "karthik" os.system("cmd /c test.bat > test.bat.output.python") -Karthik
[ "Cross-platform compatibility between Windows and \"most everybody else\" (operating systems derived or inspired from Unix) is often hard to get, especially in the innumerable corner cases that inevitably arise (e.g., as in this question, \"does setting an environment variable to empty mean unsetting it\"). Sometimes it's just easier to access Windows specific functionality directly rather than trying to stretch the \"cross-platform\" functionality.\nWhile the traditional way to access Windows-specific functionality from Python is the win32all extension package, in recent Python versions the ctypes standard library module offers an alternative with the advantage of requiring no installation of C coded extensions. An interesting project is jaraco.windows, a set of pure-Python code on top of ctypes to make Windows operations easier and smoother. For example, if you work with the environment and/or the registry, the environ.py module offers a nice set of functions and classes with a more Pythonic feel to them than the bare win32 API as accessed by the underlying ctypes (e.g., get an exception with a readable error message in it in case of errors, rather than having to check return codes &c).\n", "Yes empty values are not being put into environ, but interesting thing is calling SetEnvironmentVariable from win32api or ctypes module has same affect as os.environ though win32api.SetEnvironmentVariable would be calling the same function as in C .\nSo are you sure you get different result in C code?\nimport win32api\nimport os\nwin32api.SetEnvironmentVariable(\"TEST1\", \"\")\n# or \n# import ctypes\n# ctypes.windll.kernel32.SetEnvironmentVariable(\"TEST1\", \"\")\nos.system(\"echo %TEST1%\")\n\n", "This is a possible answer. I don't have a Windows system handy to test with, so I don't really know what this code will do, but what happens if you do this:\nimport os, subprocess\nmyenv = {}\nmyenv.update(os.environ)\nmyenv['TEST1'] = \"\"\nmyenv['TEST2'] = \"karthik\"\nsubprocess.Popen(('cmd', '/c', 'test.bat'), stdout=file(\"test.bat.output.python\", 'w'),\n env=myenv).wait()\n\nIn my opinion, you might be encountering a Python bug of some kind. Especially if the code I just gave works.\nAlso, testing your code under Unix does work. The environment ends up with an empty environment variable in it.\n" ]
[ 2, 0, 0 ]
[]
[]
[ "c", "environment_variables", "python" ]
stackoverflow_0001572153_c_environment_variables_python.txt
Q: Unexpected result in a simple example def solve(numLegs, numHeads): for numSpiders in range(0, numHeads + 1): for numChicks in range(0, numHeads - numSpiders + 1): numPigs = numHeads - numChicks - numSpiders totLegs = 4*numPigs + 2*numChicks + 6*numSpiders if totLegs == numLegs: return [numPigs, numChicks, numSpiders] return [None, None, None] def barnYard(heads, legs): pigs, chickens, spiders = solve(legs, heads) if pigs == None: print "There is no solution." else: print 'Number of pigs: ', pigs print 'Number of Chickens: ', chickens print 'Number of Spider: ', spiders barnYard(20,56) # 8 pigs - 12 chickens barnYard(21,62) # 10 pig - 11 chickens 20 heads and 56 legs returns 8 pigs and 12 chickens, so I made it 21 and 62 to add a spider, but it still returns pigs and chickens, whats wrong in the code? Thanks! A: Your code is correct - in the first iteration of the outermost for loop, numChicks is 0. Since solve returns as soon as it finds a valid match, another possible valid match won't be attempted. You could change the return statement into a yield statement and iterate over solve's results to get all possible combinations. For instance: def solve(numLegs, numHeads): for numBees in range(0, numHeads + 1): for numChicks in range(0, numHeads - numBees + 1): numPigs = numHeads - numChicks - numBees totLegs = 4*numPigs + 2*numChicks + 6*numBees if totLegs == numLegs: yield [numPigs, numChicks, numBees] def barnYard(heads, legs): for pigs, chickens, bees in solve(legs, heads): print 'Number of pigs: ', pigs print 'Number of chickens: ', chickens print 'Number of bees: ', bees barnYard(20,56) will output: Number of pigs: 8 Number of chickens: 12 Number of bees: 0 Number of pigs: 6 Number of chickens: 13 Number of bees: 1 Number of pigs: 4 Number of chickens: 14 Number of bees: 2 Number of pigs: 2 Number of chickens: 15 Number of bees: 3 Number of pigs: 0 Number of chickens: 16 Number of bees: 4 A: There is absolutely nothing wrong with your code. That's a completely valid result. With 10 pigs and 11 chickens, you get 10+11=21 heads, and 10*4 + 11*2 = 62 legs. So it returns a correct result. Now if you change that to 10 heads and 62 legs, and also change the code to have 8 legs for a spider as they tend to do, then you get the result 3 pigs, 1 chicken and 6 spiders. Your code simply tries spiders last, so you wont get any spiders unless it has to be spiders. A: A linear system with 2 equations and 3 variables is under-determined -- there may be multiple solutions for any given set of parameters; and this is indeed the case for the code you're showing. Nothing wrong with the code, if what you want is to get the solution (if any) with as few spiders as possible. If you want to get the solution (if any) with as many spiders as possible, try "many spiders" first, for example change the outer loop, which is now for numSpiders in range(0, numHeads + 1): i.e., first tries to get a solution with no spiders at all, then if that fails tries with one, and so forth, to be instead: for numSpiders in reversed(range(0, numHeads + 1)): which goes the other way round (that's what the reversed is for) and will try numHeads spiders first, then numHeads-1, and so forth. (Your equations are actually Diophantine ones, i.e., strictly integer-based, which has important implications when compared to ordinary linear equations which admit fractional solutions, but your issue here is not tied to Diophantine-equation problems, just to the bit about underdetermined linear systems).
Unexpected result in a simple example
def solve(numLegs, numHeads): for numSpiders in range(0, numHeads + 1): for numChicks in range(0, numHeads - numSpiders + 1): numPigs = numHeads - numChicks - numSpiders totLegs = 4*numPigs + 2*numChicks + 6*numSpiders if totLegs == numLegs: return [numPigs, numChicks, numSpiders] return [None, None, None] def barnYard(heads, legs): pigs, chickens, spiders = solve(legs, heads) if pigs == None: print "There is no solution." else: print 'Number of pigs: ', pigs print 'Number of Chickens: ', chickens print 'Number of Spider: ', spiders barnYard(20,56) # 8 pigs - 12 chickens barnYard(21,62) # 10 pig - 11 chickens 20 heads and 56 legs returns 8 pigs and 12 chickens, so I made it 21 and 62 to add a spider, but it still returns pigs and chickens, whats wrong in the code? Thanks!
[ "Your code is correct - in the first iteration of the outermost for loop, numChicks is 0. Since solve returns as soon as it finds a valid match, another possible valid match won't be attempted.\nYou could change the return statement into a yield statement and iterate over solve's results to get all possible combinations.\nFor instance:\ndef solve(numLegs, numHeads):\n for numBees in range(0, numHeads + 1):\n for numChicks in range(0, numHeads - numBees + 1):\n numPigs = numHeads - numChicks - numBees\n totLegs = 4*numPigs + 2*numChicks + 6*numBees \n if totLegs == numLegs:\n yield [numPigs, numChicks, numBees]\n\ndef barnYard(heads, legs):\n for pigs, chickens, bees in solve(legs, heads):\n print 'Number of pigs: ', pigs\n print 'Number of chickens: ', chickens\n print 'Number of bees: ', bees\n\nbarnYard(20,56)\n\nwill output:\nNumber of pigs: 8\nNumber of chickens: 12\nNumber of bees: 0\n\nNumber of pigs: 6\nNumber of chickens: 13\nNumber of bees: 1\n\nNumber of pigs: 4\nNumber of chickens: 14\nNumber of bees: 2\n\nNumber of pigs: 2\nNumber of chickens: 15\nNumber of bees: 3\n\nNumber of pigs: 0\nNumber of chickens: 16\nNumber of bees: 4\n\n", "There is absolutely nothing wrong with your code. That's a completely valid result. With 10 pigs and 11 chickens, you get 10+11=21 heads, and 10*4 + 11*2 = 62 legs.\nSo it returns a correct result.\nNow if you change that to 10 heads and 62 legs, and also change the code to have 8 legs for a spider as they tend to do, then you get the result 3 pigs, 1 chicken and 6 spiders.\nYour code simply tries spiders last, so you wont get any spiders unless it has to be spiders.\n", "A linear system with 2 equations and 3 variables is under-determined -- there may be multiple solutions for any given set of parameters; and this is indeed the case for the code you're showing. Nothing wrong with the code, if what you want is to get the solution (if any) with as few spiders as possible.\nIf you want to get the solution (if any) with as many spiders as possible, try \"many spiders\" first, for example change the outer loop, which is now\n for numSpiders in range(0, numHeads + 1):\n\ni.e., first tries to get a solution with no spiders at all, then if that fails tries with one, and so forth, to be instead:\n for numSpiders in reversed(range(0, numHeads + 1)):\n\nwhich goes the other way round (that's what the reversed is for) and will try numHeads spiders first, then numHeads-1, and so forth.\n(Your equations are actually Diophantine ones, i.e., strictly integer-based, which has important implications when compared to ordinary linear equations which admit fractional solutions, but your issue here is not tied to Diophantine-equation problems, just to the bit about underdetermined linear systems).\n" ]
[ 5, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001572676_python.txt
Q: converting strptime into 'X hours ago' I have a a date in strptime that I want to show as 'X hours ago'. I can happily convert hours into days and weeks etc. but I don't know how to do the initial sum. Here is how I'm converting the string into strptime: time.strptime(obj.created_at, '%a %b %d %H:%M:%S +0000 %Y') p.s. bonus points for figuring out why it won't take %z for '+0000' - am I completely wrong about what this is? A: It seems the timesince in Django could help you out without you having to convert. The source for timesince is available here. A: The datetime module is definitely easier to use, but, if you insist, you can do it with the time module instead. I.e.: >>> import time >>> fmt = '%a %b %d %H:%M:%S +0000 %Y' >>> time.strftime(fmt) 'Thu Oct 15 07:54:07 +0000 2009' >>> createdat = 'Thu Oct 15 02:30:30 +0000 2009' >>> createdtim = time.strptime(createdat, fmt) >>> hoursago = (time.time() - time.mktime(createdtim)) / 3600 >>> print hoursago 5.42057559947 One reason the time module is so pesky to use is that it uses two different ways to represent time -- one is a 9-tuple (and that's what you get from strptime), and one is a float "seconds since the epoch" (and that's what you need to do differences); the mktime function translates the former to the latter. Difference in hours is clearly 1/3600 of the difference in seconds -- you'll have to decide how to display a typically-fractionary "number of hours ago", of course (hour and fraction with some digits, or, round to closest integer number of hours, or what else). The literal '+0000' in your format, for strptime, means you expect and ignore those literal characters at that spot in your "createdat" string (normally you'd have a timezone offset specifier there). If that's indeed what you want, then you have the right format string! A: Can you use datetime instead? (Or convert whatever you have into datetime?) >>> import datetime >>> created_at = datetime.datetime(2009,10,15, 13) >>> now = datetime.datetime.now() >>> delta = now - created_at >>> hours_ago = '%d Hours Ago' % (delta.seconds/60/60) >>> hours_ago '5 Hours Ago'
converting strptime into 'X hours ago'
I have a a date in strptime that I want to show as 'X hours ago'. I can happily convert hours into days and weeks etc. but I don't know how to do the initial sum. Here is how I'm converting the string into strptime: time.strptime(obj.created_at, '%a %b %d %H:%M:%S +0000 %Y') p.s. bonus points for figuring out why it won't take %z for '+0000' - am I completely wrong about what this is?
[ "It seems the timesince in Django could help you out without you having to convert. The source for timesince is available here.\n", "The datetime module is definitely easier to use, but, if you insist, you can do it with the time module instead. I.e.:\n>>> import time\n>>> fmt = '%a %b %d %H:%M:%S +0000 %Y'\n>>> time.strftime(fmt)\n'Thu Oct 15 07:54:07 +0000 2009'\n>>> createdat = 'Thu Oct 15 02:30:30 +0000 2009'\n>>> createdtim = time.strptime(createdat, fmt)\n>>> hoursago = (time.time() - time.mktime(createdtim)) / 3600\n>>> print hoursago\n5.42057559947\n\nOne reason the time module is so pesky to use is that it uses two different ways to represent time -- one is a 9-tuple (and that's what you get from strptime), and one is a float \"seconds since the epoch\" (and that's what you need to do differences); the mktime function translates the former to the latter. Difference in hours is clearly 1/3600 of the difference in seconds -- you'll have to decide how to display a typically-fractionary \"number of hours ago\", of course (hour and fraction with some digits, or, round to closest integer number of hours, or what else).\nThe literal '+0000' in your format, for strptime, means you expect and ignore those literal characters at that spot in your \"createdat\" string (normally you'd have a timezone offset specifier there). If that's indeed what you want, then you have the right format string!\n", "Can you use datetime instead? (Or convert whatever you have into datetime?)\n>>> import datetime\n>>> created_at = datetime.datetime(2009,10,15, 13)\n>>> now = datetime.datetime.now()\n>>> delta = now - created_at\n>>> hours_ago = '%d Hours Ago' % (delta.seconds/60/60)\n>>> hours_ago\n'5 Hours Ago'\n\n" ]
[ 4, 2, 0 ]
[]
[]
[ "python", "strptime", "timestamp" ]
stackoverflow_0001571272_python_strptime_timestamp.txt
Q: Importing Python modules from a distant directory What's the shortest way to import a module from a distant, relative directory? We've been using this code which isn't too bad except your current working directory has to be the same as the directory as this code's or the relative path breaks, which can be error prone and confusing to users. import sys sys.path.append('../../../Path/To/Shared/Code') This code (I think) fixes that problem but is a lot more to type. import os,sys sys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), '../../../Path/To/Shared/Code'))) Is there a shorter way to append the absolute path? The brevity matters because this is going to have to be typed/appear in a lot of our files. (We can't factor it out because then it would be in the shared code and we couldn't get to it. Chicken & egg, bootstrapping, etc.) Plus it bothers me that we keep blindly appending to sys.path but that would be even more code. I sure wish something in the standard library could help with this. This will typically appear in script files which are run from the command line. We're running Python 2.6.2. Edit: The reason we're using relative paths is that we typically have multiple, independent copies of the codebase on our computers. It's important that each copy of the codebase use its own copy of the shared code. So any solution which supports only a single code base (e.g., 'Put it in site-packages.') won't work for us. Any suggestions? Thank you! A: Since you don't want to install it in site-packages, you should use buildout or virtualenv to create isolated development environments. That solves the problem, and means you don't have to fiddle with sys.path anymore (in fact, because Buildout does exactly that for you). A: You've explained in a comment why you don't want to install "a single site-packages directory", but what about putting in site-packages a single, tiny module, say jebootstrap.py: import os, sys def relative_dir(apath): return os.path.realpath( os.path.join(os.path.dirname(apath), '../../../Path/To/Shared/Code')) def addpack(apath): relative = relative_dir(apath) if relative not in sys.path: sys.path.append(relative) Now everywhere in your code you can just have import jebootstrap jebootsrap.addpack(__file__) and all the rest of your shared codebase can remain independent per-installation. A: Any reason you wouldn't want to make your own shared-code dir under site-packages? Then you could just import import shared.code.module...
Importing Python modules from a distant directory
What's the shortest way to import a module from a distant, relative directory? We've been using this code which isn't too bad except your current working directory has to be the same as the directory as this code's or the relative path breaks, which can be error prone and confusing to users. import sys sys.path.append('../../../Path/To/Shared/Code') This code (I think) fixes that problem but is a lot more to type. import os,sys sys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), '../../../Path/To/Shared/Code'))) Is there a shorter way to append the absolute path? The brevity matters because this is going to have to be typed/appear in a lot of our files. (We can't factor it out because then it would be in the shared code and we couldn't get to it. Chicken & egg, bootstrapping, etc.) Plus it bothers me that we keep blindly appending to sys.path but that would be even more code. I sure wish something in the standard library could help with this. This will typically appear in script files which are run from the command line. We're running Python 2.6.2. Edit: The reason we're using relative paths is that we typically have multiple, independent copies of the codebase on our computers. It's important that each copy of the codebase use its own copy of the shared code. So any solution which supports only a single code base (e.g., 'Put it in site-packages.') won't work for us. Any suggestions? Thank you!
[ "Since you don't want to install it in site-packages, you should use buildout or virtualenv to create isolated development environments. That solves the problem, and means you don't have to fiddle with sys.path anymore (in fact, because Buildout does exactly that for you).\n", "You've explained in a comment why you don't want to install \"a single site-packages directory\", but what about putting in site-packages a single, tiny module, say jebootstrap.py:\nimport os, sys\n\ndef relative_dir(apath):\n return os.path.realpath(\n os.path.join(os.path.dirname(apath),\n '../../../Path/To/Shared/Code'))\n\ndef addpack(apath):\n relative = relative_dir(apath)\n if relative not in sys.path:\n sys.path.append(relative)\n\nNow everywhere in your code you can just have\nimport jebootstrap\njebootsrap.addpack(__file__)\n\nand all the rest of your shared codebase can remain independent per-installation.\n", "Any reason you wouldn't want to make your own shared-code dir under site-packages? Then you could just import import shared.code.module...\n" ]
[ 4, 2, 1 ]
[ "You have several ways to handle imports, all documented in the Python language manual.\nSee http://docs.python.org/library/site.html and http://docs.python.org/reference/simple_stmts.html#the-import-statement\n\nPut it in site-packages and have multiple Python installations. You select the installation using the ordinary PATH environment variable.\nPut the directory in your PYTHONPATH environment variable. This is a per-individual-person setting, so you can manage to have multiple versions of the codebase this way.\nPut the directory in .pth files in your site-packages. You select the installation using the ordinary PATH environment variable.\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0001572967_python.txt
Q: Modifying state of other objects in a constructor: design no-no? I'm refactoring some code and found this (simplified of course, but general idea): class Variable: def __init__(self): self.__constraints = [] def addConstraint(self, c): self.__constraints.append(c) class Constraint: def __init__(self, variables): for v in variables: v.addConstraint(self) The fact that the constructor of Constraint modifies other object's states instead of its own smells a little funky to me. What do other people think - is this OK, or is it a prime candidate for refactoring? Edit: My concern is not the parent/child relationship, but that it is linked up inside the constructor rather than in a separate method. A: I see it as a self registration pattern. "Hello I'm new here, please allow me to join." I might prefer to have a differently named method so that the purpose is more clear, but I do actually quite like the approach. A: I entirely concur with @djna's answer that the specific use case is perfectly legit -- here, it's an example of an object needing to en-register itself with a specified set of registries "at birth". A very sharp and extremely common subcase of that would be an observer object that exists strictly for the purpose of observing a given observable -- perfectly fine to pass the observable to the observer's initializer, and exactly the right way to ensure the class invariant "instances of this observer class are at all times connected to exactly one observable", which would be not established "at birth" if the registration was carried out only after the completion of initialization. Other similar cases include for example a widget object that must at all time exist within a container window: it would somewhat weird to implement it otherwise than having the widget take the parent as an initializer argument and tell the parent "hi, I'm your new child!". At least in those 1-many cases you could imagine forcing the parent or observable to have a method that both creates and enregisters the new object. In a many-many case like this one, the somewhat inside-out nature of that approach gets revealed -- since the constraint must be registered with multiple variables, it would be "against the grain" to ask any specific one of them to create the constraint. The code you supply on the other hand is perfectly natural. Only for cases that cannot reasonably be framed as the new object "enregistering itself" would I feel some doubt (there are a few other legit ones, such as objects creating and enregistering other auxiliary ones at birth, but they're nowhere near as common). A: I agree with you. That's backwards. There may be some good reason for why, but it's unclear programming and it likely to bite someone if the foot sooner or later. A: This is common usage when you have two objects that are closely related (i.e. where only one of them alone doesn't make sense). Most common case: Parent child relations. When you add a child to a parent (i.e. parent.children.append(child)), you often also update the child.parent pointer. A: I personally am not necessarily opposed to this, but... I would choose one usage pattern, and stick with it. In your case, since Variable already has a clean addConstraint method, my preference would be to use it. Otherwise, you'll need to add good checking to prevent the user from constructing a Constraint, and then adding it to the Variable class (thereby adding it twice). That being said, with something like a Constraint, though, I would probably not do this. A Constraint seems like a conceptually independent entity from a Variable. I see no logical reason the same constraint couldn't be added to two separate variables. I would just make it so you construct your constraint, then add them manually, specifically for this reason.
Modifying state of other objects in a constructor: design no-no?
I'm refactoring some code and found this (simplified of course, but general idea): class Variable: def __init__(self): self.__constraints = [] def addConstraint(self, c): self.__constraints.append(c) class Constraint: def __init__(self, variables): for v in variables: v.addConstraint(self) The fact that the constructor of Constraint modifies other object's states instead of its own smells a little funky to me. What do other people think - is this OK, or is it a prime candidate for refactoring? Edit: My concern is not the parent/child relationship, but that it is linked up inside the constructor rather than in a separate method.
[ "I see it as a self registration pattern. \"Hello I'm new here, please allow me to join.\" \nI might prefer to have a differently named method so that the purpose is more clear, but I do actually quite like the approach.\n", "I entirely concur with @djna's answer that the specific use case is perfectly legit -- here, it's an example of an object needing to en-register itself with a specified set of registries \"at birth\".\nA very sharp and extremely common subcase of that would be an observer object that exists strictly for the purpose of observing a given observable -- perfectly fine to pass the observable to the observer's initializer, and exactly the right way to ensure the class invariant \"instances of this observer class are at all times connected to exactly one observable\", which would be not established \"at birth\" if the registration was carried out only after the completion of initialization.\nOther similar cases include for example a widget object that must at all time exist within a container window: it would somewhat weird to implement it otherwise than having the widget take the parent as an initializer argument and tell the parent \"hi, I'm your new child!\".\nAt least in those 1-many cases you could imagine forcing the parent or observable to have a method that both creates and enregisters the new object. In a many-many case like this one, the somewhat inside-out nature of that approach gets revealed -- since the constraint must be registered with multiple variables, it would be \"against the grain\" to ask any specific one of them to create the constraint. The code you supply on the other hand is perfectly natural.\nOnly for cases that cannot reasonably be framed as the new object \"enregistering itself\" would I feel some doubt (there are a few other legit ones, such as objects creating and enregistering other auxiliary ones at birth, but they're nowhere near as common).\n", "I agree with you. That's backwards. There may be some good reason for why, but it's unclear programming and it likely to bite someone if the foot sooner or later.\n", "This is common usage when you have two objects that are closely related (i.e. where only one of them alone doesn't make sense). Most common case: Parent child relations. When you add a child to a parent (i.e. parent.children.append(child)), you often also update the child.parent pointer.\n", "I personally am not necessarily opposed to this, but...\nI would choose one usage pattern, and stick with it. In your case, since Variable already has a clean addConstraint method, my preference would be to use it.\nOtherwise, you'll need to add good checking to prevent the user from constructing a Constraint, and then adding it to the Variable class (thereby adding it twice).\nThat being said, with something like a Constraint, though, I would probably not do this. A Constraint seems like a conceptually independent entity from a Variable. I see no logical reason the same constraint couldn't be added to two separate variables. I would just make it so you construct your constraint, then add them manually, specifically for this reason.\n" ]
[ 4, 2, 0, 0, 0 ]
[]
[]
[ "constructor", "oop", "python", "refactoring" ]
stackoverflow_0001573054_constructor_oop_python_refactoring.txt
Q: How do you implement a web-based direct deposit/eCheck payment system? I'm trying to develop a site that will allow users to pay for services with eChecks that other users are offering. The purchaser would pay money that would go into my account via direct deposit. The service provider could later withdraw money up to the amount they accumulated to their bank account. Every time I ask payment gateway providers about this, they act like I'm speaking in a foreign language. Paypal told me that their API doesn't allow direct deposits or eChecks. What sort of merchant account / gateway combination do I need to do this? Can you direct me to any specific companies? I use Python/Django to develop applications, do you know of any libraries that might assist me with this endeavor? A: I'm certain that you would not be able to do facilitated ACH/EFT transfers directly from one user's account to another user's account. However, as long as there's a third party in between the two users, this should be possible. But I'm assuming you'd want to do that anyways, so that you can get paid. The trick is finding a provider that will do both withdrawals and deposits, since most providers only give you withdrawals. I'd recommend at least talking to BrainTree; they're by far my favorite payment provider. If they don't work out though, you might try Alliance, however, I've never used them, so take that recommendation with a grain of salt.
How do you implement a web-based direct deposit/eCheck payment system?
I'm trying to develop a site that will allow users to pay for services with eChecks that other users are offering. The purchaser would pay money that would go into my account via direct deposit. The service provider could later withdraw money up to the amount they accumulated to their bank account. Every time I ask payment gateway providers about this, they act like I'm speaking in a foreign language. Paypal told me that their API doesn't allow direct deposits or eChecks. What sort of merchant account / gateway combination do I need to do this? Can you direct me to any specific companies? I use Python/Django to develop applications, do you know of any libraries that might assist me with this endeavor?
[ "I'm certain that you would not be able to do facilitated ACH/EFT transfers directly from one user's account to another user's account. However, as long as there's a third party in between the two users, this should be possible. But I'm assuming you'd want to do that anyways, so that you can get paid. The trick is finding a provider that will do both withdrawals and deposits, since most providers only give you withdrawals. I'd recommend at least talking to BrainTree; they're by far my favorite payment provider. If they don't work out though, you might try Alliance, however, I've never used them, so take that recommendation with a grain of salt.\n" ]
[ 4 ]
[]
[]
[ "django", "payment", "payment_gateway", "python" ]
stackoverflow_0001573383_django_payment_payment_gateway_python.txt
Q: convert exponential to decimal in python I have an array in python that contains a set of values, some of them are 2.32313e+07 2.1155e+07 1.923e+07 11856 112.32 How do I convert the exponential formats to the decimal format Additional: Is there a way I can convert the exponent directly to decimal when printing out in UNIX with awk? A: I imagine you have a list rather than an array, but here it doesn't make much of a difference; in 2.6 and earlier versions of Python, something like: >>> L = [2.32313e+07, 2.1155e+07, 1.923e+07, 11856, 112.32] >>> for x in L: print '%f' % x ... 23231300.000000 21155000.000000 19230000.000000 11856.000000 112.320000 and in 2.6 or later, the .format method. I imagine you are aware that the numbers per se, as numbers, aren't in any "format" -- it's the strings you obtain by formatting the numbers, e.g. for output, that are in some format. BTW, variants on that %f can let you control number of decimals, width, alignment, etc -- hard to suggest exactly what you may want without further specs from you. In awk, you can use printf. A: You can use locale.format() to format your numbers for output. This has the additional benefit of being consistent with any locale-specific conventions that might be expected in the presentation of the numbers. If you want complete control at the specific place where you do the output, you'd be better of with the print "format" % vars... variant. Example: >>> import locale >>> locale.setlocale(locale.LC_ALL, "") 'C/UTF-8/C/C/C/C' >>> locale.format("%f", 2.32313e+07, 1) '23231300.000000' A: In answer to the last part of your question, awk can use the same printf format: awk '{printf "%f\n",$1}' exponential_file Where exponential_file contains: 2.32313e+07 2.1155e+07 1.923e+07 11856 112.32 You can do the conversion into a variable for use later. Here is a simplistic example: awk '{n = sprintf("%f\n",$1); print n * 2}' exponential_file
convert exponential to decimal in python
I have an array in python that contains a set of values, some of them are 2.32313e+07 2.1155e+07 1.923e+07 11856 112.32 How do I convert the exponential formats to the decimal format Additional: Is there a way I can convert the exponent directly to decimal when printing out in UNIX with awk?
[ "I imagine you have a list rather than an array, but here it doesn't make much of a difference; in 2.6 and earlier versions of Python, something like:\n>>> L = [2.32313e+07, 2.1155e+07, 1.923e+07, 11856, 112.32]\n>>> for x in L: print '%f' % x\n... \n23231300.000000\n21155000.000000\n19230000.000000\n11856.000000\n112.320000\n\nand in 2.6 or later, the .format method. I imagine you are aware that the numbers per se, as numbers, aren't in any \"format\" -- it's the strings you obtain by formatting the numbers, e.g. for output, that are in some format. BTW, variants on that %f can let you control number of decimals, width, alignment, etc -- hard to suggest exactly what you may want without further specs from you.\nIn awk, you can use printf.\n", "You can use locale.format() to format your numbers for output. This has the additional benefit of being consistent with any locale-specific conventions that might be expected in the presentation of the numbers. If you want complete control at the specific place where you do the output, you'd be better of with the print \"format\" % vars... variant.\nExample:\n>>> import locale \n>>> locale.setlocale(locale.LC_ALL, \"\")\n'C/UTF-8/C/C/C/C'\n>>> locale.format(\"%f\", 2.32313e+07, 1)\n'23231300.000000'\n\n", "In answer to the last part of your question, awk can use the same printf format:\nawk '{printf \"%f\\n\",$1}' exponential_file\n\nWhere exponential_file contains:\n2.32313e+07\n2.1155e+07\n1.923e+07\n11856\n112.32\n\nYou can do the conversion into a variable for use later. Here is a simplistic example:\nawk '{n = sprintf(\"%f\\n\",$1); print n * 2}' exponential_file\n\n" ]
[ 5, 1, 0 ]
[]
[]
[ "awk", "exponent", "python", "unix" ]
stackoverflow_0001573080_awk_exponent_python_unix.txt
Q: Given a Python class, how can I inspect and find the place in my code where it is defined? I'm building a debugging tool. IPython lets me do stuff like MyCls?? And it will show me the source. A: sys.modules[MyCls.__module__].__file__ or inspect.getsourcefile(MyCls) There are more __xxx__ attributes on various objects you might find useful. A: Here's a pretty good overview of many of Python's meta-info capabilities: http://www.ibm.com/developerworks/library/l-pyint.html A: The inspect module has everything you need. A: If you just want to see the source, inspect.getsource is a very direct way to do that; for more advanced uses (getting the source file, line numbers, etc), see other functions in inspect documented at the same URL just before getsource. Note that each such function will raise an exception if source is not available, so make sure to be within a try/except block when you call it, and handle the exception as appropriate for your case. (Also, as I might hope goes without saying, you do need to import inspect in your modules in which you want to call inspect functionality).
Given a Python class, how can I inspect and find the place in my code where it is defined?
I'm building a debugging tool. IPython lets me do stuff like MyCls?? And it will show me the source.
[ "sys.modules[MyCls.__module__].__file__\n\nor\ninspect.getsourcefile(MyCls)\n\nThere are more __xxx__ attributes on various objects you might find useful.\n", "Here's a pretty good overview of many of Python's meta-info capabilities:\nhttp://www.ibm.com/developerworks/library/l-pyint.html\n", "The inspect module has everything you need.\n", "If you just want to see the source, inspect.getsource is a very direct way to do that; for more advanced uses (getting the source file, line numbers, etc), see other functions in inspect documented at the same URL just before getsource. Note that each such function will raise an exception if source is not available, so make sure to be within a try/except block when you call it, and handle the exception as appropriate for your case. (Also, as I might hope goes without saying, you do need to import inspect in your modules in which you want to call inspect functionality).\n" ]
[ 8, 4, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001568544_python.txt
Q: How to find duplicates in MySQL Suppose I have many columns. If 2 columns match and are exactly the same, then they are duplicates. ID | title | link | size | author Suppose if link and size are similar for 2 rows or more, then those rows are duplicates. How do I get those duplicates into a list and process them? A: Will return all records that have dups: SELECT theTable.* FROM theTable INNER JOIN ( SELECT link, size FROM theTable GROUP BY link, size HAVING count(ID) > 1 ) dups ON theTable.link = dups.link AND theTable.size = dups.size I like the subquery b/c I can do things like select all but the first or last. (very easy to turn into a delete query then). Example: select all duplicate records EXCEPT the one with the max ID: SELECT theTable.* FROM theTable INNER JOIN ( SELECT link, size, max(ID) as maxID FROM theTable GROUP BY link, size HAVING count(ID) > 1 ) dups ON theTable.link = dups.link AND theTable.size = dups.size AND theTable.ID <> dups.maxID A: Assuming that none of id, link or size can be NULL, and id field is the primary key. This gives you the id's of duplicate rows. Beware that same id can be in the results several times, if there are three or more rows with identical link and size values. select a.id, b.id from tbl a, tbl b where a.id < b.id and a.link = b.link and a.size = b.size A: After you remove the duplicates from the MySQL table, you can add a unique index to the table so no more duplicates can be inserted: create unique index theTable_index on theTable (link,size); A: If you want to do it exclusively in SQL, some kind of self-join of the table (on equality of link and size) is required, and can be accompanied by different kinds of elaboration. Since you mention Python as well, I assume you want to do the processing in Python; in that case, simplest is to build an iterator on a 'SELECT * FROM thetable ORDER BY link, size, and process withitertools.groupbyusing, as key, theoperator.itemgetter` for those two fields; this will present natural groupings of each bunch of 1+ rows with identical values for the fields in question. I can elaborate on either option if you clarify where you want to do your processing and ideally provide an example of the kind of processing you DO want to perform!
How to find duplicates in MySQL
Suppose I have many columns. If 2 columns match and are exactly the same, then they are duplicates. ID | title | link | size | author Suppose if link and size are similar for 2 rows or more, then those rows are duplicates. How do I get those duplicates into a list and process them?
[ "Will return all records that have dups:\nSELECT theTable.*\nFROM theTable\nINNER JOIN (\n SELECT link, size\n FROM theTable \n GROUP BY link, size\n HAVING count(ID) > 1\n) dups ON theTable.link = dups.link AND theTable.size = dups.size\n\nI like the subquery b/c I can do things like select all but the first or last. (very easy to turn into a delete query then).\nExample: select all duplicate records EXCEPT the one with the max ID: \nSELECT theTable.*\nFROM theTable\nINNER JOIN (\n SELECT link, size, max(ID) as maxID\n FROM theTable \n GROUP BY link, size\n HAVING count(ID) > 1\n) dups ON theTable.link = dups.link \n AND theTable.size = dups.size \n AND theTable.ID <> dups.maxID\n\n", "Assuming that none of id, link or size can be NULL, and id field is the primary key. This gives you the id's of duplicate rows. Beware that same id can be in the results several times, if there are three or more rows with identical link and size values.\nselect a.id, b.id \nfrom tbl a, tbl b \nwhere a.id < b.id \n and a.link = b.link \n and a.size = b.size \n\n", "After you remove the duplicates from the MySQL table, you can add a unique index\nto the table so no more duplicates can be inserted:\ncreate unique index theTable_index on theTable (link,size);\n\n", "If you want to do it exclusively in SQL, some kind of self-join of the table (on equality of link and size) is required, and can be accompanied by different kinds of elaboration. Since you mention Python as well, I assume you want to do the processing in Python; in that case, simplest is to build an iterator on a 'SELECT * FROM thetable ORDER BY link, size, and process withitertools.groupbyusing, as key, theoperator.itemgetter` for those two fields; this will present natural groupings of each bunch of 1+ rows with identical values for the fields in question.\nI can elaborate on either option if you clarify where you want to do your processing and ideally provide an example of the kind of processing you DO want to perform!\n" ]
[ 7, 1, 1, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001574064_mysql_python.txt
Q: How to match columns in MySQL Everyone knows the "=" sign. SELECT * FROM mytable WHERE column1 = column2; However, what if I have different contents in column1 and column2...but they are VERY similar? (maybe off by a space, or have a word that's different). Is it possible to: SELECT * FROM mytable WHERE ....column matches column2 with .4523423 "Score"... I believe this is called fuzzy matching? Or pattern matching? That's the technical term for it. EDIT: I know about Soundex and Levenstein disatance. IS that what you recommend? A: What you are looking for is called Levenstein distance. It gives you the number value which discribes the difference between two strings. In MySQL you have to write stored procedure for that. Here is the articla that may help. A: Lukasz Lysik posted a reference to a stored procedure that can do the fuzzy match from inside the database. If you will want to do this as an ongoing task, that is your best bet. But if you want to do this as a one-off task, and if you might want to do complicated checks, or if you want to do something complicated to clean up the fuzzy matches, you might want to do the fuzzy matching from within Python. (One of your tags is "python" so I assume you are open to a Python solution...) Using a Python ORM, you can get a Python list with one object per database row, and then use the full power of Python to analyze your data. You could use regular expressions, Python Levenstein functions, or anything else. The all-around best ORM for Python is probably SQLAlchemy. I actually like the ORM from Django a little better; it's a little simpler, and I value simplicity. If your ORM needs are not complicated, the Django ORM may be a good choice. If in doubt, just go to SQLAlchemy. Good luck!
How to match columns in MySQL
Everyone knows the "=" sign. SELECT * FROM mytable WHERE column1 = column2; However, what if I have different contents in column1 and column2...but they are VERY similar? (maybe off by a space, or have a word that's different). Is it possible to: SELECT * FROM mytable WHERE ....column matches column2 with .4523423 "Score"... I believe this is called fuzzy matching? Or pattern matching? That's the technical term for it. EDIT: I know about Soundex and Levenstein disatance. IS that what you recommend?
[ "What you are looking for is called Levenstein distance. It gives you the number value which discribes the difference between two strings. \nIn MySQL you have to write stored procedure for that. Here is the articla that may help.\n", "Lukasz Lysik posted a reference to a stored procedure that can do the fuzzy match from inside the database. If you will want to do this as an ongoing task, that is your best bet.\nBut if you want to do this as a one-off task, and if you might want to do complicated checks, or if you want to do something complicated to clean up the fuzzy matches, you might want to do the fuzzy matching from within Python. (One of your tags is \"python\" so I assume you are open to a Python solution...)\nUsing a Python ORM, you can get a Python list with one object per database row, and then use the full power of Python to analyze your data. You could use regular expressions, Python Levenstein functions, or anything else.\nThe all-around best ORM for Python is probably SQLAlchemy. I actually like the ORM from Django a little better; it's a little simpler, and I value simplicity. If your ORM needs are not complicated, the Django ORM may be a good choice. If in doubt, just go to SQLAlchemy.\nGood luck!\n" ]
[ 5, 0 ]
[]
[]
[ "mysql", "pattern_matching", "python", "sql", "string" ]
stackoverflow_0001574418_mysql_pattern_matching_python_sql_string.txt
Q: syntax error on `If` line My code: #!/usr/bin/env python def Runaaall(aaa): Objects9(1.0, 2.0) def Objects9(aaa1, aaa2): If aaa2 != 0: print aaa1 / aaa2 The error I receive: $ python test2.py File "test2.py", line 7 If aaa2 != 0: print aaa1 / aaa2 ^ SyntaxError: invalid syntax I'm at a loss to why this error is happening. A: if must be written in lower case. Furthermore, Write function names in lower case (see PEP 8, the Python style guide). Write the body of an if-clause on a separate line. Though in this case you'll probably not run into trouble, be careful with comparing floats for equality. Since you've just started learning Python, you may want to get acquainted with writing parentheses around the arguments to print, since from Python 3 onwards, print is a function, not a keyword. To enforce this syntax in Python 2.6, you can put this at the top of your file: from __future__ import print_function Demonstration: >>> print 'test' test >>> from __future__ import print_function >>> print 'test' File "<stdin>", line 1 print 'test' ^ SyntaxError: invalid syntax >>> print('test') test For more on __future__ imports, see the documentation. A: It's the capital 'I' on "If". Change it to "if" and it will work. A: How about def Objects9(aaa1, aaa2): if aaa2 != 0: print aaa1 / aaa2 Python keywords are case sensitive, so you must write 'if' instead of 'If', 'for' instead of 'fOR', et cetera.
syntax error on `If` line
My code: #!/usr/bin/env python def Runaaall(aaa): Objects9(1.0, 2.0) def Objects9(aaa1, aaa2): If aaa2 != 0: print aaa1 / aaa2 The error I receive: $ python test2.py File "test2.py", line 7 If aaa2 != 0: print aaa1 / aaa2 ^ SyntaxError: invalid syntax I'm at a loss to why this error is happening.
[ "if must be written in lower case.\nFurthermore,\n\nWrite function names in lower case (see PEP 8, the Python style guide).\nWrite the body of an if-clause on a separate line.\nThough in this case you'll probably not run into trouble, be careful with comparing floats for equality.\nSince you've just started learning Python, you may want to get acquainted with writing parentheses around the arguments to print, since from Python 3 onwards, print is a function, not a keyword.\nTo enforce this syntax in Python 2.6, you can put this at the top of your file:\nfrom __future__ import print_function\n\nDemonstration:\n>>> print 'test'\ntest\n>>> from __future__ import print_function\n>>> print 'test'\n File \"<stdin>\", line 1\n print 'test'\n ^\nSyntaxError: invalid syntax\n>>> print('test')\ntest\n\nFor more on __future__ imports, see the documentation.\n\n", "It's the capital 'I' on \"If\". Change it to \"if\" and it will work.\n", "How about\ndef Objects9(aaa1, aaa2):\n if aaa2 != 0: print aaa1 / aaa2\n\nPython keywords are case sensitive, so you must write 'if' instead of 'If', 'for' instead of 'fOR', et cetera.\n" ]
[ 16, 4, 3 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0001574530_python_syntax.txt
Q: Building Django app using Comet/Orbited on Apache, use mod_wsgi or mod_python? Building a Django app on a VPS. I am not very experienced with setting up my own server, but I decided to try a VPS this time around. I have been doing a bunch of research to learn how to "properly" setup a LAMPython server using the Apache worker MPM. Naturally, the mod_python vs mod_wsgi debate came up. Reading Graham Dumpleton's blog and his various mailinglist responses, I've learned quite a bit. Particularly, that the performance of mod_python could be greatly improved by using worker MPM - as described at Load spikes and excessive memory usage in mod_python Regardless, I had decided to go with mod_wsgi(daemon mode) + worker MPM, but then I started looking into implementing Comet and I got a bit confused. I was considering implementing comet using the technique described by Dark Porter ( http://darkporter.com/?p=7) because it looks like it optimizes the django setup a bit more by having it all in one process, but he specifically says that he uses mod_python and makes no mention of mod_wsgi. So my questions: 1) Is it possible to implement Dark Porter's method using mod_wsgi? 2) If you were setting a server to support Django+Comet, what components would you use and why? (mod_python vs mod_wsgi / DarkPortersMethod vs MorbidQ vs RabbitMQ) Thanks A: Yes, absolutely. I would probably use Orbited as implemented by Dark Porter - It's the simplest solution to get your code running, and implemented in pure python. Not to mention, based on Twisted and thus very scalable, and has a well-established community of Django users.
Building Django app using Comet/Orbited on Apache, use mod_wsgi or mod_python?
Building a Django app on a VPS. I am not very experienced with setting up my own server, but I decided to try a VPS this time around. I have been doing a bunch of research to learn how to "properly" setup a LAMPython server using the Apache worker MPM. Naturally, the mod_python vs mod_wsgi debate came up. Reading Graham Dumpleton's blog and his various mailinglist responses, I've learned quite a bit. Particularly, that the performance of mod_python could be greatly improved by using worker MPM - as described at Load spikes and excessive memory usage in mod_python Regardless, I had decided to go with mod_wsgi(daemon mode) + worker MPM, but then I started looking into implementing Comet and I got a bit confused. I was considering implementing comet using the technique described by Dark Porter ( http://darkporter.com/?p=7) because it looks like it optimizes the django setup a bit more by having it all in one process, but he specifically says that he uses mod_python and makes no mention of mod_wsgi. So my questions: 1) Is it possible to implement Dark Porter's method using mod_wsgi? 2) If you were setting a server to support Django+Comet, what components would you use and why? (mod_python vs mod_wsgi / DarkPortersMethod vs MorbidQ vs RabbitMQ) Thanks
[ "\nYes, absolutely.\nI would probably use Orbited as implemented by Dark Porter - It's the simplest solution to get your code running, and implemented in pure python. Not to mention, based on Twisted and thus very scalable, and has a well-established community of Django users.\n\n" ]
[ 3 ]
[]
[]
[ "apache", "comet", "django", "python" ]
stackoverflow_0001574513_apache_comet_django_python.txt
Q: Efficient way to convert strings from split function to ints in Python I have a string of data with the following format: xpos-ypos-zoom (i.e. 8743-12083-15) that I want to split up and store in the variables xpos, ypos, and zoom. Since I need to do some calculations with these number I'd like to convert them to integers right from the beginning. Currently, the way I'm doing this is with the following code: file = '8743-12083-15' xval, yval, zoom = file.split("-") xval = int(xval) yval = int(yval) It seems to me there should be a more efficient way of doing this. Any ideas? A: My original suggestion with a list comprehension. test = '8743-12083-15' lst_int = [int(x) for x in test.split("-")] EDIT: As to which is most efficient (cpu-cyclewise) is something that should always be tested. Some quick testing on my Python 2.6 install indicates map is probably the most efficient candidate here (building a list of integers from a value-splitted string). Note that the difference is so small that this does not really matter until you are doing this millions of times (and it is a proven bottleneck)... def v1(): return [int(x) for x in '8743-12083-15'.split('-')] def v2(): return map(int, '8743-12083-15'.split('-')) import timeit print "v1", timeit.Timer('v1()', 'from __main__ import v1').timeit(500000) print "v2", timeit.Timer('v2()', 'from __main__ import v2').timeit(500000) > output v1 3.73336911201 > output v2 3.44717001915 A: efficient as in fewer lines of code? (xval,yval,zval) = [int(s) for s in file.split('-')] A: note: you might want to pick a different name for file as it shadows the buildtin this works in Python 2 and 3 xval,yval,zval = map(int,file.split('-')) A: You can map the function int on each substring, or use a list comprehension: >>> file = '8743-12083-15' >>> list(map(int, file.split('-'))) [8743, 12083, 15] >>> [int(d) for d in file.split('-')] [8743, 12083, 15] In the above the call to list is not required, unless working with Python 3.x. (In Python 2.x map returns a list, in Python 3.x it returns a generator.) Directly assigning to the three variables is also possible (in this case a generator expression instead of a list comprehension will do): >>> xval, yval, zval = (int(d) for d in file.split('-')) >>> xval, yval, zval (8743, 12083, 15)
Efficient way to convert strings from split function to ints in Python
I have a string of data with the following format: xpos-ypos-zoom (i.e. 8743-12083-15) that I want to split up and store in the variables xpos, ypos, and zoom. Since I need to do some calculations with these number I'd like to convert them to integers right from the beginning. Currently, the way I'm doing this is with the following code: file = '8743-12083-15' xval, yval, zoom = file.split("-") xval = int(xval) yval = int(yval) It seems to me there should be a more efficient way of doing this. Any ideas?
[ "My original suggestion with a list comprehension.\ntest = '8743-12083-15'\nlst_int = [int(x) for x in test.split(\"-\")]\n\nEDIT:\nAs to which is most efficient (cpu-cyclewise) is something that should always be tested.\nSome quick testing on my Python 2.6 install indicates map is probably the most efficient candidate here (building a list of integers from a value-splitted string). Note that the difference is so small that this does not really matter until you are doing this millions of times (and it is a proven bottleneck)...\ndef v1():\n return [int(x) for x in '8743-12083-15'.split('-')]\n\ndef v2():\n return map(int, '8743-12083-15'.split('-'))\n\nimport timeit\nprint \"v1\", timeit.Timer('v1()', 'from __main__ import v1').timeit(500000)\nprint \"v2\", timeit.Timer('v2()', 'from __main__ import v2').timeit(500000)\n\n> output v1 3.73336911201 \n> output v2 3.44717001915\n\n", "efficient as in fewer lines of code?\n(xval,yval,zval) = [int(s) for s in file.split('-')]\n\n", "note: you might want to pick a different name for file as it shadows the buildtin\nthis works in Python 2 and 3\n\nxval,yval,zval = map(int,file.split('-'))\n\n", "You can map the function int on each substring, or use a list comprehension:\n>>> file = '8743-12083-15'\n>>> list(map(int, file.split('-')))\n[8743, 12083, 15]\n>>> [int(d) for d in file.split('-')]\n[8743, 12083, 15]\n\nIn the above the call to list is not required, unless working with Python 3.x. (In Python 2.x map returns a list, in Python 3.x it returns a generator.)\nDirectly assigning to the three variables is also possible (in this case a generator expression instead of a list comprehension will do):\n>>> xval, yval, zval = (int(d) for d in file.split('-'))\n>>> xval, yval, zval\n(8743, 12083, 15)\n\n" ]
[ 96, 20, 14, 12 ]
[]
[]
[ "casting", "python", "variables" ]
stackoverflow_0001574678_casting_python_variables.txt
Q: script to find pagerank of domain how can I automate finding the pagerank of a domain? I came across this Python script but it no longer works. Seems Google doesn't like people automating this. So, is there an alternative provider of page rank scores? I do not need the exact same result as Google, but something comparable. A: Here is a python script which does work. I had to do exactly the same thing recently! A: Have you tried HalOtis Marketing's Page Rank script at http://www.halotis.com/2009/08/02/google-page-range-python-script/? He generally writes good, simple Python code for exactly this kind of stuff.
script to find pagerank of domain
how can I automate finding the pagerank of a domain? I came across this Python script but it no longer works. Seems Google doesn't like people automating this. So, is there an alternative provider of page rank scores? I do not need the exact same result as Google, but something comparable.
[ "Here is a python script which does work. I had to do exactly the same thing recently!\n", "Have you tried HalOtis Marketing's Page Rank script at http://www.halotis.com/2009/08/02/google-page-range-python-script/? He generally writes good, simple Python code for exactly this kind of stuff.\n" ]
[ 4, 2 ]
[]
[]
[ "api", "pagerank", "python" ]
stackoverflow_0001572183_api_pagerank_python.txt
Q: Finding words from random input letters in python. What algorithm to use/code already there? I am trying to code a word descrambler like this one here and was wondering what algorithms I should use to implement this. Also, if anyone can find existing code for this that would be great as well. Basically the functionality is going to be like a boggle solver but without being a matrix, just searching for all word possibilities from a string of characters. I do already have adequate dictionaries. I was planning to do this in either python or ruby. Thanks in advance for your help guys! A: I'd use a Trie. Here's an implementation in Python: http://jtauber.com/2005/02/trie.py (credit to James Tauber) A: I may be missing an understanding of the game but barring some complications in the rules, such as with the introduction of "joker" (wildcard) letters, missing or additional letters, multiple words etc... I think the following ideas would help turn the problem in a somewhat relatively uninteresting thing. :-( Main idea index words by the ordered sequence of their letters. For example "computer" gets keyed as "cemoprtu". Whatever the random drawings provide is sorting in kind, and used as key to find possible matches. Using trie structures as suggested by perimosocordiae, as the underlying storage for these sorted keys and associated words(s)/wordIds in the "leaf" nodes, Word lookup can be done in O(n) time, where n is the number of letters (or better, on average due to non-existing words). To further help with indexing we can have several tables/dictionaries, one per number of letters. Also depending on statistics the vowels and consonants could be handled separately. Another trick would be to have a custom sort order, placing the most selective letters first. Additional twists to the game (such as finding words made from a subset of the letters) is mostly a matter of iterating the power set of these letters and checking the dictionary for each combination. A few heuristics can be introduced to help prune some of the combinations (for example combinations without vowels [and of a given length] are not possible solutions etc. One should manage these heuristics carefully for the lookup cost is relatively small. A: For your dictionary index, build a map (Map[Bag[Char], List[String]]). It should be a hash map so you can get O(1) word lookup. A Bag[Char] is an identifier for a word that is unique up to character order. It's is basically a hash map from Char to Int. The Char is a given character in the word and the Int is the number of times that character appears in the word. Example: {'a'=>3, 'n'=>1, 'g'=>1, 'r'=>1, 'm'=>1} => ["anagram"] {'s'=>3, 't'=>1, 'r'=>1, 'e'=>2, 'd'=>1} => ["stressed", "desserts"] To find words, take every combination of characters from the input string and look it up in this map. The complexity of this algorithm is O(2^n) in the length of the input string. Notably, the complexity does not depend on the length of the dictionary. A: This sounds like Rabin-Karp string search would be a good choice. If you use a rolling hash-function then at each position you need one hash value update and one dictionary lookup. You also need to create a good way to cope with different word lengths, like truncating all words to the shortest word in the set and rechecking possible matches. Splitting the word set into separate length ranges will reduce the amount of false positives at the expense of increasing the hashing work. A: There are two ways to do this. One is to check every candidate permutation of letters in the word to see if the candidate is in your dictionary of words. That's an O(N!) operation, depending on the length of the word. The other way is to check every candidate word in your dictionary to see if it's contained within the word. This can be sped up by aggregating the dictionary; instead of every candidate word, you check all words that are anagrams of each other at once, since if any one of them is contained in your word, all of them are. So start by building a dictionary whose key is a sorted string of letters and whose value is a list of the words that are anagrams of the key: >>> from collections import defaultdict >>> d = defaultdict(list) >>> with open(r"c:\temp\words.txt", "r") as f: for line in f.readlines(): if line[0].isupper(): continue word = line.strip() key = "".join(sorted(word.lower())) d[key].append(word) Now we need a function to see if a word contains a candidate. This function assumes that the word and candidate are both sorted, so that it can go through them both letter by letter and give up quickly when it finds that they don't match. >>> def contains(sorted_word, sorted_candidate): wchars = (c for c in sorted_word) for cc in sorted_candidate: while(True): try: wc = wchars.next() except StopIteration: return False if wc < cc: continue if wc == cc: break return False return True Now find all the candidate keys in the dictionary that are contained by the word, and aggregate all of their values into a single list: >>> w = sorted("mythopoetic") >>> result = [] >>> for k in d.keys(): if contains(w, k): result.extend(d[k]) >>> len(result) 429 >>> sorted(result)[:20] ['c', 'ce', 'cep', 'ceti', 'che', 'chetty', 'chi', 'chime', 'chip', 'chit', 'chitty', 'cho', 'chomp', 'choop', 'chop', 'chott', 'chyme', 'cipo', 'cit', 'cite'] That last step takes about a quarter second on my laptop; there are 195K keys in my dictionary (I'm using the BSD Unix words file).
Finding words from random input letters in python. What algorithm to use/code already there?
I am trying to code a word descrambler like this one here and was wondering what algorithms I should use to implement this. Also, if anyone can find existing code for this that would be great as well. Basically the functionality is going to be like a boggle solver but without being a matrix, just searching for all word possibilities from a string of characters. I do already have adequate dictionaries. I was planning to do this in either python or ruby. Thanks in advance for your help guys!
[ "I'd use a Trie. Here's an implementation in Python: http://jtauber.com/2005/02/trie.py (credit to James Tauber)\n", "I may be missing an understanding of the game but barring some complications in the rules, such as with the introduction of \"joker\" (wildcard) letters, missing or additional letters, multiple words etc... I think the following ideas would help turn the problem in a somewhat relatively uninteresting thing. :-(\nMain idea index words by the ordered sequence of their letters.\n For example \"computer\" gets keyed as \"cemoprtu\". Whatever the random drawings provide is sorting in kind, and used as key to find possible matches.\n Using trie structures as suggested by perimosocordiae, as the underlying storage for these sorted keys and associated words(s)/wordIds in the \"leaf\" nodes, Word lookup can be done in O(n) time, where n is the number of letters (or better, on average due to non-existing words). \nTo further help with indexing we can have several tables/dictionaries, one per number of letters. Also depending on statistics the vowels and consonants could be handled separately. Another trick would be to have a custom sort order, placing the most selective letters first.\nAdditional twists to the game (such as finding words made from a subset of the letters) is mostly a matter of iterating the power set of these letters and checking the dictionary for each combination. \nA few heuristics can be introduced to help prune some of the combinations (for example combinations without vowels [and of a given length] are not possible solutions etc. One should manage these heuristics carefully for the lookup cost is relatively small.\n", "For your dictionary index, build a map (Map[Bag[Char], List[String]]). It should be a hash map so you can get O(1) word lookup. A Bag[Char] is an identifier for a word that is unique up to character order. It's is basically a hash map from Char to Int. The Char is a given character in the word and the Int is the number of times that character appears in the word.\nExample:\n{'a'=>3, 'n'=>1, 'g'=>1, 'r'=>1, 'm'=>1} => [\"anagram\"]\n{'s'=>3, 't'=>1, 'r'=>1, 'e'=>2, 'd'=>1} => [\"stressed\", \"desserts\"]\n\nTo find words, take every combination of characters from the input string and look it up in this map. The complexity of this algorithm is O(2^n) in the length of the input string. Notably, the complexity does not depend on the length of the dictionary.\n", "This sounds like Rabin-Karp string search would be a good choice. If you use a rolling hash-function then at each position you need one hash value update and one dictionary lookup. You also need to create a good way to cope with different word lengths, like truncating all words to the shortest word in the set and rechecking possible matches. Splitting the word set into separate length ranges will reduce the amount of false positives at the expense of increasing the hashing work.\n", "There are two ways to do this. One is to check every candidate permutation of letters in the word to see if the candidate is in your dictionary of words. That's an O(N!) operation, depending on the length of the word.\nThe other way is to check every candidate word in your dictionary to see if it's contained within the word. This can be sped up by aggregating the dictionary; instead of every candidate word, you check all words that are anagrams of each other at once, since if any one of them is contained in your word, all of them are.\nSo start by building a dictionary whose key is a sorted string of letters and whose value is a list of the words that are anagrams of the key:\n>>> from collections import defaultdict\n>>> d = defaultdict(list)\n>>> with open(r\"c:\\temp\\words.txt\", \"r\") as f:\n for line in f.readlines():\n if line[0].isupper(): continue\n word = line.strip()\n key = \"\".join(sorted(word.lower()))\n d[key].append(word)\n\nNow we need a function to see if a word contains a candidate. This function assumes that the word and candidate are both sorted, so that it can go through them both letter by letter and give up quickly when it finds that they don't match.\n>>> def contains(sorted_word, sorted_candidate):\n wchars = (c for c in sorted_word)\n for cc in sorted_candidate:\n while(True):\n try:\n wc = wchars.next()\n except StopIteration:\n return False\n if wc < cc: continue\n if wc == cc: break\n return False\n return True\n\nNow find all the candidate keys in the dictionary that are contained by the word, and aggregate all of their values into a single list:\n>>> w = sorted(\"mythopoetic\")\n>>> result = []\n>>> for k in d.keys():\n if contains(w, k): result.extend(d[k])\n>>> len(result)\n429\n>>> sorted(result)[:20]\n['c', 'ce', 'cep', 'ceti', 'che', 'chetty', 'chi', 'chime', 'chip', 'chit', 'chitty', 'cho', 'chomp', 'choop', 'chop', 'chott', 'chyme', 'cipo', 'cit', 'cite']\n\nThat last step takes about a quarter second on my laptop; there are 195K keys in my dictionary (I'm using the BSD Unix words file).\n" ]
[ 3, 2, 2, 1, 1 ]
[]
[]
[ "anagram", "boggle", "python", "ruby", "word" ]
stackoverflow_0001570242_anagram_boggle_python_ruby_word.txt
Q: How to write a RESTful URL path regex in GAE/Python for n parameters? Currently I have three URL paths that map to ServiceHandler. How do I combine the three into one neat regex that can pass n number of arguments to ServiceHandler? (r'/s/([^/]*)', ServiceHandler), (r'/s/([^/]*)/([^/]*)', ServiceHandler), (r'/s/([^/]*)/([^/]*)/([^/]*)', ServiceHandler) A: (r'^/s/(([^/]*)((/[^/]+)*))$', ServiceHandler) Should do the trick to match any amount of /s/foo/bar/baz/to/infinity/and/beyond/ You can also limit it to a range by doing something like ^/s/(([^/]*)((/[^/]+){0,2}))$ Which would only match things like /s/foo/bar/baz /s/foo/bar /s/foo but not /s/foo/bar/baz/pirate /s A: You can try something like (r'/s/([^/]*)/?([^/]*)/?([^/]*)', ServiceHandler) I think you will always get 3 parameters to ServiceHandler but the ones that aren't used will be empty strings A: This should work for any number (r'(?<!^)/([^/]+)', ServiceHandler) Since I've looked in urlresolvers.py, I see this won't work although you could patch the correct behaviour into urlresolvers.py using regex.findall instead of re.search.
How to write a RESTful URL path regex in GAE/Python for n parameters?
Currently I have three URL paths that map to ServiceHandler. How do I combine the three into one neat regex that can pass n number of arguments to ServiceHandler? (r'/s/([^/]*)', ServiceHandler), (r'/s/([^/]*)/([^/]*)', ServiceHandler), (r'/s/([^/]*)/([^/]*)/([^/]*)', ServiceHandler)
[ "(r'^/s/(([^/]*)((/[^/]+)*))$', ServiceHandler)\n\nShould do the trick to match any amount of \n/s/foo/bar/baz/to/infinity/and/beyond/\nYou can also limit it to a range by doing something like\n^/s/(([^/]*)((/[^/]+){0,2}))$\n\nWhich would only match things like\n/s/foo/bar/baz\n/s/foo/bar\n/s/foo\n\nbut not \n/s/foo/bar/baz/pirate\n/s\n\n", "You can try something like\n(r'/s/([^/]*)/?([^/]*)/?([^/]*)', ServiceHandler)\nI think you will always get 3 parameters to ServiceHandler but the ones that aren't used will be empty strings\n", "This should work for any number\n(r'(?<!^)/([^/]+)', ServiceHandler)\n\nSince I've looked in urlresolvers.py, I see this won't work although you could patch the correct behaviour into urlresolvers.py using regex.findall instead of re.search.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python", "regex", "url_mapping" ]
stackoverflow_0001570198_google_app_engine_python_regex_url_mapping.txt
Q: How to read .ARC files from the Heritrix crawler using Python? I looked at the Heritrix documentation website, and they listed a Python .ARC file reader. However, it is 404 not found when I clicked on it. http://crawler.archive.org/articles/developer_manual/arcs.html Does anyone else know any Heritrix ARC reader that uses Python? (I asked this question before, but closed it due to inaccuracy) A: Nothing a little Googling can't find: http://archive-access.cvs.sourceforge.net/viewvc/archive-access/archive-access/projects/hedaern/
How to read .ARC files from the Heritrix crawler using Python?
I looked at the Heritrix documentation website, and they listed a Python .ARC file reader. However, it is 404 not found when I clicked on it. http://crawler.archive.org/articles/developer_manual/arcs.html Does anyone else know any Heritrix ARC reader that uses Python? (I asked this question before, but closed it due to inaccuracy)
[ "Nothing a little Googling can't find:\nhttp://archive-access.cvs.sourceforge.net/viewvc/archive-access/archive-access/projects/hedaern/\n" ]
[ 1 ]
[]
[]
[ "python", "web_crawler" ]
stackoverflow_0001575442_python_web_crawler.txt
Q: GAE load data into datastore without using CSV I've used bulkloader.Loader to load stuff into the GAE dev and live datastore, but my next thing to to create objects from non-CSV data and push it into the datastore. So say my object is something like: class CainEvent(db.Model): name =db.StringProperty(required=True) birthdate = db.DateProperty() Can anyone give me a simple example on how to do this please? A: Here's an extremely simplified example of what we're doing to use the bulkloader to load JSON data instead of CSV data: class JSONLoader(bulkloader.Loader): def generate_records(self, filename): for item in json.load(open(filename)): yield item['fields'] In this example, I'm assuming a JSON format that looks something like [ { "fields": [ "a", "b", "c", "d" ] }, { "fields": [ "e", "f", "g", "h" ] } ] which is oversimplified. Basically, all you have to do is create a subclass of bulkloader.Loader and implement (at a minimum) the generate_records method, which should yield lists of strings. This same strategy would work for loading data from XML files or ROT13-encrypted files or whatever. Note that the list of strings yielded by the generate_records method must match up (in length and order) with the "properties" list you provide when you initialize the loader (ie, the second argument to the AlbumLoader.__init__ method in this example). This approach actually provides a lot of flexibility: We're overriding the __init__ method on our JSONLoader implementation and automatically determining the kind of model we're loading and its list of properties to provide to the bulkloader.Loader parent class. A: You may find this post useful - it details how to load data direct from an RDBMS, but applies equally to loading from any other source.
GAE load data into datastore without using CSV
I've used bulkloader.Loader to load stuff into the GAE dev and live datastore, but my next thing to to create objects from non-CSV data and push it into the datastore. So say my object is something like: class CainEvent(db.Model): name =db.StringProperty(required=True) birthdate = db.DateProperty() Can anyone give me a simple example on how to do this please?
[ "Here's an extremely simplified example of what we're doing to use the bulkloader to load JSON data instead of CSV data:\nclass JSONLoader(bulkloader.Loader):\n def generate_records(self, filename):\n for item in json.load(open(filename)):\n yield item['fields']\n\nIn this example, I'm assuming a JSON format that looks something like\n[\n {\n \"fields\": [\n \"a\", \n \"b\", \n \"c\", \n \"d\"\n ]\n }, \n {\n \"fields\": [\n \"e\", \n \"f\", \n \"g\", \n \"h\"\n ]\n }\n]\n\nwhich is oversimplified.\nBasically, all you have to do is create a subclass of bulkloader.Loader and implement (at a minimum) the generate_records method, which should yield lists of strings. This same strategy would work for loading data from XML files or ROT13-encrypted files or whatever.\nNote that the list of strings yielded by the generate_records method must match up (in length and order) with the \"properties\" list you provide when you initialize the loader (ie, the second argument to the AlbumLoader.__init__ method in this example).\nThis approach actually provides a lot of flexibility: We're overriding the __init__ method on our JSONLoader implementation and automatically determining the kind of model we're loading and its list of properties to provide to the bulkloader.Loader parent class.\n", "You may find this post useful - it details how to load data direct from an RDBMS, but applies equally to loading from any other source.\n" ]
[ 2, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001422270_google_app_engine_python.txt
Q: Preempting __del__ hmmm I need to preempt __del__ and I want to know what is the right way to do this. Basically my question in code is this.. class A: def __init__(self): self.log = logging.getLogger() self.log.debug("In init") self.closed = False def close(self): self.log.debug("Doing some magic") self.closed = True def __del__(self): if not self.closed: self.close() self.log.debug("In closing") # What should go here to properly do GC?? Is there any way to now call the standard GC features? Thanks for reading!! Steve A: __del__ isn't a true destructor. It is called before an object is destroyed to free any resources it is holding. It need not worry about freeing memory itself. You can always call the parent class' __del__, too, if you are inheriting a class which may also have open resources. A: Please use the with statement for this. See http://docs.python.org/reference/compound_stmts.html#the-with-statement The with statement guarantees that if the enter() method returns without an error, then exit() will always be called. Rather than fool around with __del__, use __exit__ of a context manager object. A: If you're looking to call the GC manually then call gc.collect().
Preempting __del__ hmmm
I need to preempt __del__ and I want to know what is the right way to do this. Basically my question in code is this.. class A: def __init__(self): self.log = logging.getLogger() self.log.debug("In init") self.closed = False def close(self): self.log.debug("Doing some magic") self.closed = True def __del__(self): if not self.closed: self.close() self.log.debug("In closing") # What should go here to properly do GC?? Is there any way to now call the standard GC features? Thanks for reading!! Steve
[ "__del__ isn't a true destructor. It is called before an object is destroyed to free any resources it is holding. It need not worry about freeing memory itself.\nYou can always call the parent class' __del__, too, if you are inheriting a class which may also have open resources.\n", "Please use the with statement for this.\nSee http://docs.python.org/reference/compound_stmts.html#the-with-statement\n\nThe with statement guarantees that if\n the enter() method returns without\n an error, then exit() will always\n be called.\n\nRather than fool around with __del__, use __exit__ of a context manager object.\n", "If you're looking to call the GC manually then call gc.collect().\n" ]
[ 4, 3, 1 ]
[]
[]
[ "class", "python" ]
stackoverflow_0001575567_class_python.txt
Q: How can I read how many pixels an image has in Python Possible Duplicate: How to check dimensions of all images in a directory using python? I was wondering if somebody knows how can I read an image total amount of pixels in a python sript. Could you provide and example? Thanks a lot. A: here is an example: from PIL import Image def get_num_pixels(filepath): width, height = Image.open(filepath).size return width*height print(get_num_pixels("/path/to/my/file.jpg")) A: Use PIL to load the image. The total number of pixels will be its width multiplied by its height. A: Here is the example that you've asked for: from PIL import Image import os.path filename = os.path.join('path', 'to', 'image', 'file') img = Image.open(filename) width, height = img.size print "Dimensions:", img.size, "Total pixels:", width * height A: PIL, the Python Imaging Library can help you get this info from image's metadata.
How can I read how many pixels an image has in Python
Possible Duplicate: How to check dimensions of all images in a directory using python? I was wondering if somebody knows how can I read an image total amount of pixels in a python sript. Could you provide and example? Thanks a lot.
[ "here is an example:\nfrom PIL import Image\n\ndef get_num_pixels(filepath):\n width, height = Image.open(filepath).size\n return width*height\n\nprint(get_num_pixels(\"/path/to/my/file.jpg\"))\n\n", "Use PIL to load the image. The total number of pixels will be its width multiplied by its height.\n", "Here is the example that you've asked for:\nfrom PIL import Image\nimport os.path\n\nfilename = os.path.join('path', 'to', 'image', 'file')\nimg = Image.open(filename)\nwidth, height = img.size\nprint \"Dimensions:\", img.size, \"Total pixels:\", width * height\n\n", "PIL, the Python Imaging Library can help you get this info from image's metadata.\n" ]
[ 21, 6, 4, 1 ]
[]
[]
[ "pixels", "python" ]
stackoverflow_0001575625_pixels_python.txt
Q: Python on multiprocessor machines: multiprocessing or a non-GIL interpreter This is more a style question. For CPU bound processes that really benefit for having multiple cores, do you typically use the multiprocessing module or use threads with an interpreter that doesn't have the GIL? I've used the multiprocessing library only lightly, but also have no experience with anything besides CPython. I'm curious what the preferred approach is and if it is to use a different interpreter, which one. A: I don't really see a "style" argument to be made here, either way -- both multiprocessing in CPython 2.6, and threading in (e.g.) the current versions of Jython and IronPython, let you code in extremely similar ways (and styles;-). So, I'd choose on the basis of very "hard-nosed" considerations -- what is performance like with each choice (if I'm so CPU-bound as to benefit from multiple cores, then performance is obviously of paramount importance), could I use with serious benefit any library that's CPython-only (like numpy) or maybe something else that's JVM- or .NET- only, and so forth. A: Take a look at Parallel Python (www.parallelpython.com) -- I've used to to nicely split up work among the processors on my quad-core box. It even supports clusters!
Python on multiprocessor machines: multiprocessing or a non-GIL interpreter
This is more a style question. For CPU bound processes that really benefit for having multiple cores, do you typically use the multiprocessing module or use threads with an interpreter that doesn't have the GIL? I've used the multiprocessing library only lightly, but also have no experience with anything besides CPython. I'm curious what the preferred approach is and if it is to use a different interpreter, which one.
[ "I don't really see a \"style\" argument to be made here, either way -- both multiprocessing in CPython 2.6, and threading in (e.g.) the current versions of Jython and IronPython, let you code in extremely similar ways (and styles;-). So, I'd choose on the basis of very \"hard-nosed\" considerations -- what is performance like with each choice (if I'm so CPU-bound as to benefit from multiple cores, then performance is obviously of paramount importance), could I use with serious benefit any library that's CPython-only (like numpy) or maybe something else that's JVM- or .NET- only, and so forth.\n", "Take a look at Parallel Python (www.parallelpython.com) -- I've used to to nicely split up work among the processors on my quad-core box. It even supports clusters!\n" ]
[ 3, 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0001575985_multiprocessing_python.txt
Q: Sorting strings with integers and text in Python I'm making a stupid little game that saves your score in a highscores.txt file. My problem is sorting the lines. Here's what I have so far. Maybe an alphanumeric sorter for python would help? Thanks. import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highscores.txt") score = 500 name = "Nicholas" #If the file doesn't exist, create one with the high scores format. if file_exists == False: f = open("highscores.txt", "w") f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name') new_score = str(score) + ".........." + name f = open("highscores.txt", "r+") words = f.readlines() print words main() A: after words = f.readlines(), try something like: headers = words.pop(0) def myway(aline): i = 0 while aline[i].isdigit(): i += 1 score = int(aline[:i]) return score words.sort(key=myway, reverse=True) words.insert(0, headers) The key (;-) idea is to make a function that returns the "sorting key" from each item (here, a line). I'm trying to write it in the simplest possible way: see how many leading digits there are, then turn them all into an int, and return that. A: I'd like to encourage you to store your high scores in a more robust format. In particular I suggest JSON. import simplejson as json # Python 2.x # import json # Python 3.x d = {} d["version"] = 1 d["highscores"] = [[100, "Steve"], [200, "Ken"], [400, "Denise"]] s = json.dumps(d) print s # prints: # {"version": 1, "highscores": [[100, "Steve"], [200, "Ken"], [400, "Denise"]]} d2 = json.loads(s) for score, name in sorted(d2["highscores"], reverse=True): print "%5d\t%s" % (score, name) # prints: # 400 Denise # 200 Ken # 100 Steve Using JSON will keep you from having to write your own parser to recover data from saved files such as high score tables. You can just tuck everything into a dictionary and trivially get it all back. Note that I tucked in a version number, the version number of your high score save format. If you ever change the save format of your data, having a version number in there will be a very good thing. A: Doing a simple string sort on your new_score = str(score) + ".........." + name items isn't going to work since, for example str(1000) < str(500). In other words, 1000 will come before 500 in an alphanumeric sort. Alex's answer is good in that it demonstrates the use of a sort key function, but here is another solution which is a bit simpler and has the added advantage of visuallaly aligning the high score displays. What you need to do is right align your numbers in a fixed field of the maximum size of the scores, thus (assuming 5 digits max and ver < 3.0): new_score = "%5d........%s" % (score, name) or for Python ver 3.x: new_score = "{0:5d}........{1}".format(score, name) For each new_score append it to the words list (you could use a better name here) and sort it reversed before printing. Or you could use the bisect.insort library function rather than doing a list.append. Also, a more Pythonic form than if file_exists == False: is: if not file_exists: A: I guess something went wrong when you pasted from Alex's answer, so here is your code with a sort in there import os.path def main(): #Check if the file exists file_exists = os.path.exists("highscores.txt") score = 500 name = "Nicholas" #If the file doesn't exist, create one with the high scores format. if file_exists == False: f = open("highscores.txt", "w") f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name') new_score = str(score) + ".........." + name +"\n" f = open("highscores.txt", "r+") words = f.readlines() headers = words.pop(0) def anotherway(aline): score="" for c in aline: if c.isdigit(): score+=c else: break return int(score) words.append(new_score) words.sort(key=anotherway, reverse=True) words.insert(0, headers) print "".join(words) main() A: What you want is probably what's generally known as a "Natural Sort". Searching for "natural sort python" gives many results, but there's some good discussion on ASPN.
Sorting strings with integers and text in Python
I'm making a stupid little game that saves your score in a highscores.txt file. My problem is sorting the lines. Here's what I have so far. Maybe an alphanumeric sorter for python would help? Thanks. import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highscores.txt") score = 500 name = "Nicholas" #If the file doesn't exist, create one with the high scores format. if file_exists == False: f = open("highscores.txt", "w") f.write('Guppies High Scores\n1000..........Name\n750..........Name\n600..........Name\n450..........Name\n300..........Name') new_score = str(score) + ".........." + name f = open("highscores.txt", "r+") words = f.readlines() print words main()
[ "after words = f.readlines(), try something like:\nheaders = words.pop(0)\n\ndef myway(aline):\n i = 0\n while aline[i].isdigit():\n i += 1\n score = int(aline[:i])\n return score\n\nwords.sort(key=myway, reverse=True)\n\nwords.insert(0, headers)\n\nThe key (;-) idea is to make a function that returns the \"sorting key\" from each item (here, a line). I'm trying to write it in the simplest possible way: see how many leading digits there are, then turn them all into an int, and return that.\n", "I'd like to encourage you to store your high scores in a more robust format. In particular I suggest JSON.\nimport simplejson as json # Python 2.x\n# import json # Python 3.x\n\nd = {}\nd[\"version\"] = 1\nd[\"highscores\"] = [[100, \"Steve\"], [200, \"Ken\"], [400, \"Denise\"]]\ns = json.dumps(d)\nprint s\n# prints:\n# {\"version\": 1, \"highscores\": [[100, \"Steve\"], [200, \"Ken\"], [400, \"Denise\"]]}\n\n\nd2 = json.loads(s)\nfor score, name in sorted(d2[\"highscores\"], reverse=True):\n print \"%5d\\t%s\" % (score, name)\n\n# prints:\n# 400 Denise\n# 200 Ken\n# 100 Steve\n\nUsing JSON will keep you from having to write your own parser to recover data from saved files such as high score tables. You can just tuck everything into a dictionary and trivially get it all back.\nNote that I tucked in a version number, the version number of your high score save format. If you ever change the save format of your data, having a version number in there will be a very good thing.\n", "Doing a simple string sort on your \nnew_score = str(score) + \"..........\" + name\n\nitems isn't going to work since, for example str(1000) < str(500). In other words, 1000 will come before 500 in an alphanumeric sort.\nAlex's answer is good in that it demonstrates the use of a sort key function, but here is another solution which is a bit simpler and has the added advantage of visuallaly aligning the high score displays.\nWhat you need to do is right align your numbers in a fixed field of the maximum size of the scores, thus (assuming 5 digits max and ver < 3.0):\nnew_score = \"%5d........%s\" % (score, name)\n\nor for Python ver 3.x:\nnew_score = \"{0:5d}........{1}\".format(score, name)\n\nFor each new_score append it to the words list (you could use a better name here) and sort it reversed before printing. Or you could use the bisect.insort library function rather than doing a list.append.\nAlso, a more Pythonic form than\nif file_exists == False:\n\nis:\nif not file_exists:\n\n", "I guess something went wrong when you pasted from Alex's answer, so here is your code with a sort in there\n\nimport os.path\n\ndef main():\n #Check if the file exists\n file_exists = os.path.exists(\"highscores.txt\")\n\n score = 500\n name = \"Nicholas\"\n\n #If the file doesn't exist, create one with the high scores format.\n if file_exists == False:\n f = open(\"highscores.txt\", \"w\")\n f.write('Guppies High Scores\\n1000..........Name\\n750..........Name\\n600..........Name\\n450..........Name\\n300..........Name')\n\n new_score = str(score) + \"..........\" + name +\"\\n\"\n\n f = open(\"highscores.txt\", \"r+\")\n words = f.readlines()\n\n headers = words.pop(0)\n\n def anotherway(aline):\n score=\"\" \n for c in aline:\n if c.isdigit():\n score+=c\n else:\n break\n return int(score)\n\n words.append(new_score)\n words.sort(key=anotherway, reverse=True)\n\n words.insert(0, headers)\n\n print \"\".join(words)\n\nmain()\n\n", "What you want is probably what's generally known as a \"Natural Sort\". Searching for \"natural sort python\" gives many results, but there's some good discussion on ASPN.\n" ]
[ 4, 1, 0, 0, 0 ]
[]
[]
[ "alphanumeric", "python", "string" ]
stackoverflow_0001575971_alphanumeric_python_string.txt
Q: Output in two rows for multiple columns in python I'm working with an output list that contains the following information: [start position, stop position, chromosome, [('sample name', 'sample value'), ('sample name','sample value')...]] [[59000, 59500, chr1, [('cn_04', '1.362352462'), ('cn_01', '1.802001235')]], [100000, 110000, chr1, [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]], [63500, 64000, chr1, [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]] ...] I want to write it to an excel file that will format it with the sample names as the titles of columns and then the values for the samples in columns. Some samples don't have values so these spaces would be blank or have no data notation. Something that looks Like this (sorry had to use >> to denote column separations): cn_01 cn_02 cn_03 cn_04 cn_05 cn_06 start stop chromosome 1.802 "" "" 1.362 "" "" 59000 59500 chr1 4.302 1.990 1.887 "" "" "" 100000 110000 chr1 Any help would be great. A: For sending data to Excel, I would use CSV instead of a fixed-length text format; that way, if it turns out (say) that you need more significant figures in your float values, the format of your output doesn't change. Also, you can just open CSV files in Excel; you don't have to import them. And the csv.writer deals with all of the data-type conversion issues for you. I'd also take advantage of the (apparent) fact that the 4th item in each observation appears to be a set of key/value pairs, which the dict function can turn into a dictionary. Assuming that you know what all of the keys are, you can specify the order that you want them to appear in your output simply by putting them in a list (called keys in the below code). Then it's simple to create an ordered list of values with a list comprehension. Thus: >>> import sys >>> import csv >>> keys = ['cn_01', 'cn_02', 'cn_03', 'cn_04', 'cn_05', 'cn_06'] >>> data = [[59000, 59500, 'chr1', [('cn_04', '1.362352462'), ('cn_01', '1.802001235')]], [100000, 110000, 'chr1', [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]], [63500, 64000, 'chr1', [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]]] >>> writer = csv.writer(sys.stdout) >>> writer.writerow(keys + ['start', 'stop', 'chromosome']) cn_01,cn_02,cn_03,cn_04,cn_05,cn_06,start,stop,chromosome >>>>for obs in data: d = dict(obs[3]) row = [d.get(k, None) for k in keys] + obs[0:3] writer.writerow(row) 1.802001235,,,1.362352462,,,59000,59500,chr1 4.302275763,1.990457407,1.887268908,,,,100000,110000,chr1 4.302275763,1.990457407,1.887268908,,,,63500,64000,chr1 The above writes the data to sys.stdout; to create a real CSV file you'd do something like: with open('file.csv', 'w') as f: writer = csv.writer(f) # now use the writer to write out the data A: You can create a simple text file with "*.csv" extension. Separate each field (column) by a comma. Optionally, use quotation marks for text fields, especially if a field is expected to contain your delimiter (comma). You can even put excel formulas (preceded by '=') and excel will parse them correctly. Double click on any csv file will open it in excel (unless your computer has other settings). You can also use the csv module The Learning Python book contains examples with more complex control (formatting, spreadsheets) using Windows COM components EDIT: I have just seen this site. The PDF tutorial seems to be very detailed. Never used this. A: Here's one approach. I made the simplifying assumption that there is a small finite limit to the possible number of observations, so I just loop from 1 to 6 explicitly. You can easily expand the upper limit of the loop, although if you go past 9 the logic in the get_obs function will need to change. You could also write something more complex to first scan through all the data and get all the possible observation names, but I didn't want to put in that effort if it's not necessary. This could be somewhat simplified if you used a dictionary instead of a list of tuples to hold the observation data for each row. data = [[59000, 59500, 'chr1', [('cn_04', '1.362352462'), ('cn_01', '1.802001235')]], [100000, 110000, 'chr1', [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]], [63500, 64000, 'chr1', [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]] ] def get_obs( num, obslist ): keyval = 'cn_0' + str(num) for obs in obslist: if obs[0] == keyval: return obs[1] return "." for data_row in data: output_row = "" for obs in range(1,7): output_row += get_obs( obs, data_row[3] ) + '\t' output_row += str(data_row[0]) + '\t' output_row += str(data_row[1]) + '\t' output_row += str(data_row[2]) print output_row A: You can also use xlwt to write .xls files directly, without touching Excel. More info. Here is some sample code to get you started (far from perfect): import xlwt as xl def list2xls(data, fn=None, col_names=None, row_names=None): wb = xl.Workbook() ws = wb.add_sheet('output') if col_names: _write_1d_list_horz(ws, 0, 1, col_names) if row_names: _write_1d_list_vert(ws, 1, 0, row_names) _write_matrix(ws, 1, 1, data) if not fn: fn = 'test.xls' wb.save(fn) def _write_matrix(ws, row_start, col_start, mat): for irow, row in enumerate(mat): _write_1d_list_horz(ws, irow + row_start, col_start, row) def _write_1d_list_horz(ws, row, col, list): for i, val in enumerate(list): ws.write(row, i + col, val) def _write_1d_list_vert(ws, row, col, list): for i, val in enumerate(list): ws.write(row + i, col, val) Call list2xls, with data as a 2-d list, and optional column and row names as lists.
Output in two rows for multiple columns in python
I'm working with an output list that contains the following information: [start position, stop position, chromosome, [('sample name', 'sample value'), ('sample name','sample value')...]] [[59000, 59500, chr1, [('cn_04', '1.362352462'), ('cn_01', '1.802001235')]], [100000, 110000, chr1, [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]], [63500, 64000, chr1, [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]] ...] I want to write it to an excel file that will format it with the sample names as the titles of columns and then the values for the samples in columns. Some samples don't have values so these spaces would be blank or have no data notation. Something that looks Like this (sorry had to use >> to denote column separations): cn_01 cn_02 cn_03 cn_04 cn_05 cn_06 start stop chromosome 1.802 "" "" 1.362 "" "" 59000 59500 chr1 4.302 1.990 1.887 "" "" "" 100000 110000 chr1 Any help would be great.
[ "For sending data to Excel, I would use CSV instead of a fixed-length text format; that way, if it turns out (say) that you need more significant figures in your float values, the format of your output doesn't change. Also, you can just open CSV files in Excel; you don't have to import them. And the csv.writer deals with all of the data-type conversion issues for you.\nI'd also take advantage of the (apparent) fact that the 4th item in each observation appears to be a set of key/value pairs, which the dict function can turn into a dictionary. Assuming that you know what all of the keys are, you can specify the order that you want them to appear in your output simply by putting them in a list (called keys in the below code). Then it's simple to create an ordered list of values with a list comprehension. Thus:\n>>> import sys\n>>> import csv\n>>> keys = ['cn_01', 'cn_02', 'cn_03', 'cn_04', 'cn_05', 'cn_06']\n>>> data = [[59000, 59500, 'chr1', [('cn_04', '1.362352462'), ('cn_01', '1.802001235')]], [100000, 110000, 'chr1', [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]], [63500, 64000, 'chr1', [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]]]\n>>> writer = csv.writer(sys.stdout)\n>>> writer.writerow(keys + ['start', 'stop', 'chromosome'])\ncn_01,cn_02,cn_03,cn_04,cn_05,cn_06,start,stop,chromosome\n>>>>for obs in data:\n d = dict(obs[3])\n row = [d.get(k, None) for k in keys] + obs[0:3]\n writer.writerow(row)\n\n1.802001235,,,1.362352462,,,59000,59500,chr1\n4.302275763,1.990457407,1.887268908,,,,100000,110000,chr1\n4.302275763,1.990457407,1.887268908,,,,63500,64000,chr1\n\nThe above writes the data to sys.stdout; to create a real CSV file you'd do something like:\nwith open('file.csv', 'w') as f:\n writer = csv.writer(f)\n # now use the writer to write out the data\n\n", "You can create a simple text file with \"*.csv\" extension. Separate each field (column) by a comma. Optionally, use quotation marks for text fields, especially if a field is expected to contain your delimiter (comma). You can even put excel formulas (preceded by '=') and excel will parse them correctly.\nDouble click on any csv file will open it in excel (unless your computer has other settings).\nYou can also use the csv module\nThe Learning Python book contains examples with more complex control (formatting, spreadsheets) using Windows COM components\nEDIT: I have just seen this site. The PDF tutorial seems to be very detailed. Never used this.\n", "Here's one approach. I made the simplifying assumption that there is a small finite limit to the possible number of observations, so I just loop from 1 to 6 explicitly. You can easily expand the upper limit of the loop, although if you go past 9 the logic in the get_obs function will need to change. You could also write something more complex to first scan through all the data and get all the possible observation names, but I didn't want to put in that effort if it's not necessary.\nThis could be somewhat simplified if you used a dictionary instead of a list of tuples to hold the observation data for each row.\ndata = [[59000, 59500, 'chr1', \n [('cn_04', '1.362352462'), ('cn_01', '1.802001235')]], \n [100000, 110000, 'chr1', \n [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]],\n [63500, 64000, 'chr1', \n [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')]]\n ]\n\ndef get_obs( num, obslist ):\n keyval = 'cn_0' + str(num)\n for obs in obslist:\n if obs[0] == keyval:\n return obs[1]\n return \".\"\n\nfor data_row in data:\n output_row = \"\"\n for obs in range(1,7):\n output_row += get_obs( obs, data_row[3] ) + '\\t'\n output_row += str(data_row[0]) + '\\t'\n output_row += str(data_row[1]) + '\\t'\n output_row += str(data_row[2])\n print output_row\n\n", "You can also use xlwt to write .xls files directly, without touching Excel. More info.\nHere is some sample code to get you started (far from perfect):\nimport xlwt as xl\ndef list2xls(data, fn=None, col_names=None, row_names=None):\n wb = xl.Workbook()\n ws = wb.add_sheet('output')\n if col_names:\n _write_1d_list_horz(ws, 0, 1, col_names)\n if row_names:\n _write_1d_list_vert(ws, 1, 0, row_names)\n _write_matrix(ws, 1, 1, data)\n if not fn:\n fn = 'test.xls'\n wb.save(fn)\n def _write_matrix(ws, row_start, col_start, mat):\n for irow, row in enumerate(mat):\n _write_1d_list_horz(ws, irow + row_start, col_start, row)\n def _write_1d_list_horz(ws, row, col, list):\n for i, val in enumerate(list):\n ws.write(row, i + col, val)\n def _write_1d_list_vert(ws, row, col, list):\n for i, val in enumerate(list):\n ws.write(row + i, col, val)\n\nCall list2xls, with data as a 2-d list, and optional column and row names as lists.\n" ]
[ 3, 0, 0, 0 ]
[ "Never do these types of nested lists/dictionary, they are not pythonic and are very likely to bring you to an error.\nInstead, either use a class:\n>>> class Gene:\n def __init__(self, start, end, chromosome, transcripts):\n self.start = start\n self.end = end\n self.chromosome = chromosome\n self.transcripts = transcripts\n>>> gene1 = Gene(59000, 59500, 'chr1', [('cn_04', '1.362352462'), ('cn_01', '1.802001235')])\n>>> gene2 = Gene(100000, 110000, 'chr1', [('cn_03', '1.887268908'), ('cn_02', '1.990457407'), ('cn_01', '4.302275763')])\n>>> genes = [gene1, gene2, ...]\n>>> gene1.start\n59000\n>>> genes[1].start\n59000\n\nor either use numpy's recordarrays and matrixes.\nTo read and write CSV file you can use numpy's recarrays and functions.\n>>> from matplotlib.mlab import csv2rec, rec2csv\n>>> import numpy as np\n>>> d = array([(0, 10, 'chr1', [1, 2]), (20, 30, 'chr2', [1,2])], dtype=[('start', int), ('end', int), ('chromosome', 'S8'), ('transcripts', list)])\n\n# all values in the 'chromosome' column\n>>> d['chromosome']\narray(['chr1', 'chr2'], \n dtype='|S8')\n\n# records in which chromosome == 1\n>>> d[d['chromosome'] == 'chr1'] \n\n# print first record\n>>> d[0]\n(0, 10, 'chr1', [1, 2])\n\n# save it to a csv file:\n>>> rec2csv(d, 'csvfile.txt', delimiter='\\t')\n\n" ]
[ -1 ]
[ "bioinformatics", "file", "format", "python" ]
stackoverflow_0001573671_bioinformatics_file_format_python.txt
Q: Why does else behave differently in for/while statements as opposed to if/try statements? I have recently stumbled over a seeming inconsistency in Python's way of dealing with else clauses in different compound statements. Since Python is so well designed, I'm sure that there is a good explanation, but I can't think of it. Consider the following: if condition: do_something() else: do_something_else() Here, do_something_else() is only executed if condition is false, as expected. Similarly, in try: do_something() except someException: pass: else: do_something_else() finally: cleanup() do_something_else() is only executed if no exception occurred. But in for or while loops, an else clause is always executed, whether the contents of the for/while block have been executed or not. for i in some_iterator: print(i) else: print("Iterator is empty!") will always print "Iterator is empty!", whether I say some_iterator = [] or some_iterator = [1,2,3]. Same behavior in while-else clauses. It seems to me that else behaves more like finally in these cases. What am I overlooking? A: The for else construct executes the else clause if no break statement was executed for the loop, as described here For example, this else clause is never evaluated for i in range(1,10): if i % 5 == 0: print i break else: print "nothing divisible by 5" A: Well, it depends how you see it. You can look at the elses like this (excuse the screaming, its the only way to make emphasis in code): if condition: do_something() IF THE PREVIOUS CONDITION WAS FALSE: do_something_else() Now, there is an obvious similarity between if/else and try/except/else, if you see the else statement as an else to the except statement. Like this. try: do_something() IF THERE WAS AN EXCEPTION: pass: IF THE PREVIOUS CONDITION WAS FALSE: do_something_else() finally: cleanup() Same goes for the else/for: IF some_iterator IS NOT EMPTY: i = next(some_iterator) print(i) IF THE PREVIOUS CONDITION WAS FALSE: print("Iterator is empty!") So here we see that the else in some fundamental way do work exactly the same in all three cases. But you can also see the else in this way: try: do_something() except someException: pass: IF NO EXCEPTION: do_something_else() finally: cleanup() And then it's not the same anymore, but the else because a sort of "if nothing else". You can see for/else in the same way: for i in some_iterator: print(i) IF NO MORE ITERATING: print("Iterator is empty!") But then again, considering the elif, then this way of seeing it works for if/else as well: if condition: do_something() elif otherconditaion: do_anotherthing() IF NO CONDITION WAS TRUE: do_something_else() Which way you want to look at the else is up to you, but in both ways of viewing, else do have similarities in all three cases. A: Yes, as Eli mentioned, the else clause is executed only if you don't break. It stops you from implementing code like this: for i in range(1,10): if i % 5 == 0: print i break if i % 5 != 0: print "nothing divisible by 5" Which is roughly equivalent here, but handy if the conditions for quitting are a bit more complicated (like checking various possible conditions or combinations of conditions).
Why does else behave differently in for/while statements as opposed to if/try statements?
I have recently stumbled over a seeming inconsistency in Python's way of dealing with else clauses in different compound statements. Since Python is so well designed, I'm sure that there is a good explanation, but I can't think of it. Consider the following: if condition: do_something() else: do_something_else() Here, do_something_else() is only executed if condition is false, as expected. Similarly, in try: do_something() except someException: pass: else: do_something_else() finally: cleanup() do_something_else() is only executed if no exception occurred. But in for or while loops, an else clause is always executed, whether the contents of the for/while block have been executed or not. for i in some_iterator: print(i) else: print("Iterator is empty!") will always print "Iterator is empty!", whether I say some_iterator = [] or some_iterator = [1,2,3]. Same behavior in while-else clauses. It seems to me that else behaves more like finally in these cases. What am I overlooking?
[ "The for else construct executes the else clause if no break statement was executed for the loop, as described here For example, this else clause is never evaluated\nfor i in range(1,10):\n if i % 5 == 0:\n print i\n break\nelse:\n print \"nothing divisible by 5\"\n\n", "Well, it depends how you see it. You can look at the elses like this (excuse the screaming, its the only way to make emphasis in code):\nif condition:\n do_something()\nIF THE PREVIOUS CONDITION WAS FALSE:\n do_something_else()\n\nNow, there is an obvious similarity between if/else and try/except/else, if you see the else statement as an else to the except statement. Like this.\ntry:\n do_something()\nIF THERE WAS AN EXCEPTION:\n pass:\nIF THE PREVIOUS CONDITION WAS FALSE:\n do_something_else()\nfinally:\n cleanup()\n\nSame goes for the else/for:\nIF some_iterator IS NOT EMPTY:\n i = next(some_iterator)\n print(i)\nIF THE PREVIOUS CONDITION WAS FALSE:\n print(\"Iterator is empty!\")\n\nSo here we see that the else in some fundamental way do work exactly the same in all three cases. \nBut you can also see the else in this way:\ntry:\n do_something()\nexcept someException:\n pass:\nIF NO EXCEPTION:\n do_something_else()\nfinally:\n cleanup()\n\nAnd then it's not the same anymore, but the else because a sort of \"if nothing else\". You can see for/else in the same way:\nfor i in some_iterator:\n print(i)\nIF NO MORE ITERATING:\n print(\"Iterator is empty!\")\n\nBut then again, considering the elif, then this way of seeing it works for if/else as well:\nif condition:\n do_something()\nelif otherconditaion:\n do_anotherthing()\nIF NO CONDITION WAS TRUE:\n do_something_else()\n\nWhich way you want to look at the else is up to you, but in both ways of viewing, else do have similarities in all three cases.\n", "Yes, as Eli mentioned, the else clause is executed only if you don't break. It stops you from implementing code like this:\nfor i in range(1,10):\n if i % 5 == 0:\n print i\n break\nif i % 5 != 0:\n print \"nothing divisible by 5\"\n\nWhich is roughly equivalent here, but handy if the conditions for quitting are a bit more complicated (like checking various possible conditions or combinations of conditions).\n" ]
[ 13, 5, 4 ]
[]
[]
[ "control_flow", "python" ]
stackoverflow_0001576537_control_flow_python.txt
Q: In regex, what does [\w*] mean? What does this regex mean? ^[\w*]$ A: Quick answer: ^[\w*]$ will match a string consisting of a single character, where that character is alphanumeric (letters, numbers) an underscore (_) or an asterisk (*). Details: The "\w" means "any word character" which usually means alphanumeric (letters, numbers, regardless of case) plus underscore (_) The "^" "anchors" to the beginning of a string, and the "$" "anchors" To the end of a string, which means that, in this case, the match must start at the beginning of a string and end at the end of the string. The [] means a character class, which means "match any character contained in the character class". It is also worth mentioning that normal quoting and escaping rules for strings make it very difficult to enter regular expressions (all the backslashes would need to be escaped with additional backslashes), so in Python there is a special notation which has its own special quoting rules that allow for all of the backslashes to be interpreted properly, and that is what the "r" at the beginning is for. Note: Normally an asterisk (*) means "0 or more of the previous thing" but in the example above, it does not have that meaning, since the asterisk is inside of the character class, so it loses its "special-ness". For more information on regular expressions in Python, the two official references are the re module, the Regular Expression HOWTO. A: As exhuma said, \w is any word-class character (alphanumeric as Jonathan clarifies). However because it is in square brackets it will match: a single alphanumeric character OR an asterisk (*) So the whole regular expression matches: the beginning of a line (^) followed by either a single alphanumeric character or an asterisk followed by the end of a line ($) so the following would match: blah z <- matches this line blah or blah * <- matches this line blah A: \w refers to 0 or more alphanumeric characters and the underscore. the * in your case is also inside the character class, so [\w*] would match all of [a-zA-Z0-9_*] (the * is interpreted literally) See http://www.regular-expressions.info/reference.html To quote: \d, \w and \s --- Shorthand character classes matching digits, word characters, and whitespace. Can be used inside and outside character classes. Edit corrected in response to comment A: From the beginning of this line, "Any number of word characters (letter, number, underscore)" until the end of the line. I am unsure as to why it's in square brackets, as circle brackets (e.g. "(" and ")") are correct if you want the matched text returned. A: \w is equivalent to [a-zA-Z0-9_] I don't understand the * after it or the [] around it, because \w already is a class and * in class definitions makes no sense. A: As said above \w means any word. so you could use this in the context of below view.aspx?url=[\w] which means you can have any word as the value of the "url=" parameter
In regex, what does [\w*] mean?
What does this regex mean? ^[\w*]$
[ "Quick answer: ^[\\w*]$ will match a string consisting of a single character, where that character is alphanumeric (letters, numbers) an underscore (_) or an asterisk (*).\nDetails:\n\nThe \"\\w\" means \"any word character\" which usually means alphanumeric (letters, numbers, regardless of case) plus underscore (_)\nThe \"^\" \"anchors\" to the beginning of a string, and the \"$\" \"anchors\" To the end of a string, which means that, in this case, the match must start at the beginning of a string and end at the end of the string.\nThe [] means a character class, which means \"match any character contained in the character class\".\n\nIt is also worth mentioning that normal quoting and escaping rules for strings make it very difficult to enter regular expressions (all the backslashes would need to be escaped with additional backslashes), so in Python there is a special notation which has its own special quoting rules that allow for all of the backslashes to be interpreted properly, and that is what the \"r\" at the beginning is for.\nNote: Normally an asterisk (*) means \"0 or more of the previous thing\" but in the example above, it does not have that meaning, since the asterisk is inside of the character class, so it loses its \"special-ness\".\nFor more information on regular expressions in Python, the two official references are the re module, the Regular Expression HOWTO.\n", "As exhuma said, \\w is any word-class character (alphanumeric as Jonathan clarifies).\nHowever because it is in square brackets it will match:\n\na single alphanumeric character OR\nan asterisk (*)\n\nSo the whole regular expression matches:\n\nthe beginning of a\nline (^)\nfollowed by either a\nsingle alphanumeric character or an\nasterisk\nfollowed by the end of a\nline ($)\n\nso the following would match:\nblah\nz <- matches this line\nblah\n\nor\nblah\n* <- matches this line\nblah\n\n", "\\w refers to 0 or more alphanumeric characters and the underscore. the * in your case is also inside the character class, so [\\w*] would match all of [a-zA-Z0-9_*] (the * is interpreted literally)\nSee http://www.regular-expressions.info/reference.html\nTo quote:\n\n\\d, \\w and \\s --- Shorthand character classes matching digits, word characters, and whitespace. Can be used inside and outside character classes.\n\nEdit corrected in response to comment\n", "From the beginning of this line, \"Any number of word characters (letter, number, underscore)\" until the end of the line.\nI am unsure as to why it's in square brackets, as circle brackets (e.g. \"(\" and \")\") are correct if you want the matched text returned.\n", "\\w is equivalent to [a-zA-Z0-9_] I don't understand the * after it or the [] around it, because \\w already is a class and * in class definitions makes no sense. \n", "As said above \\w means any word. so you could use this in the context of below\nview.aspx?url=[\\w]\n\nwhich means you can have any word as the value of the \"url=\" parameter\n" ]
[ 71, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex", "syntax" ]
stackoverflow_0001576789_python_regex_syntax.txt
Q: How to use ? and ?: and : in REGEX for Python? I understand that * = "zero or more" ? = "zero or more" ...what's the difference? Also, ?: << my book uses this, it says its a "subtlety" but I don't know what exactly these do! A: As Manu already said, ? means "zero or one time". It is the same as {0,1}. And by ?:, you probably meant (?:X), where X is some other string. This is called a "non-capturing group". Normally when you wrap parenthesis around something, you group what is matched by those parenthesis. For example, the regex .(.).(.) matches any 4 characters (except line breaks) and stores the second character in group 1 and the fourth character in group 2. However, when you do: .(?:.).(.) only the fourth character is stored in group 1, everything bewteen (?:.) is matched, but not "remembered". A little demo: import re m = re.search('.(.).(.)', '1234') print m.group(1) print m.group(2) # output: # 2 # 4 m = re.search('.(?:.).(.)', '1234') print m.group(1) # output: # 4 You might ask yourself: "why use this non-capturing group at all?". Well, sometimes, you want to make an OR between two strings, for example, you want to match the string "www.google.com" or "www.yahoo.com", you could then do: www\.google\.com|www\.yahoo\.com, but shorter would be: www\.(google|yahoo)\.com of course. But if you're not going to do something useful with what is being captured by this group (the string "google", or "yahoo"), you mind as well use a non-capturing group: www\.(?:google|yahoo)\.com. When the regex engine does not need to "remember" the substring "google" or "yahoo" then your app/script will run faster. Of course, it wouldn't make much difference with relatively small strings, but when your regex and string(s) gets larger, it probably will. And for a better example to use non-capturing groups, see Chris Lutz's comment below. A: ?: << my book uses this, it says its a "subtlety" but I don't know what exactly these do! If that’s indeed what your book says, then I advise getting a better book. Inside parentheses (more precisely: right after an opening parenthesis), ? has another meaning. It starts a group of options which count only for the scope of the parentheses. ?: is a special case of these options. To understand this special case, you must first know that parentheses create capture groups: a(.)c This is a regular expression that matches any three-letter string starting with a and ending with c. The middle character is (more or less) aribtrary. Since you put it in parentheses, you can capture it: m = re.search('a(.)c', 'abcdef') print m.group(1) This will print b, since m.group(1) captures the content of the first parentheses (group(0) captures the whole hit, here abc). Now, consider this regular expression: a(?:.)c No capture is made here – this is what ?: after an opening parenthesis means. That is, the following code will fail: print m.group(1) Because there is no group 1! A: ? = zero or one you use (?:) for grouping w/o saving the group in a temporary variable as you would with () A: ? does not mean "zero or more", it means "zero or one".
How to use ? and ?: and : in REGEX for Python?
I understand that * = "zero or more" ? = "zero or more" ...what's the difference? Also, ?: << my book uses this, it says its a "subtlety" but I don't know what exactly these do!
[ "As Manu already said, ? means \"zero or one time\". It is the same as {0,1}.\nAnd by ?:, you probably meant (?:X), where X is some other string. This is called a \"non-capturing group\".\nNormally when you wrap parenthesis around something, you group what is matched by those parenthesis. For example, the regex .(.).(.) matches any 4 characters (except line breaks) and stores the second character in group 1 and the fourth character in group 2. However, when you do: .(?:.).(.) only the fourth character is stored in group 1, everything bewteen (?:.) is matched, but not \"remembered\".\nA little demo:\nimport re\nm = re.search('.(.).(.)', '1234')\nprint m.group(1)\nprint m.group(2)\n# output:\n# 2\n# 4\n\nm = re.search('.(?:.).(.)', '1234')\nprint m.group(1)\n# output:\n# 4\n\nYou might ask yourself: \"why use this non-capturing group at all?\". Well, sometimes, you want to make an OR between two strings, for example, you want to match the string \"www.google.com\" or \"www.yahoo.com\", you could then do: www\\.google\\.com|www\\.yahoo\\.com, but shorter would be: www\\.(google|yahoo)\\.com of course. But if you're not going to do something useful with what is being captured by this group (the string \"google\", or \"yahoo\"), you mind as well use a non-capturing group: www\\.(?:google|yahoo)\\.com. When the regex engine does not need to \"remember\" the substring \"google\" or \"yahoo\" then your app/script will run faster. Of course, it wouldn't make much difference with relatively small strings, but when your regex and string(s) gets larger, it probably will.\nAnd for a better example to use non-capturing groups, see Chris Lutz's comment below.\n", "\n?: << my book uses this, it says its a \"subtlety\" but I don't know what exactly these do!\n\nIf that’s indeed what your book says, then I advise getting a better book.\nInside parentheses (more precisely: right after an opening parenthesis), ? has another meaning. It starts a group of options which count only for the scope of the parentheses. ?: is a special case of these options. To understand this special case, you must first know that parentheses create capture groups:\na(.)c\n\nThis is a regular expression that matches any three-letter string starting with a and ending with c. The middle character is (more or less) aribtrary. Since you put it in parentheses, you can capture it:\nm = re.search('a(.)c', 'abcdef')\nprint m.group(1)\n\nThis will print b, since m.group(1) captures the content of the first parentheses (group(0) captures the whole hit, here abc).\nNow, consider this regular expression:\na(?:.)c\n\nNo capture is made here – this is what ?: after an opening parenthesis means. That is, the following code will fail:\nprint m.group(1)\n\nBecause there is no group 1!\n", "? = zero or one\nyou use (?:) for grouping w/o saving the group in a temporary variable as you would with ()\n", "? does not mean \"zero or more\", it means \"zero or one\".\n" ]
[ 6, 4, 2, 1 ]
[]
[]
[ "python", "regex", "syntax" ]
stackoverflow_0001576957_python_regex_syntax.txt
Q: What does this function do? def fun1(a): for i in range(len(a)): a[i] = a[i] * a[i] return a A: It takes an array as parameter and returns the same array with each member squared. EDIT: Since you modified your question from 'What does this function do' to 'What is some code to execute this function', here is an example: def fun1(a): for i in range(len(a)): a[i] = a[i] * a[i] return a test1 = [1,2,3,4,5] print 'Original list', test1 test2 = fun1(test1) print 'Result', test2 print 'Original list', test1 The output will be: Original list [1, 2, 3, 4, 5] Result [1, 4, 9, 16, 25] Original list [1, 4, 9, 16, 25] Because the function modifies the list in place, test1 is also modified. A: It will go through your List and multiply each value by itself. Example a = [ 1, 2, 3, 4, 5, 6 ] After that function a would look like this: a = [ 1, 4, 9, 16, 25, 36 ] A: It's a trivial function that could be replaced with the one-liner: a = [x*x for x in a] A: it multiplies each element of the array "a" with itself and stores the results back in the array. A: a is passed as a list , I assume. It squares each element of the list and returns the list. A: It squares every element in the input array and returns the squared array. So with a = [1,2,3,4,5] result is: [1,4,9,16,25]
What does this function do?
def fun1(a): for i in range(len(a)): a[i] = a[i] * a[i] return a
[ "It takes an array as parameter and returns the same array with each member squared.\nEDIT:\nSince you modified your question from 'What does this function do' to 'What is some code to execute this function', here is an example:\ndef fun1(a):\n for i in range(len(a)):\n a[i] = a[i] * a[i]\n return a\n\ntest1 = [1,2,3,4,5]\nprint 'Original list', test1\ntest2 = fun1(test1)\nprint 'Result', test2\nprint 'Original list', test1\n\nThe output will be:\nOriginal list [1, 2, 3, 4, 5]\nResult [1, 4, 9, 16, 25]\nOriginal list [1, 4, 9, 16, 25]\n\nBecause the function modifies the list in place, test1 is also modified.\n", "It will go through your List and multiply each value by itself.\nExample\na = [ 1, 2, 3, 4, 5, 6 ]\n\nAfter that function a would look like this:\na = [ 1, 4, 9, 16, 25, 36 ]\n\n", "It's a trivial function that could be replaced with the one-liner:\na = [x*x for x in a]\n\n", "it multiplies each element of the array \"a\" with itself and stores the results back in the array.\n", "a is passed as a list , I assume.\nIt squares each element of the list and returns the list.\n", "It squares every element in the input array and returns the squared array.\nSo with a = [1,2,3,4,5]\nresult is: [1,4,9,16,25]\n" ]
[ 12, 3, 3, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001577031_python.txt
Q: Structuring a program. Classes and functions in Python I'm writing a program that uses genetic techniques to evolve equations. I want to be able to submit the function 'mainfunc' to the Parallel Python 'submit' function. The function 'mainfunc' calls two or three methods defined in the Utility class. They instantiate other classes and call various methods. I think what I want is all of it in one NAMESPACE. So I've instantiated some (maybe it should be all) of the classes inside the function 'mainfunc'. I call the Utility method 'generate()'. If we were to follow it's chain of execution it would involve all of the classes and methods in the code. Now, the equations are stored in a tree. Each time a tree is generated, mutated or cross bred, the nodes need to be given a new key so they can be accessed from a dictionary attribute of the tree. The class 'KeySeq' generates these keys. In Parallel Python, I'm going to send multiple instances of 'mainfunc' to the 'submit' function of PP. Each has to be able to access 'KeySeq'. It would be nice if they all accessed the same instance of KeySeq so that none of the nodes on the returned trees had the same key, but I could get around that if necessary. So: my question is about stuffing EVERYTHING into mainfunc. Thanks (Edit) If I don't include everything in mainfunc, I have to try to tell PP about dependent functions, etc by passing various arguements in various places. I'm trying to avoid that. (late Edit) if ks.next() is called inside the 'generate() function, it returns the error 'NameError: global name 'ks' is not defined' class KeySeq: "Iterator to produce sequential \ integers for keys in dict" def __init__(self, data = 0): self.data = data def __iter__(self): return self def next(self): self.data = self.data + 1 return self.data class One: 'some code' class Two: 'some code' class Three: 'some code' class Utilities: def generate(x): '___________' def obfiscate(y): '___________' def ruminate(z): '__________' def mainfunc(z): ks = KeySeq() one = One() two = Two() three = Three() utilities = Utilities() list_of_interest = utilities.generate(5) return list_of_interest result = mainfunc(params) A: It's fine to structure your program that way. A lot of command line utilities follow the same pattern: #imports, utilities, other functions def main(arg): #... if __name__ == '__main__': import sys main(sys.argv[1]) That way you can call the main function from another module by importing it, or you can run it from the command line. A: If you want all of the instances of mainfunc to use the same KeySeq object, you can use the default parameter value trick: def mainfunc(ks=KeySeq()): key = ks.next() As long as you don't actually pass in a value of ks, all calls to mainfunc will use the instance of KeySeq that was created when the function was defined. Here's why, in case you don't know: A function is an object. It has attributes. One of its attributes is named func_defaults; it's a tuple containing the default values of all of the arguments in its signature that have defaults. When you call a function and don't provide a value for an argument that has a default, the function retrieves the value from func_defaults. So when you call mainfunc without providing a value for ks, it gets the KeySeq() instance out of the func_defaults tuple. Which, for that instance of mainfunc, is always the same KeySeq instance. Now, you say that you're going to send "multiple instances of mainfunc to the submit function of PP." Do you really mean multiple instances? If so, the mechanism I'm describing won't work. But it's tricky to create multiple instances of a function (and the code you've posted doesn't). For example, this function does return a new instance of g every time it's called: >>> def f(): def g(x=[]): return x return g >>> g1 = f() >>> g2 = f() >>> g1().append('a') >>> g2().append('b') >>> g1() ['a'] >>> g2() ['b'] If I call g() with no argument, it returns the default value (initially an empty list) from its func_defaults tuple. Since g1 and g2 are different instances of the g function, their default value for the x argument is also a different instance, which the above demonstrates. If you'd like to make this more explicit than using a tricky side-effect of default values, here's another way to do it: def mainfunc(): if not hasattr(mainfunc, "ks"): setattr(mainfunc, "ks", KeySeq()) key = mainfunc.ks.next() Finally, a super important point that the code you've posted overlooks: If you're going to be doing parallel processing on shared data, the code that touches that data needs to implement locking. Look at the callback.py example in the Parallel Python documentation and see how locking is used in the Sum class, and why. A: Your concept of classes in Python is not sound I think. Perhaps, it would be a good idea to review the basics. This link will help. Python Basics - Classes
Structuring a program. Classes and functions in Python
I'm writing a program that uses genetic techniques to evolve equations. I want to be able to submit the function 'mainfunc' to the Parallel Python 'submit' function. The function 'mainfunc' calls two or three methods defined in the Utility class. They instantiate other classes and call various methods. I think what I want is all of it in one NAMESPACE. So I've instantiated some (maybe it should be all) of the classes inside the function 'mainfunc'. I call the Utility method 'generate()'. If we were to follow it's chain of execution it would involve all of the classes and methods in the code. Now, the equations are stored in a tree. Each time a tree is generated, mutated or cross bred, the nodes need to be given a new key so they can be accessed from a dictionary attribute of the tree. The class 'KeySeq' generates these keys. In Parallel Python, I'm going to send multiple instances of 'mainfunc' to the 'submit' function of PP. Each has to be able to access 'KeySeq'. It would be nice if they all accessed the same instance of KeySeq so that none of the nodes on the returned trees had the same key, but I could get around that if necessary. So: my question is about stuffing EVERYTHING into mainfunc. Thanks (Edit) If I don't include everything in mainfunc, I have to try to tell PP about dependent functions, etc by passing various arguements in various places. I'm trying to avoid that. (late Edit) if ks.next() is called inside the 'generate() function, it returns the error 'NameError: global name 'ks' is not defined' class KeySeq: "Iterator to produce sequential \ integers for keys in dict" def __init__(self, data = 0): self.data = data def __iter__(self): return self def next(self): self.data = self.data + 1 return self.data class One: 'some code' class Two: 'some code' class Three: 'some code' class Utilities: def generate(x): '___________' def obfiscate(y): '___________' def ruminate(z): '__________' def mainfunc(z): ks = KeySeq() one = One() two = Two() three = Three() utilities = Utilities() list_of_interest = utilities.generate(5) return list_of_interest result = mainfunc(params)
[ "It's fine to structure your program that way. A lot of command line utilities follow the same pattern:\n#imports, utilities, other functions\n\ndef main(arg):\n #...\n\nif __name__ == '__main__':\n import sys\n main(sys.argv[1])\n\nThat way you can call the main function from another module by importing it, or you can run it from the command line.\n", "If you want all of the instances of mainfunc to use the same KeySeq object, you can use the default parameter value trick:\ndef mainfunc(ks=KeySeq()):\n key = ks.next()\n\nAs long as you don't actually pass in a value of ks, all calls to mainfunc will use the instance of KeySeq that was created when the function was defined.\nHere's why, in case you don't know: A function is an object. It has attributes. One of its attributes is named func_defaults; it's a tuple containing the default values of all of the arguments in its signature that have defaults. When you call a function and don't provide a value for an argument that has a default, the function retrieves the value from func_defaults. So when you call mainfunc without providing a value for ks, it gets the KeySeq() instance out of the func_defaults tuple. Which, for that instance of mainfunc, is always the same KeySeq instance.\nNow, you say that you're going to send \"multiple instances of mainfunc to the submit function of PP.\" Do you really mean multiple instances? If so, the mechanism I'm describing won't work.\nBut it's tricky to create multiple instances of a function (and the code you've posted doesn't). For example, this function does return a new instance of g every time it's called:\n>>> def f():\n def g(x=[]):\n return x\n return g\n>>> g1 = f()\n>>> g2 = f()\n>>> g1().append('a')\n>>> g2().append('b')\n>>> g1()\n['a']\n>>> g2()\n['b']\n\nIf I call g() with no argument, it returns the default value (initially an empty list) from its func_defaults tuple. Since g1 and g2 are different instances of the g function, their default value for the x argument is also a different instance, which the above demonstrates.\nIf you'd like to make this more explicit than using a tricky side-effect of default values, here's another way to do it:\ndef mainfunc():\n if not hasattr(mainfunc, \"ks\"):\n setattr(mainfunc, \"ks\", KeySeq())\n key = mainfunc.ks.next()\nFinally, a super important point that the code you've posted overlooks: If you're going to be doing parallel processing on shared data, the code that touches that data needs to implement locking. Look at the callback.py example in the Parallel Python documentation and see how locking is used in the Sum class, and why.\n", "Your concept of classes in Python is not sound I think. Perhaps, it would be a good idea to review the basics. This link will help.\nPython Basics - Classes\n" ]
[ 3, 1, 0 ]
[]
[]
[ "parallel_python", "python" ]
stackoverflow_0001561282_parallel_python_python.txt
Q: What does this function do? def fun1(a,x): z = 0 for i in range(len(a)): if a[i] == x: z = z + 1 return z A: It counts and returns the number of occurrences of x in the array a. More broadly, a can be any indexable object. See 5.3.2 Subscriptions of the Python Language Reference v2.6.3: 5.3.2. Subscriptions A subscription selects an item of a sequence (string, tuple or list) or mapping (dictionary) object: subscription ::= primary "[" expression_list "]" The primary must evaluate to an object of a sequence or mapping type. If the primary is a mapping, the expression list must evaluate to an object whose value is one of the keys of the mapping, and the subscription selects the value in the mapping that corresponds to that key. (The expression list is a tuple except if it has exactly one item.) If the primary is a sequence, the expression (list) must evaluate to a plain integer. If this value is negative, the length of the sequence is added to it (so that, e.g., x[-1] selects the last item of x.) The resulting value must be a nonnegative integer less than the number of items in the sequence, and the subscription selects the item whose index is that value (counting from zero). A string’s items are characters. A character is not a separate data type but a string of exactly one character. A: It counts the amount of elements in a which are equal to x. It assumes a is indexable (like a string or a list) def fun1(a,x): #Defines a function with 2 parameters, a and x z = 0 #Initializes the counter for i in range(len(a)): #len(a) returns the length of a, range(len(a)) #returns an enumerator from 0 to len(a) - 1 if a[i] == x: #which is then used here to index a z = z + 1 #if the ith element of a is equal to x, increment counter return z #return the counter Given the title change, you can execute the function like: > fun1("hola mundo","o") 2 or > fun1([1,2,3,4,4,3,2,1],4) 2 A: Counts the number of x repeated elements in the array a. A: Code to execute the function? fun1("hello world","l") A: Shorter version of the code above: >>> def f(a, x): ... return sum(1 for e in a if e == x) ... >>> f([1, 2, 3, 4, 3, 7], 3) 2 This uses a generator expression to construct an iterable which yields 1 for each occurrence of x in a. sum adds them. Even slightly shorter is to use len and filter (this code needs a conversion to list if using Python 3.x): >>> def f(a, x): ... return len(filter(x.__eq__, a)) ... >>> f([1, 2, 3, 4, 3, 7], 3) 2 The above functions work for any iterable object. As SilentGhost and gnibbler point out, for string objects and mutable sequence types there is the count method, which allows for an even more concise notation: >>> [1, 2, 3, 4, 3, 7].count(3) 2
What does this function do?
def fun1(a,x): z = 0 for i in range(len(a)): if a[i] == x: z = z + 1 return z
[ "It counts and returns the number of occurrences of x in the array a. More broadly, a can be any indexable object. See 5.3.2 Subscriptions of the Python Language Reference v2.6.3:\n\n5.3.2. Subscriptions\nA subscription selects an item of a\n sequence (string, tuple or list) or\n mapping (dictionary) object:\n subscription ::= primary \"[\" expression_list \"]\"\n\nThe primary must evaluate to an object\n of a sequence or mapping type.\nIf the primary is a mapping, the\n expression list must evaluate to an\n object whose value is one of the keys\n of the mapping, and the subscription\n selects the value in the mapping that\n corresponds to that key. (The\n expression list is a tuple except if\n it has exactly one item.)\nIf the primary is a sequence, the\n expression (list) must evaluate to a\n plain integer. If this value is\n negative, the length of the sequence\n is added to it (so that, e.g., x[-1]\n selects the last item of x.) The\n resulting value must be a nonnegative\n integer less than the number of items\n in the sequence, and the subscription\n selects the item whose index is that\n value (counting from zero).\nA string’s items are characters. A\n character is not a separate data type\n but a string of exactly one character.\n\n", "It counts the amount of elements in a which are equal to x. It assumes a is indexable (like a string or a list)\ndef fun1(a,x): #Defines a function with 2 parameters, a and x\n z = 0 #Initializes the counter\n for i in range(len(a)): #len(a) returns the length of a, range(len(a)) \n #returns an enumerator from 0 to len(a) - 1\n if a[i] == x: #which is then used here to index a\n z = z + 1 #if the ith element of a is equal to x, increment counter\n return z #return the counter\n\nGiven the title change, you can execute the function like:\n> fun1(\"hola mundo\",\"o\")\n2\n\nor\n> fun1([1,2,3,4,4,3,2,1],4)\n2\n\n", "Counts the number of x repeated elements in the array a.\n", "Code to execute the function?\nfun1(\"hello world\",\"l\")\n\n", "Shorter version of the code above:\n>>> def f(a, x):\n... return sum(1 for e in a if e == x)\n... \n>>> f([1, 2, 3, 4, 3, 7], 3)\n2\n\nThis uses a generator expression to construct an iterable which yields 1 for each occurrence of x in a. sum adds them. Even slightly shorter is to use len and filter (this code needs a conversion to list if using Python 3.x):\n>>> def f(a, x):\n... return len(filter(x.__eq__, a))\n... \n>>> f([1, 2, 3, 4, 3, 7], 3)\n2\n\nThe above functions work for any iterable object. As SilentGhost and gnibbler point out, for string objects and mutable sequence types there is the count method, which allows for an even more concise notation:\n>>> [1, 2, 3, 4, 3, 7].count(3)\n2\n\n" ]
[ 9, 4, 3, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001577169_python.txt
Q: Lossless PDF rotation is there a way to rotate a PDF 90 degrees losslessly, with Python or using the command line? I'm looking for a REAL rotation, not just adding a "/ROTATE 90" inside the PDF, because afterwards I have to send the PDF via Hylafax and it looks like that it ignores those commands. I tried with ImageMagick's convert but the quality of the resulting PDF is quite low. (Python 2.6.2, Xubuntu 9.04) Thanks for your attention! A: The best resolution you will normally obtain from a standard fax machine is about 200dpi; standard faxes are about 100dpi. If you need your faxed documents to work with an artitrary fax machine you can't go above this. Ergo, rendering your PDF to a 100 or 200dpi bitmap and rotating it 90 degress should work as well as anything. Various ghostscript based tool chains can do the rendering. Alternatively, there are a number of PDF and postscript based tools that can do this type of manipulatiion (e.g. PDF2PS and psutils) directly off the PDF. A: In the pdfjam package there is a shell script pdf90 which does the rotation via pdflatex.
Lossless PDF rotation
is there a way to rotate a PDF 90 degrees losslessly, with Python or using the command line? I'm looking for a REAL rotation, not just adding a "/ROTATE 90" inside the PDF, because afterwards I have to send the PDF via Hylafax and it looks like that it ignores those commands. I tried with ImageMagick's convert but the quality of the resulting PDF is quite low. (Python 2.6.2, Xubuntu 9.04) Thanks for your attention!
[ "The best resolution you will normally obtain from a standard fax machine is about 200dpi; standard faxes are about 100dpi. If you need your faxed documents to work with an artitrary fax machine you can't go above this.\nErgo, rendering your PDF to a 100 or 200dpi bitmap and rotating it 90 degress should work as well as anything. Various ghostscript based tool chains can do the rendering. Alternatively, there are a number of PDF and postscript based tools that can do this type of manipulatiion (e.g. PDF2PS and psutils) directly off the PDF.\n", "In the pdfjam package there is a shell script pdf90 which does the rotation via pdflatex.\n" ]
[ 3, 3 ]
[]
[]
[ "lossless", "pdf", "python", "rotation", "ubuntu" ]
stackoverflow_0001577168_lossless_pdf_python_rotation_ubuntu.txt
Q: Weird lxml behavior Consider the following snippet: import lxml.html html = '<div><br />Hello text</div>' doc = lxml.html.fromstring(html) text = doc.xpath('//text()')[0] print lxml.html.tostring(text.getparent()) #prints <br>Hello text I was expecting to see '<div><br />Hello text</div>', because br can't have nested text and is "self-closed" (I mean />). How to make lxml handle it right? A: HTML doesn't have self-closing tags. It is a xml thing. import lxml.etree html = '<div><br />Hello text</div>' doc = lxml.etree.fromstring(html) text = doc.xpath('//text()')[0] print lxml.etree.tostring(text.getparent()) prints <br/>Hello text Note that the text is not inside the tag. lxml has a "tail" concept. >>> print text.text None >>> print text.tail Hello text A: When you are dealing with valid XHTML you can use the etree instead of html. import lxml.etree html = '<div><br />Hello text</div>' doc = lxml.etree.fromstring(html) text = doc.xpath('//text()')[0] print lxml.etree.tostring(text.getparent()) Fun thing, you can typically use this to convert HTML to XHTML: import lxml.etree import lxml.html html = '<div><br>Hello text</div>' doc = lxml.html.fromstring(html) text = doc.xpath('//text()')[0] print lxml.etree.tostring(text.getparent()) Output: "<br/>Hello text"
Weird lxml behavior
Consider the following snippet: import lxml.html html = '<div><br />Hello text</div>' doc = lxml.html.fromstring(html) text = doc.xpath('//text()')[0] print lxml.html.tostring(text.getparent()) #prints <br>Hello text I was expecting to see '<div><br />Hello text</div>', because br can't have nested text and is "self-closed" (I mean />). How to make lxml handle it right?
[ "HTML doesn't have self-closing tags. It is a xml thing.\nimport lxml.etree\n\nhtml = '<div><br />Hello text</div>'\ndoc = lxml.etree.fromstring(html)\ntext = doc.xpath('//text()')[0]\nprint lxml.etree.tostring(text.getparent())\n\nprints\n<br/>Hello text\n\nNote that the text is not inside the tag. lxml has a \"tail\" concept.\n>>> print text.text\nNone\n>>> print text.tail\nHello text\n\n", "When you are dealing with valid XHTML you can use the etree instead of html.\nimport lxml.etree\n\nhtml = '<div><br />Hello text</div>'\ndoc = lxml.etree.fromstring(html)\ntext = doc.xpath('//text()')[0]\nprint lxml.etree.tostring(text.getparent())\n\nFun thing, you can typically use this to convert HTML to XHTML:\nimport lxml.etree\nimport lxml.html\n\nhtml = '<div><br>Hello text</div>'\ndoc = lxml.html.fromstring(html)\ntext = doc.xpath('//text()')[0]\nprint lxml.etree.tostring(text.getparent())\n\nOutput: \"<br/>Hello text\"\n" ]
[ 8, 2 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0001577732_lxml_python.txt
Q: Django - Custom SQL in the connection string I have had some issues with downtime as a result of hitting the max_user_connections limit in MySql. The default connection timeout is 8 hours, so once we hit the limit (and having no access to kill the connections on our shared hosting) I simply had to wait 8 hours for the connections to time out. I would like to add the following code to my connection string: SET wait_timeout=300; Which would change the timeout to 5 minutes. As you can imagine, I'm much happier to deal with 5 minutes of downtime than 8 hours. ;) Is there a good way of adding custom SQL to the connection string in django? If not, it has been suggested that we write some middleware that runs the SQL before the view is processed. That might work, but I would feel more comfortable knowing that the query was absolutely guaranteed to run for every connection, even if more than one connection is opened for each view. Thanks! PS - before you tell me I should just hunt down the code that is keeping the connections from being closed - Never Fear! - we are doing that, but I would like to have this extra insurance against another 8 hour block of downtime A: You can specify a list of commands to send to MySQL when the connection is open, by setting the DATABASE_OPTIONS dictionary in settings.py. (Incidentally, note that Django doesn't open a new connection for every view.)
Django - Custom SQL in the connection string
I have had some issues with downtime as a result of hitting the max_user_connections limit in MySql. The default connection timeout is 8 hours, so once we hit the limit (and having no access to kill the connections on our shared hosting) I simply had to wait 8 hours for the connections to time out. I would like to add the following code to my connection string: SET wait_timeout=300; Which would change the timeout to 5 minutes. As you can imagine, I'm much happier to deal with 5 minutes of downtime than 8 hours. ;) Is there a good way of adding custom SQL to the connection string in django? If not, it has been suggested that we write some middleware that runs the SQL before the view is processed. That might work, but I would feel more comfortable knowing that the query was absolutely guaranteed to run for every connection, even if more than one connection is opened for each view. Thanks! PS - before you tell me I should just hunt down the code that is keeping the connections from being closed - Never Fear! - we are doing that, but I would like to have this extra insurance against another 8 hour block of downtime
[ "You can specify a list of commands to send to MySQL when the connection is open, by setting the DATABASE_OPTIONS dictionary in settings.py. \n(Incidentally, note that Django doesn't open a new connection for every view.)\n" ]
[ 1 ]
[]
[]
[ "connection_string", "django", "python", "sql" ]
stackoverflow_0001577800_connection_string_django_python_sql.txt
Q: Releasing Python GIL while in C++ code I've got a library written in C++ which I wrap using SWIG and use in python. Generally there is one class with few methods. The problem is that calling these methods may be time consuming - they may hang my application (GIL is not released when calling these methods). So my question is: What is the simplest way to release GIL for these method calls? (I understand that if I used a C library I could wrap this with some additional C code, but here I use C++ and classes) A: Not having any idea what SWIG is I'll attempt an answer anyway :) Use something like this to release/acquire the GIL: class GILReleaser { GILReleaser() : save(PyEval_SaveThread()) {} ~GILReleaser() { PyEval_RestoreThread(save); } PyThreadState* save; }; And in the code-block of your choosing, utilize RAII to release/acquire GIL: { GILReleaser releaser; // ... Do stuff ... } A: The real problem is that SWIG is not documented well (I saw hints to use changelog for searching ;) ). Ok, I found out that I can do inline functions in SWIG and use macros to release/acquire GIL, it looks like this: %inline %{ void wrappedFunction(OriginalObject *o, <parameters>) { Py_BEGIN_ALLOW_THREADS o->originalFunction(<parameters>); Py_END_ALLOW_THREADS } %} This function is not present in original C++, but available in python module. This is (almost) exactly what I wanted. (what I would like is to wrap original method like python decorator does) A: You can use the same API call as for C. No difference. Include "python.h" and call the appoproate function. Also, see if SWIG doesn't have a typemap or something to indicate that the GIL shuold not be held for a specific function.
Releasing Python GIL while in C++ code
I've got a library written in C++ which I wrap using SWIG and use in python. Generally there is one class with few methods. The problem is that calling these methods may be time consuming - they may hang my application (GIL is not released when calling these methods). So my question is: What is the simplest way to release GIL for these method calls? (I understand that if I used a C library I could wrap this with some additional C code, but here I use C++ and classes)
[ "Not having any idea what SWIG is I'll attempt an answer anyway :)\nUse something like this to release/acquire the GIL:\nclass GILReleaser {\n GILReleaser() : save(PyEval_SaveThread()) {}\n\n ~GILReleaser() {\n PyEval_RestoreThread(save);\n }\n\n PyThreadState* save;\n};\n\nAnd in the code-block of your choosing, utilize RAII to release/acquire GIL:\n{\n GILReleaser releaser;\n // ... Do stuff ...\n}\n\n", "The real problem is that SWIG is not documented well (I saw hints to use changelog for searching ;) ). \nOk, I found out that I can do inline functions in SWIG and use macros to release/acquire GIL, it looks like this:\n%inline %{\n void wrappedFunction(OriginalObject *o, <parameters>) {\n Py_BEGIN_ALLOW_THREADS\n o->originalFunction(<parameters>);\n Py_END_ALLOW_THREADS\n}\n%}\n\nThis function is not present in original C++, but available in python module. This is (almost) exactly what I wanted. (what I would like is to wrap original method like python decorator does)\n", "You can use the same API call as for C. No difference. Include \"python.h\" and call the appoproate function.\nAlso, see if SWIG doesn't have a typemap or something to indicate that the GIL shuold not be held for a specific function.\n" ]
[ 9, 9, 0 ]
[]
[]
[ "c++", "gil", "python", "swig" ]
stackoverflow_0001576737_c++_gil_python_swig.txt
Q: How can I make Zenoss recognize skin changes? I'm writing a ZenPack for Zenoss which includes a new DataSource. The DataSource has a ToOne relationship with another persistent object and I'm trying to construct the user interface to allow a user to specify the value of this relationship. I've given the DataSource a factory_type_information attribute with an "immediate_view" key mapped to the name of a skin/template - "viewAgentScriptDataSource". In my ZenPack's skins directory, I created viewAgentScriptDataSource.pt. Zenoss seems to have liked this and now when I view an instance of the DataSource, I see a page based on viewAgentScriptDataSource.pt. However, after this first success, any edits I make to the skin/template file are ignored. I tried replacing the dummy content of the file with something more realistic and reloading the data source view. The dummy content still appears. I tried restarting Zenoss and reloading the view. The dummy content still appears. I tried deleting my ZenPack and re-installing it. The dummy content still appears. How do I get Zenoss to load the new contents of the skin file? A: The problem turned out to be that none of the template changes I made actually had any impact on the final page output. The changes were picked up, they just didn't matter.
How can I make Zenoss recognize skin changes?
I'm writing a ZenPack for Zenoss which includes a new DataSource. The DataSource has a ToOne relationship with another persistent object and I'm trying to construct the user interface to allow a user to specify the value of this relationship. I've given the DataSource a factory_type_information attribute with an "immediate_view" key mapped to the name of a skin/template - "viewAgentScriptDataSource". In my ZenPack's skins directory, I created viewAgentScriptDataSource.pt. Zenoss seems to have liked this and now when I view an instance of the DataSource, I see a page based on viewAgentScriptDataSource.pt. However, after this first success, any edits I make to the skin/template file are ignored. I tried replacing the dummy content of the file with something more realistic and reloading the data source view. The dummy content still appears. I tried restarting Zenoss and reloading the view. The dummy content still appears. I tried deleting my ZenPack and re-installing it. The dummy content still appears. How do I get Zenoss to load the new contents of the skin file?
[ "The problem turned out to be that none of the template changes I made actually had any impact on the final page output. The changes were picked up, they just didn't matter.\n" ]
[ 1 ]
[]
[]
[ "python", "zenoss", "zope" ]
stackoverflow_0001572661_python_zenoss_zope.txt
Q: Python Singletons - How do you get rid of (__del__) them in your testbench? Many thanks for the advice you have given me thus far. Using testbenches is something this forum has really shown me the light on and for that I am appreciative. My problem is that I am playing with a singleton and normally I won't del it, but in a testbench I will need to. So can anyone show me how to del the thing? I've started with a basic example and built it up into a testbench so I can see whats going on. Now I don't know how to get rid of it! Many thanks!! import sys import logging import unittest LOGLEVEL = logging.DEBUG class Singleton: """ A python singleton """ class __impl: """ Implementation of the singleton interface """ def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) def id(self): """ Test method, return singleton id """ return id(self) # storage for the instance reference __instance = None def __init__(self): """ Create singleton instance """ # Check whether we already have an instance if Singleton.__instance is None: # Create and remember instance Singleton.__instance = Singleton.__impl() # Store instance reference as the only member in the handle self.__dict__['_Singleton__instance'] = Singleton.__instance def __getattr__(self, attr): """ Delegate access to implementation """ return getattr(self.__instance, attr) def __setattr__(self, attr, value): """ Delegate access to implementation """ return setattr(self.__instance, attr, value) class A: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = Singleton() self.id = self.lowclass.id() self.log.debug("ID: %s" % self.id) class B: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = Singleton() self.id = self.lowclass.id() self.log.debug("ID: %s" % self.id) class ATests(unittest.TestCase): def testOne(self): a = A() aid = a.id b = B() bid = b.id self.assertEqual(a.id, b.id) # # How do I destroy this thing?? # del a del b a1 = A() a1id = a1.id self.assertNotEqual(a1id, aid) if __name__ == '__main__': # Set's up a basic logger logging.basicConfig( format="%(asctime)s %(levelname)-8s %(module)s %(funcName)s %(message)s", datefmt="%H:%M:%S", stream=sys.stderr ) log = logging.getLogger("") log.setLevel(LOGLEVEL) # suite = unittest.TestLoader().loadTestsFromTestCase(ATests) sys.exit(unittest.TextTestRunner(verbosity=LOGLEVEL).run(suite)) A: As Borg's author I obviously second @mjv's comment, but, with either Borg (aka "monostate") or Highlander (aka "singleton"), you need to add a "drop everything" method to support the tearDown in your test suite. Naming such method with a single leading underscore tells other parts of the sw to leave it alone, but tests are atypical beasts and often need to muck with such otherwise-internal attributes. So, for your specific case, class Singleton: ... def _drop(self): "Drop the instance (for testing purposes)." Singleton.__instance = None del self._Singleton__instance Similarly, for Borg, a _drop method would release and clear the shared dictionary and replace it with a brand new one. A: Considering you'll have many of those classes, I wouldn't exactly call them singletons. You just defer the attribute to a singleton class. It seems better to make sure the class actually is a singleton. The problem with your solution is that you would have to implement both a del method (which is fine) but also a reference-counter, which seems like a bad idea. :-) Here is a question with several implementations: Is there a simple, elegant way to define singletons? Which one is for you depends on what kind of singleton you want. One object per a certain value, but for any value? A set of predefined singletons? A proper singleton, ie, just one single object?
Python Singletons - How do you get rid of (__del__) them in your testbench?
Many thanks for the advice you have given me thus far. Using testbenches is something this forum has really shown me the light on and for that I am appreciative. My problem is that I am playing with a singleton and normally I won't del it, but in a testbench I will need to. So can anyone show me how to del the thing? I've started with a basic example and built it up into a testbench so I can see whats going on. Now I don't know how to get rid of it! Many thanks!! import sys import logging import unittest LOGLEVEL = logging.DEBUG class Singleton: """ A python singleton """ class __impl: """ Implementation of the singleton interface """ def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) def id(self): """ Test method, return singleton id """ return id(self) # storage for the instance reference __instance = None def __init__(self): """ Create singleton instance """ # Check whether we already have an instance if Singleton.__instance is None: # Create and remember instance Singleton.__instance = Singleton.__impl() # Store instance reference as the only member in the handle self.__dict__['_Singleton__instance'] = Singleton.__instance def __getattr__(self, attr): """ Delegate access to implementation """ return getattr(self.__instance, attr) def __setattr__(self, attr, value): """ Delegate access to implementation """ return setattr(self.__instance, attr, value) class A: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = Singleton() self.id = self.lowclass.id() self.log.debug("ID: %s" % self.id) class B: def __init__(self): self.log = logging.getLogger() self.log.debug("Init %s" % self.__class__.__name__) self.lowclass = Singleton() self.id = self.lowclass.id() self.log.debug("ID: %s" % self.id) class ATests(unittest.TestCase): def testOne(self): a = A() aid = a.id b = B() bid = b.id self.assertEqual(a.id, b.id) # # How do I destroy this thing?? # del a del b a1 = A() a1id = a1.id self.assertNotEqual(a1id, aid) if __name__ == '__main__': # Set's up a basic logger logging.basicConfig( format="%(asctime)s %(levelname)-8s %(module)s %(funcName)s %(message)s", datefmt="%H:%M:%S", stream=sys.stderr ) log = logging.getLogger("") log.setLevel(LOGLEVEL) # suite = unittest.TestLoader().loadTestsFromTestCase(ATests) sys.exit(unittest.TextTestRunner(verbosity=LOGLEVEL).run(suite))
[ "As Borg's author I obviously second @mjv's comment, but, with either Borg (aka \"monostate\") or Highlander (aka \"singleton\"), you need to add a \"drop everything\" method to support the tearDown in your test suite. Naming such method with a single leading underscore tells other parts of the sw to leave it alone, but tests are atypical beasts and often need to muck with such otherwise-internal attributes.\nSo, for your specific case,\nclass Singleton:\n ...\n def _drop(self):\n \"Drop the instance (for testing purposes).\"\n Singleton.__instance = None\n del self._Singleton__instance\n\nSimilarly, for Borg, a _drop method would release and clear the shared dictionary and replace it with a brand new one.\n", "Considering you'll have many of those classes, I wouldn't exactly call them singletons. You just defer the attribute to a singleton class. It seems better to make sure the class actually is a singleton.\nThe problem with your solution is that you would have to implement both a del method (which is fine) but also a reference-counter, which seems like a bad idea. :-)\nHere is a question with several implementations: Is there a simple, elegant way to define singletons?\nWhich one is for you depends on what kind of singleton you want. One object per a certain value, but for any value? A set of predefined singletons? A proper singleton, ie, just one single object?\n" ]
[ 8, 0 ]
[]
[]
[ "python", "singleton", "unit_testing" ]
stackoverflow_0001578566_python_singleton_unit_testing.txt
Q: Communication between Windows Client and Linux Server I want to provide my colleagues with an interface (using Windows Forms or WPF) to control the states of virtual machines (KVM based) on a linux host. On the command line of this server, I'm using a tool, called libvirt, which provides python bindings to access its functionality. What whould be the best pratice to remotely access several function like libvirt or reading logfiles on the server. I thought about a REST Full Webservice generated by Python. Are there other viable options to consider? Thanks, Henrik A: I'd develop an intranet web application, using any python web framework of choice. That way you don't have to develop/install software on your client. They just point the browser and it works. A: Proxmox VE is a complete solution to manage KVM (and OpenVZ) based virtual machines, including a comprehensive web console, so maybe you can get a full solution without developing anything? A: Because you are using a server-side tool that has Python bindings, you should give a serious look at PYRO which is a Python RPC library. http://pyro.sourceforge.net/ To use this you would also have to use Python on the client, but that shouldn't be a problem. If you haven't start writing your client, then you could do it all in IronPython. Or, if you need to add this to an already existing client, then you could still bind in either IronPython or CPython as an embedded scripting engine. For more on PYRO and Ironpython, see this wiki page http://www.razorvine.net/python/PyroAndIronpython
Communication between Windows Client and Linux Server
I want to provide my colleagues with an interface (using Windows Forms or WPF) to control the states of virtual machines (KVM based) on a linux host. On the command line of this server, I'm using a tool, called libvirt, which provides python bindings to access its functionality. What whould be the best pratice to remotely access several function like libvirt or reading logfiles on the server. I thought about a REST Full Webservice generated by Python. Are there other viable options to consider? Thanks, Henrik
[ "I'd develop an intranet web application, using any python web framework of choice.\nThat way you don't have to develop/install software on your client. They just point the browser and it works.\n", "Proxmox VE is a complete solution to manage KVM (and OpenVZ) based virtual machines, including a comprehensive web console, so maybe you can get a full solution without developing anything?\n", "Because you are using a server-side tool that has Python bindings, you should give a serious look at PYRO which is a Python RPC library. \nhttp://pyro.sourceforge.net/\nTo use this you would also have to use Python on the client, but that shouldn't be a problem. If you haven't start writing your client, then you could do it all in IronPython. Or, if you need to add this to an already existing client, then you could still bind in either IronPython or CPython as an embedded scripting engine. \nFor more on PYRO and Ironpython, see this wiki page http://www.razorvine.net/python/PyroAndIronpython\n" ]
[ 2, 1, 1 ]
[]
[]
[ "communication", "linux", "python", "windows" ]
stackoverflow_0001577804_communication_linux_python_windows.txt
Q: Python GUI Library for Windows/Gnome I need to create a desktop app that will work with Windows and Gnome(Ubuntu). I would like to use Python to do this. The GUI part of the app will be a single form with a message area and a couple of buttons. The list of GUI's for Python seems overwhelming. I am looking for something simple if possible, the main requirements is it must work with Gnome(2.26 and up) and Windows XP/Vista/7. A: You might want to check out wxPython. It's a mature project and should work on Windows and Linux (Gnome). A: PyGTK is a very popular GUI toolkit, but usually quite a bit easier to use on Linux than on Windows. A: Have you checked the extensive list of GUI libs for Python? For something simple I recommend, as does the list, EasyGUI. A: You can also try PyQt or PySide. Both are Python wrappers to Qt. PyQt is the original wrapper; PySide is a new project by Qt Development Frameworks/Nokia that has pretty much the same aims as PyQt, just with different licensing. PyQt is more mature, but licensing is more restrictive; PySide is quite new (in alpha/beta) but with more liberal licensing. However, for real information on licensing, check their site and preferably with a lawyer if it concerns you.
Python GUI Library for Windows/Gnome
I need to create a desktop app that will work with Windows and Gnome(Ubuntu). I would like to use Python to do this. The GUI part of the app will be a single form with a message area and a couple of buttons. The list of GUI's for Python seems overwhelming. I am looking for something simple if possible, the main requirements is it must work with Gnome(2.26 and up) and Windows XP/Vista/7.
[ "You might want to check out wxPython. It's a mature project and should work on Windows\nand Linux (Gnome).\n", "PyGTK is a very popular GUI toolkit, but usually quite a bit easier to use on Linux than on Windows.\n", "Have you checked the extensive list of GUI libs for Python? For something simple I recommend, as does the list, EasyGUI.\n", "You can also try PyQt or PySide. Both are Python wrappers to Qt. PyQt is the original wrapper; PySide is a new project by Qt Development Frameworks/Nokia that has pretty much the same aims as PyQt, just with different licensing. PyQt is more mature, but licensing is more restrictive; PySide is quite new (in alpha/beta) but with more liberal licensing. However, for real information on licensing, check their site and preferably with a lawyer if it concerns you.\n" ]
[ 4, 3, 2, 2 ]
[]
[]
[ "cross_platform", "python", "user_interface" ]
stackoverflow_0001577175_cross_platform_python_user_interface.txt
Q: Python: Extracting data from buffer with ctypes I am able to successfully call a function with ctypes in Python. I now have a buffer that is filled with Structures of data I want to extract. What is the best strategy for this? Anything else I should post? Function: class list(): def __init__(self): #[...] def getdirentries(self, path): self.load_c() self.fd = os.open(path, os.O_RDONLY) self.statinfo = os.fstat(self.fd) self.buffer = ctypes.create_string_buffer(self.statinfo.st_size) nbytes = self.statinfo.st_size transferred_bytes = self.libc.getdirentries( self.fd, ctypes.byref(self.buffer), nbytes, ctypes.byref(self.basep) ) #[...] Structure: class dirent(ctypes.Structure): _fields_ = [ ("d_fileno", ctypes.c_uint32), # /* file number of entry */ ("d_reclen", ctypes.c_uint16), # /* length of this record */ ("d_type", ctypes.c_uint8), # /* file type */ ("d_namlen", ctypes.c_uint8), # /* length of string in d_name */ ("d_name", ctypes.c_char * (MAXNAMELEN + 1) ) ] Some Output: Transferred bytes: 156 sizeof buffer: 272 Buffer: <ctypes.c_char_Array_272 object at 0x8c3f0> A: I wonder why you are using os.stat() instead of calling statinfo and os.path.walk() instead of calling getdirentries? Normally, when you have buffers of data that you want to pass in and out of C, you would use the struct modules pack and unpack methods to do this.
Python: Extracting data from buffer with ctypes
I am able to successfully call a function with ctypes in Python. I now have a buffer that is filled with Structures of data I want to extract. What is the best strategy for this? Anything else I should post? Function: class list(): def __init__(self): #[...] def getdirentries(self, path): self.load_c() self.fd = os.open(path, os.O_RDONLY) self.statinfo = os.fstat(self.fd) self.buffer = ctypes.create_string_buffer(self.statinfo.st_size) nbytes = self.statinfo.st_size transferred_bytes = self.libc.getdirentries( self.fd, ctypes.byref(self.buffer), nbytes, ctypes.byref(self.basep) ) #[...] Structure: class dirent(ctypes.Structure): _fields_ = [ ("d_fileno", ctypes.c_uint32), # /* file number of entry */ ("d_reclen", ctypes.c_uint16), # /* length of this record */ ("d_type", ctypes.c_uint8), # /* file type */ ("d_namlen", ctypes.c_uint8), # /* length of string in d_name */ ("d_name", ctypes.c_char * (MAXNAMELEN + 1) ) ] Some Output: Transferred bytes: 156 sizeof buffer: 272 Buffer: <ctypes.c_char_Array_272 object at 0x8c3f0>
[ "I wonder why you are using os.stat() instead of calling statinfo and os.path.walk() instead of calling getdirentries?\nNormally, when you have buffers of data that you want to pass in and out of C, you would use the struct modules pack and unpack methods to do this. \n" ]
[ 0 ]
[]
[]
[ "buffer", "ctypes", "extract", "python" ]
stackoverflow_0001578752_buffer_ctypes_extract_python.txt
Q: Where should I check state / throw exception? My situation is something like this: class AbstractClass: def __init__(self, property_a): self.property_a = property_a @property def some_value(self): """Code here uses property_a but not property_b to determine some_value""" @property def property_a(self): return self.property_a @property def property_b(self): """Has to be implemented in subclass.""" raise NotImplementedError class Concrete1(AbstractClass): """Code here including an implementation of property_b""" class Concrete2(AbstractClass): """Code here including an implementation of property_b""" There is also a condition that if property_b is less than property_a, then property_a is invalid and thus the result of some_value is also invalid. What I mean is this... if at any time during the object's lifetime, calling property_b would yield a number lower than calling property_a, there's a problem. However, property_b is not a field. It is determined dynamically based on n fields, where n >= 1. It is impossible to check this condition while setting property_b because property_b itself is never set. Really, setters are not anticipated to be used anywhere here. All fields are likely to be set in the constructors and then left alone. This means that property_a will be known in the constructor for AbstractClass and property_b only after evaluating the constructor for the concrete classes. <update> The fundamental problem is this: I need to check property_a for validity, but when property_a is set (the most intuitive place to check it), property_b is undefined. </update> I want to ensure that property_b is never less than property_a. How should I handle it? Check property_a against property_b in... AbstractClass.__init__. This is actually impossible because property_b hasn't been defined yet. AbstractClass.property_a. This seems problematic because I would be throwing an exception in a getter. Each concrete implementation of property_b. Not only would I be throwing an exception in a getter, I would be duplicating code. Also property_b does not logically depend on property_a. AbstractClass.some_value. This is still throwing an exception in a getter. Also, it is logically impossible for property_b to be less than property_a all the time, not just when trying to determine some_value. Further, if subclasses decide to add other properties that depend on property_a, they may forget to check it against property_b. Concrete setters for property_b. These don't exist. property_b is sometimes determined from a value set in the constructor, sometimes calculated from multiple values. Also, code duplication. Concrete class __init__ methods. Code duplication. Someone may forget. ??? UPDATE I think what is causing confusion is that property_b is not simply a field. property_b relies on calculations. It is really more a function than a property, if it helps to think about it that way. A: Add a method _validate_b(self, b) (single leading underscore to indicate "protected", i.e., callable from derived classes but not by general client code) that validates the value of b (which only subclasses know) vs the value of a (which the abstract superclass does know). Make subclasses responsible for calling the validation method whenever they're doing something that could change their internal value for b. In your very general case, the superclass cannot identify when b's value changes; since the responsibility of that change lies entirely with the subclasses, then the responsibility for triggering validation must also be with them (the superclass can perform validation, given the proposed new value of b, but it cannot know when validity must be checked). So, document that clearly. If most subclasses fall into broad categories in terms of the strategies they use to affect their b's values, you can factor that out into either intermediate abstract classes (inheriting from the general one and specializing the general approach to "determining b", including the validation call), or (better, if feasible) some form of Strategy design pattern (typically implemented via either composition, or mix-in inheritance). But this has more to do with convenience (for concrete-subclass authors) than with "guaranteeing correctness", since a given concrete subclass might bypass such mechanisms. If you need to, you can offer a "debug/test mode" where properties are validated redundantly on access (probably not advisable in production use, but for debugging and testing it would help catch errant subclasses that are not properly calling validation methods). A: The golden rule is to "encapsulate" property_b so that the subclass provides part of the implementation, but not all of it. class AbstractClass: def __init__(self, property_a): self._value_of_a = property_a @property def get_b( self ): self.validate_a() self._value_of_b = self.compute_b() self.validate_other_things() return self._value_of_b def compute_b( self ): raise NotImplementedError It's hard to say precisely what's supposed to happen when you have two classes and you're asking about allocation of responsibility. It appears that you want the superclass to be responsible for some aspect of the relationship between a and b It appears that you want the the subclass to be responsible for some other aspect of computing b, and not responsible for the relationship. If this is what you want, then your design must assign responsibility by decomposing things into the part the superclass is responsible for and the part the subclass is responsible for. A: I suggest that you don't raise raise NotImplementedError but call a method instead which raises this error. Subclasses then have to override that method (instead of property_b). In property_b, you call the method and then verify the result. Rationale: You should check the value as soon as possible (which is when someone changes it). Otherwise, an illegal value could be set and cause a problem much later in the code when no one can say how it got there. Alternatively, you could store the value and a stack trace. When the value is used, you can then check the value and print the original stack trace as "value was changed here".
Where should I check state / throw exception?
My situation is something like this: class AbstractClass: def __init__(self, property_a): self.property_a = property_a @property def some_value(self): """Code here uses property_a but not property_b to determine some_value""" @property def property_a(self): return self.property_a @property def property_b(self): """Has to be implemented in subclass.""" raise NotImplementedError class Concrete1(AbstractClass): """Code here including an implementation of property_b""" class Concrete2(AbstractClass): """Code here including an implementation of property_b""" There is also a condition that if property_b is less than property_a, then property_a is invalid and thus the result of some_value is also invalid. What I mean is this... if at any time during the object's lifetime, calling property_b would yield a number lower than calling property_a, there's a problem. However, property_b is not a field. It is determined dynamically based on n fields, where n >= 1. It is impossible to check this condition while setting property_b because property_b itself is never set. Really, setters are not anticipated to be used anywhere here. All fields are likely to be set in the constructors and then left alone. This means that property_a will be known in the constructor for AbstractClass and property_b only after evaluating the constructor for the concrete classes. <update> The fundamental problem is this: I need to check property_a for validity, but when property_a is set (the most intuitive place to check it), property_b is undefined. </update> I want to ensure that property_b is never less than property_a. How should I handle it? Check property_a against property_b in... AbstractClass.__init__. This is actually impossible because property_b hasn't been defined yet. AbstractClass.property_a. This seems problematic because I would be throwing an exception in a getter. Each concrete implementation of property_b. Not only would I be throwing an exception in a getter, I would be duplicating code. Also property_b does not logically depend on property_a. AbstractClass.some_value. This is still throwing an exception in a getter. Also, it is logically impossible for property_b to be less than property_a all the time, not just when trying to determine some_value. Further, if subclasses decide to add other properties that depend on property_a, they may forget to check it against property_b. Concrete setters for property_b. These don't exist. property_b is sometimes determined from a value set in the constructor, sometimes calculated from multiple values. Also, code duplication. Concrete class __init__ methods. Code duplication. Someone may forget. ??? UPDATE I think what is causing confusion is that property_b is not simply a field. property_b relies on calculations. It is really more a function than a property, if it helps to think about it that way.
[ "Add a method _validate_b(self, b) (single leading underscore to indicate \"protected\", i.e., callable from derived classes but not by general client code) that validates the value of b (which only subclasses know) vs the value of a (which the abstract superclass does know).\nMake subclasses responsible for calling the validation method whenever they're doing something that could change their internal value for b. In your very general case, the superclass cannot identify when b's value changes; since the responsibility of that change lies entirely with the subclasses, then the responsibility for triggering validation must also be with them (the superclass can perform validation, given the proposed new value of b, but it cannot know when validity must be checked). So, document that clearly.\nIf most subclasses fall into broad categories in terms of the strategies they use to affect their b's values, you can factor that out into either intermediate abstract classes (inheriting from the general one and specializing the general approach to \"determining b\", including the validation call), or (better, if feasible) some form of Strategy design pattern (typically implemented via either composition, or mix-in inheritance). But this has more to do with convenience (for concrete-subclass authors) than with \"guaranteeing correctness\", since a given concrete subclass might bypass such mechanisms.\nIf you need to, you can offer a \"debug/test mode\" where properties are validated redundantly on access (probably not advisable in production use, but for debugging and testing it would help catch errant subclasses that are not properly calling validation methods).\n", "The golden rule is to \"encapsulate\" property_b so that the subclass provides part of the implementation, but not all of it.\nclass AbstractClass:\n def __init__(self, property_a):\n self._value_of_a = property_a\n\n @property\n def get_b( self ):\n self.validate_a()\n self._value_of_b = self.compute_b()\n self.validate_other_things()\n return self._value_of_b\n\n def compute_b( self ):\n raise NotImplementedError\n\nIt's hard to say precisely what's supposed to happen when you have two classes and you're asking about allocation of responsibility. \nIt appears that you want the superclass to be responsible for some aspect of the relationship between a and b \nIt appears that you want the the subclass to be responsible for some other aspect of computing b, and not responsible for the relationship.\nIf this is what you want, then your design must assign responsibility by decomposing things into the part the superclass is responsible for and the part the subclass is responsible for.\n", "I suggest that you don't raise raise NotImplementedError but call a method instead which raises this error. Subclasses then have to override that method (instead of property_b). In property_b, you call the method and then verify the result.\nRationale: You should check the value as soon as possible (which is when someone changes it). Otherwise, an illegal value could be set and cause a problem much later in the code when no one can say how it got there.\nAlternatively, you could store the value and a stack trace. When the value is used, you can then check the value and print the original stack trace as \"value was changed here\".\n" ]
[ 3, 1, 0 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0001578395_exception_python.txt
Q: Python Access to BaseRequestHandler My code basically needs to start up a simple chat server with a client. Where the server and the client can talk back and forth to each other. I've gotten everything to be implemented correctly, but I can't figure out how to shut down the server whenever I'm done. (I know it's ss.shutdown()). I'm wanting to end right now based on a keyword shared between the two (something like "bye"), but I don't know if I can somehow send a message to my SocketServer from BaseRequestHandler to shutdown() whenever it receives the message. Eventually, my goal is to incorporate Tkinter to make a GUI, but I wanted to get everything else to work first, and this is my first time dealing with sockets in Python. from sys import argv, stderr from threading import Thread import socket import SocketServer import threading import sys class ThreadedRecv(Thread): def __init__(self,socket): Thread.__init__(self) self.__socket = socket self.__message = '' self.__done = False def recv(self): while self.__message.strip() != "bye" and not self.getStatus(): self.__message = self.__socket.recv(4096) print 'received',self.__message self.setStatus(True) def run(self): self.recv() def setStatus(self,status): self.__done = status def getStatus(self): return self.__done class ThreadedSend(Thread): def __init__(self,socket): Thread.__init__(self) self.__socket = socket self.__message = '' self.__done = False def send(self): while self.__message != "bye" and not self.getStatus(): self.__message = raw_input() self.__socket.send(self.__message) self.setStatus(True) def run(self): self.send() def setStatus(self,status): self.__done = status def getStatus(self): return self.__done class HostException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class EchoServer(SocketServer.BaseRequestHandler): def setup(self): print self.client_address, 'is connected!' self.request.send('Hello ' + str(self.client_address) + '\n') self.__done = False def handle(self): sender = ThreadedSend(self.request) recver = ThreadedRecv(self.request) sender.start() recver.start() while 1: if recver.getStatus(): sender.setStatus(True) break if sender.getStatus(): recver.setStatus(True) break def finish(self): print self.client_address, 'disconnected' self.request.send('bye client %s\n' % str(self.client_address)) self.setDone(True) def setDone(self,done): self.__done = done def getDone(self): return self.__done def setup(arg1, arg2, arg3): server = False defaultPort,defaultHost = 2358,"localhost" hosts = [] port = defaultPort serverNames = ["TRUE","SERVER","S","YES"] arg1 = arg1.upper() arg2 = arg2.upper() arg3 = arg3.upper() if arg1 in serverNames or arg2 in serverNames or arg3 in serverNames: server = True try: port = int(arg1) if arg2 != '': hosts.append(arg2) except ValueError: if arg1 != '': hosts.append(arg1) try: port = int(arg2) if arg3 != '': hosts.append(arg3) except ValueError: if arg2 != '': hosts.append(arg2) try: port = int(arg3) except ValueError: if arg3 != '': hosts.append(arg3) port = defaultPort for sn in serverNames: if sn in hosts: hosts.remove(sn) try: if len(hosts) != 1: raise HostException("Either more than one or no host "+ \ "declared. Setting host to localhost.") except HostException as error: print error.value, "Setting hosts to default" return (server,defaultHost,port) return (server,hosts[0].lower(),port) def main(): bufsize = 4096 while len(argv[1:4]) < 3: argv.append('') settings = setup(*argv[1:4]) connections = (settings[1],settings[2]) print connections if not settings[0]: try: mySocket = socket.socket(socket.AF_INET,\ socket.SOCK_STREAM) except socket.error, msg: stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(1) try: mySocket.connect(connections) except socket.error, msg: stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(2) message = "" print "Enter a message to send to the server. "+\ "Enter \"bye\" to quit." sender = ThreadedSend(mySocket) recver = ThreadedRecv(mySocket) sender.start() recver.start() while 1: if sender.getStatus(): recver.setStatus(True) break if recver.getStatus(): sender.setStatus(True) break else: xserverhandler = EchoServer serversocket = SocketServer.ThreadedTCPServer(\ connections,xserverhandler) server_thread = Thread(target = serversocket.serve_forever) server_thread.setDaemon(True) server_thread.start() # I would like to shut down this server whenever # I get done talking to it. """while 1: if xserverhandler.getDone(): print 'This is now true!' serversocket.shutdown() break""" if __name__ == '__main__': main() Yeah, I know setup() is a terrible function right now with the try's and catches, but it works for now, so I was going to fix it later. My question is basically: How can I get the server to actually end based on a message that it receives? If possible, is there a way to access the Request Handler after it's started? A: Please fix your code so it works, and include some way to use it. You need to add class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass since SocketServer doesn't actually include that class (at least not in my version of 2.6 nor 2.7). Instead, it's an example from the SocketServer definition. Please include an example of how to start/use the code. In this case to start the server you need to do: ss.py SERVER localhost 8001 and the client as ss.py localhost 8001 If you do that then you can't do server_thread.setDaemon(True) because there are no other threads running, which means the server will exit immediately. Once that's done the solution is to add a call (or two) to self.server.shutdown() insdie of your EchoServer.handle method, like: while 1: if recver.getStatus(): sender.setStatus(True) self.server.shutdown() break However, I can't get that to work, and I think it's because I inherited things wrong, or guessed wrong in what you did. What you should do is search for someone else who has done a chat server in Python. Using Google I found http://www.slideshare.net/didip/socket-programming-in-python and there are certainly others. Also, if you are going to mix GUI and threaded programming then you should look into examples based on that. There are a number of hits when I searched for "tkinter chat". Also, you might want to look into twisted, which has solved a lot of these problems already. What problems? Well, for example, you likely want an SO_REUSEADDR socket option. A: Request handler object is created for each new request. So you have to store "done" flag in server, not handler. Something like the following: class EchoServer(SocketServer.BaseRequestHandler): ... def setDone(self): self.server.setDone() # or even better directly self.server.shutdown()
Python Access to BaseRequestHandler
My code basically needs to start up a simple chat server with a client. Where the server and the client can talk back and forth to each other. I've gotten everything to be implemented correctly, but I can't figure out how to shut down the server whenever I'm done. (I know it's ss.shutdown()). I'm wanting to end right now based on a keyword shared between the two (something like "bye"), but I don't know if I can somehow send a message to my SocketServer from BaseRequestHandler to shutdown() whenever it receives the message. Eventually, my goal is to incorporate Tkinter to make a GUI, but I wanted to get everything else to work first, and this is my first time dealing with sockets in Python. from sys import argv, stderr from threading import Thread import socket import SocketServer import threading import sys class ThreadedRecv(Thread): def __init__(self,socket): Thread.__init__(self) self.__socket = socket self.__message = '' self.__done = False def recv(self): while self.__message.strip() != "bye" and not self.getStatus(): self.__message = self.__socket.recv(4096) print 'received',self.__message self.setStatus(True) def run(self): self.recv() def setStatus(self,status): self.__done = status def getStatus(self): return self.__done class ThreadedSend(Thread): def __init__(self,socket): Thread.__init__(self) self.__socket = socket self.__message = '' self.__done = False def send(self): while self.__message != "bye" and not self.getStatus(): self.__message = raw_input() self.__socket.send(self.__message) self.setStatus(True) def run(self): self.send() def setStatus(self,status): self.__done = status def getStatus(self): return self.__done class HostException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class EchoServer(SocketServer.BaseRequestHandler): def setup(self): print self.client_address, 'is connected!' self.request.send('Hello ' + str(self.client_address) + '\n') self.__done = False def handle(self): sender = ThreadedSend(self.request) recver = ThreadedRecv(self.request) sender.start() recver.start() while 1: if recver.getStatus(): sender.setStatus(True) break if sender.getStatus(): recver.setStatus(True) break def finish(self): print self.client_address, 'disconnected' self.request.send('bye client %s\n' % str(self.client_address)) self.setDone(True) def setDone(self,done): self.__done = done def getDone(self): return self.__done def setup(arg1, arg2, arg3): server = False defaultPort,defaultHost = 2358,"localhost" hosts = [] port = defaultPort serverNames = ["TRUE","SERVER","S","YES"] arg1 = arg1.upper() arg2 = arg2.upper() arg3 = arg3.upper() if arg1 in serverNames or arg2 in serverNames or arg3 in serverNames: server = True try: port = int(arg1) if arg2 != '': hosts.append(arg2) except ValueError: if arg1 != '': hosts.append(arg1) try: port = int(arg2) if arg3 != '': hosts.append(arg3) except ValueError: if arg2 != '': hosts.append(arg2) try: port = int(arg3) except ValueError: if arg3 != '': hosts.append(arg3) port = defaultPort for sn in serverNames: if sn in hosts: hosts.remove(sn) try: if len(hosts) != 1: raise HostException("Either more than one or no host "+ \ "declared. Setting host to localhost.") except HostException as error: print error.value, "Setting hosts to default" return (server,defaultHost,port) return (server,hosts[0].lower(),port) def main(): bufsize = 4096 while len(argv[1:4]) < 3: argv.append('') settings = setup(*argv[1:4]) connections = (settings[1],settings[2]) print connections if not settings[0]: try: mySocket = socket.socket(socket.AF_INET,\ socket.SOCK_STREAM) except socket.error, msg: stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(1) try: mySocket.connect(connections) except socket.error, msg: stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(2) message = "" print "Enter a message to send to the server. "+\ "Enter \"bye\" to quit." sender = ThreadedSend(mySocket) recver = ThreadedRecv(mySocket) sender.start() recver.start() while 1: if sender.getStatus(): recver.setStatus(True) break if recver.getStatus(): sender.setStatus(True) break else: xserverhandler = EchoServer serversocket = SocketServer.ThreadedTCPServer(\ connections,xserverhandler) server_thread = Thread(target = serversocket.serve_forever) server_thread.setDaemon(True) server_thread.start() # I would like to shut down this server whenever # I get done talking to it. """while 1: if xserverhandler.getDone(): print 'This is now true!' serversocket.shutdown() break""" if __name__ == '__main__': main() Yeah, I know setup() is a terrible function right now with the try's and catches, but it works for now, so I was going to fix it later. My question is basically: How can I get the server to actually end based on a message that it receives? If possible, is there a way to access the Request Handler after it's started?
[ "Please fix your code so it works, and include some way to use it. You need to add\nclass ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):\n pass\n\nsince SocketServer doesn't actually include that class (at least not in my version of 2.6 nor 2.7). Instead, it's an example from the SocketServer definition.\nPlease include an example of how to start/use the code. In this case to start the server you need to do:\nss.py SERVER localhost 8001\n\nand the client as\nss.py localhost 8001\n\nIf you do that then you can't do server_thread.setDaemon(True) because there are no other threads running, which means the server will exit immediately.\nOnce that's done the solution is to add a call (or two) to self.server.shutdown() insdie of your EchoServer.handle method, like:\n while 1:\n if recver.getStatus():\n sender.setStatus(True)\n self.server.shutdown()\n break\n\nHowever, I can't get that to work, and I think it's because I inherited things wrong, or guessed wrong in what you did.\nWhat you should do is search for someone else who has done a chat server in Python. Using Google I found http://www.slideshare.net/didip/socket-programming-in-python and there are certainly others.\nAlso, if you are going to mix GUI and threaded programming then you should look into examples based on that. There are a number of hits when I searched for \"tkinter chat\". Also, you might want to look into twisted, which has solved a lot of these problems already.\nWhat problems? Well, for example, you likely want an SO_REUSEADDR socket option.\n", "Request handler object is created for each new request. So you have to store \"done\" flag in server, not handler. Something like the following:\nclass EchoServer(SocketServer.BaseRequestHandler):\n ...\n def setDone(self):\n self.server.setDone() # or even better directly self.server.shutdown()\n\n" ]
[ 2, 1 ]
[]
[]
[ "python", "requesthandler", "serversocket", "sockets", "tcp" ]
stackoverflow_0001578932_python_requesthandler_serversocket_sockets_tcp.txt
Q: py2exe'd version of GTK app can't read png files I'm working on making a py2exe version of my app. Py2exe fails at copying some modules in. My original app loads .png files fine, but the exe version does not: Traceback (most recent call last): File "app.py", line 1, in <module> from gui.main import run File "gui\main.pyc", line 14, in <module> File "gui\controllers.pyc", line 10, in <module> File "gui\utils\images.pyc", line 78, in <module> ☺ File "gui\utils\images.pyc", line 70, in GTK_get_pixbuf ☺§☺▲☻ File "gui\utils\images.pyc", line 38, in PIL_to_pixbuf gobject.GError: Image type 'png' is not supported Any idea what I should force py2exe to include? A: This is a known problem with PIL and py2exe PIL (python image library) imports its plugins dynamically which py2exe doesn't pick up on, so it doesn't include the plugins in the .exe file. The fix (hopefully!) is to import the drivers explicitly like this in one of your .py files import Image import PngImagePlugin Image._initialized=2 That will mean that py2exe will definitely include the plugin. The Image._initialized bit stops PIL scanning for more plugins. Here are the docs from the py2exe wiki explaining this in full A: What platform is this? Lately I think they improved the png support on windows, so the version of pygtk you're using is pertinent also. http://aruiz.typepad.com/siliconisland/2008/02/goodbye-zlib-li.html A: Make sure you bundle the loaders when you install your application. Py2exe won't know about these, but they are a needed part of GTK, and live where the rest of the GTK "data" files live. From http://unpythonic.blogspot.com/2007/07/pygtk-py2exe-and-inno-setup-for-single.html It is not sufficient to just make py2exe pull in the GTK DLLs for packaging (which it does pretty successfully). GTK also requires a number of data files which include themes, translations etc. These will need to be manually copied into the dist directory so that the application can find them when being run. If you look inside your GTK runtime directory (usually something like c:\GTK) you will find the directories: share, etc, lib. You will need to copy all of these into the dist directory after running py2exe. Copyright retained.
py2exe'd version of GTK app can't read png files
I'm working on making a py2exe version of my app. Py2exe fails at copying some modules in. My original app loads .png files fine, but the exe version does not: Traceback (most recent call last): File "app.py", line 1, in <module> from gui.main import run File "gui\main.pyc", line 14, in <module> File "gui\controllers.pyc", line 10, in <module> File "gui\utils\images.pyc", line 78, in <module> ☺ File "gui\utils\images.pyc", line 70, in GTK_get_pixbuf ☺§☺▲☻ File "gui\utils\images.pyc", line 38, in PIL_to_pixbuf gobject.GError: Image type 'png' is not supported Any idea what I should force py2exe to include?
[ "This is a known problem with PIL and py2exe\nPIL (python image library) imports its plugins dynamically which py2exe doesn't pick up on, so it doesn't include the plugins in the .exe file.\nThe fix (hopefully!) is to import the drivers explicitly like this in one of your .py files\nimport Image\nimport PngImagePlugin\nImage._initialized=2\n\nThat will mean that py2exe will definitely include the plugin. The Image._initialized bit stops PIL scanning for more plugins.\nHere are the docs from the py2exe wiki explaining this in full\n", "What platform is this?\nLately I think they improved the png support on windows,\nso the version of pygtk you're using is pertinent also.\nhttp://aruiz.typepad.com/siliconisland/2008/02/goodbye-zlib-li.html\n", "Make sure you bundle the loaders when you install your application. Py2exe won't know about these, but they are a needed part of GTK, and live where the rest of the GTK \"data\" files live.\nFrom http://unpythonic.blogspot.com/2007/07/pygtk-py2exe-and-inno-setup-for-single.html\n\nIt is not sufficient to just make\n py2exe pull in the GTK DLLs for\n packaging (which it does pretty\n successfully). GTK also requires a\n number of data files which include\n themes, translations etc. These will\n need to be manually copied into the\n dist directory so that the application\n can find them when being run.\nIf you look inside your GTK runtime\n directory (usually something like\n c:\\GTK) you will find the\n directories: share, etc, lib. You will\n need to copy all of these into the\n dist directory after running py2exe.\n\nCopyright retained.\n" ]
[ 4, 2, 2 ]
[]
[]
[ "gtk", "image", "py2exe", "pygtk", "python" ]
stackoverflow_0001511916_gtk_image_py2exe_pygtk_python.txt
Q: numpy.extract and numpy.any functions, is it possible to make it simpler way? If there is any possibility to make this code simpler, I'd really appreciate it! I am trying to get rid of rows with zeros. The first column is date. If all other columns are zero, they have to be deleted. Number of columns varies. import numpy as np condition = [ np.any( list(x)[1:] ) for x in r] r = np.extract( condition, r ) numpy.extract docs A: You can avoid the list comprehension and instead use fancy indexing: #!/usr/bin/env python import numpy as np import datetime r=np.array([(datetime.date(2000,1,1),0,1), (datetime.date(2000,1,1),1,1), (datetime.date(2000,1,1),1,0), (datetime.date(2000,1,1),0,0), ]) r=r[r[:,1:].any(axis=1)] print(r) # [[2000-01-01 0 1] # [2000-01-01 1 1] # [2000-01-01 1 0] if r is an ndarray, then r[:,1:] is a view with the first column removed. r[:,1:].any(axis=1) is a boolean array, which you can then use as a "fancy index"
numpy.extract and numpy.any functions, is it possible to make it simpler way?
If there is any possibility to make this code simpler, I'd really appreciate it! I am trying to get rid of rows with zeros. The first column is date. If all other columns are zero, they have to be deleted. Number of columns varies. import numpy as np condition = [ np.any( list(x)[1:] ) for x in r] r = np.extract( condition, r ) numpy.extract docs
[ "You can avoid the list comprehension and instead use fancy indexing:\n#!/usr/bin/env python\nimport numpy as np\nimport datetime\nr=np.array([(datetime.date(2000,1,1),0,1),\n (datetime.date(2000,1,1),1,1),\n (datetime.date(2000,1,1),1,0),\n (datetime.date(2000,1,1),0,0), \n ])\nr=r[r[:,1:].any(axis=1)]\nprint(r)\n# [[2000-01-01 0 1]\n# [2000-01-01 1 1]\n# [2000-01-01 1 0]\n\nif r is an ndarray, then\nr[:,1:] is a view with the first column removed.\nr[:,1:].any(axis=1) is a boolean array, which you can then use as a \"fancy index\"\n" ]
[ 4 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001579218_numpy_python.txt
Q: Running Tests From a Module I am attempting to run some unit tests in python from what I believe is a module. I have a directory structure like TestSuite.py UnitTests |__init__.py |TestConvertStringToNumber.py In testsuite.py I have import unittest import UnitTests class TestSuite: def __init__(self): pass print "Starting testting" suite = unittest.TestLoader().loadTestsFromModule(UnitTests) unittest.TextTestRunner(verbosity=1).run(suite) Which looks to kick off the testing okay but it doesn't pick up any of the test in TestConvertNumberToString.py. In that class I have a set of functions which start with 'test'. What should I be doing such that running python TestSuite.py actually kicks off all of my tests in UnitTests? A: Here is some code which will run all the unit tests in a directory: #!/usr/bin/env python import unittest import sys import os unit_dir = sys.argv[1] if len(sys.argv) > 1 else '.' os.chdir(unit_dir) suite = unittest.TestSuite() for filename in os.listdir('.'): if filename.endswith('.py') and filename.startswith('test_'): modname = filename[:-2] module = __import__(modname) suite.addTest(unittest.TestLoader().loadTestsFromModule(module)) unittest.TextTestRunner(verbosity=2).run(suite) If you call it testsuite.py, then you would run it like this: testsuite.py UnitTests A: Using Twisted's "trial" test runner, you can get rid of TestSuite.py, and just do: $ trial UnitTests.TestConvertStringToNumber on the command line; or, better yet, just $ trial UnitTests to discover and run all tests in the package.
Running Tests From a Module
I am attempting to run some unit tests in python from what I believe is a module. I have a directory structure like TestSuite.py UnitTests |__init__.py |TestConvertStringToNumber.py In testsuite.py I have import unittest import UnitTests class TestSuite: def __init__(self): pass print "Starting testting" suite = unittest.TestLoader().loadTestsFromModule(UnitTests) unittest.TextTestRunner(verbosity=1).run(suite) Which looks to kick off the testing okay but it doesn't pick up any of the test in TestConvertNumberToString.py. In that class I have a set of functions which start with 'test'. What should I be doing such that running python TestSuite.py actually kicks off all of my tests in UnitTests?
[ "Here is some code which will run all the unit tests in a directory:\n#!/usr/bin/env python\nimport unittest\nimport sys\nimport os\n\nunit_dir = sys.argv[1] if len(sys.argv) > 1 else '.'\nos.chdir(unit_dir)\nsuite = unittest.TestSuite()\nfor filename in os.listdir('.'):\n if filename.endswith('.py') and filename.startswith('test_'):\n modname = filename[:-2]\n module = __import__(modname)\n suite.addTest(unittest.TestLoader().loadTestsFromModule(module))\n\nunittest.TextTestRunner(verbosity=2).run(suite)\n\nIf you call it testsuite.py, then you would run it like this:\ntestsuite.py UnitTests\n\n", "Using Twisted's \"trial\" test runner, you can get rid of TestSuite.py, and just do:\n$ trial UnitTests.TestConvertStringToNumber\n\non the command line; or, better yet, just\n$ trial UnitTests\n\nto discover and run all tests in the package.\n" ]
[ 4, 0 ]
[]
[]
[ "import", "python", "python_unittest", "tdd", "unit_testing" ]
stackoverflow_0001579350_import_python_python_unittest_tdd_unit_testing.txt
Q: How can I get all days between two days? I need all the weekdays between two days. Example: Wednesday - Friday = Wednesday, Thursday, Friday 3 - 5 = 3, 4, 5 Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday 6 - 2 = 6, 7, 1, 2 I'm pretty sure there is a clever algorithm out there to solve this. The only algorithms I can think of use either a loop or an if statement. There has to be an elegant way to solve this. I use the numbers 1-7 for the weekdays, but 0-6 is fine too. The best I could come up with: def between(d1, d2): alldays = [0,1,2,3,4,5,6,0,1,2,3,4,5,6] # or range(7) * 2 offset = 8 if d1 > d2 else 1 return alldays[d1:d2 + offset] between(0, 4) # [0,1,2,3,4] between(5,2) # [5,6,0,1,2] A: >>> def weekdays_between(s, e): ... return [n % 7 for n in range(s, e + (1 if e > s else 8))] ... >>> weekdays_between(2, 4) [2, 3, 4] >>> weekdays_between(5, 1) [5, 6, 0, 1] It's a bit more complex if you have to convert from/to actual days. >>> days = 'Mon Tue Wed Thu Fri Sat Sun'.split() >>> days_1 = {d: n for n, d in enumerate(days)} >>> def weekdays_between(s, e): ... s, e = days_1[s], days_1[e] ... return [days[n % 7] for n in range(s, e + (1 if e > s else 8))] ... >>> weekdays_between('Wed', 'Fri') ['Wed', 'Thu', 'Fri'] >>> weekdays_between('Sat', 'Tue') ['Sat', 'Sun', 'Mon', 'Tue'] A: How about (in pseudo code): weekday[] = {"Mon" .. "Sun"} for(i = wkday_start; (i % 7) != wkday_end; i = (i+1) % 7) printf("%s ", weekday[i]); It works like a circular buffer, wkday_start being the index to start at (0-based), wkday_end being the end index. Hope this helps George. A: Building on the excellent answer from Stephan202, you can generalize the concept of a circular slice. >>> def circular_slice(r, s, e): ... return [r[n % len(r)] for n in range(s, e + (1 if e>s else len(r)+1))] ... >>> circular_slice(range(0,7), 2, 4) [2, 3, 4] >>> circular_slice(range(0,7), 5, 1) [5, 6, 0, 1] >>> circular_slice('Mon Tue Wed Thu Fri Sat Sun'.split(), 5, 1) ['Sat', 'Sun', 'Mon', 'Tue'] A: The solutions provided already answer the question, but I want to suggest something extra. I don't know what you're doing, but maybe you want the actual dates instead? >>> from datetime import timedelta, date >>> from dateutil.rrule import rrule, DAILY >>> today = date(2009, 10, 13) # A tuesday >>> week = today - timedelta(days=6) >>> list(rrule(DAILY, byweekday=xrange(5), dtstart=week, until=today)) [datetime.datetime(2009, 10, 7, 0, 0), datetime.datetime(2009, 10, 8, 0, 0), datetime.datetime(2009, 10, 9, 0, 0), datetime.datetime(2009, 10, 12, 0, 0), datetime.datetime(2009, 10, 13, 0, 0)] That uses the excellent python-dateutil module. A: Use the calendar module for your list of day names: import calendar def intervening_days(day1, day2): weektest = list(calendar.day_name)*2 d1 = weektest.index(day1) d2 = weektest.index(day2,d1+1) return weektest[d1:d2+1] print intervening_days("Monday","Sunday") print intervening_days("Monday","Tuesday") print intervening_days("Thursday","Tuesday") print intervening_days("Monday","Monday") Prints: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] ['Monday', 'Tuesday'] ['Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday'] ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday'] If you don't want Monday-to-Monday to return a full week of days, change the determination of d2 to d2 = weektest.index(day2,d1). A: You asked for an algorithm, and I understand that should be language independent; however, following code works using C# and LINQ expressions: DayOfWeek start = DayOfWeek.Wednesday; DayOfWeek end = DayOfWeek.Friday; IEnumerable<DayOfWeek> interval = Enum.GetValues(typeof(DayOfWeek)).OfType<DayOfWeek>() .Where(d => d >= start && d <= end); Console.WriteLine( String.Join(", ", interval.Select(d => d.ToString()).ToArray())); Probably, using any language, your should attribute values to each day (Sunday=0 and so on) and look for all values which matches your desired interval. A: The following code returns 1 for Monday - Monday. bool isWeekday(int d) { return d >= 1 && d <= 5; } int f(int d1, int d2) { int res = isWeekday(d1) ? 1 : 0; return d1 == d2 ? res : res + f(d1 % 7 + 1, d2); }
How can I get all days between two days?
I need all the weekdays between two days. Example: Wednesday - Friday = Wednesday, Thursday, Friday 3 - 5 = 3, 4, 5 Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday 6 - 2 = 6, 7, 1, 2 I'm pretty sure there is a clever algorithm out there to solve this. The only algorithms I can think of use either a loop or an if statement. There has to be an elegant way to solve this. I use the numbers 1-7 for the weekdays, but 0-6 is fine too. The best I could come up with: def between(d1, d2): alldays = [0,1,2,3,4,5,6,0,1,2,3,4,5,6] # or range(7) * 2 offset = 8 if d1 > d2 else 1 return alldays[d1:d2 + offset] between(0, 4) # [0,1,2,3,4] between(5,2) # [5,6,0,1,2]
[ ">>> def weekdays_between(s, e):\n... return [n % 7 for n in range(s, e + (1 if e > s else 8))]\n... \n>>> weekdays_between(2, 4)\n[2, 3, 4]\n>>> weekdays_between(5, 1)\n[5, 6, 0, 1]\n\nIt's a bit more complex if you have to convert from/to actual days.\n>>> days = 'Mon Tue Wed Thu Fri Sat Sun'.split()\n>>> days_1 = {d: n for n, d in enumerate(days)}\n>>> def weekdays_between(s, e): \n... s, e = days_1[s], days_1[e]\n... return [days[n % 7] for n in range(s, e + (1 if e > s else 8))]\n... \n>>> weekdays_between('Wed', 'Fri')\n['Wed', 'Thu', 'Fri']\n>>> weekdays_between('Sat', 'Tue')\n['Sat', 'Sun', 'Mon', 'Tue']\n\n", "How about (in pseudo code):\nweekday[] = {\"Mon\" .. \"Sun\"}\nfor(i = wkday_start; (i % 7) != wkday_end; i = (i+1) % 7)\n printf(\"%s \", weekday[i]);\n\nIt works like a circular buffer, wkday_start being the index to start at (0-based), wkday_end being the end index.\nHope this helps\nGeorge.\n", "Building on the excellent answer from Stephan202, you can generalize the concept of a circular slice.\n>>> def circular_slice(r, s, e):\n... return [r[n % len(r)] for n in range(s, e + (1 if e>s else len(r)+1))]\n...\n>>> circular_slice(range(0,7), 2, 4)\n[2, 3, 4]\n>>> circular_slice(range(0,7), 5, 1)\n[5, 6, 0, 1]\n>>> circular_slice('Mon Tue Wed Thu Fri Sat Sun'.split(), 5, 1)\n['Sat', 'Sun', 'Mon', 'Tue']\n\n", "The solutions provided already answer the question, but I want to suggest something extra. I don't know what you're doing, but maybe you want the actual dates instead?\n>>> from datetime import timedelta, date\n>>> from dateutil.rrule import rrule, DAILY\n>>> today = date(2009, 10, 13) # A tuesday\n>>> week = today - timedelta(days=6)\n>>> list(rrule(DAILY, byweekday=xrange(5), dtstart=week, until=today))\n[datetime.datetime(2009, 10, 7, 0, 0),\n datetime.datetime(2009, 10, 8, 0, 0),\n datetime.datetime(2009, 10, 9, 0, 0),\n datetime.datetime(2009, 10, 12, 0, 0),\n datetime.datetime(2009, 10, 13, 0, 0)]\n\nThat uses the excellent python-dateutil module.\n", "Use the calendar module for your list of day names:\nimport calendar\n\ndef intervening_days(day1, day2):\n weektest = list(calendar.day_name)*2\n d1 = weektest.index(day1)\n d2 = weektest.index(day2,d1+1)\n return weektest[d1:d2+1]\n\nprint intervening_days(\"Monday\",\"Sunday\")\nprint intervening_days(\"Monday\",\"Tuesday\")\nprint intervening_days(\"Thursday\",\"Tuesday\")\nprint intervening_days(\"Monday\",\"Monday\")\n\nPrints:\n['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n['Monday', 'Tuesday']\n['Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']\n['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday']\n\nIf you don't want Monday-to-Monday to return a full week of days, change the determination of d2 to d2 = weektest.index(day2,d1).\n", "You asked for an algorithm, and I understand that should be language independent; however, following code works using C# and LINQ expressions:\nDayOfWeek start = DayOfWeek.Wednesday;\nDayOfWeek end = DayOfWeek.Friday;\n\nIEnumerable<DayOfWeek> interval = \n Enum.GetValues(typeof(DayOfWeek)).OfType<DayOfWeek>()\n .Where(d => d >= start && d <= end);\n\nConsole.WriteLine(\n String.Join(\", \", \n interval.Select(d => d.ToString()).ToArray()));\n\nProbably, using any language, your should attribute values to each day (Sunday=0 and so on) and look for all values which matches your desired interval.\n", "The following code returns 1 for Monday - Monday.\nbool isWeekday(int d) {\n return d >= 1 && d <= 5;\n}\n\nint f(int d1, int d2) {\n int res = isWeekday(d1) ? 1 : 0;\n return d1 == d2 ?\n res :\n res + f(d1 % 7 + 1, d2);\n}\n\n" ]
[ 10, 9, 2, 1, 1, 0, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0001577538_algorithm_python.txt
Q: Is there a random function in python that accepts variables? I'm attempting to create a simple dice roller, and I want it to create a random number between 1 and the number of sides the dice has. However, randint will not accept a variable. Is there a way to do what I'm trying to do? code below: import random a=0 final=0 working=0 sides = input("How many dice do you want to roll?") while a<=sides: a=a+1 working=random.randint(1, 4) final=final+working print "Your total is:", final A: If looks like you're confused about the number of dice and the number of sides I've changed the code to use raw_input(). input()is not recommended because Python literally evaluates the user input which could be malicious python code import random a=0 final=0 working=0 rolls = int(raw_input("How many dice do you want to roll? ")) sides = int(raw_input("How many sides? ")) while a<rolls: a=a+1 working=random.randint(1, sides) final=final+working print "Your total is:", final A: you need to pass sides to randint, for example like this: working = random.randint(1, int(sides)) also, it's not the best practice to use input in python-2.x. please, use raw_input instead, you'll need to convert to number yourself, but it's safer. A: Try randrange(1, 5) Generating random numbers in Python A: random.randint accepts a variable as either of its two parameters. I'm not sure exactly what your issue is. This works for me: import random # generate number between 1 and 6 sides = 6 print random.randint(1, sides)
Is there a random function in python that accepts variables?
I'm attempting to create a simple dice roller, and I want it to create a random number between 1 and the number of sides the dice has. However, randint will not accept a variable. Is there a way to do what I'm trying to do? code below: import random a=0 final=0 working=0 sides = input("How many dice do you want to roll?") while a<=sides: a=a+1 working=random.randint(1, 4) final=final+working print "Your total is:", final
[ "If looks like you're confused about the number of dice and the number of sides\nI've changed the code to use raw_input(). input()is not recommended because Python\nliterally evaluates the user input which could be malicious python code\nimport random\na=0\nfinal=0\nworking=0\n\nrolls = int(raw_input(\"How many dice do you want to roll? \"))\nsides = int(raw_input(\"How many sides? \"))\n\nwhile a<rolls:\n a=a+1\n working=random.randint(1, sides)\n final=final+working\n\nprint \"Your total is:\", final\n\n", "you need to pass sides to randint, for example like this:\nworking = random.randint(1, int(sides))\n\nalso, it's not the best practice to use input in python-2.x. please, use raw_input instead, you'll need to convert to number yourself, but it's safer.\n", "Try randrange(1, 5)\nGenerating random numbers in Python\n", "random.randint accepts a variable as either of its two parameters. I'm not sure exactly what your issue is.\nThis works for me:\nimport random\n\n# generate number between 1 and 6\nsides = 6\nprint random.randint(1, sides)\n\n" ]
[ 3, 2, 1, 1 ]
[]
[]
[ "python", "random" ]
stackoverflow_0001579741_python_random.txt
Q: What's the best way to search for a Python dictionary value in a list of dictionaries? I have the following data structure: data = [ {'site': 'Stackoverflow', 'id': 1}, {'site': 'Superuser', 'id': 2}, {'site': 'Serverfault', 'id': 3} ] I want to search the above list to see if it has any site with a specific value. For instance, search the above to see if the list contain a dictionary with site = 'Superuser' and return True/False. I can do the above the usual way of looping over each item and comparing them. Is there an alternative way to achieve a search? A: any(d['site'] == 'Superuser' for d in data) A: filter( lambda x: x['site']=='Superuser', data ) A: Lists absolutely require loops. That's what lists are for. To avoid looping you have to avoid lists. You want dictionaries of search keys and objects. sites = dict( (d['site'],d) for d in data ) ids = dict( (d['id'],d] for d in data ) Now you can find the item associated with 'Superuser' with sites["Superuser"] using a hashed lookup instead of a loop. A: I'm not sure of the python syntax, but it might work for you this way. While building your primary data structure, also build a parallel one that's a hash or associative array keyed on the site name; then to see if a given site exists you attempt a lookup in the hash with the site name. If it succeeds, you know there's a record in your data structure for that site and you've done it in the time of the hash lookup (likely O(1) or O(log2(n)) depending on the hash technique) instead of the O(n/2) of the list traversal. (updated while writing: this is pretty much what S.Lott posted)
What's the best way to search for a Python dictionary value in a list of dictionaries?
I have the following data structure: data = [ {'site': 'Stackoverflow', 'id': 1}, {'site': 'Superuser', 'id': 2}, {'site': 'Serverfault', 'id': 3} ] I want to search the above list to see if it has any site with a specific value. For instance, search the above to see if the list contain a dictionary with site = 'Superuser' and return True/False. I can do the above the usual way of looping over each item and comparing them. Is there an alternative way to achieve a search?
[ "any(d['site'] == 'Superuser' for d in data)\n\n", "filter( lambda x: x['site']=='Superuser', data )\n\n", "Lists absolutely require loops. That's what lists are for.\nTo avoid looping you have to avoid lists.\nYou want dictionaries of search keys and objects.\nsites = dict( (d['site'],d) for d in data )\nids = dict( (d['id'],d] for d in data )\n\nNow you can find the item associated with 'Superuser' with sites[\"Superuser\"] using a hashed lookup instead of a loop.\n", "I'm not sure of the python syntax, but it might work for you this way. While building your primary data structure, also build a parallel one that's a hash or associative array keyed on the site name; then to see if a given site exists you attempt a lookup in the hash with the site name. If it succeeds, you know there's a record in your data structure for that site and you've done it in the time of the hash lookup (likely O(1) or O(log2(n)) depending on the hash technique) instead of the O(n/2) of the list traversal.\n(updated while writing: this is pretty much what S.Lott posted)\n" ]
[ 28, 9, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001580270_python.txt