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: Can scipy calculate (double) integrals with complex-valued integrands (real and imaginary parts in integrand)? (Couldn't upload the picture showing the integral as I'm a new user.) A: Yes. Those integrals (I'll assume they're area integrals over a region in 2D space) can be calculated using an appropriate quadrature rule. You can also use Green's theorem to convert them into contour integrals and use Gaussian quadrature to integrate along the path. A: Thanks duffymo! I am calculating Huygens-Fresnel diffraction integrals: plane and other wave diffraction through circular (2D) apertures in polar coordinates. As far as the programming goes: Currently a lot of my code is in Mathematica. I am considering changing to one of: scipy, java + flanagan math library, java + apache commons math library, gnu scientific library, or octave. My first candidate for evaluation is scipy, but if it cannot handle complex-valued integrands, then I have to change my plans for the weekend...
Can scipy calculate (double) integrals with complex-valued integrands (real and imaginary parts in integrand)?
(Couldn't upload the picture showing the integral as I'm a new user.)
[ "Yes. Those integrals (I'll assume they're area integrals over a region in 2D space) can be calculated using an appropriate quadrature rule.\nYou can also use Green's theorem to convert them into contour integrals and use Gaussian quadrature to integrate along the path. \n", "Thanks duffymo!\nI am calculating H...
[ 1, 0 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0003520672_python_scipy.txt
Q: Finding all sentences from list of keywords to dict I have list of possible words to make anagram of the given words. Each string of list is key to dictionary and has value of one or more words. Which is the best (fastest, pythonic) way to make all possible sentences in the order of the keys from the words in each list of the corresponding keys in the dictionary. Lists have variable number of keys in them. keylist = ['key1', 'key2', 'key3'] worddict = {'key1': ['a','b','c'], 'key2':['d','e','f'], 'key3':['g','h','i']} Expected result (first word from first keys list, second from second keys list and so on): ["a d g", "a d h", "a d i", ..... "c f i"] A: Use the product function in the itertools module to produce all combinations of your iterables import itertools for sentence in itertools.product(['a','b','c'], ['d','e','f'], ['g','h','i']): print sentence The output will be tuples, but these can easily be converted to strings or lists if required. A: Does something like this work? import itertools anagrams = [] for x in itertools.product(*worddict.values()): anagrams.extend(" ".join(y) for y in itertools.permutations(x)) A: Encouraged to monkey with the products I could bend them to adapt variable number of keys from dictionary of lists like this: import itertools keylist = ['key1', 'key4','key2'] worddict = {'key1': ['a','b','c'], 'key2':['d','e','f'], 'key3':['g','h','i'], 'key4':['j','k','l']} sentences = (' '.join(sentence) for sentence in itertools.product(*(worddict[k] for k in keylist))) print '\n'.join(sentences)
Finding all sentences from list of keywords to dict
I have list of possible words to make anagram of the given words. Each string of list is key to dictionary and has value of one or more words. Which is the best (fastest, pythonic) way to make all possible sentences in the order of the keys from the words in each list of the corresponding keys in the dictionary. Lists have variable number of keys in them. keylist = ['key1', 'key2', 'key3'] worddict = {'key1': ['a','b','c'], 'key2':['d','e','f'], 'key3':['g','h','i']} Expected result (first word from first keys list, second from second keys list and so on): ["a d g", "a d h", "a d i", ..... "c f i"]
[ "Use the product function in the itertools module to produce all combinations of your iterables\nimport itertools\n\nfor sentence in itertools.product(['a','b','c'], ['d','e','f'], ['g','h','i']):\n print sentence\n\nThe output will be tuples, but these can easily be converted to strings or lists if required.\n"...
[ 6, 1, 0 ]
[]
[]
[ "combinations", "dictionary", "python", "word" ]
stackoverflow_0003526357_combinations_dictionary_python_word.txt
Q: PHP returning content-length of 0 to python's urllib My code fetches CSV data from a PHP page using httplib. When I open the page in Firefox or Chrome, the data displays just fine. However, when I try to fetch it with my python code, I get a header with content-length: 0 and no data. This page is the only one that does this - in another page in the same directory, the python httplib fetching works just fine. Can someone tell me what I'm doing wrong? code: FILE_LOC = '/core/csv.php' argstr = '?type=' + self.type + '&id=' + self.id conn = httplib.HTTPConnection(SERVER_ADDRESS) conn.request('GET', FILE_LOC + argstr) resp = conn.getresponse() csvstr = resp.read() The response headers: [('content-length', '0'), ('x-powered-by', 'PHP/5.1.6'), ('server', 'Apache/2.2.3 (CentOS)'), ('connection', 'close'), ('date', 'Thu, 19 Aug 2010 21:39:44 GMT'), ('content-type', 'text/html; charset=UTF-8')] A: Perhaps the PHP script expects to see some HTTP header or headers that the httplib module isn't sending. For example, httplib does not seem to send Accept, Accept-Language, or User-Agent headers by default. You may need to add one or more of those to the request() call. It does seem to send a proper Host header, though, which was my first guess. A: Probably filtering on User-Agent header -- try spoofing e.g. your Firefox. Failing that you could use Firefox to connect to a local Python server to see exactly what headers it is sending, and then replicate those.
PHP returning content-length of 0 to python's urllib
My code fetches CSV data from a PHP page using httplib. When I open the page in Firefox or Chrome, the data displays just fine. However, when I try to fetch it with my python code, I get a header with content-length: 0 and no data. This page is the only one that does this - in another page in the same directory, the python httplib fetching works just fine. Can someone tell me what I'm doing wrong? code: FILE_LOC = '/core/csv.php' argstr = '?type=' + self.type + '&id=' + self.id conn = httplib.HTTPConnection(SERVER_ADDRESS) conn.request('GET', FILE_LOC + argstr) resp = conn.getresponse() csvstr = resp.read() The response headers: [('content-length', '0'), ('x-powered-by', 'PHP/5.1.6'), ('server', 'Apache/2.2.3 (CentOS)'), ('connection', 'close'), ('date', 'Thu, 19 Aug 2010 21:39:44 GMT'), ('content-type', 'text/html; charset=UTF-8')]
[ "Perhaps the PHP script expects to see some HTTP header or headers that the httplib module isn't sending. For example, httplib does not seem to send Accept, Accept-Language, or User-Agent headers by default. You may need to add one or more of those to the request() call. It does seem to send a proper Host header, t...
[ 1, 1 ]
[]
[]
[ "content_length", "php", "python" ]
stackoverflow_0003526534_content_length_php_python.txt
Q: redirecting standard output to print messages in gui instead of terminal #!/usr/bin/python import wx import os import sys class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(480, 400)) self.panel = MyPanel(self, -1) self.Centre() self.Show(True) setstd() print 'test' """ syncall() """ class MyPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) self.text = wx.StaticText(self, -1, '', (40, 60)) class MyText(): def write(string): label = frame.panel.text.GetLabel() frame.panel.text.SetLabel(string) def setstd(): sys.stdout = MyText() sys.stderr = MyText() app = wx.App() frame = MyFrame(None, -1, 'DropBox log') app.MainLoop() Without print 'test', it even runs, but with print 'test', it doesn't run nor redirect output. How to redirect standard output to print messages in gui instead of terminal? A: When you use the print statement with wxPython, where it ends up depends on how you called wx.App(). wx.App(redirect=False) or simply wx.App(0) will send print statements to a console window, otherwise they will be sent to a little textbox window. A: I finally found: http://www.velocityreviews.com/forums/t515815-wxpython-redirect-the-stdout-to-a-textctrl.html
redirecting standard output to print messages in gui instead of terminal
#!/usr/bin/python import wx import os import sys class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(480, 400)) self.panel = MyPanel(self, -1) self.Centre() self.Show(True) setstd() print 'test' """ syncall() """ class MyPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) self.text = wx.StaticText(self, -1, '', (40, 60)) class MyText(): def write(string): label = frame.panel.text.GetLabel() frame.panel.text.SetLabel(string) def setstd(): sys.stdout = MyText() sys.stderr = MyText() app = wx.App() frame = MyFrame(None, -1, 'DropBox log') app.MainLoop() Without print 'test', it even runs, but with print 'test', it doesn't run nor redirect output. How to redirect standard output to print messages in gui instead of terminal?
[ "When you use the print statement with wxPython, where it ends up depends on how you called wx.App(). \nwx.App(redirect=False) or simply wx.App(0) will send print statements to a console window, otherwise they will be sent to a little textbox window.\n", "I finally found:\nhttp://www.velocityreviews.com/forums/t...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003526461_python.txt
Q: Pythonic way to compare two lists and print the unmatched items? I have two Python lists of dictionaries, entries9 and entries10. I want to compare the items and write joint items to a new list called joint_items. I also want to save the unmatched items to two new lists, unmatched_items_9 and unmatched_items_10. This is my code. Getting the joint_items and unmatched_items_9 (in the outer list) is quite easy: but how do I get unmatched_items_10 (in the inner list)? for counter, entry1 in enumerate(entries9): match_found = False for counter2,entry2 in enumerate(entries10): if match_found: continue if entry1[a]==entry2[a] and entry1[b]==entry2[b]: # the dictionaries only have some keys in common, but we care about a and b match_found = True joint_item = entry1 joint_items.append(joint_item) #entries10.remove(entry2) # Tried this originally, but realised it messes with the original list object! if match_found: continue else: unmatched_items_9.append(entry1) Performance is not really an issue, since it's a one-off script. A: The equivalent of what you're currently doing, but the other way around, is: unmatched_items_10 = [d for d in entries10 if d not in entries9] While more concise than your way of coding it, this has the same performance problem: it will take time proportional to the number of items in each list. If the lengths you're interested in are about 9 or 10 (as those numbers seem to indicate), no problem. But for lists of substantial length you can get much better performance by sorting the lists and "stepping through" them "in parallel" so to speak (time proportional to N log N where N is the length of the longer list). There are other possibilities, too (of growing complication;-) if even this more advanced approach is not sufficient to get you the performance you need. I'll refrain from suggesting very complicated stuff unless you indicate that you do require it to get good performance (in which case, please mention the typical lengths of each list and the typical contents of the dicts that are their items, since of course such "details" are the crucial consideration for picking algorithms that are a good compromise between speed and simplicity). Edit: the OP edited his Q to show what he cares about, for any two dicts d1 and d2 one each from the two lists, is not whether d1 == d2 (which is what the in operator checks), but rather d1[a]==d2[a] and d1[b]==d2[b]. In this case the in operator cannot be used (well, not without some funky wrapping, but that's a complication that's best avoided when feasible;-), but the all builtin replaces it handily: unmatched_items_10 = [d for d in entries10 if all(d[a]!=d1[a] or d[b]!=d2[b] for d2 in entries9)] I have switched the logic around (to != and or, per De Morgan's laws) since we want the dicts that are not matched. However, if you prefer: unmatched_items_10 = [d for d in entries10 if not any(d[a]==d1[a] and d[b]==d2[b] for d2 in entries9)] Personally, I don't like if not any and if not all, for stylistic reasons, but the maths are impeccable (by what the Wikipedia page calls the Extensions to De Morgan's laws, since any is an existential quantifier and all a universal quantifier, so to speak;-). Performance should be just about equivalent (but then, the OP did clarify in a comment that performance is not very important for them on this task). A: The Python stdlib has a class, difflib.SequenceMatcher that looks like it can do what you want, though I don't know how to use it! A: You may consider using sets and their associated methods, like intersection. You will however, need to turn your dictionaries into immutable data so that you can store them in a set (e.g. strings). Would something like this work? a = set(str(x) for x in entries9) b = set(str(x) for x in entries10) # You'll have to change the above lines if you only care about _some_ of the keys joint_items = a.union(b) unmatched_items = a - b # Now you can turn them back into dicts: joint_items = [eval(i) for i in joint_items] unmatched_items = [eval(i) for i in unmatched_items]
Pythonic way to compare two lists and print the unmatched items?
I have two Python lists of dictionaries, entries9 and entries10. I want to compare the items and write joint items to a new list called joint_items. I also want to save the unmatched items to two new lists, unmatched_items_9 and unmatched_items_10. This is my code. Getting the joint_items and unmatched_items_9 (in the outer list) is quite easy: but how do I get unmatched_items_10 (in the inner list)? for counter, entry1 in enumerate(entries9): match_found = False for counter2,entry2 in enumerate(entries10): if match_found: continue if entry1[a]==entry2[a] and entry1[b]==entry2[b]: # the dictionaries only have some keys in common, but we care about a and b match_found = True joint_item = entry1 joint_items.append(joint_item) #entries10.remove(entry2) # Tried this originally, but realised it messes with the original list object! if match_found: continue else: unmatched_items_9.append(entry1) Performance is not really an issue, since it's a one-off script.
[ "The equivalent of what you're currently doing, but the other way around, is:\nunmatched_items_10 = [d for d in entries10 if d not in entries9]\n\nWhile more concise than your way of coding it, this has the same performance problem: it will take time proportional to the number of items in each list. If the lengths...
[ 10, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003526196_list_python.txt
Q: difference between default and optional arguments okay code: #!/usr/bin/python import wx import sys class XPinst(wx.App): def __init__(self, redirect=False, filename=None): wx.App.__init__(self, redirect, filename) def OnInit(self): frame = wx.Frame(None, -1, title='Redirect Test', size=(620,450), style=wx.STAY_ON_TOP|wx.DEFAULT_FRAME_STYLE) panel = wx.Panel(frame, -1) log = wx.TextCtrl(panel, -1, size=(500,400), style = wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL) redir=RedirectText(log) sys.stdout=redir print 'test' frame.Show() return True class RedirectText: def __init__(self,aWxTextCtrl): self.out=aWxTextCtrl def write(self,string): self.out.WriteText(string) app = XPinst() app.MainLoop() added: class MyFrame(wx.Frame) def __init__(self, parent, id, title, size=(620,450), style=wx.STAY_ON_TOP|wx.DEFAULT_FRAME_STYLE): wx.Frame.__init__(self, parent, id, title, size=(620,450), style=wx.STAY_ON_TOP|wx.DEFAULT_FRAME_STYLE) replaced: frame = wx.Frame(None, -1, title='Redirect Test', size=(620,450), style=wx.STAY_ON_TOP|wx.DEFAULT_FRAME_STYLE) with: frame = MyFrame(None, -1, title='Redirect Test', size=(620,450), style=wx.STAY_ON_TOP|wx.DEFAULT_FRAME_STYLE) Now, it doesn't run... I want to be able to call the MyFrame constructor more than once in my code passing different arguments I tried many things... instanciating MyFrame with all arguments instanciating myFrame and with all, but default arguments constructor method signature with all arguments constructor method signature with all, but default arguments calling parent constructor method with all arguments calling parent constructor method with all, but default arguments plus the tutorial http://zetcode.com/wxpython/ mentions a method where the number of default and optional arguments are different! (what's the difference?) UDPATE: "it has seven parameters. The first parameter does not have a default value. The other six parameters do have. Those four parameters are optional. The first three are mandatory." - http://zetcode.com/wxpython/firststeps/ UPDATE 2: With semi-colon correction, i have just tried: class MyFrame(wx.Frame): def __init__(self, parent, id, title, size, style): wx.Frame.__init__(self, parent, id, title, size, style) I tell what arguments are going in (second line) I call with the arguments that went in (third line) UPDATE 3: the full error message is: Traceback (most recent call last): File "test.py", line 29, in <module> app = XPinst() File "test.py", line 8, in __init__ wx.App.__init__(self, redirect, filename) File "/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode/wx/_core.py", line 7978, in __init__ self._BootstrapApp() File "/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode/wx/_core.py", line 7552, in _BootstrapApp return _core_.PyApp__BootstrapApp(*args, **kwargs) File "test.py", line 10, in OnInit frame = MyFrame(None, -1, title='Redirect Test', size=(620,450), style=wx.STAY_ON_TOP|wx.DEFAULT_FRAME_STYLE) File "test.py", line 21, in __init__ wx.Frame.__init__(self, parent, id, title, size, style) File "/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode/wx/_windows.py", line 497, in __init__ _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) TypeError: Expected a 2-tuple of integers or a wxSize object. Why didn't it work? A: Runs fine for me with one tweak; you're missing a colon after your subclassed wx.Frame statement. One comment; if you're just "passing through" arguments to the parent initalizer, use *args and/or **kwargs to save some typing. class MyFrame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) If you want to modify or add particular arguments, you could just modify the dictionary kwargs, e.g. class MyFrame(wx.Frame): def __init__(self, *args, **kwargs): kwargs['size']=(1000,200) wx.Frame.__init__(self, *args, **kwargs) On running files for development: Run scripts you're working on in the console, with python, not pythonw. The latter will just quit when it sees errors and send them off to lala-land. N:\Code>pythonw wxso.pyw N:\Code>rem nothing happened. N:\Code>python wxso.pyw File "wxso.pyw", line 24 class MyFrame(wx.Frame) ^ SyntaxError: invalid syntax N:\Code> On keyword arguments: class MyFrame(wx.Frame): def __init__(self, parent, id, title, size, style): #wx.Frame.__init__(self, parent, id, title, size, style) # broken # equivalent to: #wx.Frame.__init__(self, parent, id=id, title=title, pos=size, size=style) # the below works. wx.Frame.__init__(self, parent, id, title=title, size=size, style=style) When you pass arguments as keywords e.g. title, size, style, their position to the function that actually takes them could be totally different. The first line there assigns "size" to whatever is the fifth argument in the wx.Frame.__init__ function, which is probably not size. It could be the 100th argument, but you use the keyword to tell it where to go. "Optional" is somewhat vague; keyword arguments supply defaults, but the default may be inappropriate. A: You're missing the pos from your Frame.__init__ call. Here's the prototype from the docs: Frame.__init__(self, parent, id, title, pos, size, style, name) So basically the error is saying that it expects size to be a 2-tuple or wxSize object, and what you were passing doesn't match that. I'm guessing that this crept in when you removed size= from the constructor here: class MyFrame(wx.Frame): def __init__(self, parent, id, title, size, style): wx.Frame.__init__(self, parent, id, title, size, style) Edit: Either of the following would be fine wx.Frame.__init__(self, parent, id, title, size=size, style=style) wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, size, style) but by omitting the keywords from the arguments, your call was being handled in the order passed, as wx.Frame.__init__(self, parent, id, title, pos=size, size=style)
difference between default and optional arguments
okay code: #!/usr/bin/python import wx import sys class XPinst(wx.App): def __init__(self, redirect=False, filename=None): wx.App.__init__(self, redirect, filename) def OnInit(self): frame = wx.Frame(None, -1, title='Redirect Test', size=(620,450), style=wx.STAY_ON_TOP|wx.DEFAULT_FRAME_STYLE) panel = wx.Panel(frame, -1) log = wx.TextCtrl(panel, -1, size=(500,400), style = wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL) redir=RedirectText(log) sys.stdout=redir print 'test' frame.Show() return True class RedirectText: def __init__(self,aWxTextCtrl): self.out=aWxTextCtrl def write(self,string): self.out.WriteText(string) app = XPinst() app.MainLoop() added: class MyFrame(wx.Frame) def __init__(self, parent, id, title, size=(620,450), style=wx.STAY_ON_TOP|wx.DEFAULT_FRAME_STYLE): wx.Frame.__init__(self, parent, id, title, size=(620,450), style=wx.STAY_ON_TOP|wx.DEFAULT_FRAME_STYLE) replaced: frame = wx.Frame(None, -1, title='Redirect Test', size=(620,450), style=wx.STAY_ON_TOP|wx.DEFAULT_FRAME_STYLE) with: frame = MyFrame(None, -1, title='Redirect Test', size=(620,450), style=wx.STAY_ON_TOP|wx.DEFAULT_FRAME_STYLE) Now, it doesn't run... I want to be able to call the MyFrame constructor more than once in my code passing different arguments I tried many things... instanciating MyFrame with all arguments instanciating myFrame and with all, but default arguments constructor method signature with all arguments constructor method signature with all, but default arguments calling parent constructor method with all arguments calling parent constructor method with all, but default arguments plus the tutorial http://zetcode.com/wxpython/ mentions a method where the number of default and optional arguments are different! (what's the difference?) UDPATE: "it has seven parameters. The first parameter does not have a default value. The other six parameters do have. Those four parameters are optional. The first three are mandatory." - http://zetcode.com/wxpython/firststeps/ UPDATE 2: With semi-colon correction, i have just tried: class MyFrame(wx.Frame): def __init__(self, parent, id, title, size, style): wx.Frame.__init__(self, parent, id, title, size, style) I tell what arguments are going in (second line) I call with the arguments that went in (third line) UPDATE 3: the full error message is: Traceback (most recent call last): File "test.py", line 29, in <module> app = XPinst() File "test.py", line 8, in __init__ wx.App.__init__(self, redirect, filename) File "/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode/wx/_core.py", line 7978, in __init__ self._BootstrapApp() File "/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode/wx/_core.py", line 7552, in _BootstrapApp return _core_.PyApp__BootstrapApp(*args, **kwargs) File "test.py", line 10, in OnInit frame = MyFrame(None, -1, title='Redirect Test', size=(620,450), style=wx.STAY_ON_TOP|wx.DEFAULT_FRAME_STYLE) File "test.py", line 21, in __init__ wx.Frame.__init__(self, parent, id, title, size, style) File "/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode/wx/_windows.py", line 497, in __init__ _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) TypeError: Expected a 2-tuple of integers or a wxSize object. Why didn't it work?
[ "Runs fine for me with one tweak; you're missing a colon after your subclassed wx.Frame statement.\nOne comment; if you're just \"passing through\" arguments to the parent initalizer, use *args and/or **kwargs to save some typing.\nclass MyFrame(wx.Frame):\n def __init__(self, *args, **kwargs):\n wx.Frame...
[ 1, 1 ]
[]
[]
[ "keyword_argument", "optional_parameters", "python", "wxpython" ]
stackoverflow_0003527468_keyword_argument_optional_parameters_python_wxpython.txt
Q: Python + MySQLDB Batch Insert/Update command for two of the same databases I'm working with two databases, a local version and the version on the server. The server is the most up to date version and instead of recopying all values on all tables from the server to my local version, I would like to enter each table and only insert/update the values that have changed, from server, and copy those values to my local version. Is there some simple method to handling such a case? Some sort of batch insert/update? Googl'ing up the answer isn't working and I've tried my hand at coding one but am starting to get tied up in error handling.. I'm using Python and MySQLDB... Thanks for any insight Steve A: If all of your tables' records had timestamps, you could identify "the values that have changed in the server" -- otherwise, it's not clear how you plan to do that part (which has nothing to do with insert or update, it's a question of "selecting things right"). Once you have all the important values, somecursor.executemany will let you apply them all as a batch. Depending on your indexing it may be faster to put them into a non-indexed auxiliary temporary table, then insert/update from all of that table into the real one (before dropping the aux/temp one), the latter of course being a single somecursor.execute. You can reduce wall-clock time for the whole job by using one (or a few) threads to do the selects and put the results onto a Queue.Queue, and a few worker threads to apply results plucked from the queue into the internal/local server. (Best balance of reading vs writing threads is best obtained by trying a few and measuring -- writing per se is slower than reading, but your bandwidth to your local server may be higher than to the other one, so it's difficult to predict). However, all of this is moot unless you do have a strategy to identify "the values that have changed in the server", so it's not necessarily very useful to enter into more discussion about details "downstream" from that identification.
Python + MySQLDB Batch Insert/Update command for two of the same databases
I'm working with two databases, a local version and the version on the server. The server is the most up to date version and instead of recopying all values on all tables from the server to my local version, I would like to enter each table and only insert/update the values that have changed, from server, and copy those values to my local version. Is there some simple method to handling such a case? Some sort of batch insert/update? Googl'ing up the answer isn't working and I've tried my hand at coding one but am starting to get tied up in error handling.. I'm using Python and MySQLDB... Thanks for any insight Steve
[ "If all of your tables' records had timestamps, you could identify \"the values that have changed in the server\" -- otherwise, it's not clear how you plan to do that part (which has nothing to do with insert or update, it's a question of \"selecting things right\").\nOnce you have all the important values, somecur...
[ 0 ]
[]
[]
[ "batch_file", "mysql", "python" ]
stackoverflow_0003526629_batch_file_mysql_python.txt
Q: Determine local connectivity in python How can I tell if my client system has a network connection using python? I can assume the client connected with DHCP. I can't use lists of known reliable sites to ping to test the connection, as it needs to work in isolated networks as well as open ones. I thought about fetching the local ip (should work, so long as it doesn't only return loopback). But.... print socket.gethostbyaddr('localhost') returns ('localhost', ['ip6-localhost', 'ip6-loopback'], ['::1']) which isn't very useful. Any other ideas would be appreciated, thanks! A: localhost should always return 127.0.0.1 in ip4, '::1' in ip6, so of course it's not going to be useful -- it's the loopback interface, not the ethernet card or whatever;-). Personally, I'd use subprocess.Popen to run ifconfig and parse the results (it's spelled ipconfig in Windows) -- not ideal, but pretty practical, IMNSHO;-).
Determine local connectivity in python
How can I tell if my client system has a network connection using python? I can assume the client connected with DHCP. I can't use lists of known reliable sites to ping to test the connection, as it needs to work in isolated networks as well as open ones. I thought about fetching the local ip (should work, so long as it doesn't only return loopback). But.... print socket.gethostbyaddr('localhost') returns ('localhost', ['ip6-localhost', 'ip6-loopback'], ['::1']) which isn't very useful. Any other ideas would be appreciated, thanks!
[ "localhost should always return 127.0.0.1 in ip4, '::1' in ip6, so of course it's not going to be useful -- it's the loopback interface, not the ethernet card or whatever;-).\nPersonally, I'd use subprocess.Popen to run ifconfig and parse the results (it's spelled ipconfig in Windows) -- not ideal, but pretty pract...
[ 4 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0003527720_python_sockets.txt
Q: extract specific set of lines from files I have many large (~30 MB a piece) tab-delimited text files with variable-width lines. I want to extract the 2nd field from the nth (here, n=4) and next-to-last line (the last line is empty). I can get them separately using awk: awk 'NR==4{print $2}' filename.dat and (I don't comprehend this entirely but) awk '{y=x "\n" $2};END{print y}' filename.dat but is there a way to get them together in one call? My broader intention is to wrap it in a Python script to harvest these values from a large number of files (many thousands) in separate directories and I want to reduce the number of system calls. Thanks a bunch - Edit: I know I can read over the whole file with Python to extract those values, but thought awk might be more appropriate for the task (having to do with one of the two values located near the end of the large file). A: awk 'NR==4{print $2};{y=x "\n" $2};END{print y}' filename.dat A: You can pass the number of lines into awk: awk -v lines=$( wc -l < filename.dat ) -v n=4 ' NR == n || NR == lines-1 {print $2} ' filename.dat Note, in the wc command, use the < redirection to avoid the filename being printed. A: Here's how to implement this in Python without reading the whole file To get the nth line, you have no choice but to read the file up to the nth line as the lines are variable width. To get the second to last line, guess how long the line might be (be generous) and seek to that many bytes before the end of the file. read() from the point you have seeked to. Count the number of newline characters - You need at least two. If there are less than 2 newlines double your guess and try again split the data you read at newlines - the line you seek will be the second to last item in the split A: This is my solution in Python. Inspired by this other code: def readfields(filename,nfromtop=3,nfrombottom=-2,fieldnum=1,blocksize=4096): f = open(filename,'r') out = '' for i,line in enumerate(f): if i==nfromtop: out += line.split('\t')[fieldnum]+'\t' break f.seek(-blocksize,2) out += str.split(f.read(blocksize),'\n')[nfrombottom].split('\t')[fieldnum] return out When I profiled it, the difference was 0.09 seconds quicker than a solution calling awk (awk 'NR==4{print $2};{y=x $2};END{print y}' filename.dat) with the subprocess module. Not a dealbreaker, but when the rest of the script is in Python it appears there is a payoff in going there (especially since I have a lot of these files).
extract specific set of lines from files
I have many large (~30 MB a piece) tab-delimited text files with variable-width lines. I want to extract the 2nd field from the nth (here, n=4) and next-to-last line (the last line is empty). I can get them separately using awk: awk 'NR==4{print $2}' filename.dat and (I don't comprehend this entirely but) awk '{y=x "\n" $2};END{print y}' filename.dat but is there a way to get them together in one call? My broader intention is to wrap it in a Python script to harvest these values from a large number of files (many thousands) in separate directories and I want to reduce the number of system calls. Thanks a bunch - Edit: I know I can read over the whole file with Python to extract those values, but thought awk might be more appropriate for the task (having to do with one of the two values located near the end of the large file).
[ "awk 'NR==4{print $2};{y=x \"\\n\" $2};END{print y}' filename.dat\n\n", "You can pass the number of lines into awk:\nawk -v lines=$( wc -l < filename.dat ) -v n=4 '\n NR == n || NR == lines-1 {print $2}\n' filename.dat\n\nNote, in the wc command, use the < redirection to avoid the filename being printed.\n", ...
[ 3, 2, 1, 1 ]
[]
[]
[ "awk", "python", "text_processing" ]
stackoverflow_0003518068_awk_python_text_processing.txt
Q: How to generate a UUID of type long (to be consumed by a java program) in Python? How do you generate UUID of type long (64 bits - to be consumed by a java program) using Python? I read about the UUID module. So I played with it a bit: >>> import uuid >>> uuid.uuid1().int 315596929882403038588122750660996915734L Why is there an "L" at the end of the integer generated by uuid.uuid1().int? If it's an integer shouldn't it be made up of pure numbers? Also according to the documentation uuid.uuid1().int will generate a 128 bits integer. I need an integer of type long (for a java program), that would mean it need to be 64 bits. Is it possible to generate a UUID of 64 bits instead of 128 bits? Another problem is that according to the Python doc a Python int is 32 bits while a Python long has "unlimited precision." What does "unlimited precision" mean? I need a 64 bits long int - what Python type would that be? EDIT: Thanks for everyone's replies. Looks like UUID's are by definition 128 bits. In that case I probably shouldn't be using the term UUID. What I want to do is to generate a unique ID that is of type long (64 bits). I thought UUID would do the job, but it looks like it can't. I need that ID as the document ID for Solr search engine. I'm using a real-time indexing Solr plugin Zoie. And according to the documentation, "Zoie assumes every record to be indexed must have a unique key and of type long." So given that's what I need, do you know what I can do to generate unique ID of type long? Thank you! A: The L signifies that it's a long integer value (greater than 32 bits). Standard UUIDs are always 128 bits; if you want something that's only 64 bits, you'll need to either only use a sub-part of a UUID, or use something other than a UUID. A: Depending on how unique you need it to be, you may be able to generate your own form of UUID that is more of a machine wide unique ID rather than a universally unique ID (i.e. it may not be unique across computers but on the one computer is okay). If the ID need only be unique on the one platform then you can get away with removing the node id section at the end (the last 6 bytes). Also, you might consider how often these numbers are being generated. Are they generated once per second max or very frequently? Have a look here at how a UUID is generated and you'll see what I mean: http://tools.ietf.org/id/draft-leach-uuids-guids-01.txt You can probably roll your own version for your situation and yet still meet your requirement and fit within 64 bits easily. By the way, the "L" symbolizes a long int which usually means 64-bit length, rather than 32-bit. It's just appended when you print out the number. A: The stock definition of UUID is 128 bits. I'd wager that 64 bits is not enough to guarantee non-synchronized uniqueness. A: One point to add, even Java's UUID is 128-bit long. If you are going to have it consumed by Java, you gotta make it 128-bit long instead of 64. http://download-llnw.oracle.com/javase/1.5.0/docs/api/java/util/UUID.html
How to generate a UUID of type long (to be consumed by a java program) in Python?
How do you generate UUID of type long (64 bits - to be consumed by a java program) using Python? I read about the UUID module. So I played with it a bit: >>> import uuid >>> uuid.uuid1().int 315596929882403038588122750660996915734L Why is there an "L" at the end of the integer generated by uuid.uuid1().int? If it's an integer shouldn't it be made up of pure numbers? Also according to the documentation uuid.uuid1().int will generate a 128 bits integer. I need an integer of type long (for a java program), that would mean it need to be 64 bits. Is it possible to generate a UUID of 64 bits instead of 128 bits? Another problem is that according to the Python doc a Python int is 32 bits while a Python long has "unlimited precision." What does "unlimited precision" mean? I need a 64 bits long int - what Python type would that be? EDIT: Thanks for everyone's replies. Looks like UUID's are by definition 128 bits. In that case I probably shouldn't be using the term UUID. What I want to do is to generate a unique ID that is of type long (64 bits). I thought UUID would do the job, but it looks like it can't. I need that ID as the document ID for Solr search engine. I'm using a real-time indexing Solr plugin Zoie. And according to the documentation, "Zoie assumes every record to be indexed must have a unique key and of type long." So given that's what I need, do you know what I can do to generate unique ID of type long? Thank you!
[ "The L signifies that it's a long integer value (greater than 32 bits).\nStandard UUIDs are always 128 bits; if you want something that's only 64 bits, you'll need to either only use a sub-part of a UUID, or use something other than a UUID.\n", "Depending on how unique you need it to be, you may be able to genera...
[ 8, 4, 1, 1 ]
[]
[]
[ "guid", "java", "long_integer", "python", "uuid" ]
stackoverflow_0003528119_guid_java_long_integer_python_uuid.txt
Q: python target string key count invalid syntax Why am i getting an "invalid syntax" when i run below code. Python 2.7 from string import * def countSubStringMatch(target,key): counter=0 fsi=0 #fsi=find string index while fsi<len(target): fsi=dna.find(key,fsi) if fsi!=-1: counter+=1 else: counter=0 fsi=fsi+1 fsi=fsi+1 #print '%s is %d times in the target string' %(key,counter) def countSubStringMatch("atgacatgcacaagtatgcat","atgc") A: In the line: def countSubStringMatch("atgacatgcacaagtatgcat","atgc") You should remove the def. def is used when defining a function, not when calling it. A: Other things wrong with your code: You don't use and don't need anything in the string module. Don't import from it. Don't do from somemodule import * unless you have a very good reason for it. Your code rather slowly and pointlessly struggles on after the first time that find returns -1 ... your loop should include if fsi == -1: return counter so that you return immediately with the correct count. Be consistent: you use counter += 1 but fsi = fsi + 1 ... which reminds me: find 'PEP 8' (style guide) at www.python.org, and read it -- your space bar must be feeling unloved ;-) HTH John A: for string count you could just do: target = "atgacatgcacaagtatgcat" s = 'atgc' print '%s is %d times in the target string' % (s, target.count(s))
python target string key count invalid syntax
Why am i getting an "invalid syntax" when i run below code. Python 2.7 from string import * def countSubStringMatch(target,key): counter=0 fsi=0 #fsi=find string index while fsi<len(target): fsi=dna.find(key,fsi) if fsi!=-1: counter+=1 else: counter=0 fsi=fsi+1 fsi=fsi+1 #print '%s is %d times in the target string' %(key,counter) def countSubStringMatch("atgacatgcacaagtatgcat","atgc")
[ "In the line:\ndef countSubStringMatch(\"atgacatgcacaagtatgcat\",\"atgc\")\n\nYou should remove the def. def is used when defining a function, not when calling it.\n", "Other things wrong with your code:\n\nYou don't use and don't need anything in the string module. Don't import from it.\nDon't do from somemodule...
[ 5, 3, 3 ]
[]
[]
[ "python", "string", "syntax" ]
stackoverflow_0003525952_python_string_syntax.txt
Q: search and replace text inline in file in Python I am trying to convert a file which contains ip address in the traditional format to a file which contains ip address in the binary format. The file contents are as follows. src-ip{ 192.168.64.54 } dst-ip{ 192.168.43.87 } The code I have is as follows. import re from decimal import * filter = open("filter.txt", "r") output = open("format.txt", "w") for line in filter: bytePattern = "([01]?\d\d?|2[0-4]\d|25[0-5])" regObj = re.compile("\.".join([bytePattern]*4)) for match in regObj.finditer(line): m1,m2,m3,m4 = match.groups() line = line.replace((' '.join([bin(256 + int(x))[3:] for x in '123.123.123.123'.split('.')])),bytePattern) print line The portion line.replace() does not seem to be working fine. The first parameter to line .replace is working fine.(i.e it is converting the ip address into the binary format) But line.replace doesn't seem to work. Any help or clues as to why this happens is appreciated. A: with open('filter.txt') as filter_: with open("format.txt", "w") as format: for line in filter_: if line != '\n': ip = line.split() ip[1] = '.'.join(bin(int(x)+256)[3:] for x in ip[1].split('.')) ip[4]= '.'.join(bin(int(x)+256)[3:] for x in ip[4].split('.')) ip = " ".join(ip) + '\n' format.write(ip) A: Why not take advantage of re.sub() instead, to both make your replacements easier and simplify your regex? import re from decimal import * filter = open("filter.txt", "r") output = open("format.txt", "w") pattern = re.compile(r'[\d.]+') # Matches any sequence of digits and .'s def convert_match_to_binary(match) octets = match.group(0).split('.') # do something here to convert the octets to a string you want to replace # this IP with, and store it in new_form return new_form for line in filter: line = pattern.sub(convert_match_to_binary, line) print line A: Your code is very odd: line = line.replace( (' '.join([bin(256 + int(x))[3:] for x in '123.123.123.123'.split('.')])), bytePattern ) The first argument is a constant that evaluates to '01111011 01111011 01111011 01111011', and bytePattern is the regex "([01]?\d\d?|2[0-4]\d|25[0-5])", so it's effectively this: line = line.replace('01111011 01111011 01111011 01111011', "([01]?\d\d?|2[0-4]\d|25[0-5])") This won't do anything if your file doesn't have 01111011 01111011 01111011 01111011 in it. The .replace() method only replaces literal strings, not regexes. A: If it is any help here is my old code from DaniWed IP number conversion between dotnumber string and integer with some error check added. def ipnumber(ip): if ip.count('.') != 3: raise ValueError, 'IP string with wrong number of dots' ip=[int(ipn) for ipn in ip.rstrip().split('.')] if any(ipn<0 or ipn>255 for ipn in ip): raise ValueError, 'IP part of wrong value: %s' % ip ipn=0 while ip: ipn=(ipn<<8)+ip.pop(0) return ipn def ipstring(ip): ips='' for i in range(4): ip,n=divmod(ip,256) print n if (n<0) or (n>255): raise ValueError, "IP number %i is not valid (%s, %i)." % (ip,ips,n) ips = str(n)+'.'+ips return ips[:-1] ## take out extra point inp = "src-ip{ 192.168.64.544 } dst-ip{ 192.168.43.87 }" found=' ' while found: _,found,ip = inp.partition('-ip{ ') ip,found,inp = ip.partition(' }') if ip: print ipnumber(ip)
search and replace text inline in file in Python
I am trying to convert a file which contains ip address in the traditional format to a file which contains ip address in the binary format. The file contents are as follows. src-ip{ 192.168.64.54 } dst-ip{ 192.168.43.87 } The code I have is as follows. import re from decimal import * filter = open("filter.txt", "r") output = open("format.txt", "w") for line in filter: bytePattern = "([01]?\d\d?|2[0-4]\d|25[0-5])" regObj = re.compile("\.".join([bytePattern]*4)) for match in regObj.finditer(line): m1,m2,m3,m4 = match.groups() line = line.replace((' '.join([bin(256 + int(x))[3:] for x in '123.123.123.123'.split('.')])),bytePattern) print line The portion line.replace() does not seem to be working fine. The first parameter to line .replace is working fine.(i.e it is converting the ip address into the binary format) But line.replace doesn't seem to work. Any help or clues as to why this happens is appreciated.
[ "with open('filter.txt') as filter_:\n with open(\"format.txt\", \"w\") as format: \n for line in filter_:\n if line != '\\n':\n ip = line.split()\n ip[1] = '.'.join(bin(int(x)+256)[3:] for x in ip[1].split('.'))\n ip[4]= '.'.join(bin(int(x)+256)[3:]...
[ 2, 1, 0, 0 ]
[]
[]
[ "python", "regex", "replace" ]
stackoverflow_0003527975_python_regex_replace.txt
Q: How to receive and parse a HTTP incoming request using python? How to receive and parse a HTTP incoming request using python? A: You can do: python -m SimpleHTTPServer 8080 By default it serves the current working directory. To get an idea of how this is put together/parses the requests or to work out how to build one for your own needs, look at the "SimpleHTTPServer.py" module in the lib directory of your python install. You could also look at the built in webservers that the web frameworks like django, werkzeug, cherry-py provide. Stackoverflow has quite a few interesting questions. A: There are dozens of solutions for this, of all kinds and flavors. The most basic would be SimpleHTTPServer mentioned by @davey. Other options would be: http://webpy.org/ - simple, lightweight framework http://www.tornadoweb.org/ - flexible and scalable web server http://twistedmatrix.com/trac/wiki/TwistedWeb - single-threaded, event-driven server and framework http://bottle.paws.de/ - single-file server and framework
How to receive and parse a HTTP incoming request using python?
How to receive and parse a HTTP incoming request using python?
[ "You can do:\npython -m SimpleHTTPServer 8080 \n\nBy default it serves the current working directory.\nTo get an idea of how this is put together/parses the requests or to work out how to build one for your own needs, look at the \"SimpleHTTPServer.py\" module in the lib directory of your python install.\nYou could...
[ 1, 0 ]
[]
[]
[ "http", "python" ]
stackoverflow_0003528865_http_python.txt
Q: Extract certain elements from a list I have no clue about Python and started to use it on some files. I managed to find out how to do all the things that I need, except for 2 things. 1st >>>line = ['0', '1', '2', '3', '4', '5', '6'] >>>#prints all elements of line as expected >>>print string.join(line) 0 1 2 3 4 5 6 >>>#prints the first two elements as expected >>>print string.join(line[0:2]) 0 1 >>>#expected to print the first, second, fourth and sixth element; >>>#Raises an exception instead >>>print string.join(line[0:2:4:6]) SyntaxError: invalid syntax I want this to work similar to awk '{ print $1 $2 $5 $7 }'. How can I accomplish this? 2nd how can I delete the last character of the line? There is an additional ' that I don't need. A: Provided the join here is just to have a nice string to print or store as result (with a coma as separator, in the OP example it would have been whatever was in string). line = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] print ','.join (line[0:2]) A,B print ','.join (line[i] for i in [0,1,2,4,5,6]) A,B,C,E,F,G What you are doing in both cases is extracting a sublist from the initial list. The first one use a slice, the second one use a list comprehension. As others said you could also have accessed to elements one by one, the above syntaxes are merely shorthands for: print ','.join ([line[0], line[1]]) A,B print ','.join ([line[0], line[1], line[2], line[4], line[5], line[6]]) A,B,C,E,F,G I believe some short tutorial on list slices could be helpfull: l[x:y] is a 'slice' of list l. It will get all elements between position x (included) and position y (excluded). Positions starts at 0. If y is out of list or missing, it will include all list until the end. If you use negative numbers you count from the end of the list. You can also use a third parameter like in l[x:y:step] if you want to 'jump over' some items (not take them in the slice) with a regular interval. Some examples: l = range(1, 100) # create a list of 99 integers from 1 to 99 l[:] # resulting slice is a copy of the list l[0:] # another way to get a copy of the list l[0:99] # as we know the number of items, we could also do that l[0:0] # a new empty list (remember y is excluded] l[0:1] # a new list that contains only the first item of the old list l[0:2] # a new list that contains only the first two items of the old list l[0:-1] # a new list that contains all the items of the old list, except the last l[0:len(l)-1] # same as above but less clear l[0:-2] # a new list that contains all the items of the old list, except the last two l[0:len(l)-2] # same as above but less clear l[1:-1] # a new list with first and last item of the original list removed l[-2:] # a list that contains the last two items of the original list l[0::2] # odd numbers l[1::2] # even numbers l[2::3] # multiples of 3 If rules to get items are more complex, you'll use a list comprehension instead of a slice, but it's another subjet. That's what I use in my second join example. A: You don't want to use join for that. If you just want to print some bits of a list, then specify the ones you want directly: print '%s %s %s %s' % (line[0], line[1], line[4], line[6]) A: Assuming that the line variable should contain a line of cells, separated by commas... You can use map for that: line = "1,2,3,4,5,6" cells = line.split(",") indices=[0,1,4,6] selected_elements = map( lambda i: cells[i], indices ) print ",".join(selected_elements) The map function will do the on-the-fly function for each of the indices in the list argument. (Reorder to your liking) A: You could use the following using list comprehension : indices = [0,1,4,6] Ipadd = string.join([line[i] for i in xrange(len(line)) if i in indices]) Note : You could also use : Ipadd = string.join([line[i] for i in indices]) but you will need a sorted list of indices without repetition of course. A: Answer to the second question: If your string is contained in myLine, just do: myLline = myLine[:-1] to remove the last character. Or you could also use rstrip(): myLine = myLine.rstrip("'") A: l = [] l.extend(line[0:2]) l.append(line[5]) # fourth field l.append(line[7]) # sixth field string.join(l) Alternatively "{l[0]} {l[1]} {l[4]} {l[5]}".format(l=line) Please see PEP 3101 and stop using the % operator for string formatting. A: >>> token = ':' >>> s = '1:2:3:4:5:6:7:8:9:10' >>> sp = s.split(token) >>> token.join(filter(bool, map(lambda i: i in [0,2,4,6] and sp[i] or False, range(len(sp))))) '1:3:5:7'
Extract certain elements from a list
I have no clue about Python and started to use it on some files. I managed to find out how to do all the things that I need, except for 2 things. 1st >>>line = ['0', '1', '2', '3', '4', '5', '6'] >>>#prints all elements of line as expected >>>print string.join(line) 0 1 2 3 4 5 6 >>>#prints the first two elements as expected >>>print string.join(line[0:2]) 0 1 >>>#expected to print the first, second, fourth and sixth element; >>>#Raises an exception instead >>>print string.join(line[0:2:4:6]) SyntaxError: invalid syntax I want this to work similar to awk '{ print $1 $2 $5 $7 }'. How can I accomplish this? 2nd how can I delete the last character of the line? There is an additional ' that I don't need.
[ "Provided the join here is just to have a nice string to print or store as result (with a coma as separator, in the OP example it would have been whatever was in string).\nline = ['A', 'B', 'C', 'D', 'E', 'F', 'G']\n\nprint ','.join (line[0:2])\n\nA,B\nprint ','.join (line[i] for i in [0,1,2,4,5,6])\n\nA,B,C,E,F,G\...
[ 5, 2, 2, 2, 1, 1, 1 ]
[]
[]
[ "join", "python" ]
stackoverflow_0003529103_join_python.txt
Q: Python regex, how-to group an item within a regex I'm having trouble creating a regex. Here is a sample of the text on which the regex should work: <b>Additional Equipment Items</b> <br> 40001 <br> 1 Battery Marathon L (8 cells type L6V110) <br> 40002 <br> What I now want to select is >>1<< and >>Battery Marathon L (8 cells type L6V110)<<. Therefore I have produced the following Regex: found = re.findall('<b>.*Items\s*<\/b>\s*<br>(?:\s*[1-4]0[0-9][0-9][0-9] <br>\s*(\d*) (.*) <br>)*', content) Seems like the outer regex does match, but the inner groups are empty :( Any suggestions?! A: Okay I sometimes just hate Regex. Some whitespaces owned me... Here is the solution: <b>.*Items\s*<\/b>\s*<br>(?:\s*[1-4]0[0-9][0-9][0-9] <br>\s*(\d*)\s*(.*) <br>)
Python regex, how-to group an item within a regex
I'm having trouble creating a regex. Here is a sample of the text on which the regex should work: <b>Additional Equipment Items</b> <br> 40001 <br> 1 Battery Marathon L (8 cells type L6V110) <br> 40002 <br> What I now want to select is >>1<< and >>Battery Marathon L (8 cells type L6V110)<<. Therefore I have produced the following Regex: found = re.findall('<b>.*Items\s*<\/b>\s*<br>(?:\s*[1-4]0[0-9][0-9][0-9] <br>\s*(\d*) (.*) <br>)*', content) Seems like the outer regex does match, but the inner groups are empty :( Any suggestions?!
[ "Okay I sometimes just hate Regex. Some whitespaces owned me...\nHere is the solution:\n<b>.*Items\\s*<\\/b>\\s*<br>(?:\\s*[1-4]0[0-9][0-9][0-9] <br>\\s*(\\d*)\\s*(.*) <br>)\n\n" ]
[ 0 ]
[]
[]
[ "grouping", "python", "regex" ]
stackoverflow_0003528640_grouping_python_regex.txt
Q: Replace a pattern in python How to replace the pattern in the string with decoded_str=" Name(++info++)Age(++info++)Adress of the emp(++info++)" The first pattern "(++info++)" needs to replaced with (++info a++) The second pattern "(++info++)" needs to replaced with (++info b++) The third pattern "(++info++)" needs to replaced with (++info c++) If there many more then it should be replaced accordingly A: This should be simple enough: for character in range(ord('a'), ord('z')): if "(++info++)" not in decoded_str: break decoded_str = decoded_str.replace("(++info++)", "(++info {0}++)".format(chr(character)), 1) print decoded_str It has the added benefit of stopping at 'z'. If you want to wrap around: import itertools for character in itertools.cycle(range(ord('a'), ord('z'))): if "(++info++)" not in decoded_str: break decoded_str = decoded_str.replace("(++info++)", "(++info {0}++)".format(chr(character)), 1) print decoded_str And just for fun, a one-liner, and O(n): dstr = "".join(x + "(++info {0}++)".format(chr(y)) for x, y in zip(dstr.split("(++info++)"), range(ord('a'), ord('z'))))[:-len("(++info a++)")] A: import string decoded_str = " Name(++info++)Age(++info++)Adress of the emp(++info++)" s = decoded_str.replace('++info++', '++info %s++') s % tuple(i for i in string.ascii_lowercase[:s.count('%s')]) A: Here is a rather ugly yet pragmatic solution: import string decoded_str = " Name(++info++)Age(++info++)Adress of the emp(++info++)" letters = list(string.lowercase) token = "(++info++)" rep_token = "(++info %s++)" i = 0 while (token in decoded_str): decoded_str = decoded_str.replace(token, rep_token % letters[i], 1) i += 1 print decoded_str A: Here's a quick hack to do it: string=" Name(++info++)Age(++info++)Adress of the emp(++info++)" def doit(s): import string allTheLetters = list(string.lowercase) i=0 s2 = s.replace("++info++","++info "+allTheLetters[i]+"++",1) while (s2!=s): s=s2 i=i+1 s2 = s.replace("++info++","++info "+allTheLetters[i]+"++",1) return s Note that performance is probably not very great. A: >>> import re >>> rx = re.compile(r'\(\+\+info\+\+\)') >>> s = "Name(++info++)Age(++info++)Adress of the emp(++info++)" >>> atoz = iter("abcdefghijklmnopqrstuvwxyz") >>> rx.sub(lambda m: '(++info ' + next(atoz) + '++)', s) 'Name(++info a++)Age(++info b++)Adress of the emp(++info c++)' A: import re, string decoded_str=" Name(++info++)Age(++info++)Adress of the emp(++info++)" sub_func=('(++info %s++)'%c for c in '.'+string.ascii_lowercase).send sub_func(None) print re.sub('\(\+\+info\+\+\)', sub_func, decoded_str) A: from itertools import izip import string decoded_str=" Name(++info++)Age(++info++)Adress of the emp(++info++)" parts = iter(decoded_str.split("(++info++)")) first_part = next(parts) tags = iter(string.ascii_lowercase) encoded_str=first_part+"".join("(++info %s++)%s"%x for x in izip(tags, parts)) print encoded_str A: decoded_str=" Name(++info++)Age(++info++)Adress of the emp(++info++)" import re for i, f in enumerate(re.findall(r"\(\+\+info\+\+\)",decoded_str)): decoded_str = re.sub(r"\(\+\+info\+\+\)","(++info %s++)"%chr(97+i),decoded_str,1) print decoded_str
Replace a pattern in python
How to replace the pattern in the string with decoded_str=" Name(++info++)Age(++info++)Adress of the emp(++info++)" The first pattern "(++info++)" needs to replaced with (++info a++) The second pattern "(++info++)" needs to replaced with (++info b++) The third pattern "(++info++)" needs to replaced with (++info c++) If there many more then it should be replaced accordingly
[ "This should be simple enough:\nfor character in range(ord('a'), ord('z')):\n if \"(++info++)\" not in decoded_str:\n break\n decoded_str = decoded_str.replace(\"(++info++)\", \"(++info {0}++)\".format(chr(character)), 1)\n\nprint decoded_str\n\nIt has the added benefit of stopping at 'z'. If you want ...
[ 4, 3, 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003528545_python.txt
Q: Google Docs API and Python: How to change the owner of a document? I am using the gdata-python library to perform a number of operations via the Google Docs API. This library uses version 2 of the protocol, which does not support changing the ownership of a document. Has anyone managed to find a successful workaround which lets them change the owner of a document using the version 2 API? One idea I thought of was to 'make a copy' of the document in to the new account, which would duplicate the ACL as well. Alternatively, has anyone got any advice on how to use version 3 of the API from Python? The gdata library won't work - perhaps there is a more manual way of accessing the API? A: I'm not sure if it is good form to answer my own question, or just add a comment. It turns out that a little bit more RTFM'ing was required - http://code.google.com/intl/nl-NL/apis/documents/docs/3.0/developers_guide_python.html#ACLRetrieve This document is incompatible with version 2 of the API - it turns out I was trying to use a mixture of calls, which obviously didn't work.
Google Docs API and Python: How to change the owner of a document?
I am using the gdata-python library to perform a number of operations via the Google Docs API. This library uses version 2 of the protocol, which does not support changing the ownership of a document. Has anyone managed to find a successful workaround which lets them change the owner of a document using the version 2 API? One idea I thought of was to 'make a copy' of the document in to the new account, which would duplicate the ACL as well. Alternatively, has anyone got any advice on how to use version 3 of the API from Python? The gdata library won't work - perhaps there is a more manual way of accessing the API?
[ "I'm not sure if it is good form to answer my own question, or just add a comment.\nIt turns out that a little bit more RTFM'ing was required - http://code.google.com/intl/nl-NL/apis/documents/docs/3.0/developers_guide_python.html#ACLRetrieve\nThis document is incompatible with version 2 of the API - it turns out I...
[ 1 ]
[]
[]
[ "gdata", "python" ]
stackoverflow_0003519827_gdata_python.txt
Q: Find the largest image dimensions from list of images I have a list (the paths) of images saved locally. How can I find the largest image from these? I'm not referring to the file size but the dimensions. All the images are in common web-compatible formats — JPG, GIF, PNG, etc. Thank you. A: Assuming that the "size" of an image is its area : from PIL import Image def get_img_size(path): width, height = Image.open(path).size return width*height largest = max(the_paths, key=get_img_size) A: Use Python Imaging Library (PIL). Something like this: from PIL import Image filenames = ['/home/you/Desktop/chstamp.jpg', '/home/you/Desktop/something.jpg'] sizes = [Image.open(f, 'r').size for f in filenames] max(sizes) Update (Thanks delnan): Replace last two lines of above snippet with: max(Image.open(f, 'r').size for f in filenames) Update 2 The OP wants to find the index of the file corresponding to the largest dimensions. This requires some help from numpy. See below: from numpy import array image_array = array([Image.open(f, 'r').size for f in filenames]) print image_array.argmax() A: You will need PIL. from PIL import Image img = Image.open(image_file) width, height = img.size Once you have the size of a single image, checking the whole list and selecting the bigger one is not the problem.
Find the largest image dimensions from list of images
I have a list (the paths) of images saved locally. How can I find the largest image from these? I'm not referring to the file size but the dimensions. All the images are in common web-compatible formats — JPG, GIF, PNG, etc. Thank you.
[ "Assuming that the \"size\" of an image is its area :\nfrom PIL import Image\n\ndef get_img_size(path):\n width, height = Image.open(path).size\n return width*height\n\nlargest = max(the_paths, key=get_img_size)\n\n", "Use Python Imaging Library (PIL). Something like this:\nfrom PIL import Image\nfilenames ...
[ 7, 6, 0 ]
[ "import Image\n\nsrc = Image.open(image)\nsize = src.size \n\nsize will be a tuple with the image dimensions (witdh and height)\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0003529552_python.txt
Q: Why do Python programmers still use old-style division? I started using Python in 2001. I loved the simplicity of the language, but one feature that annoyed the heck out of me was the / operator, which would bite me in subtle places like def mean(seq): """ Return the arithmetic mean of a list (unless it just happens to contain all ints) """ return sum(seq) / len(seq) Fortunately, PEP 238 had already been written, and as soon as I found about the new from __future__ import division statement, I started religiously adding it to every .py file I wrote. But here it is nearly 9 years later and I still frequently see Python code samples that use / for integer division. Is // not a widely-known feature? Or is there actually a reason to prefer the old way? A: I think // for truncation is reasonably well known, but people are reluctant to "import from the future" in every module they write. The classic approach (using float(sum(seq)) and so on to get a float result, int(...) to truncate an otherwise-float division) is the one you'd use in C++ (and with slightly different syntax in C, Java, Fortran, ...), as well as "natively" in every Python release through 2.7 included, so it's hardly surprising if a lot of people are very used to, and comfortable with, said "classic approach". When Python 3 becomes more widespread and widely used than Python 2, I expect things to change. A: You can change the behaviour of / for the whole interpreter if you prefer, so it's not necessary to import from future in every module $ python -c "print 1/2" 0 $ python -Qwarn -c "print 1/2" -c:1: DeprecationWarning: classic int division 0 $ python -Qnew -c "print 1/2" 0.5 A: To me it's always made sense that dividing using ints gives and int result in a language that doesn't normally do on the fly type conversions.
Why do Python programmers still use old-style division?
I started using Python in 2001. I loved the simplicity of the language, but one feature that annoyed the heck out of me was the / operator, which would bite me in subtle places like def mean(seq): """ Return the arithmetic mean of a list (unless it just happens to contain all ints) """ return sum(seq) / len(seq) Fortunately, PEP 238 had already been written, and as soon as I found about the new from __future__ import division statement, I started religiously adding it to every .py file I wrote. But here it is nearly 9 years later and I still frequently see Python code samples that use / for integer division. Is // not a widely-known feature? Or is there actually a reason to prefer the old way?
[ "I think // for truncation is reasonably well known, but people are reluctant to \"import from the future\" in every module they write.\nThe classic approach (using float(sum(seq)) and so on to get a float result, int(...) to truncate an otherwise-float division) is the one you'd use in C++ (and with slightly diffe...
[ 8, 2, 1 ]
[]
[]
[ "integer_division", "python" ]
stackoverflow_0003528325_integer_division_python.txt
Q: Issue with Django Inline form I have attached TestInline in the FoobarAdmin, this thing works well but i want logged in user to be pre-populated for the added_by field from django.contrib import admin from django.contrib.auth.models import User class Test(models.Model): description = models.TextField() added_on = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(User, related_name='added_by',) class TestInline(admin.TabularInline): model = Test extra = 1 class FoobarAdmin(admin.ModelAdmin): inlines = [TestInline,] admin.site.register(Foobar, FoobarAdmin) Please let me know if its possible to have user prepopulated for the added_by field A: See prepopulated_fields in the admin docs. If I understand what you need correctly, I think this article by James Bennett tackles the issue pretty well. Finally (in case you haven't seen them), there are two other informative posts on prepopulating admin fields.
Issue with Django Inline form
I have attached TestInline in the FoobarAdmin, this thing works well but i want logged in user to be pre-populated for the added_by field from django.contrib import admin from django.contrib.auth.models import User class Test(models.Model): description = models.TextField() added_on = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(User, related_name='added_by',) class TestInline(admin.TabularInline): model = Test extra = 1 class FoobarAdmin(admin.ModelAdmin): inlines = [TestInline,] admin.site.register(Foobar, FoobarAdmin) Please let me know if its possible to have user prepopulated for the added_by field
[ "See prepopulated_fields in the admin docs.\nIf I understand what you need correctly, I think this article by James Bennett tackles the issue pretty well.\nFinally (in case you haven't seen them), there are two other informative posts on prepopulating admin fields.\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003529806_django_django_admin_python.txt
Q: Django ORM Query: getting "has many" relation objects There is a model: class DomainPosition(models.Model): domain = models.ForeignKey(Domain) keyword = models.ForeignKey(Keyword) date = models.DateField() position = models.IntegerField() class Meta: ordering = ['domain', 'keyword'] How to get the positions records for a template if for each domain I want to display a next table (figures in the table are position values): +----------+--------+--------+-------+-------- | keyword | date1 | date2 | date3 | ... +----------+--------+--------+-------+-------- | keyword1 | 2 | 6 | 7 | ... +----------+--------+--------+-------+-------- | keyword2 | 4 | 12 | 5 | ... +----------+--------+--------+-------+-------- | keyword3 | 6 | 3 | 9 | ... +----------+--------+--------+-------+-------- where views.py: def show_domain_history(request, domain_name): domain = Domain.objects.filter(name__contains=domain_name) if not domain: return HttpResponseRedirect('/') else: # positions = ... variables = RequestContext(request, { 'domain': domain[0].name, 'positions': positions, }) return render_to_response('history.html', variables) A: def show_domain_history(request, domain_name): domain = Domain.objects.filter(name__contains=domain_name) if not domain: return HttpResponseRedirect('/') else: variables = {'domain': domain } return render_to_response('history.html', variables) now in the template you can iterate through this as: {% for dom in domain %} name: {{ dom.name }} {% for item in dom.domainposition_set %} date: item.date position: item.position {% endfor %} {% endfor %} A: Since you have a foreign key from DomainPosition to Domain, you should be able to get the set of all domain positions that reference a particular domain dom with dom.domainposition_set.all(). You can then build your table by iterating over this list of domain positions in your template.
Django ORM Query: getting "has many" relation objects
There is a model: class DomainPosition(models.Model): domain = models.ForeignKey(Domain) keyword = models.ForeignKey(Keyword) date = models.DateField() position = models.IntegerField() class Meta: ordering = ['domain', 'keyword'] How to get the positions records for a template if for each domain I want to display a next table (figures in the table are position values): +----------+--------+--------+-------+-------- | keyword | date1 | date2 | date3 | ... +----------+--------+--------+-------+-------- | keyword1 | 2 | 6 | 7 | ... +----------+--------+--------+-------+-------- | keyword2 | 4 | 12 | 5 | ... +----------+--------+--------+-------+-------- | keyword3 | 6 | 3 | 9 | ... +----------+--------+--------+-------+-------- where views.py: def show_domain_history(request, domain_name): domain = Domain.objects.filter(name__contains=domain_name) if not domain: return HttpResponseRedirect('/') else: # positions = ... variables = RequestContext(request, { 'domain': domain[0].name, 'positions': positions, }) return render_to_response('history.html', variables)
[ "def show_domain_history(request, domain_name):\n domain = Domain.objects.filter(name__contains=domain_name)\n if not domain:\n return HttpResponseRedirect('/')\n else:\n variables = {'domain': domain }\n return render_to_response('history.html', variables)\n\nnow in the template you c...
[ 1, 0 ]
[]
[]
[ "django", "django_models", "django_orm", "python" ]
stackoverflow_0003528783_django_django_models_django_orm_python.txt
Q: Multi processing subprocess I'm new to subprocess module of python, currently my implementation is not multi processed. import subprocess,shlex def forcedParsing(fname): cmd = 'strings "%s"' % (fname) #print cmd args= shlex.split(cmd) try: sp = subprocess.Popen( args, shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE ) out, err = sp.communicate() except OSError: print "Error no %s Message %s" % (OSError.errno,OSError.message) pass if sp.returncode== 0: #print "Processed %s" %fname return out res=[] for f in file_list: res.append(forcedParsing(f)) my questions: Is sp.communicate a good way to go? should I use poll? if I use poll I need a sperate process which monitors if process finished right? should I fork at the for loop? A: 1) subprocess.communicate() seems the right option for what you are trying to do. And you don't need to poll the proces, communicate() returns only when it's finished. 2) you mean forking to paralellize work? take a look at multiprocessing (python >= 2.6). Running parallel processes using subprocess is of course possible but it's quite a work, you cannot just call communicate(), which is blocking. About your code: cmd = 'strings "%s"' % (fname) args= shlex.split(cmd) Why not simply? args = ["strings", fname] As for this ugly pattern: res=[] for f in file_list: res.append(forcedParsing(f)) You should use list-comprehensions whenever possible: res = [forcedParsing(f) for f in file_list] A: About question 2: forking at the for loop will mostly speed things up if the script's supposed to run on a system with multiple cores/processors. It will consume more memory, though, and will stress IO harder. There will be a sweet spot somewhere that depends on the number of files in file_list, but only benchmarking on a realistic target system can tell you where it is. If you find that number, you could add an if len(file_list) > <your number>: with optional fork() 'ing [Edit: rather, as @tokland say's via multiprocessing if it's available on your Python version (2.6+)] that chooses the most efficient strategy on a per-job basis. Read about Python profiling here: http://docs.python.org/library/profile.html If you're on Linux, you can also run time: http://linuxmanpages.com/man1/time.1.php A: There are several warnings in the subprocess documentation that advise you to use communicate to avoid problems with a processes blocking, so it would be a good idea to use that.
Multi processing subprocess
I'm new to subprocess module of python, currently my implementation is not multi processed. import subprocess,shlex def forcedParsing(fname): cmd = 'strings "%s"' % (fname) #print cmd args= shlex.split(cmd) try: sp = subprocess.Popen( args, shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE ) out, err = sp.communicate() except OSError: print "Error no %s Message %s" % (OSError.errno,OSError.message) pass if sp.returncode== 0: #print "Processed %s" %fname return out res=[] for f in file_list: res.append(forcedParsing(f)) my questions: Is sp.communicate a good way to go? should I use poll? if I use poll I need a sperate process which monitors if process finished right? should I fork at the for loop?
[ "1) subprocess.communicate() seems the right option for what you are trying to do. And you don't need to poll the proces, communicate() returns only when it's finished.\n2) you mean forking to paralellize work? take a look at multiprocessing (python >= 2.6). Running parallel processes using subprocess is of course ...
[ 3, 2, 1 ]
[]
[]
[ "fork", "multithreading", "process", "python", "subprocess" ]
stackoverflow_0003530806_fork_multithreading_process_python_subprocess.txt
Q: Python auth_handler not working for me I've been reading about Python's urllib2's ability to open and read directories that are password protected, but even after looking at examples in the docs, and here on StackOverflow, I can't get my script to work. import urllib2 # Create an OpenerDirector with support for Basic HTTP Authentication... auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm=None, uri='https://webfiles.duke.edu/', user='someUserName', passwd='thisIsntMyRealPassword') opener = urllib2.build_opener(auth_handler) # ...and install it globally so it can be used with urlopen. urllib2.install_opener(opener) socks = urllib2.urlopen('https://webfiles.duke.edu/?path=/afs/acpub/users/a') print socks.read() socks.close() When I print the contents, it prints the contents of the login screen that the url I'm trying to open will redirect you to. Anyone know why this is? A: auth_handler is only for basic HTTP authentication. The site here contains a HTML form, so you'll need to submit your username/password as POST data. I recommend you using the mechanize module that will simplify the login for you. Quick example: import mechanize browser = mechanize.Browser() browser.open('https://webfiles.duke.edu/?path=/afs/acpub/users/a') browser.select_form(nr=0) browser.form['user'] = 'username' browser.form['pass'] = 'password' req = browser.submit() print req.read()
Python auth_handler not working for me
I've been reading about Python's urllib2's ability to open and read directories that are password protected, but even after looking at examples in the docs, and here on StackOverflow, I can't get my script to work. import urllib2 # Create an OpenerDirector with support for Basic HTTP Authentication... auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm=None, uri='https://webfiles.duke.edu/', user='someUserName', passwd='thisIsntMyRealPassword') opener = urllib2.build_opener(auth_handler) # ...and install it globally so it can be used with urlopen. urllib2.install_opener(opener) socks = urllib2.urlopen('https://webfiles.duke.edu/?path=/afs/acpub/users/a') print socks.read() socks.close() When I print the contents, it prints the contents of the login screen that the url I'm trying to open will redirect you to. Anyone know why this is?
[ "auth_handler is only for basic HTTP authentication. The site here contains a HTML form, so you'll need to submit your username/password as POST data.\nI recommend you using the mechanize module that will simplify the login for you.\nQuick example:\nimport mechanize\n\nbrowser = mechanize.Browser()\n\nbrowser.open(...
[ 3 ]
[]
[]
[ "authentication", "python", "urllib2", "urlopen" ]
stackoverflow_0003530910_authentication_python_urllib2_urlopen.txt
Q: Suds Performance - client.factory.create() takes more than 2 minutes I'm using Suds to send/receive SOAP messages in Python. It is taking an insanely long time to create an object to send via the soap envelope. client = Client(wsdldict['Contact'], faults=True, headers=session) #takes ~5 seconds lq1=client.factory.create("ns1:ListOfContactQuery") #takes ~130 seconds The WSDL file is fairly large (1MB) but I do not know if that is the issue or not. Does Suds performance breakdown at a certain point? A: SUDS performance does breakdown on large WSDL files. I have experienced this same thing before with the Citrix NetScaler SOAP API. If you are able to filter your WSDL into a subset of required commands, store the file on disk and load it locally, or make use of SUDS' caching functionality, you can dramatically increase this processing time when creating a new client.
Suds Performance - client.factory.create() takes more than 2 minutes
I'm using Suds to send/receive SOAP messages in Python. It is taking an insanely long time to create an object to send via the soap envelope. client = Client(wsdldict['Contact'], faults=True, headers=session) #takes ~5 seconds lq1=client.factory.create("ns1:ListOfContactQuery") #takes ~130 seconds The WSDL file is fairly large (1MB) but I do not know if that is the issue or not. Does Suds performance breakdown at a certain point?
[ "SUDS performance does breakdown on large WSDL files. I have experienced this same thing before with the Citrix NetScaler SOAP API. \nIf you are able to filter your WSDL into a subset of required commands, store the file on disk and load it locally, or make use of SUDS' caching functionality, you can dramatically i...
[ 6 ]
[]
[]
[ "python", "suds", "web_services" ]
stackoverflow_0003531537_python_suds_web_services.txt
Q: How to refer to "\" sign in python string I have problem with refering to special symbol in string: I have: path='C:\dir\dir1\dir2\filename.doc' and I want filename. When I try: filename=path[path.rfind("\"):-4] then interpreter says it's an error line right from "\" since is treated as a comment. A: You can use "\\", technically it would be better to use os.path.sep if you insist on using backslashes. But better yet, use / in your paths, it works fine on Windows Python has builtin functions to manipulate paths. Note that you need to double the backslashes if you still prefer them to forwardslashes >>> import os >>> path='C:\\dir\\dir1\\dir2\\filename.doc' >>> os.path.splitext(os.path.basename(path)) ('filename', '.doc') and using forwardslashes >>> path='C:/dir/dir1/dir2/filename.doc' >>> os.path.splitext(os.path.basename(path)) ('filename', '.doc') A: Either escape it as "\\" or use raw strings like so: r"\". A: Escape it: filename=path[path.rfind("\\"):-4] or better yet, use basename - part of Python's os.path library: from os.path import basename basename(path) From the manual for basename: Return the base name of pathname path. This is the second half of the pair returned by split(path). Note that the result of this function is different from the Unix basename program; where basename for '/foo/bar/' returns 'bar', the basename() function returns an empty string (''). A: You can type double the : "\". However to split the filename out of Windows filename, use partition as os.path.split only works with /: >>> path=r'C:\dir\dir1\dir2\filename.doc' >>> print path.rpartition('\\')[-1] filename.doc A: There is something about this in the FAQ: Why can’t raw strings (r-strings) end with a backslash? If you’re trying to build Windows pathnames, note that all Windows system calls accept forward slashes too: f = open("/mydir/file.txt") # works fine! If you’re trying to build a pathname for a DOS command, try e.g. one of dir = r"\this\is\my\dos\dir" "\\" dir = r"\this\is\my\dos\dir\ "[:-1] dir = "\\this\\is\\my\\dos\\dir"
How to refer to "\" sign in python string
I have problem with refering to special symbol in string: I have: path='C:\dir\dir1\dir2\filename.doc' and I want filename. When I try: filename=path[path.rfind("\"):-4] then interpreter says it's an error line right from "\" since is treated as a comment.
[ "You can use \"\\\\\", technically it would be better to use os.path.sep if you insist on using backslashes. But better yet, use / in your paths, it works fine on Windows\nPython has builtin functions to manipulate paths. Note that you need to double the backslashes if you still prefer them to forwardslashes\n>>> i...
[ 12, 2, 1, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003531430_python_string.txt
Q: Python dictionary reference to neighbor dictionary element I'm trying to create something following: dictionary = { 'key1': ['val1','val2'], 'key2': @key1 } where @key1 is reference to dictionary['key1']. Thank You in advance. A: Use a new class: class DictRef(object): def __init__(self, d, key): self.d, self.key = d, key d = {} d.update({ 'key1': ['val1','val2'], 'key2': DictRef(d, 'key1') }) Note the odd syntax because you have no way to know inside of which dictionary you are creating DictRef. A: I'd expand Aaron Digulla's version. What he has now is replicated here: class DictRef(object): def __init__(self, d, key): self.d, self.key = d, key d = {} d.update({ 'key1': ['val1','val2'], 'key2': DictRef(d, 'key1') }) I assume he wishes to replicate true reference semantics, so that accessing 'key2' will always give you a way to get to whatever 'key1' has as a value. the problem is while d['key1'] is a list, d['key2'] is a DictRef. So to get the "value" of 'key1' all you need to do is d['key1'], but for 'key2' you must do d[d['key2'].key]. Furthermore, you can't have a reference to a reference that works sanely, it would become d[d[d['key2'].key].key]. And how do you differentiate between a reference and a regular value? Probably through typechecking with isinstance(v, DictReference) (ew). So I have a proposal to fix all of this. Personally, I don't understand why true reference semantics are necessary. If they appear necessary, they can be made unnecessary by restructuring the problem, or the solution to the problem. It may even be that they were never necessary, and a simple d.update(key2=d['key1']) would have solved the issue. Anyway, to the proposal: class DictRef(object): def __init__(self, d, key): self.d = d self.key = key def value(self): return self.d[self.key].value() class DictVal(object): def __init__(self, value): self._value = value def value(self): return self._value d = {} d.update( key1=DictVal(['val1', 'val2']), key2=DictRef(d, 'key1') ) Now, in order to get the value of any key, whether it's a reference or not, one would simply do d[k].value(). If there are references to references, they will be dereferenced in a chain correctly. If they form a really long or infinite chain, Python will fail with a RuntimeError for excessive recursion.
Python dictionary reference to neighbor dictionary element
I'm trying to create something following: dictionary = { 'key1': ['val1','val2'], 'key2': @key1 } where @key1 is reference to dictionary['key1']. Thank You in advance.
[ "Use a new class:\nclass DictRef(object):\n def __init__(self, d, key): self.d, self.key = d, key\n\nd = {}\nd.update({\n 'key1': ['val1','val2'],\n 'key2': DictRef(d, 'key1')\n})\n\nNote the odd syntax because you have no way to know inside of which dictionary you are creating DictRef.\n", "I'd expand A...
[ 4, 4 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003531198_dictionary_python.txt
Q: Most optimal way to reverse search list of similar strings I have a list of data that includes both command strings as well as the alphabet, upper and lowercase, totaling to 512+ (including sub-lists) strings. I want to parse the input data, but i cant think of any way to do it properly other than starting from the largest possible command size and cutting it down until i find a command that is the same as the string and then output the location of the command, but that takes forever. any other way i can think of will cause overlapping. im doing this in python say: L = ['a', 'b',['aa','bb','cc'], 'c'] for 'bb' the output would be '0201' and 'c' would be '03' so how should i do this? A: It sounds like you're searching through the list for every substring. How about you built a dict to lookup the keys. Of cause you still have to start searching at the longest subkey. L = ['a', 'b',['aa','bb','cc'], 'c'] def lookups( L ): """ returns `item`, `code` tuples """ for i, item in enumerate(L): if isinstance(item, list): for j, sub in enumerate(item): yield sub, "%02d%02d" % (i,j) else: yield item, "%02d" % i You could then lookup substrings with: lookupdict = dict(lookups(L)) print lookupdict['bb'] # but you have to do 'bb' before trying 'b' ... But if the key length is not just 1 or 2, it might also make sense to group the items into separate dicts where each key has the same length. A: If you must use this data structure: from collections import MutableSequence def scanList( command, theList ): for i, elt in enumerate( theList ): if elt == command: return ( i, None ) if isinstance( elt, MutableSequence ): for j, elt2 in enumerate( elt ): if elt2 == command: return i, j L = ['a', 'b',['aa','bb','cc'], 'c'] print( scanList( "bb", L ) ) # (2, 1 ) print( scanlist( "c", L ) ) # (3, None ) BUT This is a bad data structure. Are you able to get this data in a nicer form?
Most optimal way to reverse search list of similar strings
I have a list of data that includes both command strings as well as the alphabet, upper and lowercase, totaling to 512+ (including sub-lists) strings. I want to parse the input data, but i cant think of any way to do it properly other than starting from the largest possible command size and cutting it down until i find a command that is the same as the string and then output the location of the command, but that takes forever. any other way i can think of will cause overlapping. im doing this in python say: L = ['a', 'b',['aa','bb','cc'], 'c'] for 'bb' the output would be '0201' and 'c' would be '03' so how should i do this?
[ "It sounds like you're searching through the list for every substring. How about you built a dict to lookup the keys. Of cause you still have to start searching at the longest subkey.\nL = ['a', 'b',['aa','bb','cc'], 'c']\n\ndef lookups( L ):\n \"\"\" returns `item`, `code` tuples \"\"\"\n for i, item in enum...
[ 2, 1 ]
[]
[]
[ "arrays", "indexing", "multidimensional_array", "python", "reverse" ]
stackoverflow_0003531669_arrays_indexing_multidimensional_array_python_reverse.txt
Q: SelfReferenceProperty question I am trying to use google appengine. I have this model: def Human(db.Model): name = db.StringProperty() friends = db.SelfReferenceProperty() This Human has more than one friend. So, how to handle this with google appengine? A: For simple many-to-many relationships, use a ListProperty with a list of keys. If you need to store additional metadata, give the model its own relationship, e.g. Friendship. Examples of both can be found @ http://code.google.com/appengine/articles/modeling.html
SelfReferenceProperty question
I am trying to use google appengine. I have this model: def Human(db.Model): name = db.StringProperty() friends = db.SelfReferenceProperty() This Human has more than one friend. So, how to handle this with google appengine?
[ "For simple many-to-many relationships, use a ListProperty with a list of keys.\nIf you need to store additional metadata, give the model its own relationship, e.g. Friendship.\nExamples of both can be found @ http://code.google.com/appengine/articles/modeling.html\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003531936_google_app_engine_python.txt
Q: Sorted quantile mean via Rpy The real goal here is to find the quantile means (or sums, or median, etc.) in Python. Since I'm not a power user of Python but have used R for a while, my chosen route is via Rpy. However, I ran into the problem that the returned list of means are not correspondent to the order of the quantiles. In particular, I have the followings in R: > a = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) > b = c(2, 4, 20, 40, 200, 400, 2000, 4000, 20000, 40000) > prob = seq(0,5)/5 > br = quantile(a,prob) > rcut = cut(a, br, include.lowest = TRUE) > quintile_means = tapply(b, rcut, mean) > quintile_means [1,2.8] (2.8,4.6] (4.6,6.4] (6.4,8.2] (8.2,10] 3 30 300 3000 30000 which is all very good. However, if I translate the code into Rpy, I got >>> import rpy >>> from rpy import r >>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> b = [2, 4, 20, 40, 200, 400, 2000, 4000, 20000, 40000] >>> prob = [ x / 5.0 for x in range(6)] >>> br = r.quantile(a, prob) >>> rcut = r.cut(a, br, include_lowest=r.TRUE) >>> quintile_means = r.tapply(b, rcut, r.mean) >>> print quintile_means [30.0, 300.0, 3000.0, 30000.0, 3.0] Note the final list is mis-ordered (we know it because a and b are both ordered in this case). In general, I just have no way to recover the correct order from the lowest to highest quantile in Rpy. Any suggestions? In addition (not in substitution, as I'd like to know the answer to the above question), if you can suggest a way to directly perform the analysis in python, that will be great too. (I don't have numpy or scipy installed.) Thx! EDIT: To clarify, a and b are paired but not necessarily ordered. For example, a is the size of eyes and b is the size of nose. I'm trying to find out that in the various quantiles of a, what are the means of the correspondent bs. Thanks. A: Try rpy2. With rpy2 >= 2.1.0, this could be: from rpy2.robjects.vectors import IntVector from rpy2.robjects.packages import importr base = importr('base') stats = importr('stats') a = IntVector((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) b = IntVector((2, 4, 20, 40, 200, 400, 2000, 4000, 20000, 40000)) prob = base.seq(0,5).ro / 5 br = stats.quantile(a,prob) rcut = base.cut(a, br, include_lowest = True) quintile_means = base.tapply(b, rcut, stats.mean) print(quintile_means) A: If you don't need labels (e.g: (8.2,10]) then you could call cut with labels=FALSE. This should keep order (and speed up your code for free). A: I just have no way to recover the correct order from the lowest to highest quantile in Rpy If sorting the list from the lowest to the highest solves your problem, try sorted(quintile_means).
Sorted quantile mean via Rpy
The real goal here is to find the quantile means (or sums, or median, etc.) in Python. Since I'm not a power user of Python but have used R for a while, my chosen route is via Rpy. However, I ran into the problem that the returned list of means are not correspondent to the order of the quantiles. In particular, I have the followings in R: > a = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) > b = c(2, 4, 20, 40, 200, 400, 2000, 4000, 20000, 40000) > prob = seq(0,5)/5 > br = quantile(a,prob) > rcut = cut(a, br, include.lowest = TRUE) > quintile_means = tapply(b, rcut, mean) > quintile_means [1,2.8] (2.8,4.6] (4.6,6.4] (6.4,8.2] (8.2,10] 3 30 300 3000 30000 which is all very good. However, if I translate the code into Rpy, I got >>> import rpy >>> from rpy import r >>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> b = [2, 4, 20, 40, 200, 400, 2000, 4000, 20000, 40000] >>> prob = [ x / 5.0 for x in range(6)] >>> br = r.quantile(a, prob) >>> rcut = r.cut(a, br, include_lowest=r.TRUE) >>> quintile_means = r.tapply(b, rcut, r.mean) >>> print quintile_means [30.0, 300.0, 3000.0, 30000.0, 3.0] Note the final list is mis-ordered (we know it because a and b are both ordered in this case). In general, I just have no way to recover the correct order from the lowest to highest quantile in Rpy. Any suggestions? In addition (not in substitution, as I'd like to know the answer to the above question), if you can suggest a way to directly perform the analysis in python, that will be great too. (I don't have numpy or scipy installed.) Thx! EDIT: To clarify, a and b are paired but not necessarily ordered. For example, a is the size of eyes and b is the size of nose. I'm trying to find out that in the various quantiles of a, what are the means of the correspondent bs. Thanks.
[ "Try rpy2.\nWith rpy2 >= 2.1.0, this could be:\nfrom rpy2.robjects.vectors import IntVector\nfrom rpy2.robjects.packages import importr\nbase = importr('base')\nstats = importr('stats')\n\na = IntVector((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))\nb = IntVector((2, 4, 20, 40, 200, 400, 2000, 4000, 20000, 40000))\nprob = base....
[ 4, 2, 0 ]
[]
[]
[ "python", "quantile", "r", "rpy2" ]
stackoverflow_0003530896_python_quantile_r_rpy2.txt
Q: Send keyboard event using subprocess I have two python scripts. First one is just a script waiting for user keyboard input. When user presses a key it prints a pressed key value. Second script calls first one through subprocess using Popen like this p = Popen('python first_script.py', shell=True, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT) print p.communicate(input="some value paased through")[0] I got it working when I send through string values. But I don't know how to send keyboard event and how to read it properly. A: subprocess per se has no facilities to "send keyboard events" (to the sub-process or to any other process). You need other aproaches, such as the one this article shows for Windows.
Send keyboard event using subprocess
I have two python scripts. First one is just a script waiting for user keyboard input. When user presses a key it prints a pressed key value. Second script calls first one through subprocess using Popen like this p = Popen('python first_script.py', shell=True, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT) print p.communicate(input="some value paased through")[0] I got it working when I send through string values. But I don't know how to send keyboard event and how to read it properly.
[ "subprocess per se has no facilities to \"send keyboard events\" (to the sub-process or to any other process). You need other aproaches, such as the one this article shows for Windows.\n" ]
[ 2 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0003531953_python_subprocess.txt
Q: Flipping bits in python Given an integer n , i want to toggle all bits in the binary representation of that number in the range say lower to upper. To do this i do the following [bit_string is a string containing 1's and 0's and is a binary representation of n] for i in range(lower,upper+1): n ^= (1 << len(bit_string)-1-i) #Toggle the ith bit Then , i also need to determine that given a range, say lower to upper,how many bits are set.My code to do that is as follows : number_of_ones = 0 for i in range(lower,upper+1): if(n & (1 << len(bit_string)-1-i)): #Check the ith bit number_of_ones+=1 But, if n is very large, i think these algorithms would be slow. Is there a way to make these two operations faster/more efficient ? Thank You A: For the "flipping", you can make a single bitmap (with ones in all positions of interest) and a single exclusive-or: n ^= ((1<<upper)-1)&~((1<<lower)-1) For bit-counts, once you isolate (n & mask) for the same "mask" as the above RHS, slicing it into e.g. 8-bit slices and looking up the 8-bit counts in a lookup table (just a simple list or array.array to prepare beforehand) is about the fastest approach. gmpy has some useful and speedy bit-manipulation and counting operations, esp. faster than Python's native offerings if you're dealing with very long bit strings (more than a machine word's worth, so in Python they'd be long instances). A: def bitflip(n,range): bitfliplen = range[1]-range[0] return n ^ ((2**bitfliplen-1) << (range[0])) Running: >>> a = 47727124L >>> b = bitflip(a,(5,10)) >>> print "a: {0:b}\nb: {1:b}".format(a,b) a: 10110110000100001000010100 b: 10110110000100000111110100 >>> A: For bit counting, once you've masked out the range you are interested in, see the bitCount() routine on the python BitManipulation wiki page which implements Brian Kernighan's scheme: def bitCount(int_type): count = 0 while(int_type): int_type &= int_type - 1 count += 1 return(count) A: I don't know python so I am just thinking this from a pure mathsy agorithmy point of view... It occurs to me that for the first part a more efficient method might be to construct a mask of the bits you want to switch first as an integer. To make life easy for me I'm going to assume that you are counting your lower and upper bounds from the least significant bit being 0 and the most significant being 31 (or whatever is appropriate for the length of an int in your case). If you want bits n to m (m>n) to be flipped then the binary representation of the number 2^(m+1)-2^n will have these bits set. Then do an XOR and you do all the swaps in one go. The computer should be abel to do these in one go probably rather than one per bit swap. As for the counting I'm not sure. There are ways to count the number of set bits in a number. I'm not sure if you get a gain in efficiency to use the above bitmask with an AND to 0 out all the bits you don't care about counting nad then use those algorithms or if you are best off modifying them to work for you. I dont' know how they work off the top of my head though. :)
Flipping bits in python
Given an integer n , i want to toggle all bits in the binary representation of that number in the range say lower to upper. To do this i do the following [bit_string is a string containing 1's and 0's and is a binary representation of n] for i in range(lower,upper+1): n ^= (1 << len(bit_string)-1-i) #Toggle the ith bit Then , i also need to determine that given a range, say lower to upper,how many bits are set.My code to do that is as follows : number_of_ones = 0 for i in range(lower,upper+1): if(n & (1 << len(bit_string)-1-i)): #Check the ith bit number_of_ones+=1 But, if n is very large, i think these algorithms would be slow. Is there a way to make these two operations faster/more efficient ? Thank You
[ "For the \"flipping\", you can make a single bitmap (with ones in all positions of interest) and a single exclusive-or:\nn ^= ((1<<upper)-1)&~((1<<lower)-1)\n\nFor bit-counts, once you isolate (n & mask) for the same \"mask\" as the above RHS, slicing it into e.g. 8-bit slices and looking up the 8-bit counts in a l...
[ 12, 1, 1, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0003532018_algorithm_python.txt
Q: Jython: Access singleton Java class (static) I cannot seem to get the syntax quite right for this: I have a Jython script and a Java application loaded into the same JVM (for testing). I need to access a particular part of the application through a Singleton class from the Jython script. How do I do this? Thanks EDIT: The set up is for automated testing, so assume that the Jython script already has access to the classes/classpath of the Java application. Let's say my Java application has a singleton class some.pkg.MySingleton .. how do I invoke MySingleton.getInstance() from my Jython script? A: Didn't this work? from some.pkg import MySingleton myInstance = MySingleton.getInstance() If that doesn't work, try this: (I'm not sure if this works) mySingletonClass = MySingleton(MySingleton) myInstance = mySingletonClass.getInstance()
Jython: Access singleton Java class (static)
I cannot seem to get the syntax quite right for this: I have a Jython script and a Java application loaded into the same JVM (for testing). I need to access a particular part of the application through a Singleton class from the Jython script. How do I do this? Thanks EDIT: The set up is for automated testing, so assume that the Jython script already has access to the classes/classpath of the Java application. Let's say my Java application has a singleton class some.pkg.MySingleton .. how do I invoke MySingleton.getInstance() from my Jython script?
[ "Didn't this work?\nfrom some.pkg import MySingleton\n\nmyInstance = MySingleton.getInstance()\n\nIf that doesn't work, try this: (I'm not sure if this works)\nmySingletonClass = MySingleton(MySingleton)\nmyInstance = mySingletonClass.getInstance()\n\n" ]
[ 1 ]
[]
[]
[ "java", "jython", "python", "singleton", "static" ]
stackoverflow_0003528397_java_jython_python_singleton_static.txt
Q: How do I ensure data integrity for objects in google app engine without using key names? I'm having a bit of trouble in Google App Engine ensuring that my data is correct when using an ancestor relationship without key names. Let me explain a little more: I've got a parent entity category, and I want to create a child entity item. I'd like to create a function that takes a category name and item name, and creates both entities if they don't exist. Initially I created one transaction and created both in the transaction if needed using a key name, and this worked fine. However, I realized I didn't want to use the name as the key as it may need to change, and I tried within my transaction to do this: def add_item_txn(category_name, item_name): category_query = db.GqlQuery("SELECT * FROM Category WHERE name=:category_name", category_name=category_name) category = category_query.get() if not category: category = Category(name=category_name, count=0) item_query = db.GqlQuery("SELECT * FROM Item WHERE name=:name AND ANCESTOR IS :category", name=item_name, category=category) item_results = item_query.fetch(1) if len(item_results) == 0: item = Item(parent=category, name=name) db.run_in_transaction(add_item_txn, "foo", "bar") What I found when I tried to run this is that App Engine rejects this as it won't let you run a query in a transaction: Only ancestor queries are allowed inside transactions. Looking at the example Google gives about how to address this: def decrement(key, amount=1): counter = db.get(key) counter.count -= amount if counter.count < 0: # don't let the counter go negative raise db.Rollback() db.put(counter) q = db.GqlQuery("SELECT * FROM Counter WHERE name = :1", "foo") counter = q.get() db.run_in_transaction(decrement, counter.key(), amount=5) I attempted to move my fetch of the category to before the transaction: def add_item_txn(category_key, item_name): category = category_key.get() item_query = db.GqlQuery("SELECT * FROM Item WHERE name=:name AND ANCESTOR IS :category", name=item_name, category=category) item_results = item_query.fetch(1) if len(item_results) == 0: item = Item(parent=category, name=name) category_query = db.GqlQuery("SELECT * FROM Category WHERE name=:category_name", category_name="foo") category = category_query.get() if not category: category = Category(name=category_name, count=0) db.run_in_transaction(add_item_txn, category.key(), "bar") This seemingly worked, but I found when I ran this with a number of requests that I had duplicate categories created, which makes sense, as the category is queried outside the transaction and multiple requests could create multiple categories. Does anyone have any idea how I can create these categories properly? I tried to put the category creation into a transaction, but received the error about ancestor queries only again. Thanks! Simon A: Here is an approach to solving your problem. It is not an ideal approach in many ways, and I sincerely hope that someone other AppEnginer will come up with a neater solution than I have. If not, give this a try. My approach utilizes the following strategy: it creates entities that act as aliases for the Category entities. The name of the Category can change, but the alias entity will retain its key, and we can use elements of the alias's key to create a keyname for your Category entities, so we will be able to look up a Category by its name, but its storage is decoupled from its name. The aliases are all stored in a single entity group, and that allows us to use a transaction-friendly ancestor query, so we can lookup or create a CategoryAlias without risking that multiple copies will be created. When I want to lookup or create a Category and item combo, I can use the category's keyname to programatically generate a key inside the transaction, and we are allowed to get an entity via its key inside a transaction. class CategoryAliasRoot(db.Model): count = db.IntegerProperty() # Not actually used in current code; just here to avoid having an empty # model definition. __singleton_keyname = "categoryaliasroot" @classmethod def get_instance(cls): # get_or_insert is inherently transactional; no chance of # getting two of these objects. return cls.get_or_insert(cls.__singleton_keyname, count=0) class CategoryAlias(db.Model): alias = db.StringProperty() @classmethod def get_or_create(cls, category_alias): alias_root = CategoryAliasRoot.get_instance() def txn(): existing_alias = cls.all().ancestor(alias_root).filter('alias = ', category_alias).get() if existing_alias is None: existing_alias = CategoryAlias(parent=alias_root, alias=category_alias) existing_alias.put() return existing_alias return db.run_in_transaction(txn) def keyname_for_category(self): return "category_" + self.key().id def rename(self, new_name): self.alias = new_name self.put() class Category(db.Model): pass class Item(db.Model): name = db.StringProperty() def get_or_create_item(category_name, item_name): def txn(category_keyname): category_key = Key.from_path('Category', category_keyname) existing_category = db.get(category_key) if existing_category is None: existing_category = Category(key_name=category_keyname) existing_category.put() existing_item = Item.all().ancestor(existing_category).filter('name = ', item_name).get() if existing_item is None: existing_item = Item(parent=existing_category, name=item_name) existing_item.put() return existing_item cat_alias = CategoryAlias.get_or_create(category_name) return db.run_in_transaction(txn, cat_alias.keyname_for_category()) Caveat emptor: I have not tested this code. Obviously, you will need to change it to match your actual models, but I think that the principles that it uses are sound. UPDATE: Simon, in your comment, you mostly have the right idea; although, there is an important subtlety that you shouldn't miss. You'll notice that the Category entities are not children of the dummy root. They do not share a parent, and they are themselves the root entities in their own entity groups. If the Category entities did all have the same parent, that would make one giant entity group, and you'd have a performance nightmare because each entity group can only have one transaction running on it at a time. Rather, the CategoryAlias entities are the children of the bogus root entity. That allows me to query inside a transaction, but the entity group doesn't get too big because the Items that belong to each Category aren't attached to the CategoryAlias. Also, the data in the CategoryAlias entity can change without changing the entitie's key, and I am using the Alias's key as a data point for generating a keyname that can be used in creating the actual Category entities themselves. So, I can change the name that is stored in the CategoryAlias without losing my ability to match that entity with the same Category. A: A couple of things to note (I think they're probably just typos) - The first line of your transactional method calls get() on a key - this is not a documented function. You don't need to have the actual category object in the function anyway - the key is sufficient in both of the places where you are using the category entity. You don't appear to be calling put() on either of the category or the item (but since you say you are getting data in the datastore, I assume you have left this out for brevity?) As far as a solution goes - you could attempt to add a value in memcache with a reasonable expiry - if memcache.add("category.%s" % category_name, True, 60): create_category(...) This at least stops you creating multiples. It is still a bit tricky to know what do if the query does not return the category, but you cannot grab the lock from memcache. This means the category is in the process of being created. If the originating request comes from the task queue, then just throw an exception so the task gets re-run. Otherwise you could wait a bit and query again, although this is a little dodgy. If the request comes from the user, then you could tell them there has been a conflict and to try again.
How do I ensure data integrity for objects in google app engine without using key names?
I'm having a bit of trouble in Google App Engine ensuring that my data is correct when using an ancestor relationship without key names. Let me explain a little more: I've got a parent entity category, and I want to create a child entity item. I'd like to create a function that takes a category name and item name, and creates both entities if they don't exist. Initially I created one transaction and created both in the transaction if needed using a key name, and this worked fine. However, I realized I didn't want to use the name as the key as it may need to change, and I tried within my transaction to do this: def add_item_txn(category_name, item_name): category_query = db.GqlQuery("SELECT * FROM Category WHERE name=:category_name", category_name=category_name) category = category_query.get() if not category: category = Category(name=category_name, count=0) item_query = db.GqlQuery("SELECT * FROM Item WHERE name=:name AND ANCESTOR IS :category", name=item_name, category=category) item_results = item_query.fetch(1) if len(item_results) == 0: item = Item(parent=category, name=name) db.run_in_transaction(add_item_txn, "foo", "bar") What I found when I tried to run this is that App Engine rejects this as it won't let you run a query in a transaction: Only ancestor queries are allowed inside transactions. Looking at the example Google gives about how to address this: def decrement(key, amount=1): counter = db.get(key) counter.count -= amount if counter.count < 0: # don't let the counter go negative raise db.Rollback() db.put(counter) q = db.GqlQuery("SELECT * FROM Counter WHERE name = :1", "foo") counter = q.get() db.run_in_transaction(decrement, counter.key(), amount=5) I attempted to move my fetch of the category to before the transaction: def add_item_txn(category_key, item_name): category = category_key.get() item_query = db.GqlQuery("SELECT * FROM Item WHERE name=:name AND ANCESTOR IS :category", name=item_name, category=category) item_results = item_query.fetch(1) if len(item_results) == 0: item = Item(parent=category, name=name) category_query = db.GqlQuery("SELECT * FROM Category WHERE name=:category_name", category_name="foo") category = category_query.get() if not category: category = Category(name=category_name, count=0) db.run_in_transaction(add_item_txn, category.key(), "bar") This seemingly worked, but I found when I ran this with a number of requests that I had duplicate categories created, which makes sense, as the category is queried outside the transaction and multiple requests could create multiple categories. Does anyone have any idea how I can create these categories properly? I tried to put the category creation into a transaction, but received the error about ancestor queries only again. Thanks! Simon
[ "Here is an approach to solving your problem. It is not an ideal approach in many ways, and I sincerely hope that someone other AppEnginer will come up with a neater solution than I have. If not, give this a try.\nMy approach utilizes the following strategy: it creates entities that act as aliases for the Category ...
[ 2, 0 ]
[]
[]
[ "data_integrity", "google_app_engine", "python", "transactions" ]
stackoverflow_0003525387_data_integrity_google_app_engine_python_transactions.txt
Q: python: cannot concatenate 'str' and 'long' objects I'm trying to set up a choice field in django, but I don't think this is a django issue. The choices field takes an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field. Here's my code: self.fields['question_' + question.id] = forms.ChoiceField( label=question.label, help_text=question.description, required=question.answer_set.required, choices=[("fe", "a feat"), ("faaa", "sfwerwer")]) for some reason, i always get the following error: TypeError - cannot concatenate 'str' and 'long' objects The last line is always highlighted. I'm not trying to concatenate anything. Almost regardless of what I change the list to for the 'choices' parameter, I get this error. What's going on? A: Most likely it's highlighting the last line only because you split the statement over multiple lines. The fix for the actual problem will most likely be changing self.fields['question_' + question.id] to self.fields['question_' + str(question.id)] As you can quickly test in a Python interpreter, adding a string and a number together doesn't work: >>> 'hi' + 6 Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> 'hi' + 6 TypeError: cannot concatenate 'str' and 'int' objects >>> 'hi' + str(6) 'hi6' A: 'question_' is a string, question.id is a long. You can not concatenate two things of different types, you will have to convert the long to a string using str(question.id). A: Probably question.id is an integer. Try self.fields['question_' + str(question.id)] = ... instead. A: self.fields['question_' + question.id] That looks like the problem. Try "question_%f"%question.id or "question_"+ str(question.id)
python: cannot concatenate 'str' and 'long' objects
I'm trying to set up a choice field in django, but I don't think this is a django issue. The choices field takes an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field. Here's my code: self.fields['question_' + question.id] = forms.ChoiceField( label=question.label, help_text=question.description, required=question.answer_set.required, choices=[("fe", "a feat"), ("faaa", "sfwerwer")]) for some reason, i always get the following error: TypeError - cannot concatenate 'str' and 'long' objects The last line is always highlighted. I'm not trying to concatenate anything. Almost regardless of what I change the list to for the 'choices' parameter, I get this error. What's going on?
[ "Most likely it's highlighting the last line only because you split the statement over multiple lines.\nThe fix for the actual problem will most likely be changing\nself.fields['question_' + question.id]\n\nto\nself.fields['question_' + str(question.id)]\n\nAs you can quickly test in a Python interpreter, adding a ...
[ 36, 6, 2, 2 ]
[ "This is a problem with doing too many things in one line - the error messages become slightly less helpful. Had you written it as below the problem would be much easier to find\nquestion_id = 'question_' + question.id\nself.fields[question_id] = forms.ChoiceField(\n label=question.label,\n ...
[ -2 ]
[ "python" ]
stackoverflow_0003532873_python.txt
Q: How to enable the libattr frature(abbreviated xattr) in linux? I want to use xattr in python, but found the xattr's keys() is empty, does that indicate the libattr feature wasn't enabled? I've learned the libattr feature is disabled in ext3/ext4 by default, but how to enable it? Expect your help! Thank you~ >>> import xattr >>> x = xattr.xattr('tiger_8a428_userdvd.dmg') >>> x <xattr file='tiger_8a428_userdvd.dmg'> >>> x.keys() [] A: Maybe you can use the following: >>> x = xattr.get_all('tiger_8a428_userdvd.dmg') Should be better.
How to enable the libattr frature(abbreviated xattr) in linux?
I want to use xattr in python, but found the xattr's keys() is empty, does that indicate the libattr feature wasn't enabled? I've learned the libattr feature is disabled in ext3/ext4 by default, but how to enable it? Expect your help! Thank you~ >>> import xattr >>> x = xattr.xattr('tiger_8a428_userdvd.dmg') >>> x <xattr file='tiger_8a428_userdvd.dmg'> >>> x.keys() []
[ "Maybe you can use the following:\n>>> x = xattr.get_all('tiger_8a428_userdvd.dmg')\nShould be better.\n" ]
[ 0 ]
[]
[]
[ "attr", "linux", "python" ]
stackoverflow_0003438924_attr_linux_python.txt
Q: How to control LabView VI front panel switches (on/off, bar adjuster) using Python scripts? I have a LabView front panel controlling switches and sensor voltage adjustors to the hardware and need to control these with a Python script. I do not have much knowledge of LabView. Please explain how this could be done. A: I found one reference on the LabVIEW discussion board that succeeded in this, it uses the following code: import win32com.client //load the interface labview = win32com.client.Dispatch("Labview.Application") //get a ref to the Labview application VI = labview.getvireference(r'C:\TEMP\python.vi') //load the VI VI.setcontrolvalue('Numeric','5') //set the control 'numeric' to 5 It seems like you need the win32com.client library in Python. A: You can also push data between LabVIEW and Python using Mark E. Smith's excellent XML-RPC package.
How to control LabView VI front panel switches (on/off, bar adjuster) using Python scripts?
I have a LabView front panel controlling switches and sensor voltage adjustors to the hardware and need to control these with a Python script. I do not have much knowledge of LabView. Please explain how this could be done.
[ "I found one reference on the LabVIEW discussion board that succeeded in this, it uses the following code:\nimport win32com.client //load the interface\nlabview = win32com.client.Dispatch(\"Labview.Application\") //get a ref to the Labview application\nVI = labview.getvireference(r'C:\\TEMP\\python.vi') //load the ...
[ 5, 1 ]
[]
[]
[ "labview", "python" ]
stackoverflow_0003524479_labview_python.txt
Q: random.randint for non integer number? [Python] How can I make a random number between something like 0.1 to 0.9 ? randint only work for integer numbers =/ Thank you A: Use random.uniform(). For your example, random.uniform(0.1, 0.9). It's equivalent to using random.random() to get a value between 0.0 and 1.0, then scaling and shifting the value appropriately: def rand_float_range(start, end): return random.random() * (end - start) + start
random.randint for non integer number? [Python]
How can I make a random number between something like 0.1 to 0.9 ? randint only work for integer numbers =/ Thank you
[ "Use random.uniform(). For your example, random.uniform(0.1, 0.9).\nIt's equivalent to using random.random() to get a value between 0.0 and 1.0, then scaling and shifting the value appropriately:\ndef rand_float_range(start, end):\n return random.random() * (end - start) + start\n\n" ]
[ 16 ]
[]
[]
[ "python", "random" ]
stackoverflow_0003533247_python_random.txt
Q: Python: How to extract required information from a string? I am new to Python. Is there a StringTokenizer in Python? Can I do character by character scanning and copying. I have the following input string data = '123:Palo Alto, CA -> 456:Seattle, WA 789' I need to extract the two (city, state) fields from this string. Here is the code I wrote name_list = [] while i < len(data)): if line[i] == ':': name = '' j = 0 i = i + 1 while line[i] != '-' and line[i].isnumeric() == False: name[j] = line[i] # This line gives error i = i + 1 j = j + 1 name_list.append(name) i = i + 1 What should I do? A: data = '123:Palo Alto, CA -> 456:Seattle, WA 789' citys = [] for record in data.split("->"): citys.append( re.search(r":(?P<city>[\w\s]+),\s*(?P<state>[\w]+)",record) .groupdict() ) print citys Gives: [{'city': 'Palo Alto', 'state': 'CA'}, {'city': 'Seattle', 'state': 'WA'}] A: You could always use a regular expression, if you wanted: /\d+:(\w+),\s(\w+)/. Its not pretty, but it should get the job done. Assuming string to match is the test string you had. import re for s in string_to_match.split("->"): m = re.match(r"\d+:(\w+),\s(\w+)", s) city = m.group(1) state = m.group(2) Syntax may be a little off, but the general idea is there. A: My take, assuming the string is always formatted as per your example: import re data = '123:Palo Alto, CA -> 456:Seattle, WA 789' name_list = [] r = re.compile("(\s?\d)|:") name_list += r.sub("", data).split(" ->") print name_list # Prints ['Palo Alto, CA', 'Seattle, WA'] As a note on your error, the empty string will have a length of 0, so the index 0 doesn't exist: >>> s = "" >>> len(s) 0 You can, however, concatenate strings in Python with the + operator, like so: >>> s += "Some" >>> s += " Text" >>> print s Some Text A: assuming that you always have the string formatted as shown you could do: cityState = [] for line in data.split('->'): cityState.append({'city':city=line.strip().split(',')[0].split(':')[1], 'state':state=line.strip().split(',').split(' ')[1]}) A: You can use regex. Here is my ugly regex, you can do better inputStr = '123:Palo Alto, CA -> 456:Seattle, WA 789'; m = re.search('.*:(.*),(.*)->.*:(.*),\s*(\S{2})', inputStr) print "City1=" + m.group(1) print "State1=" + m.group(2) print "City2=" + m.group(3) print "State2=" + m.group(4) Produces City1=Palo Alto State1= CA City2=Seattle State2=WA
Python: How to extract required information from a string?
I am new to Python. Is there a StringTokenizer in Python? Can I do character by character scanning and copying. I have the following input string data = '123:Palo Alto, CA -> 456:Seattle, WA 789' I need to extract the two (city, state) fields from this string. Here is the code I wrote name_list = [] while i < len(data)): if line[i] == ':': name = '' j = 0 i = i + 1 while line[i] != '-' and line[i].isnumeric() == False: name[j] = line[i] # This line gives error i = i + 1 j = j + 1 name_list.append(name) i = i + 1 What should I do?
[ "data = '123:Palo Alto, CA -> 456:Seattle, WA 789'\ncitys = []\nfor record in data.split(\"->\"):\n citys.append(\n re.search(r\":(?P<city>[\\w\\s]+),\\s*(?P<state>[\\w]+)\",record)\n .groupdict()\n )\n\nprint citys\n\nGives:\n[{'city': 'Palo Alto', 'state': 'CA'}, {'city': 'Seattle', 'state': '...
[ 8, 3, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003533072_python.txt
Q: Country-based Super User Access I'm looking to provide super-user access to entities belonging to a specific country. eg. Swedish SU can only admin Swedish entities, etc... However, I'm new to django (taking over an old system) and I need a lifeline. I'd like to be able to specify a relationship table. I've already added a userprofile and with that I have a new field called super_user_country_link = models.ForeignKey(SuperUserToCountry, blank=True, null=True) and then underneath a new class class SuperUserToCountry(models.Model): user = models.ForeignKey(User) country = models.ForeignKey(Country) I plan to run script then to add an entry for each superuser and give them a link to country 0 (ie, no country => total su access). I can then remove these entries as I start to put country-specific entries in So later I can call(using houses as an example): if user.is_superuser: if user.get_profile().super_user_county_link.country == 0: #show house detail... elsif user.get_profile().super_user_county_link.country == 0 #show house detail... else pass So looking at it, this should mean that I can list multiple countries against a single user, right? Maybe I'm over-thinking it, but does this look correct? I'm coming from a php background, so I'm just slighty dubious over how correct this is... A: Correct me if I am wrong. It seems to me that you are trying to establish an many to many relationship between UserProfile and Country. If so the best way to go about it would be to use a ManyToManyField. Something like this: class UserProfile(models.Model): countries = models.ManyToManyField(Country) You can leave it at that without requiring a separate model (SuperUserToCountry) as long as you are not storing any other information as part of this relationship. If in case you do plan to store other info, there is a way for that too. The conditions blank = True and null = True are not needed here. If no countries are associated with an user profile then the countries will return an empty lost (i.e. an_instance.countries.all() will be empty). When you start adding countries you can do something like this: profile = User.get_profile() denmark = Country.objects.get(name = 'Denmark') russia = Country.objects.get(name = 'Russia') if denmark in profile.countries.all(): print "Something is rotten in the state of Denmark" elsif russia in profile.countries.all(): print "In Soviet Russia, profiles have countries!" The above conditions can most likely be expressed more precisely based on your specific need. Incidentally you'll add a country to an user's profile like this: profile = User.get_profile() denmark = Country.objects.get(name = 'Denmark') profile.countries.add(denmark)
Country-based Super User Access
I'm looking to provide super-user access to entities belonging to a specific country. eg. Swedish SU can only admin Swedish entities, etc... However, I'm new to django (taking over an old system) and I need a lifeline. I'd like to be able to specify a relationship table. I've already added a userprofile and with that I have a new field called super_user_country_link = models.ForeignKey(SuperUserToCountry, blank=True, null=True) and then underneath a new class class SuperUserToCountry(models.Model): user = models.ForeignKey(User) country = models.ForeignKey(Country) I plan to run script then to add an entry for each superuser and give them a link to country 0 (ie, no country => total su access). I can then remove these entries as I start to put country-specific entries in So later I can call(using houses as an example): if user.is_superuser: if user.get_profile().super_user_county_link.country == 0: #show house detail... elsif user.get_profile().super_user_county_link.country == 0 #show house detail... else pass So looking at it, this should mean that I can list multiple countries against a single user, right? Maybe I'm over-thinking it, but does this look correct? I'm coming from a php background, so I'm just slighty dubious over how correct this is...
[ "Correct me if I am wrong. It seems to me that you are trying to establish an many to many relationship between UserProfile and Country. If so the best way to go about it would be to use a ManyToManyField. Something like this:\nclass UserProfile(models.Model):\n countries = models.ManyToManyField(Country)\n\nYou...
[ 1 ]
[]
[]
[ "database_design", "django", "django_models", "python" ]
stackoverflow_0003532574_database_design_django_django_models_python.txt
Q: Python. Output of crypto.cipher.blowfish and .AES can be translated neither into unicode (as sqlite wants), nor into hex Okay, I'm totally new to Python, so I decided to make a simple app. Here is my encryption function: from Crypto.Cipher import AES def encPass(login, password): keyPhr=os.environ['HOME']+login hashObj = hashlib.md5() hashObj.update(keyPhr) keyPhr=hashObj.hexdigest() keyObj=AES.new(keyPhr) encPwd=keyObj.encrypt(password+'pssd') return encPwd as you see, it gets login and pass, and encrypt pass with binding to pc. The problem is when i try to feed encPws to sqlite3 and insert it into a table, it says: sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings. If i try to put encPwd in unicode() or hex(): TypeError: hex() argument can't be converted to hex UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c in position 0: unexpected code byte I guess it's because i'm newbie, but what should I do? The same with Blowfish instead of AES A: You can use buffer and insert the encPwd as a blob. Or you can use something like base64 to convert your encPwd to ASCII (which is a subset of UTF8) so you can insert it as a string.
Python. Output of crypto.cipher.blowfish and .AES can be translated neither into unicode (as sqlite wants), nor into hex
Okay, I'm totally new to Python, so I decided to make a simple app. Here is my encryption function: from Crypto.Cipher import AES def encPass(login, password): keyPhr=os.environ['HOME']+login hashObj = hashlib.md5() hashObj.update(keyPhr) keyPhr=hashObj.hexdigest() keyObj=AES.new(keyPhr) encPwd=keyObj.encrypt(password+'pssd') return encPwd as you see, it gets login and pass, and encrypt pass with binding to pc. The problem is when i try to feed encPws to sqlite3 and insert it into a table, it says: sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings. If i try to put encPwd in unicode() or hex(): TypeError: hex() argument can't be converted to hex UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c in position 0: unexpected code byte I guess it's because i'm newbie, but what should I do? The same with Blowfish instead of AES
[ "You can use buffer and insert the encPwd as a blob.\nOr you can use something like base64 to convert your encPwd to ASCII (which is a subset of UTF8) so you can insert it as a string.\n" ]
[ 1 ]
[]
[]
[ "encryption", "python", "sqlite" ]
stackoverflow_0003533665_encryption_python_sqlite.txt
Q: Access to aliased functions in a Python module I am consolidating many shell-like operations into a single module. I would then like to be able to do: pyscript.py: from shell import * basename("/path/to/file.ext") and the shell.py module contains: shell.py: from os.path import basename The problem is that functions imported to the shell module are not available, since the import statement only includes functions, classes, and globals defined in the "shell" module, not ones that are imported. Is there any way to get around this? A: Are you sure you're not just using the wrong syntax? This works for me in 2.6. from shell import * basename("/path/to/file.ext") shell.py: from os.path import basename A: It's not a bug, it's a feature :-) If you import m1 in a module m2 and then import m2 into another module, it will only import things from m2, not from m1. This is to prevent namespace pollution. You could do this: shell.py: import os.path basename = os.path.basename Then, in pyscript.py, you can do this: from shell import * # warning: bad style! basename(...)
Access to aliased functions in a Python module
I am consolidating many shell-like operations into a single module. I would then like to be able to do: pyscript.py: from shell import * basename("/path/to/file.ext") and the shell.py module contains: shell.py: from os.path import basename The problem is that functions imported to the shell module are not available, since the import statement only includes functions, classes, and globals defined in the "shell" module, not ones that are imported. Is there any way to get around this?
[ "Are you sure you're not just using the wrong syntax? This works for me in 2.6.\nfrom shell import * \nbasename(\"/path/to/file.ext\")\n\nshell.py:\nfrom os.path import basename\n\n", "It's not a bug, it's a feature :-)\nIf you import m1 in a module m2 and then import m2 into another module, it will only import t...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003533653_python.txt
Q: gtk: detect click on a cell in a TreeView I'm displaying some data as a TreeView. How can I detect a click on a particular tree-view cell, so that I know which column of which row was clicked on? This is what I want to do, so maybe there's a better way: Part of the data is a series of True/False values indicating a particular set of options. For example, the options might be picking any of the options "Small, Medium, Large, X-Large" to be display. If the user selects "Small" and "Large", then the cell should display "Small, Large". I don't want to give each a separate column since there are actually like 20 options, and only 2 or 3 will be selected at any point. When the user clicks on the cell, I want to display a pop-up with a bunch of checkboxes. The user can then select what s/he wants and submit the changes, at which point the cell's value should be updated. The easiest way I thought of doing this would be to just detect a click (or a double-click) on the cell. Then I could pop up the window, and have the submit button of the window do what I want. A: The row-activated signal is sent when a GTK TreeView row is double-clicked. A: Ah from this grea tutorial and the API docs, I can just connect to the row-activated event, which will give me all the information I need.
gtk: detect click on a cell in a TreeView
I'm displaying some data as a TreeView. How can I detect a click on a particular tree-view cell, so that I know which column of which row was clicked on? This is what I want to do, so maybe there's a better way: Part of the data is a series of True/False values indicating a particular set of options. For example, the options might be picking any of the options "Small, Medium, Large, X-Large" to be display. If the user selects "Small" and "Large", then the cell should display "Small, Large". I don't want to give each a separate column since there are actually like 20 options, and only 2 or 3 will be selected at any point. When the user clicks on the cell, I want to display a pop-up with a bunch of checkboxes. The user can then select what s/he wants and submit the changes, at which point the cell's value should be updated. The easiest way I thought of doing this would be to just detect a click (or a double-click) on the cell. Then I could pop up the window, and have the submit button of the window do what I want.
[ "The row-activated signal is sent when a GTK TreeView row is double-clicked.\n", "Ah from this grea tutorial and the API docs, I can just connect to the row-activated event, which will give me all the information I need.\n" ]
[ 6, 0 ]
[]
[]
[ "gtk", "pygtk", "python", "user_interface" ]
stackoverflow_0003534127_gtk_pygtk_python_user_interface.txt
Q: Setting the default value of a function input to equal another input in Python Consider the following function, which does not work in Python, but I will use to explain what I need to do. def exampleFunction(a, b, c = a): ...function body... That is I want to assign to variable c the same value that variable a would take, unless an alternative value is specified. The above code does not work in python. Is there a way to do this? A: def example(a, b, c=None): if c is None: c = a ... The default value for the keyword argument can't be a variable (if it is, it's converted to a fixed value when the function is defined.) Commonly used to pass arguments to a main function: def main(argv=None): if argv is None: argv = sys.argv If None could be a valid value, the solution is to either use *args/**kwargs magic as in carl's answer, or use a sentinel object. Libraries that do this include attrs and Marshmallow, and in my opinion it's much cleaner and likely faster. missing = object() def example(a, b, c=missing): if c is missing: c = a ... The only way for c is missing to be true is for c to be exactly that dummy object you created there. A: This general pattern is probably the best and most readable: def exampleFunction(a, b, c = None): if c is None: c = a ... You have to be careful that None is not a valid state for c. If you want to support 'None' values, you can do something like this: def example(a, b, *args, **kwargs): if 'c' in kwargs: c = kwargs['c'] elif len(args) > 0: c = args[0] else: c = a A: One approach is something like: def foo(a, b, c=None): c = a if c is None else c # do something
Setting the default value of a function input to equal another input in Python
Consider the following function, which does not work in Python, but I will use to explain what I need to do. def exampleFunction(a, b, c = a): ...function body... That is I want to assign to variable c the same value that variable a would take, unless an alternative value is specified. The above code does not work in python. Is there a way to do this?
[ "def example(a, b, c=None):\n if c is None:\n c = a\n ...\n\nThe default value for the keyword argument can't be a variable (if it is, it's converted to a fixed value when the function is defined.) Commonly used to pass arguments to a main function:\ndef main(argv=None):\n if argv is None:\n ...
[ 30, 17, 1 ]
[]
[]
[ "default_value", "function", "keyword_argument", "python" ]
stackoverflow_0003534371_default_value_function_keyword_argument_python.txt
Q: Plotting a list of Complex nos on Z-plane in python I tried: plot(z) where z is a list of complex numbers, which plots abs(z) versus index. plot( z.real, z.imag ) doesn't work, it says list doesn't have attribute real. A: If z is a list of complex, use [k.real for k in z] to extract the real parts of every number in the list. A: If I'm understanding your question correctly, it might work if you fix the attribute error. ".real" and ".imag" must be performed on complex numbers as far as I know, meaning they won't work unless there is a j component: >>> a = 2.5 >>> print a.real Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'float' object has no attribute 'real' >>> a = 2.5 + 0j >>> print a.real 2.5 It looks to me like in your arguments for plot(), you tried to use ".real" and ".imag" on a list. I'd suggest trying to use ".real" and ".imag" on the complex numbers inside the list themselves. For a list of complex numbers z: >>> z[0].real >>> z[0].imag will call the real and imaginary parts of the first complex number in z, respectively. There are many ways to do this I'm sure, but the following is pretty easy: >>> x = [] >>> y = [] >>> for num in z: ... x.append(num.real) ... y.append(num.imag) ... >>> plot(x,y) Sorry that was so wordy, I'm really tired lol. While I've never used plot() before, my understanding is that it can plot lists so that should work.
Plotting a list of Complex nos on Z-plane in python
I tried: plot(z) where z is a list of complex numbers, which plots abs(z) versus index. plot( z.real, z.imag ) doesn't work, it says list doesn't have attribute real.
[ "If z is a list of complex, use\n[k.real for k in z]\n\nto extract the real parts of every number in the list.\n", "If I'm understanding your question correctly, it might work if you fix the attribute error. \".real\" and \".imag\" must be performed on complex numbers as far as I know, meaning they won't work un...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003530904_python.txt
Q: Python regex, matching pattern over multiple lines.. why isn't this working? I know that for parsing I should ideally remove all spaces and linebreaks but I was just doing this as a quick fix for something I was trying and I can't figure out why its not working.. I have wrapped different areas of text in my document with the wrappers like "####1" and am trying to parse based on this but its just not working no matter what I try, I think I am using multiline correctly.. any advice is appreciated This returns no results at all: string=' ####1 ttteest ####1 ttttteeeestt ####2 ttest ####2' import re pattern = '.*?####(.*?)####' returnmatch = re.compile(pattern, re.MULTILINE).findall(string) return returnmatch A: Multiline doesn't mean . will match line return, it means that ^ and $ are limited to lines only re.M re.MULTILINE When specified, the pattern character '^' matches at the beginning of the string and at the >beginning of each line (immediately following each newline); and the pattern character '$' >matches at the end of the string and at the end of each line (immediately preceding each >newline). By default, '^' matches only at the beginning of the string, and '$' only at the >end of the string and immediately before the newline (if any) at the end of the string. re.S or re.DOTALL makes . match even new lines. Source http://docs.python.org/ A: Try re.findall(r"####(.*?)\s(.*?)\s####", string, re.DOTALL) (works with re.compile too, of course). This regexp will return tuples containing the number of the section and the section content. For your example, this will return [('1', 'ttteest'), ('2', ' \n\nttest')]. (BTW: your example won't run, for multiline strings, use ''' or """)
Python regex, matching pattern over multiple lines.. why isn't this working?
I know that for parsing I should ideally remove all spaces and linebreaks but I was just doing this as a quick fix for something I was trying and I can't figure out why its not working.. I have wrapped different areas of text in my document with the wrappers like "####1" and am trying to parse based on this but its just not working no matter what I try, I think I am using multiline correctly.. any advice is appreciated This returns no results at all: string=' ####1 ttteest ####1 ttttteeeestt ####2 ttest ####2' import re pattern = '.*?####(.*?)####' returnmatch = re.compile(pattern, re.MULTILINE).findall(string) return returnmatch
[ "Multiline doesn't mean . will match line return, it means that ^ and $ are limited to lines only\n\nre.M\n re.MULTILINE\nWhen specified, the pattern character '^' matches at the beginning of the string and at the >beginning of each line (immediately following each newline); and the pattern character '$' >matches ...
[ 26, 19 ]
[]
[]
[ "parsing", "python", "regex" ]
stackoverflow_0003534507_parsing_python_regex.txt
Q: Uploaded and not converted files do not appear in the document feed in Google Docs I trying to retrieve a complete list of files from a given directory with code like this uri = '%s' % fentry.content.src feed = gd_client.GetDocumentListFeed(uri=uri) for r in feed.entry: print r.title.text.decode("utf-8") It works except that it only return "real" Google Documents files and does not return files, which were uploaded but not converted, e.g. *.docx files. Is there any way to get complete list of files in given directory? A: I have the suspicion that you are using a wrong uri. Read here about the different options you have: http://code.google.com/intl/en-US/apis/documents/docs/3.0/developers_guide_protocol.html#ListDocs
Uploaded and not converted files do not appear in the document feed in Google Docs
I trying to retrieve a complete list of files from a given directory with code like this uri = '%s' % fentry.content.src feed = gd_client.GetDocumentListFeed(uri=uri) for r in feed.entry: print r.title.text.decode("utf-8") It works except that it only return "real" Google Documents files and does not return files, which were uploaded but not converted, e.g. *.docx files. Is there any way to get complete list of files in given directory?
[ "I have the suspicion that you are using a wrong uri. Read here about the different options you have:\nhttp://code.google.com/intl/en-US/apis/documents/docs/3.0/developers_guide_protocol.html#ListDocs\n" ]
[ 1 ]
[]
[]
[ "google_docs_api", "python" ]
stackoverflow_0003535311_google_docs_api_python.txt
Q: Select Children of an Object With ForeignKey in Django? I'm brand new to Django, so the answer to this is probably very simple. However, I can't figure it out. Say I have two bare-bones Models. class Blog(models.Model): title = models.CharField(max_length=160) text = models.TextField() class Comment(models.Model): blog = models.ForeignKey(Blog) text = models.TextField() In the Python/Django shell, if I have a Blog object in a variable (say blog = Blog.objects.get(id=3)), how do I select all its child comments? This doesn't seem to work: blog.objects.all() A: to follow foreign keys 'backwards' you use blog.comment_set.all()
Select Children of an Object With ForeignKey in Django?
I'm brand new to Django, so the answer to this is probably very simple. However, I can't figure it out. Say I have two bare-bones Models. class Blog(models.Model): title = models.CharField(max_length=160) text = models.TextField() class Comment(models.Model): blog = models.ForeignKey(Blog) text = models.TextField() In the Python/Django shell, if I have a Blog object in a variable (say blog = Blog.objects.get(id=3)), how do I select all its child comments? This doesn't seem to work: blog.objects.all()
[ "to follow foreign keys 'backwards' you use\nblog.comment_set.all()\n\n" ]
[ 47 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003535615_django_python.txt
Q: Parsing blockbased program output using Python I am trying to parse the output of a statistical program (Mplus) using Python. The format of the output (example here) is structured in blocks, sub-blocks, columns, etc. where the whitespace and breaks are very important. Depending on the eg. options requested you get an addional (sub)block or column here or there. Approaching this using regular expressions has been a PITA and completely unmaintainable. I have been looking into parsers as a more robust solution, but am a bit overwhelmed by all the possible tools and approaches; have the impression that they are not well suited for this kind of output. E.g. LEPL has something called line-aware parsing, which seems to go in the right direction (whitespace, blocks, ...) but is still geared to parsing programming syntax, not output. Suggestion in which direction to look would be appreciated. A: Based on your example, what you have is a bunch of different, nested sub-formats that, individually, are very easily parsed. What can be overwhelming is the sheer number of formats and the fact that they can be nested in different ways. At the lowest level you have a set of whitespace-separated values on a single line. Those lines combine into blocks, and how the blocks combine and nest within each other is the complex part. This type of output is designed for human reading and was never intended to be "scraped" back into machine-readable form. First, I would contact the author of the software and find out if there is an alternate output format available, such as XML or CSV. If done correctly (i.e. not just the print-format wrapped in clumsy XML, or with commas replacing whitespace), this would be much easier to handle. Failing that I would try to come up with a hierarchical list of formats and how they nest. For example, ESTIMATED SAMPLE STATISTICS begins a block Within that block MEANS/INTERCEPTS/THRESHOLDS begins a nested block The next two lines are a set of column headings This is followed by one (or more?) rows of data, with a row header and data values And so on. If you approach each of these problems separately, you will find that it's tedious but not complex. Think of each of the above steps as modules that test the input to see if it matches and if it does, then call other modules to test further for things that can occur "inside" the block, backtracking if you get to something that doesn't match what you expect (this is called "recursive descent" by the way). Note that you will have to do something like this anyway, in order to build an in-memory version of the data (the "data model") on which you can operate. A: Yes, this is a pain to parse. You don't -- however -- actually need very many regular expressions. Ordinary split may be sufficient for breaking this document into manageable sequences of strings. These are a lot of what I call "Head-Body" blocks of text. You have titles, a line of "--"'s and then data. What you want to do is collapse a "head-body" structure into a generator function that yields individual dictionaries. def get_means_intecepts_thresholds( source_iter ): """Precondition: Current line is a "MEANS/INTERCEPTS/THRESHOLDS" line""" head= source_iter.next().strip().split() junk= source_iter.next().strip() assert set( junk ) == set( [' ','-'] ) for line in source_iter: if len(line.strip()) == 0: continue if line.strip() == "SLOPES": break raw_data= line.strip().split() data = dict( zip( head, map( float, raw_data[1:] ) ) ) yield int(raw_data[0]), data def get_slopes( source_iter ): """Precondition: Current line is a "SLOPES" line""" head= source_iter.next().strip().split() junk= source_iter.next().strip() assert set( junk ) == set( [' ','-'] ) for line in source_iter: if len(line.strip()) == 0: continue if line.strip() == "SLOPES": break raw_data= line.strip().split() ) data = dict( zip( head, map( float, raw_data[1:] ) ) ) yield raw_data[0], data The point is to consume the head and the junk with one set of operations. Then consume the rows of data which follow using a different set of operations. Since these are generators, you can combine them with other operations. def get_estimated_sample_statistics( source_iter ): """Precondition: at the ESTIMATED SAMPLE STATISTICS line""" for line in source_iter: if len(line.strip()) == 0: continue assert line.strip() == "MEANS/INTERCEPTS/THRESHOLDS" for data in get_means_intercepts_thresholds( source_iter ): yield data while True: if len(line.strip()) == 0: continue if line.strip() != "SLOPES": break for data in get_slopes( source_iter ): yield data Something like this may be better than regular expressions. A: My suggestion is to do rough massaging of the lines to more useful form. Here is some experiments with your data: from __future__ import print_function from itertools import groupby import string counter = 0 statslist = [ statsblocks.split('\n') for statsblocks in open('mlab.txt').read().split('\n\n') ] print(len(statslist), 'blocks') def blockcounter(line): global counter if not line[0]: counter += 1 return counter blocklist = [ [block, list(stats)] for block, stats in groupby(statslist, blockcounter)] for blockno,block in enumerate(blocklist): print(120 * '=') for itemno,line in enumerate(block[1:][0]): if len(line)<4 and any(line[-1].endswith(c) for c in string.letters) : print('\n** DATA %i, HEADER (%r)**' % (blockno,line[-1])) else: print('\n** DATA %i, item %i, length %i **' % (blockno, itemno, len(line))) for ind,subdata in enumerate(line): if '___' in subdata: print(' *** Numeric data starts: ***') else: if 6 < len(subdata)<16: print( '** TYPE: %s **' % subdata) print('%3i : %s' %( ind, subdata)) A: You could try PyParsing. It enables you to write a grammar for what you want to parse. It has other examples than parsing programming languages. But I agree with Jim Garrison that your case doesn't seem to call for a real parser, because writing the grammar would be cumbersome. I would try a brute-force solution, e.g. splitting lines at whitespaces. It's not foolproof, but we can assume the output is correct, so if a line has n headers, the next line will have exactly n values. A: It turns out that tabular program output like this was one of my earliest applications of pyparsing. Unfortunately, that exact example dealt with a proprietary format that I can't publish, but there is a similar example posted here: http://pyparsing.wikispaces.com/file/view/dictExample2.py .
Parsing blockbased program output using Python
I am trying to parse the output of a statistical program (Mplus) using Python. The format of the output (example here) is structured in blocks, sub-blocks, columns, etc. where the whitespace and breaks are very important. Depending on the eg. options requested you get an addional (sub)block or column here or there. Approaching this using regular expressions has been a PITA and completely unmaintainable. I have been looking into parsers as a more robust solution, but am a bit overwhelmed by all the possible tools and approaches; have the impression that they are not well suited for this kind of output. E.g. LEPL has something called line-aware parsing, which seems to go in the right direction (whitespace, blocks, ...) but is still geared to parsing programming syntax, not output. Suggestion in which direction to look would be appreciated.
[ "Based on your example, what you have is a bunch of different, nested sub-formats that, individually, are very easily parsed. What can be overwhelming is the sheer number of formats and the fact that they can be nested in different ways. \nAt the lowest level you have a set of whitespace-separated values on a sin...
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "block", "parsing", "python" ]
stackoverflow_0003533443_block_parsing_python.txt
Q: Python doesn't save data to sqlite db This is my code: conn = sqlite3.connect(nnpcconfig.commondb) cur = conn.cursor() query = ['2124124', 'test2', 'test3', 'test4', 'test5'] cur.execute("insert into users(id, encpass, sname, name, fname) values (?, ?, ?, ?, ?)", query) conn.commit cur.execute("select * from users") for row in cur: print row This code works, returning row fed to it. But it comes out that once script terminated, table is clear again! Where's the mistake? Of course, table users exists. A: You have another mistake: conn.commit instead of conn.commit()
Python doesn't save data to sqlite db
This is my code: conn = sqlite3.connect(nnpcconfig.commondb) cur = conn.cursor() query = ['2124124', 'test2', 'test3', 'test4', 'test5'] cur.execute("insert into users(id, encpass, sname, name, fname) values (?, ?, ?, ?, ?)", query) conn.commit cur.execute("select * from users") for row in cur: print row This code works, returning row fed to it. But it comes out that once script terminated, table is clear again! Where's the mistake? Of course, table users exists.
[ "You have another mistake: conn.commit instead of conn.commit()\n" ]
[ 10 ]
[]
[]
[ "database", "python", "sql", "sqlite" ]
stackoverflow_0003535532_database_python_sql_sqlite.txt
Q: Python efficiency of and vs multiple ifs Is there an efficiency difference between using and in an if statement and using multiple if statements? In other words, is something like if expr1 == expr2 and expr3==expr4: dostuff() different from an efficiency standpoint then: if expr1 == expr2: if expr3 == expr4: dostuff() My very basic testing does not reveal a difference, but does someone with more knowledge (or at least more thorough testing) have a definitive answer? A: This isn't enough of a performance difference, if any, to affect your decision. IMO, the decision here should be made purely from a readability perspective. The first is generally more standard, I think, but there are situations when the second might be clearer. Choose the method that best gets your intent across. A: Any differences in speed between using and and nested ifs will be minimal. You are barking up the wrong tree. Consider this tree: if oftenTrueCondition and rarelyTrueCondition: compared with if rarelyTrueCondition and oftenTrueCondition: So, unless the first condition must be evaluated first (it is a guard to stop the next expression from crashing or doing something silly/expensive), consider swapping the order of evaluation. A: In either case, expr1 == expr2 evaluates to false in if, the second will not be evaluated. A: When in doubt, you can check what does python compile your statements in, using dis module: >>> import dis >>> def test1(): ... if expr1 == expr2 and expr3==expr4: ... dostuff() ... >>> def test2(): ... if expr1 == expr2: ... if expr3 == expr4: ... dostuff() ... >>> dis.dis(test1) 2 0 LOAD_GLOBAL 0 (expr1) 3 LOAD_GLOBAL 1 (expr2) 6 COMPARE_OP 2 (==) 9 JUMP_IF_FALSE 24 (to 36) 12 POP_TOP 13 LOAD_GLOBAL 2 (expr3) 16 LOAD_GLOBAL 3 (expr4) 19 COMPARE_OP 2 (==) 22 JUMP_IF_FALSE 11 (to 36) 25 POP_TOP 3 26 LOAD_GLOBAL 4 (dostuff) 29 CALL_FUNCTION 0 32 POP_TOP 33 JUMP_FORWARD 1 (to 37) >> 36 POP_TOP >> 37 LOAD_CONST 0 (None) 40 RETURN_VALUE >>> dis.dis(test2) 2 0 LOAD_GLOBAL 0 (expr1) 3 LOAD_GLOBAL 1 (expr2) 6 COMPARE_OP 2 (==) 9 JUMP_IF_FALSE 28 (to 40) 12 POP_TOP 3 13 LOAD_GLOBAL 2 (expr3) 16 LOAD_GLOBAL 3 (expr4) 19 COMPARE_OP 2 (==) 22 JUMP_IF_FALSE 11 (to 36) 25 POP_TOP 4 26 LOAD_GLOBAL 4 (dostuff) 29 CALL_FUNCTION 0 32 POP_TOP 33 JUMP_ABSOLUTE 41 >> 36 POP_TOP 37 JUMP_FORWARD 1 (to 41) >> 40 POP_TOP >> 41 LOAD_CONST 0 (None) 44 RETURN_VALUE So as you can see, at python bytecode level, both statements are same - even while you use single if at first statement, it will do JUMP_IF_FALSE after first comparison. A: The first one (one if with and) is faster :-) I tried it out using timeit. These are the results: Variant 1: 9.82836714316 Variant 2: 9.83886494559 Variant 1 (True): 9.66493159804 Variant 2 (True): 10.0392633241 For the last two, the first comparision is True, so the second one is skipped. Interesting results. import timeit print "Variant 1: %s" % timeit.timeit(""" for i in xrange(1000): if i == 2*i and i == 3*i: pass """, number = 1000) print "Variant 2: %s" % timeit.timeit(""" for i in xrange(1000): if i == 2*i: if i == 3*i: pass """, number = 1000) print "Variant 1 (True): %s" % timeit.timeit(""" for i in xrange(1000): if i == i and i == 3*i: pass """, number = 1000) print "Variant 2 (True): %s" % timeit.timeit(""" for i in xrange(1000): if i == i: if i == 3*i: pass """, number = 1000)
Python efficiency of and vs multiple ifs
Is there an efficiency difference between using and in an if statement and using multiple if statements? In other words, is something like if expr1 == expr2 and expr3==expr4: dostuff() different from an efficiency standpoint then: if expr1 == expr2: if expr3 == expr4: dostuff() My very basic testing does not reveal a difference, but does someone with more knowledge (or at least more thorough testing) have a definitive answer?
[ "This isn't enough of a performance difference, if any, to affect your decision. IMO, the decision here should be made purely from a readability perspective. The first is generally more standard, I think, but there are situations when the second might be clearer. Choose the method that best gets your intent across....
[ 14, 14, 7, 5, 2 ]
[]
[]
[ "conditional", "performance", "python" ]
stackoverflow_0003533338_conditional_performance_python.txt
Q: Traversing an ftp folder with python I need to write a python script that traverses a folder on a FTP server. for file in ftpfolder: #get it #do something untoward with it Snippets and non-wheel-reinvention advice welcome. A: ftputil is the third-party module you're looking for: ftputil is a high-level FTP client library for the Python programming language. ftputil implements a virtual file system for accessing FTP servers, that is, it can generate file-like objects for remote files. The library supports many functions similar to those in the os, os.path and shutil modules. Note for example the snippet here: # download some files from the login directory host = ftputil.FTPHost('ftp.domain.com', 'user', 'secret') names = host.listdir(host.curdir) for name in names: if host.path.isfile(name): host.download(name, name, 'b') # remote, local, binary mode ftputil is pure Python, very stable, and very popular on pypi (users rate it 9, which I think is the maximum on pypi's scale). What's not to like?-)
Traversing an ftp folder with python
I need to write a python script that traverses a folder on a FTP server. for file in ftpfolder: #get it #do something untoward with it Snippets and non-wheel-reinvention advice welcome.
[ "ftputil is the third-party module you're looking for:\n\nftputil is a high-level FTP client\n library for the Python programming\n language. ftputil implements a virtual\n file system for accessing FTP servers,\n that is, it can generate file-like\n objects for remote files. The library\n supports many funct...
[ 14 ]
[]
[]
[ "directory", "download", "ftp", "python", "traversal" ]
stackoverflow_0003535936_directory_download_ftp_python_traversal.txt
Q: Encode and pad netbios name using python I'm trying to create a simple script that will convert a string (max 15 chars) to a netbios name (see http://support.microsoft.com/kb/194203) : name = sys.argv[1].upper() converted = ''.join([chr((ord(c)>>4) + ord('A'))+chr((ord(c)&0xF) + ord('A')) for c in name]) print converted Trying to convert the name : "testing" will return : "4645454646444645454a454f4548" which is correct. Now depending the length of the name submitted (max 15 chars) we need to pad 4341 until the converted string is 64 long. Example : ./script.py testing: 4645454646444645454a454f4548 But should actually be : 4645454646444645454a454f4548434143414341434143414341434143414341 Anyways to do this easily ? Thanks ! A: ... + ((16 - len(name)) * '4341')
Encode and pad netbios name using python
I'm trying to create a simple script that will convert a string (max 15 chars) to a netbios name (see http://support.microsoft.com/kb/194203) : name = sys.argv[1].upper() converted = ''.join([chr((ord(c)>>4) + ord('A'))+chr((ord(c)&0xF) + ord('A')) for c in name]) print converted Trying to convert the name : "testing" will return : "4645454646444645454a454f4548" which is correct. Now depending the length of the name submitted (max 15 chars) we need to pad 4341 until the converted string is 64 long. Example : ./script.py testing: 4645454646444645454a454f4548 But should actually be : 4645454646444645454a454f4548434143414341434143414341434143414341 Anyways to do this easily ? Thanks !
[ "... + ((16 - len(name)) * '4341')\n\n" ]
[ 0 ]
[]
[]
[ "netbios", "python" ]
stackoverflow_0003536100_netbios_python.txt
Q: Does Python 2.5.2 follow Unicode for lower() and upper()? I'm making a Google AppEngine Application. Does the Python 2.5.2 runtime environment follow the Unicode Standards? (For example, the lower() and upper() methods on unicode objects.) A: Yes and no. For an example, see the code being discussed here: How can I convert Unicode to uppercase to print it? Check here for a formal, well-written document: http://www.cmlenz.net/archives/2008/07/the-truth-about-unicode-in-python
Does Python 2.5.2 follow Unicode for lower() and upper()?
I'm making a Google AppEngine Application. Does the Python 2.5.2 runtime environment follow the Unicode Standards? (For example, the lower() and upper() methods on unicode objects.)
[ "Yes and no.\nFor an example, see the code being discussed here: How can I convert Unicode to uppercase to print it?\nCheck here for a formal, well-written document:\nhttp://www.cmlenz.net/archives/2008/07/the-truth-about-unicode-in-python\n" ]
[ 5 ]
[]
[]
[ "case_sensitive", "python", "unicode" ]
stackoverflow_0003536397_case_sensitive_python_unicode.txt
Q: Unicode case conversion I am given either a single character or a string, and am using Python. How do I find out if a specific character has a lowercase equivalent according to the standards (standard and special case mappings) proposed by Unicode? And how do I find out if a string has one or more characters that have a lowercase equivalent according to the standards (standard and special case mappings) proposed by Unicode? A: def haslower(unicodechar): return unicodechar != unicodechar.lower() def anylower(unicodestring): return any(haslower(c) for c in unicodestring) This will only work correctly in as much as the Python version you're using has correctly implemented the .lower() method per unicode standards, of course. Also, I'm assuming that you don't consider, e.g., u'a', to "have a lowercase equivalent" (it has an uppercase one of course). If you mean something different, consider def changescase(uc): return uc != uc.lower() or uc != uc.upper() (I've renamed the argument to uc to avoid excessive line length;-) -- if that's what you want I recommend not naming the function in terms of "lowercase equivalent" as that would be sure to confuse readers/maintainers of your code!-) A: @Albert, You appear to be overly concerned with the minutiae of case conversion, when you haven't yet sorted out (nor explained to answerers) what you really want to do. === Your previous attempt at explanation (in comment on my answer to this question) === @John: Well, I'm actually making an API for my web service. My webservice accepts a key that maps out to a specific record in my database. The key is case-sensitive, and the key can be composed of any unicode characteer. So in order to normalize all input, I will convert all key queries into lowercase (if they have uppercase equivalents). A consequence of that is when I create the record keys (which my users can customize), I cannot accept any uppercase character that can be converted to a lowercase equivalent by the toLower() function. So I'm trying to make a filter for that. Any suggestions? === and my replying comment === @Albert: If your keys are case sensitive, why are you normalising them??? "record keys which users can customize" means what??? "any unicode char" vs "cannot accept any uppercase char" ??? To answer your question literally: Looks like you can't accept a character c when c.lower() != c which means that you can't accept any key if key.lower() != key. I think that you should start a NEW QUESTION, explaining exactly what you are trying to do, with examples. ... and you've certainly asked a new question (in fact 2 of them) but you haven't explained anything. This "new" question is so new that @Alex Martelli's answer is essentially the same as my comment highlighted above. I think that you should start a NEW QUESTION, with new content, explaining exactly what you are trying to do, with examples.
Unicode case conversion
I am given either a single character or a string, and am using Python. How do I find out if a specific character has a lowercase equivalent according to the standards (standard and special case mappings) proposed by Unicode? And how do I find out if a string has one or more characters that have a lowercase equivalent according to the standards (standard and special case mappings) proposed by Unicode?
[ "def haslower(unicodechar):\n return unicodechar != unicodechar.lower()\n\ndef anylower(unicodestring):\n return any(haslower(c) for c in unicodestring)\n\nThis will only work correctly in as much as the Python version you're using has correctly implemented the .lower() method per unicode standards, of course...
[ 5, 1 ]
[]
[]
[ "case_sensitive", "python", "unicode" ]
stackoverflow_0003536355_case_sensitive_python_unicode.txt
Q: convert string rep of hexadecimal into actual hexadecimal Possible Duplicate: how to parse hex or decimal int in Python i have a bunch of Hexadecimal colors in a database stored as strings. e.g. '0xFFFF00' when i get them from the database i need to convert this string into an actual hexadecimal number, so 0xFFFF00 how can i do this in python A: This is one way to do it: >>> s = '0xFFFF00' >>> i = int(s, 16) >>> print i A: hex(int('0xFFFF00', 16)) A: Also this works number = int('0xFFFF00',0) print("%x follows %x" % (number+1, number)) 0 argument tells interpreter to follow the Python rules of numbers to decide the used format of number so this expression will work right for all numbers.
convert string rep of hexadecimal into actual hexadecimal
Possible Duplicate: how to parse hex or decimal int in Python i have a bunch of Hexadecimal colors in a database stored as strings. e.g. '0xFFFF00' when i get them from the database i need to convert this string into an actual hexadecimal number, so 0xFFFF00 how can i do this in python
[ "This is one way to do it:\n>>> s = '0xFFFF00'\n>>> i = int(s, 16)\n>>> print i\n\n", "hex(int('0xFFFF00', 16))\n", "Also this works \nnumber = int('0xFFFF00',0)\nprint(\"%x follows %x\" % (number+1, number))\n\n0 argument tells interpreter to follow the Python rules of numbers to decide the used format of numb...
[ 5, 0, 0 ]
[]
[]
[ "hex", "python" ]
stackoverflow_0003535324_hex_python.txt
Q: Python MIT Open Courseware Stock Market Simulation Incomplete? I just copied this code from the MIT video lecture that is posted online: (Lec 23 | MIT 6.00 Introduction to Computer Science and Programming, Fall 2008). Since I had to copy it from a video lecture, I'm not sure I got the complete program. It is not working as is, I could use some guidance. Thanks. import pylab, random class Stock(object): def __init__(self, price, distribution): self.price = price self.history = [price] self.distribution = distribution self.lastChange = 0 def setPrice(self, price): self.price = price self.history.append(price) def getPrice(self): return self.price def makeMove(self, mktBias, mo): oldPrice = self.price baseMove = self.distribution() + mktBias self.price = self.price * (1.0 + baseMove) if mo: self.price = self.price + random.gauss(.5, .5)*self.lastChange if self.price < 0.01: self.price = 0.0 self.history.append(self.price) self.lastChange = oldPrice - self.price def showHistory(self, figNum): pylab.figure(figNum) pylab.plot(self.history) pylab.title('Closing Price, Test ' + str(figNum)) pylab.xlabel('Day') pylab.ylabel('Price') def unitTestStock(): def runSim(stks, fig, mo): for a in stks: for d in range(numDays): s.makeMove(bias, mo) s.showHistory(fig) mean += s.getPrice() mean = mean/float(numStks) pylab.axhline(mean) numStks = 20 numDays = 200 stks1 = [] stks2 = [] bias = 0.0 mo = False for i in range(numStks): volatility = random.uniform(0,0.2) d1 = lambda: random.uniform(-volatility, volatility) d2 = lambda: random.gauss(0.0, volatility/2.0) stks1.append(Stock(100.0, d1)) stks2.append(Stock(100.0, d2)) runSim(stks1, 1, mo) runSim(stks2, 2, mo) unitTestStock() pylab.show() assert False class Market(object): def __init__(self): self.stks = [] self.bias = 0.0 A: You seem to be missing mean = 0.0 and need to change an a to an s: def runSim(stks, fig, mo): mean = 0.0 for s in stks: for d in range(numDays): s.makeMove(bias, mo) s.showHistory(fig) mean += s.getPrice() mean = mean/float(numStks) pylab.axhline(mean) PS. I think most of this code is in this pdf, which can be found on this page. A: In addition to mistyping the variable s and missing the mean assignment, you also have an indentation problem. As it stands, you've currently defined unitTestStock() as an attribute of the Stock class. This is not what you want, especially as unitTestStock has no self parameter. To fix your problem, incorporate the above changes, and then dedent the entire body of the function unitTestStock() and the 3 lines following it. The code should look like this: class Stock(object): <...> def showHistory(self, figNum): pylab.figure(figNum) pylab.plot(self.history) pylab.title('Closing Price, Test ' + str(figNum)) pylab.xlabel('Day') pylab.ylabel('Price') def unitTestStock(): def runSim(stks, fig, mo): mean = 0.0 for s in stks: for d in range(numDays): s.makeMove(bias, mo) s.showHistory(fig) mean += s.getPrice() mean = mean/float(numStks) pylab.axhline(mean) numStks = 20 numDays = 200 stks1 = [] stks2 = [] bias = 0.0 mo = False for i in range(numStks): volatility = random.uniform(0,0.2) d1 = lambda: random.uniform(-volatility, volatility) d2 = lambda: random.gauss(0.0, volatility/2.0) stks1.append(Stock(100.0, d1)) stks2.append(Stock(100.0, d2)) runSim(stks1, 1, mo) runSim(stks2, 2, mo) unitTestStock() pylab.show() assert False
Python MIT Open Courseware Stock Market Simulation Incomplete?
I just copied this code from the MIT video lecture that is posted online: (Lec 23 | MIT 6.00 Introduction to Computer Science and Programming, Fall 2008). Since I had to copy it from a video lecture, I'm not sure I got the complete program. It is not working as is, I could use some guidance. Thanks. import pylab, random class Stock(object): def __init__(self, price, distribution): self.price = price self.history = [price] self.distribution = distribution self.lastChange = 0 def setPrice(self, price): self.price = price self.history.append(price) def getPrice(self): return self.price def makeMove(self, mktBias, mo): oldPrice = self.price baseMove = self.distribution() + mktBias self.price = self.price * (1.0 + baseMove) if mo: self.price = self.price + random.gauss(.5, .5)*self.lastChange if self.price < 0.01: self.price = 0.0 self.history.append(self.price) self.lastChange = oldPrice - self.price def showHistory(self, figNum): pylab.figure(figNum) pylab.plot(self.history) pylab.title('Closing Price, Test ' + str(figNum)) pylab.xlabel('Day') pylab.ylabel('Price') def unitTestStock(): def runSim(stks, fig, mo): for a in stks: for d in range(numDays): s.makeMove(bias, mo) s.showHistory(fig) mean += s.getPrice() mean = mean/float(numStks) pylab.axhline(mean) numStks = 20 numDays = 200 stks1 = [] stks2 = [] bias = 0.0 mo = False for i in range(numStks): volatility = random.uniform(0,0.2) d1 = lambda: random.uniform(-volatility, volatility) d2 = lambda: random.gauss(0.0, volatility/2.0) stks1.append(Stock(100.0, d1)) stks2.append(Stock(100.0, d2)) runSim(stks1, 1, mo) runSim(stks2, 2, mo) unitTestStock() pylab.show() assert False class Market(object): def __init__(self): self.stks = [] self.bias = 0.0
[ "You seem to be missing mean = 0.0 and need to change an a to an s:\ndef runSim(stks, fig, mo):\n mean = 0.0\n for s in stks:\n for d in range(numDays):\n s.makeMove(bias, mo)\n s.showHistory(fig)\n mean += s.getPrice()\n mean = mean/float(numStks)\n pylab.axhline(mean)\n...
[ 1, 1 ]
[]
[]
[ "python", "simulation" ]
stackoverflow_0003534767_python_simulation.txt
Q: Python performance: search large list vs sqlite Lets say I have a database table which consists of three columns: id, field1 and field2. This table may have anywhere between 100 and 100,000 rows in it. I have a python script that should insert 10-1,000 new rows into this table. However, if the new field1 already exists in the table, it should do an UPDATE, not an INSERT. Which of the following approaches is more efficient? Do a SELECT field1 FROM table (field1 is unique) and store that in a list. Then, for each new row, use list.count() to determine whether to INSERT or UPDATE For each row, run two queries. Firstly, SELECT count(*) FROM table WHERE field1="foo" then either the INSERT or UPDATE. In other words, is it more efficient to perform n+1 queries and search a list, or 2n queries and get sqlite to search? A: If I understand your question correctly, it seems like you could simply use SQLite's built in conflict handling mechanism. Assuming you have a UNIQUE constraint on field1, you could simple use: INSERT OR REPLACE INTO table VALUES (...) The following syntax is also supported (identical semantics): REPLACE INTO table VALUES (...) EDIT: I realise that I am not really answering your question, just providing an alternative solution which should be faster. A: I'm not familiar with sqlite but a general approach like this should work: If there's a unique index on field1 and you're trying to insert a value that's already there you should get an error. If insert fails, you go with the update. Pseudocode: try { insert into table (value1, value2) } catch(insert fails) { update table set field2=value2 where field1=value1 } A: I imagine using a python dictionary would allow for much faster searching than using a python list. (Just set the values to 0, you won't need them, and hopefully a '0' stores compactly.) As for the larger question, I'm curious too. :) A: You appear to be comparing apples with oranges. A python list is only useful if your data fit into the address-space of the process. Once the data get big, this won't work any more. Moreover, a python list is not indexed - for that you should use a dictionary. Finally, a python list is non-persistent - it is forgotten when the process quits. How can you possibly compare these?
Python performance: search large list vs sqlite
Lets say I have a database table which consists of three columns: id, field1 and field2. This table may have anywhere between 100 and 100,000 rows in it. I have a python script that should insert 10-1,000 new rows into this table. However, if the new field1 already exists in the table, it should do an UPDATE, not an INSERT. Which of the following approaches is more efficient? Do a SELECT field1 FROM table (field1 is unique) and store that in a list. Then, for each new row, use list.count() to determine whether to INSERT or UPDATE For each row, run two queries. Firstly, SELECT count(*) FROM table WHERE field1="foo" then either the INSERT or UPDATE. In other words, is it more efficient to perform n+1 queries and search a list, or 2n queries and get sqlite to search?
[ "If I understand your question correctly, it seems like you could simply use SQLite's built in conflict handling mechanism.\nAssuming you have a UNIQUE constraint on field1, you could simple use:\nINSERT OR REPLACE INTO table VALUES (...)\n\nThe following syntax is also supported (identical semantics):\nREPLACE INT...
[ 9, 1, 0, 0 ]
[]
[]
[ "performance", "python", "sqlite" ]
stackoverflow_0003404556_performance_python_sqlite.txt
Q: Building mod_wsgi using python 2.5 on Snow Leopard I'm using the Python 2.5 that came with Mac OS X Snow Leopard (10.6). I've set the defaults value: defaults write com.apple.versioner.python Version 2.5 and normally I get python 2.5 as it suggests. However when I try to build mod_wsgi, that doesn't seem to adhere. I've used the --with-python=/usr/bin/python2.5 option to configure to force it to use python 2.5 but the shared library which is built ends up with references to the python 2.6 libraries. I've also tried: setting $VERSIONER_PYTHON_VERSION to 2.5 before building leaving off --with-python I read through the discussion on a similar SO question. Unlike that person, I'm using stock Mac OS X python which should work with the Frameworks code in the mod_wsgi build process. Here's output of some relevant commands. Note the final output of otool -L at the end which shows that it is looking in the Python 2.6 framework directory. $ make distclean rm -rf .libs rm -f mod_wsgi.o mod_wsgi.la mod_wsgi.lo mod_wsgi.slo mod_wsgi.loT rm -f config.log config.status rm -rf autom4te.cache rm -f Makefile Makefile.in $ ./configure --with-python=/usr/bin/python2.5 checking for apxs2... no checking for apxs... /usr/sbin/apxs checking Apache version... 2.2.14 configure: creating ./config.status config.status: creating Makefile $ make (compilation messages, no errors) $ otool -L .libs/mod_wsgi.so .libs/mod_wsgi.so: /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0) /System/Library/Frameworks/Python.framework/Versions/2.6/Python (compatibility version 2.6.0, current version 2.6.1) A: Try using '--disable-framework' to 'configure'. This will result in -L/-l being used to link Python library rather than framework link. This is necessary as don't know a way to make a framework link use a version other than what is designated as 'Current'.
Building mod_wsgi using python 2.5 on Snow Leopard
I'm using the Python 2.5 that came with Mac OS X Snow Leopard (10.6). I've set the defaults value: defaults write com.apple.versioner.python Version 2.5 and normally I get python 2.5 as it suggests. However when I try to build mod_wsgi, that doesn't seem to adhere. I've used the --with-python=/usr/bin/python2.5 option to configure to force it to use python 2.5 but the shared library which is built ends up with references to the python 2.6 libraries. I've also tried: setting $VERSIONER_PYTHON_VERSION to 2.5 before building leaving off --with-python I read through the discussion on a similar SO question. Unlike that person, I'm using stock Mac OS X python which should work with the Frameworks code in the mod_wsgi build process. Here's output of some relevant commands. Note the final output of otool -L at the end which shows that it is looking in the Python 2.6 framework directory. $ make distclean rm -rf .libs rm -f mod_wsgi.o mod_wsgi.la mod_wsgi.lo mod_wsgi.slo mod_wsgi.loT rm -f config.log config.status rm -rf autom4te.cache rm -f Makefile Makefile.in $ ./configure --with-python=/usr/bin/python2.5 checking for apxs2... no checking for apxs... /usr/sbin/apxs checking Apache version... 2.2.14 configure: creating ./config.status config.status: creating Makefile $ make (compilation messages, no errors) $ otool -L .libs/mod_wsgi.so .libs/mod_wsgi.so: /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0) /System/Library/Frameworks/Python.framework/Versions/2.6/Python (compatibility version 2.6.0, current version 2.6.1)
[ "Try using '--disable-framework' to 'configure'. This will result in -L/-l being used to link Python library rather than framework link. This is necessary as don't know a way to make a framework link use a version other than what is designated as 'Current'.\n" ]
[ 2 ]
[]
[]
[ "macos", "mod_wsgi", "python" ]
stackoverflow_0003534508_macos_mod_wsgi_python.txt
Q: Implementing parser for markdown-like language I have markup language which is similar to markdown and the one used by SO. Legacy parser was based on regexes and was complete nightmare to maintain, so I've come up with my own solution based on EBNF grammar and implemented via mxTextTools/SimpleParse. However, there are issues with some tokens which may include each other, and I don't see a 'right' way to do it. Here is part of my grammar: newline := "\r\n"/"\n"/"\r" indent := ("\r\n"/"\n"/"\r"), [ \t] number := [0-9]+ whitespace := [ \t]+ symbol_mark := [*_>#`%] symbol_mark_noa := [_>#`%] symbol_mark_nou := [*>#`%] symbol_mark_nop := [*_>#`] punctuation := [\(\)\,\.\!\?] noaccent_code := -(newline / '`')+ accent_code := -(newline / '``')+ symbol := -(whitespace / newline) text := -newline+ safe_text := -(newline / whitespace / [*_>#`] / '%%' / punctuation)+/whitespace link := 'http' / 'ftp', 's'?, '://', (-[ \t\r\n<>`^'"*\,\.\!\?]/([,\.\?],?-[ \t\r\n<>`^'"*]))+ strikedout := -[ \t\r\n*_>#`^]+ ctrlw := '^W'+ ctrlh := '^H'+ strikeout := (strikedout, (whitespace, strikedout)*, ctrlw) / (strikedout, ctrlh) strong := ('**', (inline_nostrong/symbol), (inline_safe_nostrong/symbol_mark_noa)* , '**') / ('__' , (inline_nostrong/symbol), (inline_safe_nostrong/symbol_mark_nou)*, '__') emphasis := ('*',?-'*', (inline_noast/symbol), (inline_safe_noast/symbol_mark_noa)*, '*') / ('_',?-'_', (inline_nound/symbol), (inline_safe_nound/symbol_mark_nou)*, '_') inline_code := ('`' , noaccent_code , '`') / ('``' , accent_code , '``') inline_spoiler := ('%%', (inline_nospoiler/symbol), (inline_safe_nop/symbol_mark_nop)*, '%%') inline := (inline_code / inline_spoiler / strikeout / strong / emphasis / link) inline_nostrong := (?-('**'/'__'),(inline_code / reference / signature / inline_spoiler / strikeout / emphasis / link)) inline_nospoiler := (?-'%%',(inline_code / emphasis / strikeout / emphasis / link)) inline_noast := (?-'*',(inline_code / inline_spoiler / strikeout / strong / link)) inline_nound := (?-'_',(inline_code / inline_spoiler / strikeout / strong / link)) inline_safe := (inline_code / inline_spoiler / strikeout / strong / emphasis / link / safe_text / punctuation)+ inline_safe_nostrong := (?-('**'/'__'),(inline_code / inline_spoiler / strikeout / emphasis / link / safe_text / punctuation))+ inline_safe_noast := (?-'*',(inline_code / inline_spoiler / strikeout / strong / link / safe_text / punctuation))+ inline_safe_nound := (?-'_',(inline_code / inline_spoiler / strikeout / strong / link / safe_text / punctuation))+ inline_safe_nop := (?-'%%',(inline_code / emphasis / strikeout / strong / link / safe_text / punctuation))+ inline_full := (inline_code / inline_spoiler / strikeout / strong / emphasis / link / safe_text / punctuation / symbol_mark / text)+ line := newline, ?-[ \t], inline_full? sub_cite := whitespace?, ?-reference, '>' cite := newline, whitespace?, '>', sub_cite*, inline_full? code := newline, [ \t], [ \t], [ \t], [ \t], text block_cite := cite+ block_code := code+ all := (block_cite / block_code / line / code)+ First problem is, spoiler, strong and emphasis can include each other in arbitrary order. And its possible that later I'll need more such inline markups. My current solution involves just creating separate token for each combination (inline_noast, inline_nostrong, etc), but obviously, number of such combinations grows too fast with growing number of markup elements. Second problem is that these lookaheads in strong/emphasis behave VERY poorly on some cases of bad markup like __._.__*__.__...___._.____.__**___*** (lots of randomly placed markup symbols). It takes minutes to parse few kb of such random text. Is it something wrong with my grammar or I should use some other kind of parser for this task? A: If one thing includes another, then normally you treat them as separate tokens and then nest them in the grammar. Lepl (http://www.acooke.org/lepl which I wrote) and PyParsing (which is probably the most popular pure-Python parser) both allow you to nest things recursively. So in Lepl you could write code something like: # these are tokens (defined as regexps) stg_marker = Token(r'\*\*') emp_marker = Token(r'\*') # tokens are longest match, so strong is preferred if possible spo_marker = Token(r'%%') .... # grammar rules combine tokens contents = Delayed() # this will be defined later and lets us recurse strong = stg_marker + contents + stg_marker emphasis = emp_marker + contents + emp_marker spoiler = spo_marker + contents + spo_marker other_stuff = ..... contents += strong | emphasis | spoiler | other_stuff # this defines contents recursively Then you can see, I hope, how contents will match nested use of strong, emphasis, etc. There's much more than this to do for your final solution, and efficiency could be an issue in any pure-Python parser (There are some parsers that are implemented in C but callable from Python. These will be faster, but may be trickier to use; I can't recommend any because I haven't used them).
Implementing parser for markdown-like language
I have markup language which is similar to markdown and the one used by SO. Legacy parser was based on regexes and was complete nightmare to maintain, so I've come up with my own solution based on EBNF grammar and implemented via mxTextTools/SimpleParse. However, there are issues with some tokens which may include each other, and I don't see a 'right' way to do it. Here is part of my grammar: newline := "\r\n"/"\n"/"\r" indent := ("\r\n"/"\n"/"\r"), [ \t] number := [0-9]+ whitespace := [ \t]+ symbol_mark := [*_>#`%] symbol_mark_noa := [_>#`%] symbol_mark_nou := [*>#`%] symbol_mark_nop := [*_>#`] punctuation := [\(\)\,\.\!\?] noaccent_code := -(newline / '`')+ accent_code := -(newline / '``')+ symbol := -(whitespace / newline) text := -newline+ safe_text := -(newline / whitespace / [*_>#`] / '%%' / punctuation)+/whitespace link := 'http' / 'ftp', 's'?, '://', (-[ \t\r\n<>`^'"*\,\.\!\?]/([,\.\?],?-[ \t\r\n<>`^'"*]))+ strikedout := -[ \t\r\n*_>#`^]+ ctrlw := '^W'+ ctrlh := '^H'+ strikeout := (strikedout, (whitespace, strikedout)*, ctrlw) / (strikedout, ctrlh) strong := ('**', (inline_nostrong/symbol), (inline_safe_nostrong/symbol_mark_noa)* , '**') / ('__' , (inline_nostrong/symbol), (inline_safe_nostrong/symbol_mark_nou)*, '__') emphasis := ('*',?-'*', (inline_noast/symbol), (inline_safe_noast/symbol_mark_noa)*, '*') / ('_',?-'_', (inline_nound/symbol), (inline_safe_nound/symbol_mark_nou)*, '_') inline_code := ('`' , noaccent_code , '`') / ('``' , accent_code , '``') inline_spoiler := ('%%', (inline_nospoiler/symbol), (inline_safe_nop/symbol_mark_nop)*, '%%') inline := (inline_code / inline_spoiler / strikeout / strong / emphasis / link) inline_nostrong := (?-('**'/'__'),(inline_code / reference / signature / inline_spoiler / strikeout / emphasis / link)) inline_nospoiler := (?-'%%',(inline_code / emphasis / strikeout / emphasis / link)) inline_noast := (?-'*',(inline_code / inline_spoiler / strikeout / strong / link)) inline_nound := (?-'_',(inline_code / inline_spoiler / strikeout / strong / link)) inline_safe := (inline_code / inline_spoiler / strikeout / strong / emphasis / link / safe_text / punctuation)+ inline_safe_nostrong := (?-('**'/'__'),(inline_code / inline_spoiler / strikeout / emphasis / link / safe_text / punctuation))+ inline_safe_noast := (?-'*',(inline_code / inline_spoiler / strikeout / strong / link / safe_text / punctuation))+ inline_safe_nound := (?-'_',(inline_code / inline_spoiler / strikeout / strong / link / safe_text / punctuation))+ inline_safe_nop := (?-'%%',(inline_code / emphasis / strikeout / strong / link / safe_text / punctuation))+ inline_full := (inline_code / inline_spoiler / strikeout / strong / emphasis / link / safe_text / punctuation / symbol_mark / text)+ line := newline, ?-[ \t], inline_full? sub_cite := whitespace?, ?-reference, '>' cite := newline, whitespace?, '>', sub_cite*, inline_full? code := newline, [ \t], [ \t], [ \t], [ \t], text block_cite := cite+ block_code := code+ all := (block_cite / block_code / line / code)+ First problem is, spoiler, strong and emphasis can include each other in arbitrary order. And its possible that later I'll need more such inline markups. My current solution involves just creating separate token for each combination (inline_noast, inline_nostrong, etc), but obviously, number of such combinations grows too fast with growing number of markup elements. Second problem is that these lookaheads in strong/emphasis behave VERY poorly on some cases of bad markup like __._.__*__.__...___._.____.__**___*** (lots of randomly placed markup symbols). It takes minutes to parse few kb of such random text. Is it something wrong with my grammar or I should use some other kind of parser for this task?
[ "If one thing includes another, then normally you treat them as separate tokens and then nest them in the grammar. Lepl (http://www.acooke.org/lepl which I wrote) and PyParsing (which is probably the most popular pure-Python parser) both allow you to nest things recursively.\nSo in Lepl you could write code someth...
[ 6 ]
[]
[]
[ "ebnf", "grammar", "markup", "parsing", "python" ]
stackoverflow_0003535706_ebnf_grammar_markup_parsing_python.txt
Q: google appengine datastore client Is there a tool/client to view inside and make queries for google appengine datastore? A: Starting with release 1.1.9 of the App Engine SDK, however, there's a new way to interact with the datastore, in the form of the remote_api module. This module allows remote access to the App Engine datastore, using the same APIs you know and love from writing App Engine Apps. http://code.google.com/appengine/articles/remote_api.html And some wrapper around it: Today, I will share with you a simple script – remote.py – which can do all the necessary staging in order for us to talk with our App Engine back-end at Google. remote.py provides a single function attach(host), which will configure the API to communicate with the specified host. This will allow us to easily write scripts that interact with the live serving application, or if we need to, a newly-deployed version. http://blog.onideas.ws/remote_api.gae A: You can login at AppSpot and go to the "Datastore Viewer". You can run custom GQL queries and view/edit entities in the datastore.
google appengine datastore client
Is there a tool/client to view inside and make queries for google appengine datastore?
[ "\nStarting with release 1.1.9 of the App Engine SDK, however, there's a new way to interact with the datastore, in the form of the remote_api module. This module allows remote access to the App Engine datastore, using the same APIs you know and love from writing App Engine Apps.\n\n\nhttp://code.google.com/appengi...
[ 3, 1 ]
[]
[]
[ "client", "command_line", "google_app_engine", "python" ]
stackoverflow_0003536770_client_command_line_google_app_engine_python.txt
Q: How to create an excel chart using py-appscript? I am using Excel 2011 v14 and trying to dynamically create a chart based on the selected range on my worksheet. To select a range, I use the following code segment: xl = app('Microsoft Excel') tcell = 'B' qcell = 'C' for r in xrange(2, 16): xl.cells[tcell + str(r)].value.set(r) xl.cells[qcell + str(r)].value.set(random.randint(2, 100)) xl.cells["B2:C15"].select() xl.make(new=k.chart, at=xl.active_sheet) but I got a blank chart on the active sheet. Any help will be appreciated. A: As I suggested to someone else who had a similar question, you should sort out how to make this work in native Applescript first and then port to py-appscript. There is a lot that can go wrong in your code snippet and there could be (and usually are) errors being returned by Applescript that the framework doesn't carry all the way back to you.
How to create an excel chart using py-appscript?
I am using Excel 2011 v14 and trying to dynamically create a chart based on the selected range on my worksheet. To select a range, I use the following code segment: xl = app('Microsoft Excel') tcell = 'B' qcell = 'C' for r in xrange(2, 16): xl.cells[tcell + str(r)].value.set(r) xl.cells[qcell + str(r)].value.set(random.randint(2, 100)) xl.cells["B2:C15"].select() xl.make(new=k.chart, at=xl.active_sheet) but I got a blank chart on the active sheet. Any help will be appreciated.
[ "As I suggested to someone else who had a similar question, you should sort out how to make this work in native Applescript first and then port to py-appscript. There is a lot that can go wrong in your code snippet and there could be (and usually are) errors being returned by Applescript that the framework doesn't ...
[ 0 ]
[]
[]
[ "applescript", "charts", "excel", "python" ]
stackoverflow_0003533305_applescript_charts_excel_python.txt
Q: gtk logic behind treeviewcolumns needing cell renderers From what I understand about GTK, if I have a TreeView, I can't just use any widget I want to display information about a column. For text, you need a gtk.CellRendererText. For toggle buttons, a gtk.CellRendererToggle. For anything else, it seems you have to implement yourself, which, from a sample one for buttons that I saw, doesn't look straightforward. Firstly, is this the case? Is there an easy way to set up whatever widget you want to be used to display some text? If not, then why is it implemented this way? If I were designing GTK i would just create some sort of system where when a row was added and when some data model information changes, user-specified callbacks would be called which would add the appropriate widget or change it, respectively. A: To write a custom CellRenderer (copy-pasted from this link!): Register some new properties that your renderer needs with the type system and write your own set_property and get_property functions to set and get your new renderer's properties. Write your own cell_renderer_get_size function and override the parent object's function (usually the parent is of type GtkCellRenderer. Note that you should honour the standard properties for padding and cell alignment of the parent object here. Write your own cell_renderer_render function and override the parent object's function. This function does the actual rendering. And there is a good/simple example for pyGTK. Writing a custom CellRenderer is not too hard, the hardness is that how to write a custom widget. If you have learned how to write a custom widget, then writing a custom CellRenderer is easy. The logic behind this design is flexibility. A TreeViewColumn indicates how the data (from a TreeModel) should be displayed by a CellRenderer, thus a TreeViewColumn which represents a value of boolean type, can be displayed as a text (CellRendererText) or can be displayed as a check box (CellRendererToggle). e.g. a TreeViewColumn which represents a value of integer type, can be displayed as a text (CellRendererText) or can be displayed as a progress bar (CellRendererProgress) or can be displayed as a spin button (CellRendererSpin) or can be displayed as everything that we want.
gtk logic behind treeviewcolumns needing cell renderers
From what I understand about GTK, if I have a TreeView, I can't just use any widget I want to display information about a column. For text, you need a gtk.CellRendererText. For toggle buttons, a gtk.CellRendererToggle. For anything else, it seems you have to implement yourself, which, from a sample one for buttons that I saw, doesn't look straightforward. Firstly, is this the case? Is there an easy way to set up whatever widget you want to be used to display some text? If not, then why is it implemented this way? If I were designing GTK i would just create some sort of system where when a row was added and when some data model information changes, user-specified callbacks would be called which would add the appropriate widget or change it, respectively.
[ "To write a custom CellRenderer (copy-pasted from this link!):\n\n\nRegister some new properties that your\n renderer needs with the type system\n and write your own set_property and\n get_property functions to set and get\n your new renderer's properties.\nWrite your own cell_renderer_get_size\n function and ...
[ 2 ]
[]
[]
[ "gtk", "pygtk", "python", "user_interface" ]
stackoverflow_0003533442_gtk_pygtk_python_user_interface.txt
Q: How to get all the minimum elements according to its first element of the inside list in a nested list? Simply put! there is this list say LST = [[12,1],[23,2],[16,3],[12,4],[14,5]] and i want to get all the minimum elements of this list according to its first element of the inside list. So for the above example the answer would be [12,1] and [12,4]. Is there any typical way in python of doing this? Thanking you in advance. A: Two passes: minval = min(LST)[0] return [x for x in LST if x[0] == minval] One pass: def all_minima(iterable, key=None): if key is None: key = id hasminvalue = False minvalue = None minlist = [] for entry in iterable: value = key(entry) if not hasminvalue or value < minvalue: minvalue = value hasminvalue = True minlist = [entry] elif value == minvalue: minlist.append(entry) return minlist from operator import itemgetter return all_minima(LST, key=itemgetter(0)) A: A compact single-pass solution requires sorting the list -- that's technically O(N log N) for an N-long list, but Python's sort is so good, and so many sequences "just happen" to have some embedded order in them (which timsort cleverly exploits to go faster), that sorting-based solutions sometimes have surprisingly good performance in the real world. Here's a solution requiring 2.6 or better: import itertools import operator f = operator.itemgetter(0) def minima(lol): return list(next(itertools.groupby(sorted(lol, key=f), key=f))[1]) To understand this approach, looking "from the inside, outwards" helps. f, i.e., operator.itemgetter(0), is a key-function that picks the first item of its argument for ordering purposes -- the very purpose of operator.itemgetter is to easily and compactly build such functions. sorted(lol, key=f) therefore returns a sorted copy of the list-of-lists lol, ordered by increasing first item. If you omit the key=f the sorted copy will be ordered lexicographically, so it will also be in order of increasing first item, but that acts only as the "primary key" -- items with the same first sub-item will in turn be sorted among them by the values of their second sub-items, and so forth -- while with the key=f you're guaranteed to preserve the original order among items with the same first sub-item. You don't specify which behavior you require (and in your example the two behaviors happen to produce the same result, so we cannot distinguish from that example) which is why I'm carefully detailing both possibilities so you can choose. itertools.groupby(sorted(lol, key=f), key=f) performs the "grouping" task that is the heart of the operation: it yields groups from the sequence (in this case, the sequence sorted provides) based on the key ordering criteria. That is, a group with all adjacent items producing the same value among themselves when you call f with the item as an argument, then a group with all adjacent item producing a different value from the first group (but same among themselves), and so forth. groupby respect the ordering of the sequence it takes as its argument, which is why we had to sort the lol first (and this behavior of groupby makes it very useful in many cases in which the sequence's ordering does matter). Each result yielded by groupby is a pair k, g: a key k which is the result of f(i) on each item in the group, an iterator g which yields each item in the group in sequence. The next built-in (the only bit in this solution which requires Python 2.6) given an iterator produces its next item -- in particular, the first item when called on a fresh, newly made iterator (and, every generator of course is an iterator, as is groupby's result). In earlier Python versions, it would have to be groupby(...).next() (since next was only a method of iterators, not a built-in), which is deprecated since 2.6. So, summarizing, the result of our next(...) is exactly the pair k, g where k is the minimum (i.e., first after sorting) value for the first sub-item, and g is an iterator for the group's items. So, with that [1] we pick just the iterator, so we have an iterator yielding just the subitems we want. Since we want a list, not an iterator (per your specs), the outermost list(...) call completes the job. Is all of this worth it, performance-wise? Not on the tiny example list you give -- minima is actually slower than either code in @Kenny's answer (of which the first, "two-pass" solution is speedier). I just think it's worth keeping the ideas in mind for the next sequence processing problem you may encounter, where the details of typical inputs may be quite different (longer lists, rarer minima, partial ordering in the input, &c, &c-). A: m = min(LST, key=operator.itemgetter(0))[0] print [x for x in LST if x[0] == m]
How to get all the minimum elements according to its first element of the inside list in a nested list?
Simply put! there is this list say LST = [[12,1],[23,2],[16,3],[12,4],[14,5]] and i want to get all the minimum elements of this list according to its first element of the inside list. So for the above example the answer would be [12,1] and [12,4]. Is there any typical way in python of doing this? Thanking you in advance.
[ "Two passes:\nminval = min(LST)[0]\nreturn [x for x in LST if x[0] == minval]\n\nOne pass:\ndef all_minima(iterable, key=None):\n if key is None: key = id\n hasminvalue = False\n minvalue = None\n minlist = []\n for entry in iterable:\n value = key(entry)\n if not hasminvalue or value < minvalue:\n ...
[ 5, 3, 2 ]
[ "minval = min(x[0] for x in LST)\nresult = [x for x in LST if x[0]==minval]\n\n" ]
[ -1 ]
[ "list", "minimum", "python" ]
stackoverflow_0003537170_list_minimum_python.txt
Q: python import error what's wrong with my imports? App folder structure: myapp/ models/models.py contains SpotModel() tests/tests.py contains TestSpotModel(unittest.TestCase). tests.py imports from myapp.models.models import * which works like a charm scripts/import.py contains from myapp.models.models import * the problem is that import.py when executed results in an error: ImportError: No module named myapp.models.models but tests.py runs. I have __init__.py files in myapp/__init__.py, myapp/models/__init__.py, myapp/tests/__init__.py and as mentioned, running the unit tests using nosetests works as intended. A: It is __init__.py not init.py. Make sure each of the directory in hierarchy contains it in order to be able to import. EDIT: I managed to reproduce it. Here's the directory structure: cesar@cesar-laptop:/tmp/asdasd$ tree . `-- myapp |-- __init__.py |-- models | |-- __init__.py | `-- models.py |-- scripts | |-- data.py | `-- __init__.py `-- tests |-- __init__.py `-- tests.py I put the following code at the very beginning of the data.py to narrow down the problem: import sys import pprint pprint.pprint(sys.path) from myapp.models.models import * Running the data.py the way OP indicated yeilds ImportError: cesar@cesar-laptop:/tmp/asdasd$ python myapp/scripts/data.py ['/tmp/asdasd/myapp/scripts', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', -- Skipped -- '/usr/local/lib/python2.6/dist-packages'] Traceback (most recent call last): File "myapp/scripts/data.py", line 6, in from myapp.models.models import * ImportError: No module named myapp.models.models But this way works like a charm: cesar@cesar-laptop:/tmp/asdasd$ python -m myapp.scripts.data ['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', -- Skipped -- '/usr/local/lib/python2.6/dist-packages'] Note the difference in the first entry of sys.path. A: How are you executing import.py? What is the current working directory when you do so? The myapp directory must be on the Python path (ie. inside one of the directories listed in sys.path) for you to be able to import it. Python automatically adds the current working directory to the path list at interpreter startup time. So if the directory that contains myapp is not added to the path manually (eg. using the PYTHONPATH environment variable, or adding it to sys.path in sitecustomize.py), you will need to be in the directory containing myapp when you run the script. If you're inside the myapp directory itself, you won't be able to import the myapp package. A: Your sys.path is clearly not set the same way when you're running the test and when you're running the script. Do import sys print(sys.path) at the top of both modules to confirm that. Then, fix the one that's wrong (by appending to sys.path the parent directory of myapp in the case where it's missing. A: Unless you forgot to mention it, you don't have a __init__.py in myapp/scripts, so myapp/scripts/import.py is not a module of myapp. Unless myapp is in your global path somehow, the script can't find it because it won't be looking for it in the right place. Either make your scripts folder a module by adding a __init__.py to it, move the scripts up the filesystem hierarchy (either into myapp or into its parent folder) or install myapp into your path (i.e. move it to your packages folder, e.g. /usr/lib/python2.6/dist-packages/).
python import error
what's wrong with my imports? App folder structure: myapp/ models/models.py contains SpotModel() tests/tests.py contains TestSpotModel(unittest.TestCase). tests.py imports from myapp.models.models import * which works like a charm scripts/import.py contains from myapp.models.models import * the problem is that import.py when executed results in an error: ImportError: No module named myapp.models.models but tests.py runs. I have __init__.py files in myapp/__init__.py, myapp/models/__init__.py, myapp/tests/__init__.py and as mentioned, running the unit tests using nosetests works as intended.
[ "It is __init__.py not init.py. Make sure each of the directory in hierarchy contains it in order to be able to import.\nEDIT: I managed to reproduce it.\nHere's the directory structure:\n\ncesar@cesar-laptop:/tmp/asdasd$ tree\n.\n`-- myapp\n |-- __init__.py\n |-- models\n | |-- __init__.py\n | `-- ...
[ 4, 1, 1, 0 ]
[]
[]
[ "importerror", "python", "python_import" ]
stackoverflow_0003537850_importerror_python_python_import.txt
Q: pyAMF for GAE (Google App Engine), little help needed: # I need this behaviour: # 1) check if the service from flash is included in the services array # 2) if not, return false or an error | if yes, step 3 # 3) combine the rootPath('app.controllers') with the service name('sub1.sub2.sub3.function_name') # 4) and then get the function('function_name') from the 'app.controllers.sub1.sub2.sub3.function_name' package # 5) then run the function the way that would be done normally by pyAMF from app.controllers.users.login import login from app.controllers.users.logout import logout from app.controllers.profiles.edit import edit as profilesEdit from app.controllers.profiles.new import new as profilesNew from app.controllers.invitations.invite import invite as invitationsInvite from app.controllers.invitations.uninvite import uninvite as invitationsUninvite def main(): services = { 'users.login': login, 'users.logout': logout, 'profiles.edit': profilesEdit, 'profiles.new': profilesNew, 'invitations.invite': invitationsInvite, 'invitations.uninvite': invitationsUninvite } gateway = WebAppGateway(services, logger=logging, debug=True) application = webapp.WSGIApplication([('/', Init), ('/ajax', gateway)], debug=True) run_wsgi_app(application) insted of this I would like: def main(): services = [ 'users.login', 'users.logout', 'profiles.edit', 'profiles.new', 'invitations.invite', 'invitations.uninvite', 'sub1.sub2.sub3.function_name' ] rootPath = 'app.controllers' gateway = WebAppGateway(services, rootPath, logger=logging, debug=True) application = webapp.WSGIApplication([('/', Init), ('/ajax', gateway)], debug=True) run_wsgi_app(application) # and then I would extend the WebAppGateway in some way to have this behaviour: # 1) check if the service from flash is included in the services array # 2) if not, return false or an error | if yes, step 3 # 3) combine the rootPath('app.controllers') with the service name('sub1.sub2.sub3.function_name') # 4) and then get the function('function_name') from the 'app.controllers.sub1.sub2.sub3.function_name' package # 5) then run the function the way that would be done normally by pyAMF is this possible? thanks A: Solved last night! thanks @njoyce from pyamf.remoting.gateway.google import WebAppGateway import logging class TottysGateway(WebAppGateway): def __init__(self, services_available, root_path, not_found_service, logger, debug): # override the contructor and then call the super self.services_available = services_available self.root_path = root_path self.not_found_service = not_found_service WebAppGateway.__init__(self, {}, logger=logging, debug=True) def getServiceRequest(self, request, target): # override the original getServiceRequest method try: # try looking for the service in the services list return WebAppGateway.getServiceRequest(self, request, target) except: pass try: # don't know what it does but is an error for now service_func = self.router(target) except: if(target in self.services_available): # only if is an available service import it's module # so it doesn't access services that should be hidden try: module_path = self.root_path + '.' + target paths = target.rsplit('.') func_name = paths[len(paths) - 1] import_as = '_'.join(paths) + '_' + func_name import_string = "from "+module_path+" import "+func_name+' as service_func' exec import_string except: service_func = False if(not service_func): # if is not found load the default not found service module_path = self.rootPath + '.' + self.not_found_service import_string = "from "+module_path+" import "+func_name+' as service_func' # add the service loaded above assign_string = "self.addService(service_func, target)" exec assign_string return WebAppGateway.getServiceRequest(self, request, target)
pyAMF for GAE (Google App Engine), little help needed:
# I need this behaviour: # 1) check if the service from flash is included in the services array # 2) if not, return false or an error | if yes, step 3 # 3) combine the rootPath('app.controllers') with the service name('sub1.sub2.sub3.function_name') # 4) and then get the function('function_name') from the 'app.controllers.sub1.sub2.sub3.function_name' package # 5) then run the function the way that would be done normally by pyAMF from app.controllers.users.login import login from app.controllers.users.logout import logout from app.controllers.profiles.edit import edit as profilesEdit from app.controllers.profiles.new import new as profilesNew from app.controllers.invitations.invite import invite as invitationsInvite from app.controllers.invitations.uninvite import uninvite as invitationsUninvite def main(): services = { 'users.login': login, 'users.logout': logout, 'profiles.edit': profilesEdit, 'profiles.new': profilesNew, 'invitations.invite': invitationsInvite, 'invitations.uninvite': invitationsUninvite } gateway = WebAppGateway(services, logger=logging, debug=True) application = webapp.WSGIApplication([('/', Init), ('/ajax', gateway)], debug=True) run_wsgi_app(application) insted of this I would like: def main(): services = [ 'users.login', 'users.logout', 'profiles.edit', 'profiles.new', 'invitations.invite', 'invitations.uninvite', 'sub1.sub2.sub3.function_name' ] rootPath = 'app.controllers' gateway = WebAppGateway(services, rootPath, logger=logging, debug=True) application = webapp.WSGIApplication([('/', Init), ('/ajax', gateway)], debug=True) run_wsgi_app(application) # and then I would extend the WebAppGateway in some way to have this behaviour: # 1) check if the service from flash is included in the services array # 2) if not, return false or an error | if yes, step 3 # 3) combine the rootPath('app.controllers') with the service name('sub1.sub2.sub3.function_name') # 4) and then get the function('function_name') from the 'app.controllers.sub1.sub2.sub3.function_name' package # 5) then run the function the way that would be done normally by pyAMF is this possible? thanks
[ "Solved last night! thanks @njoyce\nfrom pyamf.remoting.gateway.google import WebAppGateway\nimport logging\n\nclass TottysGateway(WebAppGateway):\ndef __init__(self, services_available, root_path, not_found_service, logger, debug):\n # override the contructor and then call the super\n self.services_available...
[ 0 ]
[]
[]
[ "google_app_engine", "pyamf", "python", "web_applications" ]
stackoverflow_0003535802_google_app_engine_pyamf_python_web_applications.txt
Q: I'm using pyAMF in my app, but I want to set smart service like explained here: In a normal application i set services services = { 'users.login': login, 'test': router } but I would like to do like this: services = [ 'users.login', 'test' ] and every request goes to router function. this takes 2 params: service name (can be "users.login" or "test" in this case) and input (that is the object sent by flex to python) then if the command(service) from flex is named "users.login". I would like to run the router with the params and then this will open the function login in the commands.users.login package. How would I do that? Thanks. A: If I understand your question correctly, in order to achieve this, you are going to need to to override getServiceRequest on the Gateway class that you are using: from pyamf.remoting.gateway.django import DjangoGateway from pyamf.remoting.gateway import UnknownServiceError class MyGateway(DjangoGateway): def __init__(self, router_func, **kwargs): self.router = router_func DjangoGateway.__init__(self, **kwargs) def getServiceRequest(self, request, target): try: return DjangoGateway.getServiceRequest(self, request, target) except UnknownServiceError, e: pass # cached service was not found, try to discover it try: service_func = self.router(target) except: # perhaps some logging here service_func = None if not service_func: # couldn't find a service matching `target`, crap out appropriately raise e self.addService(service_func, target) return DjangoGateway.getServiceRequest(self, request, target) self.router is a function that you supply to the constructor of the gateway. It takes the string target of the AMF remoting request and returns a matching function. If it returns None or raises an exception, an unknown service response will be returned to the requestor. Hopefully this goes some way to laying the groundwork for what you require. A: Solved last night! from pyamf.remoting.gateway.google import WebAppGateway import logging class TottysGateway(WebAppGateway): def __init__(self, services_available, root_path, not_found_service, logger, debug): # override the contructor and then call the super self.services_available = services_available self.root_path = root_path self.not_found_service = not_found_service WebAppGateway.__init__(self, {}, logger=logging, debug=True) def getServiceRequest(self, request, target): # override the original getServiceRequest method try: # try looking for the service in the services list return WebAppGateway.getServiceRequest(self, request, target) except: pass try: # don't know what it does but is an error for now service_func = self.router(target) except: if(target in self.services_available): # only if is an available service import it's module # so it doesn't access services that should be hidden try: module_path = self.root_path + '.' + target paths = target.rsplit('.') func_name = paths[len(paths) - 1] import_as = '_'.join(paths) + '_' + func_name import_string = "from "+module_path+" import "+func_name+' as service_func' exec import_string except: service_func = False if(not service_func): # if is not found load the default not found service module_path = self.rootPath + '.' + self.not_found_service import_string = "from "+module_path+" import "+func_name+' as service_func' # add the service loaded above assign_string = "self.addService(service_func, target)" exec assign_string return WebAppGateway.getServiceRequest(self, request, target)
I'm using pyAMF in my app, but I want to set smart service like explained here:
In a normal application i set services services = { 'users.login': login, 'test': router } but I would like to do like this: services = [ 'users.login', 'test' ] and every request goes to router function. this takes 2 params: service name (can be "users.login" or "test" in this case) and input (that is the object sent by flex to python) then if the command(service) from flex is named "users.login". I would like to run the router with the params and then this will open the function login in the commands.users.login package. How would I do that? Thanks.
[ "If I understand your question correctly, in order to achieve this, you are going to need to to override getServiceRequest on the Gateway class that you are using:\nfrom pyamf.remoting.gateway.django import DjangoGateway\nfrom pyamf.remoting.gateway import UnknownServiceError\n\n\nclass MyGateway(DjangoGateway):\n ...
[ 2, 0 ]
[]
[]
[ "pyamf", "python" ]
stackoverflow_0003357342_pyamf_python.txt
Q: How to reconstruct python source from loaded modules (sys.modules)? Is it possible to construct human readable source for loaded modules if you have access to sys.modules? People tell me you cannot, but I'm sure it is possible in Python. A: You can disassemble a Python-coded module using the dis module of the standard library: that produces definitely human readable source, just not Python source, but rather bytecode source. Putting eggs back together starting from the omelette is a tad harder. There used to be a decompiler for Python 2.3 (see here) but I don't know if anybody's been maintaining it over the last several years, which suggests there isn't much interest in this task in the open source community. If you disagree, you could fork that project, making your own project with the goal of decompiling 2.7 (or whatever Python release you crave to decompile for), and attract others enthusiastic about this task -- if you can find them, that is. A: Generally, the source code will be available in the file system, in places that can be easily discovered from sys.modules. for name, mod in sys.modules.items(): try: fname = mod.__file__ except AttributeError: continue if fname.endswith(".pyc"): fname = fname[:-1] try: fcode = open(fname) except IOError: continue code = fcode.read() # .. do something with name and code
How to reconstruct python source from loaded modules (sys.modules)?
Is it possible to construct human readable source for loaded modules if you have access to sys.modules? People tell me you cannot, but I'm sure it is possible in Python.
[ "You can disassemble a Python-coded module using the dis module of the standard library: that produces definitely human readable source, just not Python source, but rather bytecode source. Putting eggs back together starting from the omelette is a tad harder.\nThere used to be a decompiler for Python 2.3 (see here...
[ 4, 0 ]
[]
[]
[ "decompiling", "python", "reverse_engineering" ]
stackoverflow_0003538236_decompiling_python_reverse_engineering.txt
Q: Any one have an example that uses the element.sourceline method from lxml.html I hope I asked that correctly. I am trying to figure out what element.sourceline does and if there is some way I can use its features. I have tried building my elements from the html a number of ways but every time I iterate through my elements and ask for sourceline I always get None. When I tried to use the built-in help I done't get anything either. I have Googled for an example but none were found yet. I know it is a method of elements not trees but that is the best I have been able to come up with. In response to Jim Garrison's request for an example theTree=html.parse(open(r'c:\temp\testlxml.htm')) check_source the_elements=[(e,e.sourceline) for e in theTree.iter()] #trying to get the sourceline for each in the_elements: if each[1]!=None: check_source.append(each) When I run this len(check_source)==0 My htm file has 19,379 lines so I am not sure you want to see it I tried one solution >>> myroot=html.fromstring(xml) >>> elementlines=[(e,e.sourceline) for e in myroot.iter()] >>> elementlines [(<Element doc at 12bb730>, None), (<Element foo at 12bb650>, None)] When I do the same thing with etree I get what was demonstrated >>> myroot=etree.fromstring(xml) >>> elementlines=[(e,e.sourceline) for e in myroot.iter()] >>> elementlines [(<Element doc at 36a6b70>, 1), (<Element foo at 277b4e0>, 2)] But my source htm is so messy I can't use etree to explore the tree I get an error A: sourceline will return the line number determined at the time of parsing a document. So it won't apply to an Element that was added through the API. For example: from lxml import etree xml = '<doc>\n<foo>rain in spain</foo>\n</doc>' root = etree.fromstring(xml) print root.find('foo').sourceline # 2 root.append(etree.Element('bar')) print etree.tostring(root) print root.find('bar').sourceline # None I'm pretty sure the same applies to lxml.html.
Any one have an example that uses the element.sourceline method from lxml.html
I hope I asked that correctly. I am trying to figure out what element.sourceline does and if there is some way I can use its features. I have tried building my elements from the html a number of ways but every time I iterate through my elements and ask for sourceline I always get None. When I tried to use the built-in help I done't get anything either. I have Googled for an example but none were found yet. I know it is a method of elements not trees but that is the best I have been able to come up with. In response to Jim Garrison's request for an example theTree=html.parse(open(r'c:\temp\testlxml.htm')) check_source the_elements=[(e,e.sourceline) for e in theTree.iter()] #trying to get the sourceline for each in the_elements: if each[1]!=None: check_source.append(each) When I run this len(check_source)==0 My htm file has 19,379 lines so I am not sure you want to see it I tried one solution >>> myroot=html.fromstring(xml) >>> elementlines=[(e,e.sourceline) for e in myroot.iter()] >>> elementlines [(<Element doc at 12bb730>, None), (<Element foo at 12bb650>, None)] When I do the same thing with etree I get what was demonstrated >>> myroot=etree.fromstring(xml) >>> elementlines=[(e,e.sourceline) for e in myroot.iter()] >>> elementlines [(<Element doc at 36a6b70>, 1), (<Element foo at 277b4e0>, 2)] But my source htm is so messy I can't use etree to explore the tree I get an error
[ "sourceline will return the line number determined at the time of parsing a document. So it won't apply to an Element that was added through the API. For example:\nfrom lxml import etree\n\nxml = '<doc>\\n<foo>rain in spain</foo>\\n</doc>'\nroot = etree.fromstring(xml)\n\nprint root.find('foo').sourceline # 2\n\n...
[ 3 ]
[]
[]
[ "html", "lxml", "parsing", "python" ]
stackoverflow_0003538248_html_lxml_parsing_python.txt
Q: Does python have a robust pop3, smtp, mime library where I could build a webmail interface? Does python have a full fledged email library with things for pop, smtp, pop3 with ssl, mime? I want to create a web mail interface that pulls emails from email servers, and then shows the emails, along with attachments, can display the sender, subject, etc. (handles all the encoding issues etc). It's one thing to be available in the libraries and another for them to be production ready. I'm hoping someone who has used them to pull emails w/attachments etc. in a production environment can comment on this. A: It has all the components you need, in a more modular and flexible arrangement than you appear to envisage -- the standard library's email package deals with the message once you have received it, and separate modules each deal with means of sending and receiving, such as pop, smtp, imap. SSL is an option for each of them (if the counterpart, e.g. mail server, supports it, of course), being basically just "a different kind of socket". Have you looked at the rich online docs for all of these standard library modules? A: http://posterity.edgewall.org/ http://pypi.python.org/pypi/webmail/1.1.7 http://bobomail.sourceforge.net/ Step 1. Download the above. Step 2. Read the source. Step 3. See what libraries they use. Step 4. Use the same libraries.
Does python have a robust pop3, smtp, mime library where I could build a webmail interface?
Does python have a full fledged email library with things for pop, smtp, pop3 with ssl, mime? I want to create a web mail interface that pulls emails from email servers, and then shows the emails, along with attachments, can display the sender, subject, etc. (handles all the encoding issues etc). It's one thing to be available in the libraries and another for them to be production ready. I'm hoping someone who has used them to pull emails w/attachments etc. in a production environment can comment on this.
[ "It has all the components you need, in a more modular and flexible arrangement than you appear to envisage -- the standard library's email package deals with the message once you have received it, and separate modules each deal with means of sending and receiving, such as pop, smtp, imap. SSL is an option for eac...
[ 2, 2 ]
[]
[]
[ "email", "mime", "pop3", "python", "smtp" ]
stackoverflow_0003538430_email_mime_pop3_python_smtp.txt
Q: Casting sockets to subtypes I'm trying to create my own subclass of socket.socket that will be able to handle custom messages. So far my code looks like this: self._sockets.append(s) logging.debug("Waiting for incoming connections on port %d" % (port)) while not self.shutdown: inputready,outputready,exceptready = select(self._sockets,[],[]) print "Select returned" for i in inputready: if s == i: # handle the server socket client, address = s.accept() self._sockets.append(client) print "%r , %r" % (client, address) else: # handle all other sockets s.handleMessage() so as you can see I'm either acceptin new connections or if it returned from another socket it'll call handleMessage on that socket. Now the problem is that off course socket.accept() will return a socket.socket and not my subclass which implements the handleMessage function. What would be the easiest way to get my custom class instead of the default socket.socket? A: From your description it appears that you are making a message handler that has-a socket (or sockets). When designing classes has-a indicates composition and delegation while is-a can indicate inheritance. So it is not appropriate to inherit from socket.socket, and your code is already looking a bit hybrid. Something like this really coarse pseudo-code is probably best suited to the task: class MyMessageHandler(object): def __init__(self): self.sockets = [...] def wait(self): debug('waiting...') i, o, e = select(...) A: How difficult is it to setup a dictionary mapping socket descriptors to your socket wrapper objects?
Casting sockets to subtypes
I'm trying to create my own subclass of socket.socket that will be able to handle custom messages. So far my code looks like this: self._sockets.append(s) logging.debug("Waiting for incoming connections on port %d" % (port)) while not self.shutdown: inputready,outputready,exceptready = select(self._sockets,[],[]) print "Select returned" for i in inputready: if s == i: # handle the server socket client, address = s.accept() self._sockets.append(client) print "%r , %r" % (client, address) else: # handle all other sockets s.handleMessage() so as you can see I'm either acceptin new connections or if it returned from another socket it'll call handleMessage on that socket. Now the problem is that off course socket.accept() will return a socket.socket and not my subclass which implements the handleMessage function. What would be the easiest way to get my custom class instead of the default socket.socket?
[ "From your description it appears that you are making a message handler that has-a socket (or sockets). When designing classes has-a indicates composition and delegation while is-a can indicate inheritance.\nSo it is not appropriate to inherit from socket.socket, and your code is already looking a bit hybrid. Somet...
[ 2, 1 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0003538619_python_sockets.txt
Q: Python Reverse Find in String I have a string and an arbitrary index into the string. I want find the first occurrence of a substring before the index. An example: I want to find the index of the 2nd I by using the index and str.rfind() s = "Hello, I am 12! I like plankton but I don't like Baseball." index = 34 #points to the 't' in 'but' index_of_2nd_I = s.rfind('I', index) #returns = 36 and not 16 Now I would expect rfind() to return the index of the 2nd I (16) but it returns 36. after looking it up in the docs I found out rfind does not stand for reverse find. I'm totally new to Python so is there a built in solution to reverse find? Like reversing the string with some python [::-1] magic and using find, etc? Or will I have to reverse iterate char by char through the string? A: Your call tell rfind to start looking at index 34. You want to use the rfind overload that takes a string, a start and an end. Tell it to start at the beginning of the string (0) and stop looking at index: >>> s = "Hello, I am 12! I like plankton but I don't like Baseball." >>> index = 34 #points to the 't' in 'but' >>> index_of_2nd_I = s.rfind('I', 0, index) >>> >>> index_of_2nd_I 16 A: I became curious how to implement looking n times for string from end by rpartition and did this nth rpartition loop: orig = s = "Hello, I am 12! I like plankton but I don't like Baseball." found = tail = '' nthlast = 2 lookfor = 'I' for i in range(nthlast): tail = found+tail s,found,end = s.rpartition(lookfor) if not found: print "Only %i (less than %i) %r in \n%r" % (i, nthlast, lookfor, orig) break tail = end + tail else: print(s,found,tail)
Python Reverse Find in String
I have a string and an arbitrary index into the string. I want find the first occurrence of a substring before the index. An example: I want to find the index of the 2nd I by using the index and str.rfind() s = "Hello, I am 12! I like plankton but I don't like Baseball." index = 34 #points to the 't' in 'but' index_of_2nd_I = s.rfind('I', index) #returns = 36 and not 16 Now I would expect rfind() to return the index of the 2nd I (16) but it returns 36. after looking it up in the docs I found out rfind does not stand for reverse find. I'm totally new to Python so is there a built in solution to reverse find? Like reversing the string with some python [::-1] magic and using find, etc? Or will I have to reverse iterate char by char through the string?
[ "Your call tell rfind to start looking at index 34. You want to use the rfind overload that takes a string, a start and an end. Tell it to start at the beginning of the string (0) and stop looking at index:\n>>> s = \"Hello, I am 12! I like plankton but I don't like Baseball.\"\n>>> index = 34 #points to the 't' in...
[ 65, 2 ]
[]
[]
[ "find", "python", "reverse", "string" ]
stackoverflow_0003537717_find_python_reverse_string.txt
Q: python/win32: post a click event to a window? I want to simulate a mouse click on a window, but I want to post the click event directly to the window (not by simulating a general mouse click using win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)). What's the proper way to do it? I've tried the following, but it doesn't seem to have an effect: def MAKELONG(low, high): return low | (high << 16) win32gui.PostMessage(window, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, MAKELONG(21,42)) time.sleep(0.05) win32gui.PostMessage(window, win32con.WM_LBUTTONUP, 0, MAKELONG(21,42)) window is the correct handle for the window. In this case I was trying to get the file menu to activate. A: If window is the window that owns the menu, this won't work because WM_LBUTTONDOWN is for the window's client area, and the menu area is non-client. I haven't tested this, but you might try posting WM_NCLBUTTONDOWN instead, with a wParam of HTMENU, and mouse position in screen coordinates. Another alternative would be to just use GetSubMenu and TrackPopupMenu. The only problem with this is if you want the user to then be able to navigate to the other sub-menus.
python/win32: post a click event to a window?
I want to simulate a mouse click on a window, but I want to post the click event directly to the window (not by simulating a general mouse click using win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)). What's the proper way to do it? I've tried the following, but it doesn't seem to have an effect: def MAKELONG(low, high): return low | (high << 16) win32gui.PostMessage(window, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, MAKELONG(21,42)) time.sleep(0.05) win32gui.PostMessage(window, win32con.WM_LBUTTONUP, 0, MAKELONG(21,42)) window is the correct handle for the window. In this case I was trying to get the file menu to activate.
[ "If window is the window that owns the menu, this won't work because WM_LBUTTONDOWN is for the window's client area, and the menu area is non-client. I haven't tested this, but you might try posting WM_NCLBUTTONDOWN instead, with a wParam of HTMENU, and mouse position in screen coordinates.\nAnother alternative wou...
[ 0 ]
[]
[]
[ "python", "winapi", "windows" ]
stackoverflow_0003354952_python_winapi_windows.txt
Q: Python: rewinding one line in file when iterating with f.next() Python's f.tell doesn't work as I expected when you iterate over a file with f.next(): >>> f=open(".bash_profile", "r") >>> f.tell() 0 >>> f.next() "alias rm='rm -i'\n" >>> f.tell() 397 >>> f.next() "alias cp='cp -i'\n" >>> f.tell() 397 >>> f.next() "alias mv='mv -i'\n" >>> f.tell() 397 Looks like it gives you the position of the buffer rather than the position of what you just got with next(). I've previously used the seek/tell trick to rewind one line when iterating over a file with readline(). Is there a way to rewind one line when using next()? A: No. I would make an adapter that largely forwarded all calls, but kept a copy of the last line when you did next and then let you call a different method to make that line pop out again. I would actually make the adapter be an adapter that could wrap any iterable instead of a wrapper for file because that sounds like it would be frequently useful in other contexts. Alex's suggestion of using the itertools.tee adapter also works, but I think writing your own iterator adapter to handle this case in general would be cleaner. Here is an example: class rewindable_iterator(object): not_started = object() def __init__(self, iterator): self._iter = iter(iterator) self._use_save = False self._save = self.not_started def __iter__(self): return self def next(self): if self._use_save: self._use_save = False else: self._save = self._iter.next() return self._save def backup(self): if self._use_save: raise RuntimeError("Tried to backup more than one step.") elif self._save is self.not_started: raise RuntimeError("Can't backup past the beginning.") self._use_save = True fiter = rewindable_iterator(file('file.txt', 'r')) for line in fiter: result = process_line(line) if result is DoOver: fiter.backup() This wouldn't be too hard to extend into something that allowed you to backup by more than just one value. A: itertools.tee is probably the least-bad approach -- you can't "defeat" the buffering done by iterating on the file (nor would you want to: the performance effects would be terrible), so keeping two iterators, one "one step behind" the other, seems the soundest solution to me. import itertools as it with open('a.txt') as f: f1, f2 = it.tee(f) f2 = it.chain([None], f2) for thisline, prevline in it.izip(f1, f2): ... A: Python's file iterator does a lot of buffering, thereby advancing the position in the file far ahead of your iteration. If you want to use file.tell() you must do it "the old way": with open(filename) as fileob: line = fileob.readline() while line: print fileob.tell() line = fileob.readline()
Python: rewinding one line in file when iterating with f.next()
Python's f.tell doesn't work as I expected when you iterate over a file with f.next(): >>> f=open(".bash_profile", "r") >>> f.tell() 0 >>> f.next() "alias rm='rm -i'\n" >>> f.tell() 397 >>> f.next() "alias cp='cp -i'\n" >>> f.tell() 397 >>> f.next() "alias mv='mv -i'\n" >>> f.tell() 397 Looks like it gives you the position of the buffer rather than the position of what you just got with next(). I've previously used the seek/tell trick to rewind one line when iterating over a file with readline(). Is there a way to rewind one line when using next()?
[ "No. I would make an adapter that largely forwarded all calls, but kept a copy of the last line when you did next and then let you call a different method to make that line pop out again.\nI would actually make the adapter be an adapter that could wrap any iterable instead of a wrapper for file because that sounds...
[ 12, 5, 1 ]
[]
[]
[ "next", "python", "seek" ]
stackoverflow_0003539107_next_python_seek.txt
Q: Serve static files through a view in Django I am writng a Django application that let's you download a file after some requirements have been met (you have to log on, for example). The file needs to be inaccessible otherwise. Serve the file through Apache won't work: I have to check in the database for the user's permissions. Furthermore, don't have permission to change my Apache configuration. So I want to read the file in Django, then set the appropriate headers and send it to the client. I used the information on this page in the Django manual for the headers. I have the following code: #<- check persmissons here, continue if allowed -> #read the pdf file location = 'file.pdf' file = open(location, 'r') content = file.read() file.close #serve the file response = HttpResponse(content, mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=filename.pdf' return response However, the downloaded file seems to be corrupt: it can't be opened in Adobe Reader. I'm thinking that maybe this is some encoding problem, but I can't figure it out. Any help is appreciated :) A: You have to open() the file in binary mode (consider docs). Just like this: file = open(location, 'rb') I don't know whether it is applicable to you (since you are not allowed to change your Apache's settings), but I'd suggest to use Lighttpd + mod_secdownload for performance reasons. This elegant solution leverages Lighttpd's optimizations for serving static content while delegating authorization decisions to 3rd party (in your case Django).
Serve static files through a view in Django
I am writng a Django application that let's you download a file after some requirements have been met (you have to log on, for example). The file needs to be inaccessible otherwise. Serve the file through Apache won't work: I have to check in the database for the user's permissions. Furthermore, don't have permission to change my Apache configuration. So I want to read the file in Django, then set the appropriate headers and send it to the client. I used the information on this page in the Django manual for the headers. I have the following code: #<- check persmissons here, continue if allowed -> #read the pdf file location = 'file.pdf' file = open(location, 'r') content = file.read() file.close #serve the file response = HttpResponse(content, mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=filename.pdf' return response However, the downloaded file seems to be corrupt: it can't be opened in Adobe Reader. I'm thinking that maybe this is some encoding problem, but I can't figure it out. Any help is appreciated :)
[ "You have to open() the file in binary mode (consider docs).\nJust like this:\nfile = open(location, 'rb')\n\nI don't know whether it is applicable to you (since you are not allowed to change your Apache's settings), but I'd suggest to use Lighttpd + mod_secdownload for performance reasons. This elegant solution le...
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003539187_django_python.txt
Q: How to implement MousePressEvent for a Qt-Designer Widget in PyQt I've got a Widget (QTabeleWidget, QLabels and some QButtons). It was built in Qt-Designer, and now I have to implement some things. For that I need the mousePressEvent. Usually I would write a subclass and write something like this: def mousePressEvent(self, event): if event.button() == Qt.LeftButton: print "left" else: print 'right' But I don't know how to do that for a Widget created in the Designer. I need it for the QTabeleWidget. Hope someone can help me. I tried to solve the problem with the help of google, but without success. This site helped me many times, so I thought I'll give it a shot and ask. A: With PyQt there are three different ways to work with forms created in designer: Use single inheritance and make the form a member variable Use multiple inheritance Dynamically generate the members directly from the UI file Single Inheritance: class MyTableWidget(QTableWidget): def __init__(self, parent, *args): super(MyTableWidget, self).__init__(parent, args) self.ui = YourFormName() self.ui.setupUi(self) # all gui elements are now accessed through self.ui def mousePressEvent(self, event): pass # do something useful Multiple Inheritance: class MyTableWidget(QTableWidget, YourFormName): def __init__(self, parent, *args): super(MyTableWidget, self).__init__(parent, args) self.setupUi(self) # self now has all members you defined in the form def mousePressEvent(self, event): pass # do something useful Dynamically Generated: from PyQt4 import uic yourFormTypeInstance = uic.loadUi('/path/to/your/file.ui') For (3) above, you'll end up with an instance of whatever base type you specified for your form. You can then override your mousePressEvent as desired. I'd recommend you take a look at section 13.1 in the PyQt4 reference manual. Section 13.2 talks about the uic module.
How to implement MousePressEvent for a Qt-Designer Widget in PyQt
I've got a Widget (QTabeleWidget, QLabels and some QButtons). It was built in Qt-Designer, and now I have to implement some things. For that I need the mousePressEvent. Usually I would write a subclass and write something like this: def mousePressEvent(self, event): if event.button() == Qt.LeftButton: print "left" else: print 'right' But I don't know how to do that for a Widget created in the Designer. I need it for the QTabeleWidget. Hope someone can help me. I tried to solve the problem with the help of google, but without success. This site helped me many times, so I thought I'll give it a shot and ask.
[ "With PyQt there are three different ways to work with forms created in designer:\n\nUse single inheritance and make the form a member variable\nUse multiple inheritance\nDynamically generate the members directly from the UI file\n\nSingle Inheritance:\nclass MyTableWidget(QTableWidget):\n def __init__(self, par...
[ 4 ]
[]
[]
[ "pyqt4", "python", "qt_designer" ]
stackoverflow_0003539095_pyqt4_python_qt_designer.txt
Q: What does Instance() do in Python assignments? var = Instance(object)? A: It calls the __call__() method. A: Actually, I thought it was from the standard library. On inspection, it is from enthought.traits.api.Instance. It holds a reference to an object instance. If you pass a specific class to the constructor (e.g. Instance(MyClass) ), it does validation to make sure you pass the correct class.
What does Instance() do in Python assignments?
var = Instance(object)?
[ "It calls the __call__() method.\n", "Actually, I thought it was from the standard library. On inspection, it is from enthought.traits.api.Instance. It holds a reference to an object instance. If you pass a specific class to the constructor (e.g. Instance(MyClass) ), it does validation to make sure you pass the c...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003538724_python.txt
Q: Python, PyTables, Java - tying all together Question in nutshell What is the best way to get Python and Java to play nice with each other? More detailed explanation I have a somewhat complicated situation. I'll try my best to explain both in pictures and words. Here's the current system architecture: We have an agent-based modeling simulation written in Java. It has options of either writing locally to CSV files, or remotely via a connection to a Java server to an HDF5 file. Each simulation run spits out over a gigabyte of data, and we run the simulation dozens of times. We need to be able to aggregate over multiple runs of the same scenario (with different random seeds) in order to see some trends (e.g. min, max, median, mean). As you can imagine, trying to move around all these CSV files is a nightmare; there are multiple files produced per run, and like I said some of them are enormous. That's the reason we've been trying to move towards an HDF5 solution, where all the data for a study is stored in one place, rather than scattered across dozens of plain text files. Furthermore, since it is a binary file format, it should be able to get significant space savings as compared to uncompressed CSVS. As the diagram shows, the current post-processing we do of the raw output data from simulation also takes place in Java, and reads in the CSV files produced by local output. This post-processing module uses JFreeChart to create some charts and graphs related to the simulation. The Problem As I alluded to earlier, the CSVs are really untenable and are not scaling well as we generate more and more data from simulation. Furthermore, the post-processing code is doing more than it should have to do, essentially performing the work of a very, very poor man's relational database (making joins across 'tables' (csv files) based on foreign keys (the unique agent IDs). It is also difficult in this system to visualize the data in other ways (e.g. Prefuse, Processing, JMonkeyEngine getting some subset of the raw data to play with in MatLab or SPSS). Solution? My group decided we really need a way of filtering and querying the data we have, as well as performing cross table joins. Given this is a write-once, read-many situation, we really don't need the overhead of a real relational database; instead we just need some way to put a nicer front end on the HDF5 files. I found a few papers about this, such as one describing how to use [XQuery as the query language on HDF5 files][3], but the paper describes having to write a compiler to convert from XQuery/XPath into the native HDF5 calls, way beyond our needs. Enter [PyTables][4]. It seems to do exactly what we need (provides two different ways of querying data, either through Python list comprehension or through [in-kernel (C level) searches][5]. The proposed architecture I envision is this: What I'm not really sure how to do is to link together the python code that will be written for querying, with the Java code that serves up the HDF5 files, and the Java code that does the post processing of the data. Obviously I will want to rewrite much of the post-processing code that is implicitly doing queries and instead let the excellent PyTables do this much more elegantly. Java/Python options A simple google search turns up a few options for [communicating between Java and Python][7], but I am so new to the topic that I'm looking for some actual expertise and criticism of the proposed architecture. It seems like the Python process should be running on same machine as the Datahose so that the large .h5 files do not have to be transferred over the network, but rather the much smaller, filtered views of it would be transmitted to the clients. [Pyro][8] seems to be an interesting choice - does anyone have experience with that? A: This is an epic question, and there are lots of considerations. Since you didn't mention any specific performance or architectural constraints, I'll try and offer the best well-rounded suggestions. The initial plan of using PyTables as an intermediary layer between your other elements and the datafiles seems solid. However, one design constraint that wasn't mentioned is one of the most critical of all data processing: Which of these data processing tasks can be done in batch processing style and which data processing tasks are more of a live stream. This differentiation between "we know exactly our input and output and can just do the processing" (batch) and "we know our input and what needs to be available for something else to ask" (live) makes all the difference to an architectural question. Looking at your diagram, there are several relationships that imply the different processing styles. Additionally, on your diagram you have components of different types all using the same symbols. It makes it a little bit difficult to analyze the expected performance and efficiency. Another contraint that's significant is your IT infrastructure. Do you have high speed network available storage? If you do, intermediary files become a brilliant, simple, and fast way of sharing data between the elements of your infrastructure for all batch processing needs. You mentioned running your PyTables-using-application on the same server that's running the Java simulation. However, that means that server will experience load for both writing and reading the data. (That is to say, the simulation environment could be affected by the needs of unrelated software when they query the data.) To answer your questions directly: PyTables looks like a nice match. There are many ways for Python and Java to communicate, but consider a language agnostic communication method so these components can be changed later if necessarily. This is just as simple as finding libraries that support both Java and Python and trying them. The API you choose to implement with whatever library should be the same anyway. (XML-RPC would be fine for prototyping, as it's in the standard library, Google's Protocol Buffers or Facebook's Thrift make good production choices. But don't underestimate how great and simple just "writing things to intermediary files" can be if data is predictable and batchable. To help with the design process more and flesh out your needs: It's easy to look at a small piece of the puzzle, make some reasonable assumptions, and jump into solution evaluation. But it's even better to look at the problem holistically with a clear understanding of your constraints. May I suggest this process: Create two diagrams of your current architecture, physical and logical. On the physical diagram, create boxes for each physical server and diagram the physical connections between each. Be certain to label the resources available to each server and the type and resources available to each connection. Include physical hardware that isn't involved in your current setup if it might be useful. (If you have a SAN available, but aren't using it, include it in case the solution might want to.) On the logical diagram, create boxes for every application that is running in your current architecture. Include relevant libraries as boxes inside the application boxes. (This is important, because your future solution diagram currently has PyTables as a box, but it's just a library and can't do anything on it's own.) Draw on disk resources (like the HDF5 and CSV files) as cylinders. Connect the applications with arrows to other applications and resources as necessary. Always draw the arrow from the "actor" to the "target". So if an app writes and HDF5 file, they arrow goes from the app to the file. If an app reads a CSV file, the arrow goes from the app to the file. Every arrow must be labeled with the communication mechanism. Unlabeled arrows show a relationship, but they don't show what relationship and so they won't help you make decisions or communicate constraints. Once you've got these diagrams done, make a few copies of them, and then right on top of them start to do data-flow doodles. With a copy of the diagram for each "end point" application that needs your original data, start at the simulation and end at the end point with a pretty much solid flowing arrow. Any time your data arrow flows across a communication/protocol arrow, make notes of how the data changes (if any). At this point, if you and your team all agree on what's on paper, then you've explained your current architecture in a manner that should be easily communicable to anyone. (Not just helpers here on stackoverflow, but also to bosses and project managers and other purse holders.) To start planning your solution, look at your dataflow diagrams and work your way backwards from endpoint to startpoint and create a nested list that contains every app and intermediary format on the way back to the start. Then, list requirements for every application. Be sure to feature: What data formats or methods can this application use to communicate. What data does it actually want. (Is this always the same or does it change on a whim depending on other requirements?) How often does it need it. Approximately how much resources does the application need. What does the application do now that it doesn't do that well. What can this application do now that would help, but it isn't doing. If you do a good job with this list, you can see how this will help define what protocols and solutions you choose. You look at the situations where the data crosses a communication line, and you compare the requirements list for both sides of the communication. You've already described one particular situation where you have quite a bit of java post-processing code that is doing "joins" on tables of data in CSV files, thats a "do now but doesn't do that well". So you look at the other side of that communication to see if the other side can do that thing well. At this point, the other side is the CSV file and before that, the simulation, so no, there's nothing that can do that better in the current architecture. So you've proposed a new Python application that uses the PyTables library to make that process better. Sounds good so far! But in your next diagram, you added a bunch of other things that talk to "PyTables". Now we've extended past the understanding of the group here at StackOverflow, because we don't know the requirements of those other applications. But if you make the requirements list like mentioned above, you'll know exactly what to consider. Maybe your Python application using PyTables to provide querying on the HDF5 files can support all of these applications. Maybe it will only support one or two of them. Maybe it will provide live querying to the post-processor, but periodically write intermediary files for the other applications. We can't tell, but with planning, you can. Some final guidelines: Keep things simple! The enemy here is complexity. The more complex your solution, the more difficult the solution to implement and the more likely it is to fail. Use the least number operations, use the least complex operations. Sometimes just one application to handle the queries for all the other parts of your architecture is the simplest. Sometimes an application to handle "live" queries and a separate application to handle "batch requests" is better. Keep things simple! It's a big deal! Don't write anything that can already be done for you. (This is why intermediary files can be so great, the OS handles all the difficult parts.) Also, you mention that a relational database is too much overhead, but consider that a relational database also comes with a very expressive and well-known query language, the network communication protocol that goes with it, and you don't have to develop anything to use it! Whatever solution you come up with has to be better than using the off-the-shelf solution that's going to work, for certain, very well, or it's not the best solution. Refer to your physical layer documentation frequently so you understand the resource use of your considerations. A slow network link or putting too much on one server can both rule out otherwise good solutions. Save those docs. Whatever you decide, the documentation you generated in the process is valuable. Wiki-them or file them away so you can whip them out again when the topic come s up. And the answer to the direct question, "How to get Python and Java to play nice together?" is simply "use a language agnostic communication method." The truth of the matter is that Python and Java are both not important to your describe problem-set. What's important is the data that's flowing through it. Anything that can easily and effectively share data is going to be just fine. A: Do not make this more complex than it needs to be. Your Java process can -- simply -- spawn a separate subprocess to run your PyTables queries. Let the Operating System do what OS's do best. Your Java application can simply fork a process which has the necessary parameters as command-line options. Then your Java can move on to the next thing while Python runs in the background. This has HUGE advantages in terms of concurrent performance. Your Python "backend" runs concurrently with your Java simulation "front end". A: You could try Jython, a Python interpreter for the JVM which can import Java classes. Jython project homepage Unfortunately, that's all I know on the subject. A: Not sure if this is good etiquette. I couldn't fit all my comments into a normal comment, and the post has no activity for 8 months. Just wanted to see how this was going for you? We have a very very very similar situation where I work - only the simulation is written in C and the storage format is binary files. Every time a boss wants a different summary we have to make/modify handwritten code to do summaries. Our binary files are about 10 GB in size and there is one of these for every year of the simulation, so as you can imagine, things get hairy when we want to run it with different seeds and such. I've just discovered pyTables and had a similar idea to yours. I was hoping to change our storage format to hdf5 and then run our summary reports/queries using pytables. Part of this involves joining tables from each year. Have you had much luck doing these types of "joins" using pytables?
Python, PyTables, Java - tying all together
Question in nutshell What is the best way to get Python and Java to play nice with each other? More detailed explanation I have a somewhat complicated situation. I'll try my best to explain both in pictures and words. Here's the current system architecture: We have an agent-based modeling simulation written in Java. It has options of either writing locally to CSV files, or remotely via a connection to a Java server to an HDF5 file. Each simulation run spits out over a gigabyte of data, and we run the simulation dozens of times. We need to be able to aggregate over multiple runs of the same scenario (with different random seeds) in order to see some trends (e.g. min, max, median, mean). As you can imagine, trying to move around all these CSV files is a nightmare; there are multiple files produced per run, and like I said some of them are enormous. That's the reason we've been trying to move towards an HDF5 solution, where all the data for a study is stored in one place, rather than scattered across dozens of plain text files. Furthermore, since it is a binary file format, it should be able to get significant space savings as compared to uncompressed CSVS. As the diagram shows, the current post-processing we do of the raw output data from simulation also takes place in Java, and reads in the CSV files produced by local output. This post-processing module uses JFreeChart to create some charts and graphs related to the simulation. The Problem As I alluded to earlier, the CSVs are really untenable and are not scaling well as we generate more and more data from simulation. Furthermore, the post-processing code is doing more than it should have to do, essentially performing the work of a very, very poor man's relational database (making joins across 'tables' (csv files) based on foreign keys (the unique agent IDs). It is also difficult in this system to visualize the data in other ways (e.g. Prefuse, Processing, JMonkeyEngine getting some subset of the raw data to play with in MatLab or SPSS). Solution? My group decided we really need a way of filtering and querying the data we have, as well as performing cross table joins. Given this is a write-once, read-many situation, we really don't need the overhead of a real relational database; instead we just need some way to put a nicer front end on the HDF5 files. I found a few papers about this, such as one describing how to use [XQuery as the query language on HDF5 files][3], but the paper describes having to write a compiler to convert from XQuery/XPath into the native HDF5 calls, way beyond our needs. Enter [PyTables][4]. It seems to do exactly what we need (provides two different ways of querying data, either through Python list comprehension or through [in-kernel (C level) searches][5]. The proposed architecture I envision is this: What I'm not really sure how to do is to link together the python code that will be written for querying, with the Java code that serves up the HDF5 files, and the Java code that does the post processing of the data. Obviously I will want to rewrite much of the post-processing code that is implicitly doing queries and instead let the excellent PyTables do this much more elegantly. Java/Python options A simple google search turns up a few options for [communicating between Java and Python][7], but I am so new to the topic that I'm looking for some actual expertise and criticism of the proposed architecture. It seems like the Python process should be running on same machine as the Datahose so that the large .h5 files do not have to be transferred over the network, but rather the much smaller, filtered views of it would be transmitted to the clients. [Pyro][8] seems to be an interesting choice - does anyone have experience with that?
[ "This is an epic question, and there are lots of considerations. Since you didn't mention any specific performance or architectural constraints, I'll try and offer the best well-rounded suggestions.\nThe initial plan of using PyTables as an intermediary layer between your other elements and the datafiles seems sol...
[ 13, 5, 0, 0 ]
[]
[]
[ "architecture", "hdf5", "java", "pytables", "python" ]
stackoverflow_0001953731_architecture_hdf5_java_pytables_python.txt
Q: UnicodeDecodeError on import of a .pyd file I've started to slowly dabble with the Python/C API and after much fiddling and finagling, I was able to build a spam.pyd file. However, I must be missing something with this process and was hoping that someone could point me in the right direction. I thought that once spam.pyd was created, I could call it from Python via import spam. Is this true? When I try this, I get the following trace: Traceback (most recent call last): File "< pyshell#25 >", line 1, in <module> import spam UnicodeDecodeError: 'utf8' codec can't decode byte 0x89 in position 1: unexpected code byte Any ideas as to what I am doing wrong? I am working with Python 3.1.2 on Windows XP. I compiled spam.c via the mingw32 compiler. Thanks for reading this! EDIT: Well, it looks like the problem was that I had written the C code in an editor that saved the file with ANSI encoding. Strangely, if I retyped the code in Notepad, and saved the file with UTF8 encoding, I would get compile time errors complaining about invalid characters. When I used the built-in IDLE editor, everything worked fine. I was just following the example from the Python tutorial here. Is this an usual problem to have?? Here is all the code that was used if it helps any: #include < Python.h > static PyObject *spam_system(PyObject *self, PyObject *args) { const char *command; int sts; if (!PyArg_ParseTuple(args, "s", &command)) return NULL; sts = system(command); return Py_BuildValue("i", sts); } static PyMethodDef SpamMethods[] = { {"system", spam_system, METH_VARARGS, "Execute a shell command."}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef spammodule = { PyModuleDef_HEAD_INIT, "spam", NULL, -1, SpamMethods }; PyMODINIT_FUNC PyInit_spam(void) { return PyModule_Create(&spammodule); } A: You say: Well, it looks like the problem was that I had written the C code in an editor that saved the file with ANSI encoding. This is exceedingly unlikely. There are no non-ASCII characters visible in your published C source. If there were any, you would have got an error message from the C compiler (except maybe if it was in a string constant; I've never tried that). You say: Strangely, if I retyped the code in Notepad, and saved the file with UTF8 encoding, I would get compile time errors complaining about invalid characters. Not strangely. Notepad prepends a UTF-8 BOM. This means your C compiler was being presented with a source file which started with 3 bytes of junk. Don't use Notepad. Use a proper text editor. The indications are that the problem is much more likely to be in your Python input. The default source-file encoding in Python 3 is UTF-8. Your file contains "byte 0x89" which is not a valid UTF-8 lead byte and which the Windows cp125X encodings map to ‰ alias U+2030 PER MILLE SIGN -- either you have this in a string constant or you've typed that by mistake for a % (PER CENT SIGN). However it's difficult to guess how you got the traceback that you did. Getting into an interpreter (e.g. IDLE) and typing import spam should NOT give you that traceback.
UnicodeDecodeError on import of a .pyd file
I've started to slowly dabble with the Python/C API and after much fiddling and finagling, I was able to build a spam.pyd file. However, I must be missing something with this process and was hoping that someone could point me in the right direction. I thought that once spam.pyd was created, I could call it from Python via import spam. Is this true? When I try this, I get the following trace: Traceback (most recent call last): File "< pyshell#25 >", line 1, in <module> import spam UnicodeDecodeError: 'utf8' codec can't decode byte 0x89 in position 1: unexpected code byte Any ideas as to what I am doing wrong? I am working with Python 3.1.2 on Windows XP. I compiled spam.c via the mingw32 compiler. Thanks for reading this! EDIT: Well, it looks like the problem was that I had written the C code in an editor that saved the file with ANSI encoding. Strangely, if I retyped the code in Notepad, and saved the file with UTF8 encoding, I would get compile time errors complaining about invalid characters. When I used the built-in IDLE editor, everything worked fine. I was just following the example from the Python tutorial here. Is this an usual problem to have?? Here is all the code that was used if it helps any: #include < Python.h > static PyObject *spam_system(PyObject *self, PyObject *args) { const char *command; int sts; if (!PyArg_ParseTuple(args, "s", &command)) return NULL; sts = system(command); return Py_BuildValue("i", sts); } static PyMethodDef SpamMethods[] = { {"system", spam_system, METH_VARARGS, "Execute a shell command."}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef spammodule = { PyModuleDef_HEAD_INIT, "spam", NULL, -1, SpamMethods }; PyMODINIT_FUNC PyInit_spam(void) { return PyModule_Create(&spammodule); }
[ "You say: Well, it looks like the problem was that I had written the C code in an editor that saved the file with ANSI encoding.\nThis is exceedingly unlikely. There are no non-ASCII characters visible in your published C source. If there were any, you would have got an error message from the C compiler (except may...
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003536471_python_python_3.x.txt
Q: How to compare unicode strings with entity ref to non-unicode string I am evaluating hundreds of thousands of html files. I am looking for particular parts of the files. There can be small variations in the way the files were created For example, in one file I can have a section heading (after I converted it to upper and split then joined the text to get rid of possibly inconsistent white space: u'KEY1A\x97RISKFACTORS' In another file I could have: 'KEY1ARISKFACTORS' I am trying to create a dictionary of possible responses and I want to compare these two and conclude that they are equal. But every substitution I try to run the first string to remove the '\97 does not seem to work There are a fair number of variations of keys with various representations of entities so I would really like to create a dictionary more or less automatically so I have something like: key_dict={'u'KEY1A\x97RISKFACTORS':''KEY1ARISKFACTORS',''KEY1ARISKFACTORS':'KEY1ARISKFACTORS',. . .} I am assuming that since when I run S1='A' S2=u'A' S1==S2 I get True I should be able to compare these once the html entities are handled What I specifically tried to do is new_string=u'KEY1A\x97RISKFACTORS'.replace('|','') I got an error Sorry, I have been at this since last night. SLott pointed out something and I see I used the wrong label I hope this makes more sense A: You are correct that if S1='A' and S2 = u'A', then S1 == S2. Instead of assuming this though, you can do a simple test: key_dict= {u'A':'Value1', 'A':'Value2'} print key_dict print u'A' == 'A' This outputs: {u'A': 'Value2'} True That resolved, let's look at: new_string=u'KEY1A\x97DEMOGRAPHICRESPONSES'.replace('|','') There's a problem here, \x97 is the value you're trying to replace in the target string. However, your search string is '|', which is hex value 0x7C (ascii and unicode) and clearly not the value you need to replace. Even if the target and search string were both ascii or unicode, you'd still not find the '\x97'. Second problem is that you are trying to search for a non-unicode string in a unicode string. The easiest solution, and one that makes the most sense is to simply search for u'\x97': print u'KEY1A\x97DEMOGRAPHICRESPONSES' print u'KEY1A\x97DEMOGRAPHICRESPONSES'.replace(u'\x97', u'') Outputs: KEY1A\x97DEMOGRAPHICRESPONSES KEY1ADEMOGRAPHICRESPONSES A: Why not the obvious .replace(u'\x97','')? Where does the idea of that '|' come from? >>> s = u'KEY1A\x97DEMOGRAPHICRESPONSES' >>> s.replace(u'\x97', '') u'KEY1ADEMOGRAPHICRESPONSES'
How to compare unicode strings with entity ref to non-unicode string
I am evaluating hundreds of thousands of html files. I am looking for particular parts of the files. There can be small variations in the way the files were created For example, in one file I can have a section heading (after I converted it to upper and split then joined the text to get rid of possibly inconsistent white space: u'KEY1A\x97RISKFACTORS' In another file I could have: 'KEY1ARISKFACTORS' I am trying to create a dictionary of possible responses and I want to compare these two and conclude that they are equal. But every substitution I try to run the first string to remove the '\97 does not seem to work There are a fair number of variations of keys with various representations of entities so I would really like to create a dictionary more or less automatically so I have something like: key_dict={'u'KEY1A\x97RISKFACTORS':''KEY1ARISKFACTORS',''KEY1ARISKFACTORS':'KEY1ARISKFACTORS',. . .} I am assuming that since when I run S1='A' S2=u'A' S1==S2 I get True I should be able to compare these once the html entities are handled What I specifically tried to do is new_string=u'KEY1A\x97RISKFACTORS'.replace('|','') I got an error Sorry, I have been at this since last night. SLott pointed out something and I see I used the wrong label I hope this makes more sense
[ "You are correct that if S1='A' and S2 = u'A', then S1 == S2. Instead of assuming this though, you can do a simple test:\nkey_dict= {u'A':'Value1',\n 'A':'Value2'}\n\nprint key_dict\nprint u'A' == 'A'\n\nThis outputs:\n{u'A': 'Value2'}\nTrue\n\nThat resolved, let's look at:\nnew_string=u'KEY1A\\x97DEMOGRAPH...
[ 2, 1 ]
[]
[]
[ "entities", "html", "python", "unicode" ]
stackoverflow_0003539312_entities_html_python_unicode.txt
Q: Deleting an arbitrary chunk of a file What is the most efficient way to delete an arbitrary chunk of a file, given the start and end offsets? I'd prefer to use Python, but I can fall back to C if I have to. Say the file is this ..............xxxxxxxx---------------- I want to remove a chunk of it: ..............[xxxxxxxx]---------------- After the operation it should become: ..............---------------- Reading the whole thing into memory and manipulating it in memory is not a feasible option. A: The best performance will almost invariably be obtained by writing a new version of the file and then having it atomically write the old version, because filesystems are strongly optimized for such sequential access, and so is the underlying hardware (with the possible exception of some of the newest SSDs, but, even then, it's an iffy proposition). In addition, this avoids destroying data in the case of a system crash at any time -- you're left with either the old version of the file intact, or the new one in its place. Since every system could always crash at any time (and by Murphy's Law, it will choose the most unfortunate moment;-), integrity of data is generally considered very important (often data is more valuable than the system on which it's kept -- hence, "mirroring" RAID solutions to ensure against disk crashes losing precious data;-). If you accept this sane approach, the general idea is: open old file for reading, new one for writing (creation); copy N1 bytes over from the old file to the new one; then skip N2 bytes of the old file; then copy the rest over; close both files; atomically rename new to old. (Windows apparently has no "atomic rename" system call usable from Python -- to keep integrity in that case, instead of the atomic rename, you'd do three step: rename old file to a backup name, rename new file to old, delete backup-named file -- in case of system crash during the second one of these three very fast operations, one rename is all it will take to restore data integrity). N1 and N2, of course, are the two parameters saying where the deleted piece starts, and how long it is. For the part about opening the files, with open('old.dat', 'rb') as oldf: and with open('NEWold.dat', 'wb') as newf: statements, nested into each other, are clearly best (the rest of the code until the rename step must be nested in both of them of course). For the "copy the rest over" step, shutil.copyfileobj is best (be sure to specify a buffer length that's comfortably going to fit in your available RAM, but a large one will tend to give better performance). The "skip" step is clearly just a seek on the oldf open-for-reading file object. For copying exactly N1 bytes from oldf to newf, there is no direct support in Python's standard library, so you have to write your own, e.g: def copyN1(oldf, newf, N1, buflen=1024*1024): while N1: newf.write(oldf.read(min(N1, buflen))) N1 -= buflen A: I'd suggest memory mapping. Though it is actually manipulating file in memory it is more efficient then plain reading of the whole file into memory. Well, you have to manipulate the file contents in-memory one way or another as there's no system call for such operation neither in *nix nor in Win (at least not that I'm aware of). A: Try mmaping the file. This won't necessarily read it all into memory at once. If you really want to do it by hand, choose some chunk size and do back-and-forth reads and writes. But the seeks are going to kill you...
Deleting an arbitrary chunk of a file
What is the most efficient way to delete an arbitrary chunk of a file, given the start and end offsets? I'd prefer to use Python, but I can fall back to C if I have to. Say the file is this ..............xxxxxxxx---------------- I want to remove a chunk of it: ..............[xxxxxxxx]---------------- After the operation it should become: ..............---------------- Reading the whole thing into memory and manipulating it in memory is not a feasible option.
[ "The best performance will almost invariably be obtained by writing a new version of the file and then having it atomically write the old version, because filesystems are strongly optimized for such sequential access, and so is the underlying hardware (with the possible exception of some of the newest SSDs, but, ev...
[ 4, 0, 0 ]
[]
[]
[ "c", "file_io", "python" ]
stackoverflow_0003539517_c_file_io_python.txt
Q: How to detect if a Blobstore entry is an image so get_serving_url would work? I have a general purpose file storage backed by Google App Engine Blobstore, when I show users it's contents I would like to differentiate images from other files — I would like to show thumbnail for each image. Python get_serving_url function does not care (at least at dev server) if given blob is in fact an image, java's getServingUrl throws en exception... So my question, is: How to detect in python if a blob store entry is an image, so I could get a serving_url and use it in the UI? EDIT: On production python is throwing NotImageError on get_serving_url call with not supported blob—it's just not documented and it does not do that on dev server. A: Depending on how the images were uploaded to your Blobstore, they may all contain their MIME types, which you could try to use as a method of determining which items are most likely to contain valid image data using BlobInfo: blob_info = BlobInfo.get(blob_image_key) # All valid image formats for the GAE Images service. image_types = ('image/bmp', 'image/jpeg', 'image/png', 'image/gif', 'image/tiff', 'image/x-icon') if blob_info.content_type in image_types: # Obtain your serving URL. A: You could putting the call inside a try...except block, catching the exception which is thrown when the object is found to not be an image.
How to detect if a Blobstore entry is an image so get_serving_url would work?
I have a general purpose file storage backed by Google App Engine Blobstore, when I show users it's contents I would like to differentiate images from other files — I would like to show thumbnail for each image. Python get_serving_url function does not care (at least at dev server) if given blob is in fact an image, java's getServingUrl throws en exception... So my question, is: How to detect in python if a blob store entry is an image, so I could get a serving_url and use it in the UI? EDIT: On production python is throwing NotImageError on get_serving_url call with not supported blob—it's just not documented and it does not do that on dev server.
[ "Depending on how the images were uploaded to your Blobstore, they may all contain their MIME types, which you could try to use as a method of determining which items are most likely to contain valid image data using BlobInfo:\nblob_info = BlobInfo.get(blob_image_key)\n\n# All valid image formats for the GAE Images...
[ 3, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003538526_google_app_engine_python.txt
Q: Can I add "Smartypants" to restructuredText? I use restructuredText, and I like what smartypants does for Markdown. Is there a way to enable the same thing for restructuredText? A: Have you tried smartypants.py? I don't know how well it's implemented, much less how well it works for your specific use cases, but it does seem to target exactly your goal, unicode-ification of some ascii constructs (however, it runs on HTML, so I guess you'd run it after restructuredText or whatever other "producer of HTML" component). If that doesn't work well for you, a user has submitted a patch to python-markdown2 which he calls "this SmartyPants patch" -- it's been accepted and since a month ago it's part of the current source tree of python-markdown2 (r259 or better). That may offer smoother sailing (e.g. if you just get and built python-markdown2 as a read-only svn tree). Or, you could wait for the next downloadable release (there hasn't been one since May and this patch was accepted in mid-July), but who knows when that'll happen. A: As Alex Martelli says, smartyPants is what I need. However, I was looking for a little more detailed info on how to use it. So here's a Python script that reads the file named in the first command line argument, converts it to HTML, using Pygments for sourcecode, and then passses it through smartypants for prettifying. #!/usr/bin/python # EASY-INSTALL-SCRIPT: 'docutils==0.5','rst2html.py' """ A minimal front end to the Docutils Publisher, producing HTML. """ try: from ulif.rest import directives_plain from ulif.rest import roles_plain from ulif.rest import pygments_directive import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_doctree, publish_from_doctree from smartypants import smartyPants import sys description = ('Personal docutils parser with extra features.') doctree = publish_doctree(file(sys.argv[1]).read()) result = publish_from_doctree(doctree, writer_name='html') result = smartyPants(result) print result
Can I add "Smartypants" to restructuredText?
I use restructuredText, and I like what smartypants does for Markdown. Is there a way to enable the same thing for restructuredText?
[ "Have you tried smartypants.py? I don't know how well it's implemented, much less how well it works for your specific use cases, but it does seem to target exactly your goal, unicode-ification of some ascii constructs (however, it runs on HTML, so I guess you'd run it after restructuredText or whatever other \"pro...
[ 2, 1 ]
[]
[]
[ "python", "restructuredtext" ]
stackoverflow_0003527054_python_restructuredtext.txt
Q: Regular expressions split and match >>> zznew '...0002211 118 7.5 "Weeds" (2005) {The Love Circle Overlap (#4.10)}' >>> re.split('\(+\d+\)',zznew) ['...0002211 118 7.5 "Weeds" ', ' {The Love Circle Overlap (#4.10)}'] >>> m = re.match('\(+\d+\)',zznew) >>> m.groups() Traceback (most recent call last): File "<pyshell#104>", line 1, in <module> m.groups() AttributeError: 'NoneType' object has no attribute 'groups' in the above example when i use split it matches with (2005) and splits it... but when i use match its not match...the m.groups() file is empty.. what is wrong with this :( A: Use re.search instead of re.match. The difference between these two methods is that re.match only matches if the match starts at the beginning of the string, whereas re.search can match anywhere in the string. See the documentation for more details. As NullUserException points out, if you want to extract the year you can do it as follows: m = re.search('\((\d+)\)', zznew) print m.group(1)
Regular expressions split and match
>>> zznew '...0002211 118 7.5 "Weeds" (2005) {The Love Circle Overlap (#4.10)}' >>> re.split('\(+\d+\)',zznew) ['...0002211 118 7.5 "Weeds" ', ' {The Love Circle Overlap (#4.10)}'] >>> m = re.match('\(+\d+\)',zznew) >>> m.groups() Traceback (most recent call last): File "<pyshell#104>", line 1, in <module> m.groups() AttributeError: 'NoneType' object has no attribute 'groups' in the above example when i use split it matches with (2005) and splits it... but when i use match its not match...the m.groups() file is empty.. what is wrong with this :(
[ "Use re.search instead of re.match.\nThe difference between these two methods is that re.match only matches if the match starts at the beginning of the string, whereas re.search can match anywhere in the string. See the documentation for more details.\nAs NullUserException points out, if you want to extract the yea...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003539758_python_regex.txt
Q: Constructing a random string How to construct a string to have more than 5 characters and maximum of 15 characters using random function in python import string letters = list(string.lowercase) A: After the import and assignment you already have, assuming you want all possible lengths with the same probability: import random length = random.randrange(5, 16) randstr = ''.join(random.choice(letters) for _ in range(length))
Constructing a random string
How to construct a string to have more than 5 characters and maximum of 15 characters using random function in python import string letters = list(string.lowercase)
[ "After the import and assignment you already have, assuming you want all possible lengths with the same probability:\nimport random\n\nlength = random.randrange(5, 16)\n\nrandstr = ''.join(random.choice(letters) for _ in range(length))\n\n" ]
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0003539945_python.txt
Q: Obtaining an invertible square matrix from a non-square matrix of full rank in numpy or matlab Assume you have an NxM matrix A of full rank, where M>N. If we denote the columns by C_i (with dimensions Nx1), then we can write the matrix as A = [C_1, C_2, ..., C_M] How can you obtain the first linearly independent columns of the original matrix A, so that you can construct a new NxN matrix B that is an invertible matrix with a non-zero determinant. B = [C_i1, C_i2, ..., C_iN] How can you find the indices {i1, i2, ..., iN} either in matlab or python numpy? Can this be done using singular value decomposition? Code snippets will be very welcome. EDIT: To make this more concrete, consider the following python code from numpy import * from numpy.linalg.linalg import det M = [[3, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 1], [0, 2, 0, 0, 0]] M = array(M) I = [0,1,2,4] assert(abs(det(M[:,I])) > 1e-8) So given a matrix M, one would need to find the indices of a set of N linearly independent column vectors. A: Easy, peasy in MATLAB. Use QR, specifically, the pivoted QR. M = [3 0 0 0 0; 0 0 1 0 0; 0 0 0 0 1; 0 2 0 0 0] [Q,R,E] = qr(M) Q = 1 0 0 0 0 0 1 0 0 0 0 1 0 1 0 0 R = 3 0 0 0 0 0 2 0 0 0 0 0 1 0 0 0 0 0 1 0 E = 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 1 0 The first 4 columns of E designate the columns of M to be used, i.e., columns [1,2,3,5]. If you want the columns of M, just form the product M*E. M*E ans = 3 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 2 0 0 0 By the way, Using det to determine if a matrix is singular is the absolutely, positively, definitely worst way you can do that. Use rank instead. Essentially, you should virtually NEVER use det in MATLAB unless you understand why it is such a bad thing to do, and you choose to use it despite that fact. A: My first thought would be to try each possible combination of N out of the M columns. That could be done like this (in Python): import itertools import numpy.linalg # 'singular' returns whether a matrix is singular. # You could use something more efficient than the determinant # (I'm not sure what options there are in NumPy) singular = lambda m: numpy.linalg.det(m) == 0 def independent_square(A): N,M = A.shape for colset in itertools.combinations(xrange(M), N): B = A[:,colset] if not singular(B): return B If you want the column indices instead of the resulting square matrix, just replace return B with return colset. Or you could get both with return colset,B. I don't know of any way SVD would help here. In fact, I can't think of any purely mathematical operation that would convert A to B (or even any that would figure out the MxN column selection matrix Q such that B=A.Q), other than by trial and error. But if you want to find out whether one exists, math.stackexchange.com would be a good place to ask. If all you need is a way to do it computationally, the above code should suffice.
Obtaining an invertible square matrix from a non-square matrix of full rank in numpy or matlab
Assume you have an NxM matrix A of full rank, where M>N. If we denote the columns by C_i (with dimensions Nx1), then we can write the matrix as A = [C_1, C_2, ..., C_M] How can you obtain the first linearly independent columns of the original matrix A, so that you can construct a new NxN matrix B that is an invertible matrix with a non-zero determinant. B = [C_i1, C_i2, ..., C_iN] How can you find the indices {i1, i2, ..., iN} either in matlab or python numpy? Can this be done using singular value decomposition? Code snippets will be very welcome. EDIT: To make this more concrete, consider the following python code from numpy import * from numpy.linalg.linalg import det M = [[3, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 1], [0, 2, 0, 0, 0]] M = array(M) I = [0,1,2,4] assert(abs(det(M[:,I])) > 1e-8) So given a matrix M, one would need to find the indices of a set of N linearly independent column vectors.
[ "Easy, peasy in MATLAB. Use QR, specifically, the pivoted QR.\nM = [3 0 0 0 0;\n 0 0 1 0 0;\n 0 0 0 0 1; \n 0 2 0 0 0]\n\n[Q,R,E] = qr(M)\nQ =\n 1 0 0 0\n 0 0 1 0\n 0 0 0 1\n 0 1 0 0\n\nR =\n 3 0 0 0 0\n 0 2 ...
[ 6, 1 ]
[]
[]
[ "linear_algebra", "matlab", "numpy", "python", "svd" ]
stackoverflow_0003539026_linear_algebra_matlab_numpy_python_svd.txt
Q: Determining a timezone in Python Given a local timestamp and a UTC timestamp, is it possible to determine the timezone and whether DST is in effect? A: If your "UTC timestamp" is a float (int would suffice) of "seconds from the epoch", and your "local timestamp" is some weird version of it shifted into your local time coordinates (there is no "epoch" except the UTC one), module time in the standard Python library suffices. As these docs show, given "seconds from the epoch", gmtime translates that into a 9-items tuple in UTC, localtime into a 9-items tuple in local time; to go the other way around, calendar.timegm (UTC 9-items tuple to UTC timestamp) and mktime (local time 9-items tuple to UTC timestamp). You'll note there's no such thing as a "local timestamp" (only local time 9-items tuples aka struct_time instances), simply because no such concept exists. But, if I understand correctly what you mean by "local timestamp", then translating it to a struct time "as if" it was a real timestamp, and then back into local time, will give the offset you seek (in seconds). As for DST, a bit telling whether it's on is the 9th item of the tuples we've been mentioning. For example, using the "local timestamp" only: >>> loct 1282453595 >>> time.mktime(time.gmtime(loct)) - loct 28800.0 >>> _ / 3600 8.0 >>> This says I'm 8 hours west of UTC. And: >>> time.localtime(loct)[-1] 1 this says that it is with DST in effect. A: Try taking a look at http://docs.python.org/library/datetime.html#datetime.datetime for built-in support for dates, times, and timezones. If you need a more powerful library, peek at the suggestions here: Full-featured date and time library
Determining a timezone in Python
Given a local timestamp and a UTC timestamp, is it possible to determine the timezone and whether DST is in effect?
[ "If your \"UTC timestamp\" is a float (int would suffice) of \"seconds from the epoch\", and your \"local timestamp\" is some weird version of it shifted into your local time coordinates (there is no \"epoch\" except the UTC one), module time in the standard Python library suffices. \nAs these docs show, given \"s...
[ 3, 0 ]
[]
[]
[ "python", "timezone" ]
stackoverflow_0003540149_python_timezone.txt
Q: GAE bulkloader : entity missing from the auto-generated bulkloader.yaml I am migrating a django application to GAE,and am going to use bulkloader to upload existing data. The model is quite simple, basically there are two models: class Tag(db.Model): name = db.StringProperty (required=True) class Entry(db.Model): # some properties ... # ... tags = db.ListProperty(db.Key) I ran appcfg.py create_bulkloader_config against my GAE app,and found two problems with the bulkloader.yaml generated: Only kind Entry is generated,there is no kind Tag in the generated bulkloader.yaml. In kind Entry, property tags is missing. Also I noticed although I have code which inquiries model Tag like this: Tag.gql('WHERE name = :1',t) GAE doesn't generate index for Tag in index.yaml. I am wondering is this related to that Tag is missing from bulkloader.yaml ... Any hints folks ? Thank you in advance. A: Try running that GQL in the data store viewer in your control panel.
GAE bulkloader : entity missing from the auto-generated bulkloader.yaml
I am migrating a django application to GAE,and am going to use bulkloader to upload existing data. The model is quite simple, basically there are two models: class Tag(db.Model): name = db.StringProperty (required=True) class Entry(db.Model): # some properties ... # ... tags = db.ListProperty(db.Key) I ran appcfg.py create_bulkloader_config against my GAE app,and found two problems with the bulkloader.yaml generated: Only kind Entry is generated,there is no kind Tag in the generated bulkloader.yaml. In kind Entry, property tags is missing. Also I noticed although I have code which inquiries model Tag like this: Tag.gql('WHERE name = :1',t) GAE doesn't generate index for Tag in index.yaml. I am wondering is this related to that Tag is missing from bulkloader.yaml ... Any hints folks ? Thank you in advance.
[ "Try running that GQL in the data store viewer in your control panel. \n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003540363_google_app_engine_python.txt
Q: Does anyone know of a script to convert pygtk to tk I have a fairly large work project that uses pygtk for the GUI and I need reduce the dependencies and convert to tkinter. Does anyone know of a script to convert exisiting pygtk code to tkinter? A: Ok for anyone in the same boat as me, I just found PyGtk2Tk which is a PyGtk to Tkinter Wrapper that runs PyGtk based code unchanged using Tkinter (Tk).
Does anyone know of a script to convert pygtk to tk
I have a fairly large work project that uses pygtk for the GUI and I need reduce the dependencies and convert to tkinter. Does anyone know of a script to convert exisiting pygtk code to tkinter?
[ "Ok for anyone in the same boat as me, I just found PyGtk2Tk which is a PyGtk to Tkinter Wrapper that runs PyGtk based code unchanged using Tkinter (Tk).\n" ]
[ 2 ]
[]
[]
[ "pygtk", "python", "tkinter" ]
stackoverflow_0003539735_pygtk_python_tkinter.txt
Q: Cannot create new Django model object within Ajax post request This is kind of "I already lost x hours debugging this" kind of problem/question :( Following jQuery js code is initiating POST request upon button click $("#btn_create_tag").click(function(evt) { $.post("/tag/createAjax", { tagname: $("#txt_tag_name").val() }, function(data) { } ); }); Django code that is performed on this call is: @suppress_logging_output @login_required def createAjax(request): if request.is_ajax() and request.method == 'POST': tagName = request.POST["tagname"] new_tag = Tag() new_tag.name = tagName new_tag.save() print "new tag with id %s has been created" % new_tag.id That code is executed successfully (I'm doing checks for empty or already existing name, but didn't wrote here to be more clear), but new Tag object is NOT created. I'm even getting ""new tag with id %s has been created" printed on devserver's prompt, and every time ID is increased for one, as suppossed to, but objects are not stored in db. When I execute new_tag = Tag() new_tag.name = tagName new_tag.save() from Django shell, new Tag object is regulary created, but from jQuery request, it's not created. Have any idea what's wront, what to check, how to debug this.... DB behind is PostgresSQL 8.3. Any suggestion is more then welcome :) Update: I wrote UnitTest which is working: class AjaxTestCase(TestCase): def testAjaxCreateTag(self): tagNum = Tag.objects.filter(name="TEST_TAG").count() self.assertEqual(tagNum, 0) c = Client() c.post('/lookup/tag/createAjax', {'tagname': 'TEST_TAG'}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') tagNum = Tag.objects.filter(name="TEST_TAG").count() self.assertEqual(tagNum, 1) Update2: Hum, this morning, it seems that everything is working fine, but code hasn't changed. I don't like this at all :( A: This sounds very strange. Can you double check your database settings? Ensure that you are using the correct database inside settings.py? Also write an unit test to exercise the code using Django's test client. In your test method remember to send the HTTP_X_REQUESTED_WITH header for is_ajax() to work. A: If you are using the TransactionMiddleware (see http://docs.djangoproject.com/en/dev/topics/db/transactions/), then not returning a HttpResponse of some sort will result in a crash and a rollback. A: try new_tag=Tag(name=tagName) new_tag.save() BTW - you should sanitize the new tagname and not take it directly from the POST
Cannot create new Django model object within Ajax post request
This is kind of "I already lost x hours debugging this" kind of problem/question :( Following jQuery js code is initiating POST request upon button click $("#btn_create_tag").click(function(evt) { $.post("/tag/createAjax", { tagname: $("#txt_tag_name").val() }, function(data) { } ); }); Django code that is performed on this call is: @suppress_logging_output @login_required def createAjax(request): if request.is_ajax() and request.method == 'POST': tagName = request.POST["tagname"] new_tag = Tag() new_tag.name = tagName new_tag.save() print "new tag with id %s has been created" % new_tag.id That code is executed successfully (I'm doing checks for empty or already existing name, but didn't wrote here to be more clear), but new Tag object is NOT created. I'm even getting ""new tag with id %s has been created" printed on devserver's prompt, and every time ID is increased for one, as suppossed to, but objects are not stored in db. When I execute new_tag = Tag() new_tag.name = tagName new_tag.save() from Django shell, new Tag object is regulary created, but from jQuery request, it's not created. Have any idea what's wront, what to check, how to debug this.... DB behind is PostgresSQL 8.3. Any suggestion is more then welcome :) Update: I wrote UnitTest which is working: class AjaxTestCase(TestCase): def testAjaxCreateTag(self): tagNum = Tag.objects.filter(name="TEST_TAG").count() self.assertEqual(tagNum, 0) c = Client() c.post('/lookup/tag/createAjax', {'tagname': 'TEST_TAG'}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') tagNum = Tag.objects.filter(name="TEST_TAG").count() self.assertEqual(tagNum, 1) Update2: Hum, this morning, it seems that everything is working fine, but code hasn't changed. I don't like this at all :(
[ "This sounds very strange. Can you double check your database settings? Ensure that you are using the correct database inside settings.py? Also write an unit test to exercise the code using Django's test client. In your test method remember to send the HTTP_X_REQUESTED_WITH header for is_ajax() to work. \n", "If...
[ 1, 1, 0 ]
[]
[]
[ "django", "javascript", "jquery", "orm", "python" ]
stackoverflow_0003537399_django_javascript_jquery_orm_python.txt
Q: Python error "IOError: [Errno 2] No such file or directory" but file is there I am trying to read a csv file and I am getting the error above but the file is there. The line giving the error is infilequery = file('D:\x88_2.csv','rb') and I get the error below. Traceback (most recent call last): File "C:\Python26\usrapply_onemol2.py", line 14, in infilequery = file('D:\x88_2.csv','rb') IOError: [Errno 2] No such file or directory: 'D:\x88_2.csv' I can put a file from the same directory in its place and python at least sees it. The result of os.listdir("D:") features 'x88_2.csv' and the result of "dir D:\" also includes it. When putting the filename in and allowing python to complete the path and selecting x88_2.csv from the dropdown, I still get the same error. What is up here? A: Try 'D:\\x88_2.csv' The \x88 is interpreted as the character at code point 0x88. Alternatively you could use raw string r'D:\x88_2.csv' or forward slash 'D:/x88_2.csv'
Python error "IOError: [Errno 2] No such file or directory" but file is there
I am trying to read a csv file and I am getting the error above but the file is there. The line giving the error is infilequery = file('D:\x88_2.csv','rb') and I get the error below. Traceback (most recent call last): File "C:\Python26\usrapply_onemol2.py", line 14, in infilequery = file('D:\x88_2.csv','rb') IOError: [Errno 2] No such file or directory: 'D:\x88_2.csv' I can put a file from the same directory in its place and python at least sees it. The result of os.listdir("D:") features 'x88_2.csv' and the result of "dir D:\" also includes it. When putting the filename in and allowing python to complete the path and selecting x88_2.csv from the dropdown, I still get the same error. What is up here?
[ "Try\n'D:\\\\x88_2.csv'\n\nThe \\x88 is interpreted as the character at code point 0x88. Alternatively you could use raw string\nr'D:\\x88_2.csv'\n\nor forward slash\n'D:/x88_2.csv'\n\n" ]
[ 7 ]
[]
[]
[ "file", "io", "python" ]
stackoverflow_0003541109_file_io_python.txt
Q: Why is this pickled data not unpickling after transfer over a network? logexample.py logs over the network using logging.handlers.DatagramHandler, which pickles(protocol 1) the data it sends. logserver.py is supposed to unpickle and print to screen, but instead it raises an error. If I use pickle.loads then KeyError: '\x00' and if I use cPickle.loads its an EOFError The files are here - http://gist.github.com/542543 Python version 2.6.5 Why is this happening? --------------------------THE FIX--------------------------- For anyone else who might be interested, here is the fixed handler class LogHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request[0] socket = self.request[1] out = pickle.loads(data[4:]) record = logging.makeLogRecord(out) print record.msg A: There is an example in the docs of how to use DataGramHandler - it shows that the datagram may be sent over multiple packets, which need to be reassembled at the receiving end. The first four bytes of the first packet are the length - you are passing this into pickle.loads as well as the pickled data. Use the example code instead.
Why is this pickled data not unpickling after transfer over a network?
logexample.py logs over the network using logging.handlers.DatagramHandler, which pickles(protocol 1) the data it sends. logserver.py is supposed to unpickle and print to screen, but instead it raises an error. If I use pickle.loads then KeyError: '\x00' and if I use cPickle.loads its an EOFError The files are here - http://gist.github.com/542543 Python version 2.6.5 Why is this happening? --------------------------THE FIX--------------------------- For anyone else who might be interested, here is the fixed handler class LogHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request[0] socket = self.request[1] out = pickle.loads(data[4:]) record = logging.makeLogRecord(out) print record.msg
[ "There is an example in the docs of how to use DataGramHandler - it shows that the datagram may be sent over multiple packets, which need to be reassembled at the receiving end. The first four bytes of the first packet are the length - you are passing this into pickle.loads as well as the pickled data. Use the ex...
[ 0 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0003540842_pickle_python.txt
Q: Is it possible to run linux on hand-held tablets? I want to run a django app on a hand-held device. It'll need to run Python (obviously) and will write its data to an SQLite database. Are there any tablets available that will let me do this? Specifically, if I bought an Android tablet, would I have to/be able to install linux instead, or would I be able to run it under Android? A: If you want Linux probably Meego is the best choice. There is no hardware for it yet, I believe, but there is hardware for the predecessor Maemo. Running Django on Android is not possible, AFAIK. If you have a network connection the Django server yould be anywhere and you would just need a smartphone/tablet with a browser. That would be the easiest solution. A: Do you want it to run on a tablet or a hand-held device? Are netbooks okay? There are plenty netbooks that run Ubuntu, on which you should be able to run python. I also remember that the sharp zaurus handheld devices were able to run Zope for example (be it very, very slowly) In general, smaller, embedded systems (i.e. pandora) run versions of OpenWRT that use ipkg, and I think there are django packages for OpenWRT, so that may be an option as well.
Is it possible to run linux on hand-held tablets?
I want to run a django app on a hand-held device. It'll need to run Python (obviously) and will write its data to an SQLite database. Are there any tablets available that will let me do this? Specifically, if I bought an Android tablet, would I have to/be able to install linux instead, or would I be able to run it under Android?
[ "If you want Linux probably Meego is the best choice. There is no hardware for it yet, I believe, but there is hardware for the predecessor Maemo.\nRunning Django on Android is not possible, AFAIK. If you have a network connection the Django server yould be anywhere and you would just need a smartphone/tablet with ...
[ 1, 0 ]
[]
[]
[ "android", "django", "python" ]
stackoverflow_0003540805_android_django_python.txt
Q: os.walk() caching/speeding up I have a prototype server[0] that's doing an os.walk()[1] for each query a client[0] makes. I'm currently looking into ways of: caching this data in memory, speeding up queries, and hopefully allowing for expansion into storing metadata and data persistence later on. I find SQL complicated for tree structures, so I thought I would get some advice before actually committing to SQLite Are there any cross-platform, embeddable or bundle-able non-SQL databases that might be able to handle this kind of data? I have a small (10k-100k files) list. I have an extremely small amount of connections (maybe 10-20). I want to be able to scale to handling metadata as well. [0] the server and client are actually the same piece of software, this is a P2P application, that's designed to share files over a local trusted network with out a main server, using zeroconf for discovery, and twisted for pretty much everything else [1] query time is currently 1.2s with os.walk() on 10,000 files Here is the related function in my Python code that does the walking: def populate(self, string): for name, sharedir in self.sharedirs.items(): for root, dirs, files, in os.walk(sharedir): for dir in dirs: if fnmatch.fnmatch(dir, string): yield os.path.join(name, *os.path.join(root, dir)[len(sharedir):].split("/")) for file in files: if fnmatch.fnmatch(file, string): yield os.path.join(name, *os.path.join(root, ile)[len(sharedir):].split("/")) A: You don't need to persist a tree structure -- in fact, your code is busily dismantling the natural tree structure of the directory tree into a linear sequence, so why would you want to restart from a tree next time? Looks like what you need is just an ordered sequence: i X result of os.path.join for X where X, a string, names either a file or directory (you treat them just the same), i is a progressively incrementing integer number (to preserve the order), and the result column, also a string, is the result of os.path.join(name, *os.path.join(root, &c. This is perfectly easy to put in a SQL table, of course! To create the table the first time, just remove the guards if fnmatch.fnmatch (and the string argument) from your populate function, yield the dir or file before the os.path.join result, and use a cursor.executemany to save the enumerate of the call (or, use a self-incrementing column, your pick). To use the table, populate becomes essentially a: select result from thetable where X LIKE '%foo%' order by i where string is foo. A: I misunderstood the question at first, but I think I have a solution now (and sufficiently different from my other answer to warrant a new one). Basically, you do the normal query the first time you run walk on a directory, but you store the yielded values. The second time around, you just yield those stored values. I've wrapped the os.walk() call because it's short, but you could just as easily wrap your generator as a whole. cache = {} def os_walk_cache( dir ): if dir in cache: for x in cache[ dir ]: yield x else: cache[ dir ] = [] for x in os.walk( dir ): cache[ dir ].append( x ) yield x raise StopIteration() I'm not sure of your memory requirements, but you may want to consider periodically cleaning out cache. A: Have you looked at MongoDB? What about mod_python? mod_python should allow you to do your os.walk() and just store the data in Python data structures, since the script is persistent between connections.
os.walk() caching/speeding up
I have a prototype server[0] that's doing an os.walk()[1] for each query a client[0] makes. I'm currently looking into ways of: caching this data in memory, speeding up queries, and hopefully allowing for expansion into storing metadata and data persistence later on. I find SQL complicated for tree structures, so I thought I would get some advice before actually committing to SQLite Are there any cross-platform, embeddable or bundle-able non-SQL databases that might be able to handle this kind of data? I have a small (10k-100k files) list. I have an extremely small amount of connections (maybe 10-20). I want to be able to scale to handling metadata as well. [0] the server and client are actually the same piece of software, this is a P2P application, that's designed to share files over a local trusted network with out a main server, using zeroconf for discovery, and twisted for pretty much everything else [1] query time is currently 1.2s with os.walk() on 10,000 files Here is the related function in my Python code that does the walking: def populate(self, string): for name, sharedir in self.sharedirs.items(): for root, dirs, files, in os.walk(sharedir): for dir in dirs: if fnmatch.fnmatch(dir, string): yield os.path.join(name, *os.path.join(root, dir)[len(sharedir):].split("/")) for file in files: if fnmatch.fnmatch(file, string): yield os.path.join(name, *os.path.join(root, ile)[len(sharedir):].split("/"))
[ "You don't need to persist a tree structure -- in fact, your code is busily dismantling the natural tree structure of the directory tree into a linear sequence, so why would you want to restart from a tree next time?\nLooks like what you need is just an ordered sequence:\ni X result of os.path.join for X\n\nwh...
[ 3, 3, 0 ]
[]
[]
[ "database", "embedded_database", "nosql", "python" ]
stackoverflow_0003537279_database_embedded_database_nosql_python.txt
Q: PyArg_ParseTuple and a callback function pointer I have code like the following: PyObject *callback; PyObject *paths; // Process and convert arguments if (!PyArg_ParseTuple(args, "OO:schedule", &paths, &callback)) return NULL; What exactly happens inside PyArg_ParseTuple? My guess is that callback gets the function pointer I passed to args (also PyObject*). How does PyArg_ParseTuple convert the function pointer to PyObject*? What I want to know is what happens if I pass in the same callback function pointer twice. I think callback gets allocated a new PyObject inside PyArg_ParseTuple, so it will get a different memory address each time, but will contain the same callback function pointer. But if I PyObject_Hash callback, it will produce a different value each time, right? (since address is different each time..) A: PyArg_ParseTuple doesn't care about the type of an "O" arg. No conversion is done. No new object is created. The address of the object is dropped into the PyObject * C variable that you have specified. It does exactly the same to each of your two args. I can't imagine what is the relevance of PyObject_Hash. If you want to compare two incarnations of your callback arg, just use == on the addresses. A: The point is that if you pass the same callback twice it will receive two objects but you will never be allowed to read only one which is the las wrote. You will have a kind of memory leak as one of the two pointers will not be referenced. Of course the garbage collector will eventually pass after you to clean all the mess. But anyhow... I misread the PyObject_Hash should be called on callback and paths. It will be the same. but you probably want to compare callback and paths: if(callback==paths) {printf("it 's the same callabck");}
PyArg_ParseTuple and a callback function pointer
I have code like the following: PyObject *callback; PyObject *paths; // Process and convert arguments if (!PyArg_ParseTuple(args, "OO:schedule", &paths, &callback)) return NULL; What exactly happens inside PyArg_ParseTuple? My guess is that callback gets the function pointer I passed to args (also PyObject*). How does PyArg_ParseTuple convert the function pointer to PyObject*? What I want to know is what happens if I pass in the same callback function pointer twice. I think callback gets allocated a new PyObject inside PyArg_ParseTuple, so it will get a different memory address each time, but will contain the same callback function pointer. But if I PyObject_Hash callback, it will produce a different value each time, right? (since address is different each time..)
[ "PyArg_ParseTuple doesn't care about the type of an \"O\" arg. No conversion is done. No new object is created. The address of the object is dropped into the PyObject * C variable that you have specified. It does exactly the same to each of your two args.\nI can't imagine what is the relevance of PyObject_Hash. If ...
[ 1, 0 ]
[]
[]
[ "c", "callback", "python", "python_c_extension" ]
stackoverflow_0003532434_c_callback_python_python_c_extension.txt
Q: MySQL database: lua or python Under preferences(Menu)/general (Tab)/ Interactive GRT Shell Language: lua or python. What is the difference? I use MySQL for database and involve mostly binary. A: mysql is a database server -- it doesn't have a menu. I think you mean mysql workbench which is a visual database design tool. That option allows you to use lua scripting or python scripting to help you on the design of your database -- it is unrelated to what happens on the mysql server. There are some examples on usage of the scripting provided by mysql workbench here.
MySQL database: lua or python
Under preferences(Menu)/general (Tab)/ Interactive GRT Shell Language: lua or python. What is the difference? I use MySQL for database and involve mostly binary.
[ "mysql is a database server -- it doesn't have a menu. I think you mean mysql workbench which is a visual database design tool. That option allows you to use lua scripting or python scripting to help you on the design of your database -- it is unrelated to what happens on the mysql server. There are some examples o...
[ 5 ]
[]
[]
[ "lua", "mysql", "python" ]
stackoverflow_0003541364_lua_mysql_python.txt
Q: Python method for storing list of bytes in network (big-endian) byte order to file (little-endian) My present task is to dissect tcpdump data that includes P2P messages and I am having trouble with the piece data I acquire and write to a file on my x86 machine. My suspicion is I have a simple endian-ness issue with the bytes I write to to file. I have a list of bytes holding a piece of P2P video read and processed using python-pcapy package BTW. bytes = [14, 254, 23, 35, 34, 67, etc... ] I am looking for a way to store these bytes, presently held in a list in my Python application to a file. Currently I write the pieces as follows: def writePiece(self, filename, pieceindex, bytes, ipsrc, ipdst, ts): file = open(filename,"ab") # Iterate through bytes writing them to a file if don't have piece already if not self.piecemap[ipdst].has_key(pieceindex): for byte in bytes: file.write('%c' % byte) file.flush() self.procLog.info("Wrote (%d) bytes of piece (%d) to %s" % (len(bytes), pieceindex, filename)) # Remember we have this piece now in case duplicates arrive self.piecemap[ipdst][pieceindex] = True # TODO: Collect stats file.close() As you can see from the for loop, I write the bytes to the file in the same order as I process them from the wire (i.e. network or big-endian order). Suffice to say, the video which is the payload of the pieces does not playback well in VLC :-D I think I need to convert them to little-endian byte order but am not sure the best way to approach this in Python. UPDATE The solution that worked out for me (writing P2P pieces handling endian issues appropriately) was: def writePiece(self, filename, pieceindex, bytes, ipsrc, ipdst, ts): file = open(filename,"r+b") if not self.piecemap[ipdst].has_key(pieceindex): little = struct.pack('<'+'B'*len(bytes), *bytes) # Seek to offset based on piece index file.seek(pieceindex * self.piecesize) file.write(little) file.flush() self.procLog.info("Wrote (%d) bytes of piece (%d) to %s" % (len(bytes), pieceindex, filename)) # Remember we have this piece now in case duplicates arrive self.piecemap[ipdst][pieceindex] = True file.close() The key to the solution was usage of Python struct module as suspected and in particular: little = struct.pack('<'+'B'*len(bytes), *bytes) Thanks to those who responded with helpful suggestions. A: To save yourself some work you might like to use a bytearray (Python 2.6 and later): b = [14, 254, 23, 35] f = open("file", 'ab') f.write(bytearray(b)) This does all the converting of your 0-255 values into bytes without the need for all the looping. I can't see what your problem is otherwise without more information. If the data really is byte-wise then endianness isn't an issue, as others have said. (By the way, using bytes and file as variable names isn't good as it hide the built-ins of the same name). A: You can also use an array.array: from array import array f.write(array('B', bytes)) instead of f.write(struct.pack('<'+'B'*len(bytes), *bytes)) which when tidied up a little is f.write(struct.pack('B' * len(bytes), *bytes)) # the < is redundant; there is NO ENDIANNESS ISSUE which if len(bytes) is "large" might be better as f.write(struct.pack('%dB' % len(bytes), *bytes)) A: This may have been answered previously in Python File Slurp w/ endian conversion.
Python method for storing list of bytes in network (big-endian) byte order to file (little-endian)
My present task is to dissect tcpdump data that includes P2P messages and I am having trouble with the piece data I acquire and write to a file on my x86 machine. My suspicion is I have a simple endian-ness issue with the bytes I write to to file. I have a list of bytes holding a piece of P2P video read and processed using python-pcapy package BTW. bytes = [14, 254, 23, 35, 34, 67, etc... ] I am looking for a way to store these bytes, presently held in a list in my Python application to a file. Currently I write the pieces as follows: def writePiece(self, filename, pieceindex, bytes, ipsrc, ipdst, ts): file = open(filename,"ab") # Iterate through bytes writing them to a file if don't have piece already if not self.piecemap[ipdst].has_key(pieceindex): for byte in bytes: file.write('%c' % byte) file.flush() self.procLog.info("Wrote (%d) bytes of piece (%d) to %s" % (len(bytes), pieceindex, filename)) # Remember we have this piece now in case duplicates arrive self.piecemap[ipdst][pieceindex] = True # TODO: Collect stats file.close() As you can see from the for loop, I write the bytes to the file in the same order as I process them from the wire (i.e. network or big-endian order). Suffice to say, the video which is the payload of the pieces does not playback well in VLC :-D I think I need to convert them to little-endian byte order but am not sure the best way to approach this in Python. UPDATE The solution that worked out for me (writing P2P pieces handling endian issues appropriately) was: def writePiece(self, filename, pieceindex, bytes, ipsrc, ipdst, ts): file = open(filename,"r+b") if not self.piecemap[ipdst].has_key(pieceindex): little = struct.pack('<'+'B'*len(bytes), *bytes) # Seek to offset based on piece index file.seek(pieceindex * self.piecesize) file.write(little) file.flush() self.procLog.info("Wrote (%d) bytes of piece (%d) to %s" % (len(bytes), pieceindex, filename)) # Remember we have this piece now in case duplicates arrive self.piecemap[ipdst][pieceindex] = True file.close() The key to the solution was usage of Python struct module as suspected and in particular: little = struct.pack('<'+'B'*len(bytes), *bytes) Thanks to those who responded with helpful suggestions.
[ "To save yourself some work you might like to use a bytearray (Python 2.6 and later):\nb = [14, 254, 23, 35]\nf = open(\"file\", 'ab')\nf.write(bytearray(b))\n\nThis does all the converting of your 0-255 values into bytes without the need for all the looping.\nI can't see what your problem is otherwise without more...
[ 2, 1, 0 ]
[]
[]
[ "binary", "byte", "endianness", "file_io", "python" ]
stackoverflow_0003405972_binary_byte_endianness_file_io_python.txt
Q: How to find out if there is data to be read from stdin on Windows in Python? This code select.select([sys.stdin], [], [], 1.0) does exactly what I want on Linux, but not in Windows. I've used kbhit() in msvcrt before to see if data is available on stdin for reading, but in this case it always returns 0. Additionally msvcrt.getch() returns '\xff' whereas sys.stdin.read(1) returns '\x01'. It seems as if the msvcrt functions are not behaving properly. Unfortunately I can't use TCP sockets as I'm not in control of the application talking my Python program. A: In some rare situations, you might care what stdin is connected to. Mostly, you don't care -- you just read stdin. In someprocess | python myprogram.py, stdin is connected to a pipe; in this case, the stdout of the previous process. You simply read from sys.stdin and you're reading from the other process. [Note that in Windows, however, there's still (potentially) a "CON" device with a keyboard. It just won't be sys.stdin.] In python myprogram.py <someFile, stdin is connected to a file. You simply read from sys.stdin and you're reading from the file. In python myprogram.py, stdin is left connected to the console (/dev/ttyxx in *nix). You simple read from sys.stdin and you're reading from the keyboard. Note the common theme in the above three cases. You simply read from sys.stdin and your program's environment defines everything for you. You don't check "to see if data is available on stdin for reading". It's already available. Sometimes, you want a keyboard interrupt (or other shenanigans). Python, BTW, has a keyboard interrupt as a first-class feature of the I/O elements. Control-C raises an interrupt during I/O (it won't break into a tight loop, but it will signal a program that prints periodically.) Sometimes you need to find out what kind of file stdin is connected to. Something like os.isatty( sys.stdin.fileno() ) If sys.stdin is a TTY, you're program was left connected to the windows "CON" (the keyboard). If sys.stdin is not a TTY, it's connected to a file or a pipe. Example Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\slott>python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> import sys >>> os.isatty( sys.stdin.fileno() ) True >>> The value of True tells me Python is running without a file or pipe attached. sys.stdin is the keyboard. Using windows kbhit is needless. A value of False tells me Python is running with a file or pipe attached. sys.stdin is NOT the keyboard. Checking kbhit might be meaningful. Also, I could open the CON: device and read the keyboard directly, separate from sys.stdin. I'm not sure why you need "to see if data is available on stdin for reading". It might help to update your question with additional details of what you're trying to accomplish. A: I run a thread that reads from stdin, then forward the data to a socket. The socket is selectable, so, stdin is selectable too. In a recent project, I must continuously read from one network socket, forward to another socket, until the user inputs q from the console. One may think to use threading, but I don’t want to deal with multi-thread stuffs. Finally, I found a none-clear solution, and it worked. I create one thread – YES, thread, but no multi-thread concerns – this thread open a server socket listening on random port, then open a client socket connect to this server. The server socket accept the connection, then call sys.stdin.read() in a block way, all data read from stdin will write to that accepted connection. So client socket receive data reading from stdin. Now, the client socket is a selectable stdin, and it is thread-safe. Source code: # coding=UTF-8 """ === Windows stdio === @author ideawu@163.com @link http://www.ideawu.net/ File objects on Windows are not acceptable for select(), this module creates two sockets: stdio.s_in and stdio.s_out, as pseudo stdin and stdout. @example from stdio import stdio stdio.write('hello world') data = stdio.read() print stdio.STDIN_FILENO print stdio.STDOUT_FILENO """ import thread import sys, os import socket # socket read/write in multiple threads may cause unexpected behaviors # so use two separated sockets for stdin and stdout def __sock_stdio(): def stdin_thread(sock, console): """ read data from stdin, and write the data to sock """ try: fd = sys.stdin.fileno() while True: # DO NOT use sys.stdin.read(), it is buffered data = os.read(fd, 1024) #print 'stdin read: ' + repr(data) if not data: break while True: nleft = len(data) nleft -= sock.send(data) if nleft == 0: break except: pass #print 'stdin_thread exit' sock.close() def stdout_thread(sock, console): """ read data from sock, and write to stdout """ try: fd = sys.stdout.fileno() while True: data = sock.recv(1024) #print 'stdio_sock recv: ' + repr(data) if not data: break while True: nleft = len(data) nleft -= os.write(fd, data) if nleft == 0: break except: pass #print 'stdin_thread exit' sock.close() class Console: def __init__(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serv.bind(('127.0.0.1', 0)) self.serv.listen(5) port = self.serv.getsockname()[1] # data read from stdin will write to this socket self.stdin_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.stdin_sock.connect(('127.0.0.1', port)) self.s_in, addr = self.serv.accept() self.STDIN_FILENO = self.s_in.fileno() thread.start_new_thread(stdin_thread, (self.stdin_sock, self)) # data read from this socket will write to stdout #self.stdout_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #self.stdout_sock.connect(('127.0.0.1', port)) #self.s_out, addr = self.serv.accept() #self.STDOUT_FILENO = self.s_out.fileno() #thread.start_new_thread(stdout_thread, (self.stdout_sock, self)) self.read_str = '' # read buffer for readline def close(self): self.s_in.close() self.s_out.close() self.stdin_sock.close() self.stdout_sock.close() self.serv.close() def write(self, data): try: return self.s_out.send(data) except: return -1 def read(self): try: data = self.s_in.recv(4096) except: return '' ret = self.read_str + data self.read_str = '' return ret def readline(self): while True: try: data = self.s_in.recv(4096) except: return '' if not data: return '' pos = data.find('\n') if pos == -1: self.read_str += data else: left = data[0 : pos + 1] right = data[pos + 1 : ] ret = self.read_str + left self.read_str = right return ret stdio = Console() return stdio def __os_stdio(): class Console: def __init__(self): self.STDIN_FILENO = sys.stdin.fileno() self.STDOUT_FILENO = sys.stdout.fileno() def close(self): pass def write(self, data): try: return os.write(self.STDOUT_FILENO, data) except: return -1 def read(self): try: return os.read(self.STDIN_FILENO, 4096) except: return '' def readline(self): try: return sys.stdin.readline() except: return '' stdio = Console() return stdio if os.name == 'posix': stdio = __os_stdio() else: stdio = __sock_stdio()
How to find out if there is data to be read from stdin on Windows in Python?
This code select.select([sys.stdin], [], [], 1.0) does exactly what I want on Linux, but not in Windows. I've used kbhit() in msvcrt before to see if data is available on stdin for reading, but in this case it always returns 0. Additionally msvcrt.getch() returns '\xff' whereas sys.stdin.read(1) returns '\x01'. It seems as if the msvcrt functions are not behaving properly. Unfortunately I can't use TCP sockets as I'm not in control of the application talking my Python program.
[ "In some rare situations, you might care what stdin is connected to. Mostly, you don't care -- you just read stdin.\nIn someprocess | python myprogram.py, stdin is connected to a pipe; in this case, the stdout of the previous process. You simply read from sys.stdin and you're reading from the other process. [Not...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000323829_python.txt
Q: Client Server Socket Programing in Python I have the Client Server Socket program on python. In both the Client and Server I use the loopback address. But kindly assist how to use this code and apply on different Client Server machines Eg (Server IP 192.168.1.4 & Client IP 192.168.1.5) # Server program from socket import * host = "localhost" port = 21567 buf = 1024 addr = (host,port) UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(addr) while 1: data,addr = UDPSock.recvfrom(buf) if not data: print "Client has exited!" break else: print "\nReceived message '", data,"'" UDPSock.close() # Client program from socket import * host = "localhost" port = 21567 buf = 1024 addr = (host,port) UDPSock = socket(AF_INET,SOCK_DGRAM) def_msg = "===Enter message to send to server==="; print "\n",def_msg while (1): data = raw_input('>> ') if not data: break else: if(UDPSock.sendto(data,addr)): print "Sending message '",data,"'....." UDPSock.close() A: Instead of 'localhost', use '192.168.1.5' (the client's address) in the server code, '192.168.1.4' (the server's address) in the client code. Normally a server wouldn't need to know the client's address beforehand, but UDP's knottier than TCP (the more usual, stream-oriented approach to socket communication) in many ways;-).
Client Server Socket Programing in Python
I have the Client Server Socket program on python. In both the Client and Server I use the loopback address. But kindly assist how to use this code and apply on different Client Server machines Eg (Server IP 192.168.1.4 & Client IP 192.168.1.5) # Server program from socket import * host = "localhost" port = 21567 buf = 1024 addr = (host,port) UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(addr) while 1: data,addr = UDPSock.recvfrom(buf) if not data: print "Client has exited!" break else: print "\nReceived message '", data,"'" UDPSock.close() # Client program from socket import * host = "localhost" port = 21567 buf = 1024 addr = (host,port) UDPSock = socket(AF_INET,SOCK_DGRAM) def_msg = "===Enter message to send to server==="; print "\n",def_msg while (1): data = raw_input('>> ') if not data: break else: if(UDPSock.sendto(data,addr)): print "Sending message '",data,"'....." UDPSock.close()
[ "Instead of 'localhost', use '192.168.1.5' (the client's address) in the server code, '192.168.1.4' (the server's address) in the client code.\nNormally a server wouldn't need to know the client's address beforehand, but UDP's knottier than TCP (the more usual, stream-oriented approach to socket communication) in m...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003541611_python.txt
Q: Using Numpy arrays as lookup tables I have a 2D array of Numpy data read from a .csv file. Each row represents a data point with the final column containing a a 'key' which corresponds uniquely to 'key' in another Numpy array - the 'lookup table' as it were. What is the best (most Numpythonic) way to match up the lines in the first table with the values in the second? A: Some example data: import numpy as np lookup = np.array([[ 1. , 3.14 , 4.14 ], [ 2. , 2.71818, 3.7 ], [ 3. , 42. , 43. ]]) a = np.array([[ 1, 11], [ 1, 12], [ 2, 21], [ 3, 31]]) Build a dictionary from key to row number in the lookup table: mapping = dict(zip(lookup[:,0], range(len(lookup)))) Then you can use the dictionary to match up lines. For instance, if you just want to join the tables: >>> np.hstack((a, np.array([lookup[mapping[key],1:] for key in a[:,0]]))) array([[ 1. , 11. , 3.14 , 4.14 ], [ 1. , 12. , 3.14 , 4.14 ], [ 2. , 21. , 2.71818, 3.7 ], [ 3. , 31. , 42. , 43. ]]) A: In the special case when the index can be calculated from the keys, the dictionary can be avoided. It's an advantage when the key of the lookup table can be chosen. For Vebjorn Ljosa's example: lookup: >>> lookup[a[:,0]-1, :] array([[ 1. , 3.14 , 4.14 ], [ 1. , 3.14 , 4.14 ], [ 2. , 2.71818, 3.7 ], [ 3. , 42. , 43. ]]) merge: >>> np.hstack([a, lookup[a[:,0]-1, :]]) array([[ 1. , 11. , 1. , 3.14 , 4.14 ], [ 1. , 12. , 1. , 3.14 , 4.14 ], [ 2. , 21. , 2. , 2.71818, 3.7 ], [ 3. , 31. , 3. , 42. , 43. ]])
Using Numpy arrays as lookup tables
I have a 2D array of Numpy data read from a .csv file. Each row represents a data point with the final column containing a a 'key' which corresponds uniquely to 'key' in another Numpy array - the 'lookup table' as it were. What is the best (most Numpythonic) way to match up the lines in the first table with the values in the second?
[ "Some example data:\nimport numpy as np\n\nlookup = np.array([[ 1. , 3.14 , 4.14 ],\n [ 2. , 2.71818, 3.7 ],\n [ 3. , 42. , 43. ]])\n\na = np.array([[ 1, 11],\n [ 1, 12],\n [ 2, 21],\n [ 3, 31]])\n\nBu...
[ 10, 5 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003522946_numpy_python.txt
Q: python regular expresssion for a string consider this string prison break: proof of innocence (2006) {abduction (#1.10)} i just want to know whether there is (# floating point value )} in the string or not i tried few regular expressions like re.search('\(\#+\f+\)\}',xyz) and re.search('\(\#+(\d\.\d)+\)\}',xyz) nothing worked though...can someone suggest me something here A: Try r'\(#\d+\.\d+\)\}' The (, ), ., and } are all special metacharacters, that's why they're preceded by \, so they're matched literally instead. You also need to apply the + repetition at the right element. Here it's attached to the \d -- the shorthand for digit character class -- to mean that only the digits can appear one-or-more times. The use of r'raw string literals' makes it easier to work with regex patterns because you don't have to escape backslashes excessively. See also What exactly do u and r string flags in Python do, and what are raw string literals? Variations For instructional purposes, let's consider a few variations. This will show a few basic features of regex. Let's first consider one of the attempted patterns: \(\#+(\d\.\d)+\)\} Let's space out the parts for readability: \( \#+ ( \d \. \d )+ \) \} \__________/ this is one group, repeated with + So this pattern matches: A literal (, followed by one-or-more # Followed by one-or-more of: A digit, a literal dot, and a digit Followed by a literal )} Thus, the pattern will match e.g. (###1.23.45.6)} (as seen on rubular.com). Obviously this is not the pattern we want. Now let's try to modify the solution pattern and say that perhaps we also want to allow just a sequence of digits, without the subsequent period and following digits. We can do this by grouping that part (…), and making it optional with ?. BEFORE \(#\d+\.\d+\)\} \___/ let's make this optional! (…)? AFTER \(#\d+(\.\d+)?\)\} Now the pattern matches e.g. (#1.23)} as well as e.g. (#666)} (as seen on rubular.com). References regular-expressions.info - Optional, Brackets for Grouping A: "Escape everything" and use raw-literal syntax for safety: >>> s='prison break: proof of innocence (2006) {abduction (#1.10)}' >>> re.search(r'\(\#\d+\.\d+\)\}', s) <_sre.SRE_Match object at 0xec950> >>> _.group() '(#1.10)}' >>> This assumes that by "floating point value" you mean "one or more digits, a dot, one or more digits", and is not tolerant of other floating point syntax variations, multiple hashes (which you appear from your RE patterns to want to support but don't mention in your Q's text), arbitrary whitespace among the relevant parts (again, unclear from your Q whether you need it), ... -- some issues can be adjusted pretty easily, others "not so much" (it's particularly hard to guess what gamut of FP syntax variations you want to support, for example).
python regular expresssion for a string
consider this string prison break: proof of innocence (2006) {abduction (#1.10)} i just want to know whether there is (# floating point value )} in the string or not i tried few regular expressions like re.search('\(\#+\f+\)\}',xyz) and re.search('\(\#+(\d\.\d)+\)\}',xyz) nothing worked though...can someone suggest me something here
[ "Try r'\\(#\\d+\\.\\d+\\)\\}'\nThe (, ), ., and } are all special metacharacters, that's why they're preceded by \\, so they're matched literally instead.\nYou also need to apply the + repetition at the right element. Here it's attached to the \\d -- the shorthand for digit character class -- to mean that only the ...
[ 3, 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003541963_python_regex.txt