text
stringlengths
226
34.5k
Keyboard event handling in Python? Question: So I am not very good with keyboard event handling in Python. I have read the [Python Curses](https://docs.python.org/2/library/curses.html) tutorial on their official website and looked for answers on SO but it still does not make sense to me. So for starters I want to make a simple program that when it takes a key press such as `Escape` it prints something simple like `You pressed escape!`. Sorry I have no code, this is because I do not really know where to start. I think it might have something to do with using functions but I am not sure. You guys do not even have to give me the exact answer but just hints to where I should start! Heres the code I tried: from msvcrt import getch while True: key = ord(getch()) if key == 27: #ESC print'You pressed ESC' but it didnt work? Any ideas? Answer: I dunno what you are trying to do, but AutoHotkey Scripts(Windows) might help you in running the appropriate python script with the input taken from it.
Qprogressbar with two values Question: I have some unusual question : For visualization of packing progress i think about qprogressbar with two values in one bar - one showing bytes read, and another showing write-out bytes, which gives also imagine about compress ratio. It is possible with QT4 ? Also, I have very little experience with C++ coding, my current work is based on Python, PyQT4, Answer: Yes it's possible, but you will have to implement your own "DualValueProgressbar" here you have an example, **is not complete production code** but it will point to you in the right direction. A note before continue: Will this you will be able to show two values in the bar, but show two colours in the same bar is a very different thing. So I'll recomend you to use two prograssbar for doing what you want, keep it simple. Before see any code let me explain what I did. 1. Subclass `QProgressBar` 2. Add a variable member called `self.__value_1`. This will be the second value. 3. Override the method `paintEvent` in order to draw `self.__value_1` inside the bar. Recomendations: 1. Write code for establishing limits on the second value. (Minimun and maximun) 2. Write code for handle the `format` property. 3. Write code for habdle the aligment property. This is the result: ![enter image description here](http://i.stack.imgur.com/rkbCI.png) Here is the code: from PyQt4.QtGui import * from PyQt4.QtCore import * class DualValueProgressBar(QProgressBar): def __init__(self, parent=None): super(DualValueProgressBar, self).__init__(parent) # The other value you want to show self.__value_1 = 0 def paintEvent(self, event): # Paint the parent. super(DualValueProgressBar, self).paintEvent(event) # In the future versions if your custom object you # should use this to set the position of the value_1 # in the progressbar, right now I'm not using it. aligment = self.alignment() geometry = self.rect() # You use this to set the position of the text. # Start to paint. qp = QPainter() qp.begin(self) qp.drawText(geometry.center().x() + 20, geometry.center().y() + qp.fontMetrics().height()/2.0, "{0}%".format(str(self.value1))) qp.end() @property def value1(self): return self.__value_1 @pyqtSlot("int") def setValue1(self, value): self.__value_1 = value if __name__ == '__main__': import sys app = QApplication(sys.argv) window = QWidget() hlayout = QHBoxLayout(window) dpb = DualValueProgressBar(window) dpb.setAlignment(Qt.AlignHCenter) # This two lines are important. dpb.setValue(20) dpb.setValue1(10) # Look you can set another value. hlayout.addWidget(dpb) window.setLayout(hlayout) window.show() sys.exit(app.exec()) Finally the code sample:
wxPython on Python 3 Miniconda environment Question: Trying out wxPython Phoenix for Python 3.3 on OS X. (I'm not sure which version of Python 3 Phoenix supports, I force-install it. >>> import wx >>> wx.App() This program needs access to the screen. Please run with a Framework build of python, and only when you are logged in on the main display of your Mac. Now I read [this](http://wiki.wxpython.org/wxPythonVirtualenvOnMac) which says there is a problem wxPython has with virtualenv and provided a fix via this script: #!/bin/bash # what real Python executable to use PYVER=2.7 PYTHON=/Library/Frameworks/Python.framework/Versions/$PYVER/bin/python$PYVER # find the root of the virtualenv, it should be the parent of the dir this script is in ENV=`$PYTHON -c "import os; print os.path.abspath(os.path.join(os.path.dirname(\"$0\"), '..'))"` # now run Python with the virtualenv set as Python's HOME export PYTHONHOME=$ENV exec $PYTHON "$@" I can't read BASH (what's $@?) but it looks like it's just a matter of setting PYTHONHOME. I am running wxPython Phoenix on Python 3, not Python 2. And I'm not using virtualenv. I'm Miniconda. I don't know where to set PYTHONHOME to. I set it in PYTHONHOME="/Users/username/miniconda3/" but it doesn't work. Answer: A better fix is to use `pythonw` (install the `python.app` conda package) instead of `python`.
Drawing rectangle using mouse events in Tkinter Question: This is with respect to [Draw rectangle on mouse click [Python]](http://stackoverflow.com/questions/12837575/draw-rectangle-on-mouse- click-python). I tried out the first solution and it works perfectly. Can someone please tell me, what to do if I want to see the rectangle being drawn and the rectangle gets fixed once the mouse button is released as I can only see the drawn rectangle once the button is released. Any kind of help will be appreciated. Answer: I amended the code from the referenced question. Now it shows the rectangle when mouse is being dragged on the canvas. The canvas displays Lena image. import tkinter as tk # this is in python 3.4. For python 2.x import Tkinter from PIL import Image, ImageTk class ExampleApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.x = self.y = 0 self.canvas = tk.Canvas(self, width=512, height=512, cursor="cross") self.canvas.pack(side="top", fill="both", expand=True) self.canvas.bind("<ButtonPress-1>", self.on_button_press) self.canvas.bind("<B1-Motion>", self.on_move_press) self.canvas.bind("<ButtonRelease-1>", self.on_button_release) self.rect = None self.start_x = None self.start_y = None self._draw_image() def _draw_image(self): self.im = Image.open('./resource/lena.jpg') self.tk_im = ImageTk.PhotoImage(self.im) self.canvas.create_image(0,0,anchor="nw",image=self.tk_im) def on_button_press(self, event): # save mouse drag start position self.start_x = event.x self.start_y = event.y # create rectangle if not yet exist #if not self.rect: self.rect = self.canvas.create_rectangle(self.x, self.y, 1, 1, fill="black") def on_move_press(self, event): curX, curY = (event.x, event.y) # expand rectangle as you drag the mouse self.canvas.coords(self.rect, self.start_x, self.start_y, curX, curY) def on_button_release(self, event): pass if __name__ == "__main__": app = ExampleApp() app.mainloop() ![enter image description here](http://i.stack.imgur.com/Vw3WJ.jpg) The black square is drawn on top of the image. Hope this helps.
Python: Surpass SSL verification with urllib3 Question: Connectiing to SSL server is throwing an error: > error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify > failed I'm using this urllib3 python library for connecting to server, using this method: urllib3.connectionpool.connection_from_url(['remote_server_url'], maxsize=2) How can i ignore SSL verification? Or is there another step for doing this? Thanks. Answer: You should be able to force urllib3 to use an unverified HTTPSConnection object by overriding the static `ConnectionCls` property of any ConnectionPool instance. For example: from urllib3.connection import UnverifiedHTTPSConnection from urllib3.connectionpool import connection_from_url # Get a ConnectionPool object, same as what you're doing in your question http = connection_from_url(remote_server_url, maxsize=2) # Override the connection class to force the unverified HTTPSConnection class http.ConnectionCls = UnverifiedHTTPSConnection # Make requests as normal... r = http.request(...) For additional reference, you can [check some of our tests](https://github.com/shazow/urllib3/blob/ba06933310dbd5764e2baa53f3505cf54eae56f7/test/with_dummyserver/test_https.py#L106) which do similar overriding. I've [opened an issue to improve our documentation](https://github.com/shazow/urllib3/issues/403#issuecomment-45660345) on how and when this should be done. We always appreciate pull requests, if you'd like to contribute. :)
threading.Condition.wait(timeout) ignores threading.Condition.notify() Question: I have an application that uses 2 threads. I want to be able to shut down both threads by waiting for a condition variable `exitCondition`. I am using python 3.3 which unlike python 2.7 makes `threading.Condition.wait()` return `True` when the condition was notified and `False` for when a timeout occured. #!/usr/bin/python import threading from time import sleep exitCondition = threading.Condition() def inputActivity(): while True: exitCondition.acquire() exitConditionReached = exitCondition.wait(.1) #<-critical print(exitConditionReached) exitCondition.release() if exitConditionReached: #exitCondition reached -> shutdown return else: #exitCondition not reached -> do work sleep(.1) inThread = threading.Thread(target = inputActivity) inThread.start() sleep(.2) #<-critical exitCondition.acquire() exitCondition.notify() print("exitCondition notified") exitCondition.release() inThread.join() There are 2 lines with a `#<-critical` comment in line 10 and 21. If the `sleep`s are "misaligned" (for example .25 and .1) the program will terminate. If the `sleep`s are "aligned" (for example .2 and .1) the `inThread` will run indefinitely printing `false` forever. It looks like a race condition to me, apparently if `notify` is called at the same time as `wait` the notification is not recognized. I was under the impression that the `exitCondition.acquire()` and `exitCondition.release()` were supposed to prevent that. The question is why the condition variable is not thread safe and what I can do about it. Ideally I want to write `wait(0)` with the guarantee that no notification will be swallowed. Answer: If the call to `exitCondition.notify` occurs when the worker thread is doing work (i.e., is in the `sleep(.1)` call (or anywhere else other than the `.wait` call), then the behaviour you describe sounds like exactly what I'd expect. The `wait` call returns `True` only if the notification happened _during_ the `wait`. It sounds to me as though this is a use-case for a `threading.Event` instead of a `threading.Condition`: replace `threading.Condition` with `threading.Event`, replace the `notify` call with a `set` call, and remove the `acquire` and `release` calls altogether (in both threads). That is, the code should look like this: #!/usr/bin/python import threading from time import sleep exitCondition = threading.Event() def inputActivity(): while True: exitConditionReached = exitCondition.wait(.1) #<-critical print(exitConditionReached) if exitConditionReached: #exitCondition reached -> shutdown return else: #exitCondition not reached -> do work sleep(.1) inThread = threading.Thread(target = inputActivity) inThread.start() sleep(.2) #<-critical exitCondition.set() print("exitCondition set") inThread.join() Once you've got that far, you don't need the first `.wait`: you can replace that with a direct `is_set` call to see if the exit condition has been set yet: #!/usr/bin/python import threading from time import sleep exitCondition = threading.Event() def inputActivity(): while True: if exitCondition.is_set(): #exitCondition reached -> shutdown return else: #exitCondition not reached -> do work sleep(.1) inThread = threading.Thread(target = inputActivity) inThread.start() sleep(.2) #<-critical exitCondition.set() print("exitCondition set") inThread.join()
Py-StackExchange raise a valueError Question: I try to use the StackExchange API and I found the Py-StackExchange library for Python. I installed it through easy_install in Windows. Here is the code: from stackexchange import Site, StackOverflow so = Site(StackOverflow) my_favourite_guy = so.user(2309097) print my_favourite_guy.reputation.format() print len(my_favourite_guy.answers), 'answers' And here is the error: Traceback (most recent call last): File "C:\Users\Tasos\Desktop\test - Copy.py", line 8, in <module> my_favourite_guy = so.user(2309097) File "build\bdist.win-amd64\egg\stackexchange\__init__.py", line 626, in user u, = self.users((nid,), **kw) File "build\bdist.win-amd64\egg\stackexchange\__init__.py", line 631, in users return self._get(User, ids, 'users', kw) File "build\bdist.win-amd64\egg\stackexchange\__init__.py", line 621, in _get return self.build(root, typ, coll, kw) File "build\bdist.win-amd64\egg\stackexchange\__init__.py", line 598, in build json = self._request(url, kw) File "build\bdist.win-amd64\egg\stackexchange\__init__.py", line 570, in _request json, info = request_mgr.json_request(url, new_params) File "build\bdist.win-amd64\egg\stackexchange\web.py", line 120, in json_request return (json.loads(req.data), req.info) File "C:\Python27\lib\json\__init__.py", line 338, in loads return _default_decoder.decode(s) File "C:\Python27\lib\json\decoder.py", line 365, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python27\lib\json\decoder.py", line 383, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded I saw in [Wiki](https://github.com/lucjon/Py-StackExchange/wiki/FAQ) the following but I don't use any proxy and the code version is the latest through easy_install: > This is probably the result of some proxy/router mangling with request > headers. It could be that your router/proxy adds headers requesting gzip > data, but doesn't decompress it, and that you are running a slightly old > version of the code which does not deal with gzip compression. In this case, > just update to the latest version of the library. Answer: The [version on PyPI](https://pypi.python.org/pypi/py-stackexchange) is well out of date (released 2011) and still uses API version 1.1, which has been [shut down](https://api.stackexchange.com/docs/api-v1-shutdown). The [Github codebase](https://github.com/lucjon/Py-StackExchange) has been updated to use API v2.2, install that directly: pip install git+https://github.com/lucjon/Py-StackExchange or using `easy_install`, download the current master zip: easy_install https://github.com/lucjon/Py-StackExchange/archive/640eac1525baaf57474ddbc3be2b580f00e4f1e8.zip To get answers listed you need to call `.fetch()`: print len(my_favourite_guy.answers.fetch()), 'answers' This only fetches the _first page_ of answers: >>> from stackexchange import Site, StackOverflow >>> so = Site(StackOverflow) >>> my_favourite_guy = so.user(2309097) >>> print my_favourite_guy.reputation.format() 563 >>> print len(my_favourite_guy.answers.fetch()), 'answers' 19 answers >>> my_favourite_guy = so.user(100297) >>> print my_favourite_guy.reputation.format() 251.2k >>> print len(my_favourite_guy.answers.fetch()), 'answers' 30 answers I have a few more than 30 answers, last time I checked. Use `.extend_next()` calls to fetch the next query set, until you run out.
Python: "@" followed by a function -> What does it stand for? Question: I'm currently learning Python and I came across a notation I was wondering about: import taskmanager as tm #........ @tm.task(str) def feat(folder): BLA BLA BLA ... the code is a small excerpt from <https://github.com/kfrancoi/phd- retailreco/blob/master/libraries/plsa/example_plsa.py> (the file contains several more notations using the `@` sign). Is this a common notation in python and what does it mean? Or is this only a notation used in this special case with the taskmanager or what!? I tried my best looking this up on google but it's though to find as the @-sign is stripped out in my search (too short, special character). Same happens here on Stackoverflow. Thank you very much in advance Answer: [This a decorator](https://docs.python.org/2/glossary.html), defined by the [PEP 318](http://legacy.python.org/dev/peps/pep-0318/). Extract of the glossary: > A function returning another function, usually applied as a function > transformation using the `@wrapper` syntax. Common examples for decorators > are `classmethod()` and `staticmethod()`. > > The decorator syntax is merely syntactic sugar, the following two function > definitions are semantically equivalent: > > > def f(...): > ... > f = staticmethod(f) > > @staticmethod > def f(...): > ... > > > The same concept exists for classes, but is less commonly used there. See > the documentation for function definitions and class definitions for more > about decorators. Related: [What are some common uses for Python decorators?](http://stackoverflow.com/questions/489720/what-are-some-common- uses-for-python-decorators)
Scrapy installation fails Question: Below is the end of the log file with the error I receive when I try to install Scrapy. I am rather inexperienced so it may be obvious to one of you. My computer is windows 8.1 64-bit. I have looked at the msvccompliler.px and there is no apparent indent error at the given line.I am pretty sure this stems from the openssl portion of the install. Thanks in advance for any help. File "C:\Python27\lib\distutils\command\build_ext.py", line 23, in from distutils.msvccompiler import get_build_version File "C:\Python27\lib\distutils\msvccompiler.py", line 159 return 9.0 ^ IndentationError: unexpected indent * * * Cleaning up... Command python setup.py egg_info failed with error code 1 in C:\Users\rjudge\AppData\Local\Temp\pycharm- packaging1218832657586108286.tmp\cryptography Storing complete log in C:\Users\rjudge\pip\pip.log Answer: If you are using a text editor for your code (ie. sublime text, notepad++, etc) try to open the script with the indent error and try to convert tabs to spaces. Sometimes tabs mixed with spaces will cause "unexpected indent".
Using Python 2.7 modules in Ubuntu 12.04 Question: I have implemented a Stack.py module that I would like to be able to import, but when I tried to save it to usr/lib/python2.7 Ubuntu didn't allow it. Now, I go to usr/lib and python2.7 folder doesn't even show up anymore in the graphic interface, although I am able to see it is still there by using sudo. Any ideas about what I am doing wrong? Thanks in advance! Answer: How did you write the original Stack.py? If you used a text editor (without elevating it to super user) you'll have to save it somewhere you have write permissions (Desktop, for example) and then you could do: sudo cp ~/Desktop/Stack.py /usr/lib/python2.7 That being said, I think this is more a question for the AskUbuntu site (also a part of Stack Exchange). If that doesn't work you could simply put Stack.py in the directory with the file you want to use it with and do from Stack import [what you want to import/use] or from Stack import *
Python pandas dataframe read from_records, "AssertionError: 1 columns passed, passed data had 22 columns" Question: I have a list where `a` is `806` in length. I want to import to a dataframe where the first item in the list is the column name. My code is: import pandas as pd b = pd.DataFrame.from_records(a[1:],columns=[a[0]]) this gives me an error of `AssertionError: 1 columns passed, passed data had 22 columns` while clearly i have only one column. I've tried a representation of the code and it works. So I'm not sure what is going on here. Here is a representation of the code: import pandas as pd arr= ['title', 'a','b','','',''] arr= filter(None, arr) b = pd.DataFrame.from_records(arr[1:],columns=[arr[0]] ) Must be something wrong with my list? I printed out `a` and it looks fine, like a regular list. I have pasted the printed output of `a` and placed that as the variable `list`, and it gives me the same error `AssertionError: 1 columns passed, passed data had 22 columns`. Seems like something wrong with my list. What else can I do to debug? Edit (based on DSM suggestion): import pandas as pd arr=['Title', '000660.ks'] b = pd.DataFrame.from_records(arr[1:],columns=[arr[0]] ) This gives `AssertionError: 1 columns passed, passed data had 8 columns` Answer: Instead of using `from_records` you want to use the default DataFrame constructor. `from_records` expects a list of something iterable, so for example, the string `'0006660.ks'` is being read in as `('0','0',... ,'s')` which is why you are getting an error about 8 columns in the data. b = pd.DataFrame(a[1:], columns=[a[0]])
How to Select Items in Dropdown in Selenium Question: Firstly, I have been trying to get the dropdown from this web page: <http://solutions.3m.com/wps/portal/3M/en_US/Interconnect/Home/Products/ProductCatalog/Catalog/?PC_Z7_RJH9U5230O73D0ISNF9B3C3SI1000000_nid=RFCNF5FK7WitWK7G49LP38glNZJXPCDXLDbl> This is the code I have: import urllib2 from bs4 import BeautifulSoup import re from pprint import pprint from selenium import webdriver url = 'http://solutions.3m.com/wps/portal/3M/en_US/Interconnect/Home/Products/ProductCatalog/Catalog/?PC_Z7_RJH9U5230O73D0ISNF9B3C3SI1000000_nid=RFCNF5FK7WitWK7G49LP38glNZJXPCDXLDbl' element_xpath = '//*[@id="Component1"]' driver = webdriver.PhantomJS() driver.get(url) element = driver.find_element_by_xpath(element_xpath) element_xpath = '/option[@value="02"]' all_options = element.find_elements_by_tag_name("option") for option in all_options: print("Value is: %s" % option.get_attribute("value")) option.click() source = driver.page_source.encode('utf-8', 'ignore') driver.quit() source = str(source) soup = BeautifulSoup(source, 'html.parser') print soup What prints out is this: Traceback (most recent call last): File "../../../../test.py", line 58, in <module> Value is: XX main() File "../../../../test.py", line 46, in main option.click() File "/home/eric/dev/octocrawler-env/local/lib/python2.7/site-packages/selenium-2.33.0-py2.7.egg/selenium/webdriver/remote/webelement.py", line 54, in click self._execute(Command.CLICK_ELEMENT) File "/home/eric/dev/octocrawler-env/local/lib/python2.7/site-packages/selenium-2.33.0-py2.7.egg/selenium/webdriver/remote/webelement.py", line 228, in _execute return self._parent.execute(command, params) File "/home/eric/dev/octocrawler-env/local/lib/python2.7/site-packages/selenium-2.33.0-py2.7.egg/selenium/webdriver/remote/webdriver.py", line 165, in execute self.error_handler.check_response(response) File "/home/eric/dev/octocrawler-env/local/lib/python2.7/site-packages/selenium-2.33.0-py2.7.egg/selenium/webdriver/remote/errorhandler.py", line 158, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotVisibleException: Message: u'{"errorMessage":"Element is not currently visible and may not be manipulated","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"81","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:51413","User-Agent":"Python-urllib/2.7"},"httpVersion":"1.1","method":"POST","post":"{\\"sessionId\\": \\"30e4fd50-f0e4-11e3-8685-6983e831d856\\", \\"id\\": \\":wdc:1402434863875\\"}","url":"/click","urlParsed":{"anchor":"","query":"","file":"click","directory":"/","path":"/click","relative":"/click","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/click","queryKey":{},"chunks":["click"]},"urlOriginal":"/session/30e4fd50-f0e4-11e3-8685-6983e831d856/element/%3Awdc%3A1402434863875/click"}}' ; Screenshot: available via screen And the weirdest most infuriating bit of it all is that sometimes it actually all works out. I have no clue what's going on here. * * * **UPDATE** It seems I have no issues with visibility of dropdown forms on other sites, just this one. Is there something that might make the form invisible (and if so, why only 95% of the time)? Could there be an issue loading the page that might cause things not to be visible? Answer: Using Selenium Webdriver with Python3 here's how I did it: all_options = self.driver.find_element_by_id("Component1") options = all_options.find_elements_by_tag_name("option") for each_option in all_options: print(each_option.get_attribute("value")) If you're trying to select something from the textbox here's how to do it: select = Select(self.driver.find_element_by_id("Component1")) select.select_by_visible_text("02") references: <http://selenium-python.readthedocs.org/api.html>
Matplotlib figure not responding when used with multiprocessing Question: I'm trying to create a very basic app that will update charts in matplotlib from a streaming data source. Data is received in a separate process. But my matplotlib figure keeps dying on me even for the most basic display. The matplotlib window looses interactivity and turns into **"Figure 1 (Not Responding)"**. Do I need to give matplotlib some CPU time explicitly in order to make it work nicely with `multiprocessing`? Here is a basic sample that dies on pretty much all backends on Windows 7, 64Bit, Python 2.7.3 32Bit. I'm using unofficial binary of scipy-stack from [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/): EDIT: It also does not appear to be working on Ubuntu (32bit). import time from multiprocessing import Process import matplotlib.pyplot as plt def p1_func(): while True: time.sleep(1) def p2_func(): plt.ion() plt.plot([1.6, 2.7]) while True: time.sleep(1) if __name__ == '__main__': p1_proc = Process(target=p1_func) p2_proc = Process(target=p2_func) p1_proc.start() p2_proc.start() p1_proc.join() p2_proc.join() What am I doing wrong? **How do you generally make a matplotlib interactive graphing of live data and threading (multiprocessing or otherwise) coexist?** Answer: Here below a simple example import time from multiprocessing import Process, Pipe import numpy as np import matplotlib.pyplot as plt class DataStreamProcess(Process): def __init__(self, connec, *args, **kwargs): self.connec = connec Process.__init__(self, *args, **kwargs) def run(self): random_gen = np.random.mtrand.RandomState(seed=127260) for _ in range(30): time.sleep(0.01) new_pt = random_gen.uniform(-1., 1., size=2) self.connec.send(new_pt) def main(): conn1, conn2 = Pipe() data_stream = DataStreamProcess(conn1) data_stream.start() plt.gca().set_xlim([-1, 1.]) plt.gca().set_ylim([-1, 1.]) plt.gca().set_title("Running...") plt.ion() pt = None while True: if not(conn2.poll(0.1)): if not(data_stream.is_alive()): break else: continue new_pt = conn2.recv() if pt is not None: plt.plot([pt[0], new_pt[0]], [pt[1], new_pt[1]], "bs:") plt.pause(0.001) pt = new_pt plt.gca().set_title("Terminated.") plt.draw() plt.show(block=True) if __name__ == '__main__': main()
Python 2.7, Ubuntu 14.04: directory to load data from on sys.path, but file still not found Question: Ok, this is a little bit of a strange one. I had some Python code that needed to load data from another folder using scipy's loadmat (this bit is not really relevant, but explains the remainder of the code). Before, I added the path at the beginning of the file via path_to_add = os.path.abspath(os.path.join(os.path.dirname(__file__), '../data/unit_tests')) if not path_to_add in sys.path: sys.path.insert(1, path_to_add) and would load the file via mat_file = loadmat('test_kernel',squeeze_me=False) This code ran fine in Ubuntu 12.04. However, when I try running it in 14.04, it gives the error: IOError: [Errno 2] No such file or directory: 'test_kernel.mat' I printed out sys.path using print sys.path and sure enough, the right absolute directory with '/data/unit_tests' is present. If I go over to this folder and try to load the file using loadmat, it loads fine. But for whatever reason, even though the path is present on sys.path, I still get that error when I execute the script in another folder. Anyone have any ideas why? Answer: What version of scipy were you using and what version are you using now? You can check by running: import scipy print scipy.__version__ As far as I can tell in my version of scipy (0.14.0) it doesn't use the sys.path at all to find files when running `loadmat`. I've checked the source code and it looks like it simply passes in the filename to the builtin `open` function. Is there a chance on the Ubuntu 12.04 system you were running the script from the same directory as the mat file? As a sanity check try running the `loadmat` function with the full path to the mat file. **Edit** Here's a question with the same general problem: [open() can't find file given path relative to PYTHONPATH](http://stackoverflow.com/questions/12391709/open- cant-find-file-given-path-relative-to-pythonpath) The usual way to do what you are doing is either have a global "data" directory so when you need to load a data file you prefix the filename with that directory. Another way is to specify things as absolute/relative paths to the python script. If you get a little fancier and create a python package there are ways to load data files relative to the python package itself.
Converting an RPy2 ListVector to a Python dictionary Question: The natural Python equivalent to a named list in R is a dict, but [RPy2](http://rpy.sourceforge.net/) gives you a [ListVector](http://rpy.sourceforge.net/rpy2/doc-2.3/html/vector.html?highlight=listvector#rpy2.robjects.vectors.ListVector) object. import rpy2.robjects as robjects a = robjects.r('list(foo="barbat", fizz=123)') At this point, a is a [ListVector](http://rpy.sourceforge.net/rpy2/doc-2.3/html/vector.html?highlight=listvector#rpy2.robjects.vectors.ListVector) object. <ListVector - Python:0x108f92a28 / R:0x7febcba86ff0> [StrVector, FloatVector] foo: <class 'rpy2.robjects.vectors.StrVector'> <StrVector - Python:0x108f92638 / R:0x7febce0ae0d8> [str] fizz: <class 'rpy2.robjects.vectors.FloatVector'> <FloatVector - Python:0x10ac38fc8 / R:0x7febce0ae108> [123.000000] What I'd like to have is something I can treat like a normal Python dictionary. My temporary hack-around is this: def as_dict(vector): """Convert an RPy2 ListVector to a Python dict""" result = {} for i, name in enumerate(vector.names): if isinstance(vector[i], robjects.ListVector): result[name] = as_dict(vector[i]) elif len(vector[i]) == 1: result[name] = vector[i][0] else: result[name] = vector[i] return result as_dict(a) {'foo': 'barbat', 'fizz': 123.0} b = robjects.r('list(foo=list(bar=1, bat=c("one","two")), fizz=c(123,345))') as_dict(b) {'fizz': <FloatVector - Python:0x108f7e950 / R:0x7febcba86b90> [123.000000, 345.000000], 'foo': {'bar': 1.0, 'bat': <StrVector - Python:0x108f7edd0 / R:0x7febcba86ea0> [str, str]}} So, the question is... Is there a better way or something built into RPy2 that I should be using? Answer: I think to get a r vector into a `dictionary` does not have to be so involving, how about this: In [290]: dict(zip(a.names, list(a))) Out[290]: {'fizz': <FloatVector - Python:0x08AD50A8 / R:0x10A67DE8> [123.000000], 'foo': <StrVector - Python:0x08AD5030 / R:0x10B72458> ['barbat']} In [291]: dict(zip(a.names, map(list,list(a)))) Out[291]: {'fizz': [123.0], 'foo': ['barbat']} And of course, if you don't mind using `pandas`, it is even easier. The result will have `numpy.array` instead of `list`, but that will be OK in most cases: In [294]: import pandas.rpy.common as com com.convert_robj(a) Out[294]: {'fizz': [123.0], 'foo': array(['barbat'], dtype=object)}
Internal Server Error with Django and uWSGI 2 Emperor mode Question: I have been trying to read everything I can find concerning this issue (and have learned much while doing so). The closest link I could find is [here](http://stackoverflow.com/questions/17555699/internal-server-error-with- django-and-uwsgi) and [ here](https://github.com/unbit/uwsgi/issues/263). My issue is almost identical except I'm running uwsgi exclusively in emperor mode. When I run uswsgi services WITHOUT running it in emperor mode my django website runs just fine. No matter how I change my configuration I always get the error message my /tmp/uwsgi.log file: "--- no python application found, check your startup logs for errors ---" I have listed my configuration and error log below: OS version: Linux raspberrypi 3.6.11+ #538 armv6l GNU/Linux Django version: 1.6.5 uwsgi version: 2.0.5.1 Virtual environment: /var/www/testbed/env Project location: /var/www/testbed/project/auth project tree: ./auth/ |-- __init__.py |-- __init__.pyc |-- requirements.txt |-- settings.py |-- settings.pyc |-- urls.py |-- urls.pyc |-- wsgi.py `-- wsgi.pyc file wsgi.py: """ WSGI config for auth project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os, sys, site sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))) sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), "../"))) sys.path.append('/usr/lib/python2.7') sys.path.append('/usr/lib/python2.7/dist-packages') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "auth.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() file /etc/uwsgi/emperor.ini: [uwsgi] master = true emperor = /etc/uwsgi/vassals logto = /tmp/uwsgi.log file /etc/uwsgi/vessals/auth.ini: [uwsgi] #plugins = python # Django-related settings chdir =/var/www/testbed/project/auth module = auth.wsgi:application # the virtualenv (full path) home =/var/www/testbed/env virtualenv =/var/www/testbed/env # process-related settings enable-threads = true pythonpath = /var/www/testbed/project/auth #wsgi-file = /var/www/testbed/project/auth/auth/wsgi.py env = DJANGO_SETTINGS_MODULE=auth.settings mount = /testbed/auth/admin=/var/www/testbed/project/auth/auth/wsgi.py manage-script-name = true #route-run = log:SCRIPT_NAME=${SCRIPT_NAME} # maximum number of worker processes processes = 1 #Simple rule is # of cores on machine # the socket (use the full path to be safe socket = /var/www/testbed/project/auth/uwsgi.sock # ... with appropriate permissions - may be needed chmod-socket = 664 # clear environment on exit vacuum = true logto = /tmp/uwsgi.log Command being executed listed below: /var/www/testbed/env/bin/uwsgi --ini /etc/uwsgi/emperor.ini --emperor /etc/uwsgi/vassals/ --http :8000 --plugin python --binary-pathusr/local/bin/uwsgi Error file /tmp/uwsgi.log: *** Starting uWSGI 2.0.5.1 (32bit) on [Tue Jun 10 19:06:12 2014] *** compiled with version: 4.6.3 on 10 June 2014 01:41:52 os: Linux-3.6.11+ #538 PREEMPT Fri Aug 30 20:42:08 BST 2013 nodename: raspberrypi machine: armv6l clock source: unix detected number of CPU cores: 1 current working directory: /etc/uwsgi detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** your processes number limit is 3376 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uWSGI http bound on :8000 fd 6 *** starting uWSGI Emperor *** uwsgi socket 0 bound to TCP address 127.0.0.1:57524 (port auto-assigned) fd 5 Python version: 2.7.3 (default, Mar 18 2014, 05:13:23) [GCC 4.6.3] *** has_emperor mode detected (fd: 8) *** [uWSGI] getting INI configuration from auth.ini *** Starting uWSGI 2.0.5.1 (32bit) on [Tue Jun 10 19:06:12 2014] *** compiled with version: 4.6.3 on 09 June 2014 23:07:00 os: Linux-3.6.11+ #538 PREEMPT Fri Aug 30 20:42:08 BST 2013 nodename: raspberrypi machine: armv6l clock source: unix detected number of CPU cores: 1 current working directory: /etc/uwsgi/vassals detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** your processes number limit is 3376 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to UNIX address /var/www/testbed/project/auth/uwsgi.sock fd 3 Python version: 2.7.3 (default, Mar 18 2014, 05:13:23) [GCC 4.6.3] Set PythonHome to /var/www/testbed/env *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0x1dca830 your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 128512 bytes (125 KB) for 1 cores *** Operational MODE: single process *** *** no app loaded. going in full dynamic mode *** *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 23068) spawned uWSGI worker 1 (pid: 23071, cores: 1) spawned uWSGI http 1 (pid: 23072) Python main interpreter initialized at 0x616918 python threads support enabled your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 128512 bytes (125 KB) for 1 cores *** Operational MODE: single process *** added /var/www/testbed/project/auth/ to pythonpath. WSGI app 0 (mountpoint='') ready in 2 seconds on interpreter 0x616918 pid: 23070 (default app) mounting /var/www/testbed/project/auth/auth/wsgi.py on /testbed/auth/admin added /var/www/testbed/project/auth/ to pythonpath. WSGI app 1 (mountpoint='/testbed/auth/admin') ready in 3 seconds on interpreter 0x9c6218 pid: 23070 *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 23070) Tue Jun 10 19:06:18 2014 - [emperor] vassal auth.ini has been spawned spawned uWSGI worker 1 (pid: 23073, cores: 1) Tue Jun 10 19:06:18 2014 - [emperor] vassal auth.ini is ready to accept requests --- no python application found, check your startup logs for errors --- [pid: 23071|app: -1|req: -1/1] 192.168.1.6 () {38 vars in 742 bytes} [Tue Jun 10 19:07:11 2014] GET /testbed/auth/admin => generated 21 bytes in 1 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0) --- no python application found, check your startup logs for errors --- [pid: 23071|app: -1|req: -1/2] 192.168.1.6 () {36 vars in 626 bytes} [Tue Jun 10 19:07:11 2014] GET /favicon.ico => generated 21 bytes in 1 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0) --- no python application found, check your startup logs for errors --- [pid: 23071|app: -1|req: -1/3] 192.168.1.6 () {38 vars in 742 bytes} [Tue Jun 10 19:07:13 2014] GET /testbed/auth/admin => generated 21 bytes in 2 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0) --- no python application found, check your startup logs for errors --- [pid: 23071|app: -1|req: -1/4] 192.168.1.6 () {36 vars in 626 bytes} [Tue Jun 10 19:07:13 2014] GET /favicon.ico => generated 21 bytes in 1 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0) At this point, I'm grasping at straws. Out of all the reading that I have done I can't see why this keeps rendering the "Internal Server Error." I may have over looked something that why I've finally given in to my pride by posting my sorrows here. Since I've gotten this far I really do think that I have overlooked something very small. Any help would be greatly appreciated. Answer: I had this issue several times in my deployments with usgi-emperor an the problem was that I didn't set the correct ALLOWED_HOSTS in my Django's project config file In your config you shold have ALLOWED_HOSTS=[ "yourdomain.com", "other.domain.com" ] or ALLOWED_HOSTS=["*"] to allow any host <https://docs.djangoproject.com/en/1.8/ref/settings/#allowed-hosts>
Why does python parse dates differently on Ubuntu and MacOS? Question: I've got some code that inexplicably works differently on Ubuntu and MacOS compiles of the same python version. Any explanation or workaround would be welcome. First, the setup on Ubuntu Python. The machine is running in UTC. Using PST in the time string fails, but changing PST to UTC it works fine. Python 2.7.3 (default, Sep 26 2013, 20:03:06) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from datetime import datetime >>> date_str = 'Thu Jan 1 00:32:36 PST 2015' >>> now = datetime.strptime(date_str, '%a %b %d %H:%M:%S %Z %Y') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime (data_string, format)) ValueError: time data 'Thu Jan 1 00:32:36 PST 2015' does not match format '%a %b %d %H:%M:%S %Z %Y' >>> date_str = 'Thu Jan 1 00:32:36 UTC 2015' >>> now = datetime.strptime(date_str, '%a %b %d %H:%M:%S %Z %Y') >>> Now on MacOS (running in PDT), python there doesn't care what timezone is specified and works with any timezone: Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from datetime import datetime >>> date_str = 'Thu Jan 1 00:32:36 GMT 2015' >>> now = datetime.strptime(date_str, '%a %b %d %H:%M:%S %Z %Y') >>> The versions of GCC are different and the datestamps of python 2.7.3 are different, but this seems like pretty straightforward functionality that wouldn't have OS dependencies. I saw bugs like this <http://bugs.python.org/issue8957> that were loosely related. Is this better asked as a bug report on python.org? Answer: The documentation says that [%Z is inherently platform specific](https://docs.python.org/2/library/time.html): > Support for the %Z directive is based on the values contained in tzname and > whether daylight is true. Because of this, it is platform-specific except > for recognizing UTC and GMT which are always known (and are considered to be > non-daylight savings timezones).
Cannot compile simple PyCuda OSX application Question: I've followed the PyCuda instructions here: <http://wiki.tiker.net/PyCuda/Installation/Mac> I'm trying to compile the following code: import pycuda.autoinit import pycuda.driver as drv import numpy from pycuda.compiler import SourceModule mod = SourceModule(""" __global__ void multiply_them(float *dest, float *a, float *b) { const int i = threadIdx.x; dest[i] = a[i] * b[i]; } """) multiply_them = mod.get_function("multiply_them") a = numpy.random.randn(400).astype(numpy.float32) b = numpy.random.randn(400).astype(numpy.float32) dest = numpy.zeros_like(a) multiply_them( drv.Out(dest), drv.In(a), drv.In(b), block=(400,1,1), grid=(1,1)) print dest-a*b And I'm receiving the following error: > python test.py Traceback (most recent call last): File "test.py", line 12, in <module> """) File "/Library/Python/2.7/site-packages/pycuda-2013.1.1-py2.7-macosx-10.9-intel.egg/pycuda/compiler.py", line 251, in __init__ arch, code, cache_dir, include_dirs) File "/Library/Python/2.7/site-packages/pycuda-2013.1.1-py2.7-macosx-10.9-intel.egg/pycuda/compiler.py", line 241, in compile return compile_plain(source, options, keep, nvcc, cache_dir) File "/Library/Python/2.7/site-packages/pycuda-2013.1.1-py2.7-macosx-10.9-intel.egg/pycuda/compiler.py", line 132, in compile_plain stderr=stderr.decode("utf-8", "replace")) pycuda.driver.CompileError: nvcc compilation of /var/folders/xr/m_rf4dp96mn2tb4yxlwcft7h0000gp/T/tmpqQcztC/kernel.cu failed [command: nvcc --cubin -arch sm_30 -m64 -I/Library/Python/2.7/site-packages/pycuda-2013.1.1-py2.7-macosx-10.9-intel.egg/pycuda/cuda kernel.cu] [stderr: nvcc fatal : Path to libdevice library not specified ] I've searched google and found the following threads, but they don't help solve the issue; <http://lists.tiker.net/pipermail/pycuda/2011-June/003244.html> ... TIA! Answer: So the problem is that I hadn't installed a minor update from the nvidia control panel. After that and updating my bash_profile it works. Heh.
Python parse large db over 4gb Question: I'm trying to parse a `db` file with python that is over 4 gb. Example from the db file: % Tags relating to '217.89.104.48 - 217.89.104.63' % RIPE-USER-RESOURCE inetnum: 194.243.227.240 - 194.243.227.255 netname: PRINCESINDUSTRIEALIMENTARI remarks: INFRA-AW descr: PRINCES INDUSTRIE ALIMENTARI descr: Provider Local Registry descr: BB IBS country: IT admin-c: DUMY-RIPE tech-c: DUMY-RIPE status: ASSIGNED PA notify: [email protected] mnt-by: INTERB-MNT changed: [email protected] 20000101 source: RIPE remarks: **************************** remarks: * THIS OBJECT IS MODIFIED remarks: * Please note that all data that is generally regarded as personal remarks: * data has been removed from this object. remarks: * To view the original object, please query the RIPE Database at: remarks: * http://www.ripe.net/whois remarks: **************************** % Tags relating to '194.243.227.240 - 194.243.227.255' % RIPE-USER-RESOURCE inetnum: 194.16.216.176 - 194.16.216.183 netname: SE-CARLSTEINS descr: CARLSTEINS TRAFIK AB org: ORG-CTA17-RIPE country: SE admin-c: DUMY-RIPE tech-c: DUMY-RIPE status: ASSIGNED PA notify: [email protected] mnt-by: TELIANET-LIR changed: [email protected] 20000101 source: RIPE remarks: **************************** remarks: * THIS OBJECT IS MODIFIED remarks: * Please note that all data that is generally regarded as personal remarks: * data has been removed from this object. remarks: * To view the original object, please query the RIPE Database at: remarks: * http://www.ripe.net/whois remarks: **************************** I want to parse each block starting with `% Tags relating to` and out of the block I want to extract the `inetnum` and first `descr` This is what I got so far: **(Updated)** import re with open('test.db', "r") as f: content = f.read() r = re.compile(r'' 'descr:\s+(.*?)\n', re.IGNORECASE) res = r.findall(content) print res Answer: If you only want to get **first** descr : r = re.compile(r'' 'descr:\s+(.*?)\n(?:descr:.*\n)*', re.IGNORECASE) If you want inetnum and first descr : [ a + b for (a,b) in re.compile(r'' '(?:descr:\s+(.*?)\n(?:descr:.*\n)*)|(?:inetnum:\s+(.*?)\n)', re.IGNORECASE) ] I must admit I make no use of `% Tags relating to`, and that I suppose that all `descr` are consecutive.
Moving a Java Swing Graphic Question: I want to recreate a game I made in Python and after learning the basics of Swing, I moved on to drawing Graphics. Now I'm stuck. I created a black square and would like to move its coordinates by 10 to the right. What I want is to be able to make an animation by moving the square and be able to respond to the user's actions. Right now all I want is when the window is created (now), at run time for the square to be redrawn 10 pixels to the right. In Python Tkinter this was easy: square = myCanvas.create_rectangle(10, 10, 20, 20) then later in the code, I would do this: x = 10 while True: x = x + 10 myCanvas.coords(square, x, y, x+10, y+20) time.sleep(0.1) myMainWindow.update() It would move the square to the right for ever. Here is my Java code: package tutorial2; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JFrame; import javax.swing.JPanel; public class Tutorial2 { public static void main(String[] args) { make_gui(); } static void make_gui(){ JFrame f = new JFrame("My Window"); f.getContentPane().setPreferredSize(new Dimension(500, 300)); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new MyPanel()); f.pack(); f.setVisible(true); } } class MyRectangle extends Rectangle{ Rectangle self; int x; int y; public MyRectangle(int x, int y){ this.x = x; this.y = y; this.self = new Rectangle(this.x, this.y, this.x+10, this.y+10); } } class MyPanel extends JPanel{ MyRectangle user = new MyRectangle(10, 10); Rectangle user2 = new Rectangle(30, 30, 40, 40); public MyPanel(){ }; public void paintComponent(Graphics g){ Graphics2D graphics2d = (Graphics2D) g; //graphics2d.fill(user2); graphics2d.fill(user.self); } } How do I do it in here? Answer: Just use: g.drawRect(x1,y1,width,height); Or: g.fillRect(x1,y1,width,height); You don't need a `Rectangle` object or your own `MyRectangle` object. You can store the coordinates and update them every frame.
Add page number to a Word document using Python Question: Is there a way to add page numbers to the lower right corner of a Word document using Python win32com? I am able to add headers and footers, but I can't find a way to add page numbers in the format PageNumber of TotalPages (for example: 1 of 5) Below is the code to add centered headers and footers to a page from win32com.client import Dispatch as MakeDoc filename = name + '.doc' WordDoc = MakeDoc("Word.Application") WordDoc = WordDoc.Documents.Add() WordDoc.Sections(1).Headers(1).Range.Text = name WordDoc.Sections(1).Headers(1).Range.ParagraphFormat.Alignment = 1 WordDoc.Sections(1).Footers(1).Range.Text = filename WordDoc.Sections(1).Footers(1).Range.ParagraphFormat.Alignment = 1 Thanks Answer: To insert page numbers use the following statements: WordDoc.Sections(1).Footers(1).PageNumbers.Add(2,True) WordDoc.Sections(1).Footers(1).PageNumbers.NumberStyle = 57 However, the format of the page number is -page number-. Documentation for inserting the page number is [here](http://msdn.microsoft.com/en- us/library/bb178815%28v=office.12%29.aspx), and the one for the number style is [here](http://msdn.microsoft.com/en- us/library/bb237910%28v=office.12%29.aspx)
WSGI - Why does it cache the output for : os.popen("date").read() in multi threads and picks one randomly? Question: I woke up and refreshed my wsgi script via web. within this wsgi script there is this python code. import os ooo = os.popen("date").read() the system date was incorrect. so i refreshed the wsgi script. the system time was now showing something that was BEFORE the system time i saw earlier. the more i refreshed the web browser.. the more i noticed the output is rather random. the system time was as if.. either python or wsgi was caching it 10 times in 10 different threads and then displaying one randomly from those 10 cached threads. based on information.. it turns out python is not doing the caching and that WSGI might be responsible for this caching. well... my understanding was WSGI was simply permitting python to work via web.. i had no idea it was doing things as well such as threading and caching. i even see suggestions that WSGI is loaded once and thus it can only execute it once. does this mean i have to reload the WSGI script for every time i want a non- cached result ? so basically might as well restart the whole apache for everytime i execute a wsgi script on my web site ? i suppose this means i would be restarting apache 1 million times daily if my web site received that many hits per day ? how can i tell WSGI to not cache the output for os.popen("date").read() ? Answer: The 'caching' happens because the WSGI server/container only loads the application once. After that, for each request it calls the WSGI function. That means that any global (module level) variables will only be initialized once. Take this simple example: #!/usr/bin/python2 import time startup_time = time.ctime() def application(environ, start_response): current_time = time.ctime() start_response('200 OK', [('Content-Type', 'text/plain')]) return [startup_time, '\n', current_time] if __name__ == '__main__': from wsgiref import simple_server srv = simple_server.make_server('localhost', 8080, application) srv.serve_forever() if you'll run this, you'll see that the first time stays constant, the second doesn't. The same is true if you run this example using a different WSGI server (like apache/mod_wsgi), only that usually multiple instances of the application are launced and used to serve different requests. That explains why you see different values. So the solution is simple: everything that should be dynamic must be generated within the call to the wsgi function, don't use globals.
Scraping data from multiple URL Question: I wish to scrape data from [a link][http://cbfcindia.gov.in/html/SearchDetails.aspx?mid=1&Loc=Backlog](http://cbfcindia.gov.in/html/SearchDetails.aspx?mid=1&Loc=Backlog)! , However the MID parameter is incremental in URL to give 2nd, 3rd URL ..... till 1000 URLs, so how shall I deal with this(I am new to PYTHON AND SCRAPY, so dont mind me asking this)? Please check the XPATH i have used to extract the information, it is fetching no output, is there elementary error in the spider from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from movie.items import MovieItem class MySpider(BaseSpider): name = 'movie' allowed_domains= ["http://cbfcindia.gov.in/"] start_urls = ["http://cbfcindia.gov.in/html/SearchDetails.aspx?mid=1&Loc=Backlog"] def parse(self, response): hxs = HtmlXPathSelector(response) titles = hxs.select("//body") #Check print titles items = [] for titles in titles: print "in FOR loop" item = MovieItem() item ["movie_name"]=hxs.xpath('//TABLE[@id="Table2"]/TR[2]/TD[2]/text()').extract() print "XXXXXXXXXXXXXXXXXXXXXXXXX movie name:", item["movie_name"] item ["movie_language"] = hxs.xpath('//*[@id="lblLanguage"]/text()').extract() item ["movie_category"] = hxs.xpath('//*[@id="lblRegion"]/text()').extract() item ["regional_office"] = hxs.xpath('//*[@id="lblCertNo"]/text()').extract() item ["certificate_no"] = hxs.xpath('//*[@id="Label1"]/text()').extract() item ["certificate_date"] = hxs.xpath('//*@id="lblCertificateLength"]/text()').extract() item ["length"] = hxs.xpath('//*[@id="lblProducer"]/text()').extract() item ["producer_name"] = hxs.xpath('//*[@id="lblProducer"]/text()').extract() items.append(item) print "this is ITEMS" return items Below is the log : log> {'certificate_date': [], 'certificate_no': [], 'length': [], 'movie_category': [], 'movie_language': [], 'movie_name': [], 'producer_name': [], 'regional_office': []} 2014-06-11 23:20:44+0530 [movie] INFO: Closing spider (finished) 214-06-11 23:20:44+0530 [movie] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 256, 'downloader/request_count': 1, 'downloader/request_method_count/GET': 1, 'downloader/response_bytes': 6638, 'downloader/response_count': 1, 'downloader/response_status_count/200': 1, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2014, 6, 11, 17, 50, 44, 54000), 'item_scraped_count': 1, 'log_count/DEBUG': 4, 'log_count/INFO': 7, 'response_received_count': 1, 'scheduler/dequeued': 1, 'scheduler/dequeued/memory': 1, 'scheduler/enqueued': 1, 'scheduler/enqueued/memory': 1, 'start_time': datetime.datetime(2014, 6, 11, 17, 50, 43, 681000)} Answer: In addition to @Talvalin's answer, the correct XPath should be of the form: item["movie_name"] = hxs.xpath("//*[@id='lblMovieName']/font/text()").extract() For some reason, when the page loads, the `<font>` tag get separated from the `<span>` tag (or whatever tag the `id` is in). I've tested this and it works. Word of warning, though: the site is pretty much protected from scraping. I've tried running a second scrape and it immediately threw a `Runtime Error`.
How/where to specify Open SQL in PyRFC call to SAP RFC_READ_TABLE Question: How do I specify the Open SQL WHERE clause in an RFC_READ_TABLE query using PyRFC? I'm trying to get started with PyRFC to have python do table extractions from SAP (in the absence of a supportive/cooperative basis team). In this example from <http://scn.sap.com/community/scripting- languages/blog/2012/11/04/revisiting-python-and-sap-with-pyrfc>, they use: pyrfc.Connector.call("RFC_READ_TABLE", QUERY_TABLE=table, DELIMITER='|') <http://saplsmw.com/node/101> says that a WHERE clause needs to be passed as an OPTION to the RFC call. How do I do this in PyRFC? (OPTIONS is an exporting variable of type table in RFC_READ_TABLE's function module declaration on the SAP end). EDIT: OK <http://scn.sap.com/community/scripting- languages/blog/2014/05/05/python-for-basis> has an example of sending the WHERE clause in OPTIONS: OPTIONS = [{'TEXT':source_where}]) So it looks like the syntax is an array (maps the SAP table type) of single element dictionaries where the key is the SAP data type and the value is the WHERE clause. So next question is: How do I specify a PACKAGE SIZE to be sent to RFC_READ_TABLE so that I can extract large tables without hitting internal table limits? Answer: RFC_READ_TABLE has a parameter 'ROWCOUNT' which specifies the maximum number of rows to return in a single call. Of course, if you say restrict it to 1000 rows at a time there may be other rows that you never download if the table contains more than 1000 rows. To solve this there is another parameter, 'ROWSKIPS' through which you specify the starting row you want to return. So, with the first call ROWCOUNT = 1000 ROWSKIPS = 0 The next call ROWCOUNT = 1000 ROWSKIPS = 1000 The next call ROWCOUNT = 1000 ROWSKIPS = 2000 and so on, incrementing ROWSKIPS each time as follows: ROWSKIPS = ROWSKIPS + ROWCOUNT. An example PyRFC call with both ROWCOUNT and ROWSKIPS defined, which reads from TCURR in batches of 10 (and where FCURR is set to 'USD'): #!/usr/bin/env python from pyrfc import Connection, ABAPApplicationError, ABAPRuntimeError, LogonError, CommunicationError from ConfigParser import ConfigParser from pprint import PrettyPrinter def main(): try: config = ConfigParser() config.read('sapnwrfc.cfg') params_connection = config._sections['connection'] conn = Connection(**params_connection) options = [{ 'TEXT': "FCURR = 'USD'"}] pp = PrettyPrinter(indent=4) ROWS_AT_A_TIME = 10 rowskips = 0 while True: print u"----Begin of Batch---" result = conn.call('RFC_READ_TABLE', \ QUERY_TABLE = 'TCURR', \ OPTIONS = options, \ ROWSKIPS = rowskips, ROWCOUNT = ROWS_AT_A_TIME) pp.pprint(result['DATA']) rowskips += ROWS_AT_A_TIME if len(result['DATA']) < ROWS_AT_A_TIME: break except CommunicationError: print u"Could not connect to server." raise except LogonError: print u"Could not log in. Wrong credentials?" raise except (ABAPApplicationError, ABAPRuntimeError): print u"An error occurred." raise if __name__ == '__main__': main()
In Python, is it possible to overload Numpy's memmap to delete itself when the memmap object is no longer referenced? Question: I am trying to use memmap when certain data doesn't fit in memory and employ memmap's ability to trick code into thinking it's just an ndarray. To further expand on this way of using memmap I was wondering if it would be possible to overload memmap's dereference operator to delete the memmap file. So for example: from tempfile import mkdtemp import os.path as path filename = path.join(mkdtemp(), 'tmpfile.dat') { out = np.memmap(filename, dtype=a.dtype, mode='w+', shape=a.shape) } # At this point out is out of scope, so the overloaded # dereference function would delete tmpfile.dat Does this sound feasible/has this been done? Is there something I am not thinking of? Thank you! Answer: just delete the file after it has been opened by `np.memmap` the file will then be deleted by the system after the last reference to the file descriptor is closed. python temporary files work like this and can very conveniently be used with the `with` context manger construct: with tempfile.NamedTemporaryFile() as f: # file gone now from the filesystem # but f still holds a reference so it still exists and uses space (see /prof<pid>/fd) # open it again (will not work on windows) x = np.memmap(f.name, dtype=np.float64, mode='w+', shape=(3,4)) # f reference is gone now but x still has a reference del x # now all references are gone and the file is properly deleted
How to monitor VLC media player on Windows 7 using Python? Question: I want to know what's currently playing on [VLC media player](http://en.wikipedia.org/wiki/VLC_media_player) (Windows 7) using Python 2.7. Just knowing the details of the track/video is sufficient. **Research:** I came to know that VLC media player has [python- bindings](https://wiki.videolan.org/Python_bindings). I also found out a way to play some track using a [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) script. But I couldn't find a suitable way to check what's being played on VLC media player. **Clarification:** I have the script running. I play a audio track on my VLC media player manually on my machine, and I want that script to detect and show the details of the track present for the file playing. Answer: As per my understanding of your question: > I have the script running. I play a audio track on my VLC manually on my > machine and I want that script to detect and show the details of the track > present for the file playing. There could be two possibilities to retrieve the information of the current item being played in the VLC player. **First method** : Tested on Windows 7 OS and VLC v2.1.3 You have to first setup the web interface in the VLC player and then activate it. Then you can access all the information of currently playing track from a XML file by visiting this link `http://localhost:8080/requests/status.xml`. You can create a simple script in python that will visit the link above and fetch the information. **Dummy code** : This code will simply display the complete information of the file currently being played in the VLC player, you can try to extract what you need: import requests def getInfo(): s = requests.Session() s.auth = ('', 'password')# Username is blank, just provide the password r = s.get('http://localhost:8080/requests/status.xml', verify=False) print r.text getInfo() You cab get Requests lib [here](http://docs.python-requests.org/en/latest/). **Activating web interface** : Open VLC goto `Tools--->Preferences-----> Main Interface` as shown below tick mark the `web` option. ![player1](http://i.stack.imgur.com/wo3It.png) Then click on `Lua` option on the left pane. Enter the password in the `password` field and enter `C:\Program Files\VideoLAN\VLC\lua\http` in the `source directory` field as shown below. Verify that you have status.xml file at the location that you provided in the `source directory`. ![player 2](http://i.stack.imgur.com/EFTo4.png) **Testing** : Start the VLC player and play some file. Visit `http://localhost:8080/requests/status.xml` and you shall see a login page, leave the username field blank and enter the password that you entered in the VLC. If you logged in successfully you shall see the XML file! If you don't see any thing then do the following as shown in the image below: goto `View--->Add Interface----->Select web` ![player3](http://i.stack.imgur.com/qGaPg.png) If everything works fine now run the script that I provided above. You shall see the information of the file in the console, now you can modify the script to get only the information that you desire. _PS: The username field is blank, just enter your password in the script._ **Second method** : (_I think this is not what you desired!_) This case is when you'll play the file using python binding itself. [Here](http://liris.cnrs.fr/advene/download/python-ctypes/doc/vlc.MediaPlayer- class.html) you can find many different methods that can be used to get the information of the current playing item in the VLC. For an instance: [get_length(self)](http://liris.cnrs.fr/advene/download/python- ctypes/doc/vlc.MediaPlayer-class.html#get_length) given length of the current item being played and [get_title()](http://liris.cnrs.fr/advene/download/python- ctypes/doc/vlc.MediaPlayer-class.html#get_title) to get the title number and [get_state(self)](http://liris.cnrs.fr/advene/download/python- ctypes/doc/vlc.MediaPlayer-class.html#get_state) to know if the player is playing something or is it paused/stopped. `get_mrl()` gives the location of the track and also contains the track name at last, so you can figure out how to get track name from the location string using python. **Dummy code** : import vlc def setup_player(filename): vlc_instance = vlc.Instance() media = vlc_instance.media_new(filename) player = vlc_instance.media_player_new() player.set_media(media) print media.get_mrl()# File location to get title ;) print player.get_length()#Time duration of file print player.get_state()#Player's state setup_player(filename)#Put file name/location here
Post Request to web server with Flask Question: When you run this python script, you will see a feature of network connection with flask on 127.0.0.1:5000/ But, I could not figure out to print all of features of network from starting to run script. I mean I'm losing the previous data, so I could print any one feature of my network to my web server when refreshing my page. I haven't found anything specific in Flask documentation. Some say urllib2 or post.request is useful for it, but I'm new to Flask and Python for web at all. Thanks in advance! Code: import socket, sys from struct import * from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP) while True: packet = s.recvfrom(65536) packet = packet[0] ip_header = packet[0:20] iph = unpack('!2B3H2BH4s4s' , ip_header) t_length = iph[2] protocol = iph[6] s_addr = socket.inet_ntoa(iph[8]); d_addr = socket.inet_ntoa(iph[9]); protocol_s = protocol if protocol == 1: protocol_s = 'ICMP' if protocol == 6: protocol_s = 'TCP' if protocol == 17: protocol_s = 'UDP' tcp_header = packet[20:40] tcph = unpack('!HHLLBBHHH' , tcp_header) dest_port = tcph[1] test = 'Protocol : ' + protocol_s + ' | Source Address : ' + str(s_addr) + ' | Destination Address : ' + str(d_addr) + ' | Dest Port : ' + str(dest_port) + ' | Packet Length : ' + str(t_length) return test if __name__ == '__main__': app.run() Answer: First of all, Flask is a WSGI framework. It will only work on TCP/IP and HTTP is the protocol you will use in _most cases_. You might use websockets and other protocols, but they will also work over TCP. The socket handling is already done by the server and you do not have to worry about it. For getting information about the connection, I'm not sure how much you can get out. You can take a look at the [`flask.Request`](http://flask.pocoo.org/docs/api/#incoming-request-data) and the [`werkzeug.wrappers.Request`](http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.Request) objects. For example, you can get the remote address from the `request`: from flask import request @app.route('/') def hello(): print request.remote_addr
Django project wont run on ubuntu with aditional installed apps Question: My setup * Local machine 10.9.3 * Django 1.6.2 - local machine * Server Ubuntu 12.04 * Django 1.6 - ubuntu server When deploying a django project to a server running Ubunto 12.04 I found that having an additional, but non existent application listed in my `INSTALLED_APPS` section of my `settings.py` file prevented me from using any of the `python manage.py` commands. INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', 'survey', 'django_countries', ) In this case I had previously had a `django_countries` application in the project which I subsequently deleted. However that never prevented me from being able to use any of the `python manage.py` commands on my local machine `OSX 10.9.3` However when I uploaded the project to my production server it would give me errors e.g. running `python manage.py runserver` would get me $ python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 280, in execute translation.activate('en-us') File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/__init__.py", line 130, in activate return _trans.activate(language) File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 188, in activate _active.value = translation(language) File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 177, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 159, in _fetch app = import_module(appname) File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 40, in import_module __import__(name) ImportError: No module named django_countries Of course removing the unnecessary `django_countries` app in the `settings.py` solved my problem but I would like to know: Why is it different between the two environments? are there significant other differences that I should watch out for? Answer: That's a completely expected behaviour - `INSTALLED_APPS` defines which applications you have installed and Django tries to find theirs models, urls etc. If it can't find anything _installed_ , you'll get this error. Either remove it from `INSTALLED_APPS` or install it. Also it looks like you don't use VirtualEnv. Learn how to use it and use it for every project otherwise you'll get nuts soon .)
Calling celery task hangs for delay and apply_async Question: I have created a celery app with following directory structure (as given in celery site): proj |-- celery.py |-- celery.pyc |-- __init__.py |-- __init__.pyc |-- tasks.py `-- tasks.pyc Following are contents of celery.py from __future__ import absolute_import from celery import Celery app = Celery('proj', broker='amqp://rabbitmquser:<my_passowrd>@localhost:5672/localvhost', #backend='amqp://', include=['proj.tasks']) # Optional configuration, see the application user guide. app.conf.update( CELERY_TASK_RESULT_EXPIRES=3600, ) if __name__ == '__main__': app.start() Following is the content of tasks.py from __future__ import absolute_import from proj.celery import app @app.task def add(x, y): return x + y @app.task def mul(x, y): return x * y @app.task def xsum(numbers): return sum(numbers) Now I am starting celery worker with following command: celery -A proj worker -l debug I think worker is running fine as it outputs following on: [2014-06-12 21:25:02,326: DEBUG/MainProcess] | Worker: Preparing bootsteps. [2014-06-12 21:25:02,328: DEBUG/MainProcess] | Worker: Building graph... [2014-06-12 21:25:02,328: DEBUG/MainProcess] | Worker: New boot order: {Timer, Hub, Queues (intra), Pool, Autoscaler, Beat, Autoreloader, StateDB, Consumer} [2014-06-12 21:25:02,331: DEBUG/MainProcess] | Consumer: Preparing bootsteps. [2014-06-12 21:25:02,331: DEBUG/MainProcess] | Consumer: Building graph... [2014-06-12 21:25:02,334: DEBUG/MainProcess] | Consumer: New boot order: {Connection, Events, Mingle, Tasks, Control, Agent, Heart, Gossip, event loop} [2014-06-12 21:25:02,335: WARNING/MainProcess] /home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/celery/apps/worker.py:161: CDeprecationWarning: Starting from version 3.2 Celery will refuse to accept pickle by default. The pickle serializer is a security concern as it may give attackers the ability to execute any command. It's important to secure your broker from unauthorized access when using pickle, so we think that enabling pickle should require a deliberate action and not be the default choice. If you depend on pickle then you should set a setting to disable this warning and to be sure that everything will continue working when you upgrade to Celery 3.2:: CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml'] You must only enable the serializers that you will actually use. warnings.warn(CDeprecationWarning(W_PICKLE_DEPRECATED)) -------------- celery@ansumanb-u12 v3.1.12 (Cipater) ---- **** ----- --- * *** * -- Linux-3.5.0-25-generic-x86_64-with-Ubuntu-12.04-precise -- * - **** --- - ** ---------- [config] - ** ---------- .> app: proj:0x1f46690 - ** ---------- .> transport: amqp://rabbitmquser:**@localhost:5672/localvhost - ** ---------- .> results: disabled - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- --- ***** ----- [queues] -------------- .> celery exchange=celery(direct) key=celery [tasks] . celery.backend_cleanup . celery.chain . celery.chord . celery.chord_unlock . celery.chunks . celery.group . celery.map . celery.starmap . proj.tasks.add . proj.tasks.mul . proj.tasks.xsum [2014-06-12 21:25:02,336: DEBUG/MainProcess] | Worker: Starting Hub [2014-06-12 21:25:02,336: DEBUG/MainProcess] ^-- substep ok [2014-06-12 21:25:02,336: DEBUG/MainProcess] | Worker: Starting Pool [2014-06-12 21:25:02,344: DEBUG/MainProcess] ^-- substep ok [2014-06-12 21:25:02,345: DEBUG/MainProcess] | Worker: Starting Consumer [2014-06-12 21:25:02,345: DEBUG/MainProcess] | Consumer: Starting Connection After running the worker I am opening the terminal and from python interpreter and executing following: >>> from proj.tasks import add >>> add(2,2) 4 >>> add.delay(2,3) Here the delay hangs (same story for apply_async). When I am stopping it by Ctrl+C I am getting following: ^CTraceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/celery/app/task.py", line 453, in delay return self.apply_async(args, kwargs) File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/celery/app/task.py", line 555, in apply_async **dict(self._get_exec_options(), **options) File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/celery/app/base.py", line 352, in send_task reply_to=reply_to or self.oid, **options File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/celery/app/amqp.py", line 305, in publish_task **kwargs File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/kombu/messaging.py", line 168, in publish routing_key, mandatory, immediate, exchange, declare) File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/kombu/connection.py", line 436, in _ensured return fun(*args, **kwargs) File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/kombu/messaging.py", line 173, in _publish channel = self.channel File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/kombu/messaging.py", line 190, in _get_channel channel = self._channel = channel() File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/kombu/utils/__init__.py", line 422, in __call__ value = self.__value__ = self.__contract__() File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/kombu/messaging.py", line 205, in <lambda> channel = ChannelPromise(lambda: connection.default_channel) File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/kombu/connection.py", line 756, in default_channel self.connection File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/kombu/connection.py", line 741, in connection self._connection = self._establish_connection() File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/kombu/connection.py", line 696, in _establish_connection conn = self.transport.establish_connection() File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/kombu/transport/pyamqp.py", line 112, in establish_connection conn = self.Connection(**opts) File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/amqp/connection.py", line 171, in __init__ (10, 10), # start File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/amqp/abstract_channel.py", line 67, in wait self.channel_id, allowed_methods) File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/amqp/connection.py", line 237, in _wait_method self.method_reader.read_method() File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/amqp/method_framing.py", line 186, in read_method self._next_method() File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/amqp/method_framing.py", line 107, in _next_method frame_type, channel, payload = read_frame() File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/amqp/transport.py", line 153, in read_frame frame_type, channel, size = unpack('>BHI', read(7, True)) File "/home/ansumanb/.virtualenvs/celery_venv/local/lib/python2.7/site-packages/amqp/transport.py", line 272, in _read s = recv(n - len(rbuf)) KeyboardInterrupt Any suggestion or comment will be much appreciated. I have gone through other links where they talk about /var directory size but I think I have enough space. Result of df -h Filesystem Size Used Avail Use% Mounted on /dev/sda3 283G 99G 170G 37% / udev 1.9G 4.0K 1.9G 1% /dev tmpfs 388M 1.1M 387M 1% /run none 5.0M 0 5.0M 0% /run/lock none 1.9G 28M 1.9G 2% /run/shm following is the result of rabbitmqctl status Status of node 'rabbit@ansumanb-u12' ... [{pid,12014}, {running_applications,[{rabbit,"RabbitMQ","3.3.2"}, {os_mon,"CPO CXC 138 46","2.2.7"}, {xmerl,"XML parser","1.2.10"}, {mnesia,"MNESIA CXC 138 12","4.5"}, {sasl,"SASL CXC 138 11","2.1.10"}, {stdlib,"ERTS CXC 138 10","1.17.5"}, {kernel,"ERTS CXC 138 10","2.14.5"}]}, {os,{unix,linux}}, {erlang_version,"Erlang R14B04 (erts-5.8.5) [source] [64-bit] [smp:4:4] [rq:4] [async-threads:30] [kernel-poll:true]\n"}, {memory,[{total,27919080}, {connection_procs,2704}, {queue_procs,5408}, {plugins,0}, {other_proc,9099992}, {mnesia,63776}, {mgmt_db,0}, {msg_index,34080}, {other_ets,784160}, {binary,12144}, {code,14685283}, {atom,1367393}, {other_system,1864140}]}, {alarms,[]}, {listeners,[{clustering,25672,"::"},{amqp,5672,"::"}]}, {vm_memory_high_watermark,0.4}, {vm_memory_limit,1625165004}, {disk_free_limit,50000000}, {disk_free,181684699136}, {file_descriptors,[{total_limit,2}, {total_used,0}, {sockets_limit,0}, {sockets_used,0}]}, {processes,[{limit,1048576},{used,127}]}, {run_queue,0}, {uptime,20072}] ...done. I've checked the rabbitmq logs and didn't get anything there. Celery version is 3.1.12. I have created rabbitmq virtual host and user with following commands $ sudo rabbitmqctl add_user rabbitmquser <mypassword> $ sudo rabbitmqctl add_vhost localvhost $ sudo rabbitmqctl set_permissions -p localvhost rabbitmquser ".*" ".*" ".*" Thanks Answer: I did a great mistake. My problem was I tried to change something about which I didn't know. I am adding it for others reference. While installing rabbitmq I changed the default value of `ulimit` from 1024 to 100 at `/etc/default/rabbitmq-server`. I changed the value back to 1024 and the issue is fixed now.
no json module when running python script in docker container Question: I'm trying to run a simple python script that takes a json string as an argument in a docker container. However I get the following error: Traceback (most recent call last): File "/root/simple.py", line 2, in <module> import json ImportError: No module named json I'm running the standard ubuntu:12.04 image. Here's how I call up the container: docker run -v $(pwd)/:/root/ ubuntu:12.04 python /root/simple.py '[{"hi":"bye"}]' My `simple.py` script is just: import sys import json configs = json.loads(sys.argv[1]) print configs def read_option_keys(json_file): json_file[0]["new"] = None print json.dumps(json_file) read_option_keys(configs) Any idea why it's not returning the following as expected: [{u'hi': u'bye'}] [{"hi": "bye", "new": null}] Answer: I was able to solve the issue myself. Ubuntu image is super bare-bones. I pulled the `dockerfile/python` image and now it works.
How to get all values from Python tuple keys from dictionaries into one list? Question: My question may be a bit weird, but I don't know how else to put it. The situation is that I've got a dict with tuples as keys: {(1, 2): 'a', (3, 4): 'b', (5, 6): 'c'} I now want to get a list (or tuple) of all the values in the tuples in the dict. So the result should look like this: [1, 2, 3, 4, 5, 6] Does anybody know how I can do this in an efficient and pythonic way? All tips are welcome! [EDIT] Seeing that I get a lot of responses with some extra questions: I don't care about the order, but possible duplicates should be removed.. Answer: Chain the keys together, with a list comprehension for example: [v for key in yourdict for v in key] If you only need to iterate, using [`itertools.chain.from_iterable()`](https://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable) could do: from itertools import chain for v in chain.from_iterable(yourdict): A dictionary has no ordering, so the values from the keys won't be in any specific order either (although the 2 values per key do remain consecutive). You can always sort them with: sorted(v for key in yourdict for v in key) or sorted(chain.from_iterable(yourdict)) If you don't care about order but don't want duplicates, then _produce a set_ instead: {v for key in yourdict for v in key} Demo: >>> yourdict = {(1, 2): 'a', (3, 4): 'b', (5, 6): 'c'} >>> [v for key in yourdict for v in key] [1, 2, 5, 6, 3, 4] >>> from itertools import chain >>> list(chain.from_iterable(yourdict)) [1, 2, 5, 6, 3, 4] >>> sorted(v for key in yourdict for v in key) [1, 2, 3, 4, 5, 6] >>> sorted(chain.from_iterable(yourdict)) [1, 2, 3, 4, 5, 6] And producing a set: >>> anotherdict = {(1, 2): 'a', (3, 4): 'b', (4, 2): 'c'} >>> {v for key in yourdict for v in key} set([1, 2, 3, 4, 5, 6]) >>> {v for key in anotherdict for v in key} set([1, 2, 3, 4])
How to add form-data variables to a post request using python requests module? Question: I am trying to create a command line utility to upload files to tempsend.com using Python's `requests` module. I have read the docs and it seems like what I am trying to accomplish should be quite easy, but I can't get it to successfully post the file. Here are some of the formats I have tried: >>> import requests >>> url = "http://tempsend.com/send" >>> payload = {'file': open('happy.txt', 'rb'), 'expire': '2678400'} >>> r = requests.post(url, data=payload) >>> r.url u'http://tempsend.com/error-nopostdata' and: >>> files = {'file': open('happy.txt', 'rb'), 'expire' : '2678400'} >>> r = requests.post(url, files=files) >>> r.url u'http://tempsend.com/error-badsecondsvalue' It looks like the `'expire'` field is not recognized. I think this is what a valid raw request should look like: POST /send HTTP/1.1 Host: tempsend.com User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:29.0) Gecko/20100101 Firefox/29.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip, deflate Referer: http://tempsend.com/ Cookie: __utma=151760572.1993029721.1402528667.1402603529.1402606574.3; __utmz=151760572.1402528667.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=151760572.2.10.1402606574; __utmc=151760572 Connection: keep-alive Content-Type: multipart/form-data; boundary=---------------------------18953598303296896262036228879 Content-Length: 835112 -----------------------------18953598303296896262036228879 Content-Disposition: form-data; name="file"; filename="modules.alias" Content-Type: application/octet-stream # Aliases extracted from modules themselves. alias aes-asm aes_x86_64 alias aes aes_x86_64 alias camellia-asm camellia_x86_64 <blablablablablablablabla> -----------------------------18953598303296896262036228879 Content-Disposition: form-data; name="expire" 2678400 -----------------------------18953598303296896262036228879-- Answer: >>> import requests >>> files = {'file': open('happy.txt', 'rb')} >>> url = "http://tempsend.com/send" >>> r = requests.post(url, data={'expire':'2678400'}, files=files) >>> r.url u'http://tempsend.com/36DCF220A3' >>> I found the answer 5 minutes after asking the question.. Typical!
Writing multiple dictionaries to CSV with one header with Python Question: I am trying to write multiple dictionaries to a csv file, where header (key) gets written only once and rows (values) are written based on the key. I was able to figure this out for two dictionaries, but what if I am getting multiple dictionaries that need to be written? I am streaming tweets which get converted to json, so I am trying to end with a CSV file that is sorted by each JSON key. Here is a more detailed explanation of what I am trying to do ([Writing multiple JSON to CSV in Python - Dictionary to CSV](http://stackoverflow.com/questions/24155319/writing- multiple-json-to-csv-in-python-dictionary-to-csv) Here is what I am trying to end up with but with thousands of potential rows of data (preferably sorted by key if possible): ![Table](http://i.stack.imgur.com/QQU1m.png) Here is my basic code for two dictionaries: import csv my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4', 'key5': 'value5', 'key6': 'value6', 'key7': 'value7'} my_dict2 = {'key1': 'value1A', 'key2': 'value2A', 'key3': 'value3A', 'key4': 'value4A', 'key5': 'value5A', 'key6': 'value6A', 'key7': 'value7A'} with open('mycsvfile.csv', 'wb') as f: w = csv.DictWriter(f, my_dict.keys()) w.writeheader() w.writerow(my_dict) if my_dict.keys() == my_dict2.keys(): w.writerow(my_dict2) print my_dict P.S. I am a begginer! Answer: You can put the multiple dicts in a list. You then iterate over that list and only write the rows where the keys match. Something like this: keys = ['key1', 'key2', 'key3', 'key4', 'key5'] # and so forth.. dictionaries = [my_dict, my_dict2] # Just an example, you probably build this list while you stream the tweets. with open('mycsvfile.csv', 'wb') as f: w = csv.DictWriter(f, my_dict.keys()) w.writeheader() for d in [x for x in dictionaries if x.keys() == keys]: # only matching keys. w.writerow(d)
PyCharm import external library Question: I am using PyCharm as an editor for python code in Houdini. Whenever I try to import the main Houdini library (hou) I get an error flagged in PyCharm. If I include the code snippet:- try: import hou except ImportError: # Add $HFS/houdini/python2.6libs to sys.path so Python can find the # hou module. sys.path.append(os.environ['HFS'] + "/houdini/python%d.%dlibs" % sys.version_info[:2]) import hou my code executes, without problem, from both Houdini and my selected interpreter. My problem is with PyCharm itself. The editor flags 'import hou' as an error and any subsequent files that import this file flag modules imported by this file as errors as well. Hence I loose type ahead functionality and get an over abundance of error messages that make it hard to spot the real problems. How do I get PyCharm to recognize the path to the hou module. I have tried, for a couple of days, to Google a solution to this problem but they all seem to refer to tabs and settings that are not in my version of PyCharm (Community Edition 3.4.1). E.G. my 'Project Interpreter' setting only has a list of Packages and has no 'path' tab as stated in many 'fixes' to closely related problems. Answer: Okay. I have found the answer to this myself. It seems that since PyCharm 3.4 the path tab in the 'Project Interpreter' settings has been replaced. In order to add paths to a project you need to select the cogwheel, click on 'More...' and then select the "Show path for the selected interpreter" icon. This allows you to add paths to your project as before. My project is now behaving as I would expect. [![These are the windows you would see while following the instructions](http://i.stack.imgur.com/Dgh44.png)](http://i.stack.imgur.com/Dgh44.png)
Create a custom widget with PyGObject Question: I am trying to create a custom widget with **PyGObject**. For example I want to create this `CustomButton` widget which adds an image and a label in a button (it's just for the example) : #!/usr/bin/python #-*- coding: utf-8 -* from gi.repository import Gtk class ImageButton(Gtk.Widget): def __init__(self, label, image): Gtk.Widget.__init__(self) self.hbox = Gtk.HBox() self.label = Gtk.Label(label) self.image = Gtk.Image.new_from_stock(image, Gtk.IconSize.MENU) self.hbox.pack_start(self.image, False, False, 3) self.hbox.pack_start(self.label, False, False, 3) self.button = Gtk.Button() self.button.add(self.hbox) In another file or class, I can use it like that : button = ImageButton("My label", Gtk.STOCK_HOME) But when I want to use it, I am obliged to call the `button` attribute, like this : # Connect the "clicked" event button.button.connect("clicked", on_clicked_button) # Add the button in a container window.add(button.button) It works but it is not practical. How to create a custom widget working like any other widget please : button = ImageButton("My label", Gtk.STOCK_HOME) button.connect("clicked", on_clicked_button) window.add(button) Answer: I think that your problem it is actually a problem about understanding classes more then inheritance. If you want your widget to act exactly as a button, it should be a button. Take a look to the following example: from gi.repository import Gtk class ImageButton(Gtk.EventBox): def __init__(self, label): Gtk.EventBox.__init__(self) self.label = Gtk.Label(label) self.add(self.label) if __name__ == '__main__': def on_imagebutton_clicked(button, data=None): print("Button has been clicked!") window = Gtk.Window() button = ImageButton("My label") button.connect('button-press-event', on_imagebutton_clicked) window.add(button) window.show_all() Gtk.main() Instead of saying that my class it is a `Gtk.Widget`, I said that it is a `Gtk.EventBox` and I started it like it. From now on `ImageButton` will have the same attributes and methods like an `Gtk.EventBox`. *If I've made the same example by using `Gtk.Button` instead of a `Gtk.EventBox` **you could call** `button.connect(..` instead of `buton.connect.connect(..` as you want it in your question. The problem with this is that if `ImageButton` it is a `Gtk.Button` It is not any more possible of modifying it to do things that buttons don't do ( like adding containers and labels). **In a Few Words:** You can create a custom widget based in other widget, but only one widget will be at the top of the tree. --> Parent ---------> Child ---------> Child So when you do `self.method` it will always look to: 1) Your parent methods (the one you copied by using `Gtk.EventBox.__init__(self)` 2) The methods you created. Alternatively you can lie thanks to this: from gi.repository import Gtk class ImageButton(Gtk.EventBox): def __init__(self, label): Gtk.EventBox.__init__(self) self.label = Gtk.Label(label) self.add(self.label) def set_text(self, text): self.label.set_text(text) if __name__ == '__main__': def on_imagebutton_clicked(button, data=None): print("Button has been clicked!") window = Gtk.Window() button = ImageButton("My label") button.connect('button-press-event', on_imagebutton_clicked) button.set_text('New text!!') window.add(button) window.show_all() Gtk.main() Note that I didn't had to call `button.label.set_text(..)` I hope it be clear enough!
AttributeError: 'NoneType' object has no attribute 'replace' Question: right sorry that I'm not all good at python but my problem is that i need to replace a character here is the thing i am trying to change all i need to change is # to an A for all of the lines def puzzle(): print ("#+/084&;") print ("#3*#%#+") print ("8%203:") print (",1$&") print ("!-*%") print (".#7&33&") print ("#*#71%") print ("&-&641'2") print ("#))85") print ("9&330*;") so here is what i attempted to do(it was in another py file) from original_puzzle import puzzle puzzle() result = puzzle() question = input("first letter ") for letter in question: if letter == "a": result = result.replace("#","A") print (result) here is what it gives me Traceback (most recent call last): File "N:\AQA 4512;1-practical programming\code\game.py", line 36, in <module> result = result.replace("#","A") AttributeError: 'NoneType' object has no attribute 'replace' it would help if somebody told me a different way around it aswell thanks for the help and sorry again that i'm bad at python Answer: if you don't explicitly return something from a python function, python returns None. >>> def puzzle(): ... print 'hi' ... >>> >>> puzzle() is None hi True >>> def puzzle(): ... print 'hi' ... return None ... >>> puzzle() is None hi True >>> def puzzle(): ... return 'hi' ... >>> puzzle() 'hi' >>> puzzle() is None False >>>
Scala: Help me understand comprehensions and case classes in this code Question: I am trying to wrap my head around Scala, and I am finding it quite challenging so far. I found this library (<https://github.com/snowplow/scala- maxmind-geoip>) I used in the past with Python for finding out stuff like the country base on an IP address. So the example is pretty simple import com.snowplowanalytics.maxmind.geoip.IpGeo val ipGeo = IpGeo(dbFile = "/opt/maxmind/GeoLiteCity.dat", memCache = false, lruCache = 20000) for (loc <- ipGeo.getLocation("213.52.50.8")) { println(loc.countryCode) // => "NO" println(loc.countryName) // => "Norway" } And the documentation reads > The getLocation(ip) method returns an IpLocation case class So, if it is a case class, why this does not work? val loc = ipGeo.getLocation("213.52.50.8") println(loc.countryCode) After all I can do case class Team(team: String, country: String) val u = Team("Barcelon", "Spain") scala> u.country res5: String = Spain Thank you for your time! Answer: I guess the documentation is just outdated there. If you look in [the code](https://github.com/snowplow/scala-maxmind- geoip/blob/master/src/main/scala/com/snowplowanalytics/maxmind/geoip/IpGeo.scala) it does not return a `IpLocation` but an `Option[IpLocation]`. `Option` is a type from the scala standard library that has two constructors: `None` and `Some(value)`. So it is used where values are optional. `for` in scala is just syntactic sugar. `for (x <- xs) { println(x) }` is translated into `xs.foreach(x => println(x))`. So you basically call the `foreach` on option, which executes your printlines if a value was returned by `getLocation`.
Python 2.x optionnal subparsers - Error too few arguments Question: I have been trying to set up a main parser with two subs parser so that when called alone, the main parser would display a help message. def help_message(): print "help message" import argparse parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest='sp') parser_a = subparsers.add_parser('a') parser_a.required = False #some options... parser_b = subparsers.add_parser('b') parser_b.required = False #some options.... args = parser.parse_args([]) if args.sp is None: help_message() elif args.sp == 'a': print "a" elif args.sp == 'b': print "b" This code works well on Python 3 and I would like it to work aswell on Python 2.x I am getting this when running 'python myprogram.py' myprogram.py: error: too few arguments Here is my question : How can i manage to write 'python myprogram.py' in shell and get the help message instead of the error. Answer: I think you are dealing the bug discussed in <http://bugs.python.org/issue9253> Your `subparsers` is a positional argument. That kind of argument is always required, unless `nargs='?'` (or *). I think that is why you are getting the error message in 2.7. But in the latest py 3 release, the method of testing for required arguments was changed, and subparsers fell through the cracks. Now they are `optional` (not-required). There's a suggested patch/fudge to make `argparse` behave as it did before (require a subparser entry). I expect that eventually py3 argparse will revert to the py2 practice (with a possible option of accepting a `required=False` parameter). So instead of testing `args.sp is None`, you may want to test `sys.argv[1:]` before calling `parse_args`. `Ipython` does this to produce it's own help message.
Can't reenable menus in Python tkinter on Mac Question: I have a GUI that I created in Tkinter which has a menu. I want a button that when clicked toggles the menu being enabled / disabled. So I wrote the following minimal example (based off of <https://mail.python.org/pipermail/tkinter- discuss/2004-September/000204.html>) which works fine on my Windows 7 and Ubuntu 14.04 machines (using Python 2.7.6 and Tkinter Revision 81008). However when I tried the same code (again under Python 2.7.6 and Tkinter Revision 81008) on Mac 10.9 the menu would disable but would not reenable. Additionally, the example below also prints out what state it thinks the menu has (using entrycget) and it would print out that it thought that the menu was alternating between enabled and disabled. Can anyone reproduce this behaviour? Is this a known bug? Or is there an alternate way to enable / disable menus on Mac from Tkinter import * root=Tk() def hello(): print "hello !" menubar = Menu(root) submenu = Menu(menubar, tearoff=0) submenu.add_command(label="Hello", command=hello) menubar.add_cascade(label='test', menu=submenu) root.config(menu=menubar) def toggle(): print('I think the menu bar is %s' % menubar.entrycget(0,"state")) if menubar.entrycget('test', "state")=="normal": print('disabling') menubar.entryconfig('test', state=DISABLED) print('disbled') else: print('enabling') menubar.entryconfig('test', state=NORMAL) print('done') b = Button(root, text='Toggle', command=toggle) b.pack() root.mainloop() Answer: As noted in [here](http://bugs.python.org/issue21757), this appears to be a bug in the Apple-supplied Tk 8.5. The Cocoa versions of Tk that Apple has been shipping since OS X 10.6 have had numerous problems many of which have been fixed in more recent versions of Tk 8.5. With the current ActiveTcl 8.5.15, your test appears to work correctly. Unfortunately, you can't easily change the version of Tcl/Tk that the Apple-supplied system Pythons use. One option is to install the current Python 2.7.7 from the python.org binary installer along with ActiveTcl 8.5.15. There is more information here: <https://www.python.org/download/mac/tcltk/> <https://www.python.org/downloads/>
Finding common elements between a list and a dictionary in python Question: I have two files like this, A list of proteins - TRIUR3_05947-P1 TRIUR3_06394-P1 Traes_1BL_EB95F4919.2 And a dictionary of tab-delimited contigs and proteins - contig22 TRIUR3_05947-P1 contig15 TRIUR3_05947-P1 contig1 Traes_1BL_EB95F4919.2 contig67 Traes_1BL_EB95F4919.2 contig98 Traes_1BL_EB95F4919.2 contig45 MLOC_71599.4 My desired output is that it finds all common proteins and prints me results like this, contig22 TRIUR3_05947-P1 contig15 TRIUR3_05947-P1 contig1 Traes_1BL_EB95F4919.2 contig67 Traes_1BL_EB95F4919.2 contig98 Traes_1BL_EB95F4919.2 This is my script below, but it gives me the result of the common key just ones, I guess overriding over, how can this be solved? f1=open('mydict.txt','r') f2=open('mylist.txt','r') output = open('result.txt','w') dictA= dict() for line1 in f1: listA = line1.rstrip('\r\n').split('\t') dictA[listA[1]] = listA[0] for line1 in f2: new_list=line1.rstrip('\n').split() query=new_list[0] if query in dictA: listA[0] = dictA[query] output.write(query+'\t'+str(listA[0])+'\n') Answer: In your first for loop, you are losing information as you transform the txt file into a python dictionary: for ...: dictA[listA[1]] = listA[0] For example, if you have the lines contig1 Traes_1BL_EB95F4919.2 contig67 Traes_1BL_EB95F4919.2 contig98 Traes_1BL_EB95F4919.2 in you txt file, the resulting dictionary will only have the key-value pair of the last entry, reversed. To achieve you goal, with minimal modifications of your program, try from collections import defaultdict f1=open('mydict.txt','r') f2=open('mylist.txt','r') output = open('result.txt','w') dictA= defaultdict(list) for line1 in f1: listA = line1.rstrip('\r\n').split('\t') dictA[listA[1]].append(listA[0]) # Save all the common proteins for line1 in f2: new_list=line1.rstrip('\n').split() query=new_list[0] if query in dictA: listA = dictA[query] # Now have a list of matching contigs for contig in listA: output.write(contig + '\t' + query +'\n')
Why is 'Unexpected indent' occuring in this Python code? Question: The following is Python code that I typed: import builtins try: a = input("Enter name :- ") if (a=='Joey'): print("Yeah right ?!?") print("How come") else: print("No Problem") except IndentationError as i: print("Error : {0}".format(i)) Instead of handling the exception and printing the error message, I get an **"Unexpected indent"** error message. Why is this happening? Thanks in advance. Answer: You cannot catch syntax errors (including indentation errors) _in the code that triggers the exception itself_. The exception is thrown by the parser as it loads your file, not as it runs the code. The code is never run because of the error. You can only catch the exception from the 'outside', when loading the module with `import` or when passing text to the `compile()` function, for example.
Initializing multiple python dictionaries to the same keynames and values Question: I want to be able to loop through my main function and _bin_ values to certain keys in these dictionaries. All six dictionaries have the same keynames but the dictionaries are unique. Is there a better way to 1. initialize all the dictionaries (i.e dictionary comprehension) or 2. store this data in a better way (i.e. nested dictionaries, namedtuples...) Here is my current dictionary initialization: TRI_1 = {'HF' : 0, 'NHF' : 0, 'TF' : 0, 'HM' : 0, 'NHM' : 0, 'TM' : 0} TRI_2 = {'HF' : 0, 'NHF' : 0, 'TF' : 0, 'HM' : 0, 'NHM' : 0, 'TM' : 0} TRV_1 = {'HF' : 0, 'NHF' : 0, 'TF' : 0, 'HM' : 0, 'NHM' : 0, 'TM' : 0} TRV_2 = {'HF' : 0, 'NHF' : 0, 'TF' : 0, 'HM' : 0, 'NHM' : 0, 'TM' : 0} TRV_3 = {'HF' : 0, 'NHF' : 0, 'TF' : 0, 'HM' : 0, 'NHM' : 0, 'TM' : 0} TRV_4 = {'HF' : 0, 'NHF' : 0, 'TF' : 0, 'HM' : 0, 'NHM' : 0, 'TM' : 0} EDIT: My Solution. I will remember g.d.d.c.'s method in the future but I need to have keys for the initial zero values so I can simply print TRI_1 and have {'key' : 0 } appear. This is a combination of Padraic's dictionary templating and Aleksi's comprehension. Thank you for the simple expandable solution! TEMP = dict.fromkeys('HF NHF TF HM NHM TM'.split(), 0) TRI_1, TRI_2, TRV_1, TRV_2, TRV_3, TRV_4 = ([dict(TEMP) for i in range(6)]) Answer: I think I'd use this: from collections import defaultdict container = defaultdict(lambda: defaultdict(int)) Then you do this to tally: container['TRV_1']['HF'] += 1
What is wrong with this Python Multiprocessing Code? Question: I am trying to create some multiprocessing code for my project. I have created a snippet of the things that I want to do. However its not working as per my expectations. Can you please let me know what is wrong with this. from multiprocessing import Process, Pipe import time class A: def __init__(self,rpipe,spipe): print "In the function fun()" def run(self): print"in run method" time.sleep(5) message = rpipe.recv() message = str(message).swapcase() spipe.send(message) workers = [] my_pipe_1 = Pipe(False) my_pipe_2 = Pipe(False) proc_handle = Process(target = A, args=(my_pipe_1[0], my_pipe_2[1],)) workers.append(proc_handle) proc_handle.run() my_pipe_1[1].send("hello") message = my_pipe_2[0].recv() print message print "Back in the main function now" The trace back displayed when i press ctrl-c: ^CTraceback (most recent call last): File "sim.py", line 22, in <module> message = my_pipe_2[0].recv() KeyboardInterrupt When I run this above code, the main process does not continue after calling "proc_handle.run". Why is this? Answer: You've misunderstood how to use `Process`. You're creating a `Process` object, and passing it a class as `target`, but `target` is meant to be passed a callable (usually a function) that `Process.run` then executes. So in your case it's just instantiating `A` inside `Process.run`, and that's it. You should instead make your `A` class a `Process` subclass, and just instantiate it directly: #!/usr/bin/python from multiprocessing import Process, Pipe import time class A(Process): def __init__(self,rpipe,spipe): print "In the function fun()" super(A, self).__init__() self.rpipe = rpipe self.spipe = spipe def run(self): print"in run method" time.sleep(5) message = self.rpipe.recv() message = str(message).swapcase() self.spipe.send(message) if __name__ == "__main__": workers = [] my_pipe_1 = Pipe(False) my_pipe_2 = Pipe(False) proc_handle = A(my_pipe_1[0], my_pipe_2[1]) workers.append(proc_handle) proc_handle.start() my_pipe_1[1].send("hello") message = my_pipe_2[0].recv() print message print "Back in the main function now" mgilson was right, though. You should call `start()`, not `run()`, to make `A.run` execute in a child process. With these changes, the program works fine for me: dan@dantop:~> ./mult.py In the function fun() in run method HELLO Back in the main function now
NameError: name Timer is not defined Question: I have a small python program written for python 2.7.3: import time def fun(): print('Hi') for i in range(3): Timer(i, fun).start() When I run it, I get the error: `NameError: name 'Timer' is not defined` How can I find out which module supports this functionality? Answer: `Timer` is in the `timeit` module, not `time`. And to call it like you want to, you would have to `from timeit import Timer`, not just `import timeit`. If you just declare `import timeit`, then you would have to write `timeit.Timer` instead of `Timer` everywhere in the code.
Python numpy index Question: i have a numpy array p like this: array([[ 0.92691702, 0.07308298], [ 0.65515095, 0.34484905], [ 0.32526151, 0.67473849], ..., [ 0.34171992, 0.65828008], [ 0.77521514, 0.22478486], [ 0.96430103, 0.03569897]]) If i do x=p[:,1:2], i would get `array([[ 0.07308298], [ 0.34484905], [ 0.67473849], ..., [ 0.65828008], [ 0.22478486], [ 0.03569897]])` and x.shape is (5500,1) However, if i do x=p[:,1], i would get array([ 0.07308298, 0.34484905, 0.67473849, ..., 0.65828008, 0.22478486, 0.03569897]) and x.shape is (5500, ) Why there is difference like this? It quite confuses me. Thanks all in advance for your help. Answer: It's the difference between using a slice and a single integer in the `ndarray.__getitem__` call. Slicing causes the ndarray to return _"views"_ while integers cause the ndarray _values_. I'm being a little loose in my terminology here -- Really, for your case they both return a numpy view -- It's easier to consider just the 1D case first: >>> import numpy as np >>> x = np.arange(10) >>> x[1] 1 >>> x[1:2] array([1]) This idea extends to multiple dimensions nicely -- If you pass a slice for a particular axis, you'll get "array-like" values along that axis. If you pass a scalar for a particular axis, you'll get scalars along that axis in the result. Note that the 1D case really isn't any different from how a standard python `list` behaves: >>> x = [1, 2, 3, 4] >>> x[1] 2 >>> x[1:2] [2]
Problems overriding _iterencode method on JSONEncoder that employs a generator Question: I am trying to create my own custom encoder that mostly reuses the JSONEncoder behaviour: BinaryJSONEncoder(JSONEncoder): def _iterencode(self, o, markers): sys.stderr.write("Calling custom _iterencode\n") try: return JSONEncoder._iterencode(self, o, markers) except UnicodeDecodeError: sys.stderr.write("Got exception\n") return "" However, I still get an unhandled UnicodeDecodeError, because once the _iterencode method is called, it cycles through its generators before returning. What's strange is that the exception originates from the _iterencode method, but my method is nowhere in the return stack! But my function is being called, because the "Calling custom _iterencode" messages are coming out in the Apache error_log. How can I work around this issue without implementing the entire method from scratch? Here is the stack: Traceback (most recent call last): File "/var/www/radiator/cgi-bin/ldapsearch.py", line 108, in <module> res.body(json.dumps(res_data, cls=BinaryJSONEncoder)) File "/usr/lib64/python2.6/json/__init__.py", line 237, in dumps **kw).encode(obj) File "/usr/lib64/python2.6/json/encoder.py", line 367, in encode chunks = list(self.iterencode(o)) File "/usr/lib64/python2.6/json/encoder.py", line 306, in _iterencode for chunk in self._iterencode_list(o, markers): File "/usr/lib64/python2.6/json/encoder.py", line 204, in _iterencode_list for chunk in self._iterencode(value, markers): File "/usr/lib64/python2.6/json/encoder.py", line 306, in _iterencode for chunk in self._iterencode_list(o, markers): File "/usr/lib64/python2.6/json/encoder.py", line 204, in _iterencode_list for chunk in self._iterencode(value, markers): File "/usr/lib64/python2.6/json/encoder.py", line 309, in _iterencode for chunk in self._iterencode_dict(o, markers): File "/usr/lib64/python2.6/json/encoder.py", line 275, in _iterencode_dict for chunk in self._iterencode(value, markers): File "/usr/lib64/python2.6/json/encoder.py", line 306, in _iterencode for chunk in self._iterencode_list(o, markers): File "/usr/lib64/python2.6/json/encoder.py", line 204, in _iterencode_list for chunk in self._iterencode(value, markers): File "/usr/lib64/python2.6/json/encoder.py", line 294, in _iterencode yield encoder(o) UnicodeDecodeError: 'utf8' codec can't decode byte 0xc3 in position 2: invalid continuation byte Answer: It seems the only viable way to overcome this problem is to implement the whole function again, with handlers for the binary data: from json.encoder import encode_basestring_ascii, encode_basestring class BinaryJSONEncoder(JSONEncoder): def _iterencode(self, o, markers=None): if isinstance(o, str): try: o = unicode(o, "utf8") except UnicodeDecodeError: o = base64.b64encode(o) if isinstance(o, basestring): if self.ensure_ascii: encoder = encode_basestring_ascii else: encoder = encode_basestring _encoding = self.encoding if (_encoding is not None and isinstance(o, str) and not (_encoding == 'utf-8')): o = o.decode(_encoding) yield encoder(o) elif o is None: yield 'null' elif o is True: yield 'true' elif o is False: yield 'false' elif isinstance(o, (int, long)): yield str(o) elif isinstance(o, float): yield floatstr(o, self.allow_nan) elif isinstance(o, (list, tuple)): for chunk in self._iterencode_list(o, markers): yield chunk elif isinstance(o, dict): for chunk in self._iterencode_dict(o, markers): yield chunk else: if markers is not None: markerid = id(o) if markerid in markers: raise ValueError("Circular reference detected") markers[markerid] = o for chunk in self._iterencode_default(o, markers): yield chunk if markers is not None: del markers[markerid] I understand the issue with the yields exiting when an exception is thrown, but why can't the superclass method be called there after without it then only calling the superclass methods?
Newb to Writing Integration Tests Question: Here is my test file: from flask import Flask from flask.ext.testing import TestCase class TestInitViews(TestCase): render_templates = False def create_app(self): app = Flask(__name__) app.config['TESTING'] = True return app def test_root_route(self): self.client.get('/') self.assert_template_used('index.html') Here is the full stack trace: $ nosetests tests/api/client/test_init_views.py F ====================================================================== FAIL: test_root_route (tests.api.client.test_init_views.TestInitViews) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/dmonsewicz/dev/autoresponders/tests/api/client/test_init_views.py", line 17, in test_root_route self.assert_template_used('index.html') File "/Users/dmonsewicz/.virtualenvs/autoresponders-api/lib/python2.7/site-packages/flask_testing.py", line 120, in assertTemplateUsed raise AssertionError("template %s not used" % name) AssertionError: template index.html not used ---------------------------------------------------------------------- Ran 1 test in 0.012s FAILED (failures=1) I am a newb to Python and can't seem to figure this one out. All I am trying to do is write a simple test that hits the `/` (root route) endpoint and `asserts` that the template used was in fact `index.html` Attempt at using `LiveServerTestCase` from flask import Flask from flask.ext.testing import LiveServerTestCase class TestInitViews(LiveServerTestCase): render_templates = False def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.config['LIVESERVER_PORT'] = 6765 return app def setUp(self): self.app = self.app.test_client() def test_root_route(self): res = self.app.get('/') print(res) self.assert_template_used('index.html') I'm using `Flask-Testing` version `0.4` and for some reason the `LiveServerTestCase` doesn't exist in my import # Working Code from flask import Flask from flask.ext.testing import TestCase from api.client import blueprint class TestInitViews(TestCase): render_templates = False def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.register_blueprint(blueprint) return app def test_root_route(self): res = self.client.get('/') self.assert_template_used('index.html') Answer: You have to run pip install blinker and make sure your flask version is greater than .6. It looks like you omitted setting app.config['TESTING'] = True I was able to get the following test to run to validate the assert was True: #!/usr/bin/python import unittest from flask import Flask from flask.ext.testing import TestCase from flask import render_template class MyTest(TestCase): def create_app(self): app = Flask(__name__) app.config['TESTING'] = True @app.route('/') def hello_world(): return render_template('index.html') return app def test_root_route(self): self.client.get('/') self.assert_template_used('index.html') if __name__ == '__main__': unittest.main()
multithreaded file download in python and updating in shell with download progress Question: in an attempt to learn multithreaded file download I wrote this piece of cake: import urllib2 import os import sys import time import threading urls = ["http://broadcast.lds.org/churchmusic/MP3/1/2/nowords/271.mp3", "http://s1.fans.ge/mp3/201109/08/John_Legend_So_High_Remix(fans_ge).mp3", "http://megaboon.com/common/preview/track/786203.mp3"] url = urls[1] def downloadFile(url, saveTo=None): file_name = url.split('/')[-1] if not saveTo: saveTo = '/Users/userName/Desktop' try: u = urllib2.urlopen(url) except urllib2.URLError , er: print("%s" % er.reason) else: f = open(os.path.join(saveTo, file_name), 'wb') meta = u.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_name, file_size) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) sys.stdout.write('%s\r' % status) time.sleep(.2) sys.stdout.flush() if file_size_dl == file_size: print r"Download Completed %s%% for file %s, saved to %s" % (file_size_dl * 100. / file_size, file_name, saveTo,) f.close() return def synchronusDownload(): urls_saveTo = {urls[0]: None, urls[1]: None, urls[2]: None} for url, saveTo in urls_saveTo.iteritems(): th = threading.Thread(target=downloadFile, args=(url, saveTo), name="%s_Download_Thread" % os.path.basename(url)) th.start() synchronusDownload() but it seems like for the initiation of the second download it waits for the first thread and then goes to download the next file, as printed in shell too. my plan was to begin all downloads simultaneously and print the updated progress of the files getting downloaded. Any help will be greatly appreciated. thanks. Answer: This is a common problem and here are the steps typically taken: 1.) use Queue.Queue to create a queue of all the urls you would like to visit. 2.) Create a class that inherits from threading.Thread. It should have a run method that grabs a url from the queue and gets the data. 3.) Create a pool of threads based on your class to be "workers" 4.) Don't exit the program until queue.join() has been completed
How to add a custom array to a polydata in paraview? Question: I know that I can use the Calculator filter for operations on arrays, but I want to perform some more complicated computations. I managed to do it in Paraview python shell, but the missing step now is to go back to the viewer again (or save the new polydata to file). Here is what I have so far: polydata = servermanager.Fetch(FindSource("mydataalreadyopeninparaview")) region_size = paraview.vtk.vtkIntArray() region_size.SetNumberOfComponents(0) region_size.SetName("regionsize") for i in range(polydata .GetNumberOfPoints()): region_size.InsertNextValue(somecomputedvalue) polydata.GetPointData().AddArray(region_size) How can I "import" in the paraview pipeline my newly created data? Answer: Better approach would be use the **Programmable Filter** to add the array to your input dataset. In ParaView 4.1, the following script can be added to the _Script_ on **Properties** panel for the **Programmager Filter** polydata = output array = vtk.vtkIntArray() array.SetNumberOfComponents(0) array.SetName("regionsize") for i in range(polydata .GetNumberOfPoints()): array.InsertNextValue(somecomputedvalue) polydata.GetPointData().AddArray(array);
pandas.rpy.common.load_data() usage/documentation? Question: I am trying to convert some `<class 'rpy2.robjects.vectors.Matrix'>` variables into Pandas dataframes. There is a lot of copy-paste instructions of how to do so on the internet, all giving the brief example: pandas.rpy.common.load_data("infert") without any information on where `"infert"` is coming from. I was unable to get any sort of documentation on this function (why is there none?), but apparently I cannot use it: summary= r.summary(linear_model) filtered_summary=summary.rx2("tTable") print com.load_data("filtered_summary") gives me: --------------------------------------------------------------------------- LookupError Traceback (most recent call last) <ipython-input-68-a087eddd5220> in <module>() 8 #print test1_sum.names 9 print type(r_res) ---> 10 print com.load_data("filtered_summary") 11 #print pd.DataFrame(test1_sum.rx2("tTable")) 12 /usr/lib64/python2.7/site-packages/pandas/rpy/common.pyc in load_data(name, package, convert) 29 r.data(name) 30 ---> 31 robj = r[name] 32 33 if convert: /usr/lib64/python2.7/site-packages/rpy2/robjects/__init__.pyc in __getitem__(self, item) 226 227 def __getitem__(self, item): --> 228 res = _globalenv.get(item) 229 res = conversion.ri2ro(res) 230 res.__rname__ = item LookupError: 'filtered_summary' not found while: summary= r.summary(linear_model) print com.load_data("summary") gives me: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-69-b51722281aa4> in <module>() 8 #print test1_sum.names 9 print type(r_res) ---> 10 print com.load_data("summary") 11 #print pd.DataFrame(test1_sum.rx2("tTable")) 12 /usr/lib64/python2.7/site-packages/pandas/rpy/common.pyc in load_data(name, package, convert) 32 33 if convert: ---> 34 return convert_robj(robj) 35 else: 36 return robj /usr/lib64/python2.7/site-packages/pandas/rpy/common.pyc in convert_robj(obj, use_pandas) 222 return converter(obj) 223 --> 224 raise TypeError('Do not know what to do with %s object' % type(obj)) 225 226 TypeError: Do not know what to do with <class 'rpy2.robjects.functions.SignatureTranslatedFunction'> object So: * How do I use `load_data` correctly * How can I best get my R matrix converted to a Pandas DataFrame? Answer: I don't know whether this is the "correct" use of load_data but I've found that if your R dataframe (say, myRData) is stored in the default workspace (.RData) in the default working directory then you can use load_data to load myRData using: import rpy2.robjects as robjects import pandas.rpy.common as com print robjects.r.load(".RData") myRData = com.load_data('myRData') You could use robjects.r.XXX to run other R functions such as robjects.r.getwd() or robjects.r.setwd("path_to_new_working_directory") to navigate to new working directories.
Python, trying to parse html to attain email address Question: I am using beautifulsoup to attain an email address, however I am having problems. I do not know where to start to parse through this, to attain the email address. > #input: url > #output: address > > def urlSC(url): > soup = BeautifulSoup(urllib2.urlopen(url).read()) > #word = soup.prettify() > word = soup.find_all('a') > print word > return word OUTPUT: > [<a href="default.aspx"><img alt="·Î°í" border="0" src="image/logo.gif"/></a>, <a href="http://www.ctodayusa.com"><img > border="0" src="image/ctodayusa.jpg"><a></a> > </img></a>, <a></a>, <a href="mailto:[email protected]" id="hlEmail">[email protected]</a>, <a id="hlHomepage"></a>, <a > href="javascript:img_up('','','');"><img border="0" class="img" > src="upload/" vspace="10" width="1"/></a>, <a > href="javascript:img_up('','','');"><img border="0" class="img" > src="upload/" vspace="10" width="1"/></a>, <a > href="javascript:openWin('http://maps.yahoo.com/maps_result?addr=2100 > De armoun Rd.&amp;csz=99515&amp;country=us')" id="hlMap"><img > border='0"' src="images/globe.gif"> 위치</img></a>, <a > href="javascript:print()"><img border="0" src="images/printer.gif"> > 프린트</img></a>, <a href="javascript:mail_go('[email protected]', > '2Y5E9%2bk0h%2b4P%2f0H3jEJTq9VUG%2f0gaj40')" id="hlSendMail"><img > border="0" src="images/mails.gif"> 메일보내기</img></a>, <a > href="javascript:history.go(-1)"><img border="0" > src="images/list.gif"> > </img></a>, <a href="UpdateAddress.aspx?OrgID=4102" id="hlModify"><img alt="" border="0" src="Images/Modify.gif"/></a>] I want this email: [email protected] Answer: Get the `a` element by id, extract everything after `mailto:` from the `href` attribute value: link = soup.find('a', id='hlEmail') print link['href'][7:] Demo: >>> from bs4 import BeautifulSoup >>> import urllib2 >>> url = "http://www.koreanchurchyp.com/ViewDetail.aspx?OrgID=4102" >>> soup = BeautifulSoup(urllib2.urlopen(url)) >>> link = soup.find('a', id='hlEmail') >>> print link['href'][7:] rev_han seven seven seven at yahoo.com # obfuscated intentionally
Python regex not matching images on website (it matches in regex helper) Question: I do not understand what is wrong with my script below. It is supposed to parse out images using regex. I've verified that my regex is correct by using <http://regex101.com/>. The problem is it doesn't even grab the first image on the website (even it should?). **The website in the script is a NSFW blog. Please don't go to the link if you are offended by nudity or sexuality.** from urllib2 import urlopen import re base = "http://bassrx.tumblr.com" url = "http://bassrx.tumblr.com/tagged/tt" def parse_page(url): # returns html for parsing page = urlopen(url) html = page.read() return html def get_links(html): # returns list of all image urls on page jpgs = re.findall("src.\"(.*?500.jpg)", html, re.IGNORECASE) #pngs = re.findall("src.\"(.*?media.tumblr.*?tumblr_.*?png)", html, re.IGNORECASE) #links = jpgs + pngs return jpgs html = parse_page(url) # get the html for first page links = get_links(html) # get all relevant image links print links The very first image has the following HTML: src="http://37.media.tumblr.com/tumblr_m9q9feJcxl1qi02clo3_500.jpg" alt=""> I would like to know why it doesn't grab this image (and also misses most of the others). Answer: Consider using [BeautifulSoup](http://beautiful- soup-4.readthedocs.org/en/latest/) to do this.. >>> from urllib2 import urlopen >>> from bs4 import BeautifulSoup >>> import re >>> page = urlopen('http://bassrx.tumblr.com/tagged/tt') >>> soup = BeautifulSoup(page.read()) >>> [x['src'] for x in soup.find_all('img',{'src':re.compile('500\.jpg$')})] Output [ u'http://38.media.tumblr.com/tumblr_ln5gwxHYei1qi02clo1_500.jpg', u'http://37.media.tumblr.com/tumblr_lnmh4tD3sM1qi02clo1_500.jpg', u'http://38.media.tumblr.com/c84fce183b6220eba854ce8933a13110/tumblr_n3lxgtqp7K1qi02clo1_500.jpg' ] If you want the entire image tag, use the following: >>> soup.find_all('img',{'src':re.compile('500\.jpg$')})
Recommended tools for benchmarking Ruby and Perl Question: I want to compare the execution time for mathematical equations for different dynamic, interpreted programming languages like Ruby, Perl, and Python. In Python, there is the convenient `timeit` module, which allows me to time, where I can simply time for, e.g., a least squares fit (`python_lstsqr(x,y)`) via min(timeit.Timer('python_lstsqr(x, y)', 'from __main__ import python_lstsqr, x, y')\ .repeat(repeat=3, number=1000)) (here the best of 3 repetitions and 1000 loops per repetition) Are there equivalents in Perl and Ruby? Answer: Good old `time` ? For Perl, you can use built-in [`Benchmark`](http://perldoc.perl.org/Benchmark.html) or [`Time::Stopwatch`](https://metacpan.org/pod/Time%3a%3aStopwatch). For Ruby, the built-in [`benchmark`](http://ruby- doc.org/stdlib-2.1.2/libdoc/benchmark/rdoc/index.html) is good enough.
ValueError: The channel sent is invalid on a Raspberry Pi - Controlling GPIO Pin 2 (BOARD) using Python causes Error Question: So I have a tiny little fan connected to pin 6(Ground) and pin 2. I am trying to manually start and stop the fan when needed but I am getting this error when trying: ValueError: The channel sent is invalid on a Raspberry Pi Here is my code that I am executing as root. It seems to be working on other pins but not Pin 2 import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(2, GPIO.OUT, pull_up_down=GPIO.PUD_UP) I am not sure how to access this pin. Is there something I am doing wrong? Answer: It could be something stupid, i was looking exacty the same. It seems there are two "modes" in the GPIO. _Change GPIO.setmode(GPIO.BOARD)_ to GPIO.setmode(GPIO.BCM) It worked for me on a clean installation of Raspbian
How to use docker-py (official docker client) to start a bash shell? Question: I'm trying to use docker-py to run a docker container and drop me into a bash shell in that container. I get as far as running the container (I can see it with `docker ps`, and I can attach to it just fine with the native docker client), but when I use `attach()` from the official Python library, it just gives me an empty string in response. How do I attach to my bash shell? >>> import docker >>> c = docker.Client() >>> container = c.create_container(image='d11wtq/python:2.7.7', command='/bin/bash', stdin_open=True, tty=True, name='docker-test') >>> container {u'Id': u'dd87e4ec75496d8369e0e526f343492f7903a0a45042d312b37859a81e575303', u'Warnings': None} >>> c.start(container) >>> c.attach(container) '' Answer: I ended up releasing a library for this: <https://github.com/d11wtq/dockerpty> import docker import dockerpty client = docker.Client() container = client.create_container( image='busybox:latest', stdin_open=True, tty=True, command='/bin/sh', ) client.start(container) dockerpty.PseudoTerminal(client, container).start()
"Can't extract file(s) to egg cache" error in GAE Question: I have Windows 7 and Python 2.7 with setuptools installed. After i download pitz module (easy_install pitz), Google App Engine stop working: bad runtime process port [''] Traceback (most recent call last): File "G:\Program Files (x86)\Google\google_appengine\_python_runtime.py", line 184, in <module> _run_file(__file__, globals()) File "G:\Program Files (x86)\Google\google_appengine\_python_runtime.py", line 180, in _run_file execfile(script_path, globals_) File "G:\Program Files (x86)\Google\google_appengine\google\appengine\tools\devappserver2\python\runtime.py", line 28, in <module> from google.appengine.ext.remote_api import remote_api_stub File "G:\Program Files (x86)\Google\google_appengine\google\appengine\ext\remote_api\remote_api_stub.py", line 75, in <module> import yaml File "G:\Program Files (x86)\Google\google_appengine\lib\yaml-3.10\yaml\__init__.py", line 14, in <module> from cyaml import * File "G:\Program Files (x86)\Google\google_appengine\lib\yaml-3.10\yaml\cyaml.py", line 5, in <module> from _yaml import CParser, CEmitter File "C:\Python27\lib\site-packages\pyyaml-3.11-py2.7-win-amd64.egg\_yaml.py", line 7, in <module> File "C:\Python27\lib\site-packages\pyyaml-3.11-py2.7-win-amd64.egg\_yaml.py", line 4, in __bootstrap__ File "C:\Python27\lib\site-packages\pkg_resources.py", line 950, in resource_filename self, resource_name File "C:\Python27\lib\site-packages\pkg_resources.py", line 1607, in get_resource_filename self._extract_resource(manager, self._eager_to_zip(name)) File "C:\Python27\lib\site-packages\pkg_resources.py", line 1667, in _extract_resource manager.extraction_error() File "C:\Python27\lib\site-packages\pkg_resources.py", line 996, in extraction_error raise err pkg_resources.ExtractionError: Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: [Error 5] : 'C:\\Users\\Kostr\\AppData\\Roaming\\Python-Eggs\\pyyaml-3.11-py2.7-win-amd64.egg-tmp\\_yaml.pyd' The Python egg cache directory is currently set to: C:\Users\Kostr\AppData\Roaming\Python-Eggs Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory. How to solve this issue? Answer: from: <https://code.google.com/p/modwsgi/wiki/ApplicationIssues> To avoid this particular problem you can set the `PYTHON_EGG_CACHE` cache environment variable at the start of the WSGI application script file. The environment variable should be set to a directory which is owned and/or writable by the user that Apache runs as. import os os.environ['PYTHON_EGG_CACHE'] = '/usr/local/pylons/python-eggs' Again, make sure this exists. For Windows users, maybe something like: os.environ['PYTHON_EGG_CACHE'] = '/tmp' Alternatively, if using mod_wsgi 2.0, one could also use the WSGIPythonEggs directive for applications running in embedded mode, or the `python-eggs` option to the WSGIDaemonProcess directive when using daemon mode. Note that you should refrain from ever using directories or files which have been made writable to anyone as this could compromise security. Also be aware that if hosting multiple applications under the same web server, they will all run as the same user and so it will be possible for each to both see and modify each others files. If this is an issue, you should host the applications on different web servers running as different users or on different systems. Alternatively, any data required or updated by the application should be hosted in a database with separate accounts for each application.
How to use custom typeface for vertex labels in python igraph? Question: In R igraph, there is an easy way to set a custom typeface for vertex labels and other texts on graph plots: plot(G,vertex.label.family="DINPro") However as I see, `vertex_label_family` parameter is not available in python igraph. It took some time while I have found some workaround to be able to set the label font, so I will post my solution here. And I'm wondering, if there are more elegant or easier solutions. First I tried to call cairo's `context.select_font_face()` on the igraph plot object's context, but sadly the `draw()` function in `igraph.drawing.graph.DefaultGraphDrawer()` overwrites it in each `plot.redraw()`: lo = graph.layout_fruchterman_reingold() sf = cairo.PDFSurface("test.pdf",1280,1280) bx = igraph.drawing.utils.BoundingBox(10, 10, 1260, 1260) plot = igraph.plot(graph,layout=lo,target=sf,bbox=bx) plot._ctx.select_font_face("DINPro", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) plot.redraw() plot.save() So this doesn't work. I will post a simple solution what works. Answer: I could manage to set the typeface of vertex labels with replacing the `DefaultGraphDrawer` class with a new one, which only differs in two lines from the original. I simply copied the `igraph/drawing/graph.py` file from the site-packages directory of my python distribution, and I deleted every other classes except the `DefaultDraphDrawer`. After the imports, I added a line to import the `AbstractCairoGraphDrawer`, and modified the `__all__[]` list: from igraph.drawing.graph import AbstractCairoGraphDrawer __all__ = ["DefaultGraphDrawerFFsupport"] Then I renamed the `DefaultGraphDrawer` class, modified the font selection part of it: class DefaultGraphDrawerFFsupport(AbstractCairoGraphDrawer): ... def draw(...): ... fontFamily = graph.font if hasattr(graph, "font") else "sans-serif" context.select_font_face(fontFamily, cairo.FONT_SLANT_NORMAL, \ cairo.FONT_WEIGHT_NORMAL) ... ... I put this file (`ig_drawing.py`) in the directory of my module, and imported it. The I could set any typeface by passing the modified class as `drawing_factory` parameter for the `plot()` function: from ig_drawing import * lo = graph.layout_fruchterman_reingold() sf = cairo.PDFSurface("test.pdf",1280,1280) bx = igraph.drawing.utils.BoundingBox(10, 10, 1260, 1260) df = igraph.drawing.graph.DefaultGraphDrawer(ctx, bx) graph.font = "DINPro" plot = graph.plot(graph,layout=lo,target=sf,bbox=bx,vertex_label=graph.vs["label"],drawer_factory=DefaultGraphDrawerFFsupport) a.plot.save() In case you don't set the `graph.font`, it uses "sans-serif". But also if you give a non existing font name, then without error message it falls back to your system's default sans font. It looks like the default "sans-serif" typeface is hardcoded in igraph, both in plotting functions using cairo surfaces and svg. Any simpler way to change this?
How to programmatically access a Python package's dependencies? Question: I am trying to access a PyPI package's dependencies (i.e. its install_requires metadata). This information does not seem to be available from either the JSON or XMLRPC APIs. The [documentation](https://wiki.python.org/moin/PyPIXmlRpc) for the XMLRPC API says that the `release_data` method should return a dict with a `requires` key, but I am not seeing this when I use the API. >>> import xmlrpclib >>> client = xmlrpclib.ServerProxy('http://pypi.python.org/pypi') >>> info = client.release_data('Flask', '0.10.1') >>> 'requires' in info False >>> info {'_pypi_hidden': False, '_pypi_ordering': 17, 'author': 'Armin Ronacher', 'author_email': '[email protected]', 'bugtrack_url': None, 'cheesecake_code_kwalitee_id': None, 'cheesecake_documentation_id': None, 'cheesecake_installability_id': None, 'classifiers': ['Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules'], 'description': 'Flask\n-----\n\nFlask is a microframework for Python based on Werkzeug, Jinja 2 and good\nintentions. And before you ask: It\'s BSD licensed!\n\nFlask is Fun\n````````````\n\n.. code:: python\n\n from flask import Flask\n app = Flask(__name__)\n\n @app.route("/")\n def hello():\n return "Hello World!"\n\n if __name__ == "__main__":\n app.run()\n\nAnd Easy to Setup\n`````````````````\n\n.. code:: bash\n\n $ pip install Flask\n $ python hello.py\n * Running on http://localhost:5000/\n\nLinks\n`````\n\n* `website <http://flask.pocoo.org/>`_\n* `documentation <http://flask.pocoo.org/docs/>`_\n* `development version\n <http://github.com/mitsuhiko/flask/zipball/master#egg=Flask-dev>`_', 'docs_url': '', 'download_url': 'UNKNOWN', 'downloads': {'last_day': 4723, 'last_month': 267891, 'last_week': 64752}, 'home_page': 'http://github.com/mitsuhiko/flask/', 'keywords': None, 'license': 'BSD', 'maintainer': None, 'maintainer_email': None, 'name': 'Flask', 'package_url': 'http://pypi.python.org/pypi/Flask', 'platform': 'any', 'release_url': 'http://pypi.python.org/pypi/Flask/0.10.1', 'requires_python': None, 'stable_version': None, 'summary': 'A microframework based on Werkzeug, Jinja2 and good intentions', 'version': '0.10.1'} Is there another way I can get a package's dependencies without installing the package? Answer: The only way I know to extract dependencies from pypi is to: 1. Download package and extract it to some directory 2. Run `setup.py egg_info` 3. Parse generated `requires.txt` for flask 0.10.1 it will be Werkzeug>=0.7 Jinja2>=2.4 itsdangerous>=0.21
Bulbs : Creating "in" and "out" edges between two vertices in TitanDB Question: I am using TitanGraphDB + Cassandra.I am starting Titan as follows cd titan-cassandra-0.3.1 bin/titan.sh config/titan-server-rexster.xml config/titan-server-cassandra.properties I have a Rexster shell that I can use to communicate to Titan+Cassandra above. cd rexster-console-2.3.0 bin/rexster-console.sh I want to program the Titan Graph DB from my python program.I am using bulbs package for that. from bulbs.titan import Graph g = Graph() vertex1 = g.vertices.get_or_create('dpid',dpid_str,{'state':'active','dpid':dpid_str,'type':'switch'})) vertex2 = g.vertices.get_or_create('desc',desc,{'desc':desc,'port_id':port_id,'state':state,'port_state':port_state,'number':number,'type':'port'})) From the examples I understand how to create edges between the vertices as below g.edges.create(vertex1,"out",vertex2) But assume that I don't have the reference to the vertices in my program. I want to RETRIEVE vertex1 using its key "dpid" AND I want to RETRIEVE vertex2 using its key "desc" AND then using the retrieved values I want to create the edge.How do I do this? Answer: To retrieve a vertex by an indexed property (as opposed to its database ID), you can use one the Bulbs built-in index methods: >>> # returns an iterator (can return more than 1) >>> vertices = g.vertices.index.lookup("dpid", dpid_str) >>> vertex1 = vertices.next() >>> # returns 1 vertex or None (errors if more than 1) >>> vertex2 = g.vertices.index.get_unique( "dpid", dpid_str) To create an edge, simply do... >>> g.edges.create(vertex1, "out", vertex2) NOTE: You don't need to label the edge "out" ("out" is implied by the direction of the edge going out from vertex1 and in to vertex2). You should consider using a more descriptive label. See... Rexter index documentation: * <http://bulbflow.com/docs/api/bulbs/rexster/indices/> index.lookup() <https://github.com/espeed/bulbs/blob/afa28ccbacd2fb92e0039800090b8aa8bf2c6813/bulbs/titan/index.py#L251> index.get_unique() <https://github.com/espeed/bulbs/blob/afa28ccbacd2fb92e0039800090b8aa8bf2c6813/bulbs/titan/index.py#L274>
Calling the sendLine() method after the connectTCP method has been called on twisted Question: I made a simple server that uses the LineReceiver. I can manage to send and receive messages when I test with Telnet. I want to take things a little bit further and use a small GUI to send and receive the messages. The way I am picturing this is that I somehow will have some sort of connect function that will call the reactor.run() method, and also make an instance of the ClientFactory class. I am basing myself with this example I found: #!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet.protocol import ClientFactory from twisted.protocols.basic import LineReceiver from twisted.internet import reactor import sys class EchoClient(LineReceiver): end="Bye-bye!" def connectionMade(self): self.sendLine("Hello, world!") self.sendLine("What a fine day it is.") self.sendLine(self.end) def lineReceived(self, line): print "receive:", line if line==self.end: self.transport.loseConnection() def sendMessage(self, line): self.sendLine(line) class EchoClientFactory(ClientFactory): protocol = EchoClient def clientConnectionFailed(self, connector, reason): print 'connection failed:', reason.getErrorMessage() reactor.stop() def clientConnectionLost(self, connector, reason): print 'connection lost:', reason.getErrorMessage() reactor.stop() def main(): factory = EchoClientFactory() reactor.connectTCP('localhost', 1234, factory) reactor.run() if __name__ == '__main__': main() Observe that when I call the main() function, the connectionMade will send those messages. How can I run the reactor and the factory, and call the sendLine function? Answer: Twisted calls are broken up into things that queue future actions and things that act immediately (or near to immediately) if the reactor is running. You can combine those to schedule something to happen in the future. (see: [Scheduling tasks for the future](http://twistedmatrix.com/documents/11.0.0/core/howto/time.html)) So if you want to call sendLine in the future you could use `reactor.callLater(5, sendLine, arg_to_sendLine)`. That would schedule the `sendLine` call to be run 5 seconds after the `callLater` call (... Assuming that your code is in the `reactor.run()` state) You also said: > The way I am picturing this is that I somehow will have some sort of connect > function that will call the reactor.run() method That statement worries me because Twisted is an all-encompassing framework (in most twisted programs `reactor.run()` and it's setup calls become the whole of `main`) not just something that you start when you want to do communications (it reacts poorly when you try and only use it halfway).
wxPython/ReportLab: How to create and open a .pdf file on button clicked Question: Good day all, For about 3days I have been trying hardest to get my way around this! I have a perfectly working wxFrame as well as a perfectly working ReportLab pdf script. See the code files below respectively (Note: data1.py is the GUI while data2.py is the running pdf script). My problems are:- 1) I want the pdf script to run only after I press the “Save To PDF” button 2) The value of the name field (as stored in a variable “NameString”) should be added to the generated pdf file. At the moment, if I run the script (data2.py) it creates but the Frame and the pdf file (without including the “NameString”) at the same time. That is not what I want, I want the pdf to open and include the “NameString” only after I clicked/press the “Save To PDF” button. Thanks in advance for your time. **data1.py** class MyFrame1 ( wx.Frame ): def __init__( self, parent ): wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 250,150 ), style = wx.CAPTION|wx.CLOSE_BOX|wx.MINIMIZE_BOX|wx.SYSTEM_MENU|wx.TAB_TRAVERSAL ) self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize ) DataBox = wx.BoxSizer( wx.HORIZONTAL ) gSizer2 = wx.GridSizer( 0, 2, 0, 0 ) self.NameLabel = wx.StaticText( self, wx.ID_ANY, u"Name", wx.DefaultPosition, wx.DefaultSize, 0 ) self.NameLabel.Wrap( -1 ) self.NameLabel.SetFont( wx.Font( 13, 70, 90, 90, False, wx.EmptyString ) ) gSizer2.Add( self.NameLabel, 0, wx.ALL, 5 ) self.NameField = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) gSizer2.Add( self.NameField, 1, wx.ALL, 5 ) self.SaveToPDF = wx.Button( self, wx.ID_ANY, u"Save To PDF", wx.DefaultPosition, wx.DefaultSize, 0 ) gSizer2.Add( self.SaveToPDF, 0, wx.ALL, 5 ) DataBox.Add( gSizer2, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 5 ) self.SetSizer( DataBox ) self.Layout() self.Centre( wx.BOTH ) # Connect Events self.SaveToPDF.Bind( wx.EVT_BUTTON, self.SaveToPDF_Function ) def __del__( self ): pass # Virtual event handlers, overide them in your derived class def SaveToPDF_Function( self, event ): event.Skip() **data2.py** #!/usr/bin/python # -*- coding: utf-8 -*- import wx from data1 import MyFrame1 from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A3 from reportlab.lib.pagesizes import landscape import os import tempfile import threading class MyFrame2(MyFrame1): def __init__(self, parent): MyFrame1.__init__ (self, parent) def SaveToPDF_Function( self, event ): NameString = self.NameField.GetValue() print NameString file_not_fount = "Selected file doesn't exist!" class Launcher(threading.Thread): def __init__(self,path): threading.Thread.__init__(self) self.path = 'myFile.pdf' def run(self): self.open_file(self.path) def open_file(self,path): if os.path.exists(path): if os.name == 'posix': subprocess.call(["xdg-open", path]) #os.popen("evince %s" % path) else: os.startfile(path) else: wx.MessageBox(self.file_not_fount, self.title, wx.OK|wx.ICON_INFORMATION) # NameString = raw_input("Enter ur text: ") c = canvas.Canvas("myFile.pdf", pagesize=landscape(A3)) c.drawCentredString(600, 800, 'I want this to open only after I clicked the “Save To PDF” button. Also, the text field value (NameString variable) should appear here =>' + 'NameString' ) c.save() Launcher('myFile.pdf').start() app = wx.App(0) MyFrame2(None).Show() app.MainLoop() Answer: First of all, I would create the reportlab module so that you can actually call it. As it is currently implemented, it will immediately create the PDF whenever it is run. You need to put all the reportlab code into a function of some sort. Since this is a really simple reportlab script, I just combined it with the wxPython code and removed the threading portion so you can see one easy way to do it: import wx from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A3 from reportlab.lib.pagesizes import landscape class MyFrame1 ( wx.Frame ): def __init__( self ): wx.Frame.__init__ ( self, None, size = wx.Size( 250,150 ), style = wx.CAPTION|wx.CLOSE_BOX|wx.MINIMIZE_BOX|wx.SYSTEM_MENU|wx.TAB_TRAVERSAL ) self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize ) DataBox = wx.BoxSizer( wx.HORIZONTAL ) gSizer2 = wx.GridSizer( 0, 2, 0, 0 ) self.NameLabel = wx.StaticText( self, wx.ID_ANY, u"Name", wx.DefaultPosition, wx.DefaultSize, 0 ) self.NameLabel.Wrap( -1 ) self.NameLabel.SetFont( wx.Font( 13, 70, 90, 90, False, wx.EmptyString ) ) gSizer2.Add( self.NameLabel, 0, wx.ALL, 5 ) self.NameField = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) gSizer2.Add( self.NameField, 1, wx.ALL, 5 ) self.SaveToPDF = wx.Button( self, wx.ID_ANY, u"Save To PDF", wx.DefaultPosition, wx.DefaultSize, 0 ) gSizer2.Add( self.SaveToPDF, 0, wx.ALL, 5 ) DataBox.Add( gSizer2, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 5 ) self.SetSizer( DataBox ) self.Layout() self.Centre( wx.BOTH ) # Connect Events self.SaveToPDF.Bind( wx.EVT_BUTTON, self.SaveToPDF_Function ) self.Show() #---------------------------------------------------------------------- def create_pdf(self): """""" nameString = str(self.NameField.GetValue()) c = canvas.Canvas("myFile.pdf", pagesize=landscape(A3)) txt = """'I want this to open only after I clicked the "Save To PDF" button. Also, the text field value (NameString variable) should appear here =>' + %s """ % nameString c.drawCentredString(600, 800, txt) c.save() # Virtual event handlers, overide them in your derived class def SaveToPDF_Function( self, event ): self.create_pdf() if __name__ == "__main__": app = wx.App(False) frame = MyFrame1() app.MainLoop() I recommend reading the following articles on threads and wxPython: * <http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/> * <http://wiki.wxpython.org/LongRunningTasks> To add threading back in, I would create a threading class like your Launcher. However, I would put ALL the reportlab code inside that class and when you instantiate the Thread class, you would pass in the **namedString** : class Launcher(threading.Thread): def __init__(self,path, namedString): threading.Thread.__init__(self) self.path = 'myFile.pdf' self.namedString = namedString I hope this helps!
Execute command on linux terminal using subprocess in python Question: I want to execute following command on linux terminal using python script hg log -r "((last(tag())):(first(last(tag(),2))))" work This command give changesets between last two tags who have affected files in "work" directory I tried: import subprocess releaseNotesFile = 'diff.txt' with open(releaseNotesFile, 'w') as f: f.write(subprocess.call(['hg', 'log', '-r', '"((last(tag())):(first(last(tag(),2))))"', 'work'])) error: abort: unknown revision '((last(tag())):(first(last(tag(),2))))'! Traceback (most recent call last): File "test.py", line 4, in <module> f.write(subprocess.call(['hg', 'log', '-r', '"((last(tag())):(first(last(tag(),2))))"', 'work'])) TypeError: expected a character buffer object Working with os.popen() with open(releaseNotesFile, 'w') as file: f = os.popen('hg log -r "((last(tag())):(first(last(tag(),2))))" work') file.write(f.read()) How to execute that command using subprocess ? Answer: To solve your problem, change the `f.write(subprocess...` line to: f.write(subprocess.call(['hg', 'log', '-r', '((last(tag())):(first(last(tag(),2))))', 'dcpp'])) ### Explanation When calling a program from a command line (like bash), will "ignore" the `"` characters. The two commands below are equivalent: hg log -r something hg "log" "-r" "something" In your specific case, the original version in the shell has to be enclosed in double quotes because it has parenthesis and those have a special meaning in bash. In python that is not necessary since you are enclosing them using single quotes.
pip error code 1 when installing pyopenssl Question: Hi I am trying to install pyopenssl so i can use scrapy. When i run the installation i get this error with pip. I also get the same error when trying to install scrapy... Command python setup.py egg_info failed with error code 1 in /private/var/folders/hy/76g5m82s4nx4b8f4m1tzdd9h0000gn/T/pip_build_joegavin/cryptography Storing debug log for failure in /Users/joegavin/.pip/pip.log here is my pip list incase i'm missing something apptools (4.2.1) argcomplete (0.6.7) astropy (0.3) atom (0.3.7) backports.ssl-match-hostname (3.4.0.2) beautifulsoup4 (4.3.1) binstar (0.4.4) biopython (1.63) bitarray (0.8.1) blaze (0.4.2) blz (0.6.1) bokeh (0.4.1) boto (2.25.0) casuarius (1.1) cdecimal (2.3) chaco (4.4.1) colorama (0.2.7) conda (3.4.2) conda-build (1.3.1) configobj (4.7.2) cubes (0.10.2) Cython (0.20.1) DataShape (0.1.1) distribute (0.7.3) docutils (0.11) enable (4.3.0) enaml (0.9.1) envisage (4.4.0) Flask (0.10.1) future (0.11.2) gevent (1.0) gevent-websocket (0.9.2) gevent-zeromq (0.2.2) greenlet (0.4.2) grin (1.2.1) h5py (2.2.1) ipython (2.0.0) itsdangerous (0.23) jdcal (1.0) Jinja2 (2.7.2) keyring (3.3) kiwisolver (0.1.2) llvmpy (0.12.3) lxml (3.3.5) MarkupSafe (0.18) matplotlib (1.3.1) mayavi (4.3.1) MDP (3.3) mock (1.0.1) netCDF4 (1.0.8) networkx (1.8.1) nltk (2.0.4) nose (1.3.0) numba (0.12.1) numexpr (2.3.1) numpy (1.8.0) openpyxl (2.0.2) pandas (0.13.1) patsy (0.2.1) pep8 (1.4.6) PIL (1.1.7) pip (1.5.6) ply (3.4) psutil (1.2.1) py (1.4.20) PyAudio (0.2.7) pycosat (0.6.0) pycparser (2.10) pycrypto (2.6.1) pycurl (7.19.0) PyExcelerate (0.6.1) pyface (4.4.0) pyflakes (0.7.3) Pygments (1.6) pyinstall (0.1.4) PyInstaller (2.1) pykit (0.2.0) pyparsing (2.0.1) PySAL (1.6.0) pysam (0.6) pytest (2.5.2) python-dateutil (1.5) pytz (2013b) PyYAML (3.11) pyzmq (2.2.0.1) redis (2.9.1) requests (2.2.1) rope (0.9.4) scikit-image (0.9.3) scikit-learn (0.14.1) scipy (0.13.3) setuptools (5.1) six (1.5.2) Sphinx (1.2.1) spyder (2.2.5) SQLAlchemy (0.9.2) statsmodels (0.5.0) sympy (0.7.4.1) tables (3.1.0) tornado (3.2) traits (4.4.0) traitsui (4.4.0) ujson (1.33) virtualenv (1.11.5) VTK (5.10.1) Werkzeug (0.9.4) wsgiref (0.1.2) xlrd (0.9.2) XlsxWriter (0.5.2) xlwt (0.7.5) I've tried updating setup tools, reinstalling pip. I'm on OSX can anybody help? Thanks UPDATE : Pastebin for pip.log : <http://pastebin.com/MTNrR0n5> Answer: Perhaps your Python lacks `openssl` support? You can find out: python >>> import socket >>> hasattr(socket, 'ssl') True If `socket` doesn't have the `ssl` attribute, you don't have the needed capabilities. AFAIK, `openssl` support must be selected for compilation of the Python interpreter and cannot be installed afterwards.
python 3.4: random.choice on Enum Question: I would like to use random.choice on an Enum. I tried : class Foo(Enum): a = 0 b = 1 c = 2 bar = random.choice(Foo) But this code is not working, how can I do that ? Answer: An `Enum` is not a _sequence_ , so you cannot pass it to `random.choice()`, which tries to pick an index between 0 and `len(Foo)`. Like a dictionary, index access to an `Enum` instead expects enumeration _names_ to be passed in, so `Foo[<integer>]` fails here with a `KeyError`. You can cast it to a list first: bar = random.choice(list(Foo)) This works because `Enum` [_does_ support iteration](https://docs.python.org/3/library/enum.html#iteration). Demo: >>> from enum import Enum >>> import random >>> class Foo(Enum): ... a = 0 ... b = 1 ... c = 2 ... >>> random.choice(list(Foo)) <Foo.a: 0>
WSGI (python) how to get POST data from an HTML form? Question: This is the HTML form that "gets" /1.wsgi <form action="/1.wsgi" method="get"> <input type="text" name="one"> <input type="submit" value="Send"> </form> this is my 1.wsgi script: from cgi import parse_qs import os def application(environ, start_response): o = parse_qs(environ['QUERY_STRING']) oo = o.get('one', [''])[0] start_response('200 OK', [('content-type', 'text/html')]) yield oo works very nicely, _BUT_ I would like to use `POST` method rather than `GET`. I understand in html form `"get"` has to be changed to `"post"` but what exactly must I do in the WSGI script? Answer: A POST sends the encoded form data in the request body; read `CONTENT_LENGTH` bytes from the `wsgi.input` stream: try: request_body_size = int(environ.get('CONTENT_LENGTH', 0)) except (ValueError): request_body_size = 0 request_body = environ['wsgi.input'].read(request_body_size) o = parse_qs(request_body) This is assuming you are still using the default form encoding, `application/x-www-form-urlencoded`.
Read in binary mode interpreting newline character Question: I have a binary file that I am trying to parse based on a protocol. In the binary data there is this value `'\nW\xe1A'` which was generated by the C struct like so: struct. pack( '< f',28.1675). When I try to open the file with `'rb'` and use `unpack` to get the float back, the read(length) seems only getting the part without `'\nW'`, just `'\xe1A'`, it is like Python is interpreting the newline character `'\n'`, but open with `'rb'` is supposed to avoid this ? Is there any solution to this? Answer: There should be nothing wrong with the code you show. Here is a minimal example: import struct s = struct.pack("<f", 28.1675) open("/tmp/testi.dat", "wb").write(s) s1 = open("/tmp/testi.dat", "rb").read() print struct.unpack("<f", s1)[0] This gives 28.1674995422, which is pretty close. If you use both "rb" and "wb", there should be no newline hassle in the way.
error: no such table UNABLE TO CREATE DB Question: i am trying to run a database and make entries into it using the following code to run the database. even though i make proper entries, i still get an error "no such table: user" from flask import Flask, request, flash, url_for, redirect from flask.ext.sqlalchemy import SQLAlchemy from spello import app from datetime import datetime app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///spello.db' db = SQLAlchemy(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///spello.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer , primary_key = True) #defines the id email = db.Column(db.String(90)) #defines the Developer's email ID URL = db.Column(db.String(120)) #defines the URL # created_on = db.Column(db.DateTime) def __init__(self, email, URL): self.email = email self.URL = URL # self.creation = datetime.now() def __repr__(self): return "<User %r>" % self.email i open python in the command line and type the following codes >>> from spello import models >>> from spello.models import db,User >>> db.create_all() >>> u = User('[email protected]','www.asd.com') >>> db.session.add(u) >>> db.session.commit() but i when i run sqlite3 in the commandline to check if the database is created, i get the following error (spello)$ sqlite3 sqlite> select * from user; Error: no such table: user can please sm1 tell where i m going wrong?? Answer: What a recent version of the `sqlite3` tool actually says is: $ sqlite3 SQLite version 3.8.4.3 2014-04-03 16:53:12 Enter ".help" for usage hints. Connected to a transient in-memory database. Use ".open FILENAME" to reopen on a persistent database. sqlite> To open your database, you must actually open it: $ sqlite3 /wherever/you/have/put/spello.db
python: pickle misbehaving in django shell as opposed to python shell? Question: As an additional question stemming from [my previous question](http://stackoverflow.com/questions/24240001/pickle-cant-store-an- object-in-django-locmem-cache-during-tests/24241848#24241848) it turns out that pickle behaves differently in django shell compared to python shell... this script: import pickle class TestObj(object): pass testobj = TestObj() pickled = pickle.dumps(testobj, pickle.HIGHEST_PROTOCOL) will work fine in python shell, but in django shell will raise a `PickleError` along the lines of `PicklingError: Can't pickle <class 'TestObj'>: attribute lookup __builtin__.TestObj failed` Is anyone able to explain the issue here? and if possible, link it back to my previous question? Answer: `pickle` will make sure it can re-import a class, as only the data on the instance itself is pickled, plus the import location of the class. As such, `pickle` looks for the `__module__` attribute on the class to determine where it came from. It appears the Django interactive environment does not _set_ this `__module__` attribute; as a result `TestObj.__module__` is inherited from the `object` base class instead, and that's `__builtin__`. Perhaps no `__name__` global is set. As a result, the `pickle` module ends up looking in the wrong place for your class. There is no `__builtin__.TestObj` after all. From the comments, I gather that you are trying to store mocked objects in the Django cache. That won't work, as [mock objects are not pickleable](https://code.google.com/p/mock/issues/detail?id=139). That makes sense, as on _unpickling_ (which could be in an entirely new Python process), how would `pickle` know what original class was being mocked?
Looking through a list for a certain or relatively close value Question: I have a csv file that looks like this: Type Mag ra dec 3 24.6 223.2 50.833 6 24.5 223.19 50.834 With more than 500 values per column. I want to look for a certain value and anything close to it. I have the values 223.2516 for the ra and 58.0538 for the dec. These values were converted and they may not be exactly like this in the csv data file. I therefore, want anything that's close to the values I'm looking for. If I'm looking for 223.2516 then anything that has at least 223.25 should come out as a result this way i can compare which one is the closest. All I have now is to ask python to do a search i.e. 223.2516 in [row[2] for row in data] But this only returns true of this exact value is there which may or may not be there. Like I said, I want all values that are close to that one with the first 5 numbers: "223.25". I tried adding an asterisk after 223.25 as such 223.2 * in [row[2] for row in data] but all I get is File "<ipython-input-16-d185380219a6>", line 1 223.2 * in [row[2] for row in data] ^ SyntaxError: invalid syntax Here's the whole code: import numpy from matplotlib import * from pylab import * data = np.genfromtxt('result.csv',delimiter=',',skip_header=1, dtype=float) 223.2516 in [row[2] for row in data] The value to be found will obviously be through user input, I just haven't added that part yet. Any help is appreciated Answer: yes, what you want is something like: arr = r_[1:10] [a for a in arr if abs(a-5) < 2 ] This results in [4,5,6], for example.
Import Numerous Modules Question: I'm working on my making a simple tester for my project, my project is a group of many self contained python files (e.g. solution1.py, solution2.py, etc.). My tester works, but it requires me to do `import solution1, solution2, ...`, how can I just import everything that matches a pattern? I have tried creating a list of the files using glob and importing the list, but that gave: ImportError: No module named solutions I tried to eval() it, but that was 'invalid syntax'. Perhaps the question is, how can I interpolate a list of strings into a list of modules? Thanks! Answer: You can import a module identified by a string with the [`importlib`](https://docs.python.org/2/library/importlib.html) module: import importlib list_of_module_names = ... for s in list_of_module_names: importlib.import_module(s)
Sending email without keyfile (only certfile) using Python smtplib Question: Trying to send email with a certificate file using the following script: import smtplib client = smtplib.SMTP(myhost, myport) client.ehlo() client.starttls(certfile=mycertfile) client.ehlo() client.login(myusername, mypassword) client.sendmail(sender, receiver, Message) client.quit() I get the following error: SSLError: error:140B0009:SSL routines:SSL_CTX_use_PrivateKey_file:PEM lib I think documentations ([smtplib.html](https://docs.python.org/2/library/smtplib.html#smtplib.SMTP.starttls) and [ssl.html](https://docs.python.org/2/library/ssl.html)) say I need to provide a private key. I only have the certificate file (base64 PEM format). My devops says that a private key is not required in this case because I do not need to identify the local side of the connection. ## Question Is there a way to send the email without providing the private key? If a private key is required, why? Answer: There are two ways to use SSL/TLS: client authenticated and "basic" where the client is unauthenticated. In client authenticated connections, the both the server and the client send a certificate to the other. In "basic" only the server does. If you pass neither a certificate nor a keyfile, `smtplib` will use a basic connection, where the client is authenticated. If you use a certificate, it will be used for a client authenticated connection. In that case, the server will demand that the client shows it owns the certificate by signing a handshake message. For the client to be able to do that it also needs the private key, which can be either in the certificate file or as a separate keyfile. Long story short, if you want to use a client certificate, you must also use a key. If not, you can just leave both empty. * * * OTOH, maybe you have a server certificate file or CA list you want to use with the connection? In that case you need to pass it to `ssl.wrap_socket` in the `ca_certs` parameter. Since you use Python 2.6 there's no easy way to do that with `smtplib` (Python 3.3+ has a `context` argument to [starttls](https://docs.python.org/3.4/library/smtplib.html#smtplib.SMTP.starttls)). How to solve this depends on your application. For example, if you do not need `ssl` for anything else, a hackish solution would be to monkey-patch `ssl.wrap_socket` with one that provides your `ca_cert` (as well as `cert_reqs=CERT_REQUIRED`, likely). A more full blown solution would be to extend `smtplib.SMTP` with your own variant that does allow passing in those parameters.
Python3 Convert list of HEX values to Bytes Question: I have a list of bytes that are represented in string format, for example, when I print the list in Python3.3 I get the following output: DATA = ['FF', 'FF', 'FF', 'FF'] I would like to convert these into bytes, for example 0xFF,0xFF,0xFF,0xFF. I have tried the bytearray() function but this returns an error. I'm guessing that I am missing something simple here, but I have looked around SO and Google and have so far had no luck Thanks! Answer: Use [`binascii.unhexlify()`](https://docs.python.org/3/library/binascii.html#binascii.unhexlify) on the joined 'bytes': import binascii bytestring = binascii.unhexlify(''.join(DATA)) Demo: >>> import binascii >>> DATA = ['FF', 'FF', 'FF', 'FF'] >>> binascii.unhexlify(''.join(DATA)) b'\xff\xff\xff\xff' Note that this is _way faster_ than using manual conversion to integers: >>> import timeit >>> timeit.timeit("bytes(int(x, 16) for x in DATA)", 'from __main__ import DATA') 1.7035537050105631 >>> timeit.timeit("unhexlify(''.join(DATA))", 'from __main__ import DATA; from binascii import unhexlify') 0.2515432750224136 That's a 7x speed difference.
searching google images from python Question: #!/usr/bin/env python import urllib import mechanize from bs4 import BeautifulSoup from urlparse import urlparse def getPic(search): search = search.replace(" ","%20") try: browser = mechanize.Browser() browser.set_handle_robots(False) browser.addheaders = [('User-Agent','Mozilla')] htmltext = browser.open("https://www.google.com/search?site=&tbm=isch&source=hp&biw=1855&bih=990&q=" + search + "&oq=" +search) img_url = [] formatted_images = [] soup = BeautifulSoup(htmltext) results = soup.findAll("a") for r in results: try: if "imgres?imgurl" in r['href']: img_url.append(r['href']) except: a=0 for im in img_url: refer_url = urlparse(str(img_url[0])) return refer_url.query.split("&")[0].replace("imgurl=","") return formatted_images except: print "error" print getPic("occupy wall street") Instead of getting the link of an image as output I'm getting "[]" as an output.Can someone figure out what's the problem with my code. Answer: Google sends `"imgres?imgurl"` only to browser with JavaScript but `mechanize.Browser()` is like browser without JavaScript. Turn off JavaScript in your browser and see HTML send by Google.
Idiomatic Clojure implementation of maze generation algorithm Question: I am implementing algorithms to create and solve mazes in both Python and Clojure. I have experience with Python and am working to learn Clojure. I am likely doing too literal of a conversion from Python to Clojure and I am looking for input on a more idiomatic way to implement the code in Clojure. First the working Python implementation import random N, S, E, W = 1, 2, 4, 8 DX = {E: 1, W: -1, N: 0, S: 0} DY = {E: 0, W: 0, N: -1, S: 1} OPPOSITE = {E: W, W: E, N: S, S: N} def recursive_backtracker(current_x, current_y, grid): directions = random_directions() for direction in directions: next_x, next_y = current_x + DX[direction], current_y + DY[direction] if valid_unvisited_cell(next_x, next_y, grid): grid = remove_walls(current_y, current_x, next_y, next_x, direction, grid) recursive_backtracker(next_x, next_y, grid) return grid def random_directions(): directions = [N, S, E, W] random.shuffle(directions) return directions def valid_unvisited_cell(x, y, grid): return (0 <= y <= len(grid) - 1) and (0 <= x <= len(grid[y]) - 1) and grid[y][x] == 0 def remove_walls(cy, cx, ny, nx, direction, grid): grid[cy][cx] |= direction grid[ny][nx] |= OPPOSITE[direction] return grid Now the Clojure version that I have so far. Currently I believe it is not working because I am using the for macro which is passing a symbol into recur when it needs to be passing a vector. As I was trying to find a solution for this issue I felt like I was trying too hard to force the code to be Python which prompted this question. Any guidance is appreciated. (ns maze.core) (def DIRECTIONS { :N 1, :S 2, :E 4, :W 8}) (def DX { :E 1, :W -1, :N 0, :S 0}) (def DY { :E 0, :W 0, :N -1, :S 1}) (def OPPOSITE { :E 8, :W 4, :N 2, :S 1}) (defn make-empty-grid [w h] (vec (repeat w (vec (repeat h 0))))) (defn valid-unvisited-cell? [x y grid] (and (<= 0 y (- (count grid) 1)) ; within a column (<= 0 x (- (count (nth grid y)) 1)) ; within a row (= 0 (get-in grid [x y])))) ; unvisited (defn remove-walls [cy, cx, ny, nx, direction, grid] (-> grid (update-in [cy cx] bit-or (DIRECTIONS direction)) (update-in [ny nx] bit-or (OPPOSITE direction)))) (defn recursive-backtracker [current-x current-y grid] (loop [current-x current-x current-y current-x grid grid] (let [directions (clojure.core/shuffle [:N :S :E :W])] (for [direction directions] (let [next-x (+ current-x (DX direction)) next-y (+ current-y (DY direction))] (if (valid-unvisited-cell? next-x next-y grid) (loop next-x next-y (remove-walls current-x current-y next-x next-y direction grid))))) grid))) Answer: This seems like a basically reasonable translation of the Python code into Clojure (including some stuff beginners often miss - nicely done)...until we get to `recursive-backtracker`, the heart of the problem. You can't just transliterate the Python here, because your algorithm assumes mutability of `grid`: you call yourself recursively four times inside the `for` loop, and you need changes made to the grid to be reflected. That's not how Clojure works, so this whole thing doesn't work. The actual error you're getting is an unrelated syntax error (double-check the interface to loop/recur), but it's not really relevant here since you have to rewrite the function anyway, so I'll leave it at that. Now, how can you rewrite this function to work without mutating `grid`? As is so often the case, you can use `reduce`: for each of the four directions, you call `recursive-backtracker`, getting back a modified grid, and you make sure to use _that modified grid_ for the next recursive call. The general outline will look like this: (defn recursive-backtracker [current-x current-y grid] (reduce (fn [grid direction] (let [next-x (+ current-x (DX direction)) next-y (+ current-y (DY direction))] (if (valid-unvisited-cell? next-x next-y grid) (recursive-backtracker next-x next-y (remove-walls current-x current-y next-x next-y direction grid)) grid))) grid, (clojure.core/shuffle [:N :S :E :W]))) With that definition, `(recursive-backtracker 0 0 (make-empty-grid 5 5))` produces `[[2 5 6 3 5] [4 10 9 6 9] [14 3 1 12 4] [12 6 3 9 12] [10 11 3 3 9]]` \- is that a valid maze? It looks okay, but I don't know. You probably don't either. Which brings me to another point: using integers and bitwise arithmetic is an exercise in pointless optimization. Instead, make each entry in the grid be a map, or a set, containing keywords saying what directions are open for it. Then on inspection you can at least get a general idea for whether the maze is self-consistent.
Qmark in pymysql query Question: I'm new to python, just moving from php5. I read about the qmark param notation to prepare a query but I get the following: Traceback (most recent call last): File "t.py", line 10, in <module> cursor.execute("SELECT * FROM object WHERE otype = ?", ["user"]) File "/usr/local/lib/python3.4/site-packages/pymysql/cursors.py", line 130, in execute query = query % self._escape_args(args, conn) TypeError: not all arguments converted during string formatting Is that only for sqlite connector? import sys import pymysql try: connection = pymysql.connect(host="127.0.0.1", user="root", passwd="pass", db="xxx") except: sys.exit("Database connection error") cursor = connection.cursor() cursor.execute("SELECT * FROM object WHERE otype = ?", "user") for row in cursor: print(row) cursor.close() connection.close() Answer: Yes. Unfortunately the DB-API specification left it up to each implementer to choose the parameter. pysqlite chose the ?, and MySQLdb chose %s. Since pymsql is a drop-in replacement for MySQLdb, it also uses %s.
Using python to save a JPG image that was edited in the script Question: Referring to the answer to [this question](http://stackoverflow.com/questions/14452824/saving-image-in-python- pil), I tried to save my own JPG image files, after some basic image processing. I've only applied a rotation and a shear. This is my code: import numpy as np import sys from skimage import data, io, filter, color, exposure import skimage.transform as tf from skimage.transform import rotate, setup, AffineTransform from PIL import Image mypath = PATH_TO_FILENAME readfile = FILENAME img = color.rgb2gray(io.imread(mypath + readfile)) myimg = rotate(img, angle=10, order=2) afine_tf = tf.AffineTransform(shear=0.1) editedimg = tf.warp(myimg, afine_tf) # IF I UNCOMMENT THE TWO LINES BELOW, I CAN SEE THE EDITED IMAGE AS EXPECTED #io.imshow(editedimg) #io.show() saveimg= np.array(editedimg) result = Image.fromarray((saveimg).astype(np.uint8)) newfile = "edited_" + readfile result.save(path+newfile) I know that the image processing was fine because if I display it before saving, it's just the original image with a bit of rotation and shearing, as expected. But I'm doing something wrong while saving it. I tried without the `astype(np.uint8))` part but got an error. Then I removed some of the code from the link mentioned above because I guessed it was particularly for Fourier Transforms, since when I included some of their code, then I got an image that was all gray but with white lines in the direction of the shear I'd applied. But now the image that gets saved is just 2KB of nothing but blackness. And when I tried something as simple as: result = Image.fromarray(editedimg) result.save(path+newfile) then I got this error: raise IOError("cannot write mode %s as JPEG" % im.mode) IOError: cannot write mode F as JPEG I don't really need to use PIL, if there's another way to simply save my image, I'm fine with that. Answer: Look into the PIL fork, [Pillow](https://pypi.python.org/pypi/Pillow/2.1.0), is is not as outdated and what you should probably be using for this. Also depending on your operating system you may need a few other libraries to compile PIL with JPEG support properly, [see here](http://stackoverflow.com/questions/8915296/python-image-library-fails- with-message-decoder-jpeg-not-available-pil) [This may also help](http://stackoverflow.com/questions/21669657/getting- cannot-write-mode-p-as-jpeg-while-operating-on-jpg-image) Says you need to convert your image to RGB mode before saving. Image.open('old.jpeg').convert('RGB').save('new.jpeg')
Python barcode scanner buffer is not clearing Question: OS is Windows 7 x64 (running Python x86) but code needs to be exportable to Windows XP and Ubuntu Linux. This part of the problem is Windows 7 x64 specific, possibly. I am using a USB barcode scanner that is HID Keyboard compatible. I open a command prompt in the folder where my keyboard.py file exists and execute it. It works perfectly the first time and exits, OK. When I rerun in the same window the scanner data appears to be buffered and no longer changes when new scans are made. I've tried closing the code using: .flush() .readline() and .read() all to no avail. Is this a flaw in Win7 or am I missing something. CODE: import sys x = '' oStr = '' #while x != 'exit': while True: x = sys.stdin.read(1) if (x.find('\n') != -1) or (x.find('\04') != -1): break oStr = oStr + x print 'Output String: ' + oStr #+ '\n' Output: > D:\Python Projects\Keyboard Input>keyboard.py > [)>0617V33SR41P12973001S10515725 Output String: > [)>0617V33SR41P12973001S10515725 > > D:\Python Projects\Keyboard Input>keyboard.py > [)>0617V33SR41P12973001S10515725 The second run stalls, as shown. But, the second scan ended with 23 not 25! If I press `Enter` the script completes. Further scans are the same. Answer: To clarify my previous comment, start with this: while 1: print sys.stdin.readline.strip() This should give you a barcode per trigger press. If this works and then running the program sequentially fails you need to look at how your barcode scanner is configured (and this would be a windows configuration issue, not a python issue). * * * **Update:** windows console displayed some weirdness in console which you can workaround by using msvcrt.getch(), however this is not a cross platform solution. One possible approach to making this cross platform would be something like: try: from msvcrt import getch except: import sys getch = lambda: sys.stdin.read(1) Where you would then program against getch() for reading input.
Deploying Project in PythonAnywhere. Settings Module Import Errror Question: I´m trying to deploy my django 1.6.4 project on pythonAnywhere using python 2.7 I already configured a virtual enviroment and the wsgi file according to the guidelines on the website. But I´m getting a 404 when I check the site. The error lol tells me this: ImportError: Could not import settings 'tango_with_django_project.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named tango_with_django_project.settings Here´s my wsgi: # +++++++++++ DJANGO +++++++++++ # TURN ON THE VIRTUAL ENVIRONMENT FOR YOUR APPLICATION activate_this = '/home/pjestrada/.virtualenvs/rango/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) # To use your own django app use code like this: import os import sys # ## assuming your django settings file is at '/home/pjestrada/mysite/settings.py' path = '/home/pjestrada/rango/tango_with_django_project' if path not in sys.path: sys.path.append(path) os.chdir(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'tango_with_django_project.settings' # import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() My tree: ├── Dropbox │ ├── README.txt │ └── __init__.py ├── README.txt └── rango ├── LICENSE ├── README.md └── tango_with_django_project ├── manage.py ├── media │ ├── profile_images │ │ └── 10411981_634016890008979_1609187547738555774_n.jpg │ └── rango2.jpg ├── populate_rango.py ├── rango │ ├── __init__.py │ ├── __init__.pyc │ ├── admin.py │ ├── admin.pyc │ ├── bing_search.py │ ├── bing_search.pyc │ ├── forms.py │ ├── forms.pyc │ ├── models.py │ ├── models.pyc │ ├── tests.py │ ├── urls.py │ ├── urls.pyc │ ├── views.py │ └── views.pyc ├── static │ ├── about.jpg │ ├── css │ │ ├── bootstrap-fluid-adj.css │ │ ├── bootstrap-responsive.css │ │ ├── bootstrap-responsive.min.css │ │ ├── bootstrap.css │ │ └── bootstrap.min.css │ ├── img │ │ ├── glyphicons-halflings-white.png │ │ └── glyphicons-halflings.png │ ├── js │ │ ├── bootstrap.js │ │ ├── bootstrap.min.js │ │ ├── jquery-2.1.1.js │ │ └── rango-ajax.js │ └── rango.jpg ├── tango_with_django_project │ ├── __init__.py │ ├── __init__.pyc │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ ├── urls.pyc │ └── wsgi.py └── templates └── rango ├── about.html ├── add_category.html ├── add_page.html ├── base.html ├── category.html ├── category_list.html ├── index.html ├── login.html ├── page_list.html ├── profile.html ├── register.html ├── restricted.html └── search.html Answer: Try changing value of path. `path = '/home/pjestrada/rango'` That path is your project directory. It worked for me.
Creating Rules for Word Permutations Based on a word's POS Tag Question: I have another question and since this community has been so great helping me along I thought I would give it another shot. Right now I have Python 3 code that imports a CSV file where the first column is full of words in the following format: The Words Look Like This In A Column Once this CSV file is uploaded and read by Python, the words are tagged using an NLTK POS Tagger. From there, permutations are made from all of the words and then the results are exported to a new CSV file. Right now, my full code goes like this Import CSV with open(r'C:\Users\jkk\Desktop\python.csv', 'r') as f: reader = csv.reader(f) J = [] for row in reader: J.extend(row) import nltk D = nltk.pos_tag(J) C = list(itertools.permutations(D, 3)) with open('test.csv', 'w') as a_file: for result in C: result = ' '.join(result) a_file.write(result + '\n') **My question is, how does one make rules for the word permutations based on the word tag?** More specifically, the reason I am tagging words is because I don't want nonsense permutations (i.e. The This In / A This In / etc). Once the words are tagged with their respective part of speech, how do I code rules based on their tag (for example): Never have two "DT" labeled words follow each other (i.e. "The" and "A"). Or always have a NN tagged word be followed by a VBG tagged word (i.e. "Looks" always comes after "Words")? And then finally, once those rules are implemented, get rid of the tags so that just the original words remain? I realize this is a general question but any guidance would be very much appreciated on how to approach this question as I am still very new and learning every step of the way! Any resources, code, or even advice would help! Thank you again for taking the time to read this long post! Answer: The set of rules that define legal strings in a language is called a grammar (or formal grammar). There are many formalisms which allow you to express these rules. One that is reasonnably simple to experiment with is a context free grammar ([CFG](http://en.wikipedia.org/wiki/Context_free_grammar)). NLTK comes with tools to generate strings from these. Here is the [NLTK book's chapter on syntax](http://www.nltk.org/book/ch08.html). They go into much more depth. The following code is for python 3 with NLTK 3.0a4. The API changed between NLTK 2 and 3, so it will not run on the older version. from nltk import ContextFreeGrammar from nltk.parse.generate import generate from ntlk.util import trigrams # build a simple grammar cfg = """ S -> NP VP VP -> VBZ NP NP -> DT | NN | DT NN | DT JJ NN | JJ NN """ # you get these from your csv words = "this is a simple sentence".split() tagged = set(pos_tag(words)) # Add the words to the grammar for word, tag in tagged: cfg += "{tag} -> '{word}'\n".format(word=word, tag=tag) grammar = parse_cfg(cfg) valid_trigrams = set() language = generate(grammar) for valid_sentence in language: valid_trigrams.update(list(trigrams(valid_sentence))) print(valid_trigrams) # {('simple', 'sentence', 'is'), ('this', 'is', 'this'), ('a', 'sentence', 'is'), ('sentence', 'is', 'a'), ('a', 'is', 'a'), ('this', 'is', 'simple'), ('sentence', 'is', 'this'), ('this', 'is', 'sentence'), ('is', 'a', 'sentence'), ('is', 'a', 'simple'), ('a', 'simple', 'sentence'), ('a', 'is', 'this'), ('this', 'simple', 'sentence'), ('this', 'is', 'a'), ('is', 'simple', 'sentence'), ('a', 'is', 'simple'), ('this', 'sentence', 'is'), ('is', 'this', 'sentence'), ('sentence', 'is', 'sentence'), ('sentence', 'is', 'simple'), ('is', 'this', 'simple'), ('a', 'is', 'sentence')} There is a limitation to this approach though, since a context free grammar cannot cover all of English. There is no known way of validating syntax for English anyways though, so you can only have an approximate solution. Another thing you should be aware of is that the POS tagger assumes that the order of words is relevant. Roughly, it gives each word a set of possible tags, then refines it based on the preceding and or following words, so if you're CSV contains sentences, then you are ok, otherwise, you might want to specify the unigram pos tagger `nltk.tag.UnigramTagger`, but regardless, you will only get the most common tag. This will be an issue for words like "run" which can be a verb or a noun ("a morning run" vs "I run").
Raspberry Pi connection with Arduino over XRF continuous sensor monitoring Question: I'm trying to make a system for monitoring sensor continuously including registering the time when the sensors are offline (not reachable by the server). The system is based on Raspberry Pi as server and Arduino Leonardo as node with sensors and the data is communicated from Arduino to Raspberry via XRF. I'm using Python script with pySerial for collecting data. My Python skills are poor and I need help to figure out how to continue monitoring when the connection between Arduino and Raspberry is lost and when the connection is re-established the sensor data could be collected again without restarting the script. the Python script follows: import serial from datetime import datetime ser = serial.Serial('/dev/ttyAMA0', 9600) while True: #Arduino sends sensor analog reading when receiving the letter "k" ser.write('k') datetime = str(datetime.now()) print(datetime) print(ser.readline()) At the moment once the server looses connection to the client the script will stop. Answer: I guess you need periodically reopen the connection, and also log the moments when the connection is lost? something like this... import serial import time from datetime import datetime ser = serial.Serial('/dev/ttyAMA0', 9600) while True: if ser.isOpen()==True: ser.write('k') # Arduino sends sensor analog reading when receiving the letter "k" datetime = str(datetime.now()) print(datetime) print(ser.readline()) time.sleep(1) # take a break so that you dont thrash the sensor with requests all the time else: try: print "Lost connection at %s" % str(datetime.now()) ser.open() except: print "Cannot open port." exit(-1)
Python: How can I plot a generic 3D object if I have x, y and z as functions of some parameters? Question: For instance, for the unit sphere, one has x = cos(phi)sin(theta) y = sin(phi)sin(theta) z = cos(theta) I would like to simply plot the set of points where phi and theta are in the intervals `[0, 2*pi]` and `[0, pi]`, respectively. Is there a way to do this in the general case, meaning specifying * x,y,z as functions of some parameters, and * The ranges of those parameters and then getting a 3D plot of that? Answer: I think as far as Mayavi goes, you will always be stuck with creating some grids yourself, and plotting the resulting datapoints... This does, however, not have to be too cumbersome when using numpy : from numpy import pi, sin, cos, mgrid [phi,theta] = mgrid[0:2*pi:100j,0:pi:100j] # 100 is the amount of steps in the respective dimension x = cos(phi)*sin(theta) y = sin(phi)*sin(theta) z = cos(theta) from mayavi import mlab s = mlab.mesh(x, y, z) mlab.show()
Python Data Insert From Beautiful Soup Table to MYSQL Question: I am trying to insert data into a MYSQL table from a html table using beautiful soup written in python. Currently I was able to do this by creating an interim csv file but it does not seems to work in Linux and seems inefficient. Below is my code that works with the CSV, which is the portion I will like to elimnate. import urllib2, base64, csv from bs4 import BeautifulSoup request = urllib2.Request("http://website.com") base64string = base64.encodestring('%s:%s' % ('username','password')).replace('\n','') request.add_header("Authorization", "Basic %s" % base64string) result = urllib2.urlopen(request) soup = BeautifulSoup(result.read()) table=soup.findAll('table')[6] f = open('output.csv', 'w') for row in table.findAll('tr'): cells = row.findAll('td') #For each "tr", assign each "td" to a variable. if len(cells) == 19: column1 = cells[0].find(text=True) column2 = cells[1].find(text=True) column3 = cells[2].find(text=True) column4 = cells[3].find(text=True) column5 = cells[4].find(text=True) column6 = cells[5].find(text=True) column7 = cells[6].find(text=True) column8 = cells[7].find(text=True) column9 = cells[8].find(text=True) column10 = cells[9].find(text=True) column11 = cells[10].find(text=True) column12 = cells[11].find(text=True) column13 = cells[12].find(text=True) column14 = cells[13].find(text=True) column15 = cells[14].find(text=True) column16 = cells[15].find(text=True) column17 = cells[16].find(text=True) column18 = cells[17].find(text=True) column19 = cells[18].find(text=True) TOTAL_AD_CALLS = column6.replace(',','') TOTAL_US_AD_CALLS = column7.replace(',','') TOTAL_NON_US_AD_CALLS = column8.replace(',','') TOTAL_NON_CLEAN_US_AD_CALLS = column10.replace(',','') TOTAL_CLEAN_US_AD_CALLS = column12.replace(',','') UNUSABLE_AD_CALLS = column13.replace(',','') NO_ADS_RETURNED = column14.replace(',','') PSAS_RETURNED = column15.replace(',','') ADS_RETURNED = column16.replace(',','') TOTAL_RETURNED = column17.replace(',','') TOTAL_IMPRESSIONS = column18.replace(',','') Engagements = column19.replace(',','') NOT_US_RATE = column9.replace('%','') NOT_CLEAN_RATE = column11.replace('%','') #district can be a list of lists, so we want to iterate through the top level lists first... write_to_file = column1 + "," + column2 + "," + column3 + "," + column4 + "," + column5 + "," + TOTAL_AD_CALLS + "," + TOTAL_US_AD_CALLS + "," + TOTAL_NON_US_AD_CALLS + "," + NOT_US_RATE + "," + TOTAL_NON_CLEAN_US_AD_CALLS + "," + NOT_CLEAN_RATE + "," + TOTAL_CLEAN_US_AD_CALLS + "," + UNUSABLE_AD_CALLS + "," + NO_ADS_RETURNED + "," + PSAS_RETURNED + "," + ADS_RETURNED + "," + TOTAL_RETURNED + "," + TOTAL_IMPRESSIONS + "," + Engagements + "\n" print write_to_file f.write(write_to_file) f.close() import MySQLdb import os import string # Open database connection db = MySQLdb.connect(host="ipadress", # your host, usually localhost user="admin", # your username passwd="other", # your password db="dailies") # name of the data base cursor=db.cursor() #Query under testing sql = """LOAD DATA LOCAL INFILE 'output.csv' \ INTO TABLE PYTHON_TEST \ FIELDS TERMINATED BY ',' \ OPTIONALLY ENCLOSED BY '"' \ LINES TERMINATED BY '\r\n' \ IGNORE 0 LINES;;""" #LINES TERMINATED BY '\r\n' \ try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server db.close() Answer: I was able to figure it out. If anyone else as a similar problem hope this helps. import urllib2, base64, csv from bs4 import BeautifulSoup import MySQLdb import os import string import datetime request = urllib2.Request("website.com") base64string = base64.encodestring('%s:%s' % ('username','password')).replace('\n', '') request.add_header("Authorization", "Basic %s" % base64string) result = urllib2.urlopen(request) soup = BeautifulSoup(result.read()) #print(soup.prettify()) #table=soup.find('table', {"class":"resultsTable,ruler,sortable"})[0] # Open database connection db = MySQLdb.connect(host="ipaddress", # your host, usually localhost user="username", # your username passwd="password", # your password db="databsae") # name of the data base cursor=db.cursor() table=soup.findAll('table')[6] #print table for row in table.findAll('tr'): cells = row.findAll('td') #For each "tr", assign each "td" to a variable. if len(cells) == 19: column1 = cells[0].find(text=True) column2 = cells[1].find(text=True) column3 = cells[2].find(text=True) column4 = cells[3].find(text=True) column5 = cells[4].find(text=True) column6 = cells[5].find(text=True) column7 = cells[6].find(text=True) column8 = cells[7].find(text=True) column9 = cells[8].find(text=True) column10 = cells[9].find(text=True) column11 = cells[10].find(text=True) column12 = cells[11].find(text=True) column13 = cells[12].find(text=True) column14 = cells[13].find(text=True) column15 = cells[14].find(text=True) column16 = cells[15].find(text=True) column17 = cells[16].find(text=True) column18 = cells[17].find(text=True) column19 = cells[18].find(text=True) TOTAL_AD_CALLS = column6.replace(',','') TOTAL_US_AD_CALLS = column7.replace(',','') TOTAL_NON_US_AD_CALLS = column8.replace(',','') TOTAL_NON_CLEAN_US_AD_CALLS = column10.replace(',','') TOTAL_CLEAN_US_AD_CALLS = column12.replace(',','') UNUSABLE_AD_CALLS = column13.replace(',','') NO_ADS_RETURNED = column14.replace(',','') PSAS_RETURNED = column15.replace(',','') ADS_RETURNED = column16.replace(',','') TOTAL_RETURNED = column17.replace(',','') TOTAL_IMPRESSIONS = column18.replace(',','') Engagements = column19.replace(',','') NOT_US_RATE = column9.replace('%','') NOT_CLEAN_RATE = column11.replace('%','') Created = datetime.datetime.now() print Engagements cursor.execute ("INSERT INTO PYTHON_TEST (REPORT_TYPE, THE_DATE, PARENT_ID, SITE_ID,SITE_NAME, TOTAL_AD_CALLS, TOTAL_US_AD_CALLS, TOTAL_NON_US_AD_CALLS, NOT_US_RATE, TOTAL_NON_CLEAN_US_AD_CALLS, NOT_CLEAN_RATE, TOTAL_CLEAN_US_AD_CALLS, UNUSABLE_AD_CALLS, NO_ADS_RETURNED, PSAS_RETURNED, ADS_RETURNED, TOTAL_RETURNED, TOTAL_IMPRESSIONS, ENGAGEMENTS, CREATED) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);", (column1, column2, column3, column4, column5, TOTAL_AD_CALLS, TOTAL_US_AD_CALLS, TOTAL_NON_US_AD_CALLS, NOT_US_RATE ,TOTAL_NON_CLEAN_US_AD_CALLS, NOT_CLEAN_RATE, TOTAL_CLEAN_US_AD_CALLS, UNUSABLE_AD_CALLS, NO_ADS_RETURNED, PSAS_RETURNED, ADS_RETURNED, TOTAL_RETURNED, TOTAL_IMPRESSIONS, Engagements, Created)) #cursor.execute ("INSERT INTO PYTHON_TEST (ENGAGEMENTS,434 ) VALUES (%s);", (Engagements)) db.commit() ''' cursor.execute ("INSERT INTO PYTHON_TEST VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);", (column1, column2, column3, column4, column5, TOTAL_AD_CALLS, TOTAL_US_AD_CALLS, TOTAL_NON_US_AD_CALLS, NOT_US_RATE ,TOTAL_NON_CLEAN_US_AD_CALLS, NOT_CLEAN_RATE, TOTAL_CLEAN_US_AD_CALLS, UNUSABLE_AD_CALLS, NO_ADS_RETURNED, PSAS_RETURNED, ADS_RETURNED, TOTAL_RETURNED, TOTAL_IMPRESSIONS, Engagements, Created, Created))''' # disconnect from server db.close()
Flask flash and url_for with AJAX Question: _I am currently stuck on a rather "big" problem, and I will try to be as clear and concise as I can about it. I am developing a tool in Python, using Flask. It's meant to be an intranet. The idea is that I have a client page. There's its name, numerous other infos, and a massive checklist._ The infos are already written in input fields, so that the user just has to edit them there, press enter, and the page is reloaded with the edited information (with a notification, using the flashed messages and growl). The massive checklist is forcing me to move to a system using AJAX, since I want it to be updated "live" as users tick boxes and enter content in inputs, without reloading the page. As a consequence, I'm also switching my basic inputs for infos to AJAX, to avoir the reloading of the mage. I've come across two issues : **The first one concerns the message flashing feature of Flask.** I've got a method that updates a client name in the database, flashes a message (success or failure, depending on numerous things), then displays the page again. To avoid the page reload, I'm managing the form submit with AJAX. The problem is, my python method will flash messages. And once I'm back on my html page (that has not been reloaded, since it's AJAX), the get_flashed_message function of Jinja2 returns me nothing, since it has not been updated. As a consequence, it's impossible for me to retrieve those flashed messages. How can I get these ? The only solution I see is getting rid of any usage of flash, and coding my own messages système, that I would return from the method, and then treat in javascript. Which seems incredibly dumb, since flash is a feature of Flask, and it's made "useless" by AJAX ? I feel like I'm missing something. (as a note, until now, my flashed messages management is made in my base layout, that calls a template that runs through all messages and displays them as growl notifications) **Second issue concerns url_for.** Here is my form, for editing the client's name : <form id="changeClientName" method="POST" action="{{ url_for('clients.edit_client_name', name=client.name) }}" style="display:inline !important;"> <input type="text" name="name" class="form-control" value="{{ client.name }}" > <input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;"/> </form> As you can see, the action attribute uses url_for to call the right method to edit the client. My method looks like this : @mod.route('/edit/<name>/', methods=['POST']) def edit_client_name(name): So the url path is /edit/the_client_name . As a consequence, after an edit, the new URL is /edit/the_new_client_name, if we want to re-edit this name. Obviously, once the method has been called, my AJAX has to change this action attribute, to replace it with the new URL (in case the user wants to re-edit the name without changing page/reloading the page). And here is my second issue. The new name is stored in javascript. action is still the old url. So I have to call url_for using the new name. And I have found absolutely NO way to pass a Javascript variable to Jinja2. I want this : url_for('clients.edit_client_name', name=client.name) To become this : url_for('clients.edit_client_name', name=my_javascript_variable_one_way_or_another) I'll just have to call the js function that modifies an attribute of a form, and modify my action attribute with this new url_for.But I have found NO way to make this simple thing, i.e give a javascript variable to Jinja2, which seems very unlikely to me. So here are my two issues. How can I make flash compatible with AJAX ? And how can I pass a javascript attribute to Jinja2 ? I sincerely hope to find solutions for these two "stupid" issues. The only solutions that I can see would be coding my own messaging system, which would defeat the goal of flash, making it useless with AJAX, which seems stupid, and hardcoding the URL in my templates, which totally defeats the initial interest of Flask making URL independents from methods, and URL changes extremely flexible. Thanks. Answer: I'll take a stab at this, but I'm not sure I understand the problem completely :D. The code below isn't tested, it is more along the lines of pseudocode! Your first problem is (if I understand you correctly) that you are doing partial updates via ajax, and wanting to fetch the update results later after the partial updates. Instead of fetching update results _later_ , you should return them **after** each ajax call. So, if you have update code that looks like this: data = $('#my-form').serialize() $.post(update_url, data, function (results) { // Here you check results. if (results.success) { $('#update-div').message('Update Success') } else { $('#update-div').message('Update Failed: ' + results.error_msg) } }) Then your update route would have code similar to this: from flask import jsonify @app.route('/partialupdate/<int:userid>', methods=['POST']) def partial_update(userid): try: # fetch the user, perform the updates and commit return jsonify(success=1) except Exception, e: return jsonify(success=0, error_msg=str(e)) Your second problem involving URL generation can be fixed by using USERID instead of client name. _NEVER_ use client name for anything other than searches :D. In this case use user id. The user id is typically the primary key for a particular user in a database. If you're not using a database, then generate your own user id's somehow and attach it to a user - it should be a unique number per user. Using a user id means that you can always edit with urls like '/edituser/1'.
How to convert a hex-string into an unpacked IEEE 754 format number:- Question: using Python 2.7.3: How to convert a hex-string into an unpacked IEEE 754 format number:- I have a string of hex data in this form: data = '38 1A A3 44' I would like to convert this to a floating point number by using struct.unpack: fdata = struct.unpack('<f','\x38\xA1\xA3\x44') # fdata=1304.8193359375 Is there a Pythonic solution or do I need to somehow substitute an escape sequence for each space in _data_? Answer: Convert the hex codepoints to a byte string first; [`binascii.unhexlify()`](https://docs.python.org/2/library/binascii.html#binascii.unhexlify) can do this for you, provided you remove the whitespace: import binascii import struct fdata = struct.unpack('<f', binascii.unhexlify(data.replace(' ', '')))[0] Demo: >>> import binascii >>> import struct >>> data = '38 1A A3 44' >>> struct.unpack('<f', binascii.unhexlify(data.replace(' ', ''))) (1304.8193359375,)
Most efficient way to look for the last digit of a number? Question: I recently had a question in a Python exam where we were asked to check for numbers to be ending in 8 and I came across two ways and I was wondering which one was the most efficient or if there was an even better way to do so. (If n is the desired number) So, method 1: if n % 10 == 8: //do stuff here Method 2: if str(n)[-1] == 8: //do stuff here Answer: You could easily test this yourself with Python's built-in [`timeit.timeit`](https://docs.python.org/3/library/timeit.html#timeit.timeit) function: >>> from timeit import timeit >>> n = 12345678 >>> timeit("n % 10 == 8", "from __main__ import n") 0.45508130223254284 >>> timeit("str(n)[-1] == '8'", "from __main__ import n") 1.689859186013905 >>> As you can see from the results above, the first solution is very efficient and outperforms the second by almost four times.
Determining if string B could be the result of a deletion/addition to string A Question: Assume I have a base string of length 29, and a list of arbitrary strings of lengths 28 and 30. How would I determine the number of these strings which could be the result of a deletion/addition of one character performed on the base string? I'm doing this in Python, for the record. Answer: Let's see... I would modify the [Levenshtein distance algorithm](http://en.wikipedia.org/wiki/Levenshtein_distance) (Python code [here](http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python)) to make it work only in case of addition or deletion of one character. from functools import partial from my_distances import **add_delete_distance** def is_accepted(base_string, alternative_string): '''It uses the custom distance algorithm to evaluate (boolean output) if a particular alternative string is ok with respect to the base string.''' assert type(alternative_string) == str len_difference = abs(len(base_string)-len(alternative_string)) if len_difference == 1 : distance = add_delete_distance(base_string, alternative_string) if distance == 1: return True return False base_string = 'michele' alternative_strings = ['michel', 'michelle', 'james', 'michela'] print filter(partial(is_accepted, base_string), alternative_string) What do you think about it?
bs4: "soup.title.string" doesn't work on IDLE but Terminal Question: Mac OS X 10.9 Python 2.7 IDLE BeautifulSoup 4 installed (successfully) I followed [BS4 documentation](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) and was practicing some of the functions **on IDLE**. The following code works and was able to print out title & title.name. from bs4 import BeautifulSoup html = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ soup = BeautifulSoup(html) print soup.title print soup.title.name Print result: <title>The Dormouse's story</title> title But as I moved on and tried to print soup.title.string in the next line: print soup.title.string It returned: Traceback (most recent call last): File "/Users/yumiyang/Documents/python-folder/bsoup_test.py", line 24, in <module> print soup.title.string File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/idlelib/PyShell.py", line 1344, in write s = unicode.__getslice__(s, None, None) TypeError: an integer is required AND THEN, I tried to run the same code on Terminal: Python [filename].py It worked! <title>The Dormouse's story</title> title The Dormouse's story Can someone explained why the code didn't work on IDLE but Terminal? Thank you! Answer: This was a known bug, reported on the Python issue tracker as [issue #23583: IDLE: printing unicode subclasses broken (again)](http://bugs.python.org/issue23583). This was fixed a few months ago, so beginning with version 2.7.10 this should no longer happen. Try updating your Python!
Django/python and isues with xlwt locale formatting Question: I am using django-excel-view which uses django-excel-response which in turn uses xlwt. I have a scenario where users can switch locale which lets them view floats with a standard decimal point or in some languages a comma decimal point. When exporting the view as an xls with standard decimal point locale it works just fine, but using comma decimals makes the xls file store the float as text and adds an apostrophe before the number (e.g. '123,45). I have a feeling that ExcelResponse (<https://djangosnippets.org/snippets/1151/>) is not handling the float correctly (see line 43 onwards of the snippet). What would be the correct xlwt style to apply for the xls to be saved correctly with comma decimals and what is a good way to check whether a value is a comma decimal and should have that style applied? In other words: styles = {'datetime': xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss'), 'date': xlwt.easyxf(num_format_str='yyyy-mm-dd'), 'time': xlwt.easyxf(num_format_str='hh:mm:ss'), 'default': xlwt.Style.default_style, 'comma_decimal': xlwt.easyxf('????????')} for rowx, row in enumerate(data): for colx, value in enumerate(row): if isinstance(value, datetime.datetime): cell_style = styles['datetime'] elif isinstance(value, datetime.date): cell_style = styles['date'] elif isinstance(value, datetime.time): cell_style = styles['time'] elif isinstance(value, ?????????????): cell_style = styles['comma_decimal'] else: cell_style = styles['default'] sheet.write(rowx, colx, value, style=cell_style) SOLUTION: I ended up adding an extra check in django-excel-response that does some regex check for comma float values (which are added by django locale as they should be) and then replaces the commas with decimal points. elif (re.compile("^[0-9]+([,][0-9]+)?$")).match(u"{}".format(value)): value = float(value.replace(',', '.')) jmcnamara helped point me in this direction instead of messing with locales and xlwt formatting. Answer: > I have a scenario where users can switch locale which lets them view floats > with a standard decimal point or in some languages a comma decimal point. The important thing to note here is that the the thousands/decimal separators for a locale are a Windows setting and not an Excel setting. It is set in Control Panel/Regional and Language Options/Format or similar. So if in one locale the number format is displayed in Excel as `1,234.56` and in another locale it is displayed as `1.234,56` in both cases **the format is stored** in Excel as the US style: `0,000.00`. So, when using xlwt, or any other spreadsheet writing module, you should use the US style formatting options (comma for thousand and . for decimal). It will then be displayed in the users locale according to their Windows settings.
Forcing an existing module to be installed in a specific path Question: I have a module already installed in `/usr/lib64/...` by administrator Python 2.7.6 (default, Nov 11 2013, 13:13:15) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import matplotlib >>> print matplotlib.__file__ /usr/lib64/python2.7/site-packages/matplotlib/__init__.pyc What I want to do now is to have it installed in: `/home/myname/.local/lib/python2.7/site-packages` But when I tried to install it using this command: $ easy_install-2.7 --install-dir=/home/myname/.local/lib/python2.7/site-packages matplotlib What I get is this: packages matplotlib Searching for matplotlib Best match: matplotlib 1.3.1 Adding matplotlib 1.3.1 to easy-install.pth file Using /usr/lib64/python2.7/site-packages Processing dependencies for matplotlib Finished processing dependencies for matplotlib Which means it doesn't get installed at all. I confirmed this with this snippet again: >>> import matplotlib >>> print matplotlib.__file__ or $ ls -lh /home/myname/.local/lib/python2.7/site-packages How can I get it installed in my desired path and bypassing the already installed version. Answer: What you need to do here (_ideally_) is use [virtualenv](https://pypi.python.org/pypi/virtualenv) 1. Download [virtualenv](https://pypi.python.org/pypi/virtualenv) 2. Extract `virtualenv-<version>.tar.gz` 3. `cd /path/to/virtualenv` 4. Run: `python virtualenv.py $HOME` You should then be able tod; pip install matplotlib `which pip` should by something like: `/home/<user>/bin/pip`. **NB:** You need to also ensure that `$HOME` is in your `$PATH`. export PATH="$HOME/bin:$PATH" wget https://pypi.python.org/packages/source/v/virtualenv/virtualenv-1.11.6.tar.gz#md5=f61cdd983d2c4e6aeabb70b1060d6f49^C tar zxvf virtualenv-1.11.6.tar.gz ^Cbash-4.2# cd virtualenv-1.11.6^C python virtualenv.py $HOME^C which pip # should be $HOME/bin/pip pip install matplotlib **Also Note:** Do not cusotmize `PYTHONPATH` in any way. [virtualenv](https://pypi.python.org/pypi/virtualenv) takes care of all the nitty gritty. ALso you may find [virtualenvwrapper](https://pypi.python.org/pypi/virtualenvwrapper) a useful add-on.
web scraping - how to download image into a folder python Question: I have this code where i would like to download the image and save it into a folder but i am getting the src of the image.I have gone through stack overflow where i found this [Batch downloading text and images from URL with Python / urllib / beautifulsoup?](http://stackoverflow.com/questions/7918239/batch-downloading- text-and-images-from-url-with-python-urllib-beautifulsoup) but have no idea how to proceed Here is my code,so far i have tried elm5=soup.find('div', id="dv-dp-left-content") img=elm5.find("img") src = img["src"] print src How can i download these images using url into a folder Answer: import urllib f = open('local_file_name','wb') f.write(urllib.urlopen(src).read()) f.close() `src` have to be full path - for example`http://hostname.com/folder1/folder2/filename.ext`. If `src` is `/folder1/folder2/filename.ext` you have to add `http://hostname.com/`. If `src` is `folder2/filename.ext` you have to add `http://hostname.com/folder1/`. etc. * * * **EDIT:** example how to download StackOverflow logo :) import urllib f = open('stackoverflow.png','wb') f.write(urllib.urlopen('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=3c6263c3453b').read()) f.close()
Kivy Label.text Property doesn't update on the UI Question: I have an issue with the updated text property of a label not displaying correctly on my UI. I check the text property and can verify that it is being set to the new value but that value isn't being shown when the label is rendered. The Label is on a different Screen which I am switching to using a ScreenManager. The Sub Widgets and tree of the screen are constructed in separate .kv files (I have used the load_string() Builder method in the example but the outcome is the same) Here is a simplified example of what is going on: from kivy.config import Config Config.set('graphics', 'width', '300') Config.set('graphics', 'height', '200') Config.set('graphics', 'resizable', '0') from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder Builder.load_string(""" <screen1>: Button: id: button text: 'Press me to Update Screen2' on_press: root.update_screen2() <screen2>: Label: id: mainLabel text: 'I have not been updated' """) class screen1(Screen): def __init__(self, **kwargs): """ Set super and store the id of the button """ super(screen1, self).__init__(**kwargs) self.button = self.ids.button.__self__ return def update_screen2(self): """ send text 1 and text 2 to the screen2 object for it to set on it's label """ text1 = 'Hi There' text2 = 'Does this work' screen2.update_label(screen2(),text1, text2) return class screen2(Screen): def __init__(self, **kwargs): """ set super ond store the id of the label """ super(screen2, self).__init__(**kwargs) self.mainLabel = self.ids.mainLabel.__self__ return def update_label(self, text1, text2): """ using text1 and text2, update the text property of the label the output of each print() shows the text property is being updated it just doesn't display on the UI """ print(self.mainLabel.text) self.mainLabel.text = text1 + '\n\n' + text2 print(self.mainLabel.text) screenManager.current = 'screen2' return screenManager = ScreenManager() class MainApp(App): def build(self): #root widget is abox layout self.root = BoxLayout() #instantiate the screen objects self.screen1 = screen1(name='screen1') self.screen2 = screen2(name='screen2') #add the screens to the screenManager screenManager.add_widget(self.screen1) screenManager.add_widget(self.screen2) #set the current screen screenManager.current = 'screen1' #add the screenManager to the root widget and return it self.root.add_widget(screenManager) return self.root if __name__ == '__main__': MainApp().run() I have tried various things such as changing how i reference the label widget in python, asking the canvas to update or creating a 'screen2()' object to call the method from in the screen1 but to no avail. What is it that I'm missing? Answer: screen2.update_label(screen2(),text1, text2) This line doesn't do what you think - actually, it makes multiple mistakes, are you familiar with how python classes work? First, when you call a method, you generally want to do it with an instance of the class, e.g. a = [1, 2, 3] a.append(10) This will append 10 to this _instance_ of the list. What you've done is not call the update_label method of a class instance, but directly called it with the class definition and a new instance `screen2()`. Since this didn't crash for you I think it would probably work if you passed in the instance you want to change, but it's not normal and there's no reason to do things this way. The problem is that you changed the text of the new screen2 instance you passed in, but this is a completely different object to the one you're actually displaying in your app, so you see no change. You instead need to call the update_label method of the screen2 instance your app actually uses. For instance, something like the following should work: screen2_instance = self.parent.get_screen('screen2') screen2_instance.update_label(text1, text2) The first line uses the get_screen method of the screenmanager to retrieve the _existing_ screen with the name 'screen2'. The second line calls its update label method with your new text. Note that you do _not_ pass in the screen instance argument (called `self`) - an instance method automatically receives this first argument. You should also capitalise your class names, both because it's a python convention (this is obviously not compulsory but there's a lot to be said for following the general community style guidelines), and because kv language uses this capitalisation to identify widgets so you might hit problems later if you don't do it.
Return array, ctypes Question: I am a really newbie using ctypes. I am loading a windows dll file, and trying to read the array `GetDfuFileInfo` returns. I actually ended up on loading the file in ctypes because I dont know how to pass a `dfu_file*` pointer to the `GetDfuFileInfo` function. Is this even possible? C++ functions example usage: dfu_file* TheFile = ReadDfuFile(const char*); dfu_file_info* Info = GetDfuFileInfo(dfu_file*); Python code: lib = ctypes.WinDLL('dfulib.dll') func = lib.ReadDfuFile func.restype = ctypes.c_void_p func.argtypes = [ctypes.c_char_p] func("file.dvu") * * * **edit** Also tried this: lib = ctypes.WinDLL('dfulib.dll') func = lib.ReadDfuFile func.restype = ctypes.c_void_p func.argtypes = [ctypes.c_char_p] FileInfo = lib.GetDfuFileInfo FileInfo.argtypes = [ctypes.c_void_p] FileInfo.restype = None s = func(r'file.dvu') s = ctypes.cast(s, ctypes.c_char_p) print FileInfo(s.value) Produces the exception: `WindowsError: exception: access violation reading 0x00000016` Any kind of help will be appreciated. Answer: Sample code looks, This code invokes [GetFileAttributesA](http://msdn.microsoft.com/en- us/library/windows/desktop/aa364944%28v=vs.85%29.aspx) function from kernel32.dll >>> from ctypes import * >>> windll.LoadLibrary("kernel32.dll") <WinDLL 'kernel32.dll', handle 77260000 at 2241ad0> >>> windll.kernel32 <WinDLL 'kernel32', handle 77260000 at 225c2f0> >>> windll.kernel32.GetFileAttributesA("c:/test/1.txt") 32 You can refer to <https://docs.python.org/2/library/ctypes.html> for details
read numbers from a file specified on the command line and print the sum of the numbers Question: Write a program that inputs a list of numbers from a file and prints their sum. The file name comes in as a command-line argument. Assuming the file "orange" contains the numbers: 6 26 10 8 Your program should behave as follows: python3 a4.py orange 50 My current code: from scanner import * def main(): s = Scanner("orange") print(sum(float(x) for x in sys.argv[1:])) s.close() main() For my code to do that I will need to implement a scanner correct? However, when I run the updated code with the scanner, it returns a `cannot convert string to float: orange`. Sorry if this is a dumb question, but Im taking my first programming class and I'm trying to get ahead. Answer: You don't need a scanner, you can just get the filename from `sys.argv` and read the file like this: import sys with open(sys.argv[1], 'r') as f: print(sum(float(x) for x in f.read().split())) output for your sample file: >> python3 a4.py orange 50.0 If it's guaranteed that there are only integers in your file you can use `int(x)`.
sqlalchemy BC dates with postgresql Question: I am working on postgresql database through sqlalchemy. I need to work with BC dates with postgresql "date" column type (it supports BC dates <http://www.postgresql.org/docs/9.2/static/datatype-datetime.html>). But while I can insert BC dates in form of string (for example '2000-01-01 BC'), I can't retrieve them. Trying to get BC dates from database raises Value error: year is out of range. At first I thought the reason was that sqlalchemy in its type Date uses python datetime.date module, which does not support BC dates, but I'm not entirely sure. I was trying to find a way to map "date" type in database to custom python class (to bypass usage of datetime.date module) but I wasn't successful yet (I found ways to add logic to various processing steps in sqlalchemy, like result_processor or bind_expression with column_expression, but I didn't manage to make it work). Here is example to reproduce problem. from sqlalchemy import create_engine, Column, Integer, String, Date from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('postgresql://database:database@localhost:5432/sqlalchemy_test', echo=True) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) date = Column(Date) def __repr__(self): return "<User(name='%s', date='%s')>" % (self.name, self.date) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() # remove objects from previous launches session.query(User).delete() import datetime a_date = datetime.date.today() # Insert valid date in datetime.date format, it works. ed_user = User(name='ed', date=a_date) # Insert BC date in string format, it works. al_user = User(name='al', date='1950-12-16 BC') session.add_all([ed_user, al_user]) session.commit() # Insert data via raw sql, it works conn = engine.connect() conn.execute('INSERT INTO users (name, date) VALUES (%s, %s)', ("Lu", "0090-04-25 BC")) # Check that all 3 objects are present user_names = session.query(User.name).all() print user_names # Check entry with AD date, it works. user = session.query(User).filter_by(name='ed').first() print '-- user vith valid date: ', user, user.date # But when trying to fetch date fields in any way, it raises Value error # Trying to fetch model, it raises Value error users = session.query(User).all() print users # Trying to fetch only field, it raises Value error user_dates = session.query(User.date).all() print user_dates # Even trying to fetch dates in raw sql raises Value error a = conn.execute('SELECT * FROM users') print [c for c in a] And output with trace: 2014-06-19 16:06:20,466 INFO sqlalchemy.engine.base.Engine select version() 2014-06-19 16:06:20,466 INFO sqlalchemy.engine.base.Engine {} 2014-06-19 16:06:20,468 INFO sqlalchemy.engine.base.Engine select current_schema() 2014-06-19 16:06:20,468 INFO sqlalchemy.engine.base.Engine {} 2014-06-19 16:06:20,470 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1 2014-06-19 16:06:20,470 INFO sqlalchemy.engine.base.Engine {} 2014-06-19 16:06:20,471 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1 2014-06-19 16:06:20,471 INFO sqlalchemy.engine.base.Engine {} 2014-06-19 16:06:20,473 INFO sqlalchemy.engine.base.Engine show standard_conforming_strings 2014-06-19 16:06:20,473 INFO sqlalchemy.engine.base.Engine {} 2014-06-19 16:06:20,475 INFO sqlalchemy.engine.base.Engine select relname from pg_class c join pg_namespace n on n.oid=c.relnamespace where n.nspname=current_schema() and relname=%(name)s 2014-06-19 16:06:20,475 INFO sqlalchemy.engine.base.Engine {'name': u'users'} 2014-06-19 16:06:20,477 INFO sqlalchemy.engine.base.Engine BEGIN (implicit) 2014-06-19 16:06:20,478 INFO sqlalchemy.engine.base.Engine DELETE FROM users 2014-06-19 16:06:20,478 INFO sqlalchemy.engine.base.Engine {} 2014-06-19 16:06:20,480 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, date) VALUES (%(name)s, %(date)s) RETURNING users.id 2014-06-19 16:06:20,481 INFO sqlalchemy.engine.base.Engine {'date': datetime.date(2014, 6, 19), 'name': 'ed'} 2014-06-19 16:06:20,482 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, date) VALUES (%(name)s, %(date)s) RETURNING users.id 2014-06-19 16:06:20,482 INFO sqlalchemy.engine.base.Engine {'date': '1950-12-16 BC', 'name': 'al'} 2014-06-19 16:06:20,483 INFO sqlalchemy.engine.base.Engine COMMIT 2014-06-19 16:06:20,494 INFO sqlalchemy.engine.base.Engine INSERT INTO users (name, date) VALUES (%s, %s) 2014-06-19 16:06:20,494 INFO sqlalchemy.engine.base.Engine ('Lu', '0090-04-25 BC') 2014-06-19 16:06:20,495 INFO sqlalchemy.engine.base.Engine COMMIT 2014-06-19 16:06:20,517 INFO sqlalchemy.engine.base.Engine BEGIN (implicit) 2014-06-19 16:06:20,517 INFO sqlalchemy.engine.base.Engine SELECT users.name AS users_name FROM users 2014-06-19 16:06:20,517 INFO sqlalchemy.engine.base.Engine {} -- user names: [(u'ed',), (u'al',), (u'Lu',)] 2014-06-19 16:06:20,520 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.date AS users_date FROM users WHERE users.name = %(name_1)s LIMIT %(param_1)s 2014-06-19 16:06:20,520 INFO sqlalchemy.engine.base.Engine {'name_1': 'ed', 'param_1': 1} -- user with valid date: <User(name='ed', date='2014-06-19')> 2014-06-19 2014-06-19 16:06:20,523 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name, users.date AS users_date FROM users 2014-06-19 16:06:20,523 INFO sqlalchemy.engine.base.Engine {} Traceback (most recent call last): File "test_script.py", line 49, in <module> users = session.query(User).all() File "/home/pavel/.virtualenvs/common/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2292, in all return list(self) File "/home/pavel/.virtualenvs/common/local/lib/python2.7/site-packages/sqlalchemy/orm/loading.py", line 65, in instances fetch = cursor.fetchall() File "/home/pavel/.virtualenvs/common/local/lib/python2.7/site-packages/sqlalchemy/engine/result.py", line 788, in fetchall self.cursor, self.context) File "/home/pavel/.virtualenvs/common/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1111, in _handle_dbapi_exception util.reraise(*exc_info) File "/home/pavel/.virtualenvs/common/local/lib/python2.7/site-packages/sqlalchemy/engine/result.py", line 782, in fetchall l = self.process_rows(self._fetchall_impl()) File "/home/pavel/.virtualenvs/common/local/lib/python2.7/site-packages/sqlalchemy/engine/result.py", line 749, in _fetchall_impl return self.cursor.fetchall() ValueError: year is out of range I'm using postgresql 9.1.11, sqlalchemy 0.9.4, python 2.7 My question is: is there a way to work with BC dates in postgresql "date" type column through sqlalchemy (at least retrieve it as string, but perspectively map it to some module that can work with BC dates, like FlexiDate or astropy.time)? Answer: I was digging this problem and I found out that this Value error exception is thrown not by sqlalchemy, but by database driver (psycopg2 in this case). Here, if performed with the database, created from above, this code will raise same Value error exception. import psycopg2 conn = psycopg2.connect("dbname=sqlalchemy_test user=database password=database host=localhost port=5432") cursor = conn.cursor() cursor.execute("SELECT * FROM users") cursor.fetchall() Output: Traceback (most recent call last): File "test_script.py", line 5, in <module> values = cursor.fetchall() ValueError: year is out of range Looks like it tries to create datetime.date object from value retrieved from database and fails. I tried also pg8000 dialect, it doesn't raise Value error, but it eats BC parts, returning datetime.date object with year, month and day (I mean from database row with value '1990-11-25 BC' it returns datetime.date(1990, 11, 25), which is 1990-11-25 actually). Here example: import pg8000 conn = pg8000.connect(user='postgres', host='localhost', port=5432, database='sqlalchemy_test', password='postgres') cursor = conn.cursor() cursor.execute('SELECT * FROM users') values = cursor.fetchall() print values print [str(val[2]) for val in values] Output: ([1, u'ed', datetime.date(2014, 6, 19)], [2, u'al', datetime.date(1950, 12, 16)], [3, u'Lu', datetime.date(90, 4, 25)]) ['2014-06-19', '1950-12-16', '0090-04-25'] Also I wanted to try py-postgresql dialect, but it's only for python 3+, which in not an option (production uses python 2.7.6 for this project). So, answer for my question is: "No, it is not possible in sqlalchemy.", because type convertion between database literal and python object happens in database driver, not in sqlalchemy part. **UPDATE** : While this is indeed impossible to do in sqlalchemy, it is possible to define your own type cast in psycopg2 (and override default behavior), and make date type from database return watever you want. Here is an example: # Cast PostgreSQL date into string # http://initd.org/psycopg/docs/advanced.html#type-casting-from-sql-to-python import psycopg2 BcDate = None # This function dafines types cast, and as returned database literal is already a string, no # additional logic required. def cast_bc_date(value, cursor): return value def register_bc_date(connection): global BcDate if not BcDate: cursor = connection.cursor() cursor.execute('SELECT NULL::date') psql_date_oid = cursor.description[0][1] BcDate = psycopg2.extensions.new_type((psql_date_oid,), 'DATE', cast_bc_date) psycopg2.extensions.register_type(BcDate) conn = psycopg2.connect(database='sqlalchemy_test', user='database', password='database', host='localhost', port=5432) register_bc_date(conn) With this an example from question works like a charm. And open a ways for additional data processing in sqlalchemy.
Python, paramiko, invoke_shell and ugly characters Question: When I run the Python code below: import workflow import console import paramiko import time strComputer = 'server.com' strUser = 'user' strPwd = 'passwd' client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname=strComputer, username=strUser, password=strPwd) channel = client.invoke_shell() channel.send('ls\n') time.sleep(3) output=channel.recv(2024) print(output) #Close the connection client.close() print('Connection closed.') I get the desired output mixed with ugly characters: Last login: Thu Jun 19 23:37:55 2014 from 192.168.0.10 ls user@server:~$ ls [0m[01;34mbin[0m Rplots1.pdf [01;32mbtsync[0m Rplots.pdf btsync.conf~ [01;31mrstudio-server-0.95.265-amd64.deb[0m [01;31mbtsync_glibc23_x64.tar[0m screen.vba [01;34mbudget[0m [01;34mshiny[0m [01;3 Connection closed. Can anyone explain me what is going on, and how to get a pretty output instead? Thanks Answer: those are terminal color codes used by `ls` to highlight directories, executable files etc. you can call `/bin/ls` (or, on some distributions, `ls --color=never`) explicitly to avoid calling aliases etc. and get un-colored output. the colors are defined using those cryptic codes like `[0m[01;34m`. here's how the terminal looks like when `ls` coloring is enabled: ![enter image description here](http://i.stack.imgur.com/79YI2.png)
Counting like elements in a list and appending list Question: I am trying to create a `list` in `Python` with values pulled from an active `excel` sheet. I want it to pull the step # value from the excel file and append it to the list while also including which number of that element it is. For example, `1_1` the first time it pulls 1, `1_2` the second time, `1_3` the third, etc. My code is as follows... import win32com.client xl = win32com.client.Dispatch("Excel.Application") CellNum = xl.ActiveSheet.UsedRange.Rows.Count Steps = [] for i in range(2,CellNum + 1): #Create load and step arrays in abaqus after importing from excel if str(int(xl.Cells(i,1).value))+('_1' or '_2' or '_3' or '_4' or '_5' or '_6') in Steps: StepCount = 1 for x in Steps: if x == str(int(xl.Cells(i,1).value))+('_1' or '_2' or '_3' or '_4' or '_5' or '_6'): StepCount+=1 Steps.append(str(int(xl.Cells(i,1).value))+'_'+str(StepCount)) else: Steps.append(str(int(xl.Cells(i,1).value))+'_1') I understand that without the excel file, the program will not run for any of you, but I was just wondering if it is some simple error that I am missing. When I run this, the StepCount does not go higher than 2 so I receive a bunch of 1_2, 2_2, 3_2, etc elements. I've posted my resulting list below. >>> Steps ['1_1', '2_1', '3_1', '4_1', '5_1', '6_1', '7_1', '8_1', '9_1', '10_1', '11_1', '12_1', '13_1', '14_1', '1_2', '14_2', '13_2', '12_2', '11_2', '10_2', '2_2', '3_2', '9_2', '8_2', '7_2', '6_2', '5_2', '4_2', '3_2', '2_2', '1_2', '2_2', '3_2', '4_2', '5_2', '6_2', '7_2', '8_2', '9_2', '10_2', '11_2', '12_2', '13_2', '14_2', '1_2', '2_2'] **EDIT #1:** So, if the `('_1' or '_2' or '_3' or '_4' or '_5' or '_6')` will ALWAYS only use _1, is it this line of code that is messing with my counter? if x == str(int(xl.Cells(i,1).value))+('_1' or '_2' or '_3' or '_4' or '_5' or '_6'): Since it is only using `_1`, it will only count `1_1` and not check `1_2, 1_3, 1_4, etc` **EDIT #2:** Now I am using the following code. My input list is also below. from collections import defaultdict StepsList = [] Steps = [] tracker = defaultdict(int) for i in range(2,CellNum + 1): StepsList.append(int(xl.Cells(i,1).value)) >>> StepsList [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1, 14, 13, 12, 11, 10, 2, 3, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1, 2] for cell in StepsList: Steps.append('{}_{}'.format(cell, tracker[cell]+1)) # This is +1 because the tracker starts at 0 tracker[cell]+=1 I get the following error: `ValueError: zero length field name in format` from the `for cell in StepsList:` iteration block **EDIT #3:** Got it working. For some reason it didn't like Steps.append('{}_{}'.format(cell, tracker[cell]+1)) So I just changed it to for cell in StepsList: tracker[cell]+=1 Steps.append(str(cell)+'_'+str(tracker[cell])) Thanks for all of your help! Answer: This line: if str(int(xl.Cells(i,1).value))+('_1' or '_2' or '_3' or '_4' or '_5' or '_6') in Steps: does not do what you think it does. `('_1' or '_2' or '_3' or '_4' or '_5' or '_6')` will _always_ return `'_1'`. It does not iterate over that series of `or` values looking for a match. Without seeing expected input vs. expected output, it's hard to point you in the correct direction to actually get what you want out of your code, but likely you'll want to leverage [`itertools.product`](https://docs.python.org/2/library/itertools.html#itertools.product) or one of the other combinatoric methods from `itertools`. **Update** Based on your comments, I think that this is a way of solving your problem. Assuming an input list of the following: in_list = [1, 1, 1, 2, 3, 3, 4] You can do the following: from collections import defaultdict tracker = defaultdict(int) # defaultdict is just a regular dict with a default value at new keys (in this case 0) steps = [] for cell in in_list: steps.append('{}_{}'.format(cell, tracker[cell]+1)) # This is +1 because the tracker starts at 0 tracker[cell]+=1 Result: >>> steps ['1_1', '1_2', '1_3', '2_1', '3_1', '3_2', '4_1'] There are likely more efficient ways to do this using combinations of `itertools`, but this way is certainly the most straight-forward
Django 1.6 : MySQL ERROR 1049 (42000): Unknown database Question: According to the django tutorial on its official website, django creates database schema according to the model defined in the `models.py`. But the default engine for database is `sqlite3`. And it is working. now when I installed the `mysql` and `Mysql Connector` for django and I tried to create a database I encountered with the following error: mysql.connector.errors.ProgrammingError: 1049 (42000): Unknown database 'db.mysql.userdb' I searched the error and found some solutions to this problem but all of them mentioned that I have to create the database myself using `MYSQL Shell`. But this is not what I want! According to the django website, I have to just define my model and django creates the schema of database! _How can I do that?_ Thanks in advance. The following is my `sttings.py` file: # -*- coding: utf-8 -*- from __future__ import unicode_literals import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SECRET_KEY = '94sf3cp(#a^)9!^zrr^zr3dfdk0nz$*4=m#v19*v)j&q^o$#ym' DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website_user', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'Final_DBMI.urls' WSGI_APPLICATION = 'Final_DBMI.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': 'db.mysql.userdb', 'USER': 'hadi', 'PASSWORD': '123456', 'HOST': '127.0.0.1', 'PORT': '3306' } } LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/statics/' **Update** I'm using this [doc](https://docs.djangoproject.com/en/dev/ref/databases/) and according to that there is two ways to connect to mysql: * MYSQLdb * MySQL Connector/Python and I'm using the second one. According to the [MYSQL website](http://dev.mysql.com/doc/connector-python/en/connector-python-django- backend.html) it should be added to `settings.py` in the following way: DATABASES = { 'default': { 'NAME': 'user_data', 'ENGINE': 'mysql.connector.django', 'USER': 'mysql_user', 'PASSWORD': 'priv4te', 'OPTIONS': { 'autocommit': True, }, } } Answer: Django creates the _tables_. It does not create the _database_ that the tables live in; you must do that.
Reading csv file to python ValueError: could not convert string to float Question: Any help with this would be appreciated. Please keep in mind that I am a beginner in Python. This is the portion of the code that I am having trouble with: __author__ = 'peter' from datetime import datetime, timedelta import csv TICKER='CHTR' STDEV_FILE = TICKER + '_stdev.csv' TRADES_FILE = TICKER + '_trades.csv' DATETIME_CSV_FORMAT = '%Y%m%d %H:%M:%S' def read_data(csv_filename): result = {} with open(csv_filename, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='|') header = reader.next() #print 'HEADER',header for row in reader: new_data=None if len(row)==6: # this is a QUOTES file ticker, date, time, price, rtn, standard = row rtn = float(rtn) standard = float(standard) new_data = [rtn, standard] else: # assume this is a TRADES file otherwise ticker, date, time, price, size = row price = float(price) size = int(size) new_data = [price, size] date_object = datetime.strptime(date +' '+time, DATETIME_CSV_FORMAT) if not ticker in result: result[ticker]=[] result[ticker].append([date_object] + new_data) return result vol = read_data(STDEV_FILE) trades = read_data(TRADES_FILE ) When I run it this is the error I recieve: Traceback (most recent call last): File "/home/peter/PycharmProjects/Vol/Vol.py", line 39, in <module> vol = read_data(STDEV_FILE) File "/home/peter/PycharmProjects/Vol/Vol.py", line 25, in read_data standard = float(standard) ValueError: could not convert string to float: #DIV/0! I have run this on other csv files and had no trouble. Here is a small sample of the csv file: SYMBOL DATE TIME PRICE RTN STDEV ----------------------------------------------------------------------- CHTR 20130718 9:30:00 124.66 0 0 ----------------------------------------------------------------------- CHTR 20130718 9:30:00 124.66 0 0.0005674559 ----------------------------------------------------------------------- CHTR 20130718 9:30:00 124.56 -0.0008025039 0.0004539101 ----------------------------------------------------------------------- CHTR 20130718 9:30:00 124.54 -0.0001605781 0.0001135459 ----------------------------------------------------------------------- CHTR 20130718 9:30:00 124.54 0 0.0070177722 ----------------------------------------------------------------------- CHTR 20130718 9:31:56 123.310 -0.0099246286 0.011065531 ----------------------------------------------------------------------- CHTR 20130718 9:34:05 124.018 0.0057243955 0.0040363557 ----------------------------------------------------------------------- Ultimately I would like to plot the standard deviation on y axis and seconds from midnight on x axis. Any help would be appreciated. Answer: The issue is that you are trying to convert the string "#DIV/0' to a float. Obviously this is not possible. The cause of this is attempting to divide by zero somewhere in your excel/csv sheet. Look back through your excel sheet and see if anything is divided by zero and change it. Alternately you could implement a simple if statement: if standard == '#DIV/0': print 'Error' else: standard = float(standard) EDIT: Some references: <http://office.microsoft.com/en-us/excel-help/correct- a-div-0-error-HP010066245.aspx>
Python 3D array. Calculate R squared Question: I have 2 ndarrays with 3 dimensions. I need to calculate the Rsquared over these ndarrays. To clarify. Array1.shape = Array2.shape = (100, 100, 10) So... resultArray = np.ones(100*100).reshape(100,100) for i in range(Array1.shape[0]: for j in range(Array1.shape[1]: slope, intercept, r_value, p_value, std_err = scipy.stats.stats.linregress(Array1[i:i+1,j:j+1,:],Array1[i:i+1,j:j+1,:]) R2 = r_value**2 result[ i , j ] = R2 Answer: If passed two arrays, `stats.linregress` expects the two arrays to be 1-dimensional. `Array1[i:i+1,j:j+1,:]` has shape `(1, 1, 10)`, so it is 3-dimensional. So instead use `Array1[i, j, :]`: import numpy as np import scipy.stats as stats Array1 = np.random.random((100, 100, 10)) Array2 = np.random.random((100, 100, 10)) resultArray = np.ones(100*100).reshape(100,100) for i in range(Array1.shape[0]): for j in range(Array1.shape[1]): slope, intercept, r_value, p_value, std_err = stats.linregress( Array1[i, j, :], Array1[i, j, :]) R2 = r_value**2 resultArray[ i , j ] = R2 print(resultArray)
Scrapy first tutorial dmoz returning en error "TypeError: Can't use implementer with classes. Use one of the class-declaration functions instead." Question: Getting an error when running the first tutorial for scrapy. Scrapy : 0.22.2 lxml : 3.3.5.0 libxml2 : 2.7.8 Twisted : 12.0.0 Python : 2.7.2 (default, Oct 11 2012, 20:14:37) - [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] Platform: Darwin-12.5.0-x86_64-i386-64bit This is my file items.py: from scrapy.item import Item, Field class DmozItem(Item) title=Field() link=Field() desc=Field() My file for dmoz_spider.py: from scrapy.spider import BaseSpider class DmozSpider(BaseSpider): name = "dmoz" allowed_domains= ["dmoz.org"] start_urls = [ "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/", "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/" ] def parse(self, response): filename = response.url.split("/")[-2] open(filename, 'wb').write(response.body) This is the error message when running "scrapy crawl dmoz" > foolios-imac-2:tutorial foolio$ scrapy crawl dmoz > /usr/local/share/tutorial/tutorial/spiders/dmoz_spider.py:3: > ScrapyDeprecationWarning: tutorial.spiders.dmoz_spider.DmozSpider inherits > from deprecated class scrapy.spider.BaseSpider, please inherit from > scrapy.spider.Spider. (warning only on first subclass, there may be others) > class DmozSpider(BaseSpider): > > 2014-06-19 14:53:00-0500 [scrapy] INFO: Scrapy 0.22.2 started (bot: > tutorial) > 2014-06-19 14:53:00-0500 [scrapy] INFO: Optional features available: ssl, > http11 > 2014-06-19 14:53:00-0500 [scrapy] INFO: Overridden settings: > {'NEWSPIDER_MODULE':'tutorial.spiders', 'SPIDER_MODULES': > ['tutorial.spiders'], 'BOT_NAME': 'tutorial'} 2014-06-19 14:53:00-0500 > [scrapy] INFO: Enabled extensions: LogStats, TelnetConsole,CloseSpider, > WebService, CoreStats, SpiderState > Traceback (most recent call last): > > File "/usr/local/bin/scrapy", line 5, in > pkg_resources.run_script('Scrapy==0.22.2', 'scrapy') > File > "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", > line 489, in run_script self.require(requires)[0].run_script(script_name, > ns) > File > "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", > line 1207, in run_script execfile(script_filename, namespace, namespace) > File "/Library/Python/2.7/site-packages/Scrapy-0.22.2-py2.7.egg/EGG- > INFO/scripts/scrapy", line 4, in execute() > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/cmdline.py", line 143, in execute > _run_print_help(parser, _run_command, cmd, args, opts) > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/cmdline.py", line 89, in > _run_print_help func(*a, **kw) > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/cmdline.py", line 150, in > _run_command cmd.run(args, opts) > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/commands/crawl.py", line 50, in run > self.crawler_process.start() > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/crawler.py", line 92, in start if > self.start_crawling(): > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/crawler.py", line 124, in > start_crawling return self._start_crawler() is not None > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/crawler.py", line 139, in > _start_crawler crawler.configure() > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/crawler.py", line 47, in configure > self.engine = ExecutionEngine(self, self._spider_closed) > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/core/engine.py", line 63, in > **init** self.downloader = Downloader(crawler) > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/core/downloader/**init**.py", line > 73, in **init** self.handlers = DownloadHandlers(crawler) > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/core/downloader/handlers/**init**.py", > line 18, in **init** cls = load_object(clspath) > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/utils/misc.py", line 40, in > load_object mod = import_module(module) > File > "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/**init**.py", > line 37, in import_module **import**(name) > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/core/downloader/handlers/s3.py", > line 4, in from .http import HTTPDownloadHandler > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/core/downloader/handlers/http.py", > line 5, in from .http11 import HTTP11DownloadHandler as HTTPDownloadHandler > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/core/downloader/handlers/http11.py", > line 15, in from scrapy.xlib.tx import Agent, ProxyAgent, ResponseDone, \ > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/xlib/tx/**init**.py", line 6, in > from . import client, endpoints > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/xlib/tx/client.py", line 37, in from > .endpoints import TCP4ClientEndpoint, SSL4ClientEndpoint > File "/Library/Python/2.7/site- > packages/Scrapy-0.22.2-py2.7.egg/scrapy/xlib/tx/endpoints.py", line 222, in > interfaces.IProcessTransport, '_process')): > File > "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/zope/interface/declarations.py", > line 495, in **call** raise TypeError("Can't use implementer with classes. > Use one of " > TypeError: Can't use implementer with classes. Use one of the class- > declaration functions instead. Answer: Try updating zope and then run your code `sudo pip install --upgrade zope.interface` or `sudo easy_install --upgrade zope.interface`