text
stringlengths
226
34.5k
Encode in Python and decrypt in Javascript Question: I've searched for this, there are lots of hits, but I can't find one that is neither complete (pulls all the bits together) nor says its a bad idea, use HTTP. I've tried lots of things based on the hits I've found, but I can't get it to work. The target problem is to AES encrypt textual data at one place, send it to a web API where it is stored in a database, then retrieve from the database via another API and decode it in the browser. This is not for security in transmission, it is so that, if the originator and the receiver know the key and IV, then it can be stored without the server knowing what the real content is. The originator code is python, and the web API is python, so to make life easier initially, I'm storing the content unencrypted in the database. I've done AES encrypt/decrypt in python before, so that's not an issue. What I'm trying to do is encrypt in python as the content comes out of the database, transmit it, then decrypt in javascript. I've been using the python 'from Crypto.Cipher import AES' code, and javascript CryptoJS implementation from code.google.com I'm happy at this stage to write the key and the IV into the code, distribution isn't really a problem as the originator and the client browser are effectively the same system. I've not added any code because I think it would be more trouble than its worth at this stage. Thanks in advance! OK, some code. On the server python(3) side: text = 'This is a message' key = 'This is a key123' iv = 'This is an IV456' text += (16 - len(text) % 16) * ' ' # Pad to 16 chars, spaces are OK here aes = AES.new(key, AES.MODE_CBC, iv) enc = base64.b64encode(aes.encrypt(text)).decode() print(enc) enc is passed along with other data, JSON encoded, as the response to an AJAX request. On the client javascript side: enc = /* from JSON */ ; console.log(enc) ; key = 'This is a key123'; iv = 'This is an IV456'; text = CryptoJS.AES.decrypt(Base64.decode(enc), key, { iv: iv, mode: CryptoJS.mode.CBC })) ; console.log(text) The python print(enc) and the javascript console.log(env) are the same, so I know the b64'd encoded data is coming over OK. The console.log(text) (in Chrome) shows as l.WordArray.t.extend.init { ... }' and not 'This is a message'. So why not! Answer: **Solved, but another mystery** I used the code from this gist: <https://gist.github.com/andres-erbsen/1307675> But: this uses code from <http://crypto-js.googlecode.com/files/>... which is not what you get from the download at <https://code.google.com/p/crypto- js/downloads/list>. The gist code uses Crypto.xxxx names; the download code uses CryptoJS.xxxx names. The gist is 2 years old, has CryptoJS replaced Crypto maybe?
Python: Using mpi4py to bcast an array to other scripts with spawn Question: I'm trying to write two scripts, one a master and one a worker, where the master script will spawn multiple processes of the worker and then bcast a numpy array to the worker spawns. From looking at the number of (vague) tutorials online for mpi4py, I feel like I understand this concept, but any test code I've written won't successfully send the array to the workers. I don't get errors, but they never receive the array. Can someone please give me a clear example of how to use mpi4py, spawn, and bcast to broadcast an array to a number of spawned worker scripts? Thank you! UPDATE: Example: Master script: #! /usr/bin/env python # master test import sys,time from mpi4py import MPI import numpy as np comm2 = MPI.COMM_WORLD rank = comm2.Get_rank() mpisize = comm2.Get_size() initcomm = MPI.COMM_SELF.Spawn(sys.executable, \ args=['test2.py'], \ maxprocs=5) # Initialise the programs test = np.array([1,2,3], 'i') print("About to broadcast {0} from rank {1}".format(test, rank)) initcomm.Bcast([test, MPI.INT], root=0) initcomm.Disconnect() Worker script: #! /usr/bin/env python # child test import sys,time from mpi4py import MPI import numpy as np comm2 = MPI.COMM_WORLD rank = comm2.Get_rank() mpisize = comm2.Get_size() initcomm = MPI.Comm.Get_parent() test = np.zeros(3, 'i') print("Bcast coming to rank {0}".format(rank)) initcomm.Bcast([test, MPI.INT], root=0) print("Received {0}".format(test)) initcomm.Disconnect() Answer: You need to change Bcast in the master script to: initcomm.Bcast([test, MPI.INT], root=MPI.ROOT) If it's set to `0`, the master will think that the root is rank `0` in the remote/worker group, and the program will hang.
Python dictionary having tuple keys and values Question: What I like to have is a dictionary in the format of `{(x1,y1):(a1,b1,c1),(x2,y2):(a2,b2,c2),(x3,y3):(a3,b3,c3),...}` All the data is in a text file in a format like this: x1 y1 a1 ... x1 y1 b1 ... x1 y1 c1 ... x2 y2 a2 ... x2 y2 b2 ... x2 y2 c2 ... I read the text file but I don't know how to associate the a, b, c values with the corresponding key. The script I have right now gives me `{(x1,y1):c1,(x2,y2):c2,(x3,y3):c3,...}` which is not correct Since I read the lines one by one, I am not sure how I can save the a , b values. Answer: with open('path/to/input') as infile: answer = {} for line in infile: x,y,v = line.split() k = (x,y) if k not in answer: answer[k] = [] answer[k].append(v) answer = {k:tuple(v) for k,v in answer.items()} Of course, you could use `collections.defaultdict` to ease your burden just a little: import collections with open('path/to/input') as infile: answer = collections.defaultdict(list) for line in infile: x,y,v = line.split() answer[(x,y)].append(v) answer = {k:tuple(v) for k,v in answer.items()}
Getting Rethinkdb index metadata Question: I'd like to obtain metadata about an index on a Rethinkdb table, such as * what expression is used for arbitrary indexes * what fields are used for compound indexes * whether the index is multi or not How can I get this information through the admin interface? Through the Python API? Thanks! Answer: Unfortunately at this point you can't get any of this information. It's something that's planned as an addition to ReQL but hasn't been added yet. If this issue is important to you I'd recommend opening an issue here: <https://github.com/rethinkdb/rethinkdb> that's the best way to influence development direction.
How does os.path.join() work? Question: Please help me understand how the builtin os.path.join() function works. For example: import os print os.path.join('cat','dog') # 'cat/dog' no surprise here print os.path.join('cat','dog').join('fish') # 'fcat/dogicat/dogscat/dogh' On Mac (and i guess linux too) os.name is an alias for posixpath. So looking into the posixpath.py module, the join() function looks like this: def join(a, *p): """Join two or more pathname components, inserting '/' as needed. If any component is an absolute path, all previous path components will be discarded. An empty last part will result in a path that ends with a separator.""" path = a for b in p: if b.startswith('/'): path = b elif path == '' or path.endswith('/'): path += b else: path += '/' + b return path So join() returns a string. Why does os.path.join('something').join('something else') even work? Shouldn't it raise something like 'str' object has no attribute 'join'? I mean if I copy the function some other place and call it like renamed_join('foo','bar') it works as expected but if i do renamed_join('foo','bar').renamed_join('foobar') will raise an AttributeError as expected. Hopefully this is not a very stupid question. It struck me just when I thought I was starting to understand python... Answer: You can't chain `os.path.join` like that. `os.path.join` returns a string; calling the `join` method of that calls the regular string [`join` method](http://docs.python.org/2/library/stdtypes.html#str.join), which is entirely unrelated.
Log-In Automation Question: I am trying to write a Python script that will automate logging in to a web- client. This is to automatically log-in to the web-client with a provided user name and password. Below is my Python code: import httplib import urllib import urllib2 header = { 'Host' : 'localhost.localdomain', 'Connection' : 'keep-alive', 'Origin' : 'localhost.localdomain', #check what origin does 'User-Agent' : 'Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20131029 Firefox/17.0', 'Content-Type' : 'application/x-www-form-urlencoded', 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Referer' : 'http://localhost.localdomain/mail/index.php/mail/auth/processlogin', 'Accept-Encoding' : 'gzip, deflate', 'Accept-Language' : 'en-US,en;q=0.5', 'Cookie' : 'atmail6=tdl3ckcf4oo88fsgvt5cetoc92' } content = { 'emailName' : 'pen.test.clin', 'emailDomain' : '', 'emailDomainDefault' : '', 'cssStyle' : 'original', 'email' : 'pen.test.clin', 'password' : 'aasdjk34', 'requestedServer' : '', 'MailType' : 'IMAP', 'Language' : '' } def runBruteForceTesting(): url="http://localhost.localdomain/mail/index.php/mail/auth/processlogin" for i in range (0,100): data = urllib.urlencode(content) request = urllib2.Request(url, data, header) response = urllib2.urlopen(url, request) print 'hi' print request, response runBruteForceTesting() However: I am getting the following error: Traceback (most recent call last): File "C:/Users/dheerajg/Desktop/python/log.py", line 39, in <module> runBruteForceTesting() File "C:/Users/dheerajg/Desktop/python/log.py", line 35, in runBruteForceTesting response = urllib2.urlopen(url, request) File "C:\Python27\lib\urllib2.py", line 127, in urlopen return _opener.open(url, data, timeout) File "C:\Python27\lib\urllib2.py", line 402, in open req = meth(req) File "C:\Python27\lib\urllib2.py", line 1123, in do_request_ 'Content-length', '%d' % len(data)) File "C:\Python27\lib\urllib2.py", line 229, in __getattr__ raise AttributeError, attr AttributeError: __len__ Answer: The `request` object that you received from `urllib2.Request` does not have a `__len__` method ; in your context, it means you're calling `urllib2.urlopen` with a wrong second argument. Looking at documentation, it is written it needs a string: > data may be a string specifying additional data to send to the server, or > None if no such data is needed. So what about calling `urlopen` like this: > response = urllib2.urlopen(url, request.get_data()) ?
Can't set up a HTTP CGI Server in Python 2 Question: Does anyone notice this? #!/usr/bin/env python # -*- coding: utf-8 -*- from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler class Handler(CGIHTTPRequestHandler): cgi_directories = ["/"] httpd = HTTPServer(("", 8000), Handler) httpd.serve_forever() And the complete traceback: Traceback (most recent call last): File "server.py", line 6, in <module> from CGIHTTPServer import CGIHTTPRequestHandler File "C:\Python27\lib\CGIHTTPServer.py", line 30, in <module> import SimpleHTTPServer File "C:\Python27\lib\SimpleHTTPServer.py", line 27, in <module> class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): File "C:\Python27\lib\SimpleHTTPServer.py", line 208, in SimpleHTTPRequestHan ler mimetypes.init() # try to read system mime.types File "C:\Python27\lib\mimetypes.py", line 358, in init db.read_windows_registry() File "C:\Python27\lib\mimetypes.py", line 258, in read_windows_registry for subkeyname in enum_types(hkcr): File "C:\Python27\lib\mimetypes.py", line 249, in enum_types ctype = ctype.encode(default_encoding) # omit in 3.x! UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 2: ordinal not in range(128) I used to run this code in the past and it works right, but now it simply doesn't. The code works perfect in Python 3 (changing the imports). Running Python 2.7.6 on Windows 8 (both 64 bits). Reinstalling Python doesn't work. Any ideas? Thanks in advance. Answer: Solved. This is an issue because of the encoding in the Windows registry caused by the mimetypes module. If anybody find the same problem in the future, [here](http://bugs.python.org/issue9291) is the patch to solve it. If you don't want to waste your time checking that, here's the quick solution. Replace the `enum_types()` function from the mimetypes module (`Lib/mimetypes.py`) with this one: from itertools import count def enum_types(mimedb): for i in count(): try: yield _winreg.EnumKey(mimedb, i) except EnvironmentError: break Thanks to all.
Excel (CSV) - transform header data to rows mapping with repeating rows Question: I have Excel based data set which needs transformation. I would request a Python based solution as I am learning Python and can read/modify the code thereafter. I am OK with either an Excel or CSV based input/output. **This is what my data looks like** **Channel** **Condition** **Value1** **Value2** **Value3** _(Header)_ Channel A Condition B Live Live Pilot Channel A Condition B Live Pilot Live Channel B Condition C Pilot Pilot Pilot Channel C Condition D Live Live Live **This is the output I want:** **Channel** **Condition** **Value(all)** *_Status_ * _(Header. I am OK if this does not show up on output)_ Channel A Condition B Value1 Live Channel A Condition B Value2 Live Channel A Condition B Value 3 Pilot Channel A Condition B Value 1 Live Channel A Condition B Value 2 Pilot Channel A Condition B Value 3 Live... Basically it is a repetition of the Channel and Condition for each of the "Values" which should be fetched from Column header and the dataset it self (Live/Pilot). I would appreciate some assistance as I have about 1000 rows of such transformation to do Here is an Image representing what I want ![enter image description here](http://i.stack.imgur.com/Hg4Z4.jpg) Edit 2: There's a type on the screenshot. the Last 3 rows should read Channel B, not Channel A. Answer: Something like that should to the job. import csv transformed = [] with open('excel.csv', newline='') as csvfile: r = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in r: channel, condition, *vals = row for val in vals: transformed.append([channel, condition, val]) with open('transformed.csv', 'w', newline='') as csvfile: w = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) for row in transformed: w.writerow(' '.join(row))
Python BeautifulSoup give multiple tags to findAll Question: I'm looking for a way to use findAll to get two tags, in the order they appear on the page. Currently I have: import requests import BeautifulSoup def get_soup(url): request = requests.get(url) page = request.text soup = BeautifulSoup(page) get_tags = soup.findAll('hr' and 'strong') for each in get_tags: print each If I use that on a page with only 'em' or 'strong' in it then it will get me all of those tags, if I use on one with both it will get 'strong' tags. Is there a way to do this? My main concern is preserving the order in which the tags are found. Answer: You could [pass a list](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-list), to find either `hr` or `strong` tags: tags = soup.find_all(['hr', 'strong'])
Debugging: Shuffle deck of cards in Python/ random Question: I know the title sounds boring, because many people have already asked about this topic. I hope it can help me get some insight into how the random module works. The issue is, I wrote two different functions that I think should be identical, but the results I'm getting are not identical, and I don't understand why. I hope to end up with a "well-shuffled deck." I only care about whether cards are red or black, so my decks are very simple. I am calling "1" red and "0" black. My idea was to build the deck by appending a 1 (red) if random.random() is > .5, or a 0 (black) otherwise, and then just appending 1 or 0 automatically when I have reached 26 (half the deck) of one color. But something is going wrong. deckmaker() doesn't work properly, although deckmaker2() does. Can anyone provide insight? import random def deckmaker(): deck = [] for i in range(52): if deck.count(0) == 26: deck.append(1) elif deck.count(1) == 26: deck.append(0) elif random.random() > .5: deck.append(0) else: deck.append(1) return deck def deckmaker2(): newdeck = [] for i in range(26): newdeck.append(0) for i in range(26): newdeck.append(1) deck = [] for i in range(52): x = random.randint(0,len(newdeck)-1) deck.append(newdeck.pop(x)) return deck Note: While writing this question I discovered the random.shuffle list operator, which does the same thing as my second function, so of course getting the shuffled deck turns out to be easy. But I still wonder why my original code doesn't do the same thing. **Edited:** Sorry for being vague about the exact problem with deckmaker(). The thing is, I don't exactly understand what's wrong. It has to do with the fact that on the decks it produces, as you "turn over" the cards one by one, there are strategies that let you predict whether the "next card" is going to be red or black that don't work with decks created using random.shuffle **Edit 2:** [lots more information] I will explain how I determined that deckmaker doesn't work, in case that is important. I was writing this program to model the puzzle posted here: <http://www.thebigquestions.com/2013/12/17/tuesday-puzzle-4/> My strategy was going to be to remember the last few cards dealt, and use that information to determine when to decide to take the next card. I thought maybe after getting 5 "black" cards in a row, it was a good time to predict "red." I implemented it like so: mycards = [] for j in range(1000): mydeck = deckmaker(52) mem_length = 5 mem = [] for c in range(mem_length): mem.append(4) for i in range(len(mydeck)): if mem.count(0) == mem_length: mycards.append(mydeck[i]) break elif i == len(mydeck)-1: mycards.append(mydeck[i]) break else: mem.append(mydeck[i]) mem.pop(0) x = float(mycards.count(1)) print x/len(mycards) The result more than half the cards I was taking (putting into the list mycards) were "red," a result I achieved by taking the card after 5 _red_ cards in a row were drawn. This made no sense, so I looked for a different way to create the decks and got a more normal result. But I still don't know what was wrong with my original decks. Answer: Generally speaking, you should never believe that a randomization approach works correctly unless you can rigorously _prove_ it works correctly. And that's often hard. To get some insight into your problem, let's generalize the problematic function: import random def deckmaker(n): half = n // 2 deck = [] for i in range(n): if deck.count(0) == half: deck.append(1) elif deck.count(1) == half: deck.append(0) elif random.random() > .5: deck.append(0) else: deck.append(1) return deck And here's a little driver: from collections import Counter c = Counter() for i in range(1000): c[tuple(deckmaker(2))] += 1 for t in sorted(c): print t, c[t] Running that: (0, 1) 495 (1, 0) 505 So the two possibilities are about equally likely. Good! Now try a deck of size 4; just change the relevant line like so: c[tuple(deckmaker(4))] += 1 Running that: (0, 0, 1, 1) 236 (0, 1, 0, 1) 127 (0, 1, 1, 0) 133 (1, 0, 0, 1) 135 (1, 0, 1, 0) 130 (1, 1, 0, 0) 239 Oops! You could run a formal chi-squared test if you like, but it's dead obvious by inspection that two permutations (the first and the last) are about twice as likely as the other four. So the output isn't even close to being arguably random. Why is that? Think about it ;-) **Hint** For a deck of size `2*M`, what's the chance that the first `M` entries are all 0? There are two answers to that: 1. If all permutations of `M` zeroes and `M` ones are equal likely, the chance is 1 in `(2*M)-choose-M` (the number of ways to pick the positions of the `M` zeroes). 2. In the way the function constructs a deck, the chance is 1 in `2**M` (0 and 1 are equally likely in each of the first `M` positions). Generally speaking, `(2*M)-choose-M` is very much larger than `2**M`, so the function constructs a deck starting with all zeroes far more often than "it should". For a deck of 52 cards (`M == 26`): >>> from math import factorial as f >>> one = f(52) // f(26)**2 >>> two = 2**26 >>> float(one) / two 7389761.998476148 So "starts with 26 zeroes" is over 7 million times more likely than it should be. Cool :-) **Doing it "one at a time"** So is it possible to do this correctly picking a 0 or 1 one at a time? Yup! You just need to use the right probabilities: when there are `nzero` zeroes remaining to be picked, and `nremaining` total "cards" remaining to be picked, pick zero with probability `nzero / nremaining`: def deckmaker(n=52): deck = [None] * n nremaining = float(n) nzero = nremaining / 2.0 for i in range(n): if random.random() < nzero / nremaining: deck[i] = 0 nzero -= 1.0 else: deck[i] = 1 nremaining -= 1.0 return deck Note that there's no need to count. When `nzero` becomes 0.0, the `if` test will never succeed (`random() < 0.0` can't happen); and once we pick `n/2` ones, `nzero == nremaining` will be true, and the `if` test will always succeed (`random() < 1.0` is always true). It's cute ;-)
How does run.main() work? Question: Please explain how following statement runs a Python script. There are no custom function calls in this block: if __name__ == '__main__': import sys,os import run run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:]) Let me paste the entire script: import wx import wx.grid as grid import wx.lib.mixins.gridlabelrenderer as glr #---------------------------------------------------------------------- class MyGrid(grid.Grid, glr.GridWithLabelRenderersMixin): def __init__(self, *args, **kw): grid.Grid.__init__(self, *args, **kw) glr.GridWithLabelRenderersMixin.__init__(self) class MyRowLabelRenderer(glr.GridLabelRenderer): def __init__(self, bgcolor): self._bgcolor = bgcolor def Draw(self, grid, dc, rect, row): dc.SetBrush(wx.Brush(self._bgcolor)) dc.SetPen(wx.TRANSPARENT_PEN) dc.DrawRectangleRect(rect) hAlign, vAlign = grid.GetRowLabelAlignment() text = grid.GetRowLabelValue(row) self.DrawBorder(grid, dc, rect) self.DrawText(grid, dc, rect, text, hAlign, vAlign) class MyColLabelRenderer(glr.GridLabelRenderer): def __init__(self, bgcolor): self._bgcolor = bgcolor def Draw(self, grid, dc, rect, col): dc.SetBrush(wx.Brush(self._bgcolor)) dc.SetPen(wx.TRANSPARENT_PEN) dc.DrawRectangleRect(rect) hAlign, vAlign = grid.GetColLabelAlignment() text = grid.GetColLabelValue(col) self.DrawBorder(grid, dc, rect) self.DrawText(grid, dc, rect, text, hAlign, vAlign) class MyCornerLabelRenderer(glr.GridLabelRenderer): def __init__(self): import images self._bmp = images.Smiles.getBitmap() def Draw(self, grid, dc, rect, rc): x = rect.left + (rect.width - self._bmp.GetWidth()) / 2 y = rect.top + (rect.height - self._bmp.GetHeight()) / 2 dc.DrawBitmap(self._bmp, x, y, True) class TestPanel(wx.Panel): def __init__(self, parent, log): self.log = log wx.Panel.__init__(self, parent, -1) ROWS = 27 COLS = 15 g = MyGrid(self, size=(100,100)) g.CreateGrid(ROWS, COLS) g.SetCornerLabelRenderer(MyCornerLabelRenderer()) for row in range(0, ROWS, 3): g.SetRowLabelRenderer(row+0, MyRowLabelRenderer('#ffe0e0')) g.SetRowLabelRenderer(row+1, MyRowLabelRenderer('#e0ffe0')) g.SetRowLabelRenderer(row+2, MyRowLabelRenderer('#e0e0ff')) for col in range(0, COLS, 3): g.SetColLabelRenderer(col+0, MyColLabelRenderer('#e0ffe0')) g.SetColLabelRenderer(col+1, MyColLabelRenderer('#e0e0ff')) g.SetColLabelRenderer(col+2, MyColLabelRenderer('#ffe0e0')) self.Sizer = wx.BoxSizer() self.Sizer.Add(g, 1, wx.EXPAND) #---------------------------------------------------------------------- def runTest(frame, nb, log): win = TestPanel(nb, log) return win #---------------------------------------------------------------------- overview = """<html><body> <h2><center>GridLabelRenderer</h2> The <tt>wx.lib.mixins.gridlabelrenderer</tt> module provides a mixin class for wx.grid.Grid that enables it to have plugin renderers that work like the normal cell renderers do. If desired you can specify a different renderer for each row or col label, and even for the little corner label in the upper left corner of the grid. When each of those labels needs to be drawn the mixin calls the render's Draw method with the dc and rectangle, allowing your renderer class do do just about anything that it wants. </body></html> """ if __name__ == '__main__': import sys,os import run run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:]) it appears that there is a run.py in the same directory with the script above: #!/usr/bin/env python #---------------------------------------------------------------------------- # Name: run.py # Purpose: Simple framework for running individual demos # # Author: Robin Dunn # # Created: 6-March-2000 # RCS-ID: $Id: run.py 53286 2008-04-21 15:33:51Z RD $ # Copyright: (c) 2000 by Total Control Software # Licence: wxWindows license #---------------------------------------------------------------------------- """ This program will load and run one of the individual demos in this directory within its own frame window. Just specify the module name on the command line. """ import wx import wx.lib.inspection import wx.lib.mixins.inspection import sys, os # stuff for debugging print "wx.version:", wx.version() print "pid:", os.getpid() ##raw_input("Press Enter...") assertMode = wx.PYAPP_ASSERT_DIALOG ##assertMode = wx.PYAPP_ASSERT_EXCEPTION #---------------------------------------------------------------------------- class Log: def WriteText(self, text): if text[-1:] == '\n': text = text[:-1] wx.LogMessage(text) write = WriteText class RunDemoApp(wx.App, wx.lib.mixins.inspection.InspectionMixin): def __init__(self, name, module, useShell): self.name = name self.demoModule = module self.useShell = useShell wx.App.__init__(self, redirect=False) def OnInit(self): wx.Log_SetActiveTarget(wx.LogStderr()) self.SetAssertMode(assertMode) self.Init() # InspectionMixin frame = wx.Frame(None, -1, "RunDemo: " + self.name, pos=(50,50), size=(200,100), style=wx.DEFAULT_FRAME_STYLE, name="run a sample") frame.CreateStatusBar() menuBar = wx.MenuBar() menu = wx.Menu() item = menu.Append(-1, "&Widget Inspector\tF6", "Show the wxPython Widget Inspection Tool") self.Bind(wx.EVT_MENU, self.OnWidgetInspector, item) item = menu.Append(-1, "E&xit\tCtrl-Q", "Exit demo") self.Bind(wx.EVT_MENU, self.OnExitApp, item) menuBar.Append(menu, "&File") ns = {} ns['wx'] = wx ns['app'] = self ns['module'] = self.demoModule ns['frame'] = frame frame.SetMenuBar(menuBar) frame.Show(True) frame.Bind(wx.EVT_CLOSE, self.OnCloseFrame) win = self.demoModule.runTest(frame, frame, Log()) # a window will be returned if the demo does not create # its own top-level window if win: # so set the frame to a good size for showing stuff frame.SetSize((640, 480)) win.SetFocus() self.window = win ns['win'] = win frect = frame.GetRect() else: # It was probably a dialog or something that is already # gone, so we're done. frame.Destroy() return True self.SetTopWindow(frame) self.frame = frame #wx.Log_SetActiveTarget(wx.LogStderr()) #wx.Log_SetTraceMask(wx.TraceMessages) if self.useShell: # Make a PyShell window, and position it below our test window from wx import py shell = py.shell.ShellFrame(None, locals=ns) frect.OffsetXY(0, frect.height) frect.height = 400 shell.SetRect(frect) shell.Show() # Hook the close event of the test window so that we close # the shell at the same time def CloseShell(evt): if shell: shell.Close() evt.Skip() frame.Bind(wx.EVT_CLOSE, CloseShell) return True def OnExitApp(self, evt): self.frame.Close(True) def OnCloseFrame(self, evt): if hasattr(self, "window") and hasattr(self.window, "ShutdownDemo"): self.window.ShutdownDemo() evt.Skip() def OnWidgetInspector(self, evt): wx.lib.inspection.InspectionTool().Show() #---------------------------------------------------------------------------- def main(argv): useShell = False for x in range(len(sys.argv)): if sys.argv[x] in ['--shell', '-shell', '-s']: useShell = True del sys.argv[x] break if len(argv) < 2: print "Please specify a demo module name on the command-line" raise SystemExit name, ext = os.path.splitext(argv[1]) module = __import__(name) app = RunDemoApp(name, module, useShell) app.MainLoop() if __name__ == "__main__": main(sys.argv) Answer: In the file `run.py` there is a statement like this: def main(args): pass You are importing run, and calling that `main` function. The `__name__ == '__main__'` part just tells python not run execute that code if the file is being `import`ed, only when run as a script. * * * I'm not sure of the contents of `run.py`, but os.path.basename(sys.argv[0]) will give you the name of the script that is currently being called, so I'm guessing that it is passing the script name and the first argument (`sys.argv[1]`) to `run.main`, and that's how it knows how to run the script.
py2app ValueError: total_size > low_offset (164 > 0) Question: I have a simple python script with two resources that I want to covert to an Mac OSX app. Script runs fins from the command line, but when i try to package it into an app, I get: Ante-scriptum: I'm building in /opt/k which has the right permisions... running py2app creating /opt/k/build/bdist.macosx-10.8-x86_64/python2.7-standalone/app creating /opt/k/build/bdist.macosx-10.8-x86_64/python2.7-standalone/app/collect creating /opt/k/build/bdist.macosx-10.8-x86_64/python2.7-standalone/app/temp creating build/bdist.macosx-10.8-x86_64/python2.7-standalone/app/lib-dynload creating build/bdist.macosx-10.8-x86_64/python2.7-standalone/app/Frameworks *** using recipe: virtualenv *** *** using recipe: sip *** *** using recipe: pyside *** *** using recipe: email *** *** filtering dependencies *** 468 total 66 filtered 9 orphaned 402 remaining *** create binaries *** creating /opt/k/build/bdist.macosx-10.8-x86_64/python2.7-standalone/app/temp/PySide creating python loader for extension 'PySide.QtCore' creating python loader for extension 'PySide.QtGui' creating python loader for extension 'PySide.QtNetwork' creating python loader for extension 'PySide.QtWebKit' *** byte compile python files *** byte-compiling /usr/local/Cellar/pyside/1.2.1/lib/python2.7/site-packages/PySide/__init__.py to PySide/__init__.pyc creating /opt/k/build/bdist.macosx-10.8-x86_64/python2.7-standalone/app/collect/PySide byte-compiling /usr/local/Cellar/pyside/1.2.1/lib/python2.7/site-packages/PySide/_utils.py to PySide/_utils.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/StringIO.py to StringIO.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py to UserDict.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_LWPCookieJar.py to _LWPCookieJar.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_MozillaCookieJar.py to _MozillaCookieJar.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/__future__.py to __future__.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.py to _abcoll.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_osx_support.py to _osx_support.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py to _strptime.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.py to _sysconfigdata.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_threading_local.py to _threading_local.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_weakrefset.py to _weakrefset.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/abc.py to abc.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/aifc.py to aifc.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py to ast.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/atexit.py to atexit.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/base64.py to base64.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/bdb.py to bdb.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/bisect.py to bisect.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/calendar.py to calendar.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/chunk.py to chunk.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cmd.py to cmd.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/codecs.py to codecs.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/collections.py to collections.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py to contextlib.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/cookielib.py to cookielib.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy.py to copy.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.py to copy_reg.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/__init__.py to ctypes/__init__.pyc creating /opt/k/build/bdist.macosx-10.8-x86_64/python2.7-standalone/app/collect/ctypes byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/_endian.py to ctypes/_endian.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ctypes/wintypes.py to ctypes/wintypes.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/difflib.py to difflib.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/dis.py to dis.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/__init__.py to distutils/__init__.pyc creating /opt/k/build/bdist.macosx-10.8-x86_64/python2.7-standalone/app/collect/distutils byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dep_util.py to distutils/dep_util.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/errors.py to distutils/errors.pyc byte-compiling /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/log.py to distutils/log.pyc ... copying file /usr/local/Cellar/pyside/1.2.1/lib/python2.7/site-packages/PySide/QtWebKit.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/PySide/QtWebKit.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/MacOS.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/MacOS.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/Nav.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/Nav.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_AE.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_AE.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_Ctl.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_Ctl.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_Dlg.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_Dlg.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_Evt.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_Evt.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_File.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_File.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_Menu.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_Menu.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_Qd.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_Qd.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_Res.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_Res.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_Win.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_Win.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_bisect.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_bisect.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_codecs_cn.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_codecs_cn.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_codecs_hk.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_codecs_hk.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_codecs_iso2022.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_codecs_iso2022.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_codecs_jp.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_codecs_jp.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_codecs_kr.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_codecs_kr.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_codecs_tw.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_codecs_tw.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_collections.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_collections.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_ctypes.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_ctypes.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_elementtree.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_elementtree.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_functools.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_functools.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_hashlib.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_hashlib.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_heapq.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_heapq.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_io.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_locale.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_locale.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_multibytecodec.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_multibytecodec.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_random.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_random.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_scproxy.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_scproxy.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_socket.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_socket.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_ssl.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_ssl.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_struct.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_struct.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_testcapi.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/_testcapi.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/array.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/array.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/audioop.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/audioop.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/binascii.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/binascii.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/bz2.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/bz2.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/cPickle.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/cPickle.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/cStringIO.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/cStringIO.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/datetime.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/datetime.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/fcntl.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/fcntl.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/gestalt.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/gestalt.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/grp.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/grp.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/itertools.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/itertools.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/math.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/math.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/operator.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/operator.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/parser.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/parser.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/pyexpat.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/pyexpat.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/resource.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/resource.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/select.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/select.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/strop.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/strop.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/termios.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/termios.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/time.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/time.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/unicodedata.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/unicodedata.so copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/zlib.so -> /opt/k/dist/TestApp.app/Contents/Resources/lib/python2.7/lib-dynload/zlib.so copying file test/blah/whatever.png -> /opt/k/dist/TestApp.app/Contents/Resources/test/Ikons/iphone_mail_icon.png copying file test/jquery-1.8.3.min.js -> /opt/k/dist/TestApp.app/Contents/Resources/test/jquery-1.8.3.min.js copying file test/jquery-ui.css -> /opt/k/dist/TestApp.app/Contents/Resources/test/jquery-ui.css copying file test/jquery-ui.min.js -> /opt/k/dist/TestApp.app/Contents/Resources/test/jquery-ui.min.js copying file test/jquery.jsPlumb-1.5.5-min.js -> /opt/k/dist/TestApp.app/Contents/Resources/test/jquery.jsPlumb-1.5.5-min.js copying file test/normalize.css -> /opt/k/dist/TestApp.app/Contents/Resources/test/normalize.css copying file test/phantomjs -> /opt/k/dist/TestApp.app/Contents/Resources/test/phantomjs copying file test.htm -> /opt/k/dist/TestApp.app/Contents/Resources/test.htm copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/Resources/PythonApplet.icns -> /opt/k/dist/TestApp.app/Contents/Resources/PythonApplet.icns copying file /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/py2app/recipes/qt.conf -> /opt/k/dist/TestApp.app/Contents/Resources/qt.conf copying /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -> /opt/k/dist/TestApp.app/Contents/MacOS/python creating /opt/k/dist/TestApp.app/Contents/Frameworks/Python.framework creating /opt/k/dist/TestApp.app/Contents/Frameworks/Python.framework/Versions creating /opt/k/dist/TestApp.app/Contents/Frameworks/Python.framework/Versions/2.7 creating /opt/k/dist/TestApp.app/Contents/Frameworks/Python.framework/Versions/2.7/Resources creating /opt/k/dist/TestApp.app/Contents/Frameworks/Python.framework/Versions/2.7/include creating /opt/k/dist/TestApp.app/Contents/Frameworks/Python.framework/Versions/2.7/include/python2.7 creating /opt/k/dist/TestApp.app/Contents/Frameworks/Python.framework/Versions/2.7/lib creating /opt/k/dist/TestApp.app/Contents/Frameworks/Python.framework/Versions/2.7/lib/python2.7 creating /opt/k/dist/TestApp.app/Contents/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config copying /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/Python -> /opt/k/dist/TestApp.app/Contents/Frameworks/Python.framework/Versions/2.7 copying /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/Python -> /opt/k/dist/TestApp.app/Contents/Frameworks/Python.framework/Versions/2.7 copying /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/Resources/Info.plist -> /opt/k/dist/TestApp.app/Contents/Frameworks/Python.framework/Versions/2.7/Resources copying /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/include/python2.7/pyconfig.h -> /opt/k/dist/TestApp.app/Contents/Frameworks/Python.framework/Versions/2.7/include/python2.7 copying /usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config/Makefile -> /opt/k/dist/TestApp.app/Contents/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config Traceback (most recent call last): File "setup.py", line 24, in <module> setup_requires=['py2app'], File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/core.py", line 152, in setup dist.run_commands() File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 953, in run_commands self.run_command(cmd) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py", line 972, in run_command cmd_obj.run() File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/py2app/build_app.py", line 553, in run self._run() File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/py2app/build_app.py", line 741, in _run self.run_normal() File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/py2app/build_app.py", line 831, in run_normal self.create_binaries(py_files, pkgdirs, extensions, loader_files) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/py2app/build_app.py", line 978, in create_binaries platfiles = mm.run() File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/macholib/MachOStandalone.py", line 105, in run mm.run_file(fn) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/macholib/MachOGraph.py", line 70, in run_file m = self.createNode(MachO, pathname) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/macholib/MachOStandalone.py", line 19, in createNode res = super(FilteredMachOGraph, self).createNode(cls, name) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/altgraph/ObjectGraph.py", line 165, in createNode m = cls(name, *args, **kw) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/macholib/MachO.py", line 69, in __init__ self.load(fp) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/macholib/MachO.py", line 84, in load self.load_header(fh, 0, size) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/macholib/MachO.py", line 114, in load_header hdr = MachOHeader(self, fh, offset, size, magic, hdr, endian) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/macholib/MachO.py", line 154, in __init__ self.load(fh) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/macholib/MachO.py", line 247, in load self.total_size, low_offset)) ` It's been driving me insane! I've installed macports, same error. Removed, installed homebrew versions, same error. Here's setup.py: from setuptools import setup APP = ['blah.py'] DATA_FILES = ['test', 'test.htm'] OPTIONS = {'argv_emulation': False} setup( name = "TestApp", version = "0.9.0", app=APP, data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'], ) Answer: Are you on Mavericks? I'm running into the same problem with a fresh install of py2app on Mavericks. Looks like (in MachO.py) MachO is evaluating its maximum allowable header size (low_offset) as zero, which of course makes no sense. In my case, it was happening at this line: if cmd_cmd.filesize != 0 : low_offset = min(low_offset, cmd_cmd.fileoff) As a result of loading this module: **.../lib/python2.7/lib-dynload/_mysql.so** Right now my mySQLdb installation has a python version mismatch with certain libraries I'm using, which may be the culprit. I was able to work around the error by changing the above code in MachO.py to this: if cmd_cmd.filesize != 0 **and cmd_cmd.fileoff != 0** : low_offset = min(low_offset, cmd_cmd.fileoff) By no means a satisfactory solution, but it allowed me to deploy a needed app. When I resolve my python version mismatch, I will update with the outcome. What worked for you?
Best practice way for linking object attributes to class or object Question: I am looking for a reliable and pythonic way of giving class attributes of a certain type a back-reference to the class they are connected to. i.e. if there is class definition like the one below, I want to give `SomeAttribute()` a reference back to the `SomeClass` type object. class SomeClass(object): attribute = SomeAttribute() Currently I have an implementation that relies on a manual method call after creating a class with this kind of attributes. (Example below). The problem with the current approach is that a lot of code needs to check if the reference class has already been populated to the attributes whenever they are accessed. One solution would be to require that the class is initialized, in which case the code from `bind_attributes` could be placed into the `__init__` method. However that obviously requires instantiating the class even if an instance is not otherwise needed. I am sure a better solution could be implemented using metaclasses, but I do not know how a pythonic implementation using a metaclass would look. import inspect class Attribute(object): def __init__(self, *params): self._params = params self._definition_class = None def bind(self, definition_class): self._definition_class = definition_class def __call__(self): return self._definition_class.separator.join(self._params) class Definition(object): separator = ', ' publications = Attribute('Books', 'Magazines') clothes = Attribute('Shoes', 'Gloves', 'Hats') @classmethod def bind_attributes(cls): for name, attribute in inspect.getmembers(cls, lambda m: isinstance(m, Attribute)): attribute.bind(cls) >>> Definition.bind_attributes() >>> Definition.publications() 'Books, Magazines' >>> Definition.clothes() 'Shoes, Gloves, Hats' Answer: You can do this with a metaclass. For example: class MyMeta(type): def __new__(mcls, name, bases, members): cls = type.__new__(mcls, name, bases, members) for m in members.values(): if isinstance(m, SomeAttribute): m.bound_cls = cls return cls Now of course one downside is this functionality is tied to the class rather than the attribute, so every class you need this functionality with has to use the metaclass: class SomeClass(object): __metaclass__ = MyMeta attribute = SomeAttribute()
Camelot (Python framework): Specifying an Alternative EntityAdmin Question: With the Camelot framework, models (subclassed from Entity) are defined with a nested class (subclasses from EntityAdmin) that defines various gui properties like layout and other widgets. The documentation indicates that multiple EntityAdmins can be defined and then specified by the calling model: > ### admin > > In case of relation fields, specifies the admin class that is to be used to > visualize the other end of the relation. Defaults to the default admin class > of the target class. This can be used to make the table view within a > one2many widget look different from the default table view for the same > object. [Camelot: Field Attributes man page](http://python- > camelot.s3.amazonaws.com/gpl/release/pyqt/doc/doc/field_attributes.html#admin) I can't seem to figure to figure out the required syntax. As a case study, can anyone help me figure out how to do this with the "camelot-example" in the package? (Camelot 13.04.13, Python 2.7.6) Here is my example code: from sqlalchemy.schema import Column from sqlalchemy.types import Unicode, Integer from camelot.admin.entity_admin import EntityAdmin from camelot.core.orm import Entity, ManyToOne, OneToMany import camelot.types class Company(Entity): __tablename__ = 'company' name = Column(Unicode()) city = Column(Unicode()) employees = OneToMany('Employee') def __unicode__(self): return self.name or '' class Admin(EntityAdmin): verbose_name = 'Company' verbose_name_plural = 'Companies' list_display = ['name', 'city', 'employees'] field_attributes = {'employees': {'create_inline': True}, 'admin': 'AlternativeAdmin'} class Employee(Entity): __tablename__ = "employee" name = Column(Unicode()) age = Column(Integer()) company = ManyToOne('Company') def __unicode__(self): return self.name or '' class Admin(EntityAdmin): verbose_name = 'Employee' list_display = ['name', 'age', 'company'] class AlternativeAdmin(EntityAdmin): verbose_name = 'Employee' list_display = ['name'] Note: * "admin" under Company.Admin.field_attributes * The "AlternativeAdmin" class **This code runs without errors, but it does not work as intended**. The company form displays an employee subform that shows name, age, and company. It should just show company. I've tried the following for the "admin" value: 'AlternativeAdmin' AlternativeAdmin 'Employee.AlternativeAdmin' Employee.AlternativeAdmin The error I get when uncommenting is: NameError: name 'AlternativeAdmin' is not defined I'm a self-confessed Python novice and I suspect some better Python understanding could help me solve this. I managed to find this via the great magic eight-ball (Google): A forum-poster said this (sic), "Stupid me, I insisted in the alternate admin class being an inner class just like the original one. Once I unnested it, it worked." He was referencing this code: class A(Entity): ... class Admin(EntityAdmin): ... class AdminEmbedded(EntityAdmin): ... class B(Entity): classA = OneToMany(...) ... class Admin(EntityAdmin): field_attributes = dict(classA=dict(admin=A.AdminEmbedded???)) Unfortunately, his grammar and/or spelling makes it hard to discern what he meant. Also, I'm pretty sure there should be some quotes in there. Answer: I figured it out. The answer induced a face-palm -- I left the AlternativeAdmin class definition below where it was called after I un-nested it. Once I moved it above, it worked fine. Here is a full fixed version of the example in my question: from sqlalchemy.schema import Column from sqlalchemy.types import Unicode, Integer from camelot.admin.entity_admin import EntityAdmin from camelot.core.orm import Entity, ManyToOne, OneToMany import camelot.types class AlternativeAdmin(EntityAdmin): verbose_name = 'Employee' list_display = ['name'] class Company(Entity): __tablename__ = 'company' name = Column(Unicode()) city = Column(Unicode()) employees = OneToMany('Employee') def __unicode__(self): return self.name or '' class Admin(EntityAdmin): verbose_name = 'Company' verbose_name_plural = 'Companies' list_display = ['name', 'city', 'employees'] field_attributes = {'employees': {'create_inline': True, 'admin': AlternativeAdmin}} class Employee(Entity): __tablename__ = "employee" name = Column(Unicode()) age = Column(Integer()) company = ManyToOne('Company') def __unicode__(self): return self.name or '' class Admin(EntityAdmin): verbose_name = 'Employee' list_display = ['name', 'age', 'company']
error to append integer in c++ boost python list Question: I does this code and not work #include <boost/python.hpp> namespace bp = boost::python; int main(int argc, char **argv) { bp::list points; int one = 1; int two = 2; int three = 3; points.append(one); #crach!! points.append(two); points.append(three); return 0;} which is the reason why "append" does not accept integers and directly which would be the correct way? **edited** the solution is this: #include <boost/python.hpp> namespace bp = boost::python; int main(int argc, char **argv) { Py_Initialize(); //this part bp::list points; int one = 1; int two = 2; int three = 3; points.append(one); #crach!! points.append(two); points.append(three); Py_Finalize(); //this part return 0;} Answer: I think you are supposed to use `boost::python::list` from within the exported module, not from a C++ program directly. The reason for this is simple: `boost::python::list` is a wrapper around a Python list object and to work with it you need a Python interpreter which is not available when you try to operate on the list from your `main` method. Here's a working example: #include <boost/python.hpp> namespace bp = boost::python; bp::list getlist() { bp::list points; int one = 1; int two = 2; int three = 3; points.append(one); points.append(two); points.append(three); return points; } BOOST_PYTHON_MODULE(listtest) { using namespace boost::python; def("getlist", getlist); } Compiling this module and running the `getlist` function shows that everything works as expected: >>> import listtest >>> print listtest.getlist() [1, 2, 3]
Python Wave byte data Question: I'm trying to read the data from a .wav file. import wave wr = wave.open("~/01 Road.wav", 'r') # sample width is 2 bytes # number of channels is 2 wave_data = wr.readframes(1) print(wave_data) This gives: b'\x00\x00\x00\x00' Which is the "first frame" of the song. These 4 bytes obviously correspond to the (2 channels * 2 byte sample width) bytes per frame, but what does each byte correspond to? In particular, I'm trying to convert it to a mono amplitude signal. Answer: If you want to understand what the 'frame' is you will have to read the **standard** of the wave file format. For instance: <https://web.archive.org/web/20140221054954/http://home.roadrunner.com/~jgglatt/tech/wave.htm> From that document: > The sample points that are meant to be "played" ie, sent to a Digital to > Analog Converter(DAC) simultaneously are collectively called a **sample > frame**. In the example of our stereo waveform, every two sample points > makes up another sample frame. This is illustrated below for that stereo > example. sample sample sample frame 0 frame 1 frame N _____ _____ _____ _____ _____ _____ | ch1 | ch2 | ch1 | ch2 | . . . | ch1 | ch2 | |_____|_____|_____|_____| |_____|_____| _____ | | = one sample point |_____| To convert to mono you could do something like this, import wave def stereo_to_mono(hex1, hex2): """average two hex string samples""" return hex((ord(hex1) + ord(hex2))/2) wr = wave.open('piano2.wav','r') nchannels, sampwidth, framerate, nframes, comptype, compname = wr.getparams() ww = wave.open('piano_mono.wav','wb') ww.setparams((1,sampwidth,framerate,nframes,comptype,compname)) frames = wr.readframes(wr.getnframes()-1) new_frames = '' for (s1, s2) in zip(frames[0::2],frames[1::2]): new_frames += stereo_to_mono(s1,s2)[2:].zfill(2).decode('hex') ww.writeframes(new_frames) There is no clear-cut way to go from stereo to mono. You could just drop one channel. Above, I am averaging the channels. It all depends on your application.
PyOpenGL-accelerate + numpy Question: I'm installing [MakeHuman](http://www.makehuman.org/doc/node/overview_of_os_specific_installations_and_build_procedures.html) on Debian, so all dependencies was set up, but when launching it's an error: SYS.PLATFORM: linux2 PLATFORM.MACHINE: x86_64 PLATFORM.PROCESSOR: PLATFORM.UNAME.RELEASE: 2.6.32.26 PLATFORM.LINUX_DISTRIBUTION: debian 6.0.6 NUMPY.VERSION: 1.6.2 OpenGL_accelerate module loaded Using accelerated ArrayDatatype Unable to load numpy_formathandler accelerator from OpenGL_accelerate Unable to load registered array format handler numeric Traceback (most recent call last): File "makehuman.py", line 310, in <module> main() File "makehuman.py", line 300, in main from mhmain import MHApplication File "./core/mhmain.py", line 32, in <module> import mh File "./lib/mh.py", line 29, in <module> from glmodule import updatePickingBuffer, grabScreen, hasRenderSkin, renderSkin File "./lib/glmodule.py", line 33, in <module> from OpenGL.GL import * File "/usr/lib/python2.7/dist-packages/OpenGL/GL/__init__.py", line 3, in <module> from OpenGL.raw.GL.annotations import * File "/usr/lib/python2.7/dist-packages/OpenGL/raw/GL/annotations.py", line 40, in <module> 'v', File "/usr/lib/python2.7/dist-packages/OpenGL/arrays/arrayhelpers.py", line 197, in setInputArraySizeType function.setPyConverter( argName, asArrayTypeSize(type, size) ) File "arraydatatype.pyx", line 393, in OpenGL_accelerate.arraydatatype.AsArrayTypedSizeChecked.__init__ (src/arraydatatype.c:7688) AttributeError: 'module' object has no attribute 'sizeof' Does anyone solve problems with link PyOpenGL+ numpy? Answer: fixed that on my system by issuing: > sudo easy_install -U PyOpenGL Noting: * using Ubuntu 12.04 LTS, with python2.7 * did get a Permission denied error without that leading 'sudo' * via: <http://matthew-4gl.wikispaces.com/python_modules> ( in turn from <https://bitbucket.org/ompl/ompl/issue/59/problem-with-ompl_apppy> ) good luck
How to install WTForms? Gettiing import error when trying to import forms Question: I'm trying to follow the [Flask Mega Tutorial](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i- hello-world) for which I need to use WTForms. As is suggested in the tutorial, I use a virtualenv in which I installed WTForms like this: flask/bin/pip install flask-wtf This seemed to work fine, and when I now run it again I simply get this: Requirement already satisfied (use --upgrade to upgrade): flask-wtf in ./flask/lib/python2.7/site-packages Requirement already satisfied (use --upgrade to upgrade): Flask in ./flask/lib/python2.7/site-packages (from flask-wtf) Requirement already satisfied (use --upgrade to upgrade): WTForms>=1.0 in ./flask/lib/python2.7/site-packages (from flask-wtf) Requirement already satisfied (use --upgrade to upgrade): Werkzeug>=0.7 in ./flask/lib/python2.7/site-packages (from Flask->flask-wtf) Requirement already satisfied (use --upgrade to upgrade): Jinja2>=2.4 in ./flask/lib/python2.7/site-packages (from Flask->flask-wtf) Requirement already satisfied (use --upgrade to upgrade): itsdangerous>=0.21 in ./flask/lib/python2.7/site-packages (from Flask->flask-wtf) Requirement already satisfied (use --upgrade to upgrade): markupsafe in ./flask/lib/python2.7/site-packages (from Jinja2>=2.4->Flask->flask-wtf) Cleaning up... But when I try to import forms using `from forms import LoginForm` I get an error saying: `ImportError: cannot import name LoginForm`. Does anybody know what I'm doing wrong here, and how I can solve this? All tips are welcome! Answer: You need a module named `forms` that contains `LoginForm`, from flask.ext.wtf import Form from wtforms import TextField, BooleanField from wtforms.validators import Required class LoginForm(Form): openid = TextField('openid', validators = [Required()]) remember_me = BooleanField('remember_me', default = False) This is the example taken from [Part iii](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web- forms).
Optimizing access on numpy arrays for numba Question: I recently stumbled upon [numba](http://numba.pydata.org/) and thought about replacing some homemade C extensions with more elegant autojitted python code. Unfortunately I wasn't happy, when I tried a first, quick benchmark. It seems like numba is not doing much better than ordinary python here, though I would have expected nearly C-like performance: from numba import jit, autojit, uint, double import numpy as np import imp import logging logging.getLogger('numba.codegen.debug').setLevel(logging.INFO) def sum_accum(accmap, a): res = np.zeros(np.max(accmap) + 1, dtype=a.dtype) for i in xrange(len(accmap)): res[accmap[i]] += a[i] return res autonumba_sum_accum = autojit(sum_accum) numba_sum_accum = jit(double[:](int_[:], double[:]), locals=dict(i=uint))(sum_accum) accmap = np.repeat(np.arange(1000), 2) np.random.shuffle(accmap) accmap = np.repeat(accmap, 10) a = np.random.randn(accmap.size) ref = sum_accum(accmap, a) assert np.all(ref == numba_sum_accum(accmap, a)) assert np.all(ref == autonumba_sum_accum(accmap, a)) %timeit sum_accum(accmap, a) %timeit autonumba_sum_accum(accmap, a) %timeit numba_sum_accum(accmap, a) accumarray = imp.load_source('accumarray', '/path/to/accumarray.py') assert np.all(ref == accumarray.accum(accmap, a)) %timeit accumarray.accum(accmap, a) This gives on my machine: 10 loops, best of 3: 52 ms per loop 10 loops, best of 3: 42.2 ms per loop 10 loops, best of 3: 43.5 ms per loop 1000 loops, best of 3: 321 us per loop I'm running the latest numba version from pypi, 0.11.0. Any suggestions, how to fix the code, so it runs reasonably fast with numba? Answer: I figured out myself. numba wasn't able to determine the type of the result of `np.max(accmap)`, even if the type of accmap was set to int. This somehow slowed down everything, but the fix is easy: @autojit(locals=dict(reslen=uint)) def sum_accum(accmap, a): reslen = np.max(accmap) + 1 res = np.zeros(reslen, dtype=a.dtype) for i in range(len(accmap)): res[accmap[i]] += a[i] return res The result is quite impressive, about 2/3 of the C version: 10000 loops, best of 3: 192 us per loop
Peewee ORM gives IntegrityError: user_id may not be NULL Question: I'm trying to use the Peewee ORM for my new (Flask) website, and now I ran into a problem. I just created a simple model like so: from peewee import TextField, DateTimeField, IntegerField, ForeignKeyField from app import db ROLE_USER = 0 ROLE_ADMIN = 1 class User(db.Model): nickname = TextField() email = TextField() role = IntegerField(default = ROLE_USER) class Post(db.Model): body = TextField() timestamp = DateTimeField() user = ForeignKeyField(User, related_name='posts') So I created two users, after which I wanted to create a new post. I did this like so: >>> from app.models import User >>> u = User(nickname='john', email='[email protected]', role=0) >>> u.save() >>> from app.models import Post >>> from datetime import datetime as dt >>> p = Post(body='FIPO!!', timestamp = dt.now(), author=u) >>> p.save() No handlers could be found for logger "peewee" Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/peewee.py", line 2479, in save ret_pk = self.insert(**field_dict).execute() File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/peewee.py", line 1775, in execute return self.database.last_insert_id(self._execute(), self.model_class) File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/peewee.py", line 1470, in _execute return self.database.execute_sql(sql, params, self.require_commit) File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/peewee.py", line 1885, in execute_sql return self.sql_error_handler(exc, sql, params, require_commit) File "/Users/kramer65/dev/repos/microblog/flask/lib/python2.7/site-packages/peewee.py", line 1871, in sql_error_handler raise exception sqlite3.IntegrityError: post.user_id may not be NULL I don't understand that user_id apparently is NULL, because as far as I understand, peewee should take care of this right? Am I doing something wrong (and if so; what?), or is this a problem with peewee? All tips are welcome! Answer: The problem is you're using `author=` when you should be using `user=`. Original p = Post(body='FIPO!!', timestamp = dt.now(), author=u) Fixed p = Post(body='FIPO!!', timestamp = dt.now(), user=u)
how can I subtract a method value from another method value in python? Question: I've being trying to subtract a method value from another method value but it gives me a an error even when I use variables. from tkinter import * statistics = Tk() screenwidth = statistics.winfo_screenwidth windowwidth = statistics.winfo_width distance = screenwidth - windowwidth statistics.geometry(+distance+'0') Answer: You're trying to subtract two functions. You want to subtract the results of calling the functions. Try this: from Tkinter import * statistics = Tk() screenwidth = statistics.winfo_screenwidth() windowwidth = statistics.winfo_width() distance = screenwidth - windowwidth statistics.geometry('+%s+0' % distance)
Merge CSV Files in Python with Different file names Question: I'm really new to Python, so this question might be a bit basic. I have 44 csv files with the same headers and different file names. I want to combine them all into one file. Each file is named "Votes-[member-name]-(2010-2014)-[download-time].csv" The headers are do not include a column for the member name. I would like to add that as the first item. This does part of what I want to do: [how to merge 200 csv files in Python](http://stackoverflow.com/questions/2512386/how-to-merge-200-csv-files- in-python). I'm just not sure how to iterate through files with different names, and add those names to the csv. Thanks! Answer: To iterate through the filenames you can use a similar method as answered [here](http://stackoverflow.com/a/3964691/2327328), using glob: import glob import os os.chdir("/mydir") for files in glob.glob("*.csv"): print files Then, to add the member name to the header, you can print all the csv files line by line. If the line is a header, then print the member name on the same line as the header. (This isn't real code, but you can get the point) for files in glob.glob("*.csv"): for lines in files: if line == header: print member,line else: print line To split the CSV file and only use the member name (slightly modified so to not have a hyphen) 'Votes-[member name]-(2010-2014)-[download-time].csv'.split('-')[1] **UPDATE for bash solution:** You can save this text and run it from the terminal (see [instructions](http://stackoverflow.com/a/733901/2327328) here for Mac) Generate CSV files (not necessary) cat <<"EOF" > 1.csv 1,2,3 4,5,6 EOF cat <<"EOF" > 2.csv a,b,c d,e,f EOF _Parse CSV files_ \- this script takes all CSV files and writes their file name as the first column. It also puts them into one file (note that I tested on debian linux, not mac). rm -f all.csv for fyle in *.csv ; do echo | awk -v f=$fyle '{ print f","$0 }' $fyle >> all.csv done exit 0 **SECOND UPDATE:** If you want to remove the duplicate headers, the simplest way from the shell is to use 'grep -v', which selects all lines that don't match. You can pick a generic string that only exists in the header. head -1 all.csv > nohead.csv # add one header line grep -v "header string" all.csv >> nohead.csv # add rest of rows, with no headers
Making CSV files easier to modify/navigate within Python using headers / column names? Question: SO, I have a CSV file with a varying number of columns which _I think_ means that the traditional means of making headers as I have **attempted** below won't work... The reason I want some headers is because it gets incredibly difficult to use csv files with 100+ columns and do things like `rPol = math.exp((((-1.2359386)+float(row[48])*(row[33])+row[29]+row[13]+row[97]/row[50])))` Trying to remember the identity of each row is a nussance, and it would be much easier if I could do something like: `rPol = math.exp((((-1.2359386)+float(depolscore)*(master_num)+ripen+offset_score+full/epilic)))` import csv reader = csv.reader(open("test.csv"), delimiter=",") headers = {"data", "title", "here", "testing", "stackoverflow"} csv.DictWriter(reader, headers) reader.writeheader() for row in reader: print testing How would I go about giving specific columns a header without doing something like this: for row in reader: # put the columns into variables... data = row[0] title = row[1] here = row[2] testing = row[3] stackoverflow = row[4] # Do math score = data * here / stackoverflow # Print for user sake print score # Change the testing value testing = testing + (score - title) # Put values back into the reader object? row[0] = data row[1] = title row[2] = here row[3] = testing row[4] = stackoverflow Any ideas? Answer: You could try using a [namedtuple](http://docs.python.org/2/library/collections.html#collections.namedtuple)! It's a subclass of tuple, allowing for easy creation from an iterable and easy access to fields by name. The only gotcha you should be aware of is that namedtuples, like tuples, are immutable so you'd have to store the new tuples somewhere: headers = ["data", "title", "here", "testing", "stackoverflow"] Row = namedtuple('Row', headers) for raw_row in reader: row = Row._make(raw_row) # Do math score = row.data * row.here / stackoverflow # Print for user sake print score # Change the testing value new_testing = row.testing + (score - row.title) new_row = row._replace(testing=new_testing) # Do something with new_row...
Paginator in python django crashes on dict Question: I have 2 types of gathered data from database: One is `[<NaseljenoMesto: NaseljenoMesto object>, <NaseljenoMesto: NaseljenoMesto object>]` And another is: `[{'naseljenomesto_drzava__naziv': u'Srbija', 'sifraMesta': u'ZR', 'nazivMesta': u'Zrenjanin', 'id': 3}, {'naseljenomesto _drzava__naziv': u'Srbija', 'sifraMesta': u'BG', 'nazivMesta': u'Beograd', 'id': 1}]` First is QuerySet type and another is ValuesQuerySet. Now i have Paginator: `paginator = Paginator(filteredData, rowsPerPage)` In first case paginator works but in second crashes. How to correct this? ## EDIT Internal Server Error: /TestProjekat/main/getFormData/ Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "C:\Users\Milan\Desktop\DA_LI_RADI\Test projekat\st_forms\views.py", line 238, in getFormData serializedData = serializers.serialize("json", data) File "C:\Python27\lib\site-packages\django\core\serializers\__init__.py", line 99, in serialize s.serialize(queryset, **options) File "C:\Python27\lib\site-packages\django\core\serializers\base.py", line 46, in serialize concrete_model = obj._meta.concrete_model AttributeError: 'dict' object has no attribute '_meta' ## EDIT 2 paginator = Paginator(filteredData, rowsPerPage) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) serializedData = serializers.serialize("json", data) ## NEW ERROR Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "C:\Users\Milan\Desktop\DA_LI_RADI\Test projekat\st_forms\views.py", line 238, in getFormData serializedData = json.dumps({'data': data}) File "C:\Python27\lib\json\__init__.py", line 243, in dumps return _default_encoder.encode(obj) File "C:\Python27\lib\json\encoder.py", line 207, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Python27\lib\json\encoder.py", line 270, in iterencode return _iterencode(o, 0) File "C:\Python27\lib\json\encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: <Page 1 of 1> is not JSON serializable Answer: The problem is not the pagination, but the way you serialize your data: `serializers.serialize` is built to serialize Django model instances (from a list or a `QuerySet`), nothing else. You can use the `json` module from the python stdlib to serialize 'raw' dictionaries, try for example: import json print json.dumps({'your': 'dict'}) You might need to convert the `ValuesQuerySet` to a vanilla list-of-dicts to convince the `json` module to work, though: # [...] data = paginator.page(1) print json.dumps(list(data))
Calling IDA Pro through python Question: I am trying to use a python script to call IDA Pro and have it run in bash mode. Similar to that of the linux terminal line './idal -B input-File' is there a quick and simple way I can do this throughout the python script? I have looked through the IDA Pro book and I can only find information on IDAPython which I am struggling to understand. Answer: This is a duplicate. Checkout [this](http://stackoverflow.com/questions/89228/calling-an-external- command-in-python) answer. It's basically resumes to: from subprocess import call call(["./idal", "-B", "input-File"])
Creating an sqlite database search engine with python Question: I have an sqlite database with 2 tables. I need to create a cgi search engine for the database, with 2 options in a drop-down menu: Name & Keyword. If the option is Keyword, the 1st table is searched for a matching keyword (in any column). If the option is Name, the 1st column of the 2nd table is searched for an exact match. I have created the cgi web interface with a search box, and the drop-down menu, that saves the input search term. Now I am stuck as to how I can program my cgi script to do a search of the database based on the input term, and display the results to screen as a table. Below are the relevant parts of my script: import cgi """set up the content type, open the html, title, and body""" print '<form action=search.cgi>' print '<select name=\'dropdown\'>' print '<option> Name </option>' print '<option> Keyword </option>' print '</select>' print '<input type=\'text\' name=\'desc\' size=\'25\'>' print '<button type="submit"> Go </button>' print '</form>' args = cgi.FieldStorage() desc = args.getfirst("desc") dropdown = args.getfirst("dropdown") And here is where I need help: if dropdown == 'Keyword': ... elif dropdown == 'Name': ... Thanks in advance for any help! Answer: It seems you just need to do some pretty basic sqlite database operations. The [stdlib documentation](http://docs.python.org/2/library/sqlite3.html) should get you most of the way. It has also links for more resources to help you do more comprehensive SQL queries.
Python 2.7: Issues When Importing a Class Question: I have been searching high and low for an answer and cannot seem to find one. I am running into a fundamental issue when attempting to import a class from another file. I am relatively new to Python and OOP in general, so forgive me if my query is rudimentary. **The Issue:** I want to import a CHILD class into a PARENT class. Simple enough, but when I import the class it immediately executes. **The Question:** How do I import a class so it can be referenced globally in my parent class? Here is a basic example of the PARENT class: from child import CHILD class PARENT: def _init_(self): print "START PARENT CLASS" def goTo(self,enter): if enter == "1": c.childScreen() else: self.parentScreen(self): def parentScreen(self): enter = raw_input("ENTER [1] to go to CHILD class:") self.goTo(enter) p = PARENT() c = CHILD() Okay, so to my beginner eyes this conceptually should work. I imported the class CHILD and created a reference to it "c = CHILD". This concept works when both class's are in the same file but not when they are in two different files. Why? Instead of importing CHILD from child and storing it as a reference it instead executes immediately and does not initiate the PARENT class. Why doesn't this work? I have seen people reference the whole '_name_ ' == '_main_ ' but I don't really know how to implement that and I feel as if there is an easier way. Any help would be appreciated. Thank you! Answer: You are importing the `CHILD` class properly, but you are calling it from outside your `PARENT` class. The `PARENT` class thinks that the variable `c` is a local variable to the function `goTo`. You could use a global variable `c`, but anyone would tell you that that is a big no no. To answer your other question you probably have some code that executes in `CHILD`. If you only want this code to run when you run the file in which the `CHILD` class then put it after a if __name__ == '__main__': This only allows the code preceding it to run if executed directly and it will not run if you import the class. see examples below. You can just create an instance variable of the CHILD class in your `__init__` and use it in the rest of your PARENT class. class PARENT(object): def _init_(self): print "START PARENT CLASS" self.c = CHILD() # create instance of CHILD def goTo(self,enter): if enter == "1": self.c.childScreen() # then you can access CHILD class like this else: self.parentScreen(self): def parentScreen(self): enter = raw_input("ENTER [1] to go to CHILD class:") self.goTo(enter) if __name__ == '__main__': p = PARENT() or you can actaully inherit CHILD into PARENT: class PARENT(CHILD): def _init_(self): print "START PARENT CLASS" def goTo(self,enter): if enter == "1": # now you can access the CHILD functions as if the we were coded in the # PARENT class self.childScreen() else: self.parentScreen(self): def parentScreen(self): enter = raw_input("ENTER [1] to go to CHILD class:") self.goTo(enter) if __name__ == '__main__': p = PARENT()
Python pandas find starting/ending row and rounding numbers Question: import pandas as pd import numpy as np import urllib url = 'http://cawcr.gov.au/staff/mwheeler/maproom/RMM/RMM1RMM2.74toRealtime.txt' urllib.urlretrieve(url,'datafile.txt') df = pd.read_table('datafile.txt', sep='\s+', header=None) df.columns = ['year', 'month', 'day', 'n1', 'n2', 'n3', 'n4', 'type'] df = df[df.year > 1978] #new starting row is created, how do I find what the new starting row is df = df[df.type < 'Prelim_value'] #new ending row is created, how do I find what the new ending row is tda1 = [] for a in range(starting_row, ending_row): if a < starting_row+19: tda1.append(0.0) else: ch = df.ix[a:a+20, ['n1']] dc = np.round(ec,0) tda1.append(ec) How do I find the starting row after chopping off the beginning of the file, ditto on finding the ending row? Would I need to create a whole new dataframe if I wanted to keep everything together...aka, I want to have tda1 being right in line with n1. If I access `tda1[1700]` and `n1[1700]` I want them to both be pointing to the same date. As of yet I still can't get `df.iloc(0)['n1']` or any other combo of to give me anything other than an error suggesting that DataFrame object is not an attribute of iloc. Answer: To quickly answer your last question, use: import numpy as np np.round(ec, 0) For your first (series of) question(s), you don't give us any data to play with and your questions isn't very clear. Either way, you can always get the the first and last rows of _any_ dataframe with `df.iloc[0]` and `df.iloc[-1]`, respectively. ### Edits: If you simply need to know how many rows you have, use `df.shape`. Here's a toy example: import pandas df = pandas.DataFrame([ (1977, 1, 1), (1978, 1, 2), (1979, 1, 3), (1980, 1, 4), (1977, 2, 1), (1978, 2, 2), (1979, 2, 3), (1980, 2, 4), (1977, 3, 1), (1978, 3, 2), (1979, 3, 3), (1980, 3, 4), ], columns=['year', 'a', 'b']) print(df.to_string()) Which prints: year a b 0 1977 1 1 1 1978 1 2 2 1979 1 3 3 1980 1 4 4 1977 2 1 5 1978 2 2 6 1979 2 3 7 1980 2 4 8 1977 3 1 9 1978 3 2 10 1979 3 3 11 1980 3 4 And then: df = df[df.year > 1978] df = df[df.a < 3] print(df.to_string()) which gives: year a b 2 1979 1 3 3 1980 1 4 6 1979 2 3 7 1980 2 4 Try this our yourself after executing everything above: print(df.shape) for row in range(df.shape[0]-1): print(df.iloc[row]) ### For rounding: df = pandas.DataFrame(np.random.normal(size=(4,4))) rounded = np.round(df,1) print(rounded.to_string()) 0 1 2 3 0 -1.2 1.9 0.7 -0.8 1 -0.5 0.9 1.6 -0.3 2 0.4 -0.2 -1.6 -0.2 3 -1.7 1.1 0.1 -0.6
python - recursively deleting dict keys? Question: I'm using Python 2.7 with `plistlib` to import a .plist in a nested dict/array form, then look for a particular key and delete it wherever I see it. When it comes to the actual files we're working with in the office, I already know where to find the values -- but I wrote my script with the idea that I didn't, in the hopes that I wouldn't have to make changes in the future if the file structure changes or we need to do likewise to other similar files. Unfortunately I seem to be trying to modify a dict while iterating over it, but I'm not certain how that's actually happening, since I'm using `iteritems()` and `enumerate()` to get generators and work with those instead of the object I'm actually working with. def scrub(someobject, badvalue='_default'): ##_default isn't the real variable """Walks the structure of a plistlib-created dict and finds all the badvalues and viciously eliminates them. Can optionally be passed a different key to search for.""" count = 0 try: iterator = someobject.iteritems() except AttributeError: iterator = enumerate(someobject) for key, value in iterator: try: scrub(value) except: pass if key == badvalue: del someobject[key] count += 1 return "Removed {count} instances of {badvalue} from {file}.".format(count=count, badvalue=badvalue, file=file) Unfortunately, when I run this on my test .plist file, I get the following error: Traceback (most recent call last): File "formscrub.py", line 45, in <module> scrub(loadedplist) File "formscrub.py", line 19, in scrub for key, value in iterator: RuntimeError: dictionary changed size during iteration So the problem might be the recursive call to itself, but even then shouldn't it just be removing from the original object? I'm not sure how to avoid recursion (or if that's the right strategy) but since it's a .plist, I do need to be able to identify when things are dicts or lists and iterate over them in search of either (a) more dicts to search, or (b) the actual key-value pair in the imported .plist that I need to delete. Ultimately, this is a _partial_ non-issue, in that the files I'll be working with on a regular basis have a known structure. However, I was really hoping to create something that doesn't care about the nesting or order of the object it's working with, as long as it's a Python dict with arrays in it. Answer: Adding or removing items to/from a sequence while iterating over this sequence is tricky at best, and just illegal (as you just discovered) with dicts. The right way to remove entries from a dict while iterating over it is to iterate on a snapshot of the keys. In Python 2.x, `dict.keys()` provides such a snapshot. So for dicts the solution is: for key in mydict.keys(): if key == bad_value: del mydict[key] For lists, trying to iterate on a snapshot of the indexes (ie `for i in len(thelist):`) would result in an IndexError as soon as anything is removed (obviously since at least the last index will no more exist), and even if not you might skip one or more items (since the removal of an item makes the sequence of indexes out of sync with the list itself). `enumate` is safe against IndexError (since the iteration will stop by itself when there's no more 'next' item in the list, but you'll still skip items: >>> mylist = list("aabbccddeeffgghhii") >>> for x, v in enumerate(mylist): ... if v in "bdfh": ... del mylist[x] >>> print mylist ['a', 'a', 'b', 'c', 'c', 'd', 'e', 'e', 'f', 'g', 'g', 'h', 'i', 'i'] Not a quite a success, as you can see. The known solution here is to iterate on reversed indexes, ie: >>> mylist = list("aabbccddeeffgghhii") >>> for x in reversed(range(len(mylist))): ... if mylist[x] in "bdfh": ... del mylist[x] >>> print mylist ['a', 'a', 'c', 'c', 'e', 'e', 'g', 'g', 'i', 'i'] This works with reversed enumeration too, but we dont really care. So to summarize: you need two different code path for dicts and lists - and you also need to take care of "not container" values (values which are neither lists nor dicts), something you do not take care of in your current code. def scrub(obj, bad="_this_is_bad"): if isinstance(obj, dict): for k in obj.keys(): if k == bad: del obj[k] else: scrub(obj[k], bad) elif isinstance(obj, list): for i in reversed(range(len(obj))): if obj[i] == bad: del obj[i] else: scrub(obj[i], bad) else: # neither a dict nor a list, do nothing pass As a side note: **never** write a bare except clause. Never **ever**. This should be illegal syntax, really.
Compare incomplete date list with a reference date list Question: I know this is possible. I know there is a simple solution, but everything I've tried has failed. Here's the deal: I have a dataset in Excel format containing 939,019 weather station records (rows). The date/time interval is every 10 minutes starting from 1/29/1993 16:30 to 6/30/2013 24:00. If I do the math, it is clear that there are missing rows. I need to know the missing dates/times. It would be cool if I could have some little program/script that returned the start date/time and end date/time of the missing intervals. But I'll just be happy with a list of the missing dates/times. To figure it out, I thought, oh, all I need is a reference list to compare the list with missing dates and have some way of flagging or returning the gaps. So, in Excel, I created a column adjacent to the weather station data and populated the first row with the start date. The subsequent rows just add 10 minutes to the cell above it. Unfortunately, the number of 10 minute intervals in that 20 year span is more than excel can handle. No worries. It gets close enough (1/6/2013 10:50). Anyway, I tried the MATCH function in excel, but that is taking way too long. In the time it is taking me to type this, it has reached 3% (using 12 processors). I have 30 weather stations (with the same date range) to do. I'm hoping I can find a faster way to do this. So, I next tried Acess. I imported the files (the weather station data and a separate reference date list) as tables in Access and thought I'd just do an UNMATCHED query, but for some reason (no matter how I format the date column (date/time, serial number), the query returns just about all the rows as unmatched. Not sure why, and it does do it quick, but it is obviously wrong. I then thought - Python! That'd do it, right? But I'm a GIS person. I've only ever used Python sample scripts to run geoprocessing tools (or used ESRi's Model Builder). I don't really have a clue where to start. Any pointers? Answer: First, check out [python-excel.org](http://www.python-excel.org/) for `xlrd`, `xlwt`, and `xlutils` modules and documentation (I'm assuming you're working with `.xls` files, and not `.xlsx` \- if so, check out [`openpyxl`](http://pythonhosted.org/openpyxl/)). Once you've got them installed, read through the docs to familiarize yourself with them, they're not too long or overly complicated. The actual comparison shouldn't be too hard: all you need to do is read cell N, compare its value to cell N+1, and see if the difference is 10 minutes. If it is, great, go to the next value. If not, print the value to a new workbook (or whatever you want to do - insert a blank row with the missing time and calculate again, or what have you). I don't know how long this will take to run through ~30 million records, but I'm willing to bet it'll be faster than doing it via Excel itself :) Good luck!
Summing one array in terms of another - python Question: I have two corresponding 2D arrays, one of velocity, one of intensity. The values of intensity match each of the velocity elements. I have created another 1d array that that goes from min to max velocity in even bin widths. How would I sum the intensity values from my 2d array which correspond to my velocity bins in my 1d array. For example: if I have I = 5 corresponding to velocity = 101km/s, then this is added to the bin 100 - 105 km/s. Here's my input: rad = np.linspace(0, 3, 100) # polar coordinates phi = np.linspace(0, np.pi, 100) r, theta = np.meshgrid(rad, phi) # 2d arrays of r and theta coordinates V0 = 225 # Velocity function w/ constants. rpe = 0.149 alpha = 0.003 Vr = V0 * (1 - np.exp(-r / rpe)) * (1 + (alpha * np.abs(r) / rpe)) # returns 100x100 array of Velocities. Vlos = Vr * np.cos(theta)# Line of sight velocity assuming the observer is in the plane of the polar disk. a = (r**2) # intensity as a function of radius b = (r**2 / 0.23) I = (3.* np.exp(-1. * a)) - (1.8 * np.exp(-1. * b)) I wish to first create velocity bins from Vmin to Vmax and then sum the intensities over each bin. My desired out put would be something along the lines of V_bins = [0, 5, 10,... Vlos.max()] I_sum = [1.4, 1.1, 1.8, ... 1.2] plot(V_bins, I_sum) EDIT: I have come up with temporary solution but perhaps there is a more elegant/efficient method of achieving it? The two array Vlos and I are both 100 by 100 matrices. Vlos = array([[ 0., 8.9, 17.44, ..., 238.5],..., [-0., -8.9, -17.44, ..., -238.5]]) I = random.random((100, 100)) V = np.arange(Vlos.min(), Vlos.max()+5, 5) bins = np.zeros(len(V)) for i in range(0, len(V)-1): for j in range(0, len(Vlos)): # horizontal coordinate in matrix for k in range(0, len(Vlos[0])): # vert coordinate if Vlos[j,k] >= V[i]and Vlos[j,k] < V[i+1]: bins[i] = bins[i] + I[j,k] The result is plotted below. The overall shape in the histogram is to be expected, however I don't understand the spike in the curve at V = 0. As far as I can tell this isn't there in the data which leads me to question my method. ![I don't expect the spike at zero and I would expect a smoother curve](http://i.stack.imgur.com/ddtsi.png) Any further help would be appreciated. Answer: import numpy as np bins = np.arange(100,120,5) velocities = np.array([101, 111, 102, 112]) intensities = np.array([1,2,3,4]) h = np.histogram(velocities, bins, weights=intensities) print h Output: (array([4, 0, 6]), array([100, 105, 110, 115]))
How to skip the unmodified modules importing in PYTHON Question: I have a lot of modules to import before running each script. But the modules i am importing is same in all the scripts. In case of debugging i have to change some code in one or more modules and again run the script. So each time python imports all the modules from the starting. Is there anyway that i skip importing of modules that haven't modified? Answer: You can reload particular modules with [`reload`](http://docs.python.org/2/library/functions.html#reload) function, like this reload(math)
Python debugging, stop at particular output Question: I have complex python project with lots of modules, loggers, twisted defereds and other stuff. And somewhere in the code some line is printed to logs, and I want to find out where. Usually I just search the codebase for that string, but now that string is generated dynamically, so is not searchable. And I wander if there is any way to run python in some debug mode, and tell it to stop when some pattern will appear in sdout, and then print location in code where it stopped? Answer: How about replacing `sys.stdout`? For example: import sys import traceback class StacktraceOnPrint: def __init__(self, orig_stdout, substring): self.orig_stdout = orig_stdout self.substring = substring def write(self, txt): if self.substring in txt: traceback.print_stack() # OR import pdb; pdb.set_trace() self.orig_stdout.write(txt) sys.stdout = StacktraceOnPrint(sys.stdout, 'blah') print 'test ...' print 'Hello blah.' print 'test ...' **NOTE** [`traceback.print_stack`](http://docs.python.org/2/library/traceback.html#traceback.print_stack) uses `sys.stderr`. If you want to catch `sys.stderr`, use different function (like [`traceback.format_stack`](http://docs.python.org/2/library/traceback.html#traceback.format_stack)). Otherwise it recurses forever; causes `RuntimeError: maximum recursion depth exceeded` ..
Looking for a quick way to speed up my code Question: I am looking for a way to speed up my code. I managed to speed up most parts of my code, reducing runtime to about 10 hours, but it's still not fast enough and since I'm running out of time I'm looking for a quick way to optimize my code. **An example:** text = pd.read_csv(os.path.join(dir,"text.csv"),chunksize = 5000) new_text = [np.array(chunk)[:,2] for chunk in text] new_text = list(itertools.chain.from_iterable(new_text)) In the code above I read in about 6 million rows of text documents in chunks and flatten them. This code takes about 3-4 hours to execute. This is the main bottleneck of my program. **edit** : I realized that I wasn't very clear on what the main issue was, **The flattening is the part which takes the most amount of time.** Also this part of my program takes a long time: train_dict = dict(izip(text,labels)) result = [train_dict[test[sample]] if test[sample] in train_dict else predictions[sample] for sample in xrange(len(predictions))] The code above first zips the text documents with their corresponding labels (This a machine learning task, with the train_dict being the training set). Earlier in the program I generated predictions on a test set. There are duplicates between my train and test set so I need to find those duplicates. Therefore, I need to iterate over my test set row by row (2 million rows in total), when I find a duplicate I actually don't want to use the predicted label, but the label from the duplicate in the train_dict. I assign the result of this iteration to the variable result in the above code. I heard there are various libraries in python that could speed up parts of your code, but I don't know which of those could do the job and right know I do not have the time to investigate this, that is why I need someone to point me in the right direction. Is there a way with which I could speed the code snippets above up? **edit2** I have investigated again. And it is definitely a memory issue. I tried to read the file in a row by row manner and after a while the speed declined dramatically, furthermore my ram usage is nearly 100%, and python's disk usage increased sharply. How can I decrease the memory footprint? Or should I find a way to make sure that I don't hold everything into memory? **edit3** As memory is the main issue of my problems I'll give an outline of a part of my program. I have dropped the predictions for the time being, which reduced the complexity of my program significantly, instead I insert a standard sample for every non duplicate in my test set. import numpy as np import pandas as pd import itertools import os train = pd.read_csv(os.path.join(dir,"Train.csv"),chunksize = 5000) train_2 = pd.read_csv(os.path.join(dir,"Train.csv"),chunksize = 5000) test = pd.read_csv(os.path.join(dir,"Test.csv"), chunksize = 80000) sample = list(np.array(pd.read_csv(os.path.join(dir,"Samples.csv"))[:,2]))#this file is only 70mb sample = sample[1] test_set = [np.array(chunk)[:,2] for chunk in test] test_set = list(itertools.chain.from_iterable(test_set)) train_set = [np.array(chunk)[:,2] for chunk in train] train_set = list(itertools.chain.from_iterable(train_set)) labels = [np.array(chunk)[:,3] for chunk in train_2] labels = list(itertools.chain.from_iterable(labels)) """zipping train and labels""" train_dict = dict(izip(train,labels)) """finding duplicates""" results = [train_dict[test[item]] if test[item] in train_dict else sample for item in xrange(len(test))] Although this isn't my entire program, this is the part of my code that needs optimization. As you can see I am only using three important modules in this part, pandas, numpy and itertools. The memory issues arise when flattening train_set and test_set. The only thing I am doing is reading in the files, getting the necessary parts zipping the train documents with the corresponding labels in a dictionary. And then search for duplicates. **edit 4** As requested I'll give an explanation of my data sets. My Train.csv contains 4 columns. The first columns contain ID's for every sample, the second column contains titles and the third column contains text body samples(varying from 100-700 words). The fourth column contains category labels. Test.csv contains only the ID's and text bodies and titles. The columns are separated by commas. Answer: You can try [Cython](http://cython.org/). It supports numpy and can give you a nice speedup. Here is an introduction and explanation of what needs to be done <http://www.youtube.com/watch?v=Iw9-GckD-gQ>
Simple loading time series and plot in python Question: Being a beginner with python, I am very frustrated because after hours of research I can not find a solution for reading+plotting time serieses in python which could be done in matlab, R or gnuplot in 1 minute. Data file: # id date value1 quality anothervalue value2 1 2011-05-19_16:30:19 974.3 3_1x NODATA 10E-4 ... I tried this: import pandas as pd import numpy as np from pandas import Series, DataFrame, Panel import matplotlib as mp import matplotlib.pyplot as plt import matplotlib.dates as mdates a,b,c,d,e,f = np.loadtxt("dataset.dat", unpack=True, converters={ 1: mdates.strpdate2num('%Y-%m-%d_%H:%M:%S') }) plt.plot_date(x=b, y=c) plt.show() Python keeps failing because it tries to automatically convert the data into float. So I tried to use the converters, but it fails for the other columns. No plot at all. * how do I tell python to ignore lines beginning with # ? * do i have to convert everything by hand or can i just read in a dataset without conversion? * how to finally plot value1 over datetime? * can I tell python to interpret NODATA as a value without data? So it does not plot it? Is python so badly documented that one could not google a solution after hours or did I just miss something really practically useful out there? Answer: Not sure if you can achieve desired result with numpy, as it's not well suited for arrays of different types. But as you import pandas, you can use `pd.read_csv`: >>> from StringIO import StringIO >>> s = """# id date value1 quality anothervalue value2 ... 1 2011-05-19_16:30:19 974.3 3_1x NODATA 10E-4""" >>> pd.read_csv(StringIO(s[2:]), sep='\s+', ... date_parser=mdates.strpdate2num('%Y-%m-%d_%H:%M:%S'), ... parse_dates=['date']) id date value1 quality anothervalue value2 0 1 734276.68772 974.3 3_1x NODATA 0
Java Run Static Method in New Thread Question: I just started learning java and I ran into a slight road block involving threads. I have a static method that I would like to run in its own thread, is this possible? In python I know it would look something like this: `import thread;thread.start_new_thread( my_function, () );` And I know how to use threading with non-static methods by implementing Runnable or extending thread, but this is not what I am trying to do. Answer: Have a `Thread`'s `run` method call the `static` method: new Thread(new Runnable() { public void run() { Call.yourStaticMethod(); } }).start();
Is there a method like append for dictionaries Question: How do i add key,value to a dictionary in python? I defined an empty dictionary and now I want to pass a bunch of keys from a list and set their value as 1. From what I did it creates me every iteration a new dictionary, but I want to append the key,value so eventually I will recieve only one dictionary. this is my code: def count_d(words): count_dict={} words_set= set(words) for i in words_set: count_dict[i]= 1 print (count_dict) Answer: What you are looking for is [dict.fromkeys](http://docs.python.org/2/library/stdtypes.html#dict.fromkeys) along with [dict.update](http://docs.python.org/2/library/stdtypes.html#dict.update). **From the docs** > Create a new dictionary with keys from seq and values set to value. **Example Usage** >>> d = {} >>> d.update(dict.fromkeys(range(10), 1)) >>> d {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1} Note, you need an `dict.update` along with `dict.fromkeys`, so as to update the dictionary in-place Instead, if you want to create a dictionary and assign use the notation >>> d = dict.fromkeys(range(10), 1) >>> d {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1} Unfortunately, for in-place update, you need to create a throw-away dictionary before passing to the `dict.update` method. A non-intuitive method is to leverage [itertools](http://docs.python.org/2/library/itertools.html) from itertools import izip, repeat d.update(izip(xrange(10), repeat(1))) The same idea can be extended to [OrderedDict](http://docs.python.org/2/library/collections.html#collections.OrderedDict) which is often used, as an alternate for `OrderedSet` as standard library does not provide one.
Python solution for reading a text file into an if statement Question: I am a new to Python and I am trying to parse some network data to figure out where a certain ip address is based on the city that it is in. I have the following code working below. But I have several hundred lines of information that I would like my script to go through and creating a specific if/else statement for each one didn't seem efficient. from netaddr import * def locateip(ipaddr): if IPAddress(ipaddr) in IPNetwork('10.10.10.0/24'): return 'New York', '10', '10.10.10.0', '10.10.10.0/24', '255.255.255.0' elif IPAddress(ipaddr) in IPNetwork('10.10.20.0/24'): return 'Chicago', '20', '10.10.20.0', '10.10.20.0/24', '255.255.255.0' elif IPAddress(ipaddr) in IPNetwork('10.10.20.0/24'): return 'Dallas', '30', '10.10.30.0', '10.10.30.0/24', '255.255.255.0' ipaddrsource = raw_input('Source Ip Address:') try: srclocation, srcvlan, srcnetwork, srcnetworkcidr, srcsubnetmask = locateip(ipaddrsource) except Exception, e: print e print 'Location: ' + str(srclocation) print 'Vlan: ' + str(srcvlan) print 'Network: ' + str(srcnetwork) print 'Network/CIDR: ' + str(srcnetworkcidr) print 'Subnet Mask: ' + str(srcsubnetmask) All my data is formatted into a text file similar to what is listed below. location vlan network network+cidr subnetmask New York 10 10.10.10.0 10.10.10.0/24 255.255.255.0 Chicago 20 10.10.20.0 10.10.20.0/24 255.255.255.0 Dallas 30 10.10.30.0 10.10.30.0/24 255.255.255.0 I have been trying to get the following to work, but I haven't been able to figure out how to send a line out of a text file into the if statement to return the rest of the metadata back. Any help would be great! from netaddr import * def locateip(ipaddr): f = open('networkinfo.txt','r') for line in f: networkdata = line.split() if IPAddress(ipaddr) in IPNetwork(networkdata[3]): return networkdata[0], networkdata[1], networkdata[2], networkdata[3], networkdata[4] ipaddrsource = raw_input('Source Ip Address:') try: srclocation, srcvlan, srcnetwork, srcnetworkcidr, srcsubnetmask = locateip(ipaddrsource) except Exception, e: print e print 'Location: ' + str(srclocation) print 'Vlan: ' + str(srcvlan) print 'Network: ' + str(srcnetwork) print 'Network/CIDR: ' + str(srcnetworkcidr) print 'Subnet Mask: ' + str(srcsubnetmask) Answer: Your lines start with a location, which itself can contain spaces. As such a straightforward `str.split()` won't work: >>> 'New York 10 10.10.10.0 10.10.10.0/24 255.255.255.0\n'.split() ['New', 'York', '10', '10.10.10.0', '10.10.10.0/24', '255.255.255.0'] Note how `New` and `York` are two separate entries here, making `networkdata[3]` the wrong entry. You need to split from the end, and limit the number of splits: networkdata = line.rsplit(None, 4) Demo: >>> 'New York 10 10.10.10.0 10.10.10.0/24 255.255.255.0\n'.rsplit(None, 4) ['New York', '10', '10.10.10.0', '10.10.10.0/24', '255.255.255.0'] where `None` still splits on arbitrary-width whitespace and strips the newline from the end, but the `4` limits the splitting to 4 separators, leaving `New York` intact. Or, as a complete method with some small improvements: def locateip(ipaddr): ipaddr = IPAddress(ipaddress) with open('networkinfo.txt') as f: next(f, None) # skip the header line first for line in f: location, vlan, net, netcdr, mask = line.rsplit(None, 4) if ipaddr in IPNetwork(netcdr): return location, vlan, net, netcdr, mask It _could_ be that your input format is actually using tabs instead: New York\t10\t10.10.10.0\t10.10.10.0/24\t255.255.255.0 in which case you probably want to read the format with the `csv` module instead: import csv def locateip(ipaddr): ipaddr = IPAddress(ipaddress) with open('networkinfo.txt') as f: reader = csv.reader(f, delimiter='\t') next(reader, None) # skip the header line first for location, vlan, net, netcdr, mask in reader: if ipaddr in IPNetwork(netcdr): return location, vlan, net, netcdr, mask
Python: arguments - 4 arguments allowed, 5 given Question: Trying to create a matrix to start a search algorithm. from numpy import * z11 = vars() z12 = vars() z13 = vars() z14 = vars() z21 = vars() z22 = vars() z23 = vars() z24 = vars() z31 = vars() z32 = vars() z33 = vars() z34 = vars() z41 = vars() z42 = vars() z43 = vars() z44 = vars() A = matrix([z11,z12,z13,z14], [z21,z22,z23,z24], [z31,z32,z33,z34], [z41,z42,z43,z44]) When it is run for errors, it comes up with: Traceback (most recent call last): File "Fusion Puzzle Algorithm 2.py", line 20, in <module> A = matrix([z11,z12,z13,z14], [z21,z22,z23,z24], [z31,z32,z33,z34], [z41,z42,z43,z44]) TypeError: __new__() takes at most 4 arguments (5 given) How can I get this to work? Answer: You likely want something like: A = matrix([[z11,z12,z13,z14], [z21,z22,z23,z24], [z31,z32,z33,z34], [z41,z42,z43,z44]]) Note that there is only one argument to the matrix constructor.
NLTK set method prints characters, not words Question: I'm new to NLTK (and python...) and I'm having two issues with one of its basic methods: when I call sorted(set(<one of nltk's preloaded corpora>)) it prints a list of all the words in the text, but each word is preceded by 'u', like so: [u'yourselves', u'youth']. I thought I'd broken the tokenizer, but I tried re-cloning the repo and re-installing. The second, possibly related issue is that when I define a try using those methods on a string I pass in myself, I get the individual characters, rather than the words. Do I need to parse text that I pass in prior to using set()? Answer: **`u'foo bar'`** is a just a string in `unicode`. both `str` and `unicode` are considered as `basestring` (see <http://docs.python.org/2/howto/unicode.html>, <http://docs.python.org/2/library/functions.html#basestring>) >>> x = u'foobar' >>> isinstance(x, str) False >>> isinstance(x,unicode) True >>> isinstance(x,basestring) True >>> print x foobar When you try to access a corpus from NLTK's corpus readers, the default data structure is a list of sentences where each sentence is a list of tokens and each token is a basestring. >>> from nltk.corpus import brown >>> print brown.sents() [['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', 'Friday', 'an', 'investigation', 'of', "Atlanta's", 'recent', 'primary', 'election', 'produced', '``', 'no', 'evidence', "''", 'that', 'any', 'irregularities', 'took', 'place', '.'], ['The', 'jury', 'further', 'said', 'in', 'term-end', 'presentments', 'that', 'the', 'City', 'Executive', 'Committee', ',', 'which', 'had', 'over-all', 'charge', 'of', 'the', 'election', ',', '``', 'deserves', 'the', 'praise', 'and', 'thanks', 'of', 'the', 'City', 'of', 'Atlanta', "''", 'for', 'the', 'manner', 'in', 'which', 'the', 'election', 'was', 'conducted', '.'], ...] If you want a plain text version of the corpus, you can simply do: >>> for i in brown.sents(): ... print " ".join(i) ... break ... The Fulton County Grand Jury said Friday an investigation of Atlanta's recent primary election produced `` no evidence '' that any irregularities took place . There are many internal magics in NLTK that makes the corpora work as it is from the NLTK's modules but the simplest way to know what's in one of these 'preloaded' corpora (or more accurately 'precoded' corpus readers) is to use: >>> dir(brown) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_add', '_c2f', '_delimiter', '_encoding', '_f2c', '_file', '_fileids', '_get_root', '_init', '_map', '_para_block_reader', '_pattern', '_resolve', '_root', '_sent_tokenizer', '_sep', '_tag_mapping_function', '_word_tokenizer', 'abspath', 'abspaths', 'categories', 'encoding', 'fileids', 'open', 'paras', 'raw', 'readme', 'root', 'sents', 'tagged_paras', 'tagged_sents', 'tagged_words', 'words']
Python numba.jit types Question: I have been trying to deduce how the types are set from the numba documentation all day. I have gotten a bit of the way, but now I want to make a function which returns a one-dimensional array, and a two-dimensjonal array, and take a bunch of args, and I struggle to get any further: @jit class name(object) @double[:,:], double[:](double[:], double, double, int64) def solve(self, u0, a, b, n): self.t = linspace(a, b, n+1) dt = abs((b-a)/float(n)) u = zeros(n+1, len([u0])) u[0] = u0 u = advance(u, t, n, dt) return u.transpose(), t.transpose() The above throws these exceptions: Traceback (most recent call last): File "/home/marius/dev/python/inf1100/test_ODE.py", line 2, in <module> from DE import * File "/home/marius/dev/python/inf1100/DE.py", line 13 @double[:,:], double[:](double[:], double, double, int64) ^ SyntaxError: invalid syntax It would be good if you could tell me what is going wrong, however it would be even better if you could recommend a document which rigorously explains these syntaxes once and for all. Thank you for your time. Kind regards, Marius Answer: Here is a simpler version of a method that returns a tuple. This works for me using Numba 0.11.1 on OS X: import numba import numpy as np @numba.jit class name(object): @numba.object_(numba.double[:], numba.double) def solve(self, x, a): y = np.empty(x.shape[0], dtype=np.float64) z = np.empty(x.shape[0], dtype=np.float64) for k in xrange(x.shape[0]): y[k] = x[k] * a z[k] = x[k] + a return y, z Then using it: C = name() a, b = C.solve(np.arange(5, dtype=np.float64), 3.0) Where `a` and `b` are: In [24]: a Out[24]: array([ 0., 3., 6., 9., 12.]) In [22]: b Out[22]: array([ 3., 4., 5., 6., 7.])
urllib.request for python 3.3 not working to download file Question: I would like to download a large archive file with python and save it, but urllib is not working for me. This is my code: import urllib urllib.request("http://www.petercollingridge.co.uk/sites/files/peter/particle_tutorial_7.txt") Note that the link I used in this example is not a large archive. I am only using it as an example. It links directly to a .txt file, so it should work. I am getting this error: Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> urllib.request("http://www.petercollingridge.co.uk/sites/files/peter/particle_tutorial_7.txt") AttributeError: 'module' object has no attribute 'request' It seems to me like urllib is somehow broken and missing the "request" method. I am using Python 3.3. Should I be using another module or is it actually a Python problem? Answer: No, it is not broken. [The `urllib.request` documentation](http://docs.python.org/3.3/library/urllib.request.html) is pretty clear on how this works: import urllib.request req = urllib.request.urlopen('http://www.google.com') data = req.read() **Edit:** If you need to write the file directly to disk rather than process the data, use `urlretrieve`. urllib.request.urlretrieve('http://example.com/big.zip', 'file/on/disk.zip')
Find + Find next in Python Question: Let L be a list of strings. Here is the code I use for finding a string `texttofind` in the list L. texttofind = 'Bonjour' for s in L: if texttofind in s: print 'Found!' print s break How would you do a **Find next** feature ? Do I need to store the index of the previously found string? Answer: One approach for huge lists would be to use a generator. Suppose you do not know whether the user will need the next match. def string_in_list(s, entities): """Return elements of entities that contain given string.""" for e in entities: if s in e: yield e huge_list = ['you', 'say', 'hello', 'I', 'say', 'goodbye'] # ... matches = string_in_list('y', huge_list) # look for strings with letter 'y' next(matches) # first match next(matches) # second match The other answers suggesting list comprehensions are great for short lists when you want all results immediately. The nice thing about this approach is that if you never need the third result no time is wasted finding it. Again, it would really only matter for big lists. **Update:** If you want the cycle to restart at the first match, you could do something like this... def string_in_list(s, entities): idx = 0 while idx < len(entities): if s in entities[idx]: yield entities[idx] idx += 1 if idx >= len(entities): # restart from the beginning idx = 0 huge_list = ['you', 'say', 'hello'] m = string_in_list('y', huge_list) next(m) # you next(m) # say next(m) # you, again See [How to make a repeating generator](http://stackoverflow.com/questions/1376438/how-to-make-a-repeating- generator-in-python) for other ideas. **Another Update** It's been years since I first wrote this. Here's a better approach using [`itertools.cycle`](https://docs.python.org/3.5/library/itertools.html#itertools.cycle): from itertools import cycle # will repeat after end # look for s in items of huge_list matches = cycle(i for i in huge_list if s in i) next(matches)
How to use Hg-to-Git tool - fast-export? Question: I have tried the instructions from this [SO post](http://stackoverflow.com/questions/16037787/convert-mercurial-project- to-git): cd ~ git clone git://repo.or.cz/fast-export.git git init git_repo cd git_repo ~/fast-export/hg-fast-export.sh -r /path/to/old/mercurial_repo git checkout HEAD However when doing `git checkout HEAD` it throws: error: pathspec 'HEAD' did not match any file(s) known to git What is the work-around for this? **Update:** I managed to install mercurial-python howen when I try to import still it would not work, the error is: Error: No --marks option given When doing: C:\fast-export\hg-fast-export.py -r C:\path\to\repo Answer: Try running `hg-fast-export.sh` instead of `hg-fast-export.py`. It looks like the shell wrapper includes an option for `--marks` for you.
Python script to collect all hostnames of ip addresses with only prime entities Question: I have a Python script to collect hostnames of ip address with primes as byte entities. E.g., 211.13.17.2 is a valid ip according to my problem set where every byte entity(decimal representation) is a prime. **Code:** from itertools import product import socket # prime or not def prime(n): if n > 1: p = 0 for i in range(2, n-1): if divmod(n, i)[1] == 0: p = 1 break if p == 0: return True def get_host_name(b1, b2, b3, b4): addr = str(b1) + '.' + str(b2) + '.' + str(b3) + '.' + str(b4) try: return socket.gethostbyaddr(addr) except socket.herror: pass # find host names whose ip addresses are all primes byte = [b for b in range(0, 256) if prime(b)] ips = list(product(byte, byte, byte, byte)) print 'Total ips = ', len(ips) for ip in ips: if get_host_name(*ip): print get_host_name(*ip) The problem is my script is too slow. I need expert help to optimize this code. Please pinpoint all mistakes and ways to make it behave faster. Answer: for the prime numbers, you can use something like this, import numpy as np isprime = lambda x: np.all(np.mod(x, range(2, 1 + int(np.sqrt(x))))) primes = np.array([ x for x in range(2, 255) if isprime(x) ]) and you can have a generator for ip addresses by ('{}.{}.{}.{}'.format(*x) for x in itertools.product(primes, repeat=4)) but most likely the code is slow in the `socket` part, and because of the number of combinations that it needs to check; for that you may _try_ parallelism, by using a pool of worker processes; something like this: from multiprocessing import Pool from socket import gethostbyaddr def gethost(addr): try: return gethostbyaddr(addr) except: pass if __name__ == '__main__': p = Pool(3) print (p.map(gethost,['74.125.228.137', '11.222.333.444', '17.149.160.49', '98.139.183.24'])) **edit** : for only prime numbers less than 50, (50K+ combinations) and 20 worker processes it takes almost 6 minutes on my machines and it finds 16K+ results. so, with this huge number of combinations parallelism cannot help much.
How to re-implement Ui_MainWindow generated by Qt Question: I've created a interface in Qt as .ui file and then converted it to a python file. Then, I wanted to add some functionality to the components such as radio button, etc. For doing so, I tried to re-implement the class from Qt and add my events. But it gives the following error: self.radioButton_2.toggled.connect(self.radioButton2Clicked) NameError: name 'self' is not defined My first question is whether this is the correct/proper way to deal with classes generated by Qt? And second, why do I get the error? My code is here: import sys from PySide import QtCore, QtGui from InterfaceClass_Test01 import Ui_MainWindow class MainInterface(QtGui.QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MainInterface, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) def setupUi(self, MainWindow): super(MainInterface, self).setupUi(parent, MainWindow) self.radioButton.toggled.connect(self.radioButtonClicked) self.radioButton_2.toggled.connect(self.radioButton2Clicked) self.radioButton_3.toggled.connect(self.radioButton3Clicked) def radioButton3Clicked(self, enabled): pass def radioButton2Clicked(self, enabled): pass def radioButtonClicked(self, enabled): pass Answer: The generated files are a little unintuitive. The UI class is just a simple wrapper, and is not a sub-class of your top-level widget from Qt Designer (as you might expect). Instead, the UI class has a `setupUi` method that takes an instance of your top-level class. This method will add all the widgets from Qt Designer and make them attributes of the passed in instance (which would normally be `self`). The attribute names are taken from the `objectName` property in Qt Designer. It is a good idea to reset the default names given by Qt to more readable ones so that they are easy to refer to later. (And don't forget to re-generate the UI module after you've made your changes!) The module that imports the UI should end up looking like this: import sys from PySide import QtCore, QtGui from InterfaceClass_Test01 import Ui_MainWindow class MainInterface(QtGui.QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MainInterface, self).__init__(parent) # inherited from Ui_MainWindow self.setupUi(self) self.radioButton.toggled.connect(self.radioButtonClicked) self.radioButton_2.toggled.connect(self.radioButton2Clicked) self.radioButton_3.toggled.connect(self.radioButton3Clicked) def radioButton3Clicked(self, enabled): pass def radioButton2Clicked(self, enabled): pass def radioButtonClicked(self, enabled): pass
Can Python read from a Windows Powershell namedpipe? Question: I have the following named pipe created in Windows Powershell. # .NET 3.5 is required to use the System.IO.Pipes namespace [reflection.Assembly]::LoadWithPartialName("system.core") | Out-Null $pipeName = "pipename" $pipeDir = [System.IO.Pipes.PipeDirection]::InOut $pipe = New-Object system.IO.Pipes.NamedPipeServerStream( $pipeName, $pipeDir ) Now, what i need is some Python code snippet to read from the above named pipe created. Can Python do that ? Thanks in advance ! Answer: Courtesy :<http://jonathonreinhart.blogspot.com/2012/12/named-pipes-between-c- and-python.html> Here's the C# Code using System; using System.IO; using System.IO.Pipes; using System.Text; class PipeServer { static void Main() { var server = new NamedPipeServerStream("NPtest"); Console.WriteLine("Waiting for connection..."); server.WaitForConnection(); Console.WriteLine("Connected."); var br = new BinaryReader(server); var bw = new BinaryWriter(server); while (true) { try { var len = (int)br.ReadUInt32(); // Read string length var str = new string(br.ReadChars(len)); // Read string Console.WriteLine("Read: \"{0}\"", str); //str = new string(str.Reverse().ToArray()); // Aravind's edit: since Reverse() is not working, might require some import. Felt it as irrelevant var buf = Encoding.ASCII.GetBytes(str); // Get ASCII byte array bw.Write((uint)buf.Length); // Write string length bw.Write(buf); // Write string Console.WriteLine("Wrote: \"{0}\"", str); } catch (EndOfStreamException) { break; // When client disconnects } } } } And here's the Python code: import time import struct f = open(r'\\.\pipe\NPtest', 'r+b', 0) i = 1 while True: s = 'Message[{0}]'.format(i) i += 1 f.write(struct.pack('I', len(s)) + s) # Write str length and str f.seek(0) # EDIT: This is also necessary print 'Wrote:', s n = struct.unpack('I', f.read(4))[0] # Read str length s = f.read(n) # Read str f.seek(0) # Important!!! print 'Read:', s time.sleep(2) Convert the C# code into a .ps1 file.
Logging into Stack Overflow with Mechanize and Python Question: I have been using this guide to help me: <http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet/> I want to log into Stack Overflow and print out my login response using Mechanize in Python. I have been troubleshooting to find a form name to select and enter my information into, but am currently getting an error "ValueError: at least one argument must be supplied to specify control" because I am trying to print out all forms and controls to help me figure out what I need to choose from. import mechanize #make browser object browser = mechanize.Browser() #open stack login page browser.open("http://stackoverflow.com/users/login#login-in") #print all the forms on the page print("\n Printing all forms on page...\n") for form in browser.forms(): print("Form Name:", form.name) print form print("\n Done printing forms...\n") #printing the controls of each form browser.form=list(browser.forms())[0] print("\n Printing controls of form 0 \n") for control in browser.form.controls: print control print "type=%s, name=%s, value=%s" % (control.type, control.name, browser[control.name]) browser.form=list(browser.forms())[1] print("\n Printing controls of form 1 \n") for control in browser.form.controls: print control print "type=%s, name=%s, value=%s" % (control.type, control.name, browser[control.name]) browser.form=list(browser.forms())[2] print("\n Printing controls of form 2 \n") for control in browser.form.controls: print control print "type=%s, name=%s, value=%s" % (control.type, control.name, browser[control.name]) print("\n Done printing all controls \n") It looks like there are 3 forms on the page, but they do not contain the email and password inputs I am looking for to login. What am I doing wrong? Answer: Login forms for SO appear to use extensive JavaScript. Note that all of the buttons related to login on the page you posted call JavaScript functions. `mechanize` can not execute JavaScript and therefore won't show the content you need. You could drive a browser using [Selenium](http://www.seleniumhq.org/) with [Python bindings](https://pypi.python.org/pypi/selenium). You could also switch to doing everything in JavaScript using [CasperJS](http://casperjs.org/).
Python - Importing strings into a list, into another list :) Question: Basically I want to read strings from a text file, put them in lists three by three, and then put all those three by three lists into another list. Actually let me explain it better :) Text file (just an example, I can structure it however I want): party sleep study -------- party sleep sleep ----- study sleep party --------- etc From this, I want Python to create a list that looks like this: List1 = [['party','sleep','study'],['party','sleep','sleep'],['study','sleep','party']etc] But it's super hard. I was experimenting with something like: test2 = open('test2.txt','r') List=[] for line in 'test2.txt': a = test2.readline() a = a.replace("\n","") List.append(a) print(List) But this just does horrible horrible things. How to achieve this? Answer: **If you want to group the data in size of 3**. Assumes your data in the text file is not grouped by any separator. You need to read the file, sequentially and create a list. To group it you can use any of the known [grouper algorithms](http://stackoverflow.com/questions/312443/how-do-you-split-a-list- into-evenly-sized-chunks-in-python) from itertools import izip, imap with open("test.txt") as fin: data = list(imap(list, izip(*[imap(str.strip, fin)]*3))) pprint.pprint(data) [['party', 'sleep', 'study'], ['party', 'sleep', 'sleep'], ['study', 'sleep', 'party']] _Steps of Execution_ 1. Create a Context Manager with the file object. 2. Strip each line. (Remove newline) 3. Using zip on the iterator list of size 3, ensures that the items are grouped as tuples of three items 4. Convert tuples to list 5. Convert the generator expression to a list. Considering all are generator expressions, its done on a single iteration. **Instead, if your data is separated and grouped by a delimiter`------` you can use the `itertools.groupby` solution** from itertools import imap, groupby class Key(object): def __init__(self, sep): self.sep = sep self.count = 0 def __call__(self, line): if line == self.sep: self.count += 1 return self.count with open("test.txt") as fin: data = [[e for e in v if "----------" not in e] for k, v in groupby(imap(str.strip, fin), key = Key("----------"))] pprint.pprint(data) [['party', 'sleep', 'study'], ['party', 'sleep', 'sleep'], ['study', 'sleep', 'party']] _Steps of Execution_ 1. Create a Key Class, to increase a counter when ever the separator is encountered. The function call spits out the counter every-time its called apart from conditionally increasing it. 2. Create a Context Manager with the file object. 3. Strip each line. (Remove newline) 4. Group the data using `itertools.groupby` and using your custom key 5. Remove the separator from the grouped data and create a list of the groups.
Does the interpreter compile python scripts? Question: I wrote a script, say, `samplescript.py`. All I can recall doing with, other than editing it, is running it through the command-line python interpreter. Later, I found a `samplescript.pyc` file. Does running a script through the interpreter always invoke the compilation of the script? Answer: When you execute your code, python creates a compiled pyc file. This file is the one executed in posterior runs if you do not modify your code From [here](http://docs.python.org/release/1.5.1p1/tut/node43.html): > As an important speed-up of the start-up time for short programs that use a > lot of standard modules, if a file called "spam.pyc" exists in the directory > where "spam.py" is found, this is assumed to contain an already-``byte- > compiled'' version of the module spam. The modification time of the version > of "spam.py" used to create "spam.pyc" is recorded in "spam.pyc", and the > file is ignored if these don't match. > > Normally, you don't need to do anything to create the "spam.pyc" file. > Whenever "spam.py" is successfully compiled, an attempt is made to write the > compiled version to "spam.pyc". It is not an error if this attempt fails; if > for any reason the file is not written completely, the resulting "spam.pyc" > file will be recognized as invalid and thus ignored later. The contents of > the "spam.pyc" file is platform independent, so a Python module directory > can be shared by machines of different architectures.
Python mock.patch doesn't patch the correct import Question: # Code def test_get_network_info(self): with open(dirname(abspath(__file__)) + '/files/fake_network_info.txt', 'r') as mock_network_info: with patch('subprocess.check_output', Mock(return_value=mock_network_info.read())): self.assertEqual('192.168.1.100', get_network_info()[0]) self.assertEqual('255.255.255.0', get_network_info()[1]) self.assertEqual('192.168.1.0', get_network_info()[2]) # Error ====================================================================== ERROR: test_get_network_info (tests.test_tools.ToolsTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/tim/Documents/overseer/app/tests/test_tools.py", line 21, in test_get_network_info with patch('subprocess.check_output', Mock(return_value=mock_network_info.read())): File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1268, in __enter__ original, local = self.get_original() File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1242, in get_original "%s does not have the attribute %r" % (target, name) AttributeError: <module 'subprocess' from '/usr/local/lib/python2.7/dist-packages/twill/other_packages/subprocess.pyc'> does not have the attribute 'check_output' # What I understand My understanding of the problem is that `mock` is trying to mock [twill](https://github.com/ctb/twill)'s `subprocess` module instead of the python one. # Questions 1. Am I doing something wrong ? 2. How can I specify that I want to patch the python `subprocess` module and not the twill's one ? (that may have been imported earlier in the test suite)** 3. Is there another way to patch the `subprocess` module ? # What I tried * I tried `with patch('tools.subprocess.check_output', ...` Doesn't work. * I tired to use a decorator ... Doesn't work either * I tired to patch directly the `subprocess` module `subprocess.check_output = Mock( ...` Works but it's not good since it doesn't undo the patching. # Some more informations If I run just this test and no other tests, it works because twill's subprocess module never got imported. But as soon as I run a test using twill, the above test will fail. [Here](https://github.com/ctb/twill/blob/master/twill/other_packages/subprocess.py) is the twill's version of subprocess wich looks like it has been copy pasted from an old version of python. It doesn't have any `check_output` function and that's why the test fails. Twill's package comes from the [Flask-Testing](https://github.com/jarus/flask- testing/) plugin which I use extensively. I submitted an issue on github [here](https://github.com/jarus/flask-testing/issues/36). I hope someone from the **lovely python community** can help. :) Answer: See my comment up there, due to bad practices in twill, the proper way would be to either fix twill, which may take some work, or move away to something else, but since you now heavily depend on Flask-Testing, it's not a cheap move either. So this leaves us with a dirty trick: make sure to `import subprocess` anywhere before twill is imported. Internally, this will add a reference to the right `subprocess` module in `sys.modules`. Once a module is loaded, all subsequents `import` won't look anymore in `sys.path` but just use the reference already cached in `sys.modules`. Unfortunately this is maybe not the end of the problem. Apparently twill uses a patched version of subprocess for some reason ; and those patches won't be available for him, since the plain built-in subprocess will be loaded instead. It's very likely it'll crash or behave in an unexpected way. If it's the case, well ... back to the suggestions above.
How to use socket with a Python client and a C++ server Question: I have a simple client/server program. The client is written in python as this : import socket import sys HOST, PORT = "localhost", 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) for x in range(0, 10000): print("Step 1") s.send(b'Hello') print("Step 2") print(str(s.recv(1000))) print(x) And I wrote a server in python like this : import socket HOST = '' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() while True: data = conn.recv(1024) conn.sendall(data) I want to create a C++ version of the server. I did this : #include <iostream> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <string> #include <arpa/inet.h> #include <string.h> #include <stdio.h> using namespace std; #define SERVER_PORT htons(50007) int main() { char buffer[1000]; int n; int serverSock=socket(AF_INET, SOCK_STREAM, 0); sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = SERVER_PORT; serverAddr.sin_addr.s_addr = INADDR_ANY; /* bind (this socket, local address, address length) bind server socket (serverSock) to server address (serverAddr). Necessary so that server can use a specific port */ bind(serverSock, (struct sockaddr*)&serverAddr, sizeof(struct sockaddr)); // wait for a client /* listen (this socket, request queue length) */ listen(serverSock,1); while (1 == 1) { bzero(buffer, 1000); sockaddr_in clientAddr; socklen_t sin_size=sizeof(struct sockaddr_in); int clientSock=accept(serverSock,(struct sockaddr*)&clientAddr, &sin_size); //receive a message from a client n = read(clientSock, buffer, 500); cout << "Confirmation code " << n << endl; cout << "Server received: " << buffer << endl; strcpy(buffer, "test"); n = write(clientSock, buffer, strlen(buffer)); cout << "Confirmation code " << n << endl; } return 0; } It works one time but it block at the line `str(s.recv(1000))` of the client. This is the output from the client : Step 1 Step 2 b'test' 0 Step 1 Step 2 And this is the output from the server : code 5 Server received: Hello code 4 code 5 Server received: Hello code 4 As you can see, the communication is like this : 1. The client send a message 2. The server receive the message 3. The server send a message 4. The client send another message 5. The server receive a message and seems to send another message but the client did not receive it. What is my error? Answer: In C++ server, you `accept` connection, `read`, `write`, then _leak the open socket_ and go to wait for next client to connect. Move your `accept` out of the loop, or add inner loop after accept. And `close` the socket when you're done with it, before the variable with socket number goes out of scope.
Project/Multiple Class Verbose Mode Python Question: I'm wondering what the simplest way to enable debugging/verbose mode outputs in a project that involves multiple classes/files. The answer given here: [Easier way to enable verbose logging](http://stackoverflow.com/questions/14097061/easier-way-to-enable- verbose-logging) works well in a single script but what might be the best implementation across multiple classes? I've thought to use the Singleton design pattern to set a single instance of a `"Debugger"` which will have a `Debugger.log("message")`. Is there a better way to accomplish this? Answer: This already exists. this is `logging.root` which is a `logging.Logger` instance. You just need to set it up before using it. A simple example: >>> import logging >>> >>> logging.root.setLevel('INFO') >>> logging.root.info('Info message') INFO:root:Info message The logging functions for the root logger are also available from the `logging` module directly: >>> logging.info('Info message') INFO:root:Info message For a full reference on how to setup a logger see [the official python documentation](http://docs.python.org/3.3/library/logging.html).
Python modules run function from file Question: I have a python (2) project with this structure: alerter │ README.txt │ __init__.py │ __init__.pyc │ └───lib Alarm.py Alarm.pyc __init__.py __init__.pyc in `lib.__init__.py` I have a function that I want to call from `lib.Alarm.py`. If I just call it in `Alarm.py` I get this error: NameError: global name 'openDatabase' is not defined Now I tried almost all imports at the top of the `lib.Alarm.py` file: * `from lib import openDatabase` ERROR: ImportError: No module named lib * `from alerter.lib import openDatabase` ERROR: ImportError: cannot import name openDatabase Anyone an idea what I might try? Answer: Try this: from alerter import lib lib.openDatabase() (You don't state your Python version, which could be relevant.)
Generate output files from template file and csv data in python Question: I need to generate xml files poulated with data from a csv file in python I have two input files: one CSV file named data.csv containing data like this: ID YEAR PASS LOGIN HEX_LOGIN 14Z 2013 (3e?k<.P@H}l hex0914Z F303935303031345A 14Z 2014 EAeW+ZM..--r hex0914Z F303935303031345A ....... One Template file named template.xml <?xml version="1.0"?> <SecurityProfile xmlns="security_profile_v1"> <year></year> <security> <ID></ID> <login></login> <hex_login></hex_login> <pass></pass> </security> </SecurityProfile> I want to get as many output files as lines in the csv data file, each output filed named YEAR_ID, with the data from the csv file in the xml fields: Output files contentes: Content of output file #1 named 2013_0950014z: <?xml version="1.0"?> <SecurityProfile xmlns="security_profile_v1"> <year>2013</year> <security> <ID>14Z</ID> <login>hex0914</login> <hex_login>F303935303031345A</hex_login> <pass>(3e?k<.P@H}l</pass> </security> </SecurityProfile> Content of output file #2 named 2014_0950014z: <?xml version="1.0"?> <SecurityProfile xmlns="security_profile_v1"> <year>2014</year> <security> <ID>14Z</ID> <login>hex0914</login> <hex_login>F303935303031345A</hex_login> <pass>EAeW+ZM..--r</pass> </security> </SecurityProfile> Thank you for your suggestions. Answer: Can you make changes the template? If so, I would do the following to make this a bit simpler: <?xml version="1.0"?> <SecurityProfile xmlns="security_profile_v1"> <year>{year}</year> <security> <ID>{id}</ID> <login>{login}</login> <hex_login>{hex_login}</hex_login> <pass>{pass}</pass> </security> </SecurityProfile> Then, something like this would work: import csv input_file_name = "some_file.csv" #name/path of your csv file template_file_name = "some_file.xml" #name/path of your xml template output_file_name = "{}_09500{}.xml" with open(template_file_name,"rb") as template_file: template = template_file.read() with open(filename,"rb") as csv_file: my_reader = csv.DictReader(csv_file) for row in my_reader: with open(output_file_name.format(row["YEAR"],row["ID"]),"wb") as current_out: current.write(template.format(year=row["YEAR"], id=row["ID"], login=row["LOGIN"], hex_login=row["HEX_LOGIN"], pass=row["PASS"])) If you can't modify the template, or want to process it as XML instead of basic string manipulation, then it's a bit more involved. **EDIT:** Modified answer to use csv.DictReader rather than csv.reader.
python opencv error finding contours Question: ![](http://i.stack.imgur.com/t1NHA.jpg) I'm trying to find the contour of the attached image of a tshirt. FindContours returns a rectangular frame around the tshirt, and doesn't find any additional contours. My goal is to find the external contour of the tshirt. Any idea what am I doing wrong? Code below. Thanks. Li from PIL import Image import os import numpy import bs4 import scipy import cv2 STANDARD_SIZE = (200, 200) # read image file image_obj_orig = cv2.imread(image_file) image_name = os.path.split(image_file)[-1] name, extension = os.path.splitext(image_name) # normalize to a standard size image_obj = cv2.resize(image_obj_orig, STANDARD_SIZE) # convert to grey-scale greyscale_image = cv2.cvtColor(image_obj,cv2.COLOR_BGR2GRAY) cv2.imwrite(os.path.join(trg_dir, name + '_GS' + extension), greyscale_image) h, w = greyscale_image.shape[:2] contours, hierarchy = cv2.findContours( greyscale_image.copy(), cv2.RETR_TREE , cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours( greyscale_image, contours, -1, (128,255,255)) cv2.imshow('image', greyscale_image) Answer: Have you tried this: ret,thresh = cv2.threshold(greyscale_image.copy(),127,255,cv2.THRESH_BINARY_INV) # add this line before findContours contours, hierarchy = cv2.findContours( thresh, cv2.RETR_TREE , cv2.CHAIN_APPROX_SIMPLE)
cx_freeze & bundling files Question: At present I am using pyinstaller for bundling my python application. I am equally migrating to pyGObject (due to pygtk being depreciated). Now pyinstaller does not support pyGObject and I have as of yet not figured out the required hooks... One of the other downsides of pyinstaller is how it bundles into a single executable - it causes the company installed virus scanner to check quite intensively every time the exe is run ==> quite slow startup. Looking into using cx_freeze due to the pyGObject & py3 support I note it does not have a single-executable option. That in itself isn't an issue if the working directory can be cleaned up, be it via the pyd/dll being bundled into a second zip or into a subdirectory. Searching around (stackoverflow and other sites), it is illuded to that it can be done, but I am not getting the expected results. Any idea#s? setup.py is based around this one: <http://wiki.wxpython.org/cx_freeze> Answer: ok solved: 1) setup.py import sys from cx_Freeze import setup, Executable EXE1 = Executable( # what to build script = "foo.py", initScript = None, base = 'Win32GUI', targetDir = "dist", targetName = "foo.exe", compress = True, copyDependentFiles = True, appendScriptToExe = True, appendScriptToLibrary = False, icon = 'foo.ico' ) setup( version = "9999", description = "...", author = "...", name = "...", options = {"build_exe": {"includes": includes, "excludes": excludes, "packages": packages, "path": sys.path, "append_script_to_exe":False, "build_exe":"dist/bin", "compressed":True, "copy_dependent_files":True, "create_shared_zip":True, "include_in_shared_zip":True, "optimize":2, } }, executables = [EXE1] ) 2) foo.py header: import os import sys if getattr(sys,'frozen',False): # if trap for frozen script wrapping sys.path.append(os.path.join(os.path.dirname(sys.executable),'bin')) sys.path.append(os.path.join(os.path.dirname(sys.executable),'bin\\library.zip')) os.environ['TCL_LIBRARY'] = os.path.join(os.path.dirname(sys.executable),'bin\\tcl') os.environ['TK_LIBRARY'] = os.path.join(os.path.dirname(sys.executable),'bin\\tk') os.environ['MATPLOTLIBDATA'] = os.path.join(os.path.dirname(sys.executable),'bin\\mpl-data')
Grid search function in Python Question: I am trying to write a parameter search function to loop over one of the parameters and repeatedly call a function with all other parameters the same, other than the one I am searching over. Here is some sample code: def worker1(a, b, c): return a + b + c def worker2(d, e, f): return d * e * f def search(model, params): res = [] # Loop over one of the parameters and repeatedly append to res if model == 1: res.append(worker1(**params)) elif model == 2: res.append(worker2(**params)) return res params = dict(a=1, b=2, c=3) print search(1, params) I have two workers and they are called depending on the value of the `model` flag I pass to `search()`. The problem I am trying to solve here is to write a loop (commented in the code) over the if statements to repeatedly call say `worker1` by varying only one of the parameters. I want my code to be flexible - sometimes I want to loop through `a` and keep `b` and `c` the same, but sometimes I want to loop through `b` and keeping `a` and `c` the same. I'm open whatever solution suggested, but I think I would be specifying the search parameters in the `params` dictionary. E.g. To loop `a` over 1,2,3,4, I would say: `params = dict(a=[1,2,3,4], b=2, c=3)` Also it would be nice if I don't have to modify the code for `worker1` and `worker2`. Thank you! Answer: You could perhaps use `itertools.product` to call your workers with all combinations of params: <http://docs.python.org/2/library/itertools.html#itertools.product> eg from itertools import product def worker1(a, b, c): return a + b + c def worker2(d, e, f): return d * e * f def search(model, *params): res = [] # Loop over one of the parameters and repeatedly append to res for current_params in product(*params): if model == 1: res.append(worker1(*current_params)) elif model == 2: res.append(worker2(*current_params)) return res print search(1, [1,2,3,4], [2], [3]) # more complicated combinations are possible: print search(1, [1,2,3,4], [2,7,9], [3,13,23,43]) I've avoided using keyword arguments as your worker functions take differently-named args so it wouldn't make much sense. I'm assuming your worker functions don't actually look like the ones above as if they did you could further simplify the code using the builtin `sum` and `reduce` functions.
Can a spawned process communicate with the "main" MPI communicator Question: Is there a way using MPI to let spawned processes communicate with all other actors in the MPI_WORLD and not only with the parent that spawned the process? Now I have two main agents, the so-called master and slave that run the following code (spawn.py): # Spawn test: master and first slave import sys from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() if rank == 0 : # master code print "i am the master on rank %i" % (rank) running = True while running : msg = comm.recv(source=MPI.ANY_SOURCE,tag=0) print "master received message: ", msg if msg == "Done" : running = False print "master is done" if rank == 1 : # slave code no_spawn = 1 print "I am a slave on rank %i, about the spawn lower slaves" % (rank) icomm = MPI.COMM_SELF.Spawn(sys.executable,args=["Cpi.py","ben"],maxprocs=no_spawn) comm.send("Test_comm",dest=0,tag=0) icomm.send("Test_icomm",dest=0,tag=0) isize = icomm.Get_size() print "on slave, isize= %i" % (isize) rec = 0 while rec <= (no_spawn-1) : msg = icomm.recv(source=MPI.ANY_SOURCE,tag=20) print "slave received message: %s (rec=%i)" % (msg, rec) rec = rec +1 import time print "slave going to sleep\n" time.sleep(1) for i in range(no_spawn) : message = ("To spawn from slave",) icomm.send(message,dest=i,tag=0) for i in range(no_spawn) : message = ("Done",) icomm.send(message,dest=i,tag=0) msg = comm.recv(source=MPI.ANY_SOURCE,tag=0) print "slave received message: ", msg comm.send("Done",dest=0,tag=0) MPI.Finalize() The slave, in turn, spawns 1 more processes that runs the following code (CPi.py, named after the mpi4py tutorial file): #!/usr/bin/env python import sys from mpi4py import MPI comm = MPI.COMM_WORLD icomm = MPI.Comm.Get_parent() irank = icomm.Get_rank() print "Spawn irank=%i" % (irank) message = "From_Spawn_%i"%(irank) icomm.send(message,dest=0,tag=20) running = True while running : msg = icomm.recv(source=MPI.ANY_SOURCE,tag=0) print "Spawn on irank %i received message: %s " %(irank,msg) if msg[0] == "Done" : running = False print "spawn %i sending a last msg to the master and the slave" % (irank) comm.send(("To master from spawn",), dest=0,tag=0) comm.send(("To slave from spawn",), dest=0,tag=0) Between the master and slave I can send messages by using the `comm` communicator. Between the slave and the spawned process I can send messages over the `icomm` communicator. But what I really want is to spawn a process and that this process can communicate with both the master and slave over the `comm` communicator; see the last two lines of the spawned process. Is that possible? And would it be possible for the spawned process to listen as well to the main `comm` used by the slave and the master? Which rank would it be send to / listen to? The provided code does not terminate because the last two messages send by the spawned process are neither received by the slave or the master. (I run the code with `mpiexec -n 2 python spawn.py`) Answer: For the process spawned by the slave to talk to the master, it would need to create another new communicator using something like MPI_CONNECT and MPI_ACCEPT. It's possible to do, but you'd have to use the slave to transfer the connection details between the two. Before you go through all of that, be sure that you can't just start your job with more process and arbitrarily assign different roles to different ranks. It's a pain to use intercommunicators under the best of circumstances and it's probably simpler to start out with the correct number of processes.
Replacing a leading text string with the same string in python Question: I have the following tags in a xml file as > &\hbox{(1b)}}$$ with the initial condition <2inline-formula>$x(0)$, where > the subscript <3inline-formula>$p$ means 'plant'; <4inline-formula>$x_{p}(t) > \in \Re^{n}$ is the state, <5inline-formula>$y_{p}(t)\in\Re^{q}$ is the > output, and <6inline-formula>$u_{p}(t)\in\Re^{m}$ is the input; <7inline- > formula> I want to replace the inline-formulas which are all starting with numbers to `<inline-formula>` but i am not able to give the condition to search for the inline formula staring with numbers so any help on this.. Thanks in advance Answer: You have to use regular expresions (`re` module) for detecting one or more digits preceeding "inline-formula" (`\d+inline-formula`). Like this for example: >>> import re >>> original = "&\hbox{(1b)}}$$ with the initial condition <2inline-formula>$x(0)$, where the subscript <3inline-formula>$p$ means 'plant’; <4inline-formula>$x_{p}(t) \in \Re^{n}$ is the state, <5inline-formula>$y_{p}(t)\in\Re^{q}$ is the output, and <6inline-formula>$u_{p}(t)\in\Re^{m}$ is the input; <7inline-formula>" >>> new = re.sub(r"<\d+inline-formula>", "<inline-formula>", original) >>> print new "&\\hbox{(1b)}}$$ with the initial condition <inline-formula>$x(0)$, where the subscript <inline-formula>$p$ means 'plant\xe2\x80\x99; <inline-formula>$x_{p}(t) \\in \\Re^{n}$ is the state, <inline-formula>$y_{p}(t)\\in\\Re^{q}$ is the output, and <inline-formula>$u_{p}(t)\\in\\Re^{m}$ is the input; <inline-formula>" >>>
python Weather API location id Question: a=pywapi.get_loc_id_from_weather_com("pune") {0: (u'TTXX0257', u'Pune, OE, Timor-leste'), 1: (u'INXX0102', u'Pune, MH, India'), 2: (u'BRPA0444', u'Pune, PA, Brazil'), 3: (u'FRBR2203', u'Punel, 29, France'), 4: (u'IDVV9705', u'Punen, JT, Indonesia'), 5: (u'IRGA2787', u'Punel, 19, Iran'), 6: (u'IRGA2788', u'Punes, 19, Iran'), 7: (u'IDYY7030', u'Punen, JI, Indonesia'), 8: (u'RSUD1221', u'Punem, UD, Russia'), 9: (u'BUXX2256', u'Punevo, 09, Bulgaria'), 'count': 10} For the above command, I'm getting 10 results. I want a specific location like Pune,MH,India. How do I get it? Answer: I look the source code of pywapi, and found that the searchstring would be quoted(url encode, e.g. ',' will be quoted to "%2C") in `get_loc_id_from_waather_com`. So when you call `pywapi.get_loc_id_from_weather_com(" Pune,MH,India")` it will request the url:`http://xml.weather.com/search/search?where=Pune%2CMH%2CIndia` but not `http://wxdata.weather.com/wxdata/search/search?where=Pune,MH,India`. And the formmer is certain no results. A solution is that you can modify(hack) the pywapi. Just edit the pywapi.py and find the `get_loc_id_from_weather_com` function. replace the line `url = LOCID_SEARCH_URL % quote(search_string)` to `url = LOCID_SEARCH_URL % quote(search_string, ',')` And now you can: In [2]: import pywapi In [3]: pywapi.get_loc_id_from_weather_com("Pune,MH,India") # no spaces Out[3]: {0: (u'INXX0102', u'Pune, MH, India'), 'count': 1} PS: The source code of pywapi: def get_loc_id_from_weather_com(search_string): """Get location IDs for place names matching a specified string. Same as get_location_ids() but different return format. Parameters: search_string: Plaintext string to match to available place names. For example, a search for 'Los Angeles' will return matches for the city of that name in California, Chile, Cuba, Nicaragua, etc as well as 'East Los Angeles, CA', 'Lake Los Angeles, CA', etc. Returns: loc_id_data: A dictionary of tuples in the following format: {'count': 2, 0: (LOCID1, Placename1), 1: (LOCID2, Placename2)} """ # Weather.com stores place names as ascii-only, so convert if possible try: # search_string = unidecode(search_string.encode('utf-8')) search_string = unidecode(search_string) except NameError: pass url = LOCID_SEARCH_URL % quote(search_string) # change to:url = LOCID_SEARCH_URL % quote(search_string, ',') try: handler = urlopen(url) except URLError: return {'error': 'Could not connect to server'} if sys.version > '3': # Python 3 content_type = dict(handler.getheaders())['Content-Type'] else: # Python 2 content_type = handler.info().dict['content-type'] try: charset = re.search('charset\=(.*)', content_type).group(1) except AttributeError: charset = 'utf-8' if charset.lower() != 'utf-8': xml_response = handler.read().decode(charset).encode('utf-8') else: xml_response = handler.read() dom = minidom.parseString(xml_response) handler.close() loc_id_data = {} try: num_locs = 0 for loc in dom.getElementsByTagName('search')[0].getElementsByTagName('loc'): loc_id = loc.getAttribute('id') # loc id place_name = loc.firstChild.data # place name loc_id_data[num_locs] = (loc_id, place_name) num_locs += 1 loc_id_data['count'] = num_locs except IndexError: error_data = {'error': 'No matching Location IDs found'} return error_data finally: dom.unlink() return loc_id_data
Python permutations Question: I am trying to generate pandigital numbers using the itertools.permutations function, but whenever I do it generates them as a list of separate digits, which is not what I want. For example: for x in itertools.permutations("1234"): print(x) will produce: ('1', '2', '3', '4') ('1', '2', '4', '3') ('1', '3', '2', '4') ('1', '3', '4', '2') ('1', '4', '2', '3') ('1', '4', '3', '2'), etc. whereas I want it to return 1234, 1243, 1324, 1342, 1423, 1432, etc. How would I go about doing this in an optimal fashion? Answer: A list comprehension with the built-in `str.join()` function is what you need: import itertools a = [''.join(i) for i in itertools.permutations("1234") ] print(a) Output: ['1234', '1243', '1324', '1342', '1423', '1432', '2134', '2143', '2314', '2341', '2413', '2431', '3124', '3142', '3214', '3241', '3412', '3421', '4123', '4132', '4213', '4231', '4312', '4321']
How to get a percentile for an empirical data distribution and get it's x-coordinate? Question: I have some discrete data values, that taken together form some sort of distribution. This is one of them, but they are different with the peak being in all possible locations, from 0 to end. ![enter image description here](http://i.stack.imgur.com/D3Ypf.png) So, I want to use it's quantiles (percentiles) in Python. I think I could write some sort of function, that would some up all values starting from zero, until it reaches desired percent. But probably there is a better solution? For example, to create an empirical distribution of some sort in SciPy and then use SciPy's methods of calculating percentiles? In the very end I need x-coordinates of a left percentile and a right percentile. One could use 20% and 80% percentiles as an example, I will have to find the best numbers for my case later. Thank you in advance! **EDIT:** some example code for almost what I want. import numpy as np np.random.seed(0) distribution = np.random.normal(0, 1, 1000) left, right = np.percentile(distribution, [20, 80]) print left, right This returns percentiles themselves, I need to get their x-coordinates somehow. For normal distribution here it is possible, obviously, but I have a distribution of an unknown shape, so if a percentile isn't equal to one of the values (which is the most common thing, obviously), it becomes much more complicated. Answer: if you are looking for empirical CDF then you may use statsmodels [ECDF](http://statsmodels.sourceforge.net/devel/generated/statsmodels.tools.tools.ECDF.html). For percentiles/quantiles you can use numpy [percentile](http://docs.scipy.org/doc/numpy/reference/generated/numpy.percentile.html)
How to log both to console and file using Python? Question: I am working Python and I need to logger so I decided to start using RotatingFileHandler. Below is my `logging.conf` file [loggers] keys=root [handlers] keys=logfile [formatters] keys=logfileformatter [logger_root] level=DEBUG handlers=logfile [formatter_logfileformatter] format=%(asctime)s %(name)-12s: %(levelname)s %(message)s [handler_logfile] class=handlers.RotatingFileHandler level=NOTSET args=('ookagent.log', 'a', 50000000000, 5) formatter=logfileformatter And below is my Python script from which I am successfully able to log to the files. But I am not sure how to log both to files and console as well. #!/usr/bin/python import logging import logging.config import logging.handlers # using RotatingFileHandler for logging purpose logging.config.fileConfig('logging.conf') ooklogger = logging.getLogger('') ooklogger.info("HelloWorld") Can we make a change in my logging.conf file by which I can login both to console and files as well? Is it possible to do that? Answer: Sure, the logging configuration file format lets you specify multiple handlers. You can use a `StreamHandler` to log to the console. That would entail modifications like these to your config file: [handlers] keys=logfile,logconsole [handler_logconsole] class=StreamHandler # other configuration directives as you like [logger_root] handlers=logfile,logconsole See the [config file documentation](http://docs.python.org/2/library/logging.config.html#configuration- file-format) for more information and examples.
Dialogs tripping up in Vala Question: I've been experimenting with Vala programming recently. I've got pretty extensive experience programming in other languages, but in recent years have stuck mainly with scripting languages like Python, Tcl and Perl. I was impressed by the clean look of Elementary OS, which is what started me looking into Vala, and I must say that my first impressions are very positive. However, I have hit a snag with Dialog programming, which I thought more experienced Vala programmers might be able to help with. In my latest test program I use a Dialog-based routine to obtain a value (getYesNo), and then display a string describing that value to screen using another Dialog-based routine (showDialog). Both routines work correctly when used independently, but when used together as described the display event is held back until a second call is made to the value-obtaining routine. This sounds like the sort of situation that a call to "flush_events" would solve in Perl or Tcl. But how can I deal with it in Vala? Or is there a way to avoid it happening in the first place? Code: using Gtk; using Posix; public class DialogTestWindow: ApplicationWindow { private int RESPONSE; private Toolbar tbMain = new Toolbar(); private ToolButton bAbout = new ToolButton(new Image.from_icon_name ("help-about",IconSize.SMALL_TOOLBAR),null); private ToolButton bDoIt = new ToolButton(new Image.from_icon_name ("media-record",IconSize.SMALL_TOOLBAR),null); private ToolButton bQuit = new ToolButton(new Image.from_icon_name ("application-exit",IconSize.SMALL_TOOLBAR),null); internal DialogTestWindow(DialogTest app) { Object(application: app, title: "DialogTest"); this.window_position = WindowPosition.CENTER; this.set_default_size(720,480); // ---- Set up Toolbar ---------------------------------------------------- tbMain.get_style_context().add_class(STYLE_CLASS_PRIMARY_TOOLBAR); bQuit.is_important = true; bQuit.clicked.connect(onQuit); tbMain.add(bQuit); bAbout.is_important = true; bAbout.clicked.connect(onAbout); tbMain.add(bAbout); bDoIt.is_important = true; bDoIt.clicked.connect(onDoIt); tbMain.add(bDoIt); // ---- Pack Toolbar etc into vBox on main window ------------------------- Box vbMain = new Box(Orientation.VERTICAL,0); vbMain.pack_start(tbMain,false,true,0); this.add(vbMain); this.show_all(); printf("Started\n"); } // ==== getYesNo ========================================================== private void getYesNo(string message) { Dialog dialog = new Dialog.with_buttons ("Get",this,DialogFlags.MODAL, Stock.YES,ResponseType.YES,Stock.NO,ResponseType.NO,null); var content = dialog.get_content_area(); // warning: assignment from incompatible pointer type // [enabled by default] Label label = new Label(message); label.set_line_wrap(true); content.add(label); dialog.response.connect((id)=>{ printf("response id=%i\n",id); RESPONSE = id; dialog.destroy(); }); dialog.show_all(); } // ==== onAbout =========================================================== private void onAbout() { Dialog dialog = new Dialog.with_buttons ("About",this,DialogFlags.MODAL, Stock.OK,ResponseType.OK,null); var content = dialog.get_content_area(); // warning: assignment from incompatible pointer type // [enabled by default] Label label = new Label("This program tests pop-up dialogs"); content.add(label); dialog.response.connect(()=>{dialog.destroy();}); dialog.show_all(); } // ==== onDoIt ============================================================ private void onDoIt() { getYesNo("Well?"); if (RESPONSE==ResponseType.YES) showDialog("YES!"); } // ==== onQuit ============================================================ private void onQuit() { printf("Ending\n"); exit(-1); } // ==== showDialog ======================================================== private void showDialog(string message) { Dialog dialog = new Dialog.with_buttons ("Show",this,DialogFlags.MODAL, Stock.OK,ResponseType.OK,null); var content = dialog.get_content_area(); // warning: assignment from incompatible pointer type // [enabled by default] Label label = new Label(message); label.set_line_wrap(true); content.add(label); dialog.response.connect((id)=>{dialog.destroy();}); dialog.show_all(); } } public class DialogTest: Gtk.Application { internal DialogTest() { Object(application_id: "org.test.DialogTest"); } protected override void activate() { new DialogTestWindow(this).show(); } } extern void exit(int exit_code); public int main(string[] args) { return new DialogTest().run(args); } Answer: Use Gtk.Dialog.run, not Gtk.Widget.show_all. That will block the main loop until the dialog returns a result instead of displaying the two dialogs simultaneously.
fitting multivariate curve_fit in python Question: I'm trying to fit a simple function to two arrays of independent data in python. I understand that I need to bunch the data for my independent variables into one array, but something still seems to be wrong with the way I'm passing variables when I try to do the fit. (There are a couple previous posts related to this one, but they haven't been much help.) import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit def fitFunc(x_3d, a, b, c, d): return a + b*x_3d[0,:] + c*x_3d[1,:] + d*x_3d[0,:]*x_3d[1,:] x_3d = np.array([[1,2,3],[4,5,6]]) p0 = [5.11, 3.9, 5.3, 2] fitParams, fitCovariances = curve_fit(fitFunc, x_3d[:2,:], x_3d[2,:], p0) print ' fit coefficients:\n', fitParams The error I get reads, raise TypeError('Improper input: N=%s must not exceed M=%s' % (n, m)) TypeError: Improper input: N=4 must not exceed M=3 What is `M` the length of? Is `N` the length of `p0`? What am I doing wrong here? Answer: N and M are defined in [the help](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html) for the function. N is the number of data points and M is the number of parameters. Your error therefore basically means you need at least as many data points as you have parameters, which makes perfect sense. This code works for me: import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit def fitFunc(x, a, b, c, d): return a + b*x[0] + c*x[1] + d*x[0]*x[1] x_3d = np.array([[1,2,3,4,6],[4,5,6,7,8]]) p0 = [5.11, 3.9, 5.3, 2] fitParams, fitCovariances = curve_fit(fitFunc, x_3d, x_3d[1,:], p0) print ' fit coefficients:\n', fitParams I have included more data. I have also changed `fitFunc` to be written in a form that scans as only being a function of a single x - the fitter will handle calling this for all the data points. The code as you posted also referenced `x_3d[2,:]`, which was causing an error.
python list memory usage Question: I am trying to improve the memory usage of my script in python, therefore I need to know what's RAM usage of my list. I measure the memory usage with print str(sys.getsizeof(my_list)/1024/1024) which hopefully would give me the size of the list in RAM in Mb. it outputs 12 Mb, however in `top` command I see that my script uses 70% of RAM of 4G laptop when running. In addition this list should contain a content from file of ~500Mb. So 12Mb is unrealistic. How can I measure the real memory usage? Answer: `sys.getsizeof` only take account of the list itself, not items it contains. According to [`sys.getsizeof` documentation](http://docs.python.org/3/library/sys.html#sys.getsizeof): > ... Only the memory consumption directly attributed to the object is > accounted for, not the memory consumption of objects it refers to. ... Use [Pympler](https://pypi.python.org/pypi/Pympler/): >>> import sys >>> from pympler.asizeof import asizeof >>> >>> obj = [1, 2, (3, 4), 'text'] >>> sys.getsizeof(obj) 48 >>> asizeof(obj) 176
Adding elements to an JSON object in a external JSON file? Question: * * * (After months of surfing the internet, talking to the school's computing department and try code out, I still don't get how to do it, but I do know more specific about what I trying to do) * * * Previously I said I want to "Add lines" to a existing JSON file. What I want to do is simply add an element to an JSON object from a file, then save the file. However I am still confused about how to do it. The process I am guessing is to use ajax to load the content of the file (the JSON code in the file) into a variable then add the new element into the object then save the file. I have seen a lot of code but are all just too confusing and looks like its for webpages. I am trying to edit a file on the computer as a program which I think webpage related code such as xmlhttp requests are irrelevant as the file is in a folder in appdata. I have been confused and thought Java and Javascript were the same thing, I know now they're not. What code or functions would I look for and how would it be used in the code? (Please don't post pseudocode because I have no idea how to write the code for them since I have literally no idea how to code anything other than a html webpage and some php. Other coding language like Java, Javascript and Python I have little knowledge with but not enough to write a program alone.) Answer: I think it would be best to use code that somebody else has already written to manipulate the JSON. There are plenty of libraries for that, and the best would be the officially specified one, [JSON-P](https://jsonp.java.net). What you would do is this: 1. Go to <http://jsonp.java.net/> and download JSON-P. (You will have to examine the page carefully to find the link to "[JSON Processing RI jar](http://search.maven.org/remotecontent?filepath=org/glassfish/javax.json/1.0.4/javax.json-1.0.4.jar)".) You will need to include this JAR in your class path while you write your program. 2. Add imports to your program for `javax.json.*`. 3. Write this code to do the job (you will have to catch `JsonException`s and `IOException`s): JsonReader reader = Json.createReader(new FileReader("launcher_profiles.json")); JsonObject file = reader.readObject(); reader.close(); JsonObject profiles = file.getJsonObject("profiles"); JsonObject newProfile = Json.createObjectBuilder() .add("name", "New Lines") .add("gameDir", "New Lines") .add("lastVersionId", "New Lines") .add("playerUUID", "") .build(); JsonObjectBuilder objectBuilder = Json.createObjectBuilder() .add("New Profile Name", newProfile); for (java.util.Map.Entry<String, JsonValue> entry : profiles.entrySet()) objectBuilder.add(entry.getKey(), entry.getValue()); JsonObject newProfiles = objectBuilder.build(); // Now, figure out what I have done so far and write the rest of the code yourself! At the end, use this code to write out the new file: JsonWriter writer = Json.createWriter(new FileWriter("launcher_profiles.json")); writer.writeObject(newFile); writer.close();
How to import liblas module in Python? Question: I am using liblas for python to read .las file. When I enter: from liblas import file It gives me: > No module named liblas. I already set up las library path in system, `lasinfo` is working fine. Can anyone tell me how to import las library in Python? I am using Ubuntu by the way. Answer: It looks like the liblas is not properly installed or you configured the path incorrectly. Try installing the package **liblas** using pip or easy_install. $ easy_install liblas OR $ pip install liblas
iPython: 'no module named' ImportError Question: Windows: I have the Python package CVXOPT installed on my computer for the regular Python distribution, though not specifically with Anaconda, so it imports fine when I'm doing text editor/cmd python scripting. I tried installing CVXOPT with Anaconda, but that didn't work so I'm having to import the library directly when working with iPython. My directory structure looks like: C: --Python27 ----Lib ------site-packages --------cvxopt ----------__init__.py ----------..... The error occurs when I run this code in an iPython notebook: import sys sys.path.append('C:\Python27\Lib\site-packages\cvxopt') import cvxopt The error: ImportError: No module named cvxopt How can I fix this? Perhaps I'm appending the path incorrectly? Answer: You're defining a path a bit too deep in your file tree. You need to add to `sys.path` the folder just before your module: import sys sys.path.append('C:\Python27\Lib\site-packages') import cvxopt Here, `cvxopt` can be found in the `site-packages` folder. If you add the `cvxopt` folder in the sys path, it'll search a module of that name in the folder itself and will not checked the base folder.
Python regex on wikitext template Question: I'm trying to remove line breaks with Python from wikitext templates of the form: {{cite web |title=Testing |url=Testing |editor=Testing }} The following should be obtained with re.sub: {{cite web|title=Testing|url=Testing|editor=Testing}} I've been trying with Python regex for hours, yet haven't succeeded at it. For example I've tried: while(re.search(r'\{cite web(.*?)([\r\n]+)(.*?)\}\}')): textmodif=re.sub(r'\{cite web(.*?)([\r\n]+)(.*?)\}\}', r'{cite web\1\3}}', textmodif,re.DOTALL) But it doesn't work as expected (even without the while loop, it's not working for the first line break). I found this similar question but it didnt help: [Regex for MediaWiki wikitext templates](http://stackoverflow.com/questions/8982251/regex-for-mediawiki- wikitext-templates) . I'm quite new at Python so please don't be too hard on me :-) Thank you in advance. Answer: You need to switch on newline matching for `.`; it does _not_ match a newline otherwise: re.search(r'\{cite web(.*?)([\r\n]+)(.*?)\}\}', inputtext, flags=re.DOTALL) You have multiple newlines spread throughout the text you want to match, so matching just one set of consecutive newlines is not enough. From the [`re.DOTALL` documentation](http://docs.python.org/2/library/re.html#re.S): > Make the `'.'` special character match any character at all, including a > newline; without this flag, `'.'` will match anything _except_ a newline. You could use one `re.sub()` call to remove all newlines within the `cite` stanza in one go, without a loop: re.sub(r'\{cite web.*?[\r\n]+.*?\}\}', lambda m: re.sub('\s*[\r\n]\s*', '', m.group(0)), inputtext, flags=re.DOTALL) This uses a nested regular expression to remove all whitespace with at least one newline in it from the matched text. Demo: >>> import re >>> inputtext = '''\ ... {{cite web ... |title=Testing ... |url=Testing ... |editor=Testing ... }} ... ''' >>> re.search(r'\{cite web(.*?)([\r\n]+)(.*?)\}\}', inputtext, flags=re.DOTALL) <_sre.SRE_Match object at 0x10f335458> >>> re.sub(r'\{cite web.*?[\r\n]+.*?\}\}', lambda m: re.sub('\s*[\r\n]\s*', '', m.group(0)), inputtext, flags=re.DOTALL) '{{cite web|title=Testing|url=Testing|editor=Testing}}\n'
using html5lib with xml.etree.ElementTree Question: I need is a way to use the html5lib parser to generate a real xml.etree.ElementTree. (lxml is not an option for portability reasons.) `ELementTree.parse` [can take a parser](http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.parse) as an optional parameter xml.etree.ElementTree.parse(source, parser=None) but it's not clear what such a parser would look like. Is there a class or object within HTML5 I could use for the `parser` argument? Documentation for both libraries on this issue is thin. * * * **Context** : I have a malformed XHTML file that can't be parsed with `ElementTree.parse`: <?xml version="1.0" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Title</title></head> <body><div class="cls">Note that this br<br>is missing a closing slash</div></body> </html> So I used `html5lib.parse` instead with the default `treebuilder="etree"` parameter, which worked fine. But html5lib apparently does not output an `xml.etree.ElementTree` object, just one with a near-identical API. There are two problems with this: * html5lib's `find` does not support the [`namespaces` parameter](http://stackoverflow.com/a/14853417/1180926), making XPath excessively verbose without a clumsy [wrapper function](http://stackoverflow.com/a/1704596/1180926). * The Eclipse debugger does not support drill-through of html5lib etrees. So I cannot use either ElementTree or html5lib alone. Answer: Given `xml.etree.ElementTree` as `etree` (as it is commonly imported as): What's returned is not an `etree.ElementTree`, but rather an `etree.Element` (this is the same as what `etree.fromstring` returns; only `etree.parse` returns an `etree.ElementTree`). It is genuinely part of the etree module — it's not something with a similar API. The problem you've run into applies to `etree.fromstring` as much as it does html5lib. The Python [documentation for `xml.etree.ElementTree`](http://docs.python.org/2/library/xml.etree.elementtree.html) doesn't mention the `namespaces` argument — it seems to be an undocumented feature of `ElementTree` objects (but not `Element` objects). As such, it's probably not something that should really be relied on! Your best bet is likely going to be to use a wrapper function. The fact that Eclipse cannot go through the trees is down to the fact that html5lib defaults to `xml.etree.cElementTree` when it exists — which is meant to be identical, per the module's documentation, but is implemented in C using CPython's API, stopping Eclipse's debugger from functioning. You can get a treebuilder using the non-accelerated version (note from Python 3.3 _both_ are the C implementation — `cElementTree` merely survives as a deprecated alias) using the below: import xml.etree.ElementTree as etree import html5lib tb = html5lib.getTreeBuilder("etree", implementation=etree) p = html5lib.HTMLParser(tb) tree = p.parse("<html>")
Python - directed edge list to dictionary of dictionaries Question: I have a list of directed edges in a file in the form Source_Id Target_Id Edge_Type A B Train A C Bus B D Bus C A Train ... ... I would like to structure the data in a dictionary of dictionaries such as: {'A': {'B': 'Train', 'C': 'Bus'}, 'B': {'D': 'Bus'}, 'C': {'A': 'Train'}} What is the best way to do that? Answer: Use a [`collections.defaultdict()`](http://docs.python.org/2/library/collections.html#collections.defaultdict) object to materialize the values for you: from collections import defaultdict import csv graph = defaultdict(dict) with open('inputfile', 'rb') as infh: reader = csv.reader(infh, delimiter='\t') next(reader, None) # skip header for source, target, edge in reader: graph[source][target] = edge This assumes there is only one edge between each source and target, and that the inputfile is tab delimited. If there are multiple edges, build a list of edge names instead: graph = defaultdict(lambda: defaultdict(list)) with open('inputfile', 'rb') as infh: reader = csv.reader(infh, delimiter='\t') next(reader, None) # skip header for source, target, edge in reader: graph[source][target].append(edge) giving you {'A': {'C': ['Bus'], 'B': ['Train']}, 'C': {'A': ['Train']}, 'B': {'D': ['Bus']}} where the edge lists can then represent more edge names.
Getting URLError Exception when caching webdriver instances Question: I am attempting to cache webdriver instances across test case classes. I do not need a "clean" webdriver since I am simply using PhantomJS to query the DOM (I do need JavaScript enabled, which is why I am not simply fetching the source and parsing that). The cache is a dictionary with the URL as a key and the driver instance as value. The cache is in the base test case, and I call get() which is a method on the base test case. This method instantiates webdriver, and goes to the url if the driver is not in the cache already. It appears there's some kind of socket issue when trying to access driver properties on the cached instance in the second test case (derivedb.py). I'd appreciate if someone could tell how to get this work. I am getting the following output: $ python launcher.py test_a (deriveda.DerivedTestCaseA) ... Instantiate new driver Title is: Google ok test_b (deriveda.DerivedTestCaseA) ... Retrieve driver from cache Title is: Google ok test_a (derivedb.DerivedTestCaseB) ... Retrieve driver from cache ERROR ====================================================================== ERROR: test_a (derivedb.DerivedTestCaseB) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/cohenaa/PycharmProjects/sanity/derivedb.py", line 7, in test_a print "Title is: %s" % self.driver.title File "/Users/cohenaa/sanity-env/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 185, in title resp = self.execute(Command.GET_TITLE) File "/Users/cohenaa/sanity-env/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 162, in execute response = self.command_executor.execute(driver_command, params) File "/Users/cohenaa/sanity-env/lib/python2.7/site-packages/selenium/webdriver/remote/remote_connection.py", line 349, in execute return self._request(url, method=command_info[0], data=data) File "/Users/cohenaa/sanity-env/lib/python2.7/site-packages/selenium/webdriver/remote/remote_connection.py", line 410, in _request resp = opener.open(request) File "/sw/lib/python2.7/urllib2.py", line 404, in open response = self._open(req, data) File "/sw/lib/python2.7/urllib2.py", line 422, in _open '_open', req) File "/sw/lib/python2.7/urllib2.py", line 382, in _call_chain result = func(*args) File "/sw/lib/python2.7/urllib2.py", line 1214, in http_open return self.do_open(httplib.HTTPConnection, req) File "/sw/lib/python2.7/urllib2.py", line 1184, in do_open raise URLError(err) URLError: <urlopen error [Errno 61] Connection refused> ---------------------------------------------------------------------- Ran 3 tests in 1.271s FAILED (errors=1) **launcher.py** import unittest from deriveda import DerivedTestCaseA from derivedb import DerivedTestCaseB suite = unittest.TestSuite() testclasses = [DerivedTestCaseA, DerivedTestCaseB] testloader = unittest.TestLoader() classes_to_names = {} for tc in testclasses: classes_to_names[tc] = testloader.getTestCaseNames(tc) for tc in classes_to_names: for testname in classes_to_names[tc]: suite.addTest(tc(testname)) unittest.TextTestRunner(verbosity=10).run(suite) **deriveda.py** from basetestcase import BaseTestCase from unittest import main class DerivedTestCaseA(BaseTestCase): def test_a(self): self.get("http://www.google.com") print "Title is: %s" % self.driver.title def test_b(self): self.get("http://www.google.com") print "Title is: %s" % self.driver.title **derivedb.py** from basetestcase import BaseTestCase class DerivedTestCaseB(BaseTestCase): def test_a(self): self.get("http://www.google.com") print "Title is: %s" % self.driver.title **basetestcase.py:** import unittest from selenium import webdriver class BaseTestCase(unittest.TestCase): cache = {} def get(self, url): if url not in self.cache: print "Instantiate new driver" self.driver = webdriver.PhantomJS() self.driver.get(url) self.cache[url] = self.driver else: print "Retrieve driver from cache" self.driver = self.cache[url] @classmethod def tearDownClass(cls): for url in BaseTestCase.cache: BaseTestCase.cache[url].quit() Answer: Ahhh. I see now. The driver is quitting after each test case. If I quit after the suite is run instead, no error.
python - specifically handle file exists exception Question: I have come across examples in this forum where a specific error around files and directories is handled by testing the `errno` value in `OSError` (or `IOError` these days ?). For example, some discussion here - [Python's "open()" throws different errors for "file not found" \- how to handle both exceptions?](http://stackoverflow.com/questions/15032108/pythons-open-throws- different-errors-for-file-not-found-how-to-handle-b). But, I think, that is not the right way. After all, a `FileExistsError` exists specifically to avoid having to worry about `errno`. The following attempt didn't work as I get an error for the token `FileExistsError`. try: os.mkdir(folderPath) except FileExistsError: print 'Directory not created.' How do you check for this and similar other errors specifically ? Answer: According to the code `print ...`, it seems like you're using Python 2.x. [`FileExistsError`](http://docs.python.org/3/library/exceptions.html#FileExistsError) was added in Python 3.3; You can't use `FileExistsError`. Use [`errno.EEXIST`](http://docs.python.org/2/library/errno.html#errno.EEXIST): import os import errno try: os.mkdir(folderPath) except OSError as e: if e.errno == errno.EEXIST: print('Directory not created.') else: raise
Parse output of 'ip addr' via Python Question: I need some help parsing the output of the `ip addr` command as dumped to a text file, with contents like this: 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN \ link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 1: lo inet 127.0.0.1/8 scope host lo 1: lo inet6 ::1/128 scope host \ valid_lft forever preferred_lft forever 2: em1: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc mq master bond0 state UP qlen 1000\ link/ether b8:ca:3a:65:43:3c brd ff:ff:ff:ff:ff:ff 3: em2: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc mq master bond0 state UP qlen 1000\ link/ether b8:ca:3a:65:43:3c brd ff:ff:ff:ff:ff:ff 4: em3: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc mq master bond1 state UP qlen 1000\ link/ether b8:ca:3a:65:43:3e brd ff:ff:ff:ff:ff:ff 5: em4: <BROADCAST,MULTICAST,SLAVE,UP,LOWER_UP> mtu 1500 qdisc mq master bond1 state UP qlen 1000\ link/ether b8:ca:3a:65:43:3e brd ff:ff:ff:ff:ff:ff 6: p1p1: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN qlen 1000\ link/ether a0:36:9f:27:13:48 brd ff:ff:ff:ff:ff:ff 7: p1p2: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN qlen 1000\ link/ether a0:36:9f:27:13:49 brd ff:ff:ff:ff:ff:ff 8: p1p3: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN qlen 1000\ link/ether a0:36:9f:27:13:4a brd ff:ff:ff:ff:ff:ff 9: p1p4: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN qlen 1000\ link/ether a0:36:9f:27:13:4b brd ff:ff:ff:ff:ff:ff 10: bond0: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP \ link/ether b8:ca:3a:65:43:3c brd ff:ff:ff:ff:ff:ff 10: bond0 inet6 fe80::baca:3aff:fe65:433c/64 scope link \ valid_lft forever preferred_lft forever 12: bond1: <BROADCAST,MULTICAST,MASTER,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP \ link/ether b8:ca:3a:65:43:3e brd ff:ff:ff:ff:ff:ff 12: bond1 inet6 fe80::baca:3aff:fe65:433e/64 scope link \ valid_lft forever preferred_lft forever As you can see, there will be lines that start similarly (^\d: $device), and I'm at a loss of how to be able to iterate over the file, and pull out select information (ipv4 addr, ipv6 addr if present, link state, hw addr) for each device when this information is spread over multiple lines. Suggestions? Answer: from itertools import groupby interfaces = {} with open('ip.txt') as f: lines = [line for line in f if line.strip()] # group by line number for key, group in groupby(lines, lambda x: x.split()[0]): interface = [] for thing in group: # append lines without repeating part interface += thing.split()[2:] if interface: interfaces[key] = interface for key, interface in interfaces.items(): for x in ['inet', 'inet6', 'state', 'link/ether']: if x in interface: idx = interface.index(x) print '%s %s=%s' % (key, x, interface[idx+1]) $ python ip.py 3: state=UP 3: link/ether=b8:ca:3a:65:43:3c 4: state=UP 4: link/ether=b8:ca:3a:65:43:3e 5: state=UP 5: link/ether=b8:ca:3a:65:43:3e 1: inet=127.0.0.1/8 1: inet6=::1/128 1: state=UNKNOWN 10: inet6=fe80::baca:3aff:fe65:433c/64 10: state=UP 10: link/ether=b8:ca:3a:65:43:3c 2: state=UP 2: link/ether=b8:ca:3a:65:43:3c 8: state=DOWN 8: link/ether=a0:36:9f:27:13:4a 9: state=DOWN 9: link/ether=a0:36:9f:27:13:4b 12: inet6=fe80::baca:3aff:fe65:433e/64 12: state=UP 12: link/ether=b8:ca:3a:65:43:3e 6: state=DOWN 6: link/ether=a0:36:9f:27:13:48 7: state=DOWN 7: link/ether=a0:36:9f:27:13:49
Open a read-only Excel file using Python Question: I have a program (zTree) that is writing an Excel file and updating it constantly. What I need this Python program to do is read in the data from the Excel file as its updating. The problem that I'm having though is that when I try to read in the data using xlrd, I get the error: peek = f.read(peeksz) IO Error: [Errno 13] Permission denied which comes up because Excel is in read-only mode. Is there any way to read in the data of an Excel file in read-only mode using Python? Answer: just tested it on win 7 (64bit), but in this case it works: import xlrd workbook = xlrd.open_workbook('C:/User/myaccount/Book1.xls') worksheet = workbook.sheet_by_name('Sheet1') print worksheet could it be, that you are trying to copy it first, or that your python is trying to put a temporary copy of the file in the py-directoy? - because that would give the IO-Error
Python Updating RRDTool with Serial Port Data Question: I am trying to update a RRDTool DB with serial information. Is it possible to declare the serial data as a variable in the update line? Using the code below, rrdtool doesn't see the N: timestamp. However if I manually enter the data following the "N:" it will update. import serial import time import numpy import sys import rrdtool ser = serial.Serial('/dev/ttyUSB0', 9600) time.sleep(1) ser.flush() for i in range(2): ser.readline() while 1: # Read data temp = ser.readline() ret = rrdtool.update('temperature.rrd', 'N:', temp) if ret: print rrdtool.error() time.sleep(5) quit() Answer: I believe you want to do something like this: ret = rrdtool.update('temperature.rrd', 'N:%s' % temp) Each argument in an rrdtool wrapper function should correspond to an argument in the rrdtool cli command. So in your previous example when you were running rrdtool.update with 3 arguments you were actually running something like: rrdtool update temperature.rrd N: 65.6 the update should be a single argument, so this is really what you wanted: rrdtool update temperature.rrd N:65.6
Mod_wsgi fails to load django.core.handlers.wsgi Question: Ok, after 5-6 hours of trying, I give up. I have searched the web, tried all solutions suggested, but nothing is solving my problem. **Goal:** Set up Django on my Ubuntu 12.04 VPS. **Problem:** `Exception occurred processing WSGI script [...] ImportError: No module named django.core.handlers.wsgi` in /etc/log/apache2/error.log. **Solutions tried:** 1) Appending the site-packages directory to the sys path in Djangos' wsgi.py file, 2) re-installing mod_wsgi, 3) making sure mod_wsgi is compiled for the same Python version as Django is installed with, 4) chmod 777 for the site-packages directory. **Environment:** Ubuntu 12.04 VPS, Django installation in virtualenv, Python version 2.7.3, Django version 1.6.1, mod_wsgi built from [mod_wsgi-3.4.tar.gz](https://code.google.com/p/modwsgi/downloads/list). **Full error message:** mod_wsgi (pid=23691): Exception occurred processing WSGI script '/var/www/mySite/djangoSite/djangoSite/wsgi.py'. Traceback (most recent call last): File "/var/www/mySite/djangoSite/djangoSite/wsgi.py", line 7, in <module> import django.core.handlers.wsgi ImportError: No module named django.core.handlers.wsgi mod_wsgi (pid=23691): Target WSGI script '/var/www/mySite/djangoSite/djangoSite/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=23691): Exception occurred processing WSGI script '/var/www/mySite/djangoSite/djangoSite/wsgi.py'. Traceback (most recent call last): File "/var/www/mySite/djangoSite/djangoSite/wsgi.py", line 7, in <module> import django.core.handlers.wsgi ImportError: No module named django.core.handlers.wsgi **Conf file from sites-available:** <VirtualHost *:80> ServerAdmin [email protected] ServerName mysite.com DocumentRoot /var/www/mysite.com/djangoSite WSGIDaemonProcess djangoSite python-path=/var/www/mysite.com/djangoSite:~/Envs/myEnv/lib/python2.7/site-packages WSGIProcessGroup djangoSite WSGIScriptAlias / /var/www/mysite.com/djangoSite/djangoSite/wsgi.py Alias /static/ /var/www/mysite.com/djangoSite/static/ <Directory /var/www/mysite.com/djangoSite/static> Order deny,allow Allow from all </Directory> <Directory /var/www/mysite.com/djangoSite/djangoSite> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> </VirtualHost> **wsgi.py:** import os import sys sys.path.append('/var/www/mysite.com/djangoSite/') sys.path.append('/var/www/mysite.com/djangoSite/djangoSite/') activate_this = '/root/Envs/myenv/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) os.environ['DJANGO_SETTINGS_MODULE'] = 'djangoSite.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() **Site structure** /var/www/ -- mysite.com -- djangoSite -- manage.py -- djangoSite -- settings.py, wsgi.py etc. Answer: In your wsgi.py, try adding this to activate virtual env: import os import sys sys.path.append('/Path_To/Virtual_Env/Project_Dir/') #This is important if multiple apps are running (instead of setdefault) os.environ["DJANGO_SETTINGS_MODULE"] = "app_name.settings" activate_this = '/Path_To/Virtual_Env/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) In you apache config, you mainly need only(No Deamon Process required): WSGIScriptAlias / /var/www/mysite.com/djangoSite/djangoSite/wsgi.py Alias /static/ /var/www/mysite.com/djangoSite/static/ See from the **Create Virtual Host** section of [this link](http://thecodeship.com/deployment/deploy-django-apache-virtualenv-and- mod_wsgi/)
How to print a reStructuredText node tree? Question: Section [Parsing the Document](http://docutils.sourceforge.net/docs/dev/hacking.html#parsing-the- document) of The [Docutils Hacker's Guide](http://docutils.sourceforge.net/docs/dev/hacking.html) mentions the `quicktest.py` utility that can be used to print a node tree representation of a parsed [reStructuredText](http://docutils.sourceforge.net/rst.html) document. However I can't find `quicktest.py` anywhere in my docutils distribution installed in `/usr/lib/python2.7/dist-packages/docutils`. Is there other way to print the document tree? Answer: As pointed out by @mzjn the `quicktest.py` script is available at <https://sourceforge.net/p/docutils/code/HEAD/tree/trunk/docutils/tools/quicktest.py> A document tree can also be printed as follows: from docutils.core import publish_string print publish_string(rst) where `rst` is a string containing reStructuredText to be processed.
python ctype intialising a structure Question: My structure contains all unsigned char elements typedef struct { unsigned char bE; unsigned char cH; unsigned char cL; unsigned char EId1; unsigned char EId0; unsigned char SId1; unsigned char SId0; unsigned char DLC; unsigned char D0; unsigned char D1; unsigned char D2; unsigned char D3; unsigned char D4; unsigned char D5; unsigned char D6; unsigned char D7; } CMsg; The below function calls the structure extern int WriteCMessage(HANDLE hDev,CMsg* pMsg); I converted this structure to python ctype class CMsg(Structure): _fields_ = [('bE', c_char), ('cH', c_char), ('cL', c_char), ('EId1', c_char), ('EId0', c_char), ('SId1', c_char), ('SId0', c_char), ('DLC', c_char), ('D0', c_char), ('D1', c_char), ('D2', c_char), ('D3', c_char), ('D4', c_char), ('D5', c_char), ('D6', c_char), ('D7', c_char)] pmsg = CMsg('\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00','\x00') Then i loaded the dll file hllDll.WriteCANMessage(handle, pmsg) But this gives error Error: Access violation at 0x00000000 Answer: You passed `pmsg` by value, but the function expects a pointer. Since you've initialized to all zeros, the function ends up dereferencing a `NULL` pointer. Then ctypes uses Windows SEH to route the access violation to a Python exception. You need to use `byref(pmsg)` to pass a reference. Also, define the function's `argtypes` to ensure proper handling of the pointer on 64-bit systems. from ctypes import * from ctypes.wintypes import * class CMsg(Structure): _fields_ = [ ('bE', c_ubyte), ('cH', c_ubyte), ('cL', c_ubyte), ('EId1', c_ubyte), ('EId0', c_ubyte), ('SId1', c_ubyte), ('SId0', c_ubyte), ('DLC', c_ubyte), ('D0', c_ubyte), ('D1', c_ubyte), ('D2', c_ubyte), ('D3', c_ubyte), ('D4', c_ubyte), ('D5', c_ubyte), ('D6', c_ubyte), ('D7', c_ubyte)] hllDll = cdll... hllDll.WriteCANMessage.argtypes = [HANDLE, POINTER(CMsg)] handle = ... pmsg = CMsg() # initially memset to {0} hllDll.WriteCANMessage(handle, byref(pmsg))
Python Server Socket Without Infinite Loop? Question: I'd like to create a class that allows sending and receiving on the same port and create an event-driven application from incoming messages while the program does it operations. I don't have much experience with sockets so I don't know how to do this. Here is my SimpleSock class that so far just binds the socket. I also put an infinite loop in there to listen for connections but know this won't work for what I want because the program won't be able to do anything besides listen. import socket class SimpleSock: def __init__(self, ip=None, port=None): if ip == None or port == None: print("SimpleSock cannot init without an ip and port") else: self.ip = ip self.port = port self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("attempting connection to " + self.ip + " on port " + str(self.port)) self.socket.bind((self.ip, self.port)) self.socket.listen(5) print("connected") while True: (clientsocket, address) = self.socket.accept() #do something How can I write a listen without and infinite loop? Do I need to use threads? Answer: Event-driven network applications in Python can be built using frameworks like Python Twisted or Tornado. You can see a comparison in another question here: [When to use Tornado, when to use Twisted / Cyclone / GEvent / other](http://stackoverflow.com/questions/13941903/when-to-use-tornado-when- to-use-twisted-cyclone-gevent-other) The general idea is that the framework will let you register callbacks for when events happen like data waiting on a socket, and the framework will usually be your "main loop" (so it takes over control of the main thread typically). You do not need threads most of the time--everything can be multiplexed in a single thread so long as all your event sources are waitable using select() or similar.
How to concatenate and convert hex to base 64 in Python? Question: I'm trying to convert hex values into base 64. I have a script that does some calculations to each value. I then want to convert the final values to base 64. import base64 for i, v in enumerate([0x31, 0x37, 0x32, 0x2e]): z=i+v #adds positional index to hex value q=z+0x27 #adds constant x=q^i # XORs with positional index print (x) gives: > 88 > 94 > 89 > 91 I'm trying to convert these values into base 64. If I manually put them in this form: `585e595b`, this code is working: >>> "585e595b".decode('hex').encode('base64') 'WF5ZWw==\n' Answer: One way to do it: data = [0x31, 0x37, 0x32, 0x2e] encoded = base64.b64encode(''.join(hex(x)[2:] for x in data))
OpenCV Python unsupported array type error Question: I am new to Python (but not new to openCV) and I am pretty sure everything is installed correctly, I have tested some programs and the seem to work fine, but when ever I want to draw on an image, for example this code taken from a Python openCV tutorial : import numpy as np import cv2 # Create a black image img = np.zeros((512,512,3), np.uint8) # Draw a diagonal blue line with thickness of 5 px img = cv2.line(img,(0,0),(511,511),(255,0,0),5) cv2.imshow('img',img) cv2.waitKey(0) cv2.destroyAllWindows() I get this following error: OpenCV Error: Bad flag (parameter or structure field) (Unrecognized or unsupported array type) in cvGetMat, file /build/buildd/opencv-2.3.1/modules/core/src/array.cpp, line 2482 Traceback (most recent call last): File "/home/dccv/rec 2.py", line 17, in <module> cv2.imshow('img',img) cv2.error: /build/buildd/opencv-2.3.1/modules/core/src/array.cpp:2482: error: (-206) Unrecognized or unsupported array type in function cvGetMat any help would be appreciated, I get the same error on both windows and ubuntu. Answer: `line` function returns `None` so you're trying to show `None`. The fix (on line 6) is to not set the `img` variable to the return value, instead just ignore the return value: import numpy as np import cv2 # Create a black image img = np.zeros((512,512,3), np.uint8) # Draw a diagonal blue line with thickness of 5 px cv2.line(img,(0,0),(511,511),(255,0,0),5) cv2.imshow('img',img) cv2.waitKey(0) cv2.destroyAllWindows()
ctypes: Correctly sublcass c_void_p for passing and returning custom data types, by example Question: I am working with `ctypes` and cannot seem to figure out how to work with custom data types. The hope is to have a Python interface to the public methods of a C++ `cell` class and a C++ `cellComplex` class. My current problem is working with the C function called `get_elementsAtSpecifiedDim()`, defined below under `extern "C" {...`. This function has been written to return a `void *` which is _really_ a `std:vector< cell<double>* >`, a vector of pointers to C++ `cell` objects. My Client code below shows an example of a call to this function (via the Python `CellComplex` method `elemen()`) and this appears to me to be working fine. You will notice that my Python implementation of `elemen()` declares the return type `lib.elemen.restype` to be an array of (Python) `Cell` objects. That's what I get, `>>>print cmplx.elemen()` yields `[<cellComplex_python.Cell_Array_8 object at 0x10d5f59e0>, <cellComplex_python.Cell_Array_12 object at 0x10d5f5830>, <cellComplex_python.Cell_Array_6 object at 0x10d5f58c0>, <cellComplex_python.Cell_Array_1 object at 0x10d5f5950>]` **But here's the problem:** Now I want to call my C functions on one of the `Cell` objects in an array in this list. For example, `cmplx.elemen()[0][0]` is a `<Cell object at 0x10d5f5b00>`, so in my mind I should be able to do this: `cmplx.elemen()[0][0].dim()`, **but this segfaults**. My suspicion is that I am not creating the custom Python classes `Cell` and `CellComplex` correctly. In particular, in Python class `Cell`, method `dim(self):` I have the line `lib.dim.argtypes = [Cell]`, which must be absolutely bogus. As well, I have this silly Python class `c_cellComplex` which does nothing except allow me to indicate to myself what a particular `ctypes.c_void_p` is supposed to point to. In fact, I claim that my definitions of these Python classes are entirely bogus and I am being tricked into thinking I am on the right track by the miracle that this runs at all (up until I try to call a `Cell` method on a supposed `Cell` instance... Client code: p = [[0,1],[0,1]] cmplx = cellComplex(p) e = cmplx.elemen() e[0][0].dim() # segfault **begin EDIT** [eryksun's answer below](http://stackoverflow.com/a/20818377/390433) provides an example of how to subclass c_void_p, and addresses a few other conceptual issues - start there if you have the same questions I had. The segfault issue comes from the fact that `get_elementsAtSpecifiedDim()` defined in `extern C { ...` returns a memory address to a `std::vector<cell<double>* >`, a datatype that cannot be parsed back in Python. In this case I can just grab the pointers in the vector and return them, like so: extern "C" { void * get_elementAtSpecifiedDimAndLoc(void *ptr, int dim, int nr) { cellComplex<double>* cmplx = static_cast<cellComplex<double>* >(ptr); cell<double>* c = cmplx->elemen()[dim][nr]; return c; } } and can be called like so: def elemen(self): el = [] for i in range(self.dim): size = lib.size_elementsAtSpecifiedDim(self,i) cells = [] for j in range(size): cells.append(lib.get_elementAtSpecifiedDimAndLoc(self,i,j)) el.append(cells) return el # put this somewhere lib.get_elementAtSpecifiedDimAndLoc.restype = Cell lib.get_elementAtSpecifiedDimAndLoc.argtypes = [CellComplex,c_int,c_int] **The client code now works.** **end EDIT** Here is the magnificent folly: # cellComplex_python.py lib = ctypes.cdll.LoadLibrary('./cellComplex_lib.so') class c_cellComplex(ctypes.c_void_p): pass class Cell(ctypes.c_void_p): def dim(self): lib.dim.restype = ctypes.c_int lib.dim.argtypes = [Cell] self.dimension = lib.dim(self) return self.dimension class CellComplex(ctypes.c_void_p): def __init__(self,p): self.dimension = len(p) lib.new_cellComplex.restype = c_cellComplex lib.new_cellComplex.argtypes = [(ctypes.c_double*2)*self.dimension, ctypes.c_size_t] e = [(ctypes.c_double*2)(p[i][0],p[i][1]) for i in range(self.dimension)] point = ((ctypes.c_double*2)*self.dimension)(*e) self.cmplx = lib.new_cellComplex(point,self.dimension) def elemen(self): lib.size_elementsAtSpecifiedDim.restype = ctypes.c_int lib.size_elementsAtSpecifiedDim.argtypes = [c_cellComplex, ctypes.c_int] lib.get_elementsAtSpecifiedDim.argtypes = [c_cellComplex,ctypes.c_int] self.sizeAtDim = [] self.elements = [] for i in range(self.dimension+1): self.sizeAtDim.append(lib.size_elementsAtSpecifiedDim(self.cmplx,i)) lib.get_elementsAtSpecifiedDim.restype = Cell*self.sizeAtDim[i] self.elements.append(lib.get_elementsAtSpecifiedDim(self.cmplx,i)) return self.elements `C` code: // cellComplex_extern.cpp #include<"cell.hpp"> #include<"cellComplex.hpp"> extern "C" { void * new_cellComplex(double p[][2], size_t dim) { std::vector< std::pair<double,double> > point; for (size_t i=0; i<dim; ++i) { point.push_back( std::make_pair(p[i][0],p[i][1])); } cellComplex<double>* cmplx = new cellComplex<double>(point); return cmplx; } void * get_elementsAtSpecifiedDim(void *ptr, int dim) { cellComplex<double>* cmplx = static_cast<cellComplex<double>* >(ptr); std::vector<std::vector<cell<double>* > >* e = &cmplx->elemen(); return &e[dim]; } int size_elementsAtSpecifiedDim(void *ptr, int dim) { cellComplex<double>* cmplx = static_cast<cellComplex<double>* >(ptr); return cmplx->elemen()[dim].size(); } int dim(void *ptr) { cell<double>* ref = static_cast<cell<double>* >(ptr); return ref->dim(); } } Answer: Instead of subclassing `c_void_p`, you can define the class method `from_param` and instance attribute `_as_parameter_`. You may not need either option if you're just proxying a C++ object that's referenced in a private attribute such as `_obj`. That said, a subclass of `c_void_p` can be used directly with ctypes pointers, arrays, and structs, which may be convenient in your overall design. The following example may help: from ctypes import * __all__ = ['CellComplex'] class Cell(c_void_p): def __new__(cls, *args, **kwds): raise TypeError("cannot create %r instances" % cls.__name__) @property def dimension(self): return lib.dim(self) class CellComplex(c_void_p): def __init__(self, p): pair = c_double * 2 point = (pair * len(p))(*(pair(*q[:2]) for q in p)) self.value = lib.new_cellComplex(point, len(p)).value @property def dimension(self): """Wrap a function that returns size_t.""" return lib.????????(self) def get_elements(self): el = [] for i in range(self.dimension): size = lib.size_elementsAtSpecifiedDim(self, i) cells = lib.get_elementsAtSpecifiedDim(self, i) el.append(cells[:size]) return el Function pointer definitions: lib = CDLL('./cellComplex_lib.so') lib.dim.restype = c_int lib.dim.argtypes = [Cell] lib.new_cellComplex.restype = CellComplex lib.new_cellComplex.argtypes = [POINTER(c_double * 2), c_size_t] lib.size_elementsAtSpecifiedDim.restype = c_int lib.size_elementsAtSpecifiedDim.argtypes = [CellComplex, c_int] lib.get_elementsAtSpecifiedDim.restype = POINTER(Cell) lib.get_elementsAtSpecifiedDim.argtypes = [CellComplex, c_int] I separated out the function pointer definitions from the class method definitions. There's no need to redefine a function pointer's `restype` and `argtypes` every time a method is called. If the function returns a variably sized array, you're better off setting it to a pointer type. You can slice the result to a list or `cast` to an array type. `CellComplex` is initialized by a sequence `p` of floating point pairs such as `[[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]`. I eliminated the `c_cellComplex` class. You can just set the instance's `value`. `lib.new_cellComplex` returns an instance of `CellComplex`, but ctypes bypasses `__new__` and `__init__` when `CellComplex` is used as a `restype`, so that's not an issue. It would be less twisted to instead override `__new__`, but you'd still have to override `c_void_p.__init__`. The `dimension` attribute needs to be a property that calls an exported function, instead of relying on static data in the Python object.
How to properly parse parent/child XML with Python Question: I have a XML parsing issue that I have been working on for the last few days and I just can't figure it out. I've used both the ElementTree built-in to Python as well as the LXML libraries but get the same results. I would like to continue using ElementTree if I can, but if there are limitations to that library then LXML would do. Please see the following XML example. What I am trying to do is find a connection element and see what classes that element contains. I am expecting each connection to contain at least one class. If it doesn't have at least one class I want to know that it doesn't. The problem I am facing is that my code is returning ALL THE CLASSES in the document for each connection, instead of only the classes for that specific connection. <test> <connections> <connection> <id>10</id> <classes> <class> <classname>DVD</classname> </class> <class> <classname>DVD_TEST</classname> </class> </classes> </connection> <connection> <id>20</id> <classes> <class> <classname>TV</classname> </class> </classes> </connection> </connections> </test> For example, here is my Python code and the output that it returns: for parentConnection in elemetTree.getiterator('connection'): # print parentConnection.tag for childConnection in parentConnection: # print childConnection.text if childConnection.tag == 'id': connID = childConnection.text print connID for p in tree.xpath('./connections/connection/classes/class'): for attrib in p.attrib: print '@' + attrib + '=' + p.attrib[attrib] children = p.getchildren() for child in children: print child.text Here is the output: 10 DVD DVD_TEST TV 20 DVD DVD_TEST TV As you can see, I am printing out the text of the CONNECTION ID and then the text for each CLASSNAME. However, as you can see, they both contain the same text for CLASSNAME. The output should really look like this: 10 DVD DVD_TEST 20 TV Now as the above hand modified example shows each connection ID (Parent) has the appropriate classes/classnames (children). I just can't figure out how to make this work. If any of you have the knowledge to make this work, I would love to hear it. I've tried building a data structure and other examples on this forum but just can't get it to work right. Answer: My solution without using _xpath._ What I recommend is digging a little further into **lxml** documentation. There might be more elegant and direct ways to achieve this. There's a lot to explore!. **Solution:** from lxml import etree from io import BytesIO class FindClasses(object): @staticmethod def parse_xml(xml_string): parser = etree.XMLParser() fs = etree.parse(BytesIO(xml_string), parser) fstring = etree.tostring(fs, pretty_print=True) element = etree.fromstring(fstring) return element def find(self, xml_string): for parent in self.parse_xml(xml_string).getiterator('connection'): for child in parent: if child.tag == 'id': print child.text self.find_classes(child) @staticmethod def find_classes(child): for parent in child.getparent(): # traversing up -> connection for children in parent.getchildren(): # children of connection -> classes for child in children.getchildren(): # child of classes -> class print child.text print if __name__ == '__main__': xml_file = open('foo.xml', 'rb') #foo.xml or path to your xml file xml = xml_file.read() f = FindClasses() f.find(xml) **Output:** 10 DVD DVD_TEST 20 TV
Executing a shell script in Python from the JSON document Question: I am trying to execute the shell script in Python using subprocess module. Below is my shell script which is called as `testing.sh`. #!/bin/bash hello=$jj1 echo $hello echo $jj1 echo $jj2 for el1 in $jj3 do echo "$el1" done for el2 in $jj4 do echo "$el2" done Now I am trying to execute the above shell script in Python so I did like this - subprocess.call(['./testing.sh']) and it works fine. Now I am thinking to add the above script in a JSON document like this and then execute it - json_script = '{"script":"above testing.sh script here"}' j = json.loads(json_script) shell_script = j['script'] subprocess.call(shell_script, shell=True) But everytime I am trying, it is giving me an error - Below is my full Python script which contains the above `testing.sh` shell script in a JSON document - #!/usr/bin/python import subprocess import json import socket import os jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}' jj = json.loads(jsonData) print jj['pp'] print jj['sp'] os.putenv( 'jj1', 'Hello World 1') os.putenv( 'jj2', 'Hello World 2') os.putenv( 'jj3', ' '.join( str(v) for v in jj['pp'] ) ) os.putenv( 'jj4', ' '.join( str(v) for v in jj['sp'] ) ) print "start" jsonDataaa = '{"script":"#!/bin/bash \\n hello=$jj1 \\n echo $hello \\n echo $jj1 \\n echo $jj2 \\n for el1 in $jj3 \\n do \\n echo "$el1" \\n done \\n for el2 in $jj4 \\n do \\n echo "$el2" \\n done"}' j = json.loads(jsonDataaa) shell_script = j['script'] print "start" subprocess.call(shell_script, shell=True) print "end" And below is the error I am getting - File "C:\Python27\lib\json\__init__.py", line 338, in loads return _default_decoder.decode(s) File "C:\Python27\lib\json\decoder.py", line 365, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python27\lib\json\decoder.py", line 381, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting , delimiter: line 1 column 113 (char 112) And the expected output I should be getting like this - [0, 3, 5, 7, 9] [1, 2, 4, 6, 8] start Hello World 1 Hello World 2 0 3 5 7 9 1 2 4 6 8 end **UPDATE:-** If I have my jsonDataaa like this jsonDataaa = '{"script":"#!/bin/bash \\n hello=$jj1 \\n echo $hello \\n echo $jj1 \\n echo $jj2 \\n"}' then it works fine... And I am able to execute it properly.. But if my jsonDataaa is as I mentioned in my question, then only it gives me an error. I am thinking there might be some syntax error which I am not able to understand. Answer: It gives you this error because your json string is invalid. Specifically, it contains unescaped quotes. It works if you replace your jsonDataaa assignment with: jsonDataaa = '{"script":"#!/bin/bash \\n hello=$jj1 \\n echo $hello \\n echo $jj1 \\n echo $jj2 \\n for el1 in $jj3 \\n do \\n echo \\"$el1\\" \\n done \\n for el2 in $jj4 \\n do \\n echo \\"$el2\\" \\n done"}'
Calling variables from inside functions in Python Question: I know I have already asked a question like this before but I have made my code much cleaner and I am still coming up with a problem. My code goes like this: class Email_Stuff: def Get_From_Email(): #code to open up window and get email address emailaddr = #the input return emailaddr def Get_To_Email(): #code to open up window and get to email address recipaddr = #the input return recipaddr def Get_Email_Address(): #code to open up window and get email username EmailUser = #the input return EmailUser def Get_Email_Password(): #code to open up window and get email password EmailPass = #the input return EmailPass def Send_Email(): import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.login((EmailUser),(EmailPass)) message = "Python Test Email" server.sendmail(emailaddr,recipaddr,message) I need to get the variables: `emailaddr`, `recipaddr`, `EmailUser`, and `EmailPass` into the function `Send_Email`. I'm not sure how I could do that though because when I run this code, it tells me that "the global name isn't defined". Any ideas? Answer: Make emailaddr, recipaddr, EmailUser, and EmailPass become instance variables by adding prefix "self.". class Email_Stuff(): def Get_From_Email(self): #code to open up window and get email address self.emailaddr = #the input def Get_To_Email(self): #code to open up window and get to email address self.recipaddr = #the input def Get_Email_Address(self): #code to open up window and get email username self.EmailUser = #the input def Get_Email_Password(self): #code to open up window and get email password self.EmailPass = #the input def Send_Email(self): import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.login((self.EmailUser),(self.EmailPass)) message = "Python Test Email" server.sendmail(self.emailaddr,self.recipaddr,self.message) instance = Email_Stuff() instance.Get_From_Email() instance.Get_To_Email() instance.Get_Email_Address() instance.Get_Email_Password() instance.Send_Email() BTW, name of methods should be lowercase.
I want to download code from Google App Engine Question: I want to update the app in google app store. But I can't download the code... Is there any way to update the app without downloading the code? I tried to download with python, google app engine SDK... But appcfg.py download_app -A This command does not work giving this error NameError: global name 'execfile' is not defined... Can you help me with this? Answer: The error you have shown may occur due to incorrect PYTHONPATH environment variable. If you are using the Windows version of the GAE SDK, then do the following: 1) Go to Edit > Preferences 2) Correct your Python Path. To know the Python Path in windows do the following in the Python IDLE or Python CMD: import os import sys print os.path.dirname(sys.executable) For downloading your source code try this: download_app -A app_name -V version C:\path_to_project You may or may not need to escape the backslash. Replace app_name, version and C:\path_to_project with appropriate values To know the version go to the app engine admin website [appengine.appspot.com](http://appengine.appspot.com)
Placing the legend outside the plot Question: I want to position the legend outside the drawing box. I do not find a clean way to do this. The main problem is having everything fit on the file saved. The only thing I have been able to figure out is this code: #! /usr/bin/python import matplotlib # matplotlib.use('pdf') from matplotlib.pyplot import * subplot(111) plot([1,2,3], label="test1") l=legend(bbox_to_anchor=(1.05, 1), loc=2,borderaxespad=0) tight_layout(rect=(0,0,0.8,1)) savefig('test.pdf') There are a couple of caveats: 1. The tight_layout seems to be incompatible with `matplotlib.use('pdf')` 2. The 0.8 in the `tight_layout` has been found by trials and errors. If I replace `label="test"` by `label="this is a very very long test"`, the legend will once again get out of the border of the file. I would like that to be adjusted automatically. I have not been able to retrieve the size of the legend. `l.get_frame().get_width()` seems to always return 1.0. 3. The `tight_layout` changes the size of the plot. What I would like to achieve is: specify the size of the plot in cm (or in inches). Placing the legend outside the plot. Having a file with the correct size in order that everything fits in, including the legend; without having to resort to trial and errors. Answer: You can look at the answer to [this](http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out- of-the-plot) question by [Joe Kington](http://stackoverflow.com/users/325565/joe-kington). The answer describes most of the options you can play around with regarding placement of legends.
Best and/or fastest way to create lists in python Question: In python, as far as I know, there are at least 3 to 4 ways to create and initialize lists of a given size: **Simple loop with`append`:** my_list = [] for i in range(50): my_list.append(0) **Simple loop with`+=`:** my_list = [] for i in range(50): my_list += [0] **List comprehension:** my_list = [0 for i in range(50)] **List and integer multiplication:** my_list = [0] * 50 In these examples I don't think there would be any performance difference given that the lists have only 50 elements, but what if I need a list of a million elements? Would the use of `xrange` make any improvement? Which is the preferred/fastest way to create and initialize lists in python? Answer: Let's run some time tests* with [`timeit.timeit`](http://docs.python.org/2/library/timeit.html#timeit.timeit): >>> from timeit import timeit >>> >>> # Test 1 >>> test = """ ... my_list = [] ... for i in xrange(50): ... my_list.append(0) ... """ >>> timeit(test) 22.384258893239178 >>> >>> # Test 2 >>> test = """ ... my_list = [] ... for i in xrange(50): ... my_list += [0] ... """ >>> timeit(test) 34.494779364416445 >>> >>> # Test 3 >>> test = "my_list = [0 for i in xrange(50)]" >>> timeit(test) 9.490926919482774 >>> >>> # Test 4 >>> test = "my_list = [0] * 50" >>> timeit(test) 1.5340533503559755 >>> As you can see above, the last method is the fastest by far. * * * However, it should _only_ be used with immutable items (such as integers). This is because it will create a list with references to the same item. Below is a demonstration: >>> lst = [[]] * 3 >>> lst [[], [], []] >>> # The ids of the items in `lst` are the same >>> id(lst[0]) 28734408 >>> id(lst[1]) 28734408 >>> id(lst[2]) 28734408 >>> This behavior is very often undesirable and can lead to bugs in the code. If you have mutable items (such as lists), then you should use the still very fast list comprehension: >>> lst = [[] for _ in xrange(3)] >>> lst [[], [], []] >>> # The ids of the items in `lst` are different >>> id(lst[0]) 28796688 >>> id(lst[1]) 28796648 >>> id(lst[2]) 28736168 >>> * * * *Note: In all of the tests, I replaced `range` with `xrange`. Since the latter returns an iterator, it should always be faster than the former.
Python memory management for variables Question: I have a question regarding python memory management. I have the following code def operation(data): #some manipulations on data result=something.do(data) #some manipulations on result return result Now I am calling this function `operation` many times (probably like more than 200 times). Does python use a same memory for the `result` variable everytime I call `operation`? As in `C` we can use `Malloc` to allocate memory once and use to the same memory inorder to avoid fragmentation. Answer: The whole point of high-level languages like Python is that they free you from having to worry about memory management. If exact control over memory allocation is important to you, you should write C. If not, you can write Python. As most Python programmers will tell you from their experience, manual memory management isn't nearly as important as you think it is.
Relationship between (1) hash function, (2) length of signature and (3) jaccard similarity? Question: I am trying to understand/implement minHash based jaccard similarity in python. The main goal is use it in MapReduce. However I am not clear how the choice of hash function and length of signature affects error rate in computing jaccard similarity. From wikipedia, I found that in general length of signature (K) and error (e) associated with the computed jaccard similarity is k = O(1/e^2). I tried implementing minHash in python: import random import sys #ERROR_THRESHOLD = 0.05 #SIG_LENGTH = int(1/(ERROR_THRESHOLD**2)) _memomask = {} def hash_values(n, x): """Compute n different hash values""" values = [] for i in range(n): mask = _memomask.get(i) if mask is None: random.seed(i) mask = _memomask[i] = random.getrandbits(32) values.append((hash(str(x)) % mask)) return values def compare_signatures(x, y): """Compare MinHash Signatures""" size = len(x) if size != len(y): raise Exception("Different signature length") if size == 0: raise Exception("signature length is zero") counter = 0 for i in range(size): counter += int(x[i] == y[i]) return counter/float(size) items = [['A',3], ['A',6], ['A',9], ['B',2], ['B',4], ['B',6], ['B',8]] for SIG_LENGTH in [1, 10, 100, 400, 1000]: #Step 1: Compute Hash Signature for each token data = [] for item in items: values = hash_values(SIG_LENGTH, item[1]) key = item[0] data.append((key, values)) #Step 2: Group by Key and compute MinHash for each index signatures = {} for item in data: key = item[0] values = item[1] if key not in signatures: signatures[key] = [-1.0]*SIG_LENGTH cur_signature = signatures[key] signatures[key] = [(values[i] if cur_signature[i] == -1.0 else min(values[i], cur_signature[i])) for i in range(SIG_LENGTH)] #Step 3: Compute Probability of minHash signature to be same keys = signatures.keys() key_length = len(keys) print "Jaccard Similarity based on signature of length {0}".format(SIG_LENGTH) for i in range(key_length): x_key = keys[i] x_sig = signatures[x_key] for j in range(i+1,key_length): y_key = keys[j] y_sig = signatures[y_key] print "J({0},{1}) = {2}".format(x_key, y_key, compare_signatures(x_sig, y_sig)) In my test, I found that accuracy increases as the length of signature increases but then it starts decreasing (or remains stable) thereafter. I am wondering is it because of the choice of hash function. If yes, can someone please suggest a good hash function to use. I found some related post but still not clear: [How many hash functions are required in a minhash algorithm](http://stackoverflow.com/questions/19701052/how-many-hash- functions-are-required-in-a-minhash-algorithm/20820889#20820889) Answer: md5 and sha work pretty well: import random import hashlib import sys k = int(sys.argv[1]) salts = [random.getrandbits(32) for i in range(k)] def h(value, salt): m = hashlib.md5() #or hashlib.sha1() m.update(str(value)) m.update(str(salt)) return m.digest() def get_signatures(A): return [min([h(x, salt) for x in A]) for salt in salts] def compare_signatures(A, B): """Compare MinHash Signatures""" sigA = get_signatures(A) sigB = get_signatures(B) return sum(map(lambda x: int(sigA[x] == sigB[x]), range(k)))/float(k) A = [3,6,9] B = [2,4,6,8] print compare_signatures(A, B) and some tests: $ for((i=10;i<2000;i*=10)); do python minhash.py $i; done 0.2 0.14 0.163
why is the python GUI interface fleeting Question: #coding=utf-8 import wx class App(wx.App): def OnInit(self): frame=wx.Frame(parent=None,title='Bare') frame.Show() return Ture app=App() app.MainLoop() runs OK! but the GUI interface is fleeting, just leaving the CMD console in the screen. a newer for python ,why the outcome of the GUI interface fleeting? environment:Gvim+WIN7+PYTHON2.7 Answer: First, according to `help :!` command of `vim`: > `:!{cmd}` Execute {cmd} with **the shell**. `vim` cause the cmd shell to be executed. Second, according to [Using Python on Windows - Executing scripts](http://docs.python.org/2/using/windows.html#executing-scripts): > Python scripts (files with the extension .py) will be executed by > `python.exe by` default. **This executable opens a terminal, which stays > open even if the program uses a GUI.** If you do not want this to happen, > use the extension `.pyw` which will cause the script to be executed by > `pythonw.exe` by default (both executables are located in the top-level of > your Python installation directory). This suppresses the terminal window on > startup. So, if you want run the GUI program without cmd console, run the program outside the vim using `pythonw.exe`. For instance, save the file with `.pyw` extension, and double click the file.
Numbers without remainder python Question: I need to print out numbers between 1 and n(n is entered with keyboard) that do not divide by 2, 3 and 5. I need to use while or for loops and the remainder is gotten with %. I'm new here and I just don't understand the usage of %? I tried something like this: import math print("Hey. Enter a number.") entered_number = int(input()) for i in range(1, entered_number): if i%2 != 0: print("The number", i, "is ok.") else: pass if i%3 != 0: print("The number", i, "is ok.") else: pass if i%5 != 0: print("The number", i, "is ok.") help? Answer: You need to test for all 3 conditions in **one** statement, not in 3: for i in range(1, entered_number): if i % 2 != 0 and i % 3 != 0 and i % 5 != 0: print("The number", i, "is ok.") The `and` operators here make sure that _all three_ conditions are met before printing. You are testing each condition in isolation, which means that if the number is, say, 10, you are still printing `The number 10 is ok.` because it is not divisible by 3. For numbers that _are_ okay, you were printing `The number ... is ok.` 3 times, as your code tests that it is not divisible by 3 different numbers separately, printing each time.
global name 'GLib2Reactor' is not defined Question: I'm struggling to get some python code using the python-brisa framework to work, the code is not written by me but should be straight forward. from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() from brisa.core.threaded_call import run_async_function import xml.etree.ElementTree as ET from time import sleep import sys, os import sonos import knx Howewer after installing the frameworks I get Traceback (most recent call last): File "knxsonos.py", line 24, in <module> reactor = install_default_reactor() File "/usr/local/lib/python2.7/dist-packages/brisa/core/reactors/__init__.py", line 14, in install_default_reactor return GLib2Reactor() NameError: global name 'GLib2Reactor' is not defined I have been looking both stack overflow, and googling for days without finding a solution. Anyone??, help would be greatly appreciated... Answer: Here's some possibilities: * **GLib2Reactor doesn't return anything** \- Then your code is wrong * **GLib2Reactor is not declared** \- try this: `x = GLib2Reactor()` `return x` * **GLib2Reactor has to be imported** \- just import it **my best advice:** read the docs
Python: correct way to pass objects between modules Question: I am following the [Flask SQLalchemy Quickstart](http://pythonhosted.org/Flask-SQLAlchemy/quickstart.html) which has all of the code in a single file: Here is my initial **index.py** : from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) # [snip] - some classes related to SQLAlchemy are here if __name__ == '__main__': app.run(host='0.0.0.0') I want to split the code up a bit, so I created a separate file called **database.py** which will contain all of the database related code, and be imported as a module. I modified my **index.py** to look like this: from flask import Flask # Import my database module import database app = Flask(__name__) if __name__ == '__main__': app.run(host='0.0.0.0') And the file **database.py** : from flask.ext.sqlalchemy import SQLAlchemy app.config['SQLALCHEMY_DATABASE_URI]'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) # [snip] - some classes related to SQLAlchemy are here Obviously when I try to run this code I get the following error: File "database.py", line 5, in <module> app.config['SQLALCHEMY_DATABASE_URI]'] = 'sqlite:////tmp/test.db' NameError: name 'app' is not defined I can see that this is because the `app` object only exists within the parent module. I could put the following lines back into **index.py** : app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) But this creates a similar problem, whereby `db` is not available within the database.py file. What is the correct way to code this? Answer: Edited answer after comment: Simply use from index import app in database.py. Alternatively, with the import index statement, use `index.app` instead of `app` only. This should help you get out of python's import hell. Btw: Not sure which IDE you are using. I like pycharm a lot. Using it you can refactor code and issues such as above are prevented automagically.
Is there a way to have a python program run an action when it's about to crash? Question: I have a python script with a loop that crashes every so often with various exceptions, and needs to be restarted. Is there a way to run an action when this happens, so that I can be notified? Answer: You could install an exception hook, by assigning a custom function to the [`sys.excepthook` handler](http://docs.python.org/2/library/sys.html#sys.excepthook). The function is called whenever there is a _unhandled_ exception (so one that exits the interpreter). import sys def myexcepthook(type, value, tb): import traceback from email.mime.text import MIMEText from subprocess import Popen, PIPE tbtext = ''.join(traceback.format_exception(type, value, tb)) msg = MIMEText("There was a problem with your program:\n\n" + tbtext) msg["From"] = "[email protected]" msg["To"] = "[email protected]" msg["Subject"] = "Program exited with a traceback." p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE) p.communicate(msg.as_string()) sys.excepthook = myexcepthook This exception hook emails you the traceback whenever the program exits, provided you have a working `sendmail` command on your system.
Tkinter with Python 3.3 : Change colour of button on click Question: So I have been playing with tkinter to try add a gui to a lift simulator project I have written for university. It is not really needed, but I would like to add it. Here is the code that I currently have. import tkinter as tk class Application(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) master.title("Test") #Controls the window title. self.pack() self.createWidgets() def createWidgets(self): floors = [i for i in range(41)] buttons = [] xPos = 0 yPos = 0 for floor in floors: if(yPos == 5): xPos = xPos + 1 yPos = 0 if(xPos == 8): yPos = 2 self.button = tk.Button(self, width=3, text=floor, command = lambda f=floor: self.pressed(f)) self.button.grid(row=xPos, column =yPos) yPos = yPos +1 self.QUIT = tk.Button(self, text="QUIT", fg="red", command=root.destroy).grid(row = xPos, column = yPos) def pressed(self, index): print("number pressed", index) self.button.configure(bg = "red") root = tk.Tk() app = Application(master=root) app.mainloop() This is all fine and dandy other than when the button is pressed it prints out the correct number, but it changes the background of the last button (number 40) to red, not the one pressed. If you could let me know what needs correcting that would be great. Thanks Answer: `self.button` can only ever reference a single button, and it will always be whatever was assigned to it last. A simple solution is to store the button references in a dict, using `floor` as the key. Since you're passing that to the callback, you then have everything you need to reconfigure the button: def createWidgets(self): ... self.buttons = {} for floor in floors: ... self.buttons[floor] = tk.Button(...) ... def pressed(self, index): ... self.buttons[index].configure(bg="red")
Python PXSSH GUI spawn on login failure Question: I can't stop the GUI from spawning when a login failure occurs. simple example that fails and spawns a GUI. >>> import pxssh >>> >>> ssh = pxssh.pxssh() >>> ssh.force_password = True >>> ssh.login('127.0.0.1', 'root', 'falsePW') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/dist-packages/pxssh.py", line 226, in login raise ExceptionPxssh ('password refused') pxssh.ExceptionPxssh: password refused >>> I have tried disabling x11 forwarding in these files, nothing changed. `/etc/ssh/ssh_config` `/etc/ssh/sshd_config` I have also tried going into the pxssh module and where it sets the ssh options I set the flag `-x Disables X11 forwarding.` still no change. I am running cinnamon on Linux Mint, the pxssh docs said some x display managers will start up a GUI. To solve this is says to remove all ssh-agents, which I have also tried to no avail. Answer: After tampering with the `pxssh.py` module I found a solution thats very simple. inside the pxssh.py module: `sudo nano /usr/lib/python2.7/dist- packages/pxssh.py` Location Update: `sudo nano /usr/lib/python2.7/dist-packages/pexpect/pxssh.py` class pxssh(spawn) def _init__( parameters ) # change these variables to shown value self.force_password = True self.auto_prompt_reset = False # next under the login function def login( parameters ) # set the -x flag: disables x11 forwarding (removing GUI) ssh_options = '-q -x'