text
stringlengths
226
34.5k
Kivy Anchor and gridlayout centering Question: I am using anchor layout to hold widgets, my widget is a gridlayout, the issue is, I want a compact login display UI, however, I am getting 3 contorls near, and logout button at end, all are not together (should not have much spacing) and should be centered in Anchor Layout. I am getting it as which is not looking good: ![enter image description here](http://i.stack.imgur.com/LX7WT.png) Codes are as follows: **main**.py: from kivy.app import App from formcontrol import FormControl class MyApp(App): def build(self): self.title="sample App" self.formcontrol = FormControl() return self.formcontrol if __name__ == '__main__': MyApp().run() FormControl.py: from kivy.uix.boxlayout import BoxLayout from kivy.uix.anchorlayout import AnchorLayout from login.logincodes import LoginControl from login.logincodes import AfterLogin class FormControl(AnchorLayout): ''' classdocs ''' def __init__(self, **kwargs): ''' Constructor ''' super(FormControl,self).__init__(**kwargs) c= LoginControl() c.setparent(self) self.add_widget(c) def changewidget(self,to): if to == 'AfterLogin': self.clear_widgets() self.add_widget(AfterLogin()) logincodes.py: from kivy.uix.gridlayout import GridLayout class LoginControl(GridLayout): _parentwidget=None def __init__(self, **kwargs): super(LoginControl,self).__init__(**kwargs) self.userid.text='Welcome' def setparent(self,parent): self._parentwidget=parent def changewidget(self,to): self._parentwidget.changewidget(to) def login_pressed(self,button): print(button.text) print(self.userid.text) print(self.userpw.text) self.changewidget('AfterLogin') def close_pressed(self,button): print(button.text) exit() class AfterLogin(GridLayout): def __init__(self,**kwargs): super(AfterLogin,self).__init__(**kwargs) my.ky file: <LoginControl>: rows: 3 cols: 1 userid: userid userpw: userpw BoxLayout: size_hint_y: None height: '32dp' Label: text: 'User ID' TextInput: id: userid text: 'some password' BoxLayout: size_hint_y: None height: '32dp' Label: text: 'Password' TextInput: id: userpw password: True text: 'some password' Button: text: 'Login' on_press: root.login_pressed(self) size_hint_y: None height: '32dp' Button: text: 'Close' on_press: root.close_pressed(self) size_hint_y: None height: '32dp' <AfterLogin>: rows: 1 Label: text: 'Logged In' Please make me learn where I went wrong in configuring the UI and I dont want to use a float layout which is like using points to place widgets. I am new to both Python and Kivy. Your support and advices are valuable to me to improve, Answer: On your `GridLayout` you specify `rows` = 3 and `cols` = 1, which means the layout has space for 3 children. When it gets to laying out the Close button, all the rows and cols have been used up so the Close button goes to the default position `(0, 0)`. I would just specify `cols` and leave `rows` out - it will use as many rows as necessary to lay out the children. Second, this isn't a problem, but there's a quicker way to set all of the children's height to 32dp. Rather than specifying `size_hint` and `height` on all of the children, you can instead set `row_default_height` and `row_force_default` on the `GridLayout`. Finally, your `GridLayout` is still taking up all the space, which is why it's not centering in the `AnchorLayout`. This is easily solved with a `GridLayout` due to the `minimum_height` property - set `height` to `minimum_height` and `size_hint_y` to `None`, and it will center. Putting it all together: <LoginControl>: cols: 1 row_force_default: True row_default_height: '32dp' size_hint_y: None height: self.minimum_height ![centered GridLayout example](http://i.stack.imgur.com/qsBsW.png)
Minidom getElementById not working Question: Minidom's getElementById function is returning None for any entry I pass to it. For example, this code: l = minidom.parseString('<node id="node">Node</node>') print(l.getElementById("node")) Prints "None" on my computer. I must be doing something here wrong but I can't figure it out! I'm running Python 3.3.2 if that helps. Answer: If you want to get elements with name="node" l.getElementsByTagName("node") If you want to get elements with attribute having an attribute "id" with value "node", use [xpath](https://code.google.com/p/py-dom-xpath/): import xpath xpath.find("//*['id=node']",l) #search for all elements with an attribute id="node"
Python - Read TXT File lines --> Array Question: I need to open a text file with Python and read this Text file line by line to put it into an arrary. Later on I want to write every single content from that array into a database. This is my code so far: #!/usr/bin/python # -*- coding: utf8 -*- #importieren der Module import MySQLdb import sys import re # regex import codecs # utf8 support # Datei file einlesen names = [] fo = open("file.txt", "r") print "Name of file:", fo.name for line in fo: line = line.strip() fo.close() How can I do this ? What is the right command to insert the text lines into an array ? Answer: If I'm understanding you correctly, your text file looks something like this: E YD6567 E YD9876 E YD9867 etc... And you wish to remove the "E " and just store the "YD####" in a list. Your loop will look like this: for line in fo: names.append(line.replace('E ', '') The "append" function adds an item to a list. The "replace" function replaces whatever part of the string you specify with whatever else you specify (in this case, replacing "E " with nothing, effectively removing it from the string). If you would like to store the full line (including "E "), it's as simple as: for line in fo: names.append(line)
accurate image aspect ratio in python Question: I have the following code to get the aspect ratio of an image img0 = color.rgb2gray(io.imread("C:\\work\\TRAIN\\SET1\\bus.jpg")) img0 = resize(img0, (40, 116)) ar = 1.0 * (img0.shape[1]/img0.shape[0]) print "aspect ratio: " print ar The output is `2.0`. But that's not true. For an image with width 116 and height 40, the aspect ratio should be `116/40 = 2.9`. Where is my calculation going wrong? Answer: The problem in you case is that img0.shape[1] and img0.shape[0] are both integers. You have performed integer division, and then converted it to float. You could try: float(img0.shape[1]) / img0.shape[0] or 1.0 * img0.shape[1] / img0.shape[0] or, my recommended method, is to add as the first line of code in the file this import from __future__ import division This will make "/" always perform floating point calculation, to avoid such cases. If you want to specifically use integer division, use "//", as in 10 // 3
Py2neo Neo4j Batch submit error Question: I have a json file with data of around 1.4 million nodes and I wanted to construct a Neo4j graph database for that. I tried to use py2neo's batch submit function. My code is as follows: # the variable words is a list containing node names from py2neo import neo4j batch = neo4j.WriteBatch(graph_db) nodedict = {} # I decided to use a dictionary because I would be creating relationships # by referring to the dictionary entries later for i in words: nodedict[i] = batch.create({"name":i}) results = batch.submit() The error shown is as follows: Traceback (most recent call last): File "test.py", line 36, in <module> results = batch.submit() File "/usr/lib/python2.6/site-packages/py2neo/neo4j.py", line 2116, in submit for response in self._submit() File "/usr/lib/python2.6/site-packages/py2neo/neo4j.py", line 2085, in _submit for id_, request in enumerate(self.requests) File "/usr/lib/python2.6/site-packages/py2neo/rest.py", line 427, in _send return self._client().send(request) File "/usr/lib/python2.6/site-packages/py2neo/rest.py", line 364, in send return Response(request.graph_db, rs.status, request.uri, rs.getheader("Loc$ File "/usr/lib/python2.6/site-packages/py2neo/rest.py", line 278, in __init__ raise SystemError(body) SystemError: None Can anybody please tell me what exactly is happening here? Does it have anything to do with the fact that the batch query is pretty large? If so, what can be done? Thanks in advance! :) Answer: So here's what I figured out (Thanks to this question: [py2neo - Neo4j - System Error - Create Batch Nodes/Relationships](http://stackoverflow.com/questions/17902741/py2neo- neo4j-system-error-create-batch-nodes-relationships)): The py2neo batch submit function has it's own limitations in terms of queries that can be made. While, I wasn't able to get a exact amount on the upper limit, I tried to limit my number of queries per batch to 5000. So I decided to run the following piece of code: # the variable words is a list containing node names from py2neo import neo4j batch = neo4j.WriteBatch(graph_db) nodedict = {} # I decided to use a dictionary because I would be creating relationships # by referring to the dictionary entries later for index, i in enumerate(words): nodedict[i] = batch.create({"name":i}) if index%5000 == 0: batch.submit() batch = neo4j.WriteBatch(graph_db) # As stated by Nigel below, I'm creating a new batch batch.submit() #for the final batch This way, I sent batch requests (of size 5k queries) and was successfully able to get my entire graph created!
Split streaming message in multiple Dicts Question: I'm trying to use json to decode a streaming message but throws the following ValueError: File "/usr/lib/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 369, in decode raise ValueError(errmsg("Extra data", s, end, len(s))) ValueError: Extra data: line 2 column 1 - line 23571 column 1 (char 126 - 72358378) I searched in SO and the possible reason is my streaming message. If so, How can split my streaming message into multiple dicts in a pythonic way? some lines of my streaming message: {"delete":{"status":{"id":486174602859528192,"id_str":"486174602859528192","user_id":2455171405,"user_id_str":"2455171405"}}} {"delete":{"status":{"id":244223991382937601,"id_str":"244223991382937601","user_id":236405781,"user_id_str":"236405781"}}} {"delete":{"status":{"id":243934303371792384,"id_str":"243934303371792384","user_id":236405781,"user_id_str":"236405781"}}} {"delete":{"status":{"id":320790822129913856,"id_str":"320790822129913856","user_id":320634758,"user_id_str":"320634758"}}} {"delete":{"status":{"id":399494495630155776,"id_str":"399494495630155776","user_id":1227287820,"user_id_str":"1227287820"}}} {"delete":{"status":{"id":399528981206007808,"id_str":"399528981206007808","user_id":1227287820,"user_id_str":"1227287820"}}} {"created_at":"Wed Jul 09 12:16:27 +0000 2014","id":486846341600251904,"id_str":"486846341600251904","text":"#RT \u0430 \u0437\u043d\u0430\u0435\u0442\u0435 \u043f\u043e\u0447\u0435\u043c\u0443 \u044f \u043d\u0435 \u0431\u0443\u0434\u0443 \u043f\u043e\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0442\u044c \u0442\u0440\u0435\u043d\u0434 \u043e \u041d\u0438\u043a\u043e\u043b\u044c?","source":"\u003ca href=\"http:\/\/www.ckhi.com.ua\" rel=\"nofollow\"\u003e\"Original atok\"\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":2530930573,"id_str":"2530930573","name":"\u041b\u0435\u043f\u0430\u0448\u0438\u043da \u041f\u0435\u043b\u0430\u0433\u0435\u044f","screen_name":"miki4390","location":"\u0421\u0430\u043d\u043a\u0442-\u041f\u0435\u0442\u0435\u0440\u0431\u0443\u0440\u0433","url":"https:\/\/twitter.com\/miki4390","description":"\u042f-\u0442\u043e \u0442\u0435\u0440\u043f\u043b\u044e. \u041d\u043e \u0442\u044b-\u0442\u043e \u043f\u043e\u0436\u0430\u043b\u0435\u0435\u0448\u044c...","protected":false,"verified":false,"followers_count":0,"friends_count":0,"listed_count":0,"favourites_count":0,"statuses_count":11,"created_at":"Wed May 28 21:41:41 +0000 2014","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"0084B4","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/abs.twimg.com\/sticky\/default_profile_images\/default_profile_3_normal.png","profile_image_url_https":"https:\/\/abs.twimg.com\/sticky\/default_profile_images\/default_profile_3_normal.png","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/2530930573\/1404903710","default_profile":true,"default_profile_image":true,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[{"text":"RT","indices":[0,3]}],"trends":[],"urls":[],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"medium","lang":"ru"} {"delete":{"status":{"id":295365152621080577,"id_str":"295365152621080577","user_id":710752640,"user_id_str":"710752640"}}} Answer: Your JSON is in fact set of JSON lines. # Decoding JSON line by line Reading all the lines at once results in broken JSON data. Reading the lines one by one and decoding works well. With your json lines in file "jslines.json" following code: >>> import json >>> fname = "jslines.json" >>> f = open(fname) >>> for line in f: ... print json.loads(line) decodes and prints all the lines. # Building valid JSON array from lines Alternative approach is to use the lines to build valid JSON structure, in this case an array. We have to get list of the lines (as text), concatenate using ",", and enclose between "[" and "]"". >>> with open(fname) as f: ... lines = list(f) Now we have all the lines in a list `lines` Build the resulting JSON text: >>> jstext = "[" + ",".join(lines) + "]" And load it into dictionary: >>> json.loads(jstext) This works with the data you have provided.
Python Matplotlib animation frames are overlapping Question: I am working on my orbit program, and I have currently only animated the moon with a downward (-y) velocity of -1023. The animation works, but each frame stays on the figure when the next one comes on: ![enter image description here](http://i.stack.imgur.com/SknjS.png) Here is my code: import numpy as np import matplotlib.pyplot as plt import math import matplotlib.animation as animation er = 6378100*10#m #earth radius mr = 1737400*10#m #moon radius em = 5.97219*10**24#kg #earth mass mm = 7.34767309*10**22#kg #moon mass d = 384400000#m #distance earth-moon G = 6.67384*10**(-11) #gravity constant mv = -1023#m/s #Moon velocity nts = 10000 #no. time steps def circle(r, h, k, a): x = r*math.cos(a)+h y = r*math.sin(a)+k plt.scatter(x,y) def simData(): tmax = 10000*nts ts = 10000 x = 0.0 t = 0.0 while t < tmax: n = 0 for i in range(120): circle(mr, d, mv*t, n) n = n + math.pi/60 t = t + ts yield x, t def simPoints(simData): x, t = simData[0], simData[1] time_text.set_text(time_template%(t)) line.set_data(t, x) return line, time_text fig = plt.figure() ax = plt.axes(xlim=(-430000000, 430000000), ylim=(-430000000, 430000000)) line, = ax.plot([], [], 'bo', ms=10) time_template = 'Time = %.1f s' # prints running simulation time time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes) ani = animation.FuncAnimation(fig, simPoints, simData, blit=False,\ interval=10, repeat=True) plt.show() Answer: The answer is simple: `matplotlib` animation does not wipe the image between frames. The point is that you yourself have to change the properties of the objects on the screen. Now you instead plot a new image with some new objects when you do the `plt.scatter` in `circle`. I changed a few lines in your code to avoid adding new objects, see the comment lines marked with `####`. Now it should be a bit snappier. (Even though the Moon is escaping Earth's gravitational field. Pity.) import numpy as np import matplotlib.pyplot as plt import math import matplotlib.animation as animation er = 6378100*10#m #earth radius mr = 1737400*10#m #moon radius em = 5.97219*10**24#kg #earth mass mm = 7.34767309*10**22#kg #moon mass d = 384400000#m #distance earth-moon G = 6.67384*10**(-11) #gravity constant mv = -1023#m/s #Moon velocity nts = 10000 #no. time steps def circle(r, h, k, a): x = r*math.cos(a)+h y = r*math.sin(a)+k #### CHANGED moony.center = x,y def simData(): tmax = 10000*nts ts = 10000 x = 0.0 t = 0.0 while t < tmax: n = 0 for i in range(120): circle(mr, d, mv*t, n) n = n + math.pi/60 t = t + ts yield x, t def simPoints(simData): x, t = simData[0], simData[1] time_text.set_text(time_template%(t)) line.set_data(t, x) return line, time_text fig = plt.figure() ax = plt.axes(xlim=(-430000000, 430000000), ylim=(-430000000, 430000000)) #### CHANGED: a grey circle of moony dimensions to be moved around moony = plt.Circle((0,0), mr, facecolor=(.8,.8,.8)) ax.add_artist(moony) time_template = 'Time = %.1f s' # prints running simulation time time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes) ani = animation.FuncAnimation(fig, simPoints, simData, blit=False,\ interval=10, repeat=True) plt.show() Of course, you'll probably want to create a circle to illustrate Earth, as well. You do not need to have any `plt.plot` commands in the file if you just want to plot two objects.
Code to check if an object is a list of lists python Question: I was review how to check if something is a list of lists from here [List of Lists check](http://stackoverflow.com/questions/5251663/determine-if-a-list- contains-other-lists). But When I use the code, it appears to fail. It should not print 'asdf' in this case since `lst` is a list of strings. What am I doing wrong? ` lst = wikiinfo_df.Data.ix[2] print lst OUT: ['NYSE', ':&#160;', 'GS', '\n', 'Dow Jones Industrial Average Component', '\n', 'S&amp;P 500 Component'] if all(isinstance(i, list) for i in lst): print 'asdf' OUT: asdf UPDATE - output of print `__builtins__` and `dir(__builtins__)`, pandas versions, all module print numpy.core.fromnumeric numpy.core.fromnumeric pandas: 0.12.0 python: 2.7.5 |Anaconda 1.8.0 (x86_64)| (default, Oct 24 2013, 07:02:20) [GCC 4.0.1 (Apple Inc. build 5493)] {'bytearray': <type 'bytearray'>, 'IndexError': <type 'exceptions.IndexError'>, 'all': <built-in function all>, 'help': Type help() for interactive help, or help(object) for help about object., 'vars': <built-in function vars>, 'SyntaxError': <type 'exceptions.SyntaxError'>, '__IPYTHON__active': 'Deprecated, check for __IPYTHON__', 'unicode': <type 'unicode'>, 'UnicodeDecodeError': <type 'exceptions.UnicodeDecodeError'>, 'memoryview': <type 'memoryview'>, 'isinstance': <built-in function isinstance>, 'copyright': Copyright (c) 2001-2013 Python Software Foundation. All Rights Reserved. Copyright (c) 2000 BeOpen.com. All Rights Reserved. Copyright (c) 1995-2001 Corporation for National Research Initiatives. All Rights Reserved. Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. All Rights Reserved., 'NameError': <type 'exceptions.NameError'>, 'BytesWarning': <type 'exceptions.BytesWarning'>, 'dict': <type 'dict'>, 'input': <function <lambda> at 0x12c3adb90>, 'oct': <built-in function oct>, 'bin': <built-in function bin>, 'SystemExit': <type 'exceptions.SystemExit'>, 'StandardError': <type 'exceptions.StandardError'>, 'format': <built-in function format>, 'repr': <built-in function repr>, 'sorted': <built-in function sorted>, 'False': False, 'RuntimeWarning': <type 'exceptions.RuntimeWarning'>, 'list': <type 'list'>, 'iter': <built-in function iter>, 'reload': <built-in function reload>, 'Warning': <type 'exceptions.Warning'>, '__package__': None, 'round': <built-in function round>, 'dir': <built-in function dir>, 'cmp': <built-in function cmp>, 'set': <type 'set'>, 'bytes': <type 'str'>, 'reduce': <built-in function reduce>, 'intern': <built-in function intern>, 'issubclass': <built-in function issubclass>, 'Ellipsis': Ellipsis, 'EOFError': <type 'exceptions.EOFError'>, 'locals': <built-in function locals>, 'BufferError': <type 'exceptions.BufferError'>, 'slice': <type 'slice'>, 'FloatingPointError': <type 'exceptions.FloatingPointError'>, 'sum': <built-in function sum>, 'getattr': <built-in function getattr>, 'abs': <built-in function abs>, 'print': <built-in function print>, 'True': True, 'FutureWarning': <type 'exceptions.FutureWarning'>, 'ImportWarning': <type 'exceptions.ImportWarning'>, 'None': None, 'hash': <built-in function hash>, 'ReferenceError': <type 'exceptions.ReferenceError'>, 'len': <built-in function len>, 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands for supporting Python development. See www.python.org for more information., 'frozenset': <type 'frozenset'>, '__name__': '__builtin__', 'ord': <built-in function ord>, 'super': <type 'super'>, 'TypeError': <type 'exceptions.TypeError'>, 'license': Type license() to see the full license text, 'KeyboardInterrupt': <type 'exceptions.KeyboardInterrupt'>, 'UserWarning': <type 'exceptions.UserWarning'>, 'filter': <built-in function filter>, 'range': <built-in function range>, 'staticmethod': <type 'staticmethod'>, 'SystemError': <type 'exceptions.SystemError'>, 'BaseException': <type 'exceptions.BaseException'>, 'pow': <built-in function pow>, 'RuntimeError': <type 'exceptions.RuntimeError'>, 'float': <type 'float'>, 'MemoryError': <type 'exceptions.MemoryError'>, 'StopIteration': <type 'exceptions.StopIteration'>, 'globals': <built-in function globals>, 'divmod': <built-in function divmod>, 'enumerate': <type 'enumerate'>, 'apply': <built-in function apply>, 'LookupError': <type 'exceptions.LookupError'>, 'open': <built-in function open>, 'basestring': <type 'basestring'>, 'UnicodeError': <type 'exceptions.UnicodeError'>, 'zip': <built-in function zip>, 'hex': <built-in function hex>, 'long': <type 'long'>, 'next': <built-in function next>, 'ImportError': <type 'exceptions.ImportError'>, 'chr': <built-in function chr>, 'xrange': <type 'xrange'>, 'type': <type 'type'>, '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", 'Exception': <type 'exceptions.Exception'>, '__IPYTHON__': True, 'tuple': <type 'tuple'>, 'UnicodeTranslateError': <type 'exceptions.UnicodeTranslateError'>, 'reversed': <type 'reversed'>, 'UnicodeEncodeError': <type 'exceptions.UnicodeEncodeError'>, 'IOError': <type 'exceptions.IOError'>, 'hasattr': <built-in function hasattr>, 'delattr': <built-in function delattr>, 'setattr': <built-in function setattr>, 'raw_input': <function <lambda> at 0x12c3ad230>, 'SyntaxWarning': <type 'exceptions.SyntaxWarning'>, 'compile': <built-in function compile>, 'ArithmeticError': <type 'exceptions.ArithmeticError'>, 'str': <type 'str'>, 'property': <type 'property'>, 'dreload': <function reload at 0x1022b8c08>, 'GeneratorExit': <type 'exceptions.GeneratorExit'>, 'int': <type 'int'>, '__import__': <built-in function __import__>, 'KeyError': <type 'exceptions.KeyError'>, 'coerce': <built-in function coerce>, 'PendingDeprecationWarning': <type 'exceptions.PendingDeprecationWarning'>, 'file': <type 'file'>, 'EnvironmentError': <type 'exceptions.EnvironmentError'>, 'unichr': <built-in function unichr>, 'id': <built-in function id>, 'OSError': <type 'exceptions.OSError'>, 'DeprecationWarning': <type 'exceptions.DeprecationWarning'>, 'min': <built-in function min>, 'UnicodeWarning': <type 'exceptions.UnicodeWarning'>, 'execfile': <built-in function execfile>, 'any': <built-in function any>, 'complex': <type 'complex'>, 'bool': <type 'bool'>, 'get_ipython': <bound method ZMQInteractiveShell.get_ipython of <IPython.kernel.zmq.zmqshell.ZMQInteractiveShell object at 0x1022b9dd0>>, 'ValueError': <type 'exceptions.ValueError'>, 'NotImplemented': NotImplemented, 'map': <built-in function map>, 'buffer': <type 'buffer'>, 'max': <built-in function max>, 'object': <type 'object'>, 'TabError': <type 'exceptions.TabError'>, 'callable': <built-in function callable>, 'ZeroDivisionError': <type 'exceptions.ZeroDivisionError'>, 'eval': <built-in function eval>, '__debug__': True, 'IndentationError': <type 'exceptions.IndentationError'>, 'AssertionError': <type 'exceptions.AssertionError'>, 'classmethod': <type 'classmethod'>, 'UnboundLocalError': <type 'exceptions.UnboundLocalError'>, 'NotImplementedError': <type 'exceptions.NotImplementedError'>, 'AttributeError': <type 'exceptions.AttributeError'>, 'OverflowError': <type 'exceptions.OverflowError'>} ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues'] UPDATE to the concern that all or isinstance has been redefined. when I tab `all()` I get: all(a, axis=None, out=None, keepdims=False) Test whether all array elements along a given axis evaluate to True. It is weird that it prints 'asdf' in the second example in the screenshot ![enter image description here](http://i.stack.imgur.com/QOEKf.png) UPDATE to concern that each item in list is a list, even though it appears to be a strong: It's a bit difficult to reproduce the code for wikiinfo_df because it includes getting data off freebase. for i in test: print type(i) <type 'str'> <type 'str'> <type 'str'> <type 'str'> <type 'str'> <type 'str'> <type 'str'> Answer: In python 2.7 (assumed because of `print lst`) you should have result of [`help(all)`](https://docs.python.org/2/library/functions.html#all) like this: all(iterable) -> bool Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True. So you probably load some module or code that replaces it, try using: if __builtins__.all(isinstance(i, list) for i in lst): ...
pyjamas - pyjsbuild error due to DistributionNotFound Question: I am trying to build the HelloWorld example page from the Pyjamas example folder. However I am receiving this error when I run: `sudo pyjsbuild helloworld.py`. This error seems pretty universal to python as it seems to be related to the setup/configuration of my python environment. Any advice on where to look for the problem? Here is the error Traceback (most recent call last): File "/usr/local/bin/pyjsbuild", line 5, in <module> from pkg_resources import load_entry_point File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 2603, in <module> working_set.require(__requires__) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 666, in require needed = self.resolve(parse_requirements(requirements)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 565, in resolve raise DistributionNotFound(req) # XXX put more info here pkg_resources.DistributionNotFound: six Answer: After trying the various answers, it turns out `pip` was not properly installing the `six` package, whatever that is. So I ran `sudo easy_install pip (--upgrade)` to make sure the script configuration was right. It wrote some extra files so I assume that's why my next command `sudo pip install six` or `sudo pip install six --upgrade` worked. Now I ran into another error -_-, For anyone looking later: `Runtime Error: Top module not found 'hello world'` Edit: The top module error is coming from trying to build into the output folder that is not `pyjs/`. All I had to do was move the folder up to `pyjs/` folder in `sitepackages/`.
Python display specific values on x-axis using matplotlib Question: I'm querying data from a simple sqlite3 DB which is pulling a list of the number of connections per port observed on my system. I'm trying to graph this into a simple bar-chart using matplotlib. Thus far, I'm using the follow code: import matplotlib as mpl mpl.use('Agg') # force no x11 import matplotlib.pyplot as plt import sqlite3 con = sqlite3.connect('test.db') cur = con.cursor() cur.execute(''' SELECT dst_port, count(dst_port) as count from logs where dst_port != 0 group by dst_port order by count desc; ''' ) data = cur.fetchall() dst_ports, dst_port_count = zip(*data) #dst_ports = [22, 53223, 40959, 80, 3389, 23, 443, 35829, 8080, 4899, 21320, 445, 3128, 44783, 4491, 9981, 8001, 21, 1080, 8081, 3306, 8002, 8090] #dst_port_count = [5005, 145, 117, 41, 34, 21, 17, 16, 15, 11, 11, 8, 8, 8, 6, 6, 4, 3, 3, 3, 1, 1, 1] print dst_ports print dst_port_count fig = plt.figure() # aesthetics and data plt.grid() plt.bar(dst_ports, dst_port_count, align='center') #plt.xticks(dst_ports) # labels plt.title('Number of connections to port') plt.xlabel('Destination Port') plt.ylabel('Connection Attempts') # save figure fig.savefig('temp.png') When I run the above, the data is successful retrieved from the DB and a graph is generated. However, the graph isn't what I was expecting. For example, on the x-axis, it plots all values between 0 and 5005. I'm looking for it to display only the values in dst_ports. I've tried using xticks but this doesn't work either. I've included some sample data in the above code which I've commented out that may be useful. In addition, here is an example of the graph output from the above code: ![graph without xticks](http://i.stack.imgur.com/dyhvq.png) And also a grpah when using xticks: ![graph using xticks](http://i.stack.imgur.com/KXA9C.png) Answer: You need to create some xdata by `np.arange()`: import matplotlib as mpl import numpy as np import matplotlib.pyplot as plt dst_ports = [22, 53223, 40959, 80, 3389, 23, 443, 35829, 8080, 4899, 21320, 445, 3128, 44783, 4491, 9981, 8001, 21, 1080, 8081, 3306, 8002, 8090] dst_port_count = [5005, 145, 117, 41, 34, 21, 17, 16, 15, 11, 11, 8, 8, 8, 6, 6, 4, 3, 3, 3, 1, 1, 1] fig = plt.figure(figsize=(12, 4)) # aesthetics and data plt.grid() x = np.arange(1, len(dst_ports)+1) plt.bar(x, dst_port_count, align='center') plt.xticks(x, dst_ports, rotation=45) # labels plt.title('Number of connections to port') plt.xlabel('Destination Port') plt.ylabel('Connection Attempts') Here is the output: ![enter image description here](http://i.stack.imgur.com/DsVSS.png)
Curve fitting to a Planck's Curve Question: So I am aiming to fit my own data points to a blackbody curve, however am having difficulties. The outline of what I am doing is on <http://python4esac.github.io/fitting/example_blackbody.html> But they use random data, I am trying to use my own CSV data. This data is: Wavelength 0.7, 0.865, 1.24, 1.61, 3.7, 4.05, Radiance 0, 0.106718, 0.227031, 0.373527, 0.240927, 0.293215, Is there anyway to get Python to go into the file and use these two columns instead? Everything I have tried so far has failed. my code is as follows import csv with open('PythonCode1.csv', 'rb') as f: reader = csv.reader(f, delimiter=',') for row in reader: from scipy.optimize import curve_fit import pylab as plt from pylab import plotfile, show, gca fid=open('PythonCode1.csv','r') import numpy as np import matplotlib.cbook as cbook def blackbody_lam(lam, T): """ Blackbody as a function of wavelength (um) and temperature (K). """ from scipy.constants import h,k,c lam = 1e-6 * lam # convert to metres return 2*h*c**2 / (lam**5 * (np.exp(h*c / (lam*k*T)) - 1)) wa = np.linspace(0.1, 6, 100) # wavelengths in um T1 = 1000. T2 = 2500. y1 = blackbody_lam(wa, T1) y2 = blackbody_lam(wa, T2) ytot = y1 + y2 sigma = np.ones(len(wa)) * 1 * np.median(ytot) ydata = ytot + csv.row[1].randn(len(wa)) * sigma and returns %run "d:\temp\k1339544\tmpskczzu.py" --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) R:\Canpy103.001\Canopy32\App\appdata\canopy-1.0.3.1262.win-x86\lib\site- packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc) 174 else: 175 filename = fname --> 176 exec compile(scripttext, filename, 'exec') in glob, loc 177 else: 178 def execfile(fname, *where): d:\temp\k1339544\tmpskczzu.py in <module>() 27 28 sigma = np.ones(len(wa)) * 1 * np.median(ytot) ---> 29 ydata = ytot + csv.rows[1].randn(len(wa)) * sigma 30 31 # plot the input model and synthetic data AttributeError: 'module' object has no attribute 'rows' Answer: Instead of setting `wa` and `ydata` to artificial data, as was done in the example, you want to provide your own data. If you format your data as two columns: Wavelength,Radiance 0.7,0 0.865,0.106718 1.24,0.227031 1.61,0.373527 3.7,0.240927 4.05,0.293215 then you can ingest it with data = np.loadtxt("PythonCode1.csv", delimiter=",", skiprows=1) wa = data[:,0] ydata = data[:,1] This won't guarantee that the function can fit your data (it can't, the blackbody function lacks an adjustable scale parameter) or that the fit will converge, but this is the simplest way to get the data in.
Python looping through string and matching it with with wildcard pattern Question: string1="abc" string2="abdabcdfg" I want to find if string1 is substring of string2. However, there are wildcard characters like `"."` can be any letter, `y` can be `"a"` or `"d"`, `x` can be `"b"` or `"c"`. as a result, `".yx"` will be substring of `string2`. How can I code it using only one loop? I want to loop through string2 and make comparisons at each index. i tried dictionary but I wand to use loop my code: def wildcard(string,substring): sum="" table={'A': '.', 'C': '.', 'G': '.', 'T': '.','A': 'x', 'T': 'x', 'C': 'y', 'G': 'y'} for c in strand: if (c in table) and table[c] not in sum: sum+=table[c] elif c not in table: sum+=c if sum==substring: return True else: return False print wildcard("TTAGTTA","xyT.")#should be true Answer: I know you are specifically asking for a solution using a loop. However, I would suppose a different approach: You can easily translate your pattern to a [regular expression](https://docs.python.org/2/howto/regex.html). This is a similar language for string patterns, just much more powerful. You can then use the `re` module to check whether that regular expression (and thus your substring pattern) can be found in the string. def to_regex(pattern, table): # join substitutions from table, using c itself as default return ''.join(table.get(c, c) for c in pattern) import re symbols = {'.': '[a-z]', '#': '[ad]', '+': '[bc]'} print re.findall(to_regex('.+#', symbols), 'abdabcdfg') If you prefer a more "hands-on" solution, you can use this, using loops. def find_matches(pattern, table, string): for i in range(len(string) - len(pattern) + 1): # for each possible starting position, check the pattern for j, c in enumerate(pattern): if string[i+j] not in table.get(c, c): break # character does not match else: # loop completed without triggering the break yield string[i : i + len(pattern)] symbols = {'.': 'abcdefghijklmnopqrstuvwxyz', '#': 'ad', '+': 'bc'} print list(find_matches('.+#', symbols, 'abdabcdfg')) Output in both cases is `['abd', 'bcd']`, i.e. it can be found two times, using these substitutions.
i got invalid request response from google maps api in python when I copy the link to chrome it works fine Question: What can be the reson? { "html_attributions" : [], "results" : [], "status" : "INVALID_REQUEST" } in Chrome fine: { "html_attributions": [], "next_page_token": "CqQDkgEAAFOOGlx1ov_HPteOZTqmNHkYFmUDfDDmlQn0XpcBzeYWgCNmexMAOS1KRvaStWwFRvLDDKEUsGyFwguXrBHTuvdfmu4REV4VPH-ALqsxb7cl9wrRLhUQTyjnMilf68qgafL2Eb7GZ3OXH2s4vpsC2HRaclVPbp53kz1NZY7NeKDNPzUOW-tIHpw_X3U_2NhfUbDu-1gMFOOaMCOoaQt7FHW51ktIm4UFrn6OfytS_VdIp7RgOMp1HISIbx8GW2l1MKnUZaPEztlwJi3OvK9n4waWOvS7uUd_PPy1xPYJWv-yKtG3Ehok-LOjCv-jkB_Ki4uqjWCGW4kD5L_aKp2gjECT-ny-1aTpjtJc8a9p1Fhx_Wdbf2vee5hCZfbaSxseRgsHd0POFPaIFwIZYg6GJHHkbjW6gfbnI67oI9nC3dTH86gWzyFCsG_n0hyhCg-oHzO3mxlaDDxCM6xv1Nbp5AY4u03NGIpzTNoRekJ-EtA1d7cYu-yZ2XFzHXJGkxyWHobe_UdwLa6b4ZUQD8qCoKGQ429MxeY6x5R05AYg4Q1BEhA7UkpwystS_CoYKCCJXeoZGhRToQEqwA-RwiEMbAqwfN3n89aVZg", "results": [...], "status": "OK" } The code: # -*- coding: utf-8 -*- import urllib import json import csv import hashlib import time YOUR_API_KEY = "SECRET" def geocode(addr): url = ("http://maps.googleapis.com/maps/api/" "geocode/json?address=%s&sensor=false") % (urllib.quote(addr)) data = urllib.urlopen(url).read() info = json.loads(data).get("results")[0].get("geometry").get("location") return info def geocode2(r): info = [] url_base = ("https://maps.googleapis.com/maps/api/place/search/json?" "location=%s,%s&radius=500&types=food&sensor=false&" "key=%s&pagetoken=%s") % ( r['lat'], r['lng'], YOUR_API_KEY, '' ) data = urllib.urlopen(url_base).read() info.extend(json.loads(data).get("results")) token = json.loads(data).get("next_page_token") while token: time.sleep(5) new_url = url_base + token data = urllib.urlopen(new_url).read() token = json.loads(data).get("next_page_token") info.extend(json.loads(data).get("results")) print len(info) l = [] for i in info: t = (i["name"], i["vicinity"], i["geometry"]["location"]["lat"], i["geometry"]["location"]["lng"] ) l.append(t) return l for place in geocode2(geocode('Polska, Warszawa, Pl. Zawiszy 1')): print place The output: <https://gist.github.com/andilab/078ea76b1f4d70704b50> Answer: I guess it is much about time. I added time.sleep(5) in while loop where I try fetching new google places with next_page_token() and it works. The quota from docs confirms my guess. > The maximum number of results that can be returned is 60. **There is a short > delay between when a next_page_token is issued, and when it will become > valid.** From: [Google Places API Doc](https://developers.google.com/places/documentation/search) Worth mention, that anyway maximum number of places returned will be **60**!
Create square thumbnails with Python + MagickWand Question: How can I create square thumbnails with Python and Wand? I'm trying to make square thumbnails from source images of any size. It's important that the thumbnail have the same aspect ratio as the original, cropping is ok, and it should fill the sapce of the thumbnail. Answer: The following `crop_center()` function makes the given image square. from __future__ import division from wand.image import Image def crop_center(image): dst_landscape = 1 > image.width / image.height wh = image.width if dst_landscape else image.height image.crop( left=int((image.width - wh) / 2), top=int((image.height - wh) / 2), width=int(wh), height=int(wh) ) First you need to make the image square, and then you can [`resize()`](http://docs.wand- py.org/en/0.3.7/wand/image.html#wand.image.BaseImage.resize) the square smaller.
How to destroy a parent window when child window's red X is clicked in Tkinter 8.5 and Python 3.3 Question: Newbie question here. I would like for `secondWindow` to be destroyed in addition to `thirdWindow` when the red X is clicked in `thirdWindow`, just like what happens when you click `thirdButton` in `thirdWindow`. `firstWindow` should remain alive. Below is some example code: import tkinter from tkinter import ttk def secondWindow(): secondWindow = tkinter.Toplevel(firstWindow) secondFrame = ttk.Frame(secondWindow) secondFrame.pack() secondButton = ttk.Button(secondFrame, text="proceed to 3rd window",\ command=lambda: thirdWindow(secondWindow)) secondButton.pack() def thirdWindow(parent): thirdWindow = tkinter.Toplevel(parent) thirdFrame = ttk.Frame(thirdWindow) thirdFrame.pack() thirdButton = ttk.Button(thirdFrame, text="close 2nd and 3rd windows",\ command=lambda: destroy(thirdWindow, parent)) thirdButton.pack() def destroy(self, parent): self.destroy() parent.destroy() firstWindow = tkinter.Tk() firstFrame = ttk.Frame(firstWindow) firstFrame.pack() firstButton = ttk.Button(firstFrame, text="proceed to 2nd window",\ command=secondWindow) firstButton.pack() firstWindow.mainloop() Thanks in advance for any help you can provide! Answer: Use `parent` to run `parent` function or get variable from `parent` \- for example to get its `parent` or run function which close its parent. import tkinter from tkinter import ttk def secondWindow(parent): secondWindow = tkinter.Toplevel(parent) secondWindow.parent = parent # remember parent secondFrame = ttk.Frame(secondWindow) secondFrame.pack() secondButton = ttk.Button(secondFrame, text="proceed to 3rd window",\ command=lambda: thirdWindow(secondWindow)) secondButton.pack() def thirdWindow(parent): thirdWindow = tkinter.Toplevel(parent) thirdWindow.parent = parent # remember parent thirdFrame = ttk.Frame(thirdWindow) thirdFrame.pack() thirdButton = ttk.Button(thirdFrame, text="close 2nd and 3rd windows",\ command=lambda: destroy(thirdWindow)) thirdButton.pack() def destroy(self): self.parent.parent.destroy() # destroy grand-parent and all children are dead too. firstWindow = tkinter.Tk() firstFrame = ttk.Frame(firstWindow) firstFrame.pack() firstButton = ttk.Button(firstFrame, text="proceed to 2nd window",\ command=lambda:secondWindow(firstWindow)) firstButton.pack() firstWindow.mainloop()
Issue "removing" a block of lines from a .sql file Question: I'm working on a script that will remove a block of lines from a SQL dump (basically, cleanse any table we do not want to restore). I thought I had it working, but when trying to restore the resulting file to my database I realized that when the script rewrites to the file, it's missing more lines than it should, and the restore fails. Here's my paltry attempt at this: #!/usr/bin/python to_keep = [] to_remove = [] f = open("backuptest.sql","r") lines = f.readlines() f.close() ### Function to remove lines associated with a table block def remove_lines(table_name): for i in range(0, len(lines)): line = lines[i] if "structure" in line and table_name in line: for j in range(i, len(lines)): to_remove.append(lines[j]) if "UNLOCK TABLES;" in lines[j]: break if line not in to_remove: to_keep.append(line) f.write(line) print "Finding lines" f = open("backuptest.sql", "w") remove_lines("advanced_searches") f.close() f = open("backuptest.sql", "w") remove_lines("test_table2") f.close() f = open("backuptest.sql", "w") remove_lines("test_table3") f.close() And here's what one of the blocks of the sql file looks like, for reference: -- Table structure for table `advanced_searches` -- DROP TABLE IF EXISTS `advanced_searches`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `advanced_searches` ( `batch_size` int(11) NOT NULL DEFAULT '0' ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `advanced_searches` -- LOCK TABLES `advanced_searches` WRITE; /*!40000 ALTER TABLE `advanced_searches` DISABLE KEYS */; /*!40000 ALTER TABLE `advanced_searches` ENABLE KEYS */; UNLOCK TABLES; I start the script by matching against the first line in such a block (includes the word "structure" and the table name), then I'm attempting to iterate from that line through "UNLOCK TABLES;" What's happening instead is it's removing ALL instances of "UNLOCK TABLES;" in the script, even from blocks I do not want removed, and it's also removing the following line from each block as well " ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; " (The closing parentheses through the rest of that line). Thanks for any help. I'll keep plugging away at what I've missed. Answer: # Try `sqlparse` $ pip install sqlparse Quick test from tutorial: >>> import sqlparse >>> sql = "select * from foo; select * from bar;" >>> res = sqlparse.split(sql) >>> res [u'select * from foo;', u'select * from bar;'] Applying to your SQL script: >>> sql = """-- Table structure for table `advanced_searches` ... -- ... ... DROP TABLE IF EXISTS `advanced_searches`; ... /*!40101 SET @saved_cs_client = @@character_set_client */; ... /*!40101 SET character_set_client = utf8 */; ... CREATE TABLE `advanced_searches` ( ... `batch_size` int(11) NOT NULL DEFAULT '0' ... ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; ... /*!40101 SET character_set_client = @saved_cs_client */; ... ... -- ... -- Dumping data for table `advanced_searches` ... -- ... ... LOCK TABLES `advanced_searches` WRITE; ... /*!40000 ALTER TABLE `advanced_searches` DISABLE KEYS */; ... /*!40000 ALTER TABLE `advanced_searches` ENABLE KEYS */; ... UNLOCK TABLES;""" ... >>> res = sqlparse.split(sql) >>> res [u'-- Table structure for table `advanced_searches`\n--\n\nDROP TABLE IF EXISTS `advanced_searches`;', u'/*!40101 SET @saved_cs_client = @@character_set_client */;', u'/*!40101 SET character_set_client = utf8 */;', u"CREATE TABLE `advanced_searches` (\n `batch_size` int(11) NOT NULL DEFAULT '0'\n) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;", u'/*!40101 SET character_set_client = @saved_cs_client */;', u'--\n-- Dumping data for table `advanced_searches`\n--\n\nLOCK TABLES `advanced_searches` WRITE;', u'/*!40000 ALTER TABLE `advanced_searches` DISABLE KEYS */;', u'/*!40000 ALTER TABLE `advanced_searches` ENABLE KEYS */;', u'UNLOCK TABLES;'] This provides properly parsed script and last thing to do, is to filter it one by one, picking only those, which seem to be needed. This I leave to you.
How to do a loop inside of a loop in python Question: Currently I have a program which goes through a list of vector coordinates and performs a simple math function on the two vectors, but I want to make a loop inside of a loop to be able to have more control on what happens, this is my program so far: import operator import numpy as np b = 0 a = 1 for a in range(0,56): vector1 = (int(l[b][0]),int(l[b][1]),int(l[b][2])) vector2 = (int(l[a][0]),int(l[a][1]),int(l[a][2])) #print vector1 #print vector2 x = vector1 y = vector2 vector3 = list(np.array(x) - np.array(y)) #print vector3 dotProduct = reduce( operator.add, map( operator.mul, vector3, vector3)) print dotProduct a += 1 But what I want is that once a hits 56 and does its final run through, I want B to add 1 and a to reset back to zero, and redo the loop of operations until b goes up to 55. Desired output: example of coordiantes: Cu 46.7176 27.1121 27.1121 Cu 43.2505 36.0618 32.4879 Cu 43.3392 36.0964 28.9236 Cu 43.2509 37.8362 27.1091 Cu 34.4872 14.1794 16.5767 Cu 34.4103 16.0364 14.3521 Cu 32.7006 14.069 14.412 and I want the first coordinate to perform the dot product with everything under it, and go back and then start with the second coordinate and perform dot product with everything under it, and so on.. Answer: You can do a nested for loop. Below is what you want: for b in range(0, 56): for a in range(0, 57):
How to convert 4 byte IEEE (little endian) float binary representation to float Question: I am decoding a binary file, which has decimal numbers represented by four bytes, little endian. For example, `94 53 F0 40` represents 7.510202. Unfortunately, Python is giving me 7.51020240784. When I try to parse this data using `unpack("<f",sampledata)[0]` I don't get exact representations of the original, due to the way Python stores values (for more information, see <http://bugs.python.org/issue4114>). Unfortunately, I _do_ need to get the _exact_ same representation- regardless of discussions about the inaccuray of floats, because I need to write these values to a text file, with the same number of decimal places as they were initially written to the binary file with. I'd rather stick to Python if possible, but am happy to implement a solution in C if necessary. The reason I cannot simply truncate the return of the unpack function, is that I cannot guarantee how many decimal places the original float had, for example `0C 02 0F 41` represents 8.938 according to my hex editor, from the original binary file, which only has 3 decimal places. To be clear, I need to take four hex bytes as my input, and output either a text/ASCII or number representation of the IEEE 32-bit floating point number, that has the same number of decimal places as was intended by the creator of the file. The output I will use to create a CSV of the original binary data file, not for actually performing any calculations. Any suggestions? Example: from __future__ import print_function from struct import * print("Should print 7.510202") hexbytes = b"\x94\x53\xF0\x40" # 01101001 11001000 11110001 01000000 # should print 7.510202 print(unpack("<f",hexbytes)[0]) Answer: A 4-byte IEEE format floating point number holds approximately 7 digits. What you want to do is round the result of `unpack` to a total of 7 digits. From there the normal Python conversion from float to string will hide all the floating point nastiness from you. def magnitude(x): return 0 if x==0 else int(math.floor(math.log10(abs(x)))) + 1 def round_total_digits(x, digits=7): return round(x, digits - magnitude(x)) >>> round_total_digits(struct.unpack('<f', '\x94\x53\xF0\x40')[0]) 7.510202 >>> round_total_digits(struct.unpack('<f', '\x0C\x02\x0F\x41')[0]) 8.938 >>> x = struct.unpack('<f', struct.pack('<f', 12345.67))[0] >>> x 12345.669921875 >>> round_total_digits(x) 12345.67 Note that if your numbers did not originate from a direct conversion of a decimal number but were the result of a calculation, this could _reduce_ the total accuracy. But not by much.
Syntax Error using import ctypes Question: I'm new to python and have installed Python2.6 directory address of python is "C:\Python26" I tried to use import ctypes I'm getting below errors Traceback (most recent call last): File "C:\Python26\Lib\msdecmiolib\__init__.py", line 22, in <module> import ctypes File "C:\Python26\Lib\ctypes\__init__.py", line 25 5DEFAULT_MODE = RTLD_LOCAL ^ SyntaxError: invalid syntax. Answer: Something's wrong with your Python installation; that line in `ctypes/__init__.py` should simply read DEFAULT_MODE = RTLD_LOCAL It's hard to imagine how that could have happened other than accidentally -- maybe you opened the file to look at it and accidentally hit `5` before saving? Anyway, you can either fix it yourself and see what happens or if you'd prefer reinstall Python. (Possibly upgrading to at least 2.7 while you're at it, which would be a good idea unless there's some peculiar reason you can't, although that's up to you.)
Much more Efficient way to Parse and Process Large files with Json Objects Question: This is by far the craziest question I have asked on SO but I am going to give it a shot in the hope of getting some advice about whether or not I am leveraging the right tools and methods for processing large amounts of data efficiently. I'm not necessarily looking for help on optimizing my code unless there is something I am completely overlooking but essentially would just like to know if I should be going with a different framework all together instead of Python. I'm new enough to Python to not be completely sure if it is possible to process large amount of data and store into DB much more efficiently. Essentially the below implementation reads text files in a directory with each text file containing 50K lines of json objects that need to be parsed and read and then converted into a csv before loading into a database. I hate using list containers and I am hoping that there is something else I can research implementing in Python for doing this in a much much better way. My initial thoughts are that I should be researching using generators but not totally sure. The crazy concat part at the end is important because it converts a comma separated list into it's own rows. [Converting Column with string separated values into rows](http://stackoverflow.com/questions/24419551/converting-column-with- string-separated-values-into-rows) triggerZipFiles = glob.glob('*.zip') for triggerFiles in triggerZipFiles: with zipfile.ZipFile(triggerFiles, 'r') as myzip: for logfile in myzip.namelist(): datacc = [] zipcc = [] csvout = '{}_US.csv'.format(logfile[:-4]) f = myzip.open(logfile) contents = f.readlines() for line in contents: try: parsed = json.loads(line[:-2]) if "CC" in parsed['data']['weatherType'] and "US" in parsed['zipcodes']: datacc.append(parsed['data']) zipcc.append(parsed['zipcodes']) except: pass if len(datacc) > 0: df = pd.concat([pd.DataFrame(zipcc), pd.DataFrame(datacc)], axis=1) df = pd.concat((pd.Series((v, row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key'], row['key']), df.columns) for _, row in df.iterrows() for v in row['US']), axis=1).T df.to_csv(csvout, header=None, index=False) else: pass print datetime.now().strftime('%Y/%m/%d %H:%M:%S') + ": Finished: {}".format(logfile) Answer: Firstly, _lines_ isn't a particularly useful metric when it comes to json! Secondly, you've got the right idea: you definitely want to do this chunk- based (read/clean/dump each part separately). I recommend using pandas' `read_json` function, it's much more efficient at creating DataFrames (it doesn't create a temporary python dict), _see the[reading in json section of the docs](http://pandas.pydata.org/pandas- docs/dev/io.html#reading-json)._ * If there not _actually_ json, then doing string manipulation to make them json is usually your best bet.* * If you have "oddly-shaped" json, then you can either [`json_normalize`](http://pandas.pydata.org/pandas-docs/dev/io.html#normalization) when reading, or parse the columns which contain multiple columns after reading in the DataFrame (e.g. using a Series string method or apply). _*it's unclear what the actual format is, but often it doesn't take much to make them into**valid** json._ Python bonus tip: if you're more that a few indentation levels deep consider breaking it apart into more functions. (The obvious choice here is to have `f1(logfile)` and `f2(line)`, but using descriptive names...)
looking for example for QCompleter with segmented completion / tree models Question: The PySide docs include this section on [QCompleter with tree models](http://srinikom.github.io/pyside- docs/PySide/QtGui/QCompleter.html#pyside-qtgui-qcompleter-handling-tree- models): > PySide.QtGui.QCompleter can look for completions in tree models, assuming > that any item (or sub-item or sub-sub-item) can be unambiguously represented > as a string by specifying the path to the item. The completion is then > performed one level at a time. > > Let’s take the example of a user typing in a file system path. The model is > a (hierarchical) PySide.QtGui.QFileSystemModel . The completion occurs for > every element in the path. For example, if the current text is C:\Wind , > PySide.QtGui.QCompleter might suggest Windows to complete the current path > element. Similarly, if the current text is C:\Windows\Sy , > PySide.QtGui.QCompleter might suggest System . > > For this kind of completion to work, PySide.QtGui.QCompleter needs to be > able to split the path into a list of strings that are matched at each > level. For C:\Windows\Sy , it needs to be split as “C:”, “Windows” and “Sy”. > The default implementation of PySide.QtGui.QCompleter.splitPath() , splits > the PySide.QtGui.QCompleter.completionPrefix() using QDir.separator() if the > model is a PySide.QtGui.QFileSystemModel . > > To provide completions, PySide.QtGui.QCompleter needs to know the path from > an index. This is provided by PySide.QtGui.QCompleter.pathFromIndex() . The > default implementation of PySide.QtGui.QCompleter.pathFromIndex() , returns > the data for the edit role for list models and the absolute file path if the > mode is a PySide.QtGui.QFileSystemModel. But I can't seem to find an example showing how to do this. **Can anyone point me at an example I can use as a starting point?** (In my investigation it looks like maybe the hard part is the tree model rather than the QCompleter) It looks like you would need to provide these functions: * ability to split a string into segments (for the example given, `C:\Windows\Sy` to `['C:','Windows','Sy']` * the ability to specify the list of items that include the last segment (e.g. all the items included in `['C:','Windows']` I found an example for the basic functionality of QCompleter and have been able to tweak the basics fine (see below), I just don't know how to go about implementing a tree model type application. '''based on http://codeprogress.com/python/libraries/pyqt/showPyQTExample.php?index=403&key=QCompleterQLineEdit''' from PySide.QtGui import * from PySide.QtCore import * import sys def main(): app = QApplication(sys.argv) edit = QLineEdit() strList = ''' Germany;Russia;France; french fries;frizzy hair;fennel;fuzzball frayed;fickle;Frobozz;fear;framing;frames Franco-American;Frames;fancy;fire;frozen yogurt football;fnord;foul;fowl;foo;bar;baz;quux family;Fozzie Bear;flinch;fizzy;famous;fellow friend;fog;foil;far;flower;flour;Florida '''.replace('\n',';').split(";") strList.sort(key=lambda s: s.lower()) completer = QCompleter(strList,edit) completer.setCaseSensitivity(Qt.CaseInsensitive) edit.setWindowTitle("PySide QLineEdit Auto Complete") edit.setCompleter(completer) edit.show() sys.exit(app.exec_()) if __name__ == '__main__': main() Answer: I couldn't find a good example for what I wanted, but I figured out how to adapt the Qt TreeModel example to using a QCompleter: <https://gist.github.com/jason-s/9dcef741288b6509d362> ![enter image description here](http://i.stack.imgur.com/ZmPf7.png) The QCompleter is the easy part, you just have to tell it how to split a path into segments, and then how to get from a particular entry in the model back to a path: class MyCompleter(QtGui.QCompleter): def splitPath(self, path): return path.split('/') def pathFromIndex(self, index): result = [] while index.isValid(): result = [self.model().data(index, QtCore.Qt.DisplayRole)] + result index = index.parent() r = '/'.join(result) return r Aside from that, you have to configure the QCompleter properly, telling it how to get from a model item to a text string. Here I set it up to use the DisplayRole and to use column 0. edit = QtGui.QLineEdit() completer = MyCompleter(edit) completer.setModel(model) completer.setCompletionColumn(0) completer.setCompletionRole(QtCore.Qt.DisplayRole) completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
Numpy PIL Python : crop image on whitespace or crop text with histogram Thresholds Question: How would I go about finding the bounding box or window for the region of whitespace surrounding the numbers in the image below?: # Original image: ![enter image description here](http://i.stack.imgur.com/Aet62.png) Height: 762 pixels Width: 1014 pixels # Goal: Something like: `{x-bound:[x-upper,x-lower], y-bound:[y-upper,y-lower]}` so I can crop to the text and input into tesseract or some OCR. # Attempts: I had thought of slicing the image into hard coded chunk sizes and analysing at random, but i think it would be too slow. Example code using `pyplot` adapted from ([Using python and PIL how can I grab a block of text in an image?](http://stackoverflow.com/questions/9402765/using-python-and-pil-how- can-i-grab-a-block-of-text-in-an-image)): from PIL import Image import numpy as np import matplotlib.pyplot as plt im = Image.open('/home/jmunsch/Pictures/Aet62.png') p = np.array(im) p = p[:,:,0:3] p = 255 - p lx,ly,lz = p.shape plt.plot(p.sum(axis=1)) plt.plot(p.sum(axis=0)) #I was thinking something like this #The image is a 3-dimensional ndarray [[x],[y],[color?]] #Set each value below an axes mean to 0 [item = 0 for item in p[axis=0] if item < p.mean(axis=0)] # and then some type of enumerated groupby for each axes #finding the mean index for each groupby(0) on axes plt.plot(p[mean_index1:mean_index2,mean_index3:mean_index4]) Based on the graphs each of the valleys would indicate a place to bound. * The first graph shows where lines of text would be * The second graph shows where characters would be # Plot example `plt.plot(p.sum(axis=1))`: ![enter image description here](http://i.stack.imgur.com/sIFDT.png) # Plot example output `plt.plot(p.sum(axis=0))`: ![enter image description here](http://i.stack.imgur.com/ZViU1.png) Related posts/docs: * [Trim whitespace using PIL](http://stackoverflow.com/questions/10615901/trim-whitespace-using-pil) * [Using python and PIL how can I grab a block of text in an image?](http://stackoverflow.com/questions/9402765/using-python-and-pil-how-can-i-grab-a-block-of-text-in-an-image) * [Use Python / PIL or similar to shrink whitespace](http://stackoverflow.com/questions/9396312/use-python-pil-or-similar-to-shrink-whitespace/9398422#9398422) * [Crop the image using PIL in python](http://stackoverflow.com/questions/9983263/crop-the-image-using-pil-in-python) * [Rectangular bounding box around blobs in a monochrome image using python](http://stackoverflow.com/questions/9525313/rectangular-bounding-box-around-blobs-in-a-monochrome-image-using-python?rq=1) * [How can I improve my paw detection?](http://stackoverflow.com/questions/4087919/how-can-i-improve-my-paw-detection?lq=1) * <http://scipy-lectures.github.io/advanced/image_processing/> * <http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html> # update: solution by HYRY ![enter image description here](http://i.stack.imgur.com/uPeca.gif) Answer: I think you can use Morphology functions in `scipy.ndimage`, here is an example: import pylab as pl import numpy as np from scipy import ndimage img = pl.imread("Aet62.png")[:, :, 0].astype(np.uint8) img2 = ndimage.binary_erosion(img, iterations=40) img3 = ndimage.binary_dilation(img2, iterations=40) labels, n = ndimage.label(img3) counts = np.bincount(labels.ravel()) counts[0] = 0 img4 = labels==np.argmax(counts) img5 = ndimage.binary_fill_holes(img4) result = ~img & img5 result = ndimage.binary_erosion(result, iterations=3) result = ndimage.binary_dilation(result, iterations=3) pl.imshow(result, cmap="gray") the output is: ![enter image description here](http://i.stack.imgur.com/o1GKe.png)
Get new result in infinite loop with SqlAlchemy Question: I'm new to Python - coming from PHP - and have been bouncing back and forth between Python official documentation and SqlAlchemy (which I'm trying to use as easily as Laravel's DB class) I have this bit of code: from sqlalchemy import * engine = create_engine('mysql://root:[email protected]/db') db_connection = engine.connect() meta = MetaData() video_processing = Table('video_processing', meta, autoload=True, autoload_with=engine) while True: sleep(1) stmt = select([video_processing]).where(video_processing.c.finished_processing == 0).where(video_processing.c.in_progress == 0) result = db_connection.execute(stmt) rows = result.fetchall() print len(rows) stmt = None result = None rows = None When I execute my statement, I let it run and print out the number of rows that it fetches. While that's going, I go in and delete rows from my db. The problem is that even though I'm resetting pretty much everything I can think of that is related to the query, it's still printing out the same number of fetched rows in every iteration of my loop, even though I'm changing the underlying data. Any ideas? Answer: The tricky part is that the connection needs to be closed if using engine.connect() with db_connection.close() otherwise you might not see new data changes. I ended up bypassing the connection and executing my statement directly on the engine, which makes more sense logically anyways: result = engine.execute(stmt)
NoSuchElementException when trying to use Selenium Python Question: I keep getting a NoSuchElementException when trying to use Selenium to find an element in python. I'm waiting for the page to fully load, and I'm switching to the right frame (or at least I think so!). Here is the code: driver.get("https://www.arcgis.com/home/signin.html") driver.implicitly_wait(10) driver.switch_to_frame("oAuthFrame") elem = driver.find_element_by_name('username') elem1 = driver.find_element_by_name('password') Here is the webpage part I'm trying to access: <input id="user_username" class="textBox" type="text" name="username" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"> which is located inside <iframe dojoattachpoint="_iFrame" id="oAuthFrame" scrolling="no" style="display: block; border: 0px;" marginheight="0" marginwidth="0" frameborder="0" width="400" height="500"...> You can go see the source code for yourself at <https://www.arcgis.com/home/signin.html> Full error output: Traceback (most recent call last): File "C:\Python34\beginSample.py", line 12, in <module> elem = driver.find_element_by_name('username') File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", l ine 302, in find_element_by_name return self.find_element(by=By.NAME, value=name) File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", l ine 662, in find_element {'using': by, 'value': value})['value'] File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", l ine 173, in execute self.error_handler.check_response(response) File "C:\Python34\lib\site-packages\selenium\webdriver\remote\errorhandler.py" , line 164, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: 'no such element\n (Session info: chrome=35.0.1916.153)\n (Driver info: chromedriver=2.9.248315,pl atform=Windows NT 6.1 SP1 x86_64)' If someone could help me figure out what's wrong, I'd greatly appreciate it. **UPDATE** : I'm now using actions, and I've debugged to the point of no errors, but also its not typing anything. Here is the code: from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains actions = ActionChains(driver) actions.send_keys("sd") actions.send_keys(Keys.TAB) actions.send_keys("bg") actions.perform() Answer: Personally I try to stick with the xpath and utilize xquery functionality. You can still use the other attachments since they are usually "attributes" of the element, but it provides more flexibility for complex types contains searching. I am able to find the username/password fields with the below two attach xpaths. You shouldn't need to switch to the iframe first...although some of the direct calls like name seem to not function...the xpath version worked for me. element = driver.find_element_by_xpath("//input[@name='username']") element1 = driver.find_element_by_xpath("//input[@name='password']") **Update** : I was able to duplicate the issue... I'm not sure why the locators are not functioning for this specifically, but here is a work around that works. The default placement of the focus when the page is loaded is the username box. actions = selenium.webdriver.common.action_chains.ActionChains(driver) actions.SendKeys("sd").Perform() actions.SendKeys(selenium.webdriver.common.Keys.Tab).Perform() actions.SendKeys("bg").Perform() <http://selenium.googlecode.com/git/docs/api/py/webdriver/selenium.webdriver.common.action_chains.html> I'll update again if I can figure out a way to directly connect to the fields. **Update:** With Chrome if you grab the specific iFrame you will see an error that says your browser does not support this iFrame. I believe the communication breakdown might be in the browser not being able to read it correctly...even though it seems to render it and allow functionality correctly. Since Selenium is based on the DOM selection it would be attempting to utilize similar behaviors to find this. I would recommend trying a `driver.execute_script("script goes here")` and trying to locate it purely with javascript and see if that would work. You would of course then have to continue using javascript and modify the control attributes/properties directly with javascript and then execute a javascript submit event for the button.
Async like pattern in pyqt? Or cleaner background call pattern? Question: I'm trying to write a short(one file pyqt) program which is responsive(so dependencies outside python/lxml/qt, especially ones I can't just stick in the file have some downsides for this use case but I might still be willing to try them). I'm trying to perform possibly lengthy(and cancelable) operations on a worker thread(actually the background operation has a lock around it to prevent multiple operations at once(since the library it uses can only be used one call at a time) and timeouts so spawning multiple threads would be fine also). As far as I can figure out the "basic" way to do this with qt is. (note code is not tested so it may be wrong) class MainWindow(QWidget): #self.worker moved to background thread def initUI(self): ... self.cmd_button.clicked.connect(self.send) ... @pyqtslot() def send(self): ... ...#get cmd from gui QtCore.QTimer.singleShot(0, lambda : self.worker(cmd)) @pyqtslot(str) def end_send(self, result): ... ...# set some gui to display result ... class WorkerObject(QObject): def send_cmd(self, cmd): ... get result of cmd QtCore.QTimer.singleShot(0, lambda: self.main_window.end_send()) (Am I using QTimer right(it runs on different thread right)?) I'd really prefer to have something simpler and more abstracted along the lines of c#'s async. (note I haven't used asyncio so I might be getting some things wrong) class MainWindow(QWidget): ... @asyncio.coroutine def send(self): ... ...#get cmd from gui result = yield from self.worker(cmd) #set gui textbox to result class WorkerObject(QObject): @asyncio.coroutine def send_cmd(self, cmd): ... get result of cmd yield from loop.run_in_executor(None, self.model.send_command, cmd) I heard that python 3 had similar features and there was a back port but does it work properly with qt? If anyone knows of another saner pattern. that too would be useful/an acceptable answer. Answer: The short answer to your question ("is there a way to use an `asyncio`-like pattern in PyQt?") is yes, but it's pretty complicated and arguably not worth it for a small program. Here's some prototype code that allows you to use an asynchronous pattern like you described: import types import weakref from functools import partial from PyQt4 import QtGui from PyQt4 import QtCore from PyQt4.QtCore import QThread, QTimer ## The following code is borrowed from here: # http://stackoverflow.com/questions/24689800/async-like-pattern-in-pyqt-or-cleaner-background-call-pattern # It provides a child->parent thread-communication mechanism. class ref(object): """ A weak method implementation """ def __init__(self, method): try: if method.im_self is not None: # bound method self._obj = weakref.ref(method.im_self) else: # unbound method self._obj = None self._func = method.im_func self._class = method.im_class except AttributeError: # not a method self._obj = None self._func = method self._class = None def __call__(self): """ Return a new bound-method like the original, or the original function if refers just to a function or unbound method. Returns None if the original object doesn't exist """ if self.is_dead(): return None if self._obj is not None: # we have an instance: return a bound method return types.MethodType(self._func, self._obj(), self._class) else: # we don't have an instance: return just the function return self._func def is_dead(self): """ Returns True if the referenced callable was a bound method and the instance no longer exists. Otherwise, return False. """ return self._obj is not None and self._obj() is None def __eq__(self, other): try: return type(self) is type(other) and self() == other() except: return False def __ne__(self, other): return not self == other class proxy(ref): """ Exactly like ref, but calling it will cause the referent method to be called with the same arguments. If the referent's object no longer lives, ReferenceError is raised. If quiet is True, then a ReferenceError is not raise and the callback silently fails if it is no longer valid. """ def __init__(self, method, quiet=False): super(proxy, self).__init__(method) self._quiet = quiet def __call__(self, *args, **kwargs): func = ref.__call__(self) if func is None: if self._quiet: return else: raise ReferenceError('object is dead') else: return func(*args, **kwargs) def __eq__(self, other): try: func1 = ref.__call__(self) func2 = ref.__call__(other) return type(self) == type(other) and func1 == func2 except: return False class CallbackEvent(QtCore.QEvent): """ A custom QEvent that contains a callback reference Also provides class methods for conveniently executing arbitrary callback, to be dispatched to the event loop. """ EVENT_TYPE = QtCore.QEvent.Type(QtCore.QEvent.registerEventType()) def __init__(self, func, *args, **kwargs): super(CallbackEvent, self).__init__(self.EVENT_TYPE) self.func = func self.args = args self.kwargs = kwargs def callback(self): """ Convenience method to run the callable. Equivalent to: self.func(*self.args, **self.kwargs) """ self.func(*self.args, **self.kwargs) @classmethod def post_to(cls, receiver, func, *args, **kwargs): """ Post a callable to be delivered to a specific receiver as a CallbackEvent. It is the responsibility of this receiver to handle the event and choose to call the callback. """ # We can create a weak proxy reference to the # callback so that if the object associated with # a bound method is deleted, it won't call a dead method if not isinstance(func, proxy): reference = proxy(func, quiet=True) else: reference = func event = cls(reference, *args, **kwargs) # post the event to the given receiver QtGui.QApplication.postEvent(receiver, event) ## End borrowed code ## Begin Coroutine-framework code class AsyncTask(QtCore.QObject): """ Object used to manage asynchronous tasks. This object should wrap any function that you want to call asynchronously. It will launch the function in a new thread, and register a listener so that `on_finished` is called when the thread is complete. """ def __init__(self, func, *args, **kwargs): super(AsyncTask, self).__init__() self.result = None # Used for the result of the thread. self.func = func self.args = args self.kwargs = kwargs self.finished = False self.finished_cb_ran = False self.finished_callback = None self.objThread = RunThreadCallback(self, self.func, self.on_finished, *self.args, **self.kwargs) self.objThread.start() def customEvent(self, event): event.callback() def on_finished(self, result): """ Called when the threaded operation is complete. Saves the result of the thread, and executes finished_callback with the result if one exists. Also closes/cleans up the thread. """ self.finished = True self.result = result if self.finished_callback: self.finished_ran = True func = partial(self.finished_callback, result) QTimer.singleShot(0, func) self.objThread.quit() self.objThread.wait() class RunThreadCallback(QtCore.QThread): """ Runs a function in a thread, and alerts the parent when done. Uses a custom QEvent to alert the main thread of completion. """ def __init__(self, parent, func, on_finish, *args, **kwargs): super(RunThreadCallback, self).__init__(parent) self.on_finished = on_finish self.func = func self.args = args self.kwargs = kwargs def run(self): try: result = self.func(*self.args, **self.kwargs) except Exception as e: print "e is %s" % e result = e finally: CallbackEvent.post_to(self.parent(), self.on_finished, result) def coroutine(func): """ Coroutine decorator, meant for use with AsyncTask. This decorator must be used on any function that uses the `yield AsyncTask(...)` pattern. It shouldn't be used in any other case. The decorator will yield AsyncTask objects from the decorated generator function, and register itself to be called when the task is complete. It will also excplicitly call itself if the task is already complete when it yields it. """ def wrapper(*args, **kwargs): def execute(gen, input=None): if isinstance(gen, types.GeneratorType): if not input: obj = next(gen) else: try: obj = gen.send(input) except StopIteration as e: result = getattr(e, "value", None) return result if isinstance(obj, AsyncTask): # Tell the thread to call `execute` when its done # using the current generator object. func = partial(execute, gen) obj.finished_callback = func if obj.finished and not obj.finished_cb_ran: obj.on_finished(obj.result) else: raise Exception("Using yield is only supported with AsyncTasks.") else: print("result is %s" % result) return result result = func(*args, **kwargs) execute(result) return wrapper ## End coroutine-framework code If you put the above code into a module (say `qtasync.py`) you can import it into a script and use it like so to get `asyncio`-like behavior: import sys import time from qtasync import AsyncTask, coroutine from PyQt4 import QtGui from PyQt4.QtCore import QThread class MainWindow(QtGui.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.initUI() def initUI(self): self.cmd_button = QtGui.QPushButton("Push", self) self.cmd_button.clicked.connect(self.send_evt) self.statusBar() self.show() def worker(self, inval): print "in worker, received '%s'" % inval time.sleep(2) return "%s worked" % inval @coroutine def send_evt(self, arg): out = AsyncTask(self.worker, "test string") out2 = AsyncTask(self.worker, "another test string") QThread.sleep(3) print("kicked off async task, waiting for it to be done") val = yield out val2 = yield out2 print ("out is %s" % val) print ("out2 is %s" % val2) out = yield AsyncTask(self.worker, "Some other string") print ("out is %s" % out) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) m = MainWindow() sys.exit(app.exec_()) Output (when the button is pushed): in worker, received 'test string' in worker, received 'another test string' kicked off async task, waiting for it to be done out is test string worked out2 is another test string worked in worker, received 'Some other string' out is Some other string worked As you can see, `worker` gets run asynchronously in a thread whenever it gets called via the `AsyncTask` class, but its return value can be `yield`ed directly from `send_evt`, without needing to use callbacks. The code uses the coroutine-supporting features (`generator_object.send`) of Python generators, and a [recipe I found on ActiveState](http://code.activestate.com/recipes/578634-pyqt-pyside-thread- safe-callbacks-main-loop-integr/) that provides a child->main thread communication mechanism, to implement some very basic coroutines. The coroutines are quite limited: You can't return anything from them, and you can't chain coroutine calls together. It's probably possible to implement both of those things, but also probably not worth the effort, unless you really need them. I haven't done much negative testing with this either, so exceptions in workers and elsewhere may not be handled properly. What it _does_ do well, though, is allow you to call methods in separate threads via the `AsyncTask` class, and then `yield` a result from the thread when one is ready, **without blocking the Qt event loop**. Normally this kind of thing would be done with callbacks, which can be difficult to follow and is generally less readable than having all the code in a single function. You're welcome to use this approach if the limitations I mentioned are acceptable to you, but this is really just a proof-of-concept; you would need to do a whole bunch of testing before you think about put it into production anywhere. As you mentioned, Python 3.3 and 3.4 makes asynchronous programming easier with the introduction of `yield from` and `asyncio`, respectively. I think `yield from` would actually be quite useful here to allow chaining coroutines (meaning have one coroutine call another and get a result from it). `asyncio` has no PyQt4 event-loop integration, so it's usefulness is pretty limited. Another option would be to drop the coroutine piece of this altogether and just use the [callback-based inter-thread communication mechanism](http://code.activestate.com/recipes/578634-pyqt-pyside-thread-safe- callbacks-main-loop-integr/) directly: import sys import time from qtasync import CallbackEvent # No need for the coroutine stuff from PyQt4 import QtGui from PyQt4.QtCore import QThread class MyThread(QThread): """ Runs a function in a thread, and alerts the parent when done. Uses a custom QEvent to alert the main thread of completion. """ def __init__(self, parent, func, on_finish, *args, **kwargs): super(MyThread, self).__init__(parent) self.on_finished = on_finish self.func = func self.args = args self.kwargs = kwargs self.start() def run(self): try: result = self.func(*self.args, **self.kwargs) except Exception as e: print "e is %s" % e result = e finally: CallbackEvent.post_to(self.parent(), self.on_finished, result) class MainWindow(QtGui.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.initUI() def initUI(self): self.cmd_button = QtGui.QPushButton("Push", self) self.cmd_button.clicked.connect(self.send) self.statusBar() self.show() def customEvent(self, event): event.callback() def worker(self, inval): print("in worker, received '%s'" % inval) time.sleep(2) return "%s worked" % inval def end_send(self, cmd): print("send returned '%s'" % cmd) def send(self, arg): t = MyThread(self, self.worker, self.end_send, "some val") print("Kicked off thread") if __name__ == "__main__": app = QtGui.QApplication(sys.argv) m = MainWindow() sys.exit(app.exec_()) Output: Kicked off thread in worker, received 'some val' send returned 'some val worked' This could get a bit unwieldy if you're dealing with a long callback chain, but it doesn't rely on the more unproven `coroutine` code.
The system cannot find the file specified when calling copy from python Question: Here's my copy.py: from subprocess import call call("copy p2.txt p3.txt") If in command prompt I use `copy p2.txt p3.txt` it copies fine. but when I use `python copy.py` it gives me: Traceback (most recent call last): File "copy.py", line 2, in <module> call("copy p2.txt p3.txt") File "C:\Python27\lib\subprocess.py", line 493, in call return Popen(*popenargs, **kwargs).wait() File "C:\Python27\lib\subprocess.py", line 679, in __init__ errread, errwrite) File "C:\Python27\lib\subprocess.py", line 896, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified If I replace the python call to copy with xcopy, it works fine. Why would this be? Answer: When `subprocess.call()`ing a command like in a shell, you'll need to specify [`shell=True`](https://docs.python.org/2/library/subprocess.html#using-the- subprocess-module) as well. from subprocess import call call("copy p2.txt p3.txt", shell=True) The reason you need to use `shell=True` in this case is that the `copy` command in Windows is not actually an executable but a built-in command of the shell (if memory serves right). `xcopy` on the other hand is a real executable (in `%WINDIR%\System32`, which is usually in the `%PATH%`), so it can be called outside of a `cmd.exe` shell. In this particular instance, [`shutil.copy` or `shutil.copy2`](https://docs.python.org/2/library/shutil.html#shutil.copy) might be viable alternatives. Please note that using `shell=True` can lead to security hazards, or as the docs put it: > Warning: Using `shell=True` can be a security hazard. See the warning under > [Frequently Used > Arguments](https://docs.python.org/2/library/subprocess.html#frequently- > used-arguments) for details.
python imobiledevice module error Question: i write simple python script to test imobiledevice module ... my script : import imobiledevice if __name__ == '__main__': dev = imobiledevice.iDevice() but always get error : Traceback (most recent call last): File "/home/abbas/Main/test.py", line 7, in <module> import imobiledevice File "plist.pxd", line 8, in init imobiledevice (imobiledevice.c:57051) ImportError: /usr/local/lib/python2.7/dist-packages/plist.so: undefined symbol: plist_set_type i compile last version of libimobiledevice from source ... please help Answer: This is definitely problem within the `imobiledevice`. I would recommend to try compiling from some older (stable) version.
Raising exception during SQLite database connection in Python Question: Here is my code snippet:- import sqlite3 database = "sample.db" def dbConnection(database): try: connection = sqlite3.connect(database) db_cursor = connection.cursor() db_cursor.execute("show tables;") rows = db_cursor.fetchall() for row in rows: print row connection.close() except sqlite3.Error, e: print "Error in connection",e dbConnection("enb.db") It is raising this exception:- Error in connection near "show": syntax error I can't see anything wrong with the syntax as I just want to view the tables in the database. What could be the problem here?Thanks Answer: "SHOW TABLES" is not supported by SQLite. It is valid for other databases such as MySQL. [SQLite sql reference](http://sqlite.org/lang.html) [How to 'show tables' in SQLite](http://stackoverflow.com/questions/82875/how- do-i-list-the-tables-in-a-sqlite-database-file)
QStatusBar message disappears on menu hover Question: I have a very basic `QMainWindow` application that contains a `menubar` and a `statusbar`. When I hover over the menu the status message disappears. More precisely, the status message is cleared. I have no idea what is causing this behavior but it's resulting in a very difficult workaround for what I hoped to be trivial behavior. This is problematic for the following reason: I can make the message permanent by adding a `QLabel` widget to the `QStatusBar`, but then I get the awkward border. I don't want the border. The only way I know how to remove the border is via `QStatusBar.setStyleSheet()`. I am using a palette for my color scheme as opposed to a stylesheet so modifying the stylesheet messes up other colors. I also can't restore the original `statusBar QLabel` color when I make a modification via the stylesheet. I'm not the best at using stylesheets. Is there a way to prevent the menu interaction from clearing the status message? If not, is there a way to remove the border from the StatusBar when adding a QLabel widget while preserving my palette (maybe not via stylesheets)? #!/usr/bin/env python import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class win(QMainWindow): def __init__(self,parent=None): super(win,self).__init__(parent) self.menubar = QMenuBar(self) self.fileMenu = QMenu("File") self.exitAction = QAction("Exit",self) self.fileMenu.addAction(self.exitAction) self.menubar.addMenu(self.fileMenu) self.statusBar().showMessage("Hello") self.connect(self.exitAction,SIGNAL("triggered()"), self.close) if __name__ == "__main__": app = QApplication(sys.argv) GUI = win() GUI.show() app.exec_() Answer: Basically, each widget you hover over sets the status bar text to their `statusTip` property even when that property is an empty string. For `QMenu`, the text is stored in the `menuAction` action status tip, so, you can have a text instead of just clearing the status bar with something like this: self.fileMenu.menuAction().setStatusTip("File Menu is hovered") To prevent anything to change the status bar, you can probably install an `eventFilter` on the status bar and filter out all `QStatusTipEvent`.
How to implement a strategy pattern with runtime selection of a method? Question: **_Context_** I'm trying to implement some variant of strategy pattern in Python 2.7. I want to be able to instantiate a 'my_strategy' base class, but switch between different implementations of a 'score' method at run-time. I will have many common methods in 'my_strategy' but a bunch of 'score' implementations. The **main** illustrates how I want to use it. Here the scoring implementation is dummy of course. **_What I tried (i.e. My code so far)_** strategy.py: from algo_one import * #from algo_two import * class my_strategy ( object ): def __init__(self, candidate = ""): self.candidate = candidate self.method = 'default' self.no = 10 self._algo = algo_one def set_strategy(self, strategy='default'): self.strategy = strategy if self.strategy == 'algo_one': self._algo = algo_one elif self.strategy == 'algo_two': # self._algo = algo_two pass else: self._algo = None def score(self, *args): if len(args) > 0: self.candidate = args[0] self._algo.score(self.candidate) if __name__ == "__main__": s = my_strategy() s.strategy = 'algo_one' s.candidate = "hello world" print s.score() print s.score("hi") # s.set_method('algo_two') # print s.score("hi") I want to save the selected strategy in some sort of private pointer to the sub-class method. algo_one.py: from strategy import my_strategy class algo_one ( my_strategy ): def score(self, candidate): return len(candidate)*self.no I could have a class-less method, but later I'll need to access public variables of the base class. algo_two.py: from strategy import my_strategy class algo_two ( my_strategy ): def score(self, candidate): return len(candidate)*3 I have an empty **init**.py too. **_The errors_** **1.** in score self._algo.score(self.candidate) > TypeError: unbound method score() must be called with algo_one instance as > first argument (got str instance instead) **2.** If I uncomment the import of the second strategy: from algo_two import * I get the following error. > ImportError: cannot import name my_strategy My guess is that I run into some sort of circular dependency. **3.** from algo_one import * This is obviously not pretty (unable to detect undefined names), but if I from algo_one import algo_one I get > ImportError: cannot import name algo_one **_Question_** I think the errors are intertwined and that my approach, as a whole, may be flawed. If not just addressing the error, I'm looking for suggestions to improve the design. Or any comment, really. Also I'm open to suggestions regarding the title of this question. Thank you! Answer: You make it much more complicated than it needs to be. Python functions are first class objects so the simplest way to implement the strategy pattern in Python is to pass a 'strategy' function to your "context" object (the one that uses the strategy). The fine part is that any callable object (ie: any object implementing the `__call__` method) will work. def default_score_strategy(scorer): return len(scorer.candidate) * 3 def universal_answer_score_strategy(scorer): return 42 # definitly the universal answer <g> class ComplicatedStrategy(object): def __init__(self, factor): self.factor = factor def __call__(self, scorer): return len(scorer.candidate) * self.factor class Scorer(object): def __init__(self, candidate="", strategy=default_score_strategy): self.candidate = candidate self.strategy = strategy def score(self): return self.strategy(self) s1 = Scorer("foo") s2 = Scorer("bar", strategy=universal_answer_score_strategy) s3 = Scorer("baaz", strategy=ComplicatedStrategy(365)) Note that your strategies dont have to be in the same module as the `Scorer` class (well, except the default one of course), and that the module containing the `Scorer` class doesn't have to import the stratgeies modules - nor know anything about where the strategies are defined: # main.py from mylib.scores import Scorer from myapp.strategies import my_custom_strategy s = Scorer("yadda", my_custom_strategy)
Issues reading json from txt file Question: I have a json string in a txt file and I'm trying to read it to do some other procedures afterwards. It looks like this: with open('code test.txt', 'r', encoding=('UTF-8')) as f: x = json.load(f) I know the json is valid, but I'm getting: Traceback (most recent call last): File "C:\Python33\lib\json\decoder.py", line 368, in raw_decode obj, end = self.scan_once(s, idx) StopIteration During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 334, in <module> user_input() File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 328, in user_input child_remover() File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 280, in child_remover x = json.load(f) File "C:\Python33\lib\json\__init__.py", line 274, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "C:\Python33\lib\json\__init__.py", line 319, in loads return _default_decoder.decode(s) File "C:\Python33\lib\json\decoder.py", line 352, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python33\lib\json\decoder.py", line 370, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded I used this [website](http://jsonlint.com/) to check if the string is valid. If I use `.loads()`, I get a different error: Traceback (most recent call last): File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 334, in <module> user_input() File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 328, in user_input child_remover() File "C:\Users\rodrigof\Desktop\xml test\xml extraction.py", line 280, in child_remover x = json.loads(f) File "C:\Python33\lib\json\__init__.py", line 319, in loads return _default_decoder.decode(s) File "C:\Python33\lib\json\decoder.py", line 352, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer Originally the json was embeded in my script like this: json_text="""json stuff here""" And didn't get any errors. Any ideas on how to fix this??? Running python 3.3.3 just in case. Thanks!! **EDIT:** Just some random (valid) json on the txt and I get the same issue. This os one of the ones i tried: {"data": {"mobileHelp": {"value": { "ID1":{"children": [1,2,3,4,5]}, "ID2":{"children": []}, "ID3":{"children": [6,7,8,9,10]} } } } } Which is valid as well as per jsonlint.com. Answer: Your file contains a [UTF-8 BOM character](http://en.wikipedia.org/wiki/Byte_order_mark#UTF-8) at the start. UTF-8 **doesn't need a BOM** but especially Microsoft tools insist on adding one anyway. Open the file with the `utf-8-sig` encoding instead: >>> open('/tmp/json.test', 'wb').write(b'\xef\xbb\xbf{"data":\r\n {"mobileHelp":\r\n {"value":\r\n {\r\n "ID1":{"children": [1,2,3,4,5]},\r\n "ID2":{"children": []},\r\n "ID3":{"children": [6,7,8,9,10]}\r\n }\r\n }\r\n }\r\n}') 230 >>> import json >>> with open('/tmp/json.test', encoding='utf8') as f: ... data = json.load(f) ... Traceback (most recent call last): File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/decoder.py", line 367, in raw_decode obj, end = self.scan_once(s, idx) StopIteration During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 2, in <module> File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/__init__.py", line 271, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/__init__.py", line 316, in loads return _default_decoder.decode(s) File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/decoder.py", line 351, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.3/json/decoder.py", line 369, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded >>> with open('/tmp/json.test', encoding='utf-8-sig') as f: ... data = json.load(f) ... >>> data {'data': {'mobileHelp': {'value': {'ID2': {'children': []}, 'ID3': {'children': [6, 7, 8, 9, 10]}, 'ID1': {'children': [1, 2, 3, 4, 5]}}}}} Note that from Python 3.4 onwards you get a more helpful error message here: Traceback (most recent call last): File "<stdin>", line 2, in <module> File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/json/__init__.py", line 268, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.4/json/__init__.py", line 314, in loads raise ValueError("Unexpected UTF-8 BOM (decode using utf-8-sig)") ValueError: Unexpected UTF-8 BOM (decode using utf-8-sig)
kivy custom widget bind error Question: I am new to Kivy as well as Python, so please bare with me. I am trying to make a small tetris game for learning python with kivy. I am trying to create a custom widget with size 20,20. When I add it to the float layout and run the below code I receive the following error: Error: File "D:\OS Files\workspace\Tetris\holder.py", line 10, in __init__ self.add_widget(c) File "C:\Kivy180\kivy\kivy\uix\floatlayout.py", line 115, in add_widget pos_hint=self._trigger_layout) TypeError: descriptor 'bind' of 'kivy._event.EventDispatcher' object needs an argument Code: holder.py File: from items import Cell class Holder(FloatLayout): def __init__(self, **kwargs): super(Holder,self).__init__(**kwargs) self.size=(300,300) c=Cell #c.pos= (20,20) self.add_widget(c) #self.add_widget(c) items.py File: from kivy.uix.widget import Widget from kivy.graphics import * class Cell(Widget): def __init__(self, **kwargs): super(Cell,self).__init__(**kwargs) with self.canvas: Color(1, 0, 0) Rectangle(pos=(0, 0), size=(50, 50)) self.height=50 self.width=50 main.py File: from kivy.app import App from holder import Holder class start(App): def build(self): return Holder() if __name__ == '__main__': start().run() Could you please explain where I went wrong, I am stuck at the starting point itself. Regarding the error, I haven't written any events also, and it is just a widget class. Could you please explain where I went wrong in understanding kivy. Answer: c=Cell I bet you want `c` to be an instance of the `Cell` class. If you want to do that, you need to do: c=Cell()
local variable 'moodsc' referenced before assignment Question: In the code below I get the following error: "local variable 'moodsc' referenced before assignment" I'm new to programming and python. I'm struggling with interpreting other questions on the similar topic. Any context around this specific code would be helpful. import re import json import sys def moodScore(sent, myTweets): scores = {} # initialize an empty dictionary new_mdsc = {} # intitalize an empty dictionary txt = {} for line in sent: term, score = line.split("\t") # The file is tab-delimited. "\t" means "tab character" scores[term] = int(score) # Convert the score to an integer. data = [] # initialize an empty list for line in myTweets: tweet = json.loads(line) if "text" in tweet and "lang" in tweet and tweet["lang"] == "en": clean = re.compile("\W+") clean_txt = clean.sub(" ", tweet["text"]).strip() line = clean_txt.lower().split() moodsc = 0 pos = 0 neg = 0 count = 1 for word in range(0, len(line)): if line[word] in scores: txt[word] = int(scores[line[word]]) else: txt[word] = int(0) moodsc += txt[word] print txt if any(v > 0 for v in txt.values()): pos = 1 if any(v < 0 for v in txt.values()): neg = 1 for word in range(0, len(line)): # score each word in line if line[word] not in scores: if str(line[word]) in new_mdsc.keys(): moodsc2 = new_mdsc[str(line[word])][0] + moodsc pos2 = new_mdsc[str(line[word])][1] + pos neg2 = new_mdsc[str(line[word])][2] + neg count2 = new_mdsc[str(line[word])][3] + count new_mdsc[str(line[word])] = [moodsc2, pos2, neg2, count2] else: new_mdsc[str(line[word])] = [moodsc, pos, neg, count] def new_dict(): for val in new_mdsc.values(): comp = val[0] / val[3] val.append(comp) for key, val in new_mdsc.items(): print (key, val[4]) def main(): sent_file = open(sys.argv[1]) tweet_file = open(sys.argv[2]) moodScore(sent_file, tweet_file) # new_dict() if __name__ == '__main__': main() Answer: Ok @joshp, I think you need to globalise some variables, because the error is 'moodsc referenced before assignment', I think the code only gets as far as `moodsc += txt[word]` but you may also have trouble with `pos` and `neg`. Try `global moodsc` and `pos` etc. before you define `moodsc` and `pos` etc. If this doesn't work try `global moodsc` before `moodsc += txt[word]` and so forth, you may need to use global in both places for it to work, I often find that this is needed in my code, to globalise it at definition and wherever else you use it (at the start of each function and statement where it is used).
The best way to open two files Question: I need to open a file, read a line, hash it, and then save to a different file. Should I open both text files at the beginning of my script, or should I open each every time I save/read? I'm new to all this and I'm using python for android for sl4a. This is my code so far: import android import hashlib import time name = 0 droid = android.Android() name = raw_input("Enter a password to hash: ") hash_object = hashlib.md5 (name) print(hash_object.hexdigest()) time.sleep(2) print name f = open('name.txt', 'w',) f.write(hash_object.hexdigest()) f.close() Answer: If you want to read from the file `name.txt` and write to another: with open('name.txt', 'r') as f, open('out.txt', 'w') as f1: line = f.next() # get first line hash_object = hashlib.md5 (line) f1.write(hash_object.hexdigest()) # write to second file
raise class exception pass rock paper scissor game Question: I have this hw here which I am currently stuck on. My professor provided the class exception for us, but I was wondering is anyone can tell me how it works and for some reason when I run this program I get this: Traceback (most recent call last): File "C:\Python34\lab3.1.py", line 32, in <module> rps_game_winner(game_2) File "C:\Python34\lab3.1.py", line 5, in rps_game_winner raise WrongNumberOfPlayersError('Wrong number of players!') WrongNumberOfPlayersError: Wrong number of players! so wondering if someone can tell me what i did wrong or what i can do to make this program better. ty to everyone class WrongNumberOfPlayersError(Exception): pass class NoSuchStrategyError(Exception): pass def rps_game_winner(game): if len(game) != 2: raise WrongNumberOfPlayersError('Wrong number of players!') return print ("A WrongNumberOfPlayers error has occurred. \n\n") # Write the code for the NoSuchStratgyError stop_words = ['R', 'P', 'S'] if stop_words not in game[0]: raise NoSuchStrategyError('No such strategy!') # Write the code to determine the winner # Write the code to return a List with the winner's name and strategy if ("R" in game[0]) and ("S" in game[1]): return print (game[0], "wins since Rock beat Scissor\n\n") elif ("P" in game[0]) and ("R" in game[1]): return print (game[0], "wins since Paper beat Rock\n\n") elif ("S" in game[0]) and ("P" in game[1]): return print (game[0], "wins since Scissor beat Paper\n\n") elif ("S" in game[1]) and ("P" in game[0]): return print (game[1], "wins since Scissor beat Paper\n\n") elif ("P" in game[1]) and ("R" in game[0]): return print (game[1], "wins since Paper beat Scissor\n\n") elif ("R" in game[1]) and ("S" in game[0]): return print (game[1], "wins since Rock beat Scissor\n\n") game = [["Armando", "P"], ["Dave", "S"]]# ["Dave", "S"] wins game_2 = [['Joe','R']] # wrong number of players game_3 = [['Joe','R'],['Walter','Q']] # no such strategy as 'Q' rps_game_winner(game)# returns the list ["Dave", "S"] wins since Scissors beat Paper rps_game_winner(game_2)# raises exception wrong number of players rps_game_winner(game_3)# raises exception no such strategy as 'Q' Answer: I think you're having trouble understanding what an exception (or rather, an `Exception`!) is. You define them for the purpose of understanding why your code may have failed. For example: class WrongNumberOfPlayersError(Exception): pass This is an `Exception` (literally, as it inherits from `Exception` so it can do everything an `Exception` can do) that you've defined to know when you've got the wrong number of players! Therefore players = [("Player 1", "S"), ("Player 2", "P"), ("Player 3", "R")] rps_game_winner(players) # this should raise an exception, since there are the WRONG NUMBER OF PLAYERS! You handle these with `try/except` blocks (called `try/catch` in some languages) as such: while True: players = get_players() # imagine a function that created this list, # now you're looping over making a new one each # time it's wrong try: rps_game_winner(players) except WrongNumberOfPlayersError as e: # handle the exception somehow. You only make it into this block if # there are the wrong number of players, and it's already looping forever # so probably just... pass else: # if there are no exceptions break # get out of the infinite loop!! In your `rps_game_winner` function, you have the following logic: if len(game) != 2: raise WrongNumberOfPlayersError("Wrong number of players!") return print ("A WrongNumberOfPlayers error has occurred. \n\n") This is why I think your understanding is slightly flawed. Once you `raise` that exception, the function exits. It never reads the `return` line (which is probably for the best since you can't `return` a print function, it's just `None` for reasons that are outside the scope of this discussion. In Python 2 I believe this would cause your code to fail to run completely) This of a function like a small machine that does Work for you ("Work" in this case being some sort of computation, or running an algorithm, etc). Once the machine finishes working, it `return`s the result of that Work. However if something goes wrong, it should inform you that "Hey this isn't the result of my work, this is Something Bad," so it `raise`s an exception instead. Essentially: you can either `raise` if something goes wrong, or `return` if everything goes right. Note that there are more things wrong than this (e.g. you can NEVER throw a `NoSuchStrategyError` with your current code) but that the basics of the issue are in a misunderstanding of what exceptions are for. Below is an overly abstracted bit of code that should accomplish what you want it to. Keep in mind that I've purposely obfuscated some of the code so it's unusable as a copy/paste. In particular, I'm rather proud of my implementation of win/lose/draw :) R = 0b001 P = 0b010 S = 0b100 class WrongNumberOfPlayersError(Exception): pass class NoSuchStrategyError(Exception): pass class RPSGame(object): def __init__(self, *players): try: self.p1, self.p2 = players # assume constructed as game('p1','p2') except Exception: try: self.p1, self.p2 = players[0] # assume constructed as game(['p1','p2']) except Exception: raise WrongNumberOfPlayersError("Only two players per game") # no more assumptions, raise that exception def start(self): print("{0.name} plays {0.human_choice} || {1.name} plays {1.human_choice}".format( self.p1, self.p2)) def winner(p1, p2): global R, P, S wintable = {R: {R^S: 2, R^P: 1}, P: {P^R: 2, P^S: 1}, S: {S^P: 2, S^R: 1}} resulttable = ["Draw","Lose","Win"] return resulttable[wintable[p1.choice].get(p1^p2,0)] + " for {}".format(p1) return winner(self.p1, self.p2) class Player(object): rhyme_to_reason = {R:"Rock", P:"Paper", S:"Scissors"} def __init__(self, name, choice): self.name = name try: choiceU = choice.upper() except AttributeError: # choice is R, P, S not "R", "P", "S" choiceU = choice if choiceU not in ("R","P","S",R,P,S): raise NoSuchStrategyError("Must use strategy R, P, or S") choicetable = {"R":R,"P":P,"S":S} self.choice = choicetable.get(choiceU,choiceU) self.human_choice = Player.rhyme_to_reason[self.choice] def __xor__(self, other): if not isinstance(other, Player): raise NotImplementedError("Cannot xor Players with non-Players") return self.choice^other.choice def __hash__(self): return hash((self.name, self.choice)) def __str__(self): return self.name if __name__ == "__main__": import random, itertools num_players = input("How many players are there? ") players = [Player(input("Player name: "), input("Choice: ") or random.choice([R,P,S])) for _ in range(int(num_players))] scoreboard = {player: 0 for player in players} for pairing in itertools.combinations(players, 2): game = RPSGame(pairing) result = game.start() if result.startswith("W"): scoreboard[pairing[0]] += 1 elif result.startswith("L"): scoreboard[pairing[1]] += 1 else: pass print(result) for player, wins in scoreboard.items(): print("{:.<20}{}".format(player,wins))
Python smtplib: Why is the connection refused? Question: So, in the Python interpreter, I do this (and only this): >>> import smtplib >>> s=smtplib.SMTP("localhost") And this is what I get: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.4/smtplib.py", line 242, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.4/smtplib.py", line 321, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python3.4/smtplib.py", line 292, in _get_socket self.source_address) File "/usr/lib/python3.4/socket.py", line 509, in create_connection raise err File "/usr/lib/python3.4/socket.py", line 500, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused Does anyone have any ideas as to why am I getting this error? (That's my question.) It's not supposed to do that from what I understand. Tell me if I'm wrong. I'm using Xubuntu 14.04. If you need more information, please ask. I don't know of anything else I can tell you, off-hand. Thanks! Answer: SMTPlib is going to try to connect to an SMTP service, usually running on port 25, though it can run on various other ports. Sounds like maybe you need to install sendmail, postfix, or something of that nature.
Django urls regex is not working Question: I have an issue with Django's urls.py's regex part. I want to show a page for every entry users entered. My views.py looks like: def tekent(request): tumentry = Entry.objects.get(id=id) return render_to_response("baslik/tekentry.html", locals(), context_instance=RequestContext(request)) def tek(request, slug): basliklar = Baslik.objects.filter(active=True).order_by('-updated') baslik = Baslik.objects.get(slug=slug) entryler = baslik.entry_set.all() form2 = EntryForm(request.POST or None) if form2.is_valid(): entry = form2.save(commit=False) entry.baslik = baslik entry.user = request.user entry.save() return HttpResponseRedirect('/entry/%s'%(entry.id)) return render_to_response("baslik/tek.html", locals(), context_instance=RequestContext(request)) My main urls.py(not the app's) looks like this: from baslik import * urlpatterns = patterns('', url(r'^entry/(?P<Entry.id>)/$', 'tekent', name = "tek_entry"), ) and when I add an entry on web browser, it raises an error like this: DoesNotExist at /baslik/entry4/ Baslik matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/baslik/entry4/ Django Version: 1.6.5 Exception Type: DoesNotExist Exception Value: Baslik matching query does not exist. Exception Location: /Users/malisit/Django/sozluk/lib/python2.7/site-packages/django/db/models/query.py in get, line 310 Python Executable: /Users/malisit/Django/sozluk/bin/python What should I do to fix this up? Thanks. Answer: Try `url(r'^entry/(?P<id>\d+)/$', 'tekent', name = "tek_entry"),` Why don't you use class based views? [DetailView](https://docs.djangoproject.com/en/1.6/ref/class-based- views/generic-display/#detailview) is really handy for such things.
Tkinter Button will not create due to error in function Question: I am very new to Python and especially new to using Tkinter. I have a question on getting a button of mine to actually create in the GUI. I am trying to make a basic button that will take an input from an entry box as an integer and add it to the current balance (kind of a little bank app). The problem is that when I run the code and click the deposit button, the second "Make Deposit" button that is supposed to spawn in (defined in the make_deposit() function) will not spawn in due to an error in turning the input for the entry box into an integer. As far as I can tell, this error is only created because the second "Make Deposit" button is trying to run its function before the button is pressed. Is there any way to prevent this from happening? Below is the code, excluding some bits of the program not relevant to the issue at hand. from Tkinter import * def get_entry(entry): global s s = entry.get() s = int(s) data["current"] += s label = Label(root, text = "Current Balance: %d" % (data["current"])) label.grid(row = 1, column = 0) def make_deposit(): deposit = Entry(root, text = "Deposit Amount") deposit.grid(row = 2, column = 0) withdrawal.grid_forget() deposit_button = Button(root, text = "Make Deposit", command = get_entry(deposit)) deposit_button.grid(row = 3, column = 0) frame = Frame(root, height = 300, width = 300) frame.grid(row = 1, column = 0) label = Label(root, text = "ETA Until Car Purchase") label.grid(row = 0, column = 0) label = Label(root, text = "Current Balance: %d" % (data["current"])) label.grid(row = 1, column = 0) deposit = Button(root, text = "Make Deposit", command = make_deposit) deposit.grid(row = 2, column = 0) withdrawal = Button(root, text = "Make Withdrawal") withdrawal.grid(row = 3, column = 0) Any help would be greatly appreciated, and please take into account that I am an absolute beginner to Tkinter so the way that I have created some of the GUI elements might not be the best way of doing so. Answer: `command=` expect function name without `()` and arguments. Using command = get_entry(deposit) You run function `get_entry(deposit)` and its result is assigned to `command=`. It is good if you want to assign function to `command=` dynamicly. But you need `lambda`: command = lambda: get_entry(deposit)
Simple Python POST urlencode() Question: I'm trying to send a POST to my Node.js app using Python. Here is my code import urllib import urllib2 url = my_url values = {'email' : my_email, 'password' : my_password } data = urllib.urlencode(values) req = urllib2.Request(url,data) response = urllib2.urlopen(req) the_page = response.read() print(the_page) The request is sent, but somehow the parameters are getting messed up because the response I am getting corresponds to invalid login credentials. I can do this same request using Postman for Chrome and it works just fine. So I know it's not something with my API. So essentially I can do GET requests just fine with Python but for some reason, when I try to include parameters in a POST they are not translated correctly. I've already looked through the docs for urllib, urllib2 and urlencode(). I could not find anything helpful Answer: I do no longer debug urllib2 problems, since I switched to requests, I do no longer have them, you may do so: import requests print requests.post(my_url, data={'email': my_email, 'password': my_password}).text So readable, so elegant... If your jquery app returns json, you may use ".json()" instead of ".text" Your problem seems to have to keep cookies, to do so, you may just use a [requests session](http://docs.python-requests.org/en/latest/user/advanced/)
Enums in SQLite Question: My model uses a couple of Enum's for various columns, creating the tables using SQLAlchemy's create_all() method works fine in PostgreSQL, but it doesn't work with SQLite, it just stalls. The problem seems to be with creating Enum's, as far as I can tell sqlite doesn't support these, but according to SQLAlchemy's docs that shouldn't pose a problem. When I try to create_all() on an sqlite memory db it just stalls, even with echo=True no output appears. I tried the following code to demonstrate the problem: from sqlalchemy import create_engine, Enum from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() e = Enum('foo', 'bar', metadata=Base.metadata) engine = create_engine('sqlite:///:memory:', echo=True) Base.metadata.create_all(bind=engine) When I run this script it shows no output whatsoever, it just stalls. Python uses 100% CPU and the script never ends, until I ctrl-c it. When I try to create_all() on my actual schema it does echo some PRAGMA commands trying to determine if tables exist, but then it stalls on the creating the Enums. I tried to remove code from the model definition until it worked just fine, this was when I figured out it's the Enums. I tried to run this on Python 3.4 with SQLAlchemy 0.9.6 using SQLite 3.7.13. Answer: A friend ran into exactly this same problem recently, and it looks to me like an infinite-loop bug in SQLA (which I should really report, so thanks for this minimal testcase :)). Just remove the `metadata=` kwarg from your real code; as long as the enum is used as a type inside a declarative class, it'll inherit the right metadata anyway.
Different versions of django Question: I have just moved my django application to another server, which I have configured a long time ago, so I'm not really sure what's installed and configured. When running the application, I started getting weird errors, which pointed to running an old version of django. Hence, I decided to check the version. First, I ran: python -c "import django; print(django.get_version())" which showed version **1.3.1**. So then I did sudo easy_install --upgrade django which ran fine, but when running the first command again, it still shows **1.3.1** , so I decided to do: django-admin.py version and this returned **1.6.5**. Therefore, I assume that I have installed the latest django version, but for some reason python is using **1.3.1**. **How can I get python to use the latest version of django?** Answer: Firstly do not use `easy_install` but `pip`: easy install pip Try to install/update from `pip`: pip install django --upgrade If it fails, try to uninstall and after réinstall: pip uninstall django Be careful if you've installed django with Ubuntu's `apt-get`. It's a bad thing to mix system and python installers. Uninstall from `apt-get` if it's the case: apt-get remove python-django
lldb python handle breakpoint hit Question: I was looking through this huge LLDB python reference manual, and can't find still how to handle breakpoint hit with my code. I mean, I want to run my foo() when some breakpoint was hit. Please help me with some code snippets! Or point me the needed class in Python reference manual. Thanx! Answer: On the page: <http://lldb.llvm.org/python-reference.html> there is a section titled: RUNNING A PYTHON SCRIPT WHEN A BREAKPOINT GETS HIT which has some useful info. What you are doing is "adding a command to your breakpoint". The lldb command for this is "breakpoint command add". All the basic lldb commands are in the form "noun [sub-noun [...]] verb options"; knowing that might help translate from the thing you want to do to where in the command set the command for that operation lives. Anyway, the help on "breakpoint command add" has other examples that might be useful. Then condensed version is, make a python module containing a function with this signature: breakpoint_function (frame, bp_loc, dict) Bring that module into lldb with the command: (lldb) command script import "path to your .py file" You can also use the module name in "command script import" if you've set up the PYTHONPATH to point to it, but unlike Python's "import" you don't have to, the command will take care of that for you. Then make a breakpoint, and use "br com a" to add your function to it: (lldb) br com a -F MyModule.breakpoint_function Now when a breakpoint gets hit, your function will get called with the following arguments: The "frame" argument is the frame that hit the breakpoint. You can get the thread from the frame & thus the complete stack if you need it. The "bploc" argument is the "Breakpoint Location" that hit the breakpoint. In lldb one "breakpoint specification" (which is what you are setting with "break set") can resolve to many locations. For instance, a "source pattern" breakpoint might match many source patterns in your code. So you might want to know which one was actually hit. The "dict" option is so we can squirrel some stuff away and pass it to Python, it should be left alone. One other thing to keep in mind is that though the script interpreter (accessible with the "script" command) defines lldb.thread, lldb.frame etc. convenience variables, these variables are NOT set up when your breakpoint command is running. So if you've used these variables in the script interpreter while prototyping your command, you'll have to find them from the frame you were passed in if you need them in the breakpoint command. Note, Python breakpoint commands don't currently work in Xcode 6, though that should be fixed by the time it is done.
Where are python logs default stored when ran through IPython notebook? Question: In an IPython notebook cell I wrote: import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) handler = logging.FileHandler('model.log') handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) Notice that I am supplying a file name, but not a path. Where could I find that log? (ran a 'find' and couldn't locate it...) Answer: There's multiple ways to set the IPython working directory. If you don't set any of that in your IPython profile/config, environment or notebook, the log should be in your working directory. Also try `$ ipython locate` to print the default IPython directory path, the log may be there. What about giving it an absolute file path to see if it works at all? Other than that the call to `logging.basicConfig` doesn't seem to do anything inside an IPython notebook: # In: import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger() logger.debug('root debug test') There's no output. As per the docs, the [`logging.basicConfig`](https://docs.python.org/2/library/logging.html#logging.basicConfig) doesn't do anything if the root logger already has handlers configured for it. This seems to be the case, IPython apparently already has the root logger set up. We can confirm it: # In: import logging logger = logging.getLogger() logger.handlers # Out: [<logging.StreamHandler at 0x106fa19d0>] So we can try setting the root logger level manually: import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.debug('root debug test') which yields a formatted output in the notebook: ![enter image description here](http://i.stack.imgur.com/jN0mS.png) Now onto setting up the file logger: # In: import logging # set root logger level root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) # setup custom logger logger = logging.getLogger(__name__) handler = logging.FileHandler('model.log') handler.setLevel(logging.INFO) logger.addHandler(handler) # log logger.info('test info my') which results in writing the output both to the notebook and the _model.log_ file, which for me is located in a directory I started IPython and notebook from. Mind that repeated calls to this piece of code without restarting the IPython kernel will result in creating and attaching yet another handler to the logger on every run and the number of messages being logged to the file with each log call will grow.
python and global variables Question: How do I setup the global variable properly? # default objects is being set as None (null), after importing the piCamera library camera = None after that I'm declaring the Webcam class with the `GET` definition: class Webcam: def GET(self): web.header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary') stream=io.BytesIO() start=time.time() for foo in camera.capture_continuous(stream,'jpeg'): web.header('Content-type','--jpgboundary') web.header('Content-type','image/jpeg') web.header('Content-length',len(stream.getvalue())) yield (stream.getvalue()) stream.seek(0) stream.truncate() time.sleep(.5) if __name__ == "__main__": camera = picamera.PiCamera() global camera camera.resolution = (640, 480) app = web.application(urls, globals()) app.internalerror = web.debugerror app.run() Should I put the `if __name__ == "__main__":` before I'm defining the Webcam class? Here's my traceback of the calls: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/wsgiserver/__init__.py", line 1245, in communicate req.respond() File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/wsgiserver/__init__.py", line 775, in respond self.server.gateway(self).respond() File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/wsgiserver/__init__.py", line 2018, in respond response = self.req.server.wsgi_app(self.env, self.start_response) File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/httpserver.py", line 306, in __call__ return self.app(environ, xstart_response) File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/httpserver.py", line 274, in __call__ return self.app(environ, start_response) File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 281, in wsgi result = peep(result) File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 261, in peep firstchunk = iterator.next() File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 605, in wrap yield next() File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 597, in next return result.next() File "/home/pi/piApp/index.py", line 77, in GET for foo in camera.capture_continuous(stream,'jpeg'): AttributeError: 'NoneType' object has no attribute 'capture_continuous' Answer: It looks like you are running this as a library file and therefore the `__main__` section does not execute. Put that code at global scope. I would guess something like this is what you want: def main(): global camera camera = picamera.PiCamera() camera.resolution = (640, 480) app = web.application(urls, globals()) app.internalerror = web.debugerror app.run() main()
Does ply.lex parse the same token once? Question: I was reading a [lexical parsing](http://www.dabeaz.com/ply/ply.html) document so that I can parse some arguments and I exactly followed the document to create a parser. This is the whole code: #!/usr/bin/env python #-*- coding: utf-8 -*- import ply.lex as lex args = ['[watashi]', '[anata]>500', '[kare]>400&&[kare]<800'] tokens = ('NUMBER', 'EXPRESSION', 'AND', 'LESS', 'MORE') t_EXPRESSION = r'\[.*\]' t_AND = r'&&' t_LESS = r'<' t_MORE = r'>' t_ignore = '\t' def t_NUMBER(t): r'\d+' t.value = int(t.value) return t def t_newline(t): r'\n+' t.lexer.lineno += len(t.value) def t_error(t): print 'Illegal character "%s"' % t.value[0] t.lexer.skip(1) lexer = lex.lex() for i in args: lexer.input(i) while True: tok = lexer.token() if not tok: break print tok print '#############' I simply created a list of sample arguments and I got this output: LexToken(EXPRESSION,'[watashi]',1,0) ############# LexToken(EXPRESSION,'[anata]',1,0) LexToken(MORE,'>',1,7) LexToken(NUMBER,500,1,8) ############# LexToken(EXPRESSION,'[kare]>400&&[kare]',1,0) LexToken(LESS,'<',1,18) LexToken(NUMBER,800,1,19) ############# The first and second sample arguments are parsed correctly, but the third one is not. The third sample argument is EXPRESSION+LESS+NUMBER whereas it must be EXPRESSION+MORE+NUMBER+AND+EXPRESSION+LESS+NUMBER. So I thought there could be one of those problems: * **ply.lex is only parsing one token:** In the codes above, ply.lex cannot parse two seperate expressions and it returns the latest token as its type. "[kare]>400&&[kare]" is EXPRESSION because it ends with the latest EXPRESSION token which is second [kare] and 800 is NUMBER because it is the latest NUMBER token. **!!! OR !!!** * **There is a mistake in t_EXPRESSION variable:** I defined this variable as "[.*]" to get all characters in those two brackets ([]). The first token of third sample argument is "[kare]>400&&[kare]" since it simply starts and ends with those brackets and contains .* (every single character) in them, but I thought the interpreter would stop in the first (]) character due to being first. So I could not find a way to solve but asked here. in general this is what I am struggling with lexer.input("[kare]>400&&[kare]<800") while True: tok = lexer.token() if not tok: break print tok I get LexToken(EXPRESSION,'[kare]>400&&[kare]',1,0) LexToken(LESS,'<',1,18) LexToken(NUMBER,800,1,19) but I expected something more like LexToken(EXPRESSION,'[kare]',1.0) LexToken(LESS,'>',?) LexToken(NUMBER,400,?) LexToken(AND,'&&',?) LexToken(EXPRESSION,'[kare]',1,0) LexToken(LESS,'<',1,18) LexToken(NUMBER,800,1,19) Answer: I think I see your problem t_EXPRESSION = r'\[.*\]' is greedy and will match the biggest match it can ie `'[kare]>400&&[kare]'` instead try t_EXPRESSION = r'\[[^\]]*\]' this will match only one set since it looks for not open bracket(`[^\]]`) instead of anything(`.`) you can also use not greedy matching t_EXPRESSION = r'\[.*?\]' the `?` makes it match as few characters as possible rather than the maximum
How can I make the composite of two images in OpenCV with Python? Question: I have one image that remains unchanged and another image which is the first one, but with a filter applied on it. I want to create the third image which should be the composite of these first two images. I know that in MATLAB there is a function called as `imfuse()` with the default color channel green-magenta. I want to do the same thing in Python, with exactly the same color channel. How can I do this ? Here are the images (first is the original picture, second is the first picture with the filter applied, third is the MATLAB result): ![image](http://i59.tinypic.com/2q1usqs.jpg) ![filter](http://i59.tinypic.com/35iq612.jpg) ![result](http://i62.tinypic.com/21c9vmf.jpg) Thanks for your help ! Answer: By default, [`imfuse`](http://www.mathworks.com/help/images/ref/imfuse.html) simply overlays the pair of images in different color bands (Default being `Method=falsecolor` and `ColorChannels=green-magenta`). Here is an example in MATLAB to illustrate (it should should be easy to write this in Python/OpenCV): % a pair of grayscale images A = imread('cameraman.tif'); B = imrotate(A,5,'bicubic','crop'); % image "A" rotated a bit % use IMFUSE C = imfuse(A,B); imshow(C) % use our version where: Red=B, Green=A, Blue=B C = cat(3, B, A, B); imshow(C) Both should give you the same thing: ![fused_images](http://i.stack.imgur.com/TBUuf.png) * * * # EDIT: Here is the Python/OpenCV version: import numpy as np import cv2 A = cv2.imread(r"C:\path\to\a.png", 0) B = cv2.imread(r"C:\path\to\b.png", 0) #C = cv2.merge((B,A,B)) C = np.dstack((B,A,B)) cv2.imshow("imfuse",C) cv2.waitKey(0) ![opencv_python_imfuse](http://i.stack.imgur.com/nmjE1.png)
Python - change pixel value Question: I have used this code to change the pixel value of image, im=Image.open("image.jpg") pix=im.load() pix[50,50]=(70,70,70) it is work well with me, but when I use a png image everything is okay and the changes are saved to the image, but when I use a JPG image the changes are not saved to the image. Is there something missing in the code, do I need to save the changes , and how would I do ?? Answer: Try with: im.putpixel((50,50), (70, 70, 70)) or you can also do: import numpy as np from PIL import Image # pix has 4 channels for png and 3 for jpg pix = np.array(im) pix[50, 50, 0] = 70 # 0 accesses the first channel pix[50, 50, 1] = 70 # 1 accesses the second channel pix[50, 50, 2] = 70 # 2 accesses the third channel Image.fromarray(pix).save('new_img.jpg')
How can I make Python's ElementTree enforce XML schema? Question: Suppose I wish to parse an XML document, and its schema dictates that a given element can only occur once. How do I make sure that an exception gets raised if the element occurs twice or more? Or, if the schema says that a given element's value should be an integer, and the value is "turkey sandwich", how do I make the parser crash and burn like it's supposed to? Can ElementTree do this? Can anything do this? Does this question even make sense? Answer: ElementTree from the STD lib has not schema support. For this, I suggest you to use the [lxml](http://lxm.de/) package which has it (and by the way, it's much faster). Here after an example from my own code: from lxml import etree # Create the schema object with open(xsd_file) as f: xmlschema_doc = etree.parse(f) xmlschema = etree.XMLSchema(xmlschema_doc) # Create a tree for the XML document doc = etree.parse(xml_text) # Validate the XML document using the schema return xmlschema.validate(doc) or if you want a exception to be raised: xmlschema.assertValid(doc)
Getting an error for a simple Tkinter program Question: I have been trying to make a simple program using Tkinter and Python. All you do is click buttons and depending on what button you click, it updates certain labels. This is my code: from tkinter import * apples = 0 gold = 0 def pick(): global apples apples = apples + 1 def sell(): global apples global gold gold = gold + (apples * 10) apples = 0 app = Tk() app.title("Apple Picking Simulator 2014") app.geometry("400x300+100+60") label1 = Label(text = "Welcome to Apple Picking Simulator 2014!").pack() Label().pack() label2 = Label(text = "Apples: " + apples).pack() label3 = Label(text = "Gold: " + gold).pack() button1 = Button(text = "Pick Apple", command = pick).pack() button2 = Button(text = "Sell Apples", command = sell).pack() app.mainloop() Now, whenever I try to run the program, I just get the error: TypeError: Can't convert 'int' object to str implicitly I understand that it can't convert an integer to a string, but I've been trying everything, and I can't seem to make it work. Is there an easy way to display the apple and gold numbers on the window and have them update every time I click the pick or sell button? Thanks. Answer: Trying to concatenate an integer to a string is what is causing your error. You need to explicitly cast your `apples` and `gold` integer variables to a string using the [`str` function](https://docs.python.org/2/library/functions.html#str). Replace: label2 = Label(text = "Apples: " + apples).pack() label3 = Label(text = "Gold: " + gold).pack() With: label2 = Label(text = "Apples: " + str(apples)).pack() label3 = Label(text = "Gold: " + str(gold)).pack() Fixed source code: from tkinter import * apples = 0 gold = 0 def pick(): global apples apples = apples + 1 def sell(): global apples global gold gold = gold + (apples * 10) apples = 0 app = Tk() app.title("Apple Picking Simulator 2014") app.geometry("400x300+100+60") label1 = Label(text = "Welcome to Apple Picking Simulator 2014!").pack() Label().pack() label2 = Label(text = "Apples: " + str(apples)).pack() label3 = Label(text = "Gold: " + str(gold)).pack() button1 = Button(text = "Pick Apple", command = pick).pack() button2 = Button(text = "Sell Apples", command = sell).pack() app.mainloop()
How to parse multiple expressions when using the rply library Question: I created a parser using the rply library for python and can currently perform basic arithmetic. The problem is that I cannot parse more than one line when reading from a file. Say I have: 5 + 4 on a single line. That parses with no errors. But if I have something like the following over two lines. 5 + 4 7 * 3 I get this error: rply.errors.ParsingError. I have set my lexer to ignore newlines and spaces: lg.ignore('\n') lg.ignore('\s+') And these are my productions: @pg.production('main : expression') def main(p): return p[0] @pg.production(’expression : NUMBER’) def expression_number(p): return Number(int(p[0].getstr())) @pg.production(’expression : expression PLUS expression’) def expression_binop(p): left = p[0] right = p[2] if p[1].gettokentype() == ’AND’: return Add(left, right) Any help would be greatly appreciated! Thanks! Answer: This will work, you had no multiplication setup: from rply import ParserGenerator, LexerGenerator from rply.token import BaseBox lg = LexerGenerator() # Add takes a rule name, and a regular expression that defines the rule. lg.add("PLUS", r"\+") lg.add("MINUS", r"-") lg.add("NUMBER", r"\d+") lg.add('MUL', r'\*') # added MUL here lg.ignore(r"\s+") # This is a list of the token names. precedence is an optional list of # tuples which specifies order of operation for avoiding ambiguity. # precedence must be one of "left", "right", "nonassoc". # cache_id is an optional string which specifies an ID to use for # caching. It should *always* be safe to use caching, # RPly will automatically detect when your grammar is # changed and refresh the cache for you. pg = ParserGenerator(["NUMBER", "PLUS", "MINUS",'MUL'], # added MUL here precedence=[("left", ['PLUS', 'MINUS'])], cache_id="myparser") @pg.production("main : expr") def main(p): # p is a list, of each of the pieces on the right hand side of the # grammar rule return p[0] @pg.production("expr : expr MUL expr") # added MUL here @pg.production("expr : expr PLUS expr") @pg.production("expr : expr MINUS expr") def expr_op(p): lhs = p[0].getint() rhs = p[2].getint() if p[1].gettokentype() == "PLUS": return BoxInt(lhs + rhs) elif p[1].gettokentype() == "MINUS": return BoxInt(lhs - rhs) elif p[1].gettokentype() == 'MUL': # added Mul here return BoxInt(lhs * rhs) else: raise AssertionError("This is impossible, abort the time machine!") @pg.production("expr : NUMBER") def expr_num(p): return BoxInt(int(p[0].getstr())) lexer = lg.build() parser = pg.build() class BoxInt(BaseBox): def __init__(self, value): self.value = value def getint(self): return self.value with open("hello.txt") as f: for line in f: if line.strip(): print parser.parse(lexer.lex(line)).value 21 9
Removing integer values from a alphanumeric column in python Question: I am new to python and struggling in one trivial task. I have one alphanumeric column known as region. It has both entries beginning with / such as /health/blood pressure etc and integer values. So typically few observations look like: /health/blood pressure /health/diabetes 7867 /fitness 9087 /health/type1 diabetes Now I want to remove all the rows/cases with integer values. So after importing the data set into python shell, it is showing region as object. I intended to solve this problem with a sort of regular expression. So I did the following: pattern='/' data.region=Series(data.region) matches=data.region.str.match(pattern) matches Here it gives a boolean object explaining whether each pattern is in the data set or not. So I get something like this: 0 true 1 false 2 true 3 true ......... so on. Now I am stuck further how to remove rows of matches boolean object with false tag. If statement is not working. If anyone can offer some sort of assistance, that would be great!! Thanks!! Answer: It seems like you are using the pandas framework. So I am not completely sure if this is working: You can try: matches = [i for i in data.region if i.str.match(pattern)] In python this is called a list comprehension that goes through every entry in data.region and checks your pattern and puts it in the list if the pattern is matching (and the expression after 'if' is thus true). See: <https://docs.python.org/2/tutorial/datastructures.html#list- comprehensions> If you want to map those for every region you can try to create a dictionary that maps the regions to the lists with the following dict-comprehension: matches = {region: [i for i in data.region if i.str.match(pattern)] for region in data} See: <https://docs.python.org/2/tutorial/datastructures.html#dictionaries> However you are definitely leaving the realm of the pandas framework. This could eventually fail of regions is not an integer/string but a list itself (as Is aid I don't know pandas enough to judge). In that case you could try: matches = {} for region in list_of_regions: matches[region] = [i for i in data.region if i.str.match(pattern)] which is basically the same just with a given list of region and the dict comprehension made explicit in a for loop.
How can I import an Odoo/OpenERP Addon module in an interactive python environment? Question: How do I import an Odoo/OpenERP addon module from a python shell? I want to learn more about the structure of Odoo. I prefer to do that through IPython, but I'm not sure how to import addons into the environment. For starts I merely want to load a default Addon into my environment. So I just copied a line from the default Product module. I did not modify anything in the source code. I have been grepping through the source code to find out why I can't simply import the Addon in the I'm used to with Python. My Odoo installation works fine. $ cd /opt/odoo $ ipython In [1]: import openerp In [2]: openerp.modules.module? [not much luck] In [3]: openerp.addons? [not much luck either, nothing here either] In [4]: import openerp.addons [no error] In [5]: import openerp.addons.decimal_precision as dp # Line from addons/product/product.py [....] ImportError: No module named decimal_precision `openerp.addons` doesn't have anything but still `import openerp.addons.STUFF` works fine from Odoo addon modules. I have the feeling that `addons` needs to be initialized but I haven't found out how to do that. I started going through the code from `openerp.main.cli()`. `openerp.tools.config.parse_config()` is a step in the right direction but it's not enough. I need to somehow pass `--addons-path=addons` as well (since Odoo is not smart enough to find its own addons). Answer: According to [openerp source code](https://github.com/odoo/odoo/blob/master/openerp/addons/__init__.py) > Addons are made available under `openerp.addons` after > openerp.tools.config.parse_config() is called (so that the addons paths are > known). so you should call `openerp.tools.config.parse_config()` before doing any import. If you need to pass any arguments you can do it as such: `openerp.tools.config.parse_config(['--addons-path=addons'])`
How to cast variables in python with jcc Question: In java it is possible to cast an object onto a class. An good example is found here Object aSentenceObject = "This is just a regular sentence"; String aSentenceString = (String)aSentenceObject; I have a program that needs to integrate some java with python. I am trying to do this via the [JCC library](https://pypi.python.org/pypi/JCC/). The problem that I am encountering is that with JCC, all of the java classes are loaded into the imported library that I created with JCC. So I can create an instance of the base class by passing the necessary argument to the constructor of the java class. obj = javaLibrary.BaseClass('foo') However, in my code I need to be able to cast this object onto a a more “specific” type of Object. How can I accomplish this in python with JCC? It seems like it may be impossible because python is dynamically typed, but that is why I am asking this question. Answer: All comments above valid, but to be specific for your case: casted_obj = Object.cast_(obj)
Getting actual facebook and twitter image urls using python Question: I want to write a python code that downloads 'main' image from urls that contain images. I have urls like these in my data (text files) 1. <http://t.co/fd9F0Gp1P1> points to an fb image 1. <http://t.co/0Ldy6j26fb> points to twitter image but their expanded urls don't result in .jpg,.png images. Instead they direct us to a page that contains the desired image. How do I download images from these urls? Answer: Here you will find an example of how I downloaded the plane image from the facebook page, you can adapt this to work for your twitter page: from bs4 import BeautifulSoup import urllib urlData = urllib.urlopen('https://www.facebook.com/photo.php?fbid=10152055005350906') data = str(urlData.readlines()) bs = BeautifulSoup(data) imgUrl = bs.find('img', attrs={'class': 'fbPhotoImage img'}).get('src') urllib.urlretrieve(imgUrl, "plane.jpg") ## **EDIT** I decided to actually help you out with the twitter one as well, here is the twitter example of downloading the image from the link you gave: from bs4 import BeautifulSoup import urllib urlData = urllib.urlopen('https://twitter.com/USABillOfRights/status/468852515409502210/photo/1') data = str(urlData.readlines()) bs = BeautifulSoup(data) imgUrl = bs.find('img', attrs={'alt': 'Embedded image permalink'}).get('src') urllib.urlretrieve(imgUrl, "cnn.jpg") And here is the web reference for [BeautifulSoup.](http://www.crummy.com/software/BeautifulSoup/)
Hide os.system command line call in python script Question: I have a python script (myscript.py) that I am running on the linux server like below: python myscript.py In my script I am using the system call, example below: os.system("./myprogram.pl -x 5 > results.out") When I run myscript.py on the server whenever there is `os.system` call, the command call is visible on the server. Is there a way to hide all the command calls so that they are not displayed when they are called within the program (`myscript.py`)? (This is not about hiding the output resulted in the command calls within the program) Answer: You can use a subprocess pipe instead of the os.system command: import subprocess; NewPipeObject = subprocess.Popen( [ './myprogram.pl -x 5 > results.out' ], stdout= subprocess.PIPE, stderr= subprocess.PIPE ); or you can take advantage of the list format of the arguments for the subprocess pipe (it adds a space between each list element) and present them as the following (which will be easier to generalize): import subprocess; NewPipeObject = subprocess.Popen( [ './myprogram.pl', '-x', '5', '>', 'results.out' ], stdout= subprocess.PIPE, stderr= subprocess.PIPE ); Either way you're suppressing the outputs from `stdout` and `stderr` into the pipe object (`NewPipeObject`).
python interactive shell using cmd repeating statements with no arguments typed Question: New to python and i'm working on an interactive shell using cmd that takes defined functions and arguments and returns value in an if/then format. Example below. But my issue is that every time the user types a function and i return something to the user, if they just hit enter then they recieve the last provided output. For example code below...but basically if the user doesn't type an argument or function for that matter, i just want nothing displayed just a "" or empty space. I assumed the else pass argument would have done that for me, but obviously not. I have tried if and elif, with the same results. Example output with "test arp", just hitting enter returns the previous argument pressed : user@hostname>test arp ? (192.168.50.1) at 0:26:88:38:c6:48 on en0 ifscope [ethernet] ? (192.168.50.255) at ff:ff:ff:ff:ff:ff on en0 ifscope [ethernet] > **<enter key>** ? (192.168.50.1) at 0:26:88:38:c6:48 on en0 ifscope [ethernet] ? (192.168.50.255) at ff:ff:ff:ff:ff:ff on en0 ifscope [ethernet] > **<enter key>** **_Example Code:_** #!/usr/bin/env python from cmd import Cmd from time import ctime import csv, os, subprocess, getpass, socket, pwd, re, select, shutil, subprocess, sys syntaxError = "Sorry that syntax isn't quite right..." class cliPrompt(Cmd): def do_test(self, args): if len(args) == 0: print syntaxError if args == '?': print 'want to read the help?' if args == 'arp': subprocess.call('arp -an', shell=True) if args == 'cpu': subprocess.call('grep "model name" /proc/cpuinfo', shell=True) if args == 'firewall': subprocess.call('iptables -L -v -n --line-numbers', shell=True) if args == 'interfaces': subprocess.call('ifconfig', shell=True) else: pass if __name__ == '__main__': prompt = cliPrompt() prompt.prompt = '>' prompt.cmdloop() Answer: Right on the front page of the cmd documentation discusses disabling the returning previous command option. <https://wiki.python.org/moin/CmdModule>
Internal Server Error with Flask app on Apache using Raspbian Question: I can successfully deploy my flask app from the localhost:5000 but I get an internal server error 500 when connecting through a web browser at raspberrypi.local and the same error when I tried the RPi's IP apache error log shows Mon Jul 14 23:25:01 2014] [error] [client 192.168.1.118] mod_wsgi (pid=2081): Target WSGI script '/var/www/Intr anet_for_RPi/Intranet_for_RPi.wsgi' cannot be loaded as Python module. [Mon Jul 14 23:25:01 2014] [error] [client 192.168.1.118] mod_wsgi (pid=2081): Exception occurred processing WSG I script '/var/www/Intranet_for_RPi/Intranet_for_RPi.wsgi'. [Mon Jul 14 23:25:01 2014] [error] [client 192.168.1.118] Traceback (most recent call last): [Mon Jul 14 23:25:01 2014] [error] [client 192.168.1.118] File "/var/www/Intranet_for_RPi/Intranet_for_RPi.wsg i", line 7, in <module> [Mon Jul 14 23:25:01 2014] [error] [client 192.168.1.118] from Intranet_for_RPi import app as application [Mon Jul 14 23:25:01 2014] [error] [client 192.168.1.118] ImportError: No module named Intranet_for_RPi /etc/apache2sites-available/ <VirtualHost *:80> ServerName raspberrypi ServerAdmin [email protected] WSGIScriptAlias / /var/www/Intranet_for_RPi/Intranet_for_RPi.wsgi <Directory /var/www/Intranet_for_RPi/Intranet_for_RPi/> Order allow,deny Allow from all WSGIScriptReloading On </Directory> Alias /static /var/www/Intranet_for_RPi/Intranet_for_RPi/static <Directory /var/www/Intranet_for_RPi/Intranet_for_RPi/static/> Order allow,deny Allow from all </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> flask file # all the imports from __future__ import with_statement import sqlite3 import os from contextlib import closing from flask import Flask, request, session, g, redirect, url_for, \ abort, render_template, flash, send_from_directory from werkzeug import secure_filename # configuration DATABASE = '/tmp/flaskr.db' DEBUG = True SECRET_KEY = 'key-gen secret' USERNAME = 'admin' PASSWORD = 'default' app = Flask(__name__) app.config.from_object(__name__) app.config.from_envvar('FLASKR_SETTINGS', silent=True) # This is the path to the upload directory app.config['UPLOAD_FOLDER']='/var/www/Intranet_for_RPi/Intranet_for_RPi/uploads' # These are the extensions that we are accepting to be uploaded app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'jpg', 'jpeg', 'gif']) # For a given file, return whether it's an allowed type or not def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS'] # This route will show a form to perform an AJAX request # jQuery is loaded to execute the request and update the value of the operation @app.route('/index') def index(): return render_template('index.html') # Route that will process the file upload @app.route('/upload', methods=['POST']) def upload(): # Get the name of the uploaded files uploaded_files = request.files.getlist("file[]") filenames = [] for file in uploaded_files: # Check if the file is one of the allowed types/extensions if file and allowed_file(file.filename): #Make the filename safe, remove unsupported chars filename = secure_filename(file.filename) #Move teh file from the temporal folder to the upload folder we setup file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # Save teh filename into a list, we'll use it later filenames.append(filename) # Redirect the user to the uploaded_file route, which will basically # show on the browser the uploaded file # Load an html page with a link to each uploaded file return render_template('upload.html', filenames=filenames) # This route is expecting a parameter containing the name of a file. Then it will locate that # file on the upload directory and show it on the browser, so if the user uploads an image, # that image is going to be shown after the upload. @app.route('/uploads/<filename>') def uploaded_file(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) def connect_db(): return sqlite3.connect(app.config['DATABASE']) def init_db(): with closing(connect_db()) as db: with app.open_resource('schema.sql') as f: db.cursor().executescript(f.read()) db.commit() @app.before_request def before_request(): g.db = connect_db() @app.teardown_request def teardown_request(exception): g.db.close() @app.route('/') def show_entries(): cur = g.db.execute('select title, text from entries order by id desc') entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()] return render_template('show_entries.html', entries=entries) @app.route('/add', methods=['POST']) def add_entry(): if not session.get('logged_in'): abort(401) g.db.execute('insert into entries (title, text) values (?, ?)', [request.form['title'], request.form['text']]) g.db.commit() flash('New entry was successfully posted') return redirect(url_for('show_entries')) @app.route('/login', methods=['GET', 'POST']) def login(): error = None if request.method == 'POST': if request.form['username'] != app.config['USERNAME']: error = 'Invalid username' elif request.form['password'] != app.config['PASSWORD']: error = 'Invalid password' else: session['logged_in'] = True flash('You were logged in') return redirect(url_for('show_entries')) return render_template('login.html', error=error) @app.route('/logout') def logout(): session.pop('logged_in', None) flash('You were logged out') return redirect(url_for('show_entries')) @app.route('/files') def files(): return render_template('files.html') if __name__ == '__main__': app.run() Here is my wsgi file #!/usr/bin/python Import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/Intranet_for_RPi/") from Intranet_for_RPi import app as application application.secret_key = 'key-gen-secret' ``` I have made the wsgi file executable. I think it may have something to do with my python version or path pertaining to `/etc/apache2/mods- available/wsgi.conf`. Any help would greatly be appreciated Answer: The error obviously says that the `wsgi` script can't find `Intranet_for_RPi` module. Check your paths. You might need to add `WSGIPythonPath` to your apache configuration: WSGIPythonPath /var/www/Intranet_for_RPi:/var/www/Intranet_for_RPi/packages:etc <VirtualHost *:80> ...
Getting this error _csv.Error: sequence expected in Python Question: I am trying to write a python script called header.py where I have a list of headers which is:- header = ['name', 'age', 'gender'] I am trying to append a header to it and write it in a csv file. Here is my code snippet:- import csv header = ['name', 'age', 'gender'] updated_csv_writer = csv.writer(open("updatedQueryOutput.csv", "w"),delimiter = ',') appendAdd = header.append("address") updated_csv_writer.writerow(appendAdd) But I am getting this error:- _csv.Error: sequence expected I don't know what is wrong with my code. Any help?Thanks Answer: `append` mutates the list but doesn't return it, so you need to move the header.append statement out onto its own. See this top-level example: Python 2.7.5+ (default, Feb 27 2014, 19:37:08) [GCC 4.8.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = [1,2,3] >>> a.append(4) >>> a [1, 2, 3, 4] So you could modify your code like this: import csv header = ['name', 'age', 'gender'] updated_csv_writer = csv.writer(open("updatedQueryOutput.csv", "w"),delimiter = ',') header.append("address") updated_csv_writer.writerow(header) If you wanted to preserve the original value of `header`, you could always make a new list like this: header_new = header + ['address']
How to make selenium webdriver open in google chrome without Incognito Question: I'm using selenium for the past 1 month. I want to create some small applications using selenium. Selenium webdriver opens an incognito window when I run it. Is there any way to make it launch in normal window(i.e which has my accounts logged in)? This is the code which I'm using : (python code in linux) chromedriver = Path to chrome driver os.environ["webdriver.chrome.driver"] = chromedriver driver = webdriver.Chrome(chromedriver) driver.get("http://www.gmail.com") Answer: If you want to re-use your login/authentication cookies, you can save the cookies and then load it again. You can refer to [this post](http://stackoverflow.com/questions/15058462/how- to-save-and-load-cookies-using-python-selenium-webdriver/15058521#15058521): To save cookies: import pickle import selenium.webdriver driver = selenium.webdriver.Firefox() driver.get("http://www.google.com") pickle.dump( driver.get_cookies() , open("cookies.pkl","wb")) To add back the cookies: import pickle import selenium.webdriver driver = selenium.webdriver.Firefox() driver.get("http://www.google.com") cookies = pickle.load(open("cookies.pkl", "rb")) for cookie in cookies: driver.add_cookie(cookie) If you want to load an extension when Chrome starts, you can refer to [this post](http://stackoverflow.com/questions/10425799/selenium-chromedriver- causes-chrome-to-start-without-configured-plugins-bookmar/10434536#10434536) and [this post](https://sites.google.com/a/chromium.org/chromedriver/extensions).
Python, virtualenv: Getting permission error while activating Question: I have been given a laptop. So I copied from my Work PC `.virtualenvs/` directory to my NAS and then I copied it back to my new laptop. I installed `virtualenv` and `virtualenvwrapper` but I can't get my virtual environment to work. This is what I got at first: chris@chris-amilo ~ $ workon iwidget virtualenvwrapper.user_scripts could not run "/home/chris/.virtualenvs/preactivate": [Errno 13] Permission denied virtualenvwrapper.user_scripts could not run "/home/chris/.virtualenvs/iwidget/bin/preactivate": [Errno 13] Permission denied then I did a chmod +x to those files. Although I could change to this environment after, no library can be seen. I also get this: chris@chris-amilo ~ $ ./.virtualenvs/iwidget/bin/activate bash: ./.virtualenvs/iwidget/bin/activate: Permission denied Also, the following shows that although I can `workon` on certain env, nothing can be imported: (after I did a chmod +x to preactivate files) chris@chris-amilo ~ $ workon iwidget (iwidget)chris@chris-amilo ~ $ python Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pytz Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named pytz >>> (iwidget)chris@chris-amilo ~ $ ls .virtualenvs/iwidget/lib/python2.7/site-packages/py py4j/ pytz/ py4j-0.8.1-py2.7.egg-info/ pytz-2014.2-py2.7.egg-info/ python_dateutil-2.2-py2.7.egg-info/ How can I fix this? Answer: Moving virtualenvs is tricky. It's a much better bet to rebuild them from scratch on the new machine. If you're using a requirements file, this is trivial: just do `pip install -r requirements.txt`. If you're not using one, create it on the old machine with `pip freeze > requirements.txt`.
Finding all maximal monotone subsequences in python Question: Now trying to figure out how to find all the maximal subsequences(both positive and negative) in sequence. Here I got some troubles, because there is no suitable solution found. I've this code, but the output is ok only for positive numbers. I'm newbie to python so can not figure out in short time how can this be handled. testcase = [1,2,3,4,5,4,3,2,1,0,-1,-2,-3,-2,-1,-2,-1,-2,-3,-4,-5] def process(lst): def sub(lst): temp = [] while lst and (not temp or temp[-1] <= lst[0]): temp.append(lst[0]) lst = lst[1:] return temp, lst res=[] while lst: subres, lst = sub(lst) res.append(subres[0] if len(subres)==1 else subres) return res if __name__ == "__main__": print(process(testcase)) So, the sample output is [[1, 2, 3, 4, 5], 4, 3, 2, 1, 0, -1, -2, [-3, -2, -1], [-2, -1], -2, -3, -4, -5]] While, I want it to be [[1,2,3,4],[5,4,3,2,1,0,-1,-2,-3],[-2,-1],-2,[-1,-2,-3,-4,-5]] So, the question is how can this be done? Answer: You basically need to track the "derivative" (difference between elements), and see when it changes direction. You can express this very cleanly using `numpy`: import numpy as np np_split_indexes= np.where(np.diff(np.diff(testcase))!=0)[0]+2 split_indexes= [0] + list(np_split_indexes) + [len(testcase)] result= [testcase[a:b] for a,b in zip(split_indexes[:-1],split_indexes[1:])] or, if you prefer pure python: result=[] tmp=[] last_direction=0; last_element=0; for x in testcase: direction= (x-last_element)/abs(x-last_element) #math trick - divide by the magnitude to get the direction (-1/1) last_element= x if (direction!=last_direction) and tmp: result.append(tmp) tmp=[] last_direction= direction tmp.append(x) if tmp: result.append(tmp) print result output: [[1, 2, 3, 4, 5], [4, 3, 2, 1, 0, -1, -2, -3], [-2, -1], [-2], [-1], [-2, -3, -4, -5]] Note this differs from your intended output on the end. I'm not sure why you grouped `-1` in the last group, since it's a local maximum.
numpy array equivalent for += operator Question: I often do the following: import numpy as np def my_generator_fun(): yield x # some magically generated x A = [] for x in my_generator_fun(): A += [x] A = np.array(A) Is there a better solution to this which operates on a numpy array from the start and avoids the creation of a standard python list? Note that the += operator allows to extend an empty and dimensionless array with an arbitrarily dimensioned array whereas np.append and np.concatenate demand for equally dimensioned arrays. Answer: Use [`np.fromiter`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html): def f(n): for j in range(n): yield j >>> np.fromiter(f(5), dtype=np.intp) array([0, 1, 2, 3, 4]) If you know beforehand the number of items the iterator is going to return, you can speed things up using the `count` keyword argument: >>> np.fromiter(f(5), dtype=np.intp, count=5) array([0, 1, 2, 3, 4])
Inconsistent Execution Time in Python on all systems Question: Something that's been driving me crazy with python... I used to think it was [just Windows](http://stackoverflow.com/questions/24749808/), but I was wrong. I can have the same exact code and run it multiple times and it executes in wildly different amounts of time. Take the following test code, for example: import math def fib(count): x = 0 while x < count: a = int(((((1 + math.sqrt(5)) / 2) ** x) - (((1 - math.sqrt(5)) / 2) ** (x))) / math.sqrt(5)) x+=1 if __name__ == '__main__': import timeit t = timeit.Timer("fib(1250)", setup="from __main__ import fib",) #print t.timeit(10) count = 10000 results = t.repeat(count, 1) min = 0xFFFF max = 0 sum = 0 for i in results: i = i*1000.0 if i < min: min = i if i > max: max = i sum+=i print "Min {:.3f} | Max {:.3f} | Max/Min {:.3f} | Avg {:.3f}".format(min, max, max/min, sum/count) Basically, it generates the first 1250 elements of fibonacii 10,000 times and uses timeit to get the amount of time each run takes. I then coalesce those times and find min, max, average and variance between min and max (the spread, if you will). Here's the results: Windows: Min 3.071 | Max 8.903 | Max/Min 2.899 | Avg 3.228 Mac OS: Min 1.531 | Max 3.167 | Max/Min 2.068 | Avg 1.621 Ubuntu: Min 1.242 | Max 10.090 | Max/Min 8.123 | Avg 1.349 So, Linux is the fastest but also has the most variance. By a LOT. But all of them can have a pretty wild swing: Only 200% for Mac, but 290% for Windows and 810% for linux! Is it actually taking that much different time to execute? Is timeit not accurate enough? Is there something else I am missing? I'm working a lot with generating animations and I need as consistent time as possible. Answer: You are measuring very short times, and then even a little bit of something happening somewhere has a big impact. I ran your test script on my machine (OS X, Core i7, Python 2.7) and made this plot of `results`: ![enter image description here](http://i.stack.imgur.com/844uk.png) You can see that most of the time the timing results are very consistent, but there are isolated incidents of the algorithm taking much more time (because there is something else happening). * * * I made a tiny adjustment to your timing procedure: results=t.repeat(10, 1000) So, now we are timing runs of 1000 function calls. The total amount of time is the same, naturally (10000 calls): ![enter image description here](http://i.stack.imgur.com/k0LBb.png) Now you can see that the performance is much more predictable. It may be that part of your wobbly timings are due to the timing methodology, not due really different times to carry out anything. Millisecond-level timing is difficult in a real-world OS environment. Even when your computer is "doing nothing", it is still switching tasks, doing background jobs, etc. * * * I understand the original point was not to calculate the Fibonacci numbers. But if it were, then choosing the right tool makes a difference: import numpy as np def fib(count): x = np.arange(count) a = (((1 + np.sqrt(5))/2) ** x - ((1 - np.sqrt(5)) / 2) ** x) / np.sqrt(5) a = a.astype('int') This gives: Min 0.120 | Max 0.471 | Max/Min 3.928 | Avg 0.125 Ten-fold speed improvement. * * * About the images in this answer, they are plotted with `matplotlib`. The first one is done thus: import matplotlib.pyplot as plt # create a figure fig = plt.figure() # create axes into the figure ax = fig.add_subplot(111) # plot the vector results with dots of size 2 (points) and semi-transparent blue color ax.plot(results, '.', c=(0, 0, 1, .5), markersize=2) See the documentation of `matplotlib`. It is easiest to get started by using `IPython` and `pylab`.
Trying to load JSON into d3 treemap without using a GET Question: I am using <http://bost.ocks.org/mike/treemap/> to attempt to incorporate a D3 treemap into Splunk. However, it errors on the d3.JSON("flare.json") as it can't find the file. I have tried putting the JSON array right into the js and calling root = JSON.parse(myjson), but then then it arrays with unexpected character JSON.parse. If you look at the js from Bostick's page, you can see that I can't just remove the d3.JSON, because it calls back to the functions that actually render the treemap. Do you have any ideas on how I can fix this? renderResults: function($super, results) { if(!results) { this.resultsContainer.html('No content available.'); return; } var margin = {top: 20, right: 0, bottom: 0, left: 0}, width = 960, height = 500 - margin.top - margin.bottom, formatNumber = d3.format(",d"), transitioning; var x = d3.scale.linear() .domain([0, width]) .range([0, width]); var y = d3.scale.linear() .domain([0, height]) .range([0, height]); var treemap = d3.layout.treemap() .children(function(d, depth) { return depth ? null : d._children; }) .sort(function(a, b) { return a.value - b.value; }) .ratio(height / width * 0.5 * (1 + Math.sqrt(5))) .round(false); var svg = d3.select("#chart").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.bottom + margin.top) .style("margin-left", -margin.left + "px") .style("margin.right", -margin.right + "px") .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")") .style("shape-rendering", "crispEdges"); var grandparent = svg.append("g") .attr("class", "grandparent"); grandparent.append("rect") .attr("y", -margin.top) .attr("width", width) .attr("height", margin.top); grandparent.append("text") .attr("x", 6) .attr("y", 6 - margin.top) .attr("dy", ".75em"); var myjson = not including the actual array to save space root = JSON.parse(myjson); d3.json("flare.json", function(root) { initialize(root); accumulate(root); layout(root); display(root); function initialize(root) { root.x = root.y = 0; root.dx = width; root.dy = height; root.depth = 0; } // Aggregate the values for internal nodes. This is normally done by the // treemap layout, but not here because of our custom implementation. // We also take a snapshot of the original children (_children) to avoid // the children being overwritten when when layout is computed. function accumulate(d) { return (d._children = d.children) ? d.value = d.children.reduce(function(p, v) { return p + accumulate(v); }, 0) : d.value; } // Compute the treemap layout recursively such that each group of siblings // uses the same size (1×1) rather than the dimensions of the parent cell. // This optimizes the layout for the current zoom state. Note that a wrapper // object is created for the parent node for each group of siblings so that // the parent’s dimensions are not discarded as we recurse. Since each group // of sibling was laid out in 1×1, we must rescale to fit using absolute // coordinates. This lets us use a viewport to zoom. function layout(d) { if (d._children) { treemap.nodes({_children: d._children}); d._children.forEach(function(c) { c.x = d.x + c.x * d.dx; c.y = d.y + c.y * d.dy; c.dx *= d.dx; c.dy *= d.dy; c.parent = d; layout(c); }); } } function display(d) { grandparent .datum(d.parent) .on("click", transition) .select("text") .text(name(d)); var g1 = svg.insert("g", ".grandparent") .datum(d) .attr("class", "depth"); var g = g1.selectAll("g") .data(d._children) .enter().append("g"); g.filter(function(d) { return d._children; }) .classed("children", true) .on("click", transition); g.selectAll(".child") .data(function(d) { return d._children || [d]; }) .enter().append("rect") .attr("class", "child") .call(rect); g.append("rect") .attr("class", "parent") .call(rect) .append("title") .text(function(d) { return formatNumber(d.value); }); g.append("text") .attr("dy", ".75em") .text(function(d) { return d.name; }) .call(text); function transition(d) { if (transitioning || !d) return; transitioning = true; var g2 = display(d), t1 = g1.transition().duration(750), t2 = g2.transition().duration(750); // Update the domain only after entering new elements. x.domain([d.x, d.x + d.dx]); y.domain([d.y, d.y + d.dy]); // Enable anti-aliasing during the transition. svg.style("shape-rendering", null); // Draw child nodes on top of parent nodes. svg.selectAll(".depth").sort(function(a, b) { return a.depth - b.depth; }); // Fade-in entering text. g2.selectAll("text").style("fill-opacity", 0); // Transition to the new view. t1.selectAll("text").call(text).style("fill-opacity", 0); t2.selectAll("text").call(text).style("fill-opacity", 1); t1.selectAll("rect").call(rect); t2.selectAll("rect").call(rect); // Remove the old node when the transition is finished. t1.remove().each("end", function() { svg.style("shape-rendering", "crispEdges"); transitioning = false; }); } return g; } function text(text) { text.attr("x", function(d) { return x(d.x) + 6; }) .attr("y", function(d) { return y(d.y) + 6; }); } function rect(rect) { rect.attr("x", function(d) { return x(d.x); }) .attr("y", function(d) { return y(d.y); }) .attr("width", function(d) { return x(d.x + d.dx) - x(d.x); }) .attr("height", function(d) { return y(d.y + d.dy) - y(d.y); }); } function name(d) { return d.parent ? name(d.parent) + "." + d.name : d.name; } }; } I am still not 100% sure how these two even are able to interact. I have a little JavaScript experience, but no Python experience. The way Splunk integrates all these scripts together is baffling. import cherrypy import controllers.module as module import splunk, splunk.search, splunk.util, splunk.entity import json from splunk.appserver.mrsparkle.lib import jsonresponse import lib.util as util import lib.i18n as i18n import logging logger = logging.getLogger('splunk.module.TreeMap1') import math import cgi class TreeMap1(module.ModuleHandler): def generateResults(self, host_app, client_app, sid, count=1000, offset=0, entity_name='results'): count = max(int(count), 0) offset = max(int(offset), 0) if not sid: raise Exception('TreeMap1.generateResults - sid not passed!') try: job = splunk.search.getJob(sid) except splunk.ResourceNotFound, e: logger.error('TreeMap could not find job %s. Exception: %s' % (sid, e)) return _('<p class="resultStatusMessage">Could not get search data.</p>') dataset = getattr(job, entity_name)[offset: offset+count] outputJSON = {} for i, result in enumerate(dataset): tdict = {} tdict[str(result.get('itemName', None))] = str(result.get('totalCPU', None)) name = str(result.get('itemCat', None)) if name not in outputJSON: outputJSON[name] = dict() outputJSON[name].update(tdict) cherrypy.response.headers['Content-Type'] = 'text/json' return json.dumps(outputJSON, sort_keys=True) def render_json(self, response_data, set_mime='text/json'): cherrypy.response.headers['Content-Type'] = set_mime if isinstance(response_data, jsonresponse.JsonResponse): response = response_data.toJson().replace("</", "<\\/") else: response = json.dumps(response_data).replace("</", "<\\/") return ' ' * 256 + '\n' + response Answer: D3's `d3.JSON(url, ...)` literally performs a GET request and attempts to parse the response as JSON*; it is similar to jQuery's `$.getJSON(url, ...)`. If you already have the JSON necessary to construct the tree map, just ignore the call altogether and go straight to the callback. **If you already have an array/object, you don't need`JSON.parse`**; JSON.parse turns a valid JSON string into an array/object. *See the documentation on [d3.json](https://github.com/mbostock/d3/wiki/Requests) for more... Along the same lines, if you already have the data, you can just use: ... var myJSON = [ ... ] //The actual array you're loading. initialize(myJSON); accumulate(myJSON); layout(myJSON); display(myJSON); ... **However,** notice what you're actually doing in the code above. You're passing an _array_ into `initialize` \-- which appears to want an _object_ : function initialize(root) { //Root in this case is myVar -- an ARRAY. root.x = root.y = 0; //Arrays don't have fields. This is BAD. root.dx = width; root.dy = height; root.depth = 0; } Thus, what you should do is figure out what type of structure `myJSON` should use. * * * If the error that you want to fix is actually that the "flare.json" file can't be found, then your problem is actually _server-side_. How are you serving the flare.json file? Try accessing it in your browser to make sure it is located where you think it is.
Hashlib md5 in python returning incorrect digests for some unicode characters? Question: I have been playing around with python's and Java's MD5 implementation and encountered this quirk that's been puzzling me. The following python script illustrates the problem: # -*- coding: utf-8 -*- import hashlib def md5hash(x): m = hashlib.md5() m.update(x) return m.hexdigest() print md5hash('\xdb') print md5hash('Û') Output: 98fd00d788afe2a5fa5e4f8e1666638b 31ecfb09f120720a55d96a2034f5d00b I expected the two digests to be equivalent, given that `Û` ought to be equivalent to `\xdb`. I built an equivalent implementation in Java to get some more insight: import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Test { public static void main(String[] args) throws Exception { MessageDigest m = MessageDigest.getInstance("MD5"); m.update("\u00db".getBytes()); System.out.println(bytesToHex(m.digest())); m.update("Û".getBytes()); System.out.println(bytesToHex(m.digest())); } final protected static char[] hexArray = "0123456789abcdef".toCharArray(); public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } } Output: 31ecfb09f120720a55d96a2034f5d00b 31ecfb09f120720a55d96a2034f5d00b The output of Java is consistent, as expected. This is leading me to believe that `md5hash('\xdb')` is outputting an incorrect result, but I am not sure what it is that I'm missing. Any thoughts? Answer: Your assumptions are incorrect. You started your Python source code with: # -*- coding: utf-8 -*- `Û` is **not** equivalent to `\xdb` in that case; it is instead two bytes: >>> u'Û'.encode('utf8') '\xc3\x9b' Python is entirely consistent here: >>> import hashlib >>> hashlib.md5('\xc3\x9b').hexdigest() '31ecfb09f120720a55d96a2034f5d00b' >>> hashlib.md5('\xdb').hexdigest() '98fd00d788afe2a5fa5e4f8e1666638b' In Java you started with a Unicode codepoint instead, converting that to UTF-8 bytes: "\u00db".getBytes() The Python equivalent would be to use a `unicode` string literal and either a `\uhhhh` or `\xhh` escape sequence: >>> u'\u00db'.encode('utf8') '\xc3\x9b' >>> u'\xdb'.encode('utf8') '\xc3\x9b' Note the `u` prefix to produce a `unicode` string. `\xdb` without a `u` prefix is a _byte string_ , not a Unicode codepoint, and only if you were to decode it as _Latin 1_ would you get the same Unicode string: >>> '\xdb'.decode('latin1') u'\xdb' >>> '\xdb'.decode('latin1').encode('utf8') '\xc3\x9b' You probably want to study up on Python and Unicode; see: * The [Python Unicode HOWTO](http://docs.python.org/2/howto/unicode.html) * [Pragmatic Unicode](http://nedbatchelder.com/text/unipain.html) by Ned Batchelder and for completeness sake: * [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](http://joelonsoftware.com/articles/Unicode.html) by Joel Spolsky
How to collect the value corresponding to a field of an array/list of named tuples Question: I am new to Python, in the process of migrating from MATLAB. I was using the `namedtuple` class the following way. from collections import namedtuple import numpy as np MyStruct = namedtuple("MyStruct", "field1 field2 field3") d = [] d.append(MyStruct(field1=np.array(3,'int'),field2=np.array(4,'int'),field3=np.array(5,'int'))) d d.append(MyStruct(field1=np.array(4,'int'),field2=np.array(5,'int'),field3=np.array(6,'int'))) Here `d` is a 2-element list of `namedtuple` objects. What I want is to obtain an array of all `field1` values through all the elements of `d` in a nifty way without the need to iterate through the elements of `d`. Something similar to MATLAB, where we put square brackets around an array of structures. I'd appreciate any insights into this matter. Srini Answer: This is what list comprehensions are for: field1vals = [x.field1 for x in d]
Python Dict from CSV IndexError Question: I need to compare 2 CSV files and I am trying to use the @Martijn Pieters solution at [Python: Comparing two CSV files and searching for similar items](http://stackoverflow.com/questions/5268929/python-comparing-two-csv- files-and-searching-for-similar-items) but I am running into an error: IndexError: list index out of range Here is the code I am using, import csv with open('filename.csv', 'rb') as a: indices = dict((r[2], i) for i, r in enumerate(csv.reader(a))) print indices filename.csv has 10 columns and 2000 rows. I want to index column 3 that has hostnames and then match with hostnames in other .csv file type,id,hostname,os,,,, phy,123,server1,rhel5,,,, vir,234,server2,rhel6,,,, I am not sure why I am getting IndexError. Please help to fix the problem. Answer: You probably have empty lines at the start or end of your csv file. I was able to reproduce this error with the following code: import csv with open('filename.csv', 'wb') as a: strng = """ type,id,hostname,os,,,, phy,123,server1,rhel5,,,, vir,234,server2,rhel6,,,, """ a.write(strng) with open('filename.csv', 'rb') as a: indices = dict((r[2], i) for i, r in enumerate(csv.reader(a))) print indices However when I removed those blank lines, the code runs perfectly : import csv with open('filename.csv', 'wb') as a: strng = """type,id,hostname,os,,,, phy,123,server1,rhel5,,,, vir,234,server2,rhel6,,,, """ a.write(strng) with open('filename.csv', 'rb') as a: indices = dict((r[2], i) for i, r in enumerate(csv.reader(a))) print indices Refer to this [SO Answer](http://stackoverflow.com/a/18891114/3244627) on how to skip blank lines in csv.
progressbar in Tkinter with a label inside Question: Is It possible to improve my progressbar in Tkinter-Python adding a label in the middle (ex: reading file)? I tried to find a elegant coding solution but without a real result from Tkinter import * import ttk import tkFileDialog import time class MainWindow(Frame): def __init__(self): Frame.__init__(self) self.master.title("ProgressBar example") self.master.minsize(200, 100) self.grid(sticky=E+W+N+S) top = self.winfo_toplevel() top.rowconfigure(0, weight=1) top.columnconfigure(0, weight=1) self.start_ind = Button(self, text='Start indeterminate', command=self.start_ind, activeforeground="red") self.start_ind.grid(row=0, column=0, pady=2, padx=2, sticky=E+W+N+S) self.pbar_ind = ttk.Progressbar(self, orient="horizontal", length=300, mode="indeterminate") self.pbar_ind.grid(row=1, column=0, pady=2, padx=2, sticky=E+W+N+S) def start_ind(self): for i in xrange(50): self.pbar_ind.step(1) self.update() # Busy-wait time.sleep(0.1) if __name__=="__main__": d = MainWindow() d.mainloop() Answer: Have you tried creating a text Label and putting it in the same row/column and setting it the same size like so: self.Lab = Label(self,length=200) self.Lab.grid(row=1,column=0,pady=2,padx=2,sticky=E+W+N+S)) But you would want to put it after the progress bar widget.
Is there a built-in Django template filter that finds the first value in a list to satisfy a condition? Question: In a Django template, how do I return the first element of a list that matches a condition? The list could be empty. I want to know if there is a filter that finds the first element in an iterable to match a particular condition, then stops checking, similar to Python's [next](https://docs.python.org/2/library/functions.html#next) (<http://stackoverflow.com/a/2364277/1337422>). >>> lis = ['a', 1, 40, 'three', 5] >>> next(x for x in lis if x == 1) 1 Answer: There isn't a built in Django template filter that does this. If it is a particular condition you want to match, then it would be easy to write a [custom template filter](https://docs.djangoproject.com/en/dev/howto/custom-template- tags/#writing-custom-template-filters). For example: from django import template register = template.Library() @register def first_one_in_list(l): return next((x for x in l if x==1), default=None) # specify default to avoid stop iteration If you want to specify an arbitrary condition in the template, I think you'd need to do something hacky. The Django template language is designed to prevent complex logic in templates.
Importing modules Python Question: Hey I am having some trouble figuring out what is being asked to import in this code #!/opt/local/bin/python import sys from formatter import Formatter def main(): #do stuff in my class formatter.py, do I have had to define a function with a name Formatter. A little confused on this. I have been testing my code by putting from formatter import * Which takes all the definitions in my class(I believe). Answer: your line `from formatter import Formatter` will search through the module formatter for anything with the name `Formatter`. so if you had a function called `Formatter` in that module, it would be imported, meaning you could use it in your main section (anywhere below the import line will work) It will import classes as well. `formatter.py` is a module. a class might look something like: class A: variable = 1 def b(): #do stuff
Syntax error with wexpect Question: I did download the latest copy of `wexpect` from github and placed it in the site-packages folder of my working directory for python. I also installed the py32 packages as instructed. When I try to run the `import wexpect` command from IDLE I get the following error message import wexpect Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python34\lib\site-packages\wexpect.py", line 94 except ImportError, e: ^ SyntaxError: invalid syntax Could you please give me some pointers as to how to debug. Answer: You're running the app using Python 3, while the syntax `except ImportError, e:` is for Python 2. In Python 3, it's `except ImportError as e:`. If it's a library code, either search for the latest version of the library for Python 3, or run it using Python 2 otherwise.
Image searching system using Bag Of Features method Question: I am doing a project making visual search system using Bag Of Features method but have little question. If I understood the method correctly, the method has few steps. 1. Feature extraction from an image 2. Vector quantization 3. Image searching from a database I am stock at between 2 and 3. I use python package called scikit-learn to quantize the feature vectors extracted using SIFT algorithm in opencv. For now, I set the cluster size 8 with default setting. I tried to generate histogram out of the output codebook and display it. I tried this with same image several times but all the histograms looked different. The code is below. It is a simple code. import cv2 import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans def feature_extract(img): sift = cv2.SIFT() gray = img kp, des = sift.detectAndCompute(gray, None) return kp, des def codebook(k, des): km = KMeans(n_clusters=k, max_iter=500) km.fit(des) codebook = km.cluster_centers_ label = km.labels_ return codebook, label img = cv2.imread('sift_example.jpg', 0) kp, des = feature_extract(img) k = 8 codebook, label = codebook(k, des) plt.hist(label, bins=range(0,9), align='left'), plt.show() I suspect that the problem come from the clustering error. Since the initial centers for clustering is set to random, the final converged centers are different. Is there any solution to this? Answer: You are right about the randomness of KMeans initial centers, but I would assume that if you dont explicitely change the initial seed of the random number generator, then it would always pick the same "random" features as initial centers. Another reason could be that, if feature detection/extraction is multithreaded, the features computed on your image can appear in different orders between each run. You might check that aswell. Alternatively, you can pass your own centers to KMeans as initial centroids so you could pick them or generate them by yourself to make sure KMeans starts with always the same initial centers
Python: "import JSON... json.loads(request.body)" 2.7->3.4 Question: I recently converted a django server to python version 3.4.1 from python version 2.7. My request.body is an array serialized to JSON. When de- serialized it will be a python list. Unfortunately, it would seem that json.loads no longer takes raw bytes (which is what request.body is). How can I fix this issue? def index(request): if request.method == 'POST': print("Made it here!") registered = [] notRegistered = [] print("Is it this?") print(repr(request.body)) data = json.loads(request.body) print("Did I make it here?") The last call to print never executes, which is why I'm assuming it has to do with json.loads() Answer: I would expect a traceback to occur rather than just "the last line never executing", but that aside... # Let's just assume the request is UTF-8 encoded. data = json.loads(request.body.decode('utf-8'))
How to assign a value to a radiobutton in pyqt? Question: I want to assign a value to a radiobutton when it is checked. def radiobutton8(self): if self.radioButton_8.isChecked(): self.radioButton_8 = 02 However, this cannot work. Any solution? UPDATE: My code has been edited to be: class MyRadioButton(QtGui.QRadioButton): def __init__(self): super(MyRadioButton, self).__init__() self.value = None def SetValue(self, val): self.value = val def GetValue(self): return self.value class UserTool(QtGui.QDialog): def setup(self, Dialog): ... self.radioButton_8.toggled.connect(self.radiobutton8) def retranslateUi(self, Dialog): ... self.radioButton_8 = MyRadioButton() self.radioButton_8.setText(_translate("Dialog", "A1", None)) def radiobutton8(self): if self.radioButton_8.isChecked(): value = self.radioButton_8.setValue("02") self.lcdNumber.display(value) However, my original text 'A1' for the radio button is now missing and my number still does not appear on my lcd when checked. Any idea why? UPDATE: I edited my code to be something like that: class MyRadioButton(QtGui.QRadioButton): def __init__(self): super(MyRadioButton, self).__init__() self.value = None def SetValue(self, val): self.value = val def GetValue(self): return self.value class UserTool(QtGui.QDialog): def setup(self, Dialog): ... self.lcdNumber = QtGui.QLCDNumber(Dialog) self.lcdNumber.setGeometry(QtCore.QRect(590, 10, 71, 23)) self.lcdNumber.setFrameShadow(QtGui.QFrame.Raised) self.lcdNumber.setObjectName(_fromUtf8("lcdNumber")) self.lcdNumber.setStyleSheet("* {background-color: black; color: white;}") self.lcdNumber.display('00') self.radioButton_8 = QtGui.QRadioButton(Dialog) self.radioButton_8.setGeometry(QtCore.QRect(460, 10, 82, 17)) self.radioButton_8.setChecked(False) self.radioButton_8.setAutoExclusive(False) self.radioButton_8.setObjectName(_fromUtf8("radioButton_8")) self.radioButton_8 = MyRadioButton() self.radioButton_8.setText("A1") self.radioButton_8.setValue(02) self.radioButton_8.toggled.connect(self.showValueFromRadioButtonToLCDNumber) def showValueFromRadioButtonToLCDNumber(self): value = self.radioButton_8.GetValue() if self.radioButton_8.isChecked(): self.lcdNumber.display(value) And then now I have this error: Traceback (most recent call last): File "C:/Users/Vivien Phua/Documents/Python Scripts/Rs232.py", line 303, in handleOpenWidget self.popup = UserTool() File "C:/Users/Vivien Phua/Documents/Python Scripts/Rs232.py", line 39, in __init__ self.setup(self) File "C:/Users/Vivien Phua/Documents/Python Scripts/Rs232.py", line 153, in setup self.radioButton_8.setValue(02) AttributeError: 'MyRadioButton' object has no attribute 'setValue' I have also tried the code you have given me and there is no such error, but the LCD in your code does not show the value 02. Answer: Do you mean text value next to radioButton? if so, here is solution: def radiobutton8(self): if self.radioButton_8.isChecked(): self.radioButton_8.setText("02") **EDIT1** : radioButton doesn't have value field as you need. However, you can write your own radiobButton class that inherits original QRadioButton, and add that field. Example: class MyRadioButton(QtGui.QRadioButton): def __init__(self): super(MyRadioButton, self).__init__() self.value = None def SetValue(self, val): self.value = val def GetValue(self): return self.value and use it like this: self.radioButton_8 = MyRadioButton() self.radioButton_8.setText("some text") ... def radiobutton8(self): if self.radioButton_8.isChecked(): self.radioButton_8.SetValue("02")# or .SetValue(2) if you want it to be integer **EDIT2** # -*- coding: utf-8 -*- import sys from PyQt4 import QtCore, QtGui from PyQt4.QtCore import Qt class MyRadioButton(QtGui.QRadioButton): def __init__(self): super(MyRadioButton, self).__init__() self.value = None def SetValue(self, val): self.value = val def GetValue(self): return self.value class Widget(QtGui.QWidget): def __init__(self): super(Widget, self).__init__() self.layout = QtGui.QVBoxLayout(self) self.pushButton_7 = QtGui.QPushButton("if RB is checked, show it's value to LCD") self.pushButton_7.setGeometry(QtCore.QRect(220, 650, 75, 23)) self.pushButton_7.clicked.connect(self.showValueFromRadioButtonToLCDNumber) self.radioButton = MyRadioButton() self.radioButton.setText("some text") self.radioButton.SetValue("02")# somewhere in code first set value to radio button self.lcdNumber = QtGui.QLCDNumber() self.layout.addWidget(self.pushButton_7) self.layout.addWidget(self.radioButton) self.layout.addWidget(self.lcdNumber) def showValueFromRadioButtonToLCDNumber(self): value = self.radioButton.GetValue() if self.radioButton.isChecked(): self.lcdNumber.display(value) if __name__ == '__main__': app = QtGui.QApplication([]) w = Widget() w.show() sys.exit(app.exec_())
POST to .jsp website with Python requests library Question: I'm using Python 3.3 and Requests 2.2.1. I'm trying to POST to a website ending in .jsp, which then changes to .doh ending. Using the same basic requests code outline I'm able to successfully login and scrape other websites, but the javascript part on this site is not working. This is my code: import requests url = 'https://prodpci.etimspayments.com/pbw/include/sanfrancisco/input.jsp' payload = {'plateNumber':'notshown', 'statePlate':'CA'} #tried CA and California s = requests.Session() #Tried 'session' and 'Session' following different advice post = s.post(url, data=payload) r = s.get('https://prodpci.etimspayments.com/pbw/include/sanfrancisco/input.jsp') print(r.text) Finally, when manually entering data into the webpage through firefox browser, the page changes and url becomes <https://prodpci.etimspayments.com/pbw/inputAction.doh>, which only has contet if you are redirected there after typing in license plate. From the printed text, I know I'm getting content from the page as it would be without POSTing anything, but I need the content for the page once I've POSTed the payload. For the POST payload, do I need to include something like 'submit':'submit' to simulate clicking the search button? Am I doing the GET request from the right url, considering the url I POST to? Answer: You're making POST request and after that another GET request and this is why you get the same page with the form. response = s.post(url, data=payload) print(response.text) Also if you check the form markup, you'll find its action is `/pbw/inputAction.doh` and additionally the form sends a few parameters from `hidden` inputs. Therefore you should use that URL in your request and probably the values from `hidden` inputs. ![enter image description here](http://i.stack.imgur.com/9ZZbA.png) With the next code I'm able to retrieve the same response as via regular request in browser: import requests url = 'https://prodpci.etimspayments.com/pbw/inputAction.doh' payload = { 'plateNumber': 'notshown', 'statePlate': 'CA', 'requestType': 'submit', 'clientcode': 19, 'requestCount': 1, 'clientAccount': 5, } s = requests.Session() response = s.post(url, data=payload) print(response.text) The same you can see in browser after same request via the form: ... <td colspan="2"> <li class="error">Plate is not found</li></td> ...
Why can't I catch SIGINT when asyncio event loop is running? Question: Using Python 3.4.1 on Windows, I've found that while executing an [asyncio event loop](https://docs.python.org/3/library/asyncio.html), my program can't be interrupted (i.e. by pressing Ctrl+C in the terminal). More to the point, the SIGINT signal is ignored. Conversely, I've determined that SIGINT is handled when not in an event loop. Why is it that SIGINT is ignored when executing an asyncio event loop? The below program should demonstrate the problem - run it in the terminal and try to stop it by pressing Ctrl+C, it should keep running: import asyncio import signal # Never gets called after entering event loop def handler(*args): print('Signaled') signal.signal(signal.SIGINT, handler) print('Event loop starting') loop = asyncio.SelectorEventLoop() asyncio.set_event_loop(loop) loop.run_forever() print('Event loop ended') See [discussion](https://groups.google.com/forum/#!topic/python- tulip/pr9fgX8Vh-A) on official (Tulip) mailing list. Answer: I've found a workaround, which is to schedule a periodic callback. While this running, SIGINT is apparently processed: import asyncio def wakeup(): # Call again loop.call_later(0.1, wakeup) print('Event loop starting') loop = asyncio.SelectorEventLoop() # Register periodic callback loop.call_later(0.1, wakeup) asyncio.set_event_loop(loop) loop.run_forever() print('Event loop ended') Not sure why this is necessary, but it indicates that signals are blocked while the event loop waits for events ("polls"). The matter has been [discussed](https://groups.google.com/forum/#!topic/python-tulip/pr9fgX8Vh-A) on the official (Tulip) mailing list, my workaround is apparently the way to go as of now. ## Update A fix has supposedly [made its way into Python 3.5](https://code.google.com/p/tulip/issues/detail?id=191), so hopefully my workaround will be made obsolete by that Python version.
Copy IPython's pretty printing of results Question: When displaying results in [IPython](https://github.com/ipython) (without using `print()`), nested objects gets an easy-to-view formatting. Is there a way to create/copy a function in Python with the same pretty formatting functionalities as IPython uses? I have been trying to look through their code for a possible module to import, but it seems like an impossible task. Would it be possible to write one yourself? IPython example: In [1]: {'Mario': {'Stats': [63, 10, 69, 24, 82], 'Result': [(2, 7, 5, {'ids': [46737432927499418861568L, 61421050754327147184128L, 46239274047769245908992L]})]}, 'Luigi': {'Results': [(7, 9, 6, {'ids': [20471482889415933558784L, 87284089722223609249792L, 27117156251036496691200L]})], 'Stats': [14, 71, 93, 49, 53]}} Out[1]: {'Luigi': {'Results': [(7, 9, 6, {'ids': [20471482889415933558784L, 87284089722223609249792L, 27117156251036496691200L]})], 'Stats': [14, 71, 93, 49, 53]}, 'Mario': {'Result': [(2, 7, 5, {'ids': [46737432927499418861568L, 61421050754327147184128L, 46239274047769245908992L]})], 'Stats': [63, 10, 69, 24, 82]}} **[EDIT]** I know of the `pprint` module, but it does not do indentations the same way as IPython does (I don't want the indentation level of child elements to be dependent on their parent). What `pprint` outputs: {'Luigi': {'Results': [(7, 9, 6, {'ids': [20471482889415933558784L, 87284089722223609249792L, 27117156251036496691200L]})], 'Stats': [14, 71, 93, 49, 53]}, 'Mario': {'Result': [(2, 7, 5, {'ids': [46737432927499418861568L, 61421050754327147184128L, 46239274047769245908992L]})], 'Stats': [63, 10, 69, 24, 82]}} Answer: Try the [pprint](https://docs.python.org/3/library/pprint.html) module. Usually simply using `from pprint import pprint` and then using `pprint()` instead of `print()` can get you decent results; its output can be customized as well if you read over the module docs.
Running shell command in python and reading output Question: I have the following: cmd = "ps aux | grep 'java -jar' | grep -v grep | awk '//{print $2}'".split(' ') p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() print out When I run the command in the console (outside of python), I get the desired output. Running this above code in python prints a blank line. I am assuming there is something up with the `cmd` (specifically the `|` operator) but I can't be sure. I need to achieve this with the standard Python 2.6.6 install (no additional modules) Answer: You need to use a single call to `Popen()` for each piece of the original command, as connected by the pipe, as in import subprocess p1 = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) p2 = subprocess.Popen(["grep", "java -jar"], stdin=p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p3 = subprocess.Popen(["grep", "-v", "grep"], stdin=p2.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p4 = subprocess.Popen(["awk", "//{print $2}"], stdin=p3.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p4.communicate() print out The [subprocess documentation](https://docs.python.org/2/library/subprocess.html#replacing- shell-pipeline) has an in-depth discussion.
python run redis error when crontab shell Question: i install redis-2.7.1 in my folder,and run my python code,it worked. COMMON_MODEL_DIR="/data/aa/redis-2.7.1" sys.path.append(COMMON_MODEL_DIR) import redis And when i set up crontab , */10 1-23 * * * (cd /data3/aa/; python step.py 2 >> /data3/aa/2.log 2>&1) But it won't worked it will report Traceback (most recent call last): File "step.py", line 11, in ? import redis File "/data/aa/redis-2.7.1/redis/__init__.py", line 1, in ? from redis.client import Redis, StrictRedis File "/data/aa/redis-2.7.1/redis/client.py", line 157 response = [nativestr(i) if i is not None else None for i in response] ^ SyntaxError: invalid syntax How will i fix it? Answer: Obviously the user account under which your cron job is running is using another (and quite old) Python version that doesn't support ternary expressions. Find out which Python _you_ are using and pass the full path in your crontab.
Python realtime plotting Question: I acquire some data in two arrays: one for the time, and one for the value. When I reach 1000 points, I trigger a signal and plot these points (x=time, y=value). I need to keep on the same figure the previous plots, but only a reasonable number to avoid slowing down the process. For example, I would like to keep 10,000 points on my graph. The matplotlib interactive plot works fine, but I don't know how to erase the first points and it slows my computer very quickly. I looked into matplotlib.animation, but it only seems to repeat the same plot, and not really actualise it. I'm really looking for a light solution, to avoid any slowing. As I acquire for a very large amount of time, I erase the input data on every loop (the 1001st point is stored in the 1st row and so on). Here is what I have for now, but it keeps all the points on the graph: import matplotlib.pyplot as plt def init_plot(): plt.ion() plt.figure() plt.title("Test d\'acqusition", fontsize=20) plt.xlabel("Temps(s)", fontsize=20) plt.ylabel("Tension (V)", fontsize=20) plt.grid(True) def continuous_plot(x, fx, x2, fx2): plt.plot(x, fx, 'bo', markersize=1) plt.plot(x2, fx2, 'ro', markersize=1) plt.draw() I call the init function once, and the continous_plot is in a process, called every time I have 1000 points in my array. Answer: The lightest solution you may have is to replace the X and Y values of an existing plot. (Or the Y value only, if your X data does not change. A simple example: import matplotlib.pyplot as plt import numpy as np import time fig = plt.figure() ax = fig.add_subplot(111) # some X and Y data x = np.arange(10000) y = np.random.randn(10000) li, = ax.plot(x, y) # draw and show it fig.canvas.draw() plt.show(block=False) # loop to update the data while True: try: y[:-10] = y[10:] y[-10:] = np.random.randn(10) # set the new data li.set_ydata(y) fig.canvas.draw() time.sleep(0.01) except KeyboardInterrupt: break This solution is quite fast, as well. The maximum speed of the above code is 100 redraws per second (limited by the `time.sleep`), I get around 70-80, which means that one redraw takes around 4 ms. But YMMV depending on the backend, etc.
xpath in python does not grab entire HTML block Question: I am using scrapy to scrape information off of a website. My xpath is working but it does not grab information from block. Python code: sel.xpath('//div[@class="content"]/div/blockquote/node()').extract()[0] I am using this to grab the first blockquote on the page. It cuts off after there is a `<br>`. For example: If I can see this: <blockquote class="postcontent restore "> 4th Generation Intel Core i7-4710HQ Processor (2.50GHz 1600MHz 6MB) <br> Operating System <br> Windows 8.1 64 <br> Display </blockquote> It will only return: > 4th Generation Intel Core i7-4710HQ Processor (2.50GHz 1600MHz 6MB) But I would prefer it return everything, including html tags and the rest of the text in blockquote. Answer: `//div[@class="content"]/div/blockquote/node()` will get you all nodes just under _a_ `blockquote`, children text nodes and element nodes. In your case, you'll get the text nodes and the `<br>`s `sel.xpath('//div[@class="content"]/div/blockquote/node()').extract()[0]` will extract only the 1st node, which is the text node with "4th Generation Intel Core i7-4710HQ Processor (2.50GHz 1600MHz 6MB)" Here's a sample ipython session to show different outputs using selectors: $ ipython Python 2.7.6 (default, Mar 22 2014, 22:59:56) Type "copyright", "credits" or "license" for more information. IPython 1.2.1 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: import scrapy In [2]: selector = scrapy.selector.Selector(text="""<blockquote class="postcontent restore "> ...: 4th Generation Intel Core i7-4710HQ Processor (2.50GHz 1600MHz 6MB) ...: <br> ...: Operating System ...: <br> ...: Windows 8.1 64 ...: <br> ...: Display ...: </blockquote>""") In [3]: selector.xpath('blockquote/node()').extract() Out[3]: [] In [4]: selector.xpath('.//blockquote/node()').extract() Out[4]: [u'\n4th Generation Intel Core i7-4710HQ Processor (2.50GHz 1600MHz 6MB)\n', u'<br>', u'\nOperating System\n', u'<br>', u'\nWindows 8.1 64\n', u'<br>', u'\nDisplay\n'] In [5]: selector.xpath('.//blockquote').extract() Out[5]: [u'<blockquote class="postcontent restore ">\n4th Generation Intel Core i7-4710HQ Processor (2.50GHz 1600MHz 6MB)\n<br>\nOperating System\n<br>\nWindows 8.1 64\n<br>\nDisplay\n</blockquote>'] In [6]: selector.xpath('string(.//blockquote)').extract() Out[6]: [u'\n4th Generation Intel Core i7-4710HQ Processor (2.50GHz 1600MHz 6MB)\n\nOperating System\n\nWindows 8.1 64\n\nDisplay\n'] In [7]: selector.xpath('.//blockquote//text()').extract() Out[7]: [u'\n4th Generation Intel Core i7-4710HQ Processor (2.50GHz 1600MHz 6MB)\n', u'\nOperating System\n', u'\nWindows 8.1 64\n', u'\nDisplay\n'] In [8]: "\n".join(selector.xpath('.//blockquote//text()').extract()) Out[8]: u'\n4th Generation Intel Core i7-4710HQ Processor (2.50GHz 1600MHz 6MB)\n\n\nOperating System\n\n\nWindows 8.1 64\n\n\nDisplay\n' In [9]: * * * After OP's comment, a good fit would be `(//div[@class="content"]/div/blockquote)[1]//text()` Using the OP's original input page: $ scrapy shell http://forums.redflagdeals.com/dominos-pizza-50-off-july-14th-20th-1505545/ 2014-07-16 20:43:45+0200 [scrapy] INFO: Scrapy 0.24.2 started (bot: scrapybot) 2014-07-16 20:43:45+0200 [scrapy] INFO: Optional features available: ssl, http11, boto 2014-07-16 20:43:45+0200 [scrapy] INFO: Overridden settings: {'LOGSTATS_INTERVAL': 0} 2014-07-16 20:43:45+0200 [scrapy] INFO: Enabled extensions: TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState 2014-07-16 20:43:46+0200 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats 2014-07-16 20:43:46+0200 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware 2014-07-16 20:43:46+0200 [scrapy] INFO: Enabled item pipelines: 2014-07-16 20:43:46+0200 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023 2014-07-16 20:43:46+0200 [scrapy] DEBUG: Web service listening on 127.0.0.1:6080 2014-07-16 20:43:46+0200 [default] INFO: Spider opened 2014-07-16 20:43:47+0200 [default] DEBUG: Crawled (200) <GET http://forums.redflagdeals.com/dominos-pizza-50-off-july-14th-20th-1505545/> (referer: None) [s] Available Scrapy objects: [s] crawler <scrapy.crawler.Crawler object at 0x7f63775b0c10> [s] item {} [s] request <GET http://forums.redflagdeals.com/dominos-pizza-50-off-july-14th-20th-1505545/> [s] response <200 http://forums.redflagdeals.com/dominos-pizza-50-off-july-14th-20th-1505545/> [s] settings <scrapy.settings.Settings object at 0x7f6377c4fd90> [s] spider <Spider 'default' at 0x7f6376d52bd0> [s] Useful shortcuts: [s] shelp() Shell help (print this help) [s] fetch(req_or_url) Fetch request (or URL) and update local objects [s] view(response) View response in a browser In [1]: response.xpath('//div[@class="content"]/div/blockquote') Out[1]: [<Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>, <Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>, <Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>, <Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>, <Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>, <Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>, <Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>, <Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>, <Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>, <Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>, <Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>, <Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>, <Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>, <Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>, <Selector xpath='//div[@class="content"]/div/blockquote' data=u'<blockquote class="postcontent restore "'>] In [2]: response.xpath('(//div[@class="content"]/div/blockquote)[1]') Out[2]: [<Selector xpath='(//div[@class="content"]/div/blockquote)[1]' data=u'<blockquote class="postcontent restore "'>] In [3]: response.xpath('(//div[@class="content"]/div/blockquote)[1]//text()') Out[3]: [<Selector xpath='(//div[@class="content"]/div/blockquote)[1]//text()' data=u'\r\n\t\t\t\tGot a coupon that stated 50% off a'>, <Selector xpath='(//div[@class="content"]/div/blockquote)[1]//text()' data=u'\r\n'>, <Selector xpath='(//div[@class="content"]/div/blockquote)[1]//text()' data=u'\r\nCode is CAG5014'>, <Selector xpath='(//div[@class="content"]/div/blockquote)[1]//text()' data=u'\r\n'>, <Selector xpath='(//div[@class="content"]/div/blockquote)[1]//text()' data=u'\r\nDeal is on! '>, <Selector xpath='(//div[@class="content"]/div/blockquote)[1]//text()' data=u'\r\n'>, <Selector xpath='(//div[@class="content"]/div/blockquote)[1]//text()' data=u'\r\n'>, <Selector xpath='(//div[@class="content"]/div/blockquote)[1]//text()' data=u"Don't Forget to tip driver!!">, <Selector xpath='(//div[@class="content"]/div/blockquote)[1]//text()' data=u'\r\n'>, <Selector xpath='(//div[@class="content"]/div/blockquote)[1]//text()' data=u'\r\n'>, <Selector xpath='(//div[@class="content"]/div/blockquote)[1]//text()' data=u'\r\n\t\t\t'>] In [4]: response.xpath('string((//div[@class="content"]/div/blockquote)[1])').extract() Out[4]: [u"\r\n\t\t\t\tGot a coupon that stated 50% off any pizza at menu price. \r\n\r\nCode is CAG5014\r\n\r\nDeal is on! \r\n\r\nDon't Forget to tip driver!!\r\n\r\n\r\n\t\t\t"] In [5]: response.xpath('normalize-space((//div[@class="content"]/div/blockquote)[1])').extract() Out[5]: [u"Got a coupon that stated 50% off any pizza at menu price. Code is CAG5014 Deal is on! Don't Forget to tip driver!!"] In [6]:
Comparing two csv files in Python Question: I have this program that takes two csv files into consideration. It looks at "testclaims" (one column many rows) and sees if any words in "masterlist"(one column, many rows) are within the rows of "testclaims." If the rows in "testclaims" contains any word in "masterlist" it will list it into a new .csv file called "output." This part of the program works great. The part that I can't seem to figure out is to output all the remaining rows in "testclaims" that don't contain ANY words in "masterlist" into another csv called "output2" I would think that the last two lines of my code should get this to work, but it's not outputting what I want. I hope I've explained this clearly enough. Here's my code: import csv with open("testclaims.csv") as file1, open("masterlist.csv") as file2, open("stopwords.csv") as file3,\ open("output.csv", "wb+") as file4, open("output2.csv", "wb+") as file5: writer = csv.writer(file4) writer2 = csv.writer(file5) key_words = [word.strip() for word in file2.readlines()] stop_words = [word.strip() for word in file3.readlines()] internal_stop_words = [' a ', ' an ', ' and ', 'as ', ' at ', ' be ', 'ed ', 'ers ', ' for ',\ ' he ', ' if ', ' in ', ' is ', ' it ', ' of ', ' on ', ' to ', 'her ', 'hers '\ ' do ', ' did ', ' a ', ' b ', ' c ', ' d ', ' e ', ' f ', ' g ', ' h ', ' i ',\ ' j ', ' k ', ' l ', ' m ', 'n ', ' n', ' nc ' ' o ', ' p ', ' q ', ' r ', ' s ',\ ' t ', ' u ', ' v ', ' w ', ' x ', ' y ', 'z ', ',', '"', 'ers ', ' th ', ' gc ',\ ' so ', ' ot ', ' ft ', ' ow ', ' ir ', ' ho ', ' er ', ] for row in file1: row = row.strip() row = row.lower() for stop in stop_words: if stop in row: row = row.replace(stop," ") for stopword in internal_stop_words: if stopword in row: row = row.replace(stopword," ") for key in key_words: if key in row: writer.writerow([key, row]) elif key not in row: writer2.writerow([row]) What output2 is outputting is every row in "testclaims" repeated multiple times. For example if "testclaims" contains this one column: Happy Sad Angry Dog Cat "output2" is outputting a csv that prints this one column: Happy Happy Happy Happy Happy Sad Sad Sad Sad Angry Angry Angry Angry Angry Dog Dog Dog Dog Dog Cat Cat Cat Cat Cat And it doesn't output the same number of each row either. Answer: you have a double for loop and each time you print the row, but you only want it at most once per row. you should adjust your last two lines: for row in file1: ... for key in key_words: if key in row: writer.writerow([key, row]) if not any(key in row for key in key_words): writer2.writerow([row])
ValueError: invalid literal for float(): Timestep: Question: I have a program that finds some data and runs a basic math function on the data, but when I run it I get the following error: `ValueError: invalid literal for float(): Timestep:`. The error occurs in line where I call `map(float,line.split()[1:])`. Does anyone know why and how to fix this error. #!/usr/bin/python l=[] with open("movie.xyz") as f: line = f.next() nat = int(line.split()[0]) print nat f.next()# skip headers for line in f: if line.strip(): l.append(map(float,line.split()[1:])) # make all values floats #print l[0][0] b = 0 a = 1 for b in range(55): for a in range(b+1,56): import operator import numpy as np #vector1 = l[b] vector1 = (l[b][0],l[b][1],l[b][2]) vector2 = (l[a][0],l[a][1],l[a][2]) #print('vector 1 = %' % vector1) #print('vector 1 = (%f,%f,%f)' % vector1) #print vector2 x = vector1 y = vector2 vector3 = list(np.array(x) - np.array(y)) #print vector3 dotProduct = reduce( operator.add, map( operator.mul, vector3, vector3)) dp = dotProduct**.5 print dp first couple lines of data look like: 2805 Atoms. Timestep: 0 Cu 46.7176 27.1121 27.1121 Cu 43.2505 36.0618 32.4879 Cu 43.3392 36.0964 28.9236 Cu 43.2509 37.8362 27.1091 Cu 43.3406 36.0958 25.2957 Cu 43.2582 36.0629 21.737 Cu 43.2505 32.4879 36.0618 Answer: insert import pdb; pdb.set_trace() before this line and see what gives you `line.split()[1:]` pdb = prompt debugger: <https://docs.python.org/2/library/pdb.html> or do this: if line.strip(): try: l.append(map(float,line.split()[1:])) except ValueError: print "Value error at: ", line.split()[1:] ## # to make this code work add this function: def foo(value): try: result = float(value) except ValueError: print "cant parse %r into float" %value result = None return result and replace the line: l.append(map(float,line.split()[1:])) to: l.append(map(foo, line.split()[1:]))
Calculate the Cumulative Distribution Function (CDF) in Python Question: How can I calculate in python the [Cumulative Distribution Function (CDF)](https://en.wikipedia.org/wiki/Cumulative_distribution_function)? I want to calculate it from an array of points I have (discrete distribution), not with the continuous distributions that, for example, scipy has. Answer: (It is possible that my interpretation of the question is wrong. If the question is how to get from a discrete PDF into a discrete CDF, then `np.cumsum` divided by a suitable constant will do if the samples are equispaced. If the array is not equispaced, then `np.cumsum` of the array multiplied by the distances between the points will do.) If you have a discrete array of samples, and you would like to know the CDF of the sample, then you can just sort the array. If you look at the sorted result, you'll realize that the smallest value represents 0% , and largest value represents 100 %. If you want to know the value at 50 % of the distribution, just look at the array element which is in the middle of the sorted array. Let us have a closer look at this with a simple example: import matplotlib.pyplot as plt import numpy as np # create some randomly ddistributed data: data = np.random.randn(10000) # sort the data: data_sorted = np.sort(data) # calculate the proportional values of samples p = 1. * arange(len(data)) / (len(data) - 1) # plot the sorted data: fig = figure() ax1 = fig.add_subplot(121) ax1.plot(p, data_sorted) ax1.set_xlabel('$p$') ax1.set_ylabel('$x$') ax2 = fig.add_subplot(122) ax2.plot(data_sorted, p) ax2.set_xlabel('$x$') ax2.set_ylabel('$p$') This gives the following plot where the right-hand-side plot is the traditional cumulative distribution function. It should reflect the CDF of the process behind the points, but naturally it is not the as long as the number of points is finite. ![cumulative distribution function](https://i.stack.imgur.com/sSjIz.png) This function is easy to invert, and it depends on your application which form you need.
Connect Android App to Python script on Mac OS X via Bluetooth Question: My goal is very basic. I am trying to transmit a String from my android device to my Mac running OSX 10.9 via bluetooth. On my Mac I am using the lightblue python library to do the connections. I am pretty sure that the issue is raised by a cast-like exception between what methods are expecting (more detail below). I am relatively new to this type of networking. This is ultimately going to become a rough proof of concept. Any advice would work as well. Thanks! Android Code (Sending String): public class Main extends Activity { private OutputStream outputStream; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { init(); write("Test"); } catch (IOException e) { e.printStackTrace(); } } private void init() throws IOException { BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter(); if (blueAdapter != null) { if (blueAdapter.isEnabled()) { Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices(); if(bondedDevices.size() > 0){ BluetoothDevice device = (BluetoothDevice) bondedDevices.toArray()[0]; ParcelUuid[] uuids = device.getUuids(); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid()); socket.connect(); outputStream = socket.getOutputStream(); } Log.e("error", "No appropriate paired devices."); }else{ Log.e("error", "Bluetooth is disabled."); } } } public void write(String s) throws IOException { outputStream.write(s.getBytes()); } public void run() { final int BUFFER_SIZE = 1024; byte[] buffer = new byte[BUFFER_SIZE]; int bytes = 0; while (true) { try { bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes); } catch (IOException e) { e.printStackTrace(); } } } } Adapted from: [Android sample bluetooth code to send a simple string via bluetooth](http://stackoverflow.com/questions/22899475/android-sample- bluetooth-code-to-send-a-simple-string-via-bluetooth) Python LightBlue Example Code (Receiving String): import lightblue # create and set up server socket sock = lightblue.socket() sock.bind(("", 0)) # bind to 0 to bind to a dynamically assigned channel sock.listen(1) lightblue.advertise("EchoService", sock, lightblue.RFCOMM) print "Advertised and listening on channel %d..." % sock.getsockname()[1] conn, addr = sock.accept() print "Connected by", addr data = conn.recv(1024) #CRASHES HERE print "Echoing received data:", data # sometimes the data isn't sent if the connection is closed immediately after # the call to send(), so wait a second import time time.sleep(1) conn.close() sock.close() Error in console: python test.py Advertised and listening on channel 1... Connected by ('78:52:1A:69:B2:6D', 1) Traceback (most recent call last): File "test.py", line 16, in <module> data = conn.recv(1024) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lightblue/_bluetoothsockets.py", line 470, in recv return self.__incomingdata.read(bufsize) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lightblue/_bluetoothsockets.py", line 150, in read self._build_str() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lightblue/_bluetoothsockets.py", line 135, in _build_str new_string = "".join(self.l_buffer) TypeError: sequence item 0: expected string, memoryview found The last line is where I am pretty sure I am messing up. It is expecting a string, but I am pretty sure I am not sending a memoryview (as far as I am aware). Answer: In your Android part, you're better off using [DataOutputStream](http://developer.android.com/reference/java/io/DataOutputStream.html) to send string. Do it like this: public void write(String s) throws IOException { // outputStream.write(s.getBytes()); // Wrap the OutputStream with DataOutputStream DataOutputStream dOut = new DataOutputStream(outputStream); // Encode the string with UTF-8 byte[] message = s.getBytes("UTF-8"); // Send it out dOut.write(message, 0, message.length); } * * * Further reading: [MUTF-8 (Modified UTF-8) Encoding](http://developer.android.com/reference/java/io/DataInput.html)
How to extract the price from html using regex in python Question: I have a html output that contains this: <span class="value"> Price:<br> <span style="color:white">23,07€ </span> </span> I tried to extract the prices using: prices = re.findall(r'<span class="value">.*?(\d{1,3}\.?\d{1,2}).*?</span>',search_result) sometimes the decimals are replaced with -- when there are 00, also i need this 2 numbers that get extracted by the expression 23 07 joined 2307 Thank you for your time. Answer: Get the matched group from index 1. (?<=>)(\d[^€]*) [demo](http://regex101.com/r/rI6yA4/5) * * * OR get the matched group index 1 and 2 for each number (?<=>)(\d+)\D(\d+)\D [demo](http://regex101.com/r/rI6yA4/7) * * * If you are interested only for `<span>` tag then try below regex <span [^>]*>(\d+)\D(\d+)\D[^<]* [demo](http://regex101.com/r/rI6yA4/12) Sample code: import re p = re.compile(ur'<span [^>]*>(\d+)\D(\d+)\D[^<]*') test_str = u"..." re.findall(p, test_str)
Split long string of addresses into list of addresses in Python Question: I have a string of a couple thousand addresses in python, like such: `'123 Chestnut Way 4567 Oak Lane 890 South Pine Court'` What is the easiest way to split this long string into separate addresses? I'm trying to write a program that splits based on 3 or 4 characters in a row where `47 < ord(i) < 58`, but I'm having trouble. Answer: Assuming all of the addresses are like those given, you can use [`re.findall`](https://docs.python.org/2/library/re.html#re.findall): >>> from re import findall >>> string = '123 Chestnut Way 4567 Oak Lane 890 South Pine Court' >>> findall("\d+\D+(?=\s\d|$)", string) ['123 Chestnut Way', '4567 Oak Lane', '890 South Pine Court'] >>> All of the Regex syntax used above is explained [here](https://docs.python.org/2/library/re.html#regular-expression-syntax), but below is a quick breakdown: \d+ # One or more digits \D+ # One or more non-digits (?= # The start of a lookahead assertion \s # A space \d|$ # A digit or the end of the string ) # The end of the lookahead assertion
How to give the folder name using model instance in django Question: New to python . Anyway I am on my way to first project. See i need to upload multiple file into single folder so i come up with an idea like this. folder_name1 ------myfiles1.jpg ------myfiled2.jpg folder_name2 ------mynewfiles.jpg ------mynewfiles1.jpg And i read lot of tutorials this is my models.py def content_file_name(instance, filename): return "uploads/{folder}/{file}".format(id=instance, folder=instance.albumname, file=filename) class Album(models.Model): albumname = models.CharField(max_length=100) audiofile = models.FileField(upload_to=content_file_name)#documents/%Y/%m/%d Updated: This is my view.py def viewalbum(request): if request.method == 'POST': form = AlbumForm(request.POST, request.FILES) if form.is_valid(): alubmnew = Album() albumvalue = Album() albumnew = Album(albumname = request.POST.get('albumname', None)) albumvalue = Album(audiofile = request.FILES['audiofile']) #for albumvalue in request.FILES.getlist('audiofile'): albumvalue.save() albumnew.save() return HttpResponseRedirect(reverse('google.views.viewalbum')) else: form = AlbumForm() return render_to_response('audio/test.html',{'form': form}, context_instance=RequestContext(request)) The problem i am having right now is.. It doesn`t create albumname folder And also in my form i can`t able to upload multiple file in single time. Its actually takes only one file to upload... Answer: import os def content_file_name(instance, filename): upload_dir = os.path.join('uploads', instance.albumname) if not os.path.exists(upload_dir): os.makedirs(upload_dir) return os.path.join(upload_dir, filename)
After 12 requests (~60 sec) Firebase or Python-firebasin library do not send and receive data Question: I have a problem, please help me. I created Python script what is collaborating with Firebase to save and receive data. My script works with python-firebasin library ([link to python- firebasin](https://github.com/abeisgreat/python-firebasin)). I tested my application one week with my Firebase account - HACKER PLAN. All works fine all this time. After that i buy premium account with special URL like x.firebaseio.com here begins my problems. I import json structure from my old firebase to my new firebase account and set in my Python script new firebase URL to my new firebase account. So now all must works fine with my new firebase premium account. I run my script and ~60 seconds my script works fine. Callback events work, set values works. But after ~60 seconds Firebase do not receive and do not send any callback to my Python script. For debugging i wrote simple script what send unixtime to firebase every 5 second. So all works fine first 12 requests (12 * 5 = ~60 sec), after what firebase do not receive any data. Python do not send any error and callback too. Atention: All works fine with my old Firebase account - HACKER PLAN! from firebasin import Firebase from time import sleep, time # Firebase vGFirebase = None vGCompanyId = '1' vGHardwareId = '0000000000123123' i = 1 vGFirebase = Firebase('https://subdomain.firebaseio.com') def errorCallback(data): print('errorCallback', data) while True: try: pingChild = vGFirebase.child('data/app/pings/' + str(vGCompanyId) + '/' + str(vGHardwareId)) sendTime = int(time()) pingChild.set(sendTime, errorCallback) print(i, 'send ', sendTime) i += 1 sleep(5) except: print('Exception') break vGFirebase.waitForInterrupt() I enable Debug mode in python-firebasin library. So after 12 requests i got this message: **(('Closed down :(', 1006, 'Going away'),)** So i think this is because Firebase close connection... But why? Sorry for my bad english... Answer: firebasin does not start a Heartbeat to keep the connection alive. You can easily start one yourself. After the line creating `vGFirebase`: from ws4py.websocket import Heartbeat while not vGFirebase.connection.data: sleep(1) Heartbeat(vGFirebase.connection.data,2).start() Unfortunately, the _keep_alive method in dataref.py seems to not get along with hacker plans and causes them to disconnect when it fires its own keepalive message, so you'll also need to disable that. You can do so on the fly by adding import firebasin firebasin.dataref.RootDataRef._keep_alive = lambda *x: None to the top of your script. A more permanent, but non-portable solution would be to patch dataref.py to replace it's _keep_alive method with one that starts ws4py's Heartbeat. I've submitted a pull request to do that upstream; we'll see if there is a reason Abe Haskins didn't do it that way in the first place.
subprocess.call and tar -zxvf Question: I am trying to call this command `tar -zxvf file.tar.gz` from a python script and I'm having trouble with it. I've read some relevant q/a's but I still haven't figured out how to do it. I was thinking to fit my code to the original command: subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False) So far I've made several attempts, as shown below stdin = file.tar.gz subprocess.check_call(-zxvf, stdin) Any help? Thanks. Answer: You can untar a file using the `tarfile` module import tarfile tar = tarfile.open("sample.tar.gz") tar.extractall() tar.close()
Test to see if URL exists Question: What is the best way to test if a URL exists in python, I currently use cURL however I wanted to switch to use python In cURL I use something like curl http://www.google.com | tidy -i together with a bash script Answer: The quickest way is probably something like import httplib try: url = httplib.HTTPConnection('yahoo.com') url.connect() except httplib.HTTPException as ex: print "not connected"
Should logger.exception only be called inside an except block? Why? Question: The docs for [`logger.exception`](https://docs.python.org/2/library/logging.html#logging.Logger.exception) mention: > This method should only be called from an exception handler. So usage should be somethnig like this: import logging, sys logger = logging.getLogger() logger.setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) logger.addHandler(handler) try: errorerrorerror except NameError as e: logger.exception('debug message 1 {}'.format(e)) But when I tried doing it the "wrong" way, behaviour seemed to be just the same: try: errorerrorerror except NameError as e: pass logger.exception('debug message 2 {}'.format(e)) What is the reason for that caveat mentioned in the docs? Is it _actually_ true that we can only use it in an except block, for some subtle reason not evident here? I am aware that in python 3 this has changed, but python documentation is usually very consistent in mentioning these differences.. Answer: The method is _designed_ for use in an exception handler. As such the documentation tells you this, by using the word _should_ , not _must_. In the text of standards, _should_ and _must_ are rigidly defined; one means _we advice you to do it this way, it'd be much better if you did_ , the other means _it's an outright error if you don't do this_. See [RFC 2119](http://www.ietf.org/rfc/rfc2119.txt) for the IETF taskforce wording. All `logging.exception()` does is set the `exc_info` keyword argument before calling `logging.error()`. The `exc_info` argument is then later fleshed out to include the _most recently handled exception_ , taken from [`sys.exc_info()`](https://docs.python.org/2/library/sys.html#sys.exc_info). It is then up to the formatter to include the exception message (via the [`Formatter.format_exception()` method](https://docs.python.org/2/library/logging.html#logging.Formatter.formatException) to format the exception. Because `sys.exc_info()` works both in the `except` suite and out, both variants work. From a _code documentation point of view_ , it is just clearer if you use it in the `except` handler. You don't need to include the error message, really, because your log formatter should already do that for you: logger.exception('debug message 2') # exception should be included automatically You can explicitly attach an exception to any log message with: logger.error('debug message 2', exc_info=sys.exc_info()) or any other 3-tuple value with the exception type, the exception value and a traceback. Alternatively, set `exc_info=1` to have the logger retrieve the information from `sys.exc_info()` itself. See the documentation for [`Logger.debug()`](https://docs.python.org/2/library/logging.html#logging.Logger.debug): > _exc_info_ which, if it does not evaluate as false, causes exception > information to be added to the logging message. If an exception tuple (in > the format returned by `sys.exc_info()`) is provided, it is used; otherwise, > `sys.exc_info()` is called to get the exception information.
python matplotlib imshow with difference lenghts in data-array Question: Is there a way to plot heat map with different row lengths using matplotlib? like this: plt.imshow( [ [1,2,3], [1,2], [1,2,3,4,5,6,7], [1,2,3,4]]) plt.jet() plt.colorbar() plt.show() [Desired image](http://postimg.org/image/geoa9nrxf/) Answer: Given the desired image, I think you will want to you `plt.pcolormesh` rather than `imshow` but I may be wrong. In any case I personally would create a function to pad the array then use a mask so that `imshow` or `pcolormesh` will not plot those points. For example import matplotlib.pylab as plt import numpy as np def regularise_array(arr, val=-1): """ Takes irregular array and returns regularised masked array This first pads the irregular awway *arr* with values *val* to make it of rectangular. It then applies a mask so that the padded values are not displayed by pcolormesh. For this reason val should not be in *arr* as you will loose these points. """ lengths = [len(d) for d in data] max_length = max(lengths) reg_array = np.zeros(shape=(arr.size, max_length)) for i in np.arange(arr.size): reg_array[i] = np.append(arr[i], np.zeros(max_length-lengths[i])+val) reg_array = np.ma.masked_array(reg_array, reg_array == val) return reg_array data = np.array([[1,2,3], [1,2], [1,2,3,4,5,6,7], [1,2,3,4]]) reg_data = regularise_array(data, val=-1) plt.pcolormesh(reg_data) plt.jet() plt.colorbar() plt.show() ![enter image description here](http://i.stack.imgur.com/i1V4a.png) The issue with this is you need to take care thet `val` is not in the array. You could add a simple check for this or base it on the data you are using. The for loop could probably be vectorised but I cannot work out how.
Fetch time from mysql using python Question: I am using the code below to fetch time entity called `fajr_begins` from `mysql`. I am able to print `fajr_begins` which is in the format: 5:27:00, how can i convert this to a time format in python, so that i can manipulate the time and add 15mins? cnx = mysql.connector.connect(host=mysql_remote_host, user=mysql_remote_host_user, password=mysql_remote_host_password, database=mysql_remote_host_database) cursor = cnx.cursor() cursor.execute("select * from prayertimes where DATE(date) = DATE(NOW())" ) results = cursor.fetchall() id, date, fajr_begins, fajr_jamaat, sunrise, zuhr_begins, zuhr_jamaat, asr_begins, asr_jamaat, maghrib_jamaat, isha_begins, isha_jamaat = results[0] cursor.close() print fajr_begins Answer: You have to convert it using [`strptime`](https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime). `timedelta` will be use for adding minutes. >>> from datetime import datetime, timedelta >>> a = "05:27:00" >>> b = datetime.strptime(a, "%H:%M:%S") >>> print b 1900-01-01 05:27:00 >>> c = timedelta(minutes=15) >>> print c 0:15:00 >>> print b+c 1900-01-01 05:42:00
Python pandas how to get the reverse of groupby Question: I have two data frames. They are the same except for one column. I want to change the column of the second dataframe according to mean values from the first dataframe. For the latter I have to use groupby, but then I don't know how to get a reverse. Below is a minimal example, where in this particular example df_two should end up being the same as df_one. My question is how to get from tmp to df2_new - see the code below. import pandas as pd def foo(df1, df2): # Group by A groupsA_one = dict(list(df1.groupby('A', as_index=False))) groupsA_two = dict(list(df2.groupby('A', as_index=False))) for key_A in groupsA_one: # Group by B groupsB_one = dict(list(groupsA_one[key_A].groupby('B', as_index=False))) groupsB_two = dict(list(groupsA_two[key_A].groupby('B', as_index=False))) for key_B in groupsB_one: # Group by C tmp = groupsB_two[key_B].groupby('C', as_index=False)['D'].mean() # Returns DataFrame with NaN tmp['D'] = groupsB_one[key_B].groupby('C', as_index=False)['D'].mean()['D'] print tmp df2_new = [] # ??? return df2_new if __name__ == '__main__': A1 = {'A': [1, 1, 1, 1, 2, 2, 2, 2], 'B': [1, 1, 2, 2, 1, 1, 2, 2], 'C': [1, 2, 1, 2, 1, 2, 1, 2], 'D': [5, 5, 5, 5, 5, 5, 5, 5]} A2 = {'A': [1, 1, 1, 1, 2, 2, 2, 2], 'B': [1, 1, 2, 2, 1, 1, 2, 2], 'C': [1, 2, 1, 2, 1, 2, 1, 2], 'D': [0, 0, 0, 0, 0, 0, 0, 0]} df_one = pd.DataFrame(A1) df_two = pd.DataFrame(A2) foo(df_one, df_two) Answer: Here is the solution that I wanted. Please, if you find a more elegant solution I will be happy to set it as a correct answer. Hre it is: import pandas as pd import numpy as np def foo(df): # Group by A groups_a_one = dict(list(df.groupby('A', as_index=False))) for key_a in groups_a_one: # Group by B groups_b_one = dict(list(groups_a_one[key_a].groupby('B', as_index=False))) for key_b in groups_b_one: # Group by C tmp = groups_b_one[key_b].groupby('C', as_index=False).transform(lambda x: x.fillna(x.mean())) df.ix[tmp.index, 'D'] = tmp['D']# assign mean values to correct lines in df return df if __name__ == '__main__': A1 = {'A': [1, 1, 1, 1, 2, 2, 2, 2], 'B': [1, 1, 2, 2, 1, 1, 2, 2], 'C': [1, 2, 1, 2, 1, 2, 1, 2], 'D': [5, 5, 5, 5, 5, 5, 5, 5]} A2 = {'A': [1, 1, 1, 1, 2, 2, 2, 2], 'B': [1, 1, 2, 2, 1, 1, 2, 2], 'C': [1, 2, 1, 2, 1, 2, 1, 2], 'D': [np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN]} df_one = pd.DataFrame(A1) df_two = pd.DataFrame(A2) df = pd.concat([df_one, df_two], axis=0, ignore_index=True)# To get only one DataFrame # run the transform foo(df) Here is the initial state and the final one: # Initial A B C D 0 1 1 1 5 1 1 1 2 5 2 1 2 1 5 3 1 2 2 5 4 2 1 1 5 5 2 1 2 5 6 2 2 1 5 7 2 2 2 5 8 1 1 1 NaN 9 1 1 2 NaN 10 1 2 1 NaN 11 1 2 2 NaN 12 2 1 1 NaN 13 2 1 2 NaN 14 2 2 1 NaN 15 2 2 2 NaN # Final A B C D 0 1 1 1 5 1 1 1 2 5 2 1 2 1 5 3 1 2 2 5 4 2 1 1 5 5 2 1 2 5 6 2 2 1 5 7 2 2 2 5 8 1 1 1 5 9 1 1 2 5 10 1 2 1 5 11 1 2 2 5 12 2 1 1 5 13 2 1 2 5 14 2 2 1 5 15 2 2 2 5
Detecting and Comparing GPIO events in Beaglebone using Python Question: I am trying to detect two events in two different GPIOs in the Beaglebone Black, and then decide which one happened first. I am using Adafruit_BBIO.GPIO for the code which is written in Python. It is not working properly, and have no idea why. Here is the code: import sys import thread import time from datetime import datetime import bitarray import Adafruit_BBIO.GPIO as GPIO gpio_state = [0, 0] gpio_time = [0, 0] ir_recv = ['GPIO0_26', 'GPIO1_12'] def checkEvent(index): while True: if GPIO.event_detected(ir_recv[index]): if (gpio_state[index] == 0): gpio_state[index] = 1 gpio_time[index] = datetime.now() print ir_recv[index] time.sleep(5) # time to avoid rebounces for gpio in ir_recv: GPIO.setup(gpio, GPIO.IN) GPIO.add_event_detect(gpio, GPIO.RISING) try: thread.start_new_thread(checkEvent, (0, ) ) thread.start_new_thread(checkEvent, (1, ) ) except: print "Error: unable to start thread" while True: if (gpio_state[0] == 1) and (gpio_state[1] == 1): if gpio_time[0] > gpio_time[1]: print "1" if gpio_time[0] < gpio_time[1]: print "2" if gpio_time[0] == gpio_time[1]: print "???" gpio_state[0] = 0 gpio_state[1] = 0 gpio_time[0] = 0 gpio_time[1] = 0 I don't get any error. The main problem is that the events are not compared correctly, e.g. although event in GPIO0_26 happens first than the one in GPIO1_12 (i.e. gpio_time[0] is smaller than gpio_time[1]), the output in the last While loop does not print out "2". Also sometimes the code prints out twice the GPIO pin from the threads. Thanks in advance for any suggestion to find a solution. Answer: I'd recommend using [PyBBIO](https://github.com/graycatlabs/PyBBIO) for this (granted, I am the author). It has an interrupt API which is based on [epoll](http://linux.die.net/man/4/epoll) (for kernel level interrupt signalling), and would greatly simplify this. Something like this should do the trick (I haven't tested it): from datetime import datetime from bbio import * gpio_state = [0, 0] gpio_time = [0, 0] ir_recv = ['GPIO0_26', 'GPIO1_12'] def getInterrupt(index): gpio_time[index] = datetime.now() gpio_state[index] = 1 print "received interrupt from {} at {}".fomrat(ir_recv[index], gpio_time[index] ) def setup(): for i in range(len(ir_recv)): pinMode(ir_recv[i], INPUT, pull=-1) # The optional pull=-1 enables the internal pull-down resistor attachInterrupt(ir_recv[0], lambda: getInterrupt(0), RISING) attachInterrupt(ir_recv[1], lambda: getInterrupt(1), RISING) def loop(): # You can do other stuff here while you're waiting... delay(1000) run(setup, loop) And you should make sure your PyBBIO is up to date with: # pip install -U PyBBIO
Get and count node neighbors Python Question: I am trying to read a file with node pairs and weight. I have find the neighbours of each pair individual and combined both also count them. Later find the ratio of the neighbours that each node has. I am stuck with finding nodes. infile.txt 0_node1 0_node2 0w 1_node1 1_node2 1w 2_node1 2_node2 2w 3_node1 3_node2 3w 4_node1 4_node2 4w Code: import networkx as nx import matplotlib.pyplot as plt G=nx.Graph() G = nx.read_edgelist('infile.txt', data=[("weight", float)]) def get_triangle(G): for n1 in G.nodes: neighbors1 = set(G[n1]) for n2 in filter(lambda x: x>n1, nodes): neighbors2 = set(G[n2]) common = neighbors1 & neighbors2 for n3 in filter(lambda x: x>n2, common): print n1 print n2 print n3 I did check the indentations in program does not seem to be problem. I not getting the neighbours list. Answer: If you are going to do anything with the values I suggest yield'ing a 3 node tuple. I had to change the data so the import would work (i stripped out the w's) and there is support for finding triangle nodes in networkx which helps limit how many objects we are iterating over each time. infile.txt 0_node1 0_node2 0 1_node1 1_node2 1 2_node1 2_node2 2 3_node1 3_node2 3 4_node1 4_node2 4 0_node1 1_node2 5 0_node2 1_node2 6 0_node2 1_node1 7 ![enter image description here](http://i.stack.imgur.com/IY2q9.png) code: import networkx as nx import itertools as it def get_triangles(G): def found_rotation(x): for rotation in it.permutations(x): if rotation in triangles_duplicates: return 1 return 0 triangles = [] triangles_duplicates=[] triangle_nodes = dict((x,nx.triangles(G,x)) for x in G.nodes() if nx.triangles(G,x) > 0) for vertex1 in triangle_nodes: vertex1_neighbors_that_are_triangles = set(G.neighbors(vertex1)).intersection( \ set(triangle_nodes) ) for vertex2 in vertex1_neighbors_that_are_triangles: if triangle_nodes[vertex2] > 0: vertex2_neighbors_that_are_triangles_and_not_vertex1 = \ set(G.neighbors(vertex2)).intersection(\ G.neighbors(vertex1))-{vertex1}-{vertex2} for vertex3 in vertex2_neighbors_that_are_triangles_and_not_vertex1: if triangle_nodes[vertex3]>0: for z in G.neighbors(vertex3): if (vertex1 == z) and not found_rotation((vertex1,vertex2,vertex3)): triangle_nodes[vertex1] -=1 triangle_nodes[vertex2] -=1 triangle_nodes[vertex3] -=1 triangles.append((vertex1,vertex2,vertex3)) triangles_duplicates.append((vertex1,vertex2,vertex3)) return triangles if __name__ == "__main__": #G = nx.karate_club_graph() G = nx.read_edgelist('this.txt', data=[("weight",int)]) With data like this the answer would be 2 triangles (or you could switch it with karate_club_graph and get 45) I'd be interested in seeing improvements if you do something with this.
python strip string from end the most greedily Question: here it is: str_ = 'file_.csv_.csv.bz2' re.sub(regex, '', str_) I want 'regex' value to get `'file_.csv_'` i.e. the file name without the actual extension which here `'.csv.bz2'` and could be `'.csv.*'` while `.* = ''|bz2|gz|7z|`... any compression format. More precisely I want `re.sub` to match from the end of `str_` the most greedily. with `regex = '\.csv.*$'` I would get only `'file_'`. I could of course do `os.path.splitext()` \- check if `str_` ends with `'.csv'` \- `os.path.splitext()` if so, but is there a shorter way? Answer: You could use `re.split()` splitting of the suffix: result = re.split(r'\.csv(?:\.\w+)?$', filename)[0] Demo: >>> import re >>> filename = 'file_.csv_.csv.bz2' >>> re.split(r'\.csv(?:\.\w+)?$', filename)[0] 'file_.csv_' >>> re.split(r'\.csv(?:\.\w+)?$', 'foobar_.csv_.csv')[0] 'foobar_.csv_' >>> re.split(r'\.csv(?:\.\w+)?$', 'foobar_.csv_.csv.gz')[0] 'foobar_.csv_'
Correct way to edit dictionary value python Question: I have written the following code in two different ways. I am trying to find the "correct pythonic" way of doing it. I will explain the reasons for both. First way, EAFP. This one uses pythons EAFP priciple, but causes some code duplication. try: my_dict['foo']['bar'] = some_var except KeyError: my_dict['foo'] = {} my_dict['foo']['bar'] = some_var Second way, LBYL. LBYL is not exactly considered pythonic, but it removes the code duplication. if 'foo' not in my_dict: my_dict['foo'] = {} my_dict['foo']['bar'] = some_var Which way would be considered best? Or is there a better way? Answer: I would say a seasoned Python developer would either use [dict.setdefault](https://docs.python.org/2/library/stdtypes.html#dict.setdefault) or [collections.defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict) my_dict.setdefault('foo', {})['bar'] = some_var or from collection import defaultdict my_dict = defaultdict(dict) my_dict['foo']['bar'] = some_var Also for the sake of completeness, I will introduce you to a recursive `defaultdict` pattern, which allows for dictionaries with infinite depth without any key error >>> from collections import defaultdict >>> def tree(): return defaultdict(tree) >>> my_dict = tree() >>> my_dict['foo']['bar']['spam']['egg'] = 0 >>> my_dict defaultdict(<function tree at 0x026FFDB0>, {'foo': defaultdict(<function tree at 0x026FFDB0>, {'bar': defaultdict(<function tree at 0x026FFDB0>, {'spam': defaultdict(<function tree at 0x026FFDB0>, {'egg': 0})})})})
Fetch 1M records in orientdb: why is it 6x slower than bare SQL+MySQL Question: For some graph algorithm I need to fetch a lot of records from a database to memory (~ 1M records). I want this to be done fast and I want the records to be objects (that is: I want ORM). To crudely benchmark different solutions I created a simple problem of one table with 1M Foo objects like I did here: [Why is SQLAlchemy 10x slower than SQL?](http://stackoverflow.com/questions/23185319/why-is- sqlalchemy-10x-slower-than-sql) . One can see that fetching them using bare SQL is extremely fast; also converting the records to objects using a simple for-loop is fast. Both execute in around 2-3 seconds. However using ORM's like SQLAlchemy and Hibernate, this takes 20-30 seconds: a lot slower if you ask me, and this is just a simple example without relations and joins. SQLAlchemy gives itself the feature "Mature, High Performing Architecture," (<http://www.sqlalchemy.org/features.html>). Similarly for Hibernate "High Performance" (<http://hibernate.org/orm/>). In a way both are right, because they allow for very generic object oriented data models to be mapped back and forth to a MySQL database. On the other hand they are awfully wrong, since they are 10x slower than just SQL and native code. Personally I think they could do better benchmarks to show this, that is, a benchmark comparing with native SQL + java or python. But that is not the problem at hand. Of course, I don't want SQL + native code, as it is hard to maintain. So I was wondering why there does not exist something like an object oriented database, which handles the database->object mapping native. Someone suggested OrientDB, hence I tried it. The API is quite nice: when you have your getters and setters right, the object is insertable and selectable. But I want more than just API-sweetness, so I tried the 1M example: import java.io.Serializable; public class Foo implements Serializable { public Foo() {} public Foo(int a, int b, int c) { this.a=a; this.b=b; this.c=c; } public int a,b,c; public int getA() { return a; } public void setA(int a) { this.a=a; } public int getB() { return b; } public void setB(int b) { this.b=b; } public int getC() { return c; } public void setC(int c) { this.c=c; } } import com.orientechnologies.orient.object.db.OObjectDatabaseTx; public class Main { public static void insert() throws Exception { OObjectDatabaseTx db = new OObjectDatabaseTx ("plocal:/opt/orientdb-community-1.7.6/databases/test").open("admin", "admin"); db.getEntityManager().registerEntityClass(Foo.class); int N=1000000; long time = System.currentTimeMillis(); for(int i=0; i<N; i++) { Foo foo = new Foo(i, i*i, i+i*i); db.save(foo); } db.close(); System.out.println(System.currentTimeMillis() - time); } public static void fetch() { OObjectDatabaseTx db = new OObjectDatabaseTx ("plocal:/opt/orientdb-community-1.7.6/databases/test").open("admin", "admin"); db.getEntityManager().registerEntityClass(Foo.class); long time = System.currentTimeMillis(); for (Foo f : db.browseClass(Foo.class).setFetchPlan("*:-1")) { if(f.getA() == 345234) System.out.println(f.getB()); } System.out.println("Fetching all Foo records took: " + (System.currentTimeMillis() - time) + " ms"); db.close(); } public static void main(String[] args) throws Exception { //insert(); fetch(); } } Fetching 1M Foo's using **OrientDB** takes approximately **18 seconds**. The for-loop with the getA() is to force the object fields to be actually loaded into memory, as I noticed that by default they are fetched lazily. I guess this may also be the reason fetching the Foo's is slow, because it has db- access each iteration instead of db-access once when it fetches everything (including the fields). I tried to fix that using setFetchPlan("*:-1"), I figured it may also apply on fields, but that did not seem to work. **Question:** Is there a way to do this fast, preferably in the 2-3 seconds range? Why does this take 18 seconds, whilst the bare SQL version uses 3 seconds? **Addition:** Using a ODatabaseDocumentTX like @frens-jan-rumph suggested only gave ma a speedup of approximately 5, but of approximatelt 2. Adjusting the following code gave me a running time of approximately 9 seconds. This is still 3 times slower than raw sql whilst no conversion to Foo's was executed. Almost all time goes to the for-loop. public static void fetch() { ODatabaseDocumentTx db = new ODatabaseDocumentTx ("plocal:/opt/orientdb-community-1.7.6/databases/pits2").open("admin", "admin"); long time = System.currentTimeMillis(); ORecordIteratorClass<ODocument> it = db.browseClass("Foo"); it.setFetchPlan("*:0"); System.out.println("Fetching all Foo records took: " + (System.currentTimeMillis() - time) + " ms"); time = System.currentTimeMillis(); for (ODocument f : it) { //if((int)f.field("a") == 345234) System.out.println(f.field("b")); } System.out.println("Iterating all Foo records took: " + (System.currentTimeMillis() - time) + " ms"); db.close(); } Answer: The answer lies in convenience. During an interview, when I asked a candidate what they thought of LINQ (C# I know, but pertinent to your question), they quite rightly answered that it was a sacrifice of performance, over convenience. A hand-written SQL statement (whether or not it calls a stored procedure) is _always_ going to be faster than using an ORM that auto-magically converts the results of the query in to nice, easy-to-use POCOs. That said, the difference should _not be that great_ as you have experienced. Yes, there is overhead in doing it the auto-magical way, but it shouldn't be that great. I do have experience here, and within C# I have had to use special reflection classes to reduce the time it takes to do this auto-magical mapping. With large swabs of data, I would expect an initial slow-down from an ORM, but then it would be negligible. 3 seconds to 18 seconds is _huge_.