text
stringlengths
226
34.5k
Selenium (Python): How to insert value on a hidden input? Question: I'm using Selenium's WebDriver and coding in Python. There's a hidden input field in which I'm trying to insert a specific date value. The field originally produces a calendar, from which a user can select an appropriate date, but that seems like a more complicated endeavour to emulate than inserting the appropriate date value directly. The page's source code looks like this: <div class="dijitReset dijitInputField"> <input id="form_date_DateTextBox_0" class="dijitReset" type="text" autocomplete="off" dojoattachpoint="textbox,focusNode" tabindex="0" aria-required="true"/> <input type="hidden" value="2013-11-26" sliceindex="0"/> where `value="2013-11-26"` is the field I'm trying to inject a value (it's originally empty, ie: `value=""`. I understand that WebDriver is not able to insert a value into a hidden input, because regular users would not be able to do that in a browser, but a workaround is to use Javascript. Unfortunately that's a language I'm not familiar with. Would anyone know what would work? Answer: You can use [`WebDriver.execute_script`](https://selenium- python.readthedocs.org/en/latest/api.html?highlight=execute_script#selenium.webdriver.remote.webdriver.WebDriver.execute_script). For example: from selenium import webdriver driver = webdriver.Firefox() driver.get('http://jsfiddle.net/falsetru/mLGnB/show/') elem = driver.find_element_by_css_selector('div.dijitReset>input[type=hidden]') driver.execute_script(''' var elem = arguments[0]; var value = arguments[1]; elem.value = value; ''', elem, '2013-11-26') * * * **UPDATE** from selenium import webdriver driver = webdriver.Firefox() driver.get('http://matrix.itasoftware.com/') elem = driver.find_element_by_xpath( './/input[@id="ita_form_date_DateTextBox_0"]' '/following-sibling::input[@type="hidden"]') value = driver.execute_script('return arguments[0].value;', elem) print("Before update, hidden input value = {}".format(value)) driver.execute_script(''' var elem = arguments[0]; var value = arguments[1]; elem.value = value; ''', elem, '2013-11-26') value = driver.execute_script('return arguments[0].value;', elem) print("After update, hidden input value = {}".format(value))
Retrieving comments using python libclang Question: In the following header file I'd like to get the corresponding `+reflect` comment to the class and member variable: #ifndef __HEADER_FOO #define __HEADER_FOO //+reflect class Foo { public: private: int m_int; //+reflect }; #endif Using the python bindings for libclang and the following script: import sys import clang.cindex def dumpnode(node, indent): print ' ' * indent, node.kind, node.spelling for i in node.get_children(): dumpnode(i, indent+2) def main(): index = clang.cindex.Index.create() tu = index.parse(sys.argv[1], args=['-x', 'c++']) dumpnode(tu.cursor, 0) if __name__ == '__main__': main() Gives me this output: CursorKind.TRANSLATION_UNIT None CursorKind.TYPEDEF_DECL __builtin_va_list CursorKind.CLASS_DECL type_info CursorKind.CLASS_DECL Foo CursorKind.CXX_ACCESS_SPEC_DECL CursorKind.CXX_ACCESS_SPEC_DECL CursorKind.FIELD_DECL m_int The problem is that the comments are missing. Are they stripped by the preprocessor? Is there any way to prevent that? Answer: You need to modify the cindex.py script and expose the following function. class Cursor(Structure): def getRawComment(self): return conf.lib.clang_Cursor_getRawCommentText(self) also add this to the correct spot in cindex.py ("clang_Cursor_getRawCommentText", [Cursor], _CXString, _CXString.from_result), I had to make my comments using /*! * +reflect */ though
What does the `as` command do in Python 3.x? Question: I've seen it many times but never understood what the `as` command does in Python 3.x. Can you explain it in plain English? Answer: It's not a command per se, it's a keyword used as part of the [`with` statement](http://docs.python.org/2/reference/compound_stmts.html#the-with- statement): with open("myfile.txt") as f: text = f.read() The object after `as` gets assigned the result of the expression handled by the `with` context manager. Another use is to rename an imported module: import numpy as np so you can use the name `np` instead of `numpy` from now on. The third use is to give you access to an `Exception` object: try: f = open("foo") except IOError as exc: # Now you can access the Exception for more detailed analysis
How to pull info from a string and output it? Question: I have to create a game where the computer picks a random word and the player has to guess that word. The computer tells the player how many letters are in the word. Then the player gets five chances to ask if a letter is in the word. The computer can only respond with `"yes"` or `"no"`. Then, the player must guess the word. I only have: import random WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone", "truck" , "doom" , "mayonase" ,"flying" ,"magic" ,"mine" ,"bugle") word = random.choice(WORDS) print(len(word)) correct = word guess = input("\nYour guess: ") if guess != correct and guess != "" : print("No.") if guess == correct: print("Yes!\n") I have no idea how to do this problem. Answer: I assume you want to let the user ask the computer if a letter is in the word, 5 times. If so, here is the code: for i in range(5): #Let the player ask 5 times letter = input("What letter do you want to ask about? ")[0] #take only the 1st letter if they try to cheat if letter in correct: print("yes, letter is in word\n") else: print("no, letter is not in word") The key is the `in` operator within the `for` loop.
Can literals in Python be overridden? Question: Couldn't find a way to phrase the title better, feel free to correct. I'm pretty new to Python, currently experimenting with the language.. I've noticed that all built-ins types cannot be extended with other members.. I'd like for example to add an `each` method to the `list` type, but that would be impossible. I realize that it's designed that way for efficiency reasons, and that most of the built-ins types are implemented in C. Well, one why I found to override this behavior is be defining a new class, which extends `list` but otherwise does nothing. Then I can assign the variable `list` to that new class, and each time I would like to instantiate a new list, I'd use the `list` constructor, like it would have been used to create the original `list` type. class MyList(list): def each(self, func): for item in self: func(item) list = MyList my_list = list((1,2,3,4)) my_list.each(lambda x: print(x)) Output: 1 2 3 4 The idea can be generalize of course by defining a method that gets a built it type and returns a class that extends that type. Further more, the original `list` variable can be saved in another variable to keep an access to it. Only problem I'm facing right now, is that when you instantiate a `list` by its literal form, (i.e. `[1,2,3,4]`), it will still use the original list constructor (or does it?). Is there a way to override this behavior? If the answer is no, do you know of some other way of enabling the user to extend the built-ins types? (just like javascript allows extending built-ins prototypes). I find this limitation of built-ins (being unable to add members to them) one of Python's drawbacks, making it inconsistent with other user-defined types... Overall I really love the language, and I really don't understand why this limitation is REALLY necessary. Answer: This is a conscientious choice from Python. Firstly, with regards to patching inbuilt type, this is primarily a design _decision_ and only secondarily an optimization. I have learnt from much lurking on the Python Mailing List that monkey patching on builtin types, although enjoyable for small scripts, serves no good purpose in anything larger. Libraries, for one, make certain assumptions about types. If it were encouraged to extend default types, many libraries would end up fighting each other. It would also discourage _making_ new types – a deque is a deque, an ordered set is an ordered set, a dictionary is a dictionary and that should be that. Literal syntax is a particularly important point. If you cannot guarantee that `[1, 2, 3]` is a list, what can you guarantee? If people could change those behaviours it would have such global impacts as to destroy the stability of a lot of code. There is a reason _goto_ and global variables are discouraged. * * * There is one particular hack that I _am_ fond of, though. When you see `r"hello"`, this seems to be an extended literal form. So why not `r[1, 2, 3]`? class ListPrefixer: def __init__(self, typ): self.typ = typ def __getitem__(self, args): return self.typ(args) class MyList(list): def each(self, func): return MyList(func(x) for x in self) e = ListPrefixer(MyList) e[1, 2, 3, 4].each(lambda x: x**2) #>>> [1, 4, 9, 16] * * * Finally, if you really want to do deep AST hacks, check out [MacroPy](https://github.com/lihaoyi/macropy).
Finding the mode and frequency of items in a Python list Question: How would you find the mode and frequency of items in a Python list? This is what I have so for: elif user_option == 7: for score in scores_list: count = scores_list.count(score) print ("mode(s), occuring" + str(count) + ":") print(score) What I need to do is print out the scores that appear the most if the user inputs a set of scores where 2 appear at the same amount of time and I also have to display the actual score. But this is what I get when I test it: Select an option above:7 mode(s), occuring2: 45.0 mode(s), occuring2: 45.0 mode(s), occuring1: 67.0 Answer: if you are trying to count frequency of an item of a list try this: from collections import Counter data = Counter(your_list_in_here) data.most_common() # Returns all unique items and their counts data.most_common(1) # Returns the highest occurring item
How to load data in Python for which data is stored as a customized class Question: I have a question with loading data in Python. Basically, I defined all Classes I need in a file called "utility.py". and I have one data file "result.data" which stores results in form of a specific class called "Solution" which is defined in "utility.py". What I want to do is to load "result.data" in another py. file (ex:new.py). From what I know, cPickle module is the one that can be used. So in new.py, I wrote "from utility import *", and "Sol=cPickle.load(open('Result.data'))". This works fine when I worked among windows based system. However, when I tried to load the result.data I generated in windows system to new.py file in linux or mac system, The error "ImportError: No module named utility" always occurs. I'm a not a professional programmer, and I just start to code in python. Could you please give some guide on how to solve this problem? Thank you in advance. Answer: Check `sys.path`. Does it contain the location where utility.py is kept? Does it have current directory ( an empty string )? That could be the issue.
Can pip (or setuptools, distribute etc...) list the license used by each installed package? Question: I'm trying to audit a Python project with a large number of dependencies and while I can manually look up each project's homepage/license terms, it seems like most OSS packages should already contain the license name and version in their metadata. Unfortunately I can't find any options in pip or easy_install to list more than the package name and installed version (via pip freeze). Does anyone have pointers to a tool to list license metadata for Python packages? Answer: You can use `pkg_resources`: import pkg_resources def get_pkg_license(pkgname): """ Given a package reference (as from requirements.txt), return license listed in package metadata. NOTE: This function does no error checking and is for demonstration purposes only. """ pkgs = pkg_resources.require(pkgname) pkg = pkgs[0] for line in pkg.get_metadata_lines('PKG-INFO'): (k, v) = line.split(': ', 1) if k == "License": return v return None Example use: >>> get_pkg_license('mercurial') 'GNU GPLv2+' >>> get_pkg_license('pytz') 'MIT' >>> get_pkg_license('django') 'UNKNOWN'
Error: [only length-1 arrays can be converted to Python scalars] when changing variable order Question: Dear Stackoverflow Community, I am very new to Python and to programming in general, so please don't get mad when I don't get your answers and ask again. I am trying to fit a curve to experimental data with scipy.optimization.curve_fit. This is my code: %matplotlib inline import matplotlib.pyplot as plt import numpy as nm from __future__ import division import cantera as ct from matplotlib.backends.backend_pdf import PdfPages import math as ma import scipy.optimize as so R = 8.314 T = nm.array([700, 900, 1100, 1300, 1400, 1500, 1600, 1700]) k = nm.array([289, 25695, 763059, 6358040, 14623536, 30098925, 56605969, 98832907]) def func(A, E, T): return A*ma.exp(-E/(R*T)) popt, pcov = so.curve_fit(func, T, k) Now this code works for me, but if I change the function to: def func(T, A, E) and keep the rest I get: TypeError: only length-1 arrays can be converted to Python scalars Also I am not really convinced by the Parameter solution of the first one. Can anyone tell me what happens when you change the variable order? Answer: I wonder whether you data shows an exponential decay of rate. The mathematical model may not be the most suitable one. ![enter image description here](http://i.stack.imgur.com/gSt4y.png)See the doc string of `curve_fit` > f : callable The model function, f(x, ...). It must take the independent > variable as the first argument and the parameters to fit as separate > remaining arguments. since your formula is essentially: `k=A*ma.exp(-E/(R*T))`, the right order of parameters in `func` should be `(T, A, E)` or `(T, E, A)`. Regarding the order of `A` and `E`, they don't really matter. If you flip them, the result will get flipped as well: >>> def func(T, A, E): return A*ma.exp(-E/(R*T)) >>> so.curve_fit(func, T, k) (array([ 8.21449078e+00, -5.86499656e+04]), array([[ 6.07720215e+09, 4.31864058e+12], [ 4.31864058e+12, 3.07102992e+15]])) >>> def func(T, E, A): return A*ma.exp(-E/(R*T)) >>> so.curve_fit(func, T, k) (array([ -5.86499656e+04, 8.21449078e+00]), array([[ 3.07102992e+15, 4.31864058e+12], [ 4.31864058e+12, 6.07720215e+09]])) I didn't get your `typeerror` at all.
What does [^.]* mean in regular expression? Question: I'm trying to get 482.75 from the following text: `<span id="yfs_l84_aapl">482.75</span>` The regex I used is: `regex = '<span id="yfs_l84_[^.]*">(.+?)</span>'` and it worked. But the thing that I do not understand is why [^.]* can match aapl here? My understanding is that . means any character except a newline; and ^ means negator. So [^.] should be newline and [^.]* should be any number of new lines. However this theory is contrary to real world implementation. Any help is appreciated and thanks in advance. * * * The python code I used: import urllib import re htmlfile = urllib.urlopen("http://finance.yahoo.com/q?s=AAPL&ql=0") htmltext = htmlfile.read() regex = '<span id="yfs_l84_[^.]*">(.+?)</span>' pattern = re.compile(regex) price = re.findall(pattern, htmltext) print "the price of of aapl is", price[0] Answer: Within the `[]` the `.` means just a dot. And the leading `^` means "anything but ...". So `[^.]*` matches zero or more non-dots.
Call oracle stored procedure with cursor output parameter from python script Question: I am trying to call a oracle stored procedure with 2 in and 1 out parameter from python script. The problem I am having is passing a cursor out-parameter. The Oracle stored procedure is essentially: PROCEDURE ci_lac_state (LAC_ID_IN IN VARCHAR2, CI_ID_IN IN VARCHAR2 DEFAULT NULL, CGI_ID OUT SYS_REFCURSOR) AS BEGIN OPEN cgi_id FOR ... END; The python code calling to the database is: #! /usr/bin/python import cx_Oracle lac='11508' ci='9312' try: my_connection=cx_Oracle.Connection('login/passwd@db_name') except cx_Oracle.DatabaseError,info: print "Logon Error:",info sys.exit() my_cursor=my_connection.cursor() cur_var=my_cursor.var(cx_Oracle.CURSOR) my_cursor.callproc("cgi_info.ci_lac_state", [lac, ci, cur_var]) print cur_var.getvalue() And I get such cursor value as the result: <__builtin__.OracleCursor on <cx_Oracle.Connection to login@db_name>> What am I doing wrong? Thanks. Answer: I've just had similar issue. `cur_var` has type `<type 'cx_Oracle.CURSOR'>` and `cur_var.getvalue()` gets object of type `<type 'OracleCursor'>`. To get data you have to fetched them from the OracleCursor object. Try for example: print cur_var.getvalue().fetchall() To see more function of OracleCursor object just check its directory: dir(cur_var.getvalue()) Hope this will help you!
Launching a cmd window with commands using python script? Question: How do I launch a cmd window and input the commands i specify into the cmd for windows using a python script? For example , the script will launch the cmd and input the following : runas /username:Admin control Then cmd will then prompt the user for their passwords and open the control panel. Any idea? Thanks Answer: import subprocess subprocess.call(['runas', '/username:Admin', 'control']) Don't have a python shell here to test, but this should get you pretty close to what you want. It should run the `runas` command which will prompt you for the password, then launch the control panel. This could easily be done with a batch program too, or even just a shortcut. Just putting that out there. * * * ### controlpanel.bat This one is most comparable to your python script, but it skips having to load the pyton interpreter. runas /username:Admin control * * * ### shortcut This one lets you have a little more control over the command, and who is running it. *right click desktop *new *shortcut *Enter "runas /username:Admin control" for the Location. *Type a name for the shortcut. * * * ### alternative shortcut This one is useful if you just want UAC to handle it. * same as above, but for location type just "control" * then right click on the new shortcut, and click properties. * click the shortcut tab * click "advanced" * check the "run as administrator" box. * * * ### Bonus alternative This gives you a master list of all settings you can change, rather than just the control panel. * Create a new folder, and rename it to: Settings.{ED7BA470-8E54-465E-825C-99712043E01C} * You can change the "Settings" part to anything you want * follow the instructions above for "alternative shortcut"
Prevent CSS/other resource download in PhantomJS/Selenium driven by Python Question: I'm trying to speed up Selenium/PhantomJS webscraper in Python by preventing download of CSS/other resources. All I need to download is img src and alt tags. I've found this code: page.onResourceRequested = function(requestData, request) { if ((/http:\/\/.+?\.css/gi).test(requestData['url']) || requestData['Content-Type'] == 'text/css') { console.log('The url of the request is matching. Aborting: ' + requestData['url']); request.abort(); } }; via: [how can I control phantomjs to skip download some kind of resource](http://stackoverflow.com/questions/9486377/how-can-i-control- phantomjs-to-skip-download-some-kind-of-resource) _How/where can I implement this code in Selenium driven by Python? Or, is there another better way to stop CSS/other resources from downloading?_ Note: I've already found how to prevent image download by editing service_args variable via: [How do I set a proxy for phantomjs/ghostdriver in python webdriver?](http://stackoverflow.com/questions/14699718/how-do-i-set-a-proxy- for-phantomjs-ghostdriver-in-python-webdriver?lq=1) and [PhantomJS 1.8 with Selenium on python. How to block images?](http://stackoverflow.com/questions/15371495/phantomjs-1-8-with- selenium-on-python-how-to-block-images?lq=1) But service_args can't help me with resources like CSS. Thanks! Answer: A bold young soul by the name of “watsonmw” [recently added](https://github.com/detro/ghostdriver/commit/d9b65ed014ed9ff8a5e852cc40e59a0fd66d0cf1) functionality to Ghostdriver (which Phantom.js uses to interface with Selenium) that allows access to [Phantom.js API calls which require a page object](http://phantomjs.org/api/webpage/), like the `onResourceRequested` one you cited. For a solution at all costs, consider building from source (which developers note “takes roughly 30 minutes ... with 4 parallel compile jobs on a modern machine”) and integrating his patch, linked above. Then this (untested) Python code should work as a proof of concept: from selenium import webdriver driver = webdriver.PhantomJS('phantomjs') # hack while the python interface lags driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute') driver.execute('executePhantomScript', {'script': ''' page.onResourceRequested = function(requestData, request) { // ... } ''', 'args': []}) Until then, you’ll just get a `Can't find variable: page` exception. Good luck! There are a lot of great alternatives, like working in a Javascript environment, driving Gecko, proxies, etc.
Python Decorator Self-firing Question: I am fairly new to Python and have been learning about decorators. After messing around with Flask, I am trying to write some code that simulates their route handler/decorators, just to understand how decorators (with arguments) work. In the code below, the route decorator seems to call itself once the script runs. My question is, how is it possible that `app.route()` gets called when i run this script, and what is really happening here? Notice i don't call my `index()` function anywhere directly. # test.py class Flask(object): def __init__(self, name): self.scriptname = name def route(self, *rargs, **kargs): args = list(rargs) if kargs: print(kargs['methods']) def decorator(f): f(args[0]) return decorator app = Flask(__name__) @app.route("/", methods = ["GET","PUT"]) def index(rt): print('route: ' + rt) the above prints this in my terminal: $ python test.py ['GET', 'PUT'] route: / Any insight would be appreciated. Answer: `@app.route("/", methods = ["GET","PUT"])` is an executable statement: it calls the `route()` method of the app object. Since it's at module level, it will be executed when the script is imported. Now, the _result_ of calling `app.route(...)` is a function, and because you've used the `@` to mark it as a decorator, that function will wrap `index`. Note that the syntax is just a shortcut for this: index = app.route(...)(index) in other words, Python will call the function returned by `app.route()` with `index` as a parameter, and store the result as the new `index` function. However, you're missing a level here. A normal decorator, without params, is written like this: @foo def bar() pass and when the module is imported, `foo()` is run and returns a function that wraps `bar`. But you're calling your `route()` function _within_ the decorator call! So actually your function needs to _return a decorator function_ that itself returns a function that wraps the original function... headscratching, to be sure. Your `route` method should look more like this: def route(self, *rargs, **kargs): args = list(rargs) if kargs: print(kargs['methods']) def decorator(f): def wrapped(index_args): f(args[0]) return wrapped return decorator
Import statement: Config file Python Question: I'm maintaining a dictionary and that is loaded inside the config file. The dictionary is loaded from a JSON file. **In config.py** name_dict = json.load(open(dict_file)) I'm importing this config file in several other scripts(file1.py, file2.py,...,filen.py) using import config statement. My question is when will the config.py script be executed ? I'm sure it wont be executed for every import call that is made inside my multiple scripts. But, what exactly happens when an import statement is called. Answer: The top-level code in a module is executed once, the first time you `import` it. After that, the module object will be found in `sys.modules`, and the code will not be re-executed to re-generate it. There are a few exceptions to this: * `reload`, obviously. * Accidentally importing the same module under two different names (e.g., if the module is in a package, and you've got some directory in the middle of the package in `sys.path`, you could end up with `mypackage.mymodule` and `mymodule` being two copies of the same thing, in which case the code gets run twice). * Installing import hooks/custom imported that replace the standard behavior. * Explicitly monkeying with `sys.modules`. * Directly calling functions out of `imp`/`importlib` or the like. * Certain cases with `multiprocessing` (and modules that use it indirectly, like `concurrent.futures`). * * * For Python 3.1 and later, this is all described in detail under [The import system](http://docs.python.org/3/reference/import.html). In particular, look at the Searching section. (The `multiprocessing`-specific cases are described for that module.) For earlier versions of Python, you pretty much have to infer the behavior from a variety of different sources and either reading the code or experimenting. However, the well-documented new behavior is intended to work like the old behavior except in specifically described ways, so you can usually get away with reading the 3.x docs even for 2.x. * * * Note that _in general_ , you don't want to rely on whether top-level code in the module is run once or multiple times. For example, given a top-level function definition, as long as you never compare function objects, or rebind any globals that it (meaning the definition itself, not just the body) depends on, it doesn't make any difference. However, there are some exceptions to that, and loading start-time config files is a perfect example of an exception.
Python Fabric Git Pull Merge Message Question: I've got **Python Fabric** running nicely, however **I have one problem**. When doing `$ fab deploy` I always get a **Merge popup** Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch. I don't understand why it always does this. If I do the exact same command in SSH to pull my git repo it works without a merge issue. I will say I'm on Windows 8 and pulling to linux if that matters. The Line endings shouldnt be an issue, it never has. This is the **fabfile.py** from fabric.api import * from fabric.colors import * env.user = 'username' env.host_string = '99.99.0.99' def deploy(branch = 'master'): path = '/var/www/mysite/htdocs' with cd(path): run("git pull origin {0}".format(branch)) def commit(branch = 'master'): local('git add -u') local('git add .') message = prompt("commit msg: ") local('git commit -m "{0}"'.format(message)) local('git push origin {0}'.format(branch)) Answer: It is asking you to do merges because the pulls are not fast-forward merges. Check that your branches are not farckled and you don't have rouge commits on the deployment side.
Not able to import getpass in python Question: I have a requirement to input username and password from the console. For the password I am using password = getpass.getpass('Enter password') I have used `import getpass` But getting ImportError : no module named getpass Also tried setting the pythonpath using export pythonpath=/usr/lib/python2.4/site-packages:/usr/lib/python2.4 Code: #!/usr/bin/python2.4 import sys import getpass WL_USER = raw_input('Enter the username to login to BI EM:') WL_PASSWD = getpass.getpass('Enter the password:') HOST_NAME = raw_input('Enter the BI host URL') WL_PORT = raw_input('Enter the admin port for BI') error: ImportError: no module named getpass One important thing is that I am trying to run the script as a wlst script i.e. trying to edit the attribute of an Mbean. So the execution goes like this: /home/wlserver_10.3/common/bin/wlst.sh test.py I tried to execute the script as python test.py It executes fine. So it looks like there is some issue with wlst. Need assistance on this. Answer: The argument `getpass.getpass()` was added in python 2.5. Check the old manual, <http://docs.python.org/release/2.4/lib/module-getpass.html>
TypeError: 'Undefined' object is not iterable? Question: The following is the mako template I have created <%inherit file="/openerp/controllers/templates/base_dispatch.mako"/> <%def name="header()"> <title>${_("Otp")}</title> <script type="text/javascript">alert("OTP PAGE");</script> </%def> <%def name="content()"> <table width="100%"> <tr><%include file="header.mako"/></tr> </table> </br> <table class="view" cellpadding="0" cellspacing="0" style="padding-top: 10px; border:none;" align="center"> <tr> <td style="padding:35px 10px 5px 35px; width="450" align="center"> <form action="${py.url(target)}" method="post" name="otpform" id="otpform" style="padding-bottom: 5px; min-width: 100px;"> % for key, value in origArgs.items(): <input type="hidden" name="${key}" value="${value}"/> % endfor <input name="otp_action" value="otp" type="hidden"/> <fieldset class="box" style="width:300px"> <legend style="padding: 4px;"> <img src="/openerp/static/images/stock/stock_person.png" alt=""/> </legend> <div class="box2" style="padding: 5px 5px 20px 5px"> <b>Please enter SMS code</b> <table width="" cellspacing="2px" cellpadding="0" style="border:none;"> <tr> <td class="label"><label for="otp">${_("Otp:")}</label></td> <td style="padding: 3px;"><input type="text" id="otp" name="otp" class="db_user_pass" value="${otp}" autofocus="true"/></td> </tr> <tr> <td></td> <td class="db_login_buttons"> <button type="submit" class="static_boxes">${_("Otp")}</button> </td> </tr> </table> </div> </fieldset> </form> </td> </tr> </table> <%include file="footer.mako"/> </%def> And the python file for the template is import re from openobject.controllers import BaseController import cherrypy from openerp.utils import rpc from mako.lookup import TemplateLookup from mako.template import Template from openobject import tools import openobject from openobject.tools import expose, url, redirect, validate, error_handler import formencode import base64 import time class OTP(BaseController): _cp_path = "/openerp/otp" msg = { } def __init__(self, *args, **kwargs): super(OTP, self).__init__(*args, **kwargs) self._msg = {} @expose() def index(self, *args, **kw): print '>>>>>>>>>>>>>>>>>>>>>>>INDEX<<<<<<<<<<<<<<<<<<<<<<<<<<' self.msg = {} target='/' url='socket://localhost:8070' action='otp' info='' info = None message='' origArgs=self.get_orig_args(kw) self.otp_check(target, action, message, origArgs) @expose(template="/openerp/controllers/templates/otp.mako") def otp_check(self, target, action=None, message=None, origArgs={}): print '>>>>>>>>>>>>>>>>>>>>>>>otp_check<<<<<<<<<<<<<<<<<<<<<<<<<<' target='/' url='socket://localhost:8070' action='otp' info='' info = None return dict(target=target, url=url, action=action, message=message, origArgs=origArgs, info=info) def get_orig_args(self,kw): if not kw.get('otp_action'): return kw new_kw = kw.copy() clear_login_fields(new_kw) return new_kw # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: But on running it I am getting the following error in browser. 500 Internal Server Error The server encountered an unexpected condition which prevented it from fulfilling the request. Traceback (most recent call last): File "/usr/lib/pymodules/python2.6/cherrypy/_cprequest.py", line 606, in respond cherrypy.response.body = self.handler() File "/usr/lib/pymodules/python2.6/cherrypy/_cpdispatch.py", line 25, in __call__ return self.callable(*self.args, **self.kwargs) File "/home/zbeanz/workspace/Sms_authentication/openerp-web-6.0.4/openobject/tools/_expose.py", line 182, in func_wrapper res = func(*args, **kw) File "/home/zbeanz/workspace/Sms_authentication/openerp-web-6.0.4/openobject/controllers/_root.py", line 90, in default return request.handler() File "/usr/lib/pymodules/python2.6/cherrypy/_cpdispatch.py", line 25, in __call__ return self.callable(*self.args, **self.kwargs) File "/home/zbeanz/workspace/Sms_authentication/openerp-web-6.0.4/openobject/tools/_expose.py", line 182, in func_wrapper res = func(*args, **kw) File "/home/zbeanz/workspace/Sms_authentication/openerp-web-6.0.4/addons/openerp/controllers/otp.py", line 83, in index self.otp_check(target, action, message, origArgs) File "/home/zbeanz/workspace/Sms_authentication/openerp-web-6.0.4/openobject/tools/_expose.py", line 222, in func_wrapper return render_template(_template, res).encode("utf-8") File "/home/zbeanz/workspace/Sms_authentication/openerp-web-6.0.4/openobject/tools/_expose.py", line 141, in render_template return utils.NoEscape(template.render_unicode(**kw)) File "/usr/lib/pymodules/python2.6/mako/template.py", line 138, in render_unicode return runtime._render(self, self.callable_, args, data, as_unicode=True) File "/usr/lib/pymodules/python2.6/mako/runtime.py", line 364, in _render _render_context(template, callable_, context, *args, **_kwargs_for_callable(callable_, data)) File "/usr/lib/pymodules/python2.6/mako/runtime.py", line 381, in _render_context _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) File "/usr/lib/pymodules/python2.6/mako/runtime.py", line 414, in _exec_template callable_(context, *args, **kwargs) File "_openobject_controllers_templates_base_mako", line 61, in render_body File "/usr/lib/pymodules/python2.6/mako/runtime.py", line 255, in <lambda> return lambda *args, **kwargs:callable_(self.context, *args, **kwargs) File "_openerp_controllers_templates_otp_mako", line 89, in render_content TypeError: 'Undefined' object is not iterable What is causing this error ? Answer: The error description is very clear. 'Undefined' object is not iterable i.e you have a list object and try to iterate in your mako file. But in runtime the object is not assigned with value. so the object is undefined. In your case you iterate only one variable % for key, value in origArgs.items(): <input type="hidden" name="${key}" value="${value}"/> % endfor check if variable **origArgs** has got values while running. It's good to handle this kind of exceptions like below %if origArgs: % for key, value in origArgs.items(): <input type="hidden" name="${key}" value="${value}"/> % endfor %endif If that's not the one causing error, then check for the iterables in file "/openerp/controllers/templates/base_dispatch.mako". You must be able to get it. If still no luck, leave a comment below. Cheers!!
Trying to run KIVY, for the first time Question: I'm trying to run kivy for the first time. Im using a default program. from kivy.app import App from kivy.uix.widget import Widget class PongGame(Widget): pass class PongApp(App): def build(self): return PongGame() if __name__ == '__main__': PongApp().run() I get this error: ################################## done bootstraping kivy...have fun!\n running "python.exe C:\Python27\hello.py" \n Traceback (most recent call last): File "C:\Python27\hello.py", line 1, in <module> from kivy.app import App ImportError: No module named kivy.app Press any key to continue . . . A lot of people have raised the issue online, but no one has mentioned the right solution. Answer: **UPDATE** : based on the error you're getting—which you just pasted now, after my original response below—, you seem to be missing not only PyGame but Kivy itself. Go ahead and run `pip install kivy`. But before you do that, I'd recommend you take a look at [virtualenv](http://www.virtualenv.org/en/latest/) and install all your Python packages specific to this project in a virtualenv created for that project. If you don't want that, you have to run `sudo pip install kivy` to install Kivy globally (assuming you're on OS X or Linux). On Windows, `sudo` should not be needed. (Also, I'm sure the information below will be useful as well—since you don't even have Kivy, it must mean that you would have run into problems for not having PyGame either once would have installed Kivy.) **ORIGINAL ANSWER:** **Short version:** You're missing PyGame, which is a dependency of Kivy. **Long version:** Since you didn't tell us what the error was, I went ahead and ran your code on my OS X 10.8 machine and got this: $ python main.py [INFO ] Kivy v1.7.2 ... [CRITICAL] [Window ] Unable to find any valuable Window provider at all! [CRITICAL] [App ] Unable to get a Window, abort. googling that error landed me on <http://kivy.org/docs/installation/troubleshooting-macosx.html>. So I went ahead and installed PyGame with the help of <http://juliaelman.com/blog/2013/04/02/installing-pygame-on-osx-mountain- lion/>; except I installed it in a virtualenv: $ pip install hg+http://bitbucket.org/pygame/pygame after that: $ python yourcode.py [INFO ] Kivy v1.7.2 Purge log fired. Analysing... Purge finished ! [INFO ] [Logger ] Record log in /Users/erik.allik/.kivy/logs/kivy_13-10-01_2.txt [INFO ] [Factory ] 144 symbols loaded [DEBUG ] [Cache ] register <kv.lang> with limit=None, timeout=Nones [DEBUG ] [Cache ] register <kv.image> with limit=None, timeout=60s ... [INFO ] [OSC ] using <multiprocessing> for socket [DEBUG ] [Base ] Create provider from mouse [INFO ] [Base ] Start application main loop And I get a nice Kivy window popping up!
Create name value pairs in python Question: I have a python script that has the following output stored in a variable called jvmData: Stats name=jvmRuntimeModule, type=jvmRuntimeModule# { name=HeapSize, ID=1, description=The total memory (in KBytes) in the Java virtual machine run time., unit=KILOBYTE, type=BoundedRangeStatistic, lowWaterMark=1048576, highWaterMark=1048576, current=1048576, integral=0.0, lowerBound=1048576, upperBound=2097152 name=FreeMemory, ID=2, description=The free memory (in KBytes) in the Java virtual machine run time., unit=KILOBYTE, type=CountStatistic, count=348466 name=UsedMemory, ID=3, description=The amount of used memory (in KBytes) in the Java virtual machine run time., unit=KILOBYTE, type=CountStatistic, count=700109 name=UpTime, ID=4, description=The amount of time (in seconds) that the Java virtual machine has been running., unit=SECOND, type=CountStatistic, count=3706565 name=ProcessCpuUsage, ID=5, description=The CPU Usage (in percent) of the Java virtual machine., unit=N/A, type=CountStatistic, count=0 } What I would like to do is simply print out name/value pairs for the important parts, which in this case would simply be: HeapSize=1048576 FreeMemory=348466 UsedMemory=700109 UpTime=3706565 ProcessCpuUsage=0 Im not at all good with python :) The only solution in my head seems very long-winded? Split the lines, throw away first, second and last lines, then loop through each line with different cases (sometimes current, sometimes count) for finding the length of string, etc etc Perhaps (well definitely) I am missing something some nice function I can use to put these into the equivalent of a java hashmap or something? Answer: The "equivalent of a java HashMap" would be called a dictionary in python. As for how to parse this, just iterate over the lines that contain the data, make a dict of all key/value pairs in the line and have a special case for the `HeapSize`: jvmData = "..." #the string holding the data jvmLines = jvmData.split("\n") #a list of the lines in the string lines = [l.strip() for l in jvmLines if "name=" in l] #filter all data lines result = {} for line in lines: data = dict(s.split("=") for s in line.split(", ")) #the value is in "current" for HeapSize or in "count" otherwise value = data["current"] if data["name"] == "HeapSize" else data["count"] result[data["name"]] = value As you seem to be stuck on Jython2.1, here's a version that should work with it (obviously untested). Basically the same as above, but with the list comprehension and generator expression replaced by `filter` and `map` respectively, and without using the ternary `if/else` operator: jvmData = "..." #the string holding the data jvmLines = jvmData.split("\n") #a list of the lines in the string lines = filter(lambda x: "name=" in x, jvmLines) #filter all data lines result = {} for line in lines: data = dict(map(lambda x: x.split("="), line.split(", "))) if data["name"] == "HeapSize": result[data["name"]] = data["current"] else: result[data["name"]] = data["count"]
Python dealing with months and years in arrays Question: newbie question, I have three arrays, one with years, one with months and one with my data. The years array has which year the data occurs in, but as the data is collected monthly, I have a lot of repeat years, eg `[1996,1997,...,1997,1998,...,1998,1999 etc]` Then in the array I have `[01,02,...,11,12,01,02, etc]` Is there anyway to amalgamate these two arrays into one, and then plot them vs my data? I have tried multiplying the second array by `1/12` and adding it to the first array, but would prefer a more elegant solution. Any tips? Thank you. Answer: You could use `zip` to combine the years and months into `datetime.date` objects: dates = [DT.date(y,m,1) for y, m in zip(years, months)] To plot using [matplotlib](http://matplotlib.org/): import matplotlib.pyplot as plt import datetime as DT import numpy as np years = [1996]+[1997]*12+[1998]*12 months =[12]+range(1,13)+range(1,13) dates = [DT.date(y,m,1) for y, m in zip(years, months)] values = np.random.random(len(dates)) plt.plot(dates, values) plt.show() ![enter image description here](http://i.stack.imgur.com/1GpVE.png)
Python-Twitter script works at home and not at University. Deadline REALLY soon Question: I've written quite a simple python script that pulls in tweets and turns on a GPIO if a filter is matched. I've tried it at home and it works really well, however, on the University network it seems not to be able to connect to twitter. The details of the University network are WIRELESS SSID: Uni-WiFi WPA2 Enterprise It uses PEAP (MSCHAPv2) to connect, meaning that I need to type in my university username and password. The network is connected at present and I can browse the internet, but when I launch the python script I get the error: urllib2.HTTPError: HTTP Error 401: Unauthorized Here is the full python script - If any body could help it would be amazing, this needs handing in really soon! #!/usr/bin/env python import twitter import RPi.GPIO as GPIO ## Import GPIO library import time ## Import 'time' library. Allows us to use 'sleep' from termcolor import colored GPIO.setmode(GPIO.BOARD) ## Use board pin numbering GPIO.cleanup() #My app keys and secrets CONSUMER_KEY = 'TXXGPRg' CONSUMER_SECRET = 'jRVxtEgf1CQWuan0N8L4a3s' OAUTH_TOKEN = '528854Jaudhna2K36g4y79oiwUq' OAUTH_SECRET = 'ZoQEv1deAQ' FILTER_TAG = u'art' # Can also be just text, like u'idol', but expect a lot more results! # We want a continuous stream of events which match a given tag, so we need to use the streaming API. twitter_stream = twitter.TwitterStream(auth=twitter.OAuth(OAUTH_TOKEN,OAUTH_SECRET,CONSUMER_KEY,CONSUMER_SECRET)) # Now, we don't want every single tweet from the stream, so we'll filter to include only specific text, or a specific tag. iterator = twitter_stream.statuses.filter(track = FILTER_TAG) # Now, iterator is a generator which yields a new tweet whenever it sees one. We need to loop over it forever. for tweet in iterator: print colored(tweet.get(u'user', {}).get(u'name'), 'white', 'on_red'), colored(tweet.get(u'text'), 'cyan') if "hate" in tweet.get(u'text', u'fake_text_that_never_matches'): # Now, you need to light up the light for 5 seconds, then shut it off. print colored("Switch turned ON!", "red", 'on_yellow') GPIO.setup(7, GPIO.OUT) GPIO.output(7,True)## Switch on pin 7 time.sleep(5)## Wait GPIO.output(7,False)## Switch off pin 7 print "----------------------------------------------------------------------------------------------------------------------------------------------------" Answer: Part of the OAuth signature is a timestamp, which is generated when you make the request. If your server's time differs too much from Twitter's server time, the Twitter server will reject your request with a 401. So, check the time being returned by the Twitter server and make sure your local machine that is generating the signature matches the same time.
Fast peak-finding and centroiding in python Question: I am trying to develop a fast algorithm in python for finding peaks in an image and then finding the centroid of those peaks. I have written the following code using the scipy.ndimage.label and ndimage.find_objects for locating the objects. This seems to be the bottleneck in the code, and it takes about 7 ms to locate 20 objects in a 500x500 image. I would like to scale this up to larger (2000x2000) image, but then the time increases to almost 100 ms. So, I'm wondering if there is a faster option. Here is the code that I have so far, which works, but is slow. First I simulate my data using some gaussian peaks. This part is slow, but in practice I will be using real data, so I don't care too much about speeding that part up. I would like to be able to find the peaks very quickly. import time import numpy as np import matplotlib.pyplot as plt import scipy.ndimage import matplotlib.patches plt.figure(figsize=(10,10)) ax1 = plt.subplot(221) ax2 = plt.subplot(222) ax3 = plt.subplot(223) ax4 = plt.subplot(224) size = 500 #width and height of image in pixels peak_height = 100 # define the height of the peaks num_peaks = 20 noise_level = 50 threshold = 60 np.random.seed(3) #set up a simple, blank image (Z) x = np.linspace(0,size,size) y = np.linspace(0,size,size) X,Y = np.meshgrid(x,y) Z = X*0 #now add some peaks def gaussian(X,Y,xo,yo,amp=100,sigmax=4,sigmay=4): return amp*np.exp(-(X-xo)**2/(2*sigmax**2) - (Y-yo)**2/(2*sigmay**2)) for xo,yo in size*np.random.rand(num_peaks,2): widthx = 5 + np.random.randn(1) widthy = 5 + np.random.randn(1) Z += gaussian(X,Y,xo,yo,amp=peak_height,sigmax=widthx,sigmay=widthy) #of course, add some noise: Z = Z + scipy.ndimage.gaussian_filter(0.5*noise_level*np.random.rand(size,size),sigma=5) Z = Z + scipy.ndimage.gaussian_filter(0.5*noise_level*np.random.rand(size,size),sigma=1) t = time.time() #Start timing the peak-finding algorithm #Set everything below the threshold to zero: Z_thresh = np.copy(Z) Z_thresh[Z_thresh<threshold] = 0 print 'Time after thresholding: %.5f seconds'%(time.time()-t) #now find the objects labeled_image, number_of_objects = scipy.ndimage.label(Z_thresh) print 'Time after labeling: %.5f seconds'%(time.time()-t) peak_slices = scipy.ndimage.find_objects(labeled_image) print 'Time after finding objects: %.5f seconds'%(time.time()-t) def centroid(data): h,w = np.shape(data) x = np.arange(0,w) y = np.arange(0,h) X,Y = np.meshgrid(x,y) cx = np.sum(X*data)/np.sum(data) cy = np.sum(Y*data)/np.sum(data) return cx,cy centroids = [] for peak_slice in peak_slices: dy,dx = peak_slice x,y = dx.start, dy.start cx,cy = centroid(Z_thresh[peak_slice]) centroids.append((x+cx,y+cy)) print 'Total time: %.5f seconds\n'%(time.time()-t) ########################################### #Now make the plots: for ax in (ax1,ax2,ax3,ax4): ax.clear() ax1.set_title('Original image') ax1.imshow(Z,origin='lower') ax2.set_title('Thresholded image') ax2.imshow(Z_thresh,origin='lower') ax3.set_title('Labeled image') ax3.imshow(labeled_image,origin='lower') #display the color-coded regions for peak_slice in peak_slices: #Draw some rectangles around the objects dy,dx = peak_slice xy = (dx.start, dy.start) width = (dx.stop - dx.start + 1) height = (dy.stop - dy.start + 1) rect = matplotlib.patches.Rectangle(xy,width,height,fc='none',ec='red') ax3.add_patch(rect,) ax4.set_title('Centroids on original image') ax4.imshow(Z,origin='lower') for x,y in centroids: ax4.plot(x,y,'kx',ms=10) ax4.set_xlim(0,size) ax4.set_ylim(0,size) plt.tight_layout plt.show() The results for size=500: ![enter image description here](http://i.stack.imgur.com/CNONo.png) EDIT: If the number of peaks is large (~100) and the size of the image is small, then the bottleneck is actually the centroiding part. So, perhaps the speed of this part also needs to be optimized. Answer: Your method for finding the peaks (simple thresholding) is of course very sensitive to the choice of threshold: set it too low and you'll "detect" things that are not peaks; set it too high and you'll miss valid peaks. There are more robust alternatives, that will detect all the local maxima in the image intensity regardless of their intensity value. My preferred one is applying a dilation with a small (5x5 or 7x7) structuring element, then find the pixels where the original image and its dilated version have the same value. This works because, by definition, dilation(x, y, E, img) = { max of img within E centered at pixel (x,y) }, and therefore dilation(x, y, E, img) = img(x, y) whenever (x,y) is the location of a local maximum at the scale of E. With a fast implementation of the morphological operators (e.g. the one in OpenCV) this algorithm is linear in the size of the image in both space and time (one extra image-sized buffer for the dilated image, and one pass on both). In a pinch, it can also be implemented on-line without the extra buffer and a little extra complexity, and it's still linear time. To further robustify it in the presence of salt-and-pepper or similar noise, which may introduce many false maxima, you can apply the method twice, with structuring elements of different size (say, 5x5 and 7x7), then retain only the stable maxima, where stability can be defined by unchanging position of the maxima, or by position not changing by more than one pixel, etc. Additionally, you may want to suppress low nearby maxima when you have reason to believe they are due to noise. An efficient way to do this is to first detect all the local maxima as above, sort them descending by height, then go down the sorted list and keep them if their value in the image has not changed and, if they are kept, set to zero all the pixels in a (2d+1) x (2d+1) neighborhood of them, where d is the min distance between nearby maxima that you are willing to tolerate.
easy_install virtualenvwrapper error in CentOS 5.8 64bit Question: Installed Python 2.6.1 (with /opt prefix), setuptools 0.6c9, and virtualenv onto CentOS 5.8 64bit.(I was mostly following the instructions from here: <http://bda.ath.cx/blog/2009/04/08/installing-python-26-in-centos-5-or- rhel5/comment-page-1/#comment-15422>) I got stuck when I tried to install virtualenwrapper and got the following errors: /opt/bin/easy_install virtualenvwrapper Searching for virtualenvwrapper Reading http://pypi.python.org/simple/virtualenvwrapper/ Best match: virtualenvwrapper 4.1.1 Downloading https://pypi.python.org/packages/source/v/virtualenvwrapper/virtualenvwrapper-4.1.1.tar.gz#md5=f18f2c612b936583a8ec0f7114b6637e Processing virtualenvwrapper-4.1.1.tar.gz Running virtualenvwrapper-4.1.1/setup.py -q bdist_egg –dist-dir /tmp/easy_install-gIYCea/virtualenvwrapper-4.1.1/egg-dist-tmp-oaCjsg Checking .pth file support in . /opt/bin/python2.6 -E -c pass Searching for pbr>=0.5.19 Reading http://pypi.python.org/simple/pbr/ Best match: pbr 0.5.21 Downloading https://pypi.python.org/packages/source/p/pbr/pbr-0.5.21.tar.gz#md5=1dafd1ef666b9bce4d880170ddc39387 Processing pbr-0.5.21.tar.gz Running pbr-0.5.21/setup.py -q bdist_egg –dist-dir /tmp/easy_install-gIYCea/virtualenvwrapper-4.1.1/temp/easy_install-Prh_Pq/pbr-0.5.21/egg-dist-tmp-PLfFJs Installed /tmp/easy_install-gIYCea/virtualenvwrapper-4.1.1/pbr-0.5.21-py2.6.egg Searching for pip>=1.0 Reading http://pypi.python.org/simple/pip/ Best match: pip 1.4.1 Downloading https://pypi.python.org/packages/source/p/pip/pip-1.4.1.tar.gz#md5=6afbb46aeb48abac658d4df742bff714 Processing pip-1.4.1.tar.gz Running pip-1.4.1/setup.py -q bdist_egg –dist-dir /tmp/easy_install-gIYCea/virtualenvwrapper-4.1.1/temp/easy_install-N07Olv/pip-1.4.1/egg-dist-tmp-cH_0sg warning: no files found matching ‘*.html’ under directory ‘docs’ warning: no previously-included files matching ‘*.rst’ found under directory ‘docs/_build’ no previously-included directories found matching ‘docs/_build/_sources’ Installed /tmp/easy_install-gIYCea/virtualenvwrapper-4.1.1/pip-1.4.1-py2.6.egg /opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/dist.py:245: UserWarning: Module pbr was already imported from /tmp/easy_install-gIYCea/virtualenvwrapper-4.1.1/temp/easy_install-Prh_Pq/pbr-0.5.21/pbr/__init__.py, but /tmp/easy_install-gIYCea/virtualenvwrapper-4.1.1/pbr-0.5.21-py2.6.egg is being added to sys.path Traceback (most recent call last): File “/opt/bin/easy_install”, line 8, in load_entry_point(‘setuptools==0.6c9′, ‘console_scripts’, ‘easy_install’)() File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py”, line 1671, in main File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py”, line 1659, in with_ei_usage File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py”, line 1675, in File “/opt/lib/python2.6/distutils/core.py”, line 152, in setup dist.run_commands() File “/opt/lib/python2.6/distutils/dist.py”, line 975, in run_commands self.run_command(cmd) File “/opt/lib/python2.6/distutils/dist.py”, line 995, in run_command cmd_obj.run() File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py”, line 211, in run File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py”, line 446, in easy_install File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py”, line 476, in install_item File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py”, line 655, in install_eggs File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py”, line 930, in build_and_install File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py”, line 919, in run_setup File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py”, line 27, in run_setup File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py”, line 63, in run File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py”, line 29, in File “setup.py”, line 7, in File “/opt/lib/python2.6/distutils/core.py”, line 113, in setup _setup_distribution = dist = klass(attrs) File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/dist.py”, line 223, in __init__ File “/opt/lib/python2.6/distutils/dist.py”, line 270, in __init__ self.finalize_options() File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/dist.py”, line 256, in finalize_options File “/opt/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/pkg_resources.py”, line 1913, in load ImportError: No module named core No idea what's going on. Can anyone help? Answer: it turned out by using a newer version of setuptools solved the problem.
Django app missing after import? Question: I'm working on a django project using win7 with aptana3/pydev . I have a project called mytest and I'm trying to import an app called 'django-mailbox' into my project (<http://django- mailbox.readthedocs.org/en/latest/topics/installation.html>) Following the directions I performed: ~tools/virtualenvs/mytest $ pip install django-mailbox Downloading/unpacking django-mailbox Downloading django-mailbox-3.0.2.tar.gz Running setup.py egg_info for package django-mailbox Downloading/unpacking six (from django-mailbox) Downloading six-1.4.1.tar.gz Running setup.py egg_info for package six Installing collected packages: django-mailbox, six Running setup.py install for django-mailbox Running setup.py install for six Successfully installed django-mailbox six Cleaning up... I have also added: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_mailbox', to my settings.py file. I was expecting to see the 'django_mailbox' directory within the 'mytest' dirctory, but its not. What happened, and where is it? edit: My directory structure is: |-development |---projects |---tools |-----PortableGit |-----Portablepython - ( actually installed in here ) ( Global files ? ) |-----Virtalenvs |--------mytest ( I thought it should be installed here ) |--------otherfile /development/tools/virtualenvs/mytest $ find ./ -type d | sed -e 's/[^-][^\/]*\//--/g;s/--/ |-/' |- |-mytest |-chat1 |-Lib |---encodings |---site-packages |-----setuptools |-------command |-------tests |-------_backport |---------hashlib |-----_markerlib |-----setuptools-0.9.8-py2.7.egg-info |-----pip |-------backwardcompat |-------commands |-------vcs |-------vendor |---------distlib |-----------_backport |---------html5lib |-----------filters |-----------serializer |-----------treebuilders |-----------treewalkers |-----------trie |-----pip-1.4.1-py2.7.egg-info |---distutils |-Include |---pygame |---pycairo |---pygtk-2.0 |-----pygtk |-Scripts Answer: In your `virtualenv`, it is stored very similar to the Python installation of the packages. <path_to_virtualenv>/lib/python2.7/site-packages/
Jquery ajax with google app engine post method Question: Just trying to learn using ajax with appengine,started with the post method,but it does not work. This is my HTML Code for the page <html> <head> <title> Hello </title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script> var data={"name":"Hola"}; $(document).ready(function(){ $('#subbut').click(function(){ $.ajax({ url: '/test', type: 'POST', data: data, success: function(data,status){ alert("Data" + data +"status"+status); } }); }); }); </script> </head> <body> <form method="post" action="/test"> <input type="submit" id="subbut"> </form> <div id="success"> </div> </body> </html> Here goes my python code to render the above html code , its handler is /test1 from main import * class TestH1(Handler): def get(self): self.render('tester.html') And this is the python script to which AJAX request must be sent to,handler is /test. from main import * import json class TestH(Handler): def post(self): t=self.request.get('name') output={'name':t+" duck"} output=json.dumps(output) self.response.out.write(output) Expected behavior is that when i click on submit button,i get an alert message saying "Hola duck" , get nothing instead. Any help would be appreciated as i am just starting with AJAX and Jquery withGAE Answer: At first, I suppose you should suppress default behavior of form submitting when you press submit button by adding "return false" to the .click function. But I suppose it would be better to use just <input type="button" id="subbut"> instead (even without form). Then you should add "dataType: 'json'" to your ajax call to tell jQuery what type of data you expect from server. Doing this you will be able to get response data by property names like "data.name". So: var data={"name":"Hola"}; $(document).ready(function(){ $('#subbut').click(function(){ $.ajax({ url: '/test', type: 'POST', data: data, dataType: 'json', success: function(data,status){ alert(data.name); alert("Data" + data +"status"+status); } }); return false; }); }); and it would be better if you set appropriate content type header to your response: response.headers = {'Content-Type': 'application/json; charset=utf-8'} self.response.out.write(output)
Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty Question: I am trying to set up multiple setting files (development, production, ..) that include some base settings. Cannot succeed though. When I try to run `./manage.py runserver` I am getting the following error: (cb)clime@den /srv/www/cb $ ./manage.py runserver ImproperlyConfigured: The SECRET_KEY setting must not be empty. Here is my settings module: (cb)clime@den /srv/www/cb/cb/settings $ ll total 24 -rw-rw-r--. 1 clime clime 8230 Oct 2 02:56 base.py -rw-rw-r--. 1 clime clime 489 Oct 2 03:09 development.py -rw-rw-r--. 1 clime clime 24 Oct 2 02:34 __init__.py -rw-rw-r--. 1 clime clime 471 Oct 2 02:51 production.py Base settings (contain SECRET_KEY): (cb)clime@den /srv/www/cb/cb/settings $ cat base.py: # Django base settings for cb project. import django.conf.global_settings as defaults DEBUG = False TEMPLATE_DEBUG = False INTERNAL_IPS = ('127.0.0.1',) ADMINS = ( ('clime', '[email protected]'), ) MANAGERS = ADMINS DATABASES = { 'default': { #'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'cwu', # Or path to database file if using sqlite3. 'USER': 'clime', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'Europe/Prague' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = False # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = False # TODO: make this true and accustom date time input DATE_INPUT_FORMATS = defaults.DATE_INPUT_FORMATS + ('%d %b %y', '%d %b, %y') # + ('25 Oct 13', '25 Oct, 13') # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '/srv/www/cb/media' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '/srv/www/cb/static' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&amp;022shmi1jcgihb*' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.request', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.core.context_processors.tz', 'django.contrib.messages.context_processors.messages', 'web.context.inbox', 'web.context.base', 'web.context.main_search', 'web.context.enums', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'watson.middleware.SearchContextMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'middleware.UserMemberMiddleware', 'middleware.ProfilerMiddleware', 'middleware.VaryOnAcceptMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'cb.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'cb.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. '/srv/www/cb/web/templates', '/srv/www/cb/templates', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'south', 'grappelli', # must be before admin 'django.contrib.admin', 'django.contrib.admindocs', 'endless_pagination', 'debug_toolbar', 'djangoratings', 'watson', 'web', ) AUTH_USER_MODEL = 'web.User' # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'null': { 'level':'DEBUG', 'class':'django.utils.log.NullHandler', }, 'logfile': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': "/srv/www/cb/logs/application.log", 'maxBytes': 50000, 'backupCount': 2, 'formatter': 'standard', }, 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'django': { 'handlers':['console'], 'propagate': True, 'level':'WARN', }, 'django.db.backends': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'web': { 'handlers': ['console', 'logfile'], 'level': 'DEBUG', }, }, } LOGIN_URL = 'login' LOGOUT_URL = 'logout' #ENDLESS_PAGINATION_LOADING = """ # <img src="/static/web/img/preloader.gif" alt="loading" style="margin:auto"/> #""" ENDLESS_PAGINATION_LOADING = """ <div class="spinner small" style="margin:auto"> <div class="block_1 spinner_block small"></div> <div class="block_2 spinner_block small"></div> <div class="block_3 spinner_block small"></div> </div> """ DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, } import django.template.loader django.template.loader.add_to_builtins('web.templatetags.cb_tags') django.template.loader.add_to_builtins('web.templatetags.tag_library') WATSON_POSTGRESQL_SEARCH_CONFIG = 'public.english_nostop' One of the setting files: (cb)clime@den /srv/www/cb/cb/settings $ cat development.py from base import * DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', '31.31.78.149'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'cwu', 'USER': 'clime', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } MEDIA_ROOT = '/srv/www/cb/media/' STATIC_ROOT = '/srv/www/cb/static/' TEMPLATE_DIRS = ( '/srv/www/cb/web/templates', '/srv/www/cb/templates', ) Code in `manage.py`: (cb)clime@den /srv/www/cb $ cat manage.py #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cb.settings.development") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) If I add `from base import *` into `/srv/www/cb/cb/settings/__init__.py` (which is otherwise empty), it magically starts to work but I don't understand why. Anyone could explain to me what's going on here? It must be some python module magic. **EDIT:** Everything also starts to work if I remove this line from base.py django.template.loader.add_to_builtins('web.templatetags.cb_tags') If I remove this line from web.templatetags.cb_tags, it also starts to work: from endless_pagination.templatetags import endless I guess it is because, in the end, it leads to from django.conf import settings PER_PAGE = getattr(settings, 'ENDLESS_PAGINATION_PER_PAGE', 10) So it creates some weird circular stuff and game over. Answer: I had the same error and it turned out to be a circular dependency between something loaded by the settings and the settings module itself. In my case it was a middleware class which was named in the settings which itself tried to load the settings.
TypeError: '_csv.reader' object has no attribute '__getitem__' // getting columns? Question: I'm trying to open a .csv file and put each column in different list: import csv CSV = csv.reader(open("AAPL.csv","rb")) column1 = CSV[0] column2 = CSV[1] column3 = CSV[2] column4 = CSV[2] column5 = CSV[4] column6 = CSV[5] Here is my `AAPL.csv`: Date Open High Low Close Volume Adj Close 2013-09-27 874.82 877.52 871.31 876.39 1258800 876.39 2013-09-26 878.3 882.75 875 878.17 1259900 878.17 2013-09-25 886.55 886.55 875.6 877.23 1649000 877.23 2013-09-24 886.5 890.1 881.4 886.84 1467000 886.84 2013-09-23 896.15 901.59 885.2 886.5 1777400 886.5 2013-09-20 898.39 904.13 895.62 903.11 4345300 903.11 2013-09-19 905.99 905.99 895.4 898.39 1597900 898.39 2013-09-18 886.35 903.97 883.07 903.32 1934700 903.32 2013-09-17 887.41 888.39 881 886.11 1259400 886.11 2013-09-16 896.2 897 884.87 887.76 1336500 887.76 ............................................................. end of file: ............................................................. 2012-06-29 574.96 58013 572.20 580.07 2519500 580.07 2012-06-28 565.90 566.23 557.21 564.31 1920900 564.31 2012-06-27 567.70 573.99 566.02 569.30 1692300 569.30 2012-06-26 562.76 566.60 559.48 564.68 1350200 564.68 2012-06-25 567.33 568.09 557.35 560.70 1581600 560.70 When I run my code, it returns me the following error: Traceback (most recent call last): File "/home/misha/Documents/finance/prices/some_csv.py", line 3, in <module> column1 = CSV[0] TypeError: '_csv.reader' object has no attribute '__getitem__' Is there any pythonic way to open a .csv file and put each column in different list not using attribute `getitem`? Thanks. NOTE: and also i need to skip first row. Answer: A `csv.reader` instance is an iterable over the lines of the CSV file. If you want each column in a separate list, you can use the `zip` function: import csv with open("AAPL.csv", "rb") as f: CSV = csv.reader(f) header = next(CSV) # read the header row column_data = zip(*CSV) # read data and arrange by columns instead of by rows # do stuff with column_lists Note that this reads the whole file in at once. If you have a very large amount of data in your file, you might want to redesign your algorithms to work on the data one row at a time as you iterate over the `CSV` object, so you don't need to hold it all in memory.
Python - Formatting specific data within text files Question: I have a number of log files I need extract and format data. some of these log files are very big with over 10,000 lines. can anyone suggest a code sample to help me read a text file, remove unwanted lines, then edit the remaining lines into a particular format. i haven't been able to find any previous threads that have what I'm after. An example of the data I need to edit is below: 136: add student 50000000 35011 / Y01T :Unknown id in field 3 - ignoring line 137: add student 50000000 5031 / Y01S :Unknown id in field 3 - ignoring line 138: add student 50000000 881 / Y01S :Unknown course idnumber in field 4 - ignoring line 139: add student 50000000 5732 / Y01S :Unknown id in field 3 - ignoring line 134: add student 50000000 W250 / Y02S :OK 135: add student 50000000 35033 / Y01T :OK I need to search the file and delete any line that is suffixed with :OK. Then, i need to edit the remaining lines in to a CSV format such as: add,student,50000000,1234 / abcd Any tips, code snippets, etc would be very helpful and i'll be most grateful. i'd try it first before asking, but I have little time to self teach python file access/string formatting. So please allow me to apologise in advance for not attempting it prior to asking Answer: This could be a solution: import sys if len(sys.argv) != 2: print 'Add an input file as parameter' sys.exit(1) print 'opening file: %s' % sys.argv[1] with open(sys.argv[1]) as input, open('output', 'w+') as output: for line in input: if line is not None: if line == '\n': pass elif 'OK' in line: pass else: new_line = line.split(' ', 7) output.write('%s,%s,%s,%s / %s\n' % (new_line[1], new_line[2], new_line[3], new_line[4], new_line[6])) # just for checking purposes let's print the lines print '%s,%s,%s,%s / %s' % (new_line[1], new_line[2], new_line[3], new_line[4], new_line[6]) Watch out for the output file name!
numpy unique strange behaviour Question: according to the official numpy.unique documentation (<http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html>) return_index=True should allow me to recover the first occurrences of elements in an array. However, this does not work for this simple example: import numpy as np a = np.array([10,20,30,40,50,60,70,80,3,2,4,3,2,5,2,1,999,1000]) a = np.append(a,np.repeat(999,10000)) u, indices = np.unique(a, return_index=True) print indices[13], u[13] #according to unique documentation indices[13] should be 16 (i.e. first occurrence of 999 = u[13]), but it is not This results in: [mvogelsberger@itc021 ~]$ python test.py 6685 999 Clearly, 6685 is not the index of first occurrence of 999 in the array a. Can someone clarify? I probably misunderstand the documentation... Thanks! Mark Answer: As you've guessed in the comments, this behaviour is indeed [a bug that was fixed in Numpy v1.7](https://github.com/numpy/numpy/commit/dbf235169ed3386b359caaa9217f5280bf1d6749)
Importing a class into another class in Python Question: as I'm still learning python I came up to a problem. Why does this work: class SomeOtherClass(object): def __init__(self): self.number = 10 print(self.number) def increase(self): self.number += 1 print(self.number) class MyMainClass(object): def __init__(self): self.otherClass = MyClass() app = MyMainClass() #Output: 10 app.otherclass.increase() #Output: 11 but this doesn't: from tkinter import * class MyMainClass(object): def __init__(self): self.tk = Tkinter() # <-- Error: see below. app = MyMainClass() app.tk.title("My window") ... Both times I include a class, but in the second example it says: > NameError: global name 'Tkinter' is not defined Where's the difference between those examples and how can I solve this, so I'm able to use tkinter in my class? Thanks for your help. Answer: Perhaps you meant `Tk()`? the `tkinter` module on Python 3.x does not seem to contain a class `Tkinter`. As to the meaning of your question and example... well, the examples are absolutely irrelevant, and the question should simply be "why can't I create an instance of `Tkinter`" or something. **Python Lesson:** This is also a good example of why it's a bad idea to use star imports (i.e `from <module> import *`, because `*` looks like a star). This imports everything from `tkinter`, but doesn't let you know if something you thought was there actually isn't from tkinter import * whereas this from tkinter import Tkinter would have immediately pointed out that (the class) `Tkinter` does not exist in `tkinter`. Another option that some seem to prefer (incl. myself in some cases), is `import tkinter` followed by `tkinter.Tk()`, which has the advantage that it's obvious where a class comes from. Futhermore, [PEP8](http://www.python.org/dev/peps/pep-0008/#imports) also discourages the use of star imports (referring to them as "wildcard imports").
python itertools: Using cycle with islice Question: Question: I have the code below. I want to know why does it not matter whether or not I include the line with the comment in the code below. #!/usr/bin/env python from itertools import * import time cc = cycle([ iter([1,2,3]), iter([4]) , iter([5,6]) ] ) p = 3 while p: try: for k in cc: print k.next() except StopIteration: p = p - 1 cc = cycle(islice(cc, p)) # this does not matter Output: 1 4 5 2 6 3 Also checkout `roundrobin` recipe at <http://docs.python.org/2.7/library/itertools.html> This code shows that `islice` is impacting `cc` #!/usr/bin/env python from itertools import * import time cc = cycle([ iter([1,2,3]), iter([4]) , iter([5,6]) ] ) p = 3 while p: try: for k in cc: print k,k.next() except StopIteration: print "stop iter" p = p - 1 cc = cycle(islice(cc, p)) Output <listiterator object at 0x7f32bc50cfd0> 1 <listiterator object at 0x7f32bc518050> 4 <listiterator object at 0x7f32bc518090> 5 <listiterator object at 0x7f32bc50cfd0> 2 <listiterator object at 0x7f32bc518050> stop iter <listiterator object at 0x7f32bc518090> 6 <listiterator object at 0x7f32bc50cfd0> 3 <listiterator object at 0x7f32bc518090> stop iter <listiterator object at 0x7f32bc50cfd0> stop iter Answer: Short course: the behaviors with and without rebinding `cc` aren't **generally** the same, but the outputs **happen** to be the same for the specific input you used. Long course: let's call your three iterators A, B and C. Without the `cc` rebinding: A produces 1, B produces 4, C produces 5, A produces 2, B raises `StopIteration`. `p` drops to 2. Then C produces 6, A produces 3, and B raises `StopIteration` **again**. `p` drops to 1. C raises `StopIteration`. `p` drops to 0, and the loop exits. With the `cc` rebinding: A produces 1, B produces 4, C produces 5, A produces 2, B raises `StopIteration`. `p` drops to 2. All the same so far. The purpose of the rebinding in the round-robin algorithm is to **remove** exhausted iterators. It so happens that in this specific example it makes no difference to the outcome. With the rebinding `islice(cc, 2)` takes "the next two things" from `cc`, which are, in order, C and A. B is no longer there. Then C and A are put in a new `cycle`. Then C produces 6, A produces 3, and C raises `StopIteration`. `p` drops to 1. The `cc` rebinding gets rid of C (the exhausted iterator), leaving just A in a new `cycle`. The loop goes around, and A raises `StopIteration`. `p` drops to 0, and we're done. Of course removing exhausted iterators is crucial to making round-robin work correctly in general. But, as you've shown, there are specific cases in which that doesn't matter :-) ## Simple example A simple case where rebinding `cc` makes a huge difference: cc = cycle([iter([1,2,3,4,5]), iter([])]) p = 2 With rebinding, we get all 5 values. Without rebinding, we only get 1 and 2.
Python object encapsulation security Question: I have a question, and my decision in choosing Python as a possible language for a bigger project depends on the answer - which I cannot come up with myself: We all know that Python has no _real_ object encapsulation, so there is nothing like "private" properties of an object. Regarding this issue, Guido van Rossum says that one can access hidden parts of a foreign object without being "allowed" to, with "we are all adults", "just don't do it". I can live perfectly well with that, as long as the software I write is in my own hand, so I am responsible for my own errors and just can try to avoid such things. BUT - and here comes my question: What if I provide a plugin framework with some plugins that have some extension points, and many of the plugins are by OTHER people, maybe ones that I cannot trust completely. How do I prevent exposing internals of my framework from being accessed by a plugin? Is there a way to achieve this, or is the only way to use Python having confidence that no one will abuse my API? Answer: You should never really rely on `private`, `public` etc for security (as in "protection against malicious code and external threats"). They are meant as something to keep the programmer from shooting himself in the foot, not as a (computer) security measure. You can also easily access private member fields of C++ objects, as long as you bypass static compiler checks and go straight to the memory, but would you say that C++ lacks true encapsulation? * For **C++** , see <http://phoxis.org/2012/01/25/accessing-private-data-members-directly-outside-from-its-class-in-c/> * Same about the **JVM** (and thus **Java**): [How do I read a private field in Java?](http://stackoverflow.com/questions/1196192/how-do-i-read-a-private-field-in-java) * And (more or less) the same about **CLR** (i.e. **.NET**): [Does reflection breaks the idea of private methods, because private methods can be access outside of the class?](http://stackoverflow.com/questions/3300680/does-reflection-breaks-the-idea-of-private-methods-because-private-methods-can) So you would never really use `private` or `protected` as a security measure against malicious plugins in C++ nor Java, and I assume C# as well. Your best bet is to run your plugins in a separate process and expose the core API over IPC/RPC or even web service, or run them in a [sandbox](https://www.google.com/search?q=sandboxed+python) (as per what @MarkHildreth pointed out). Alternatively, you can set up a certification and signing process for your plugins so that you can review and filter out potentially malicious plugins before they even get distributed. **NOTE:** You can actually achieve true encapsulation using lexical closures: def Foo(param): param = [param] # because `nonlocal` was introduced only in 3.x class _Foo(object): @property def param(self): return param[0] @param.setter def param(self, val): param[0] = val return _Foo() foo = Foo('bar') print foo.param # bar foo.param = 'baz' print foo.param # baz # no way to access `foo._param` or anything ...but even then, the value is actually still relatively easily accessible via reflection: >>> foo.__class__.param.fget.__closure__[0].cell_contents[0] = 'hey' >>> foo.param 'hey' ...and even if this weren't possible, we'd still be left with [`ctypes`](http://docs.python.org/2/library/ctypes.html) which allows direct memory access, bypassing any remaining cosmetic "restrictions": import ctypes arr = (ctypes.c_ubyte * 64).from_address(id(foo)) and now you can just assign to `arr` or read from it; although you'd have to work hard to traverse pointers from there down to the actual memory location where `.param` is stored, but it proves the point.
Setting python path for WinPython to use f2py Question: I installed the Winpython distribution on my copy of Windows 7. Launching iPython consoles and other items from the distribution from within the folder it copied to works fine. I'd like to use the f2py module from numpy to be able to call Fortran subroutines from Python. My understanding is that f2py must be called from the command line, but the system does not seem to find f2py, returning `ImportError: no module named site` when I call it either with or without flags. This same error is returned when I try to run python itself from the command line. When I manually navigate to the Winpython directory (e.g. `C:\Users\AGK\WinPython-32bit-2.7.5.3\python-2.7.5`) and call `f2py -c --help- fcompiler` to see if f2py is found there, I receive the following error Traceback (most recent call last): File ".\lib\site.py", line 538, in main main() File ".\lib\site.py", line 530, in main known_paths = addusersitepackages(known_paths) File ".\lib\site.py", line 266, in addusersitepackages user_site = getusersitepackages() File ".\lib\site.py", line 241, in getusersitepackages user_base = getuserbase() # this will also set USER_BASE File ".\lib\site.py", line 231, in getuserbase USER_BASE = get_config_var('userbase') File "C:\Users\AGK\WinPython-32bit-2.7.5.3\python-2.7.5\lib\sysconfig.py", line 516, in get_config_var return get_config_vars().get(name) File "C:\Users\AGK\WinPython-32bit-2.7.5.3\python-2.7.5\lib\sysconfig.py", line 449, in get_config_vars import re File "C:\Users\AGK\WinPython-32bit-2.7.5.3\python-2.7.5\lib\re.py", line 1 05, in <module> import sre_compile File "C:\Users\AGK\WinPython-32bit-2.7.5.3\python-2.7.5\lib\sre_parse.py" ", line 14, in <module> import sre_parse File "C:\Users\AGK\WinPython-32bit-2.7.5.3\python-2.7.5\lib\sre_constants.py", line 17, in <module> from sre_constants import * File "C:\Users\konings\WinPython-32bit-2.7.5.3\pyt py", line 18, in <module> from _sre import MAXREPEAT ImportError: cannot import name MAXREPEAT Could somebody explain to me what this error means and/or how to use f2py with Winpython? Thanks! Answer: You can set your environment variable `PYTHONPATH` pointing to the folder where these modules are. This should solve the `ImportError`s.
Unit test in aptana studio 3 Question: How do you run a Unit test on your class creation in aptana studio 3 on a python format class. I am wondering if I am supposed to add something to my code or is there a function in aptana studio that does it for you. Answer: Aptana Studio does not have a special test mode like PyCharm does, if you want to run unit-tests, you will simply need to create a `unittest` using Python's `unittest` module. So, for example: import unittest class MyTestCase(unittest.TestCase): def test_something(self): self.assertEqual(True, False) if __name__ == '__main__': unittest.main() And now, simply run this script.
Regular Expressions using Substitution to convert numbers Question: I'm a Python beginner, so keep in mind my regex skills are level -122. I need to convert a string with text containing `file1` to `file01`, but not convert `file10` to `file010`. My program is wrong, but this is the closest I can get, I've tried dozens of combinations but I can't get close: import re txt = 'file8, file9, file10' pat = r"[0-9]" regexp = re.compile(pat) print(regexp.sub(r"0\d", txt)) Can someone tell me what's wrong with my pattern and substitution and give me some suggestions? Answer: You could capture the number and check the length before adding 0, but you might be able to use this instead: import re txt = 'file8, file9, file10' pat = r"(?<!\d)(\d)(?=,|$)" regexp = re.compile(pat) print(regexp.sub(r"0\1", txt)) [regex101 demo](http://regex101.com/r/bA3xC6) `(?<! ... )` is called a negative lookbehind. This prevents (negative) a match if the pattern after it has the pattern in the negative lookbehind matches. For example, `(?<!a)b` will match all `b` in a string, except if it has an `a` before it, meaning `bb`, `cb` matches, but `ab` doesn't match. `(?<!\d)(\d)` thus matches a digit, unless it has another digit before it. `(\d)` is a single digit, enclosed in a capture group, denoted by simple parentheses. The captured group gets stored in the first capture group. `(?= ... )` is a positive lookahead. This matches _only_ if the pattern inside the positive lookahead matches after the pattern before this positive lookahead. In other words, `a(?=b)` will match all `a` in a string only if there's a `b` after it. `ab` matches, but `ac` or `aa` don't. `(?=,|$)` is a positive lookahead containing `,|$` meaning either a comma, or the end of the string. `(?<!\d)(\d)(?=,|$)` thus matches any digit, as long as there's no digit before it and there's a comma after it, or if that digit is at the end of the string.
twisted reactor.spawnProcess get stdout w/o bufffering on windows Question: I'm running an external process and I need to get the stdout immediately so I can push it to a textview, on GNU/Linux I can use "usePTY=True" to get the stdout by line, unfortunately usePTY is not available on windows. I'm fairly new to twisted, is there a way to achieve the same result on Windows with some twisted (or python maybe) magic stuff? Answer: > on GNU/Linux I can use "usePTY=True" to get the stdout by line Sort of! What `usePTY=True` actually does is create a PTY (a "pseudo-terminal" - the thing you always get when you log in to a shell on GNU/Linux unless you have a _real_ terminal which no one does anymore :) instead of a boring old pipe. A PTY is a lot like a pipe but it has some extra features - but more importantly for you, a PTY is strongly associated with interactive sessions (ie, a _user_) whereas a pipe is pretty strongly associated with programmatic uses (think `foo | bar` \- no user ever sees the output of `foo`). This means that people tend to use existence of a PTY as stdout as a signal that they should produce output in a timely manner - because a human is waiting to see it. On the flip side, the existence of a regular old pipe as stdout is taken as a signal that another program is consuming the output and they should instead produce output in the most _efficient_ way possible. What this **tends** to mean in practice is that if a program has a PTY then _it_ will line buffer its output and if it has a pipe then _it_ will "block" buffer its output (usually gather up about 4kB of data before writing any of it) - because line buffering is less efficient. The thing to note here is that it is the _program you are running_ that does this buffering. Whether you pass `usePTY=True` or `usePTY=False` makes no direct difference to that buffering: it is just a hint to the program you are running what kind of output buffering it should do. This means that you might run programs that block buffer even if you pass `usePTY=True` and vice versa. However... Windows doesn't have PTYs. So programs on Windows can't consider PTYs as a hint for how to buffer their output. I don't actually know if there is another hint that it is conventional for programs to respect on Windows. I've never come across one, at least. If you're lucky, then the program you're running will have _some_ way for you to request line-buffered output. If you're running Python, then it does - the `PYTHONUNBUFFERED` environment variable controls this, as does the `-u` command line option (and I think they both work on Windows). Incidentally, if you plan to pass binary data between the two processes, then you probably also want to put stdio into binary mode in the child process as well: import os, sys, mscvrt msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
Getting error when running the Django server on my Mac 10.8.5 Question: I am trying to setup Python/Django/Mysql on my Mac but I keep getting the following error when I run this command in terminal Python manage.py runserver The error I get is Marks-MacBook-Air:FirstBlog mmillar$ python manage.py runserver Validating models... Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.commands.runserver.Command object at 0x1017c2b10>> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 92, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 280, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/validation.py", line 35, in get_validation_errors for (app_name, error) in get_app_errors().items(): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/loading.py", line 166, in get_app_errors self._populate() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/loading.py", line 72, in _populate self.load_app(app_name, True) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/loading.py", line 96, in load_app models = import_module('.models', app_name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Users/mmillar/PycharmProjects/FirstBlog/blog/models.py", line 5, in <module> class post(models.Model): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.py", line 145, in __new__ new_class.add_to_class(obj_name, obj) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.py", line 265, in add_to_class value.contribute_to_class(cls, name) TypeError: Error when calling the metaclass bases unbound method contribute_to_class() must be called with TextField instance as first argument (got ModelBase instance instead) * * * **models.py** from django.db import models # Create your models here. class post(models.Model): author = models.CharField(max_length=30) title = models.CharField(max_length=100) bodytext = models.TextField timestamp = models.DateTimeField Answer: I think you did something like that: wrong: class Foo(models.Model): bar = models.TextField correct: class Foo(models.Model): bar = models.TextField() Thus you try to validate with a class instead of a class instance.
How to create Excel or Windows Msg Box using COM in Python? Question: Is there a way to get pywin32 to generate a VBA-style MsgBox in Excel, if not, perhaps the Windows equivalent? I tried: from win32com.client import Dispatch excel = Dispatch('Excel.Application') excel.MsgBox('foo') but it gives the error below: AttributeError: Excel.Application.MsgBox Answer: Hi you can use win32api: import win32api from win32con import MB_SYSTEMMODAL response = win32api.MessageBox(0, "Did you hear the Buzzer?", "Buzzer Test", 4, MB_SYSTEMMODAL) MB_SYSTEMMODAL is used for telling the system to show a message above all other applications.
Input to process using Python Question: I have a command (Say foo) that I normally run from terminal like so: user@computer$ foo enter the string: *(here I enter some string)* RESULT OF THE COMMAND WITH THE GIVEN INPUT I know beforehand what input I need to give. So, how do I automate the call using this python code: from subprocess import call call(['foo']) How do I automate the input to foo ? Answer: You can check out the third-party [pexpect](http://www.noah.org/wiki/pexpect) module ([Here is the API](http://pexpect.sourceforge.net/pexpect.html)): import pexpect child = pexpect.spawn('foo') child.expect('enter the string:') child.sendline('STRING YOU KNOW TO ENTER') child.close() # End Communication
Scrape internal links with Beautiful soup Question: I have written a python code to fetch the web-page corresponding to a given url, and parses all the links on that page into a repository of links. Next, it fetches the contents of any of the url from the repository just created, parses the links from this new content into the repository and continues this process for all links in the repository until stopped or after a given number of links are fetched. Here code: import BeautifulSoup import urllib2 import itertools import random class Crawler(object): """docstring for Crawler""" def __init__(self): self.soup = None # Beautiful Soup object self.current_page = "http://www.python.org/" # Current page's address self.links = set() # Queue with every links fetched self.visited_links = set() self.counter = 0 # Simple counter for debug purpose def open(self): # Open url print self.counter , ":", self.current_page res = urllib2.urlopen(self.current_page) html_code = res.read() self.visited_links.add(self.current_page) # Fetch every links self.soup = BeautifulSoup.BeautifulSoup(html_code) page_links = [] try : page_links = itertools.ifilter( # Only deal with absolute links lambda href: 'http://' in href, ( a.get('href') for a in self.soup.findAll('a') ) ) except Exception: # Magnificent exception handling pass # Update links self.links = self.links.union( set(page_links) ) # Choose a random url from non-visited set self.current_page = random.sample( self.links.difference(self.visited_links),1)[0] self.counter+=1 def run(self): # Crawl 3 webpages (or stop if all url has been fetched) while len(self.visited_links) < 3 or (self.visited_links == self.links): self.open() for link in self.links: print link if __name__ == '__main__': C = Crawler() C.run() This code does not fetch internal links (only absolute formed hyperlinks) **How to fetch Internal links that starts with '/' or '#' or '.'** Answer: Well, your code kind of already tells you what's going on. In your lambda you are only grabbing absolute links that start with http:// (which you are not grabbing https FWIW). You should grab all of the links and check to see if they start with http+ or not. If they don't, then they are a relative link, and since you know what the `current_page` is then you can use that to create an absolute link. Here's a modification to your code. Excuse my Python as it's a little rusty, but I ran it and it worked in Python 2.7 for me. You'll want to clean it up and add some edge/error detection, but you get the gist: #!/usr/bin/python from bs4 import BeautifulSoup import urllib2 import itertools import random import urlparse class Crawler(object): """docstring for Crawler""" def __init__(self): self.soup = None # Beautiful Soup object self.current_page = "http://www.python.org/" # Current page's address self.links = set() # Queue with every links fetched self.visited_links = set() self.counter = 0 # Simple counter for debug purpose def open(self): # Open url print self.counter , ":", self.current_page res = urllib2.urlopen(self.current_page) html_code = res.read() self.visited_links.add(self.current_page) # Fetch every links self.soup = BeautifulSoup(html_code) page_links = [] try : for link in [h.get('href') for h in self.soup.find_all('a')]: print "Found link: '" + link + "'" if link.startswith('http'): page_links.append(link) print "Adding link" + link + "\n" elif link.startswith('/'): parts = urlparse.urlparse(self.current_page) page_links.append(parts.scheme + '://' + parts.netloc + link) print "Adding link " + parts.scheme + '://' + parts.netloc + link + "\n" else: page_links.append(self.current_page+link) print "Adding link " + self.current_page+link + "\n" except Exception, ex: # Magnificent exception handling print ex # Update links self.links = self.links.union( set(page_links) ) # Choose a random url from non-visited set self.current_page = random.sample( self.links.difference(self.visited_links),1)[0] self.counter+=1 def run(self): # Crawl 3 webpages (or stop if all url has been fetched) while len(self.visited_links) < 3 or (self.visited_links == self.links): self.open() for link in self.links: print link if __name__ == '__main__': C = Crawler() C.run()
Python TypeError: iteration over non-sequence on simple list Question: import os test = os.system("ls /etc/init.d/ | grep jboss- | grep -vw jboss-") for row in test: print row For some reason this gives the TypeError: iteration over non-sequence error on this. When I do a print test without the for loop, it gives a list of the jboss instances, plus a "0" at the bottom.. The heck? Answer: `os.system()` returns the _exit code_ of the process, _not_ the result of the `grep` commands. This is always an integer. In the meantime, the output of the process itself is not redirected, so it writes to `stdout` directly (bypassing Python). You cannot iterate over over an integer. You should use the [`subprocess.check_output()` function](http://docs.python.org/2/library/subprocess.html#subprocess.check_output) instead if you wanted to retrieve the stdout output of the command. In this case, you'd be better off using `os.listdir()` and code the whole search in Python instead: for filename in os.listdir('/etc/init.d/'): if 'jboss-' in filename and not filename.startswith('jboss-'): print filename I've interpreted the `grep -vw jboss-` command as filtering out filenames that _start_ with `jboss`; adjust as needed.
Deduction of Integer Math (Order of Operations) Question: I'm working in Python at the moment, and I'm coming to a problem I don't know where to grab straws. Forgive me if this is covered in some initial Algorithm CS class somewhere, my background is really in Economics. I'm working with financial data, and I know the output and the inputs, I just don't know how to get to the order of operations. For instance, I have a final price to earnings ratio of 2, but inputs of 10 (price) and 5 (earnings). Just looking at this, I know 10/5 would be equivalent to 2. However, the problem is the order of operations .... this could be either addition, multiplication, division and square roots. This part seems doable if I just had inputs = [10,5] output = 2 def deduction_int(inputs, output): initial_output = 0 while initial_output != output: try adding, try subtracting (inverse), try dividing(inverse) prints 'yay' when its got itself figured out or if there is an answer The above code seems obvious and quick, however, when you add 3 variables to it .... inputs : 10, 5, 7 output : 2.14 and situations such as (10 + 5) / 7 = 2.14. I'm stuck with situations where numbers might be run with a different order. For instance 10+5 runs before dividing by 7. Is this a common algorithm type of problem? If so, where exactly do I look for some textbook description (name of the algorithm, textbook)? Thanks! Answer: Here is a brute-force algorithm. from __future__ import division import itertools as IT import operator opmap = {operator.add: '+', operator.mul: '*', operator.truediv: '/'} operators = opmap.keys() def deduction_int(inputs, output): iternums = IT.permutations(inputs, len(inputs)) iterops = IT.product(operators, repeat=len(inputs)-1) for nums, ops in IT.product(iternums, iterops): for result, rstr in combine(nums, ops): if near(result, output, atol=1e-3): return rstr def combine(nums, ops, astr=''): a = nums[0] astr = astr if astr else str(a) try: op = ops[0] except IndexError: return [(a, astr)] # combine a op (...) result = [] for partial_val, partial_str in combine(nums[1:], ops[1:]): r = op(a, partial_val) if len(nums[1:]) > 1: rstr = '{}{}({})'.format(astr, opmap[op], partial_str) else: rstr = '{}{}{}'.format(astr, opmap[op], partial_str) assert near(eval(rstr), r) result.append((r, rstr)) # combine (a op ...) b = nums[1] astr = '({}{}{})'.format(astr,opmap[op], b) for partial_val, partial_str in combine((op(a, b),)+nums[2:], ops[1:], astr): assert near(eval(partial_str), partial_val) result.append((partial_val, partial_str)) return result def near(a, b, rtol=1e-5, atol=1e-8): return abs(a - b) < (atol + rtol * abs(b)) def report(inputs, output): rstr = deduction_int(inputs, output) return '{} = {}'.format(rstr, output) print(report([10,5,7], (10+5)/7)) print(report([1,2,3,4], 3/7.)) print(report([1,2,3,4,5], (1+(2/3)*(4-5)))) yields (10+5)/7 = 2.14285714286 (1+2)/(3+4) = 0.428571428571 (1+5)/((2+4)*3) = 0.333333333333 * * * The main idea is to simply enumerate all orderings of the input values, and all orderings of the operators. For example, In [19]: list(IT.permutations([10,5,7], 3)) Out[19]: [(10, 5, 7), (10, 7, 5), (5, 10, 7), (5, 7, 10), (7, 10, 5), (7, 5, 10)] Then you pair each ordering of the input values with each ordering of the operators: In [38]: list(IT.product(iternums, iterops)) Out[38]: [((10, 5, 7), (<built-in function add>, <built-in function mul>)), ((10, 5, 7), (<built-in function add>, <built-in function truediv>)), ((10, 5, 7), (<built-in function mul>, <built-in function add>)), ((10, 5, 7), (<built-in function mul>, <built-in function truediv>)), ... The `combine` function takes an ordering of the nums and an ordering of the ops, and enumerates all possible groupings of the nums and ops: In [65]: combine((10, 5, 7), (operator.add, operator.mul)) Out[65]: [(45, '10+(5*7)'), (45, '10+((5*7))'), (105, '(10+5)*7'), (105, '((10+5)*7)')] It returns a list of tuples. Each tuple is a 2-tuple consisting of a numerical value and the string representation, `rstr`, of the grouped operations which evaluates to that value. So, you just loop over every possibility and return the `rstr` which, when evaluated, produces a number close to `output`. for nums, ops in IT.product(iternums, iterops): for result, rstr in combine(nums, ops): if near(result, output, atol=1e-3): return rstr * * * **Some useful references:** * [itertools.permutations](http://docs.python.org/2/library/itertools.html#itertools.permutations) * [itertools.product](http://docs.python.org/2/library/itertools.html#itertools.product) * [itertools.izip](http://docs.python.org/2/library/itertools.html#itertools.izip)
Follow the keyboard selection in Ubuntu preferably by Python Question: I am doing automation of my application. To do this at one point I need to move my mouse to selected item. I shall select the item with my keyboard and mouse will move accordingly to that point. Is there any code for doing this in Ubuntu 12.04 and 12.10. I am using Python for automation. Answer: Assuming you: * Know the coordinates of the "item" you've selected in your application * Are using Ubuntu You can do this inside your python script: from subprocess import call call(["xdotool", "mousemove", "300", "500"]) You might have to install xdotool if you don't have it installed: sudo apt-get install xdotool You may want to `man xdotool` to get more information on it - it's pretty awesome for automating keyboard/mouse events!
Read value from web page using python Question: I am trying to read a value in a html page into a variable in a python script. I have already figured out a way of downloading the page to a local file using urllib and could extract the value with a bash script but would like to try it in Python. import urllib urllib.urlretrieve('http://url.com', 'page.htm') The page has this in it: <div name="mainbody" style="font-size: x-large;margin:auto;width:33;"> <b><a href="w.cgi?hsn=10543">Plateau (19:01)</a></b> <br/> Wired: 17.4 <br/>P10 Chard: 16.7 <br/>P1 P. Gris: 17.1 <br/>P20 Pinot Noir: 15.8- <br/>Soil Temp : Error <br/>Rainfall: 0.2<br/> </div> I need the 17.4 value from the Wired: line Any suggestions? Thanks Answer: Start with not using `urlretrieve()`; you want the data, not a file. Next, use a HTML parser. [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) is great for extracting text from HTML. Retrieving the page with `urllib2` would be: from urllib2 import urlopen response = urlopen('http://url.com/') then read the data into BeautifulSoup: from bs4 import BeautifulSoup soup = BeautifulSoup(response.read(), from_encoding=response.headers.getparam('charset')) The `from_encoding` part there will tell BeautifulSoup what encoding the web server told you to use for the page; if the web server did not specify this then BeautifulSoup will make an educated guess for you. Now you can search for your data: for line in soup.find('div', {'name': 'mainbody'}).stripped_strings: if 'Wired:' in line: value = float(line.partition('Wired:')[2]) print value For your demo HTML snippet that gives: >>> for line in soup.find('div', {'name': 'mainbody'}).stripped_strings: ... if 'Wired:' in line: ... value = float(line.partition('Wired:')[2]) ... print value ... 17.4
my RAM gets full and PC crashes when i execute my python script . Question: I wrote a simple script in python . It's a talking battery monitor , inspired from IronMan Jarvis . Now the problem is that , the code runs perfectly but the RAM keeps getting full when the code is running . Finally when the RAM gets full , the PC crashes . What could be the problem? I dont use any new varibles . I update the same variable by polling . This is my code- # Get power status of the system using ctypes to call GetSystemPowerStatus import ctypes from ctypes import wintypes import speech def startmonitor(): class SYSTEM_POWER_STATUS(ctypes.Structure): _fields_ = [ ('ACLineStatus', wintypes.BYTE), ('BatteryFlag', wintypes.BYTE), ('BatteryLifePercent', wintypes.BYTE), ('Reserved1', wintypes.BYTE), ('BatteryLifeTime', wintypes.DWORD), ('BatteryFullLifeTime', wintypes.DWORD), ] SYSTEM_POWER_STATUS_P = ctypes.POINTER(SYSTEM_POWER_STATUS) GetSystemPowerStatus = ctypes.windll.kernel32.GetSystemPowerStatus GetSystemPowerStatus.argtypes = [SYSTEM_POWER_STATUS_P] GetSystemPowerStatus.restype = wintypes.BOOL status = SYSTEM_POWER_STATUS() #define an object of the class SYSTEM_POWER_STATUS if not GetSystemPowerStatus(ctypes.pointer(status)): raise ctypes.WinError() return status x=0 #counting variable def setflag0(): for x in range(7): flag[x]=0 return flag def setxval(): if(status.BatteryLifePercent==100): x=0 elif(status.BatteryLifePercent<100 and status.BatteryLifePercent>30): x=1 elif(status.BatteryLifePercent<=30 and status.BatteryLifePercent>15): x=2 elif(status.BatteryLifePercent<=15 and status.BatteryLifePercent>5): x=3 elif(status.BatteryLifePercent<=5): x=4 return x flag=[0,0,0,0,0,0,0] speech.say("This is the talking battery monitor version 1.0") while(1) : status=startmonitor() bat=setxval() if(bat!=0 and status.ACLineStatus==1 and flag[1]!=1): speech.say("All power systems being charged sir ! ") flag=setflag0() flag[1]=1 elif(bat==0 and flag[6]!=1): if(status.ACLineStatus==1): speech.say("Battery : one hundred percent charged") elif(status.ACLineStatus==0): speech.say("Sir , You have full battery power") flag=setflag0() flag[6]=1 elif(bat==1 and status.ACLineStatus==0 and flag[2]!=1): speech.say("Battery Level : ") speech.say(status.BatteryLifePercent) speech.say("percent") flag=setflag0() flag[2]=1 elif(bat==2 and flag[3]!=1 and status.ACLineStatus==0): speech.say("Sir, i'm running low on battery . Please put me on charge !" ) flag=setflag0() flag[3]=1 elif(bat==3 and flag[4]!=1 and status.ACLineStatus==0): speech.say("Sir, you're now running on emergency backup power") flag=setflag0() flag[4]=1 elif(bat==4 and flag[5]!=1 and status.ACLineStatus==0): speech.say(" Alert ! Power critical Sir, I might turn off in ") speech.say(status.BatteryLifeTime/1000000) speech.say("minutes") flag=setflag0() flag[5]=1 Answer: Somewhere in the loop a function is using memory. It might be that the system call SYSTEM_POWER_STATUS is using memory. Is it possible to call status=startmonitor() before the while loop? Otherwise start removing code (even though it breaks the functionality temporarily) to find out which part uses memory and try to find an alternative for that part.
How to set an optional argument from python in terminal? Question: I have a program that takes one input but can also take another optional argument if the user wants. How can I implement this optional argument? I am importing sys library to get the first arguement like this word_input = sys.argv[1] num_input = sys.argv[2] // I want to make this optional Answer: Test for the length; `sys.argv` is just a list, really: num_input = sys.argv[2] if len(sys.argv) > 2 else None
Problems using Metakit for Python on Windows Question: I'm having problems trying to use Metakit for Python on Windows. It always report this error: Traceback (most recent call last): File "<pyshell#86>", line 1, in <module> import metakit File "C:\Python27\lib\site-packages\metakit.py", line 22, in <module> from Mk4py import * ImportError: No module named Mk4py I've already: * Downloaded metakit.py and Mk4py.dll from <http://equi4.com/pub/mk/> (official release) * Copied metatkit.py to C:\Python27\lib\site-packages\ * Copied Mk4py.dll to C:\Python27\DLLs\ I have installed Python 2.7.5 win32 version Any idea to solve this problem? Answer: I also had the same problem and couldn't get the system to work with the provided dlls. I also tried compiling metakit from source to make it work and installing it from an the official source via egg, which failed in the same way (as it compiles from source). Using my older windows XP machine with visual studio 2002 I managed to build it from source and install it with just a minor change of the setup script (changing every instance of msvc60 to msvc70 in the setup script). However, copying those files to my windows 8 machine still failed, and even copying what appeared to be the changes were unsuccessful. In the end I copied my entire python directory from the xp machine to the windows 8 machine and now it is working without issues. Obviously i could provide my dlls but I doubt they would be any more successful than the provided ones. My next step is to reduce my reliance on having to use metakit as it seems very poorly supported.
Integer Gui input for button command in Python 2.7 Question: I have a very simple GUI I am trying to make in which I have a single entry, and a single button. I would like to enter a number in the entry, and then use that number as a variable in the command that my button initiates. For example, if you enter a 2 and my command was to compute 2+emtry, selecting the button would yield a 4. I have 2 problems: 1. How to convert the entry into an integer? 2. How to use that integer in the command my button calls. I am very new to Python. Here is my code: from Tkinter import * import tkMessageBox import Tkinter root = Tkinter.Tk() root.title("Title") root.geometry("150x150") Lbl1 = Label(root, text="Input a number here:") Lbl1.pack(side=TOP,padx=5,pady=5) Entry1 = Entry(root, bd =1) Entry1.pack(side=TOP,padx=5,pady=5) def PrintCommand(): print('I want the number from the entry here') bttn1 = Tkinter.Button(root, text ="print command", command = PrintCommand) bttn1.pack(side = TOP,padx=10,pady=20) root.mainloop() Answer: To get the value, use the `get` method on the entry. To convert it to an integer you can use the python `int` function: def PrintCommand(): the_number = int(Entry1.get()) print(the_number)
How to run two loops at the same time in python Question: How can i run a loop within a loop in python to make points in a simple word game import random WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone", "truck", "doom", "mayonase", "flying", "magic", "mine", "bugle") play = "Yes" points = 0 ask = ('Yes') word = random.choice(WORDS) while play == "Yes": hint = word correct = word jumble = "" while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] print( """ Welcome to Word Jumble! Unscramble the letters to make a word. (Press the enter key at the prompt to quit.) """ ) print("The jumble is:", jumble) guess = input("\nYour guess: ") while guess != correct and guess != "": print("Sorry, that's not it.") guess = input("Your guess: ") print("Do you want a hint") if ask == "yes": print(word) points - 10 print(points) if guess == correct: print("That's it! You guessed it!\n") play = input("Do you want to play again") points + 100 print(points) print("Thanks for playing.") input("\n\nPress the enter key to exit.") is all the code i have im trying to add a point system into it. The problem im trying to do is "Improve “Word Jumble” so that each word is paired with a hint. The player should be able to see the hint if he or she is stuck. Add a scoring system that rewards players who solve a jumble without asking for the hint." Answer: Came up with something like this... needs a lot of work, but it will set you on the right track (I hope so!!) Here's the modified code: import random WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone", "truck", "doom", "mayonase", "flying", "magic", "mine", "bugle") play = "Yes" points = 0 ask = ('Yes') word = random.choice(WORDS) while play == "Yes": next_hint = 4 hint = "{}...".format(word[0:next_hint]) correct = word jumble = "" while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] print( """ Welcome to Word Jumble! Unscramble the letters to make a word. (Press the enter key at the prompt to quit.) """ ) print("The jumble is:", jumble) guess = input("\nYour guess: ") while guess != correct and guess != "": print("Sorry, that's not it.") if hint != word: ask = input("Do you want a hint? yes / no: ") if ask in ("yes", "y", "yeah"): print(hint) next_hint += 1 hint = "{}...".format(correct[0:next_hint]) points -= 10 print("You lose 10 points!") guess = input("Your guess: ") if guess == correct: print("That's it! You guessed it!\n") play = input("Do you want to play again? yes/no: ") points += 100 print("You earn {} points!".format(points)) print("Thanks for playing.") input("\n\nPress the enter key to exit.") I added hints that will gradually show the word and fixed the point system (Or at least it takes into account how many hints you used). The problem is, I always show at least 4 characters of the string and some words are that short (you'll have to fix that) Hope it helps!!!
Select all in a tkinter Listbox Question: I am creating a `Listbox` using Tkinter and Python. I want to make a Button for `select all`, but I can't find any info regarding selecting elements using code. self.l = Listbox(self, height=12, selectmode=MULTIPLE) self.selectAll=Button(self, text="select all", command=self.selectAllCallback()) def selectAllCallback(self) # What to do here Answer: You can use [`selection_set`](http://effbot.org/tkinterbook/listbox.htm#Tkinter.Listbox.selection_set- method) (or `select_set`) method with `0` and `END` as arguments. For example, try following code: from Tkinter import * def select_all(): lb.select_set(0, END) root = Tk() lb = Listbox(root, selectmode=MULTIPLE) for i in range(10): lb.insert(END, i) lb.pack() Button(root, text='select all', command=select_all).pack() root.mainloop() In the following statement, you are calling `self.selectAllCallback`, not bind it with button click. It is called before the button is generated. self.selectAll=Button(self,text="select all", command=self.selectAllCallback()) ^^ It should be: self.selectAll=Button(self, text="select all", command=self.selectAllCallback)
Flexible UNIX command line interface with Python Question: I was wondering how to create a flexible CLI interface with Python. So far I have come up with the following: $ cat cat.py #!/usr/bin/env python from sys import stdin from fileinput import input from argparse import ArgumentParser, FileType def main(args): for line in input(): print line.strip() if __name__ == "__main__": parser = ArgumentParser() parser.add_argument('FILE', nargs='?', type=FileType('r'), default=stdin) main(parser.parse_args()) This handles both stdin and file input: $ echo 'stdin test' | ./cat.py stdin test $ ./cat.py file file test The problem is it doesn't handle multiple input or no input the way I would like: $ ./cat.py file file usage: cat.py [-h] [FILE] cat.py: error: unrecognized arguments: file $ ./cat.py For multiple inputs it should `cat` the file multiple times and for no input input should ideally have same the behaviour as `-h`: $ ./cat.py -h usage: cat.py [-h] [FILE] positional arguments: FILE optional arguments: -h, --help show this help message and exit Any ideas on creating a flexible CLI interface with Python? Answer: Use [`nargs='*'`](http://docs.python.org/2/library/argparse.html#nargs) to allow for 0 or more arguments: if __name__ == "__main__": parser = ArgumentParser() parser.add_argument('FILE', nargs='*', type=FileType('r'), default=stdin) main(parser.parse_args()) The help output now is: $ bin/python cat.py -h usage: cat.py [-h] [FILE [FILE ...]] positional arguments: FILE optional arguments: -h, --help show this help message and exit and when no arguments are given, `stdout` is used. If you want to require at least one `FILE` argument, use `nargs='+'` instead, but then the default is ignored, so you may as well drop that: if __name__ == "__main__": parser = ArgumentParser() parser.add_argument('FILE', nargs='+', type=FileType('r')) main(parser.parse_args()) Now not specifying a command-line argument gives: $ bin/python cat.py usage: cat.py [-h] FILE [FILE ...] cat.py: error: too few arguments You can always specify `stdin` still by passing in `-` as an argument: $ echo 'hello world!' | bin/python cat.py - hello world!
Using Counter() in Python to build histogram? Question: I saw on another question that I could use `Counter()` to count the number of occurrences in a set of strings. So if I have `['A','B','A','C','A','A']` I get `Counter({'A':3,'B':1,'C':1})`. But now, how can I use that information to build a histogram for example? Answer: For your data it is probably better to use a barchart instead of a histogram. Check out this code: from collections import Counter import numpy as np import matplotlib.pyplot as plt labels, values = zip(*Counter(['A','B','A','C','A','A']).items()) indexes = np.arange(len(labels)) width = 1 plt.bar(indexes, values, width) plt.xticks(indexes + width * 0.5, labels) plt.show() Result: ![enter image description here](http://i.stack.imgur.com/0ZQq9.png)
How to use the resource module to measure the running time of a function? Question: I want to measure the CPU running time and wall clock running time of functions using Python code. The resource module was suggested here: [How to measure CPU running time and wall clock running time of a function, separately, as Python code (not from terminal)?](http://stackoverflow.com/q/19204618/1690799) Here is the module documentation: <http://docs.python.org/2/library/resource.html> The problem is that: 1) I can't figure out how to use it to measure the running time of a function. 2) I don't know how to extract that information from the object returned. How do I do this? Answer: Just call [`getrusage`](http://docs.python.org/2/library/resource.html#resource.getrusage) before and after executing the function, subtract the fields you care about, and you're done. Since `resource` doesn't do wall time, you'll need to use a separate function for that. You can wrap that up in a helper function, or even a decorator, like this: import datetime import functools import resource import sys def timed(func): @functools.wraps(func) def wrapper(*args, **kwargs): r0 = resource.getrusage(resource.RUSAGE_SELF) t0 = datetime.datetime.now() retval = func(*args, **kwargs) r = resource.getrusage(resource.RUSAGE_SELF) t = datetime.datetime.now() sys.stderr.write('{}: utime {} stime {} wall: {}\n'.format( func.__name__, datetime.timedelta(seconds=r.ru_utime-r0.ru_utime), datetime.timedelta(seconds=r.ru_stime-r0.ru_stime), t-t0)) return retval return wrapper @timed def myfunc(i): for _ in range(100000000): pass return i*2 print(myfunc(2)) This will print out something like: myfunc: utime 0:00:03.261688 stime 0:00:00.805324 wall 0:00:04.067109 4 If you want more than a couple fields, you probably want to subtract all of the members of the rusage results, but since these are all int or float, that's easy: rdiff = resource.struct_rusage(f1-f0 for f0, f1 in zip(r0, r)) sys.stderr.write('{}: utime {} maxrss {} nsignals {} etc.\n'.format( datetime.timedelta(seconds=rdiff.r_utime), rdiff.ru_maxrss, rdiff.ru_nsignals))
Does Queue.get block main? Question: I know that `Queue.get()` method in python is a blocking function. I need to know if I implemented this function inside the main, waiting for an object set by a thread, does this means that all the main will be blocked. For instance, if the main contains functions for transmitter and receiver, will the two work together or not? Answer: Yes -- if you call `some_queue.get()` within either the thread or the `main` function, the program will block there until some object as passed through the queue. * * * However, it is possible to use queues so that they [don't block](http://docs.python.org/2/library/queue.html#Queue.Queue.get), or so that they have a timeout of some kind: import Queue while True: try: data = some_queue.get(False) # If `False`, the program is not blocked. `Queue.Empty` is thrown if # the queue is empty except Queue.Empty: data = None try: data2 = some_queue.get(True, 3) # Waits for 3 seconds, otherwise throws `Queue.Empty` except Queue.Empty: data = None You can do the same for `some_queue.put` \-- either do `some_queue.put(item, False)` for non-blocking queues, or `some_queue.put(item, True, 3)` for timeouts. If your queue has a size limit, it will throw a `Queue.Full` exception if there is no more room left to append a new item.
Why calculations of eigenvectors of a 2 by 2 matrix with numpy crashes my Python session? Question: I try to do the following: import numpy as np from numpy import linalg as la w, v = la.eig(np.array([[1, -1], [1, 1]])) As a result I have a crash of the python session with the following message: Illegal instruction (core dumped) I tried to use scipy instead of numpy. The result is the same. Answer: I suspect that there is a problem with your installation of python/numpy/scipy as when I try it I have no problems. Python 2.7.4 (default, Sep 26 2013, 03:20:26) [GCC 4.7.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy as np >>> from numpy import linalg as la >>> w, v = la.eig(np.array([[1, -1], [1, 1]])) >>> w array([ 1.+1.j, 1.-1.j]) >>> v array([[ 0.70710678+0.j , 0.70710678+0.j ], [ 0.00000000-0.70710678j, 0.00000000+0.70710678j]]) >>> I would suggest that you try a fresh installation.
Remote executing of program via xterm run using paramiko python ssh library Question: Flow of the program is: 1. Connect to OpenSSH server on Linux machine using Paramiko library 2. Open X11 session 3. Run xterm executable 4. Run some other program (e.g. Firefox) by typing executable name in the terminal and running it. I would be grateful if someone can explain how to cause some executable to run in a terminal which was open by using the following code and provide sample source code ([source](http://stackoverflow.com/a/19164039)): import select import sys import paramiko import Xlib.support.connect as xlib_connect import os import socket import subprocess # run xming XmingProc = subprocess.Popen("C:/Program Files (x86)/Xming/Xming.exe :0 -clipboard -multiwindow") ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(SSHServerIP, SSHServerPort, username=user, password=pwd) transport = ssh_client.get_transport() channelOppositeEdges = {} local_x11_display = xlib_connect.get_display(os.environ['DISPLAY']) inputSockets = [] def x11_handler(channel, (src_addr, src_port)): local_x11_socket = xlib_connect.get_socket(*local_x11_display[:3]) inputSockets.append(local_x11_socket) inputSockets.append(channel) channelOppositeEdges[local_x11_socket.fileno()] = channel channelOppositeEdges[channel.fileno()] = local_x11_socket transport._queue_incoming_channel(channel) session = transport.open_session() inputSockets.append(session) session.request_x11(handler = x11_handler) session.exec_command('xterm') transport.accept() while not session.exit_status_ready(): readable, writable, exceptional = select.select(inputSockets,[],[]) if len(transport.server_accepts) > 0: transport.accept() for sock in readable: if sock is session: while session.recv_ready(): sys.stdout.write(session.recv(4096)) while session.recv_stderr_ready(): sys.stderr.write(session.recv_stderr(4096)) else: try: data = sock.recv(4096) counterPartSocket = channelOppositeEdges[sock.fileno()] counterPartSocket.sendall(data) except socket.error: inputSockets.remove(sock) inputSockets.remove(counterPartSocket) del channelOppositeEdges[sock.fileno()] del channelOppositeEdges[counterPartSocket.fileno()] sock.close() counterPartSocket.close() print 'Exit status:', session.recv_exit_status() while session.recv_ready(): sys.stdout.write(session.recv(4096)) while session.recv_stderr_ready(): sys.stdout.write(session.recv_stderr(4096)) session.close() XmingProc.terminate() XmingProc.wait() I was thinking about running the program in child thread, while the thread running the xterm is waiting for the child to terminate. Answer: Well, this is a bit of a hack, but hey. What you can do on the remote end is the following: Inside the xterm, you run `netcat`, listen to any data coming in on some port, and pipe whatever you get into `bash`. It's not quite the same as typing it into xterm direclty, but it's almost as good as typing it into bash directly, so I hope it'll get you a bit closer to your goal. If you really want to interact with xterm directly, you might want to [read this](http://books.google.co.uk/books?id=t8C4pEDQ8s0C&lpg=PA294&ots=n6IT4dU7Po&dq=expect%20xterm&pg=PA293#v=onepage&q=expect%20xterm&f=false). For example: terminal 1: % nc -l 3333 | bash terminal 2 (type `echo hi` here): % nc localhost 3333 echo hi Now you should see `hi` pop out of the first terminal. Now try it with `xterm&`. It worked for me. Here's how you can automate this in Python. You may want to add some code that enables the server to tell the client when it's ready, rather than using the silly `time.sleep`s. import select import sys import paramiko import Xlib.support.connect as xlib_connect import os import socket import subprocess # for connecting to netcat running remotely from multiprocessing import Process import time # data import getpass SSHServerPort=22 SSHServerIP = "localhost" # get username/password interactively, or use some other method.. user = getpass.getuser() pwd = getpass.getpass("enter pw for '" + user + "': ") NETCAT_PORT = 3333 FIREFOX_CMD="/path/to/firefox &" #FIREFOX_CMD="xclock&"#or this :) def run_stuff_in_xterm(): time.sleep(5) s = socket.socket(socket.AF_INET6 if ":" in SSHServerIP else socket.AF_INET, socket.SOCK_STREAM) s.connect((SSHServerIP, NETCAT_PORT)) s.send("echo \"Hello there! Are you watching?\"\n") s.send(FIREFOX_CMD + "\n") time.sleep(30) s.send("echo bye bye\n") time.sleep(2) s.close() # run xming XmingProc = subprocess.Popen("C:/Program Files (x86)/Xming/Xming.exe :0 -clipboard -multiwindow") ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(SSHServerIP, SSHServerPort, username=user, password=pwd) transport = ssh_client.get_transport() channelOppositeEdges = {} local_x11_display = xlib_connect.get_display(os.environ['DISPLAY']) inputSockets = [] def x11_handler(channel, (src_addr, src_port)): local_x11_socket = xlib_connect.get_socket(*local_x11_display[:3]) inputSockets.append(local_x11_socket) inputSockets.append(channel) channelOppositeEdges[local_x11_socket.fileno()] = channel channelOppositeEdges[channel.fileno()] = local_x11_socket transport._queue_incoming_channel(channel) session = transport.open_session() inputSockets.append(session) session.request_x11(handler = x11_handler) session.exec_command("xterm -e \"nc -l 0.0.0.0 %d | /bin/bash\"" % NETCAT_PORT) p = Process(target=run_stuff_in_xterm) transport.accept() p.start() while not session.exit_status_ready(): readable, writable, exceptional = select.select(inputSockets,[],[]) if len(transport.server_accepts) > 0: transport.accept() for sock in readable: if sock is session: while session.recv_ready(): sys.stdout.write(session.recv(4096)) while session.recv_stderr_ready(): sys.stderr.write(session.recv_stderr(4096)) else: try: data = sock.recv(4096) counterPartSocket = channelOppositeEdges[sock.fileno()] counterPartSocket.sendall(data) except socket.error: inputSockets.remove(sock) inputSockets.remove(counterPartSocket) del channelOppositeEdges[sock.fileno()] del channelOppositeEdges[counterPartSocket.fileno()] sock.close() counterPartSocket.close() p.join() print 'Exit status:', session.recv_exit_status() while session.recv_ready(): sys.stdout.write(session.recv(4096)) while session.recv_stderr_ready(): sys.stdout.write(session.recv_stderr(4096)) session.close() XmingProc.terminate() XmingProc.wait() I tested this on a Mac, so I commented out the `XmingProc` bits and used `/Applications/Firefox.app/Contents/MacOS/firefox` as `FIREFOX_CMD` (and `xclock`). The above isn't exactly a secure setup, as anyone connecting to the port at the right time could run arbitrary code on your remote server, but it sounds like you're planning to use this for testing purposes anyway. If you want to improve the security, you could make netcat bind to `127.0.0.1` rather than `0.0.0.0`, setup an ssh tunnel (run `ssh -L3333:localhost:3333 [email protected]` to tunnel all traffic received locally on port 3333 to remote-host.com:3333), and let Python connect to `("localhost", 3333)`. Now you can combine this with [selenium](http://docs.seleniumhq.org/) for browser automation: Follow the instructions from [this page](https://pypi.python.org/pypi/selenium), i.e. download the selenium standalone server jar file, put it into `/path/to/some/place` (on the server), and `pip install -U selenium` (again, on the server). Next, put the following code into `selenium-example.py` in `/path/to/some/place`: #!/usr/bin/env python from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.keys import Keys import time browser = webdriver.Firefox() # Get local session of firefox browser.get("http://www.yahoo.com") # Load page assert "Yahoo" in browser.title elem = browser.find_element_by_name("p") # Find the query box elem.send_keys("seleniumhq" + Keys.RETURN) time.sleep(0.2) # Let the page load, will be added to the API try: browser.find_element_by_xpath("//a[contains(@href,'http://docs.seleniumhq.org')]") except NoSuchElementException: assert 0, "can't find seleniumhq" browser.close() and change the firefox command: FIREFOX_CMD="cd /path/to/some/place && python selenium-example.py" And watch firefox do a Yahoo search. You might also want to increase the `time.sleep`. If you want to run more programs, you can do things like this before or after running firefox: # start up xclock, wait for some time to pass, kill it. s.send("xclock&\n") time.sleep(1) s.send("XCLOCK_PID=$!\n") # stash away the process id (into a bash variable) time.sleep(30) s.send("echo \"killing $XCLOCK_PID\"\n") s.send("kill $XCLOCK_PID\n\n") time.sleep(5) If you want to do perform general X11 application control, I think you might need to write similar "driver applications", albeit using different libraries. You might want search for "x11 send {mouse|keyboard} events" to find more general approaches. That brings up [these](http://stackoverflow.com/q/6447704/1298153) [questions](http://stackoverflow.com/q/4402216/1298153), but I'm sure there's lots more. If the remote end isn't responding instantaneously, you might want to sniff your network traffic in Wireshark, and check whether or not TCP is batching up the data, rather than sending it line by line (the `\n` seems to help here, but I guess there's no guarantee). If this is the case, you might be [out of luck](http://stackoverflow.com/q/10511672/1298153), but [nothing is impossible](http://stackoverflow.com/q/13517246/1298153). I hope you don't need to go that far though ;-) One more note: if you need to communicate with CLI programs' STDIN/STDOUT, you might want to look at expect scripting (e.g. using [pexpect](http://www.noah.org/wiki/pexpect), or for simple cases you might be able to use subprocess.Popen.communicate](<http://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate>)).
Unknown command: 'collectstatic' Django 1.7 Question: I want do static files. I use Django 1.7 and Python 2.7.5 and openshift hosting. When I try to run: `python manage.py collectstatic` I get: Unknown command: 'collectstatic' Type 'manage.py help' for usage. In my settings.py: ... INSTALLED_APPS = ( 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'testapp', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.static', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['OPENSHIFT_APP_NAME'], 'USER': os.environ['OPENSHIFT_MYSQL_DB_USERNAME'], 'PASSWORD': os.environ['OPENSHIFT_MYSQL_DB_PASSWORD'], 'HOST': os.environ['OPENSHIFT_MYSQL_DB_HOST'], 'PORT': os.environ['OPENSHIFT_MYSQL_DB_PORT'], } } STATIC_ROOT = '' STATIC_URL = '/static/' ... Many people had this proble. They forgot 'django.contrib.staticfiles' in INSTALLED_APPS. But I have this setting. Ok, I run help: Options: -v VERBOSITY, --verbosity=VERBOSITY Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output --settings=SETTINGS The Python path to a settings module, e.g. "myproject.settings.main". If this isn't provided, the DJANGO_SETTINGS_MODULE environment variable will be used. --pythonpath=PYTHONPATH A directory to add to the Python path, e.g. "/home/djangoprojects/myproject". --traceback Raise on exception --no-color Don't colorize the command output. --version show program's version number and exit -h, --help show this help message and exit Traceback (most recent call last): ... File "c:\Python27\lib\os.py", line 423, in __getitem__ return self.data[key.upper()] KeyError: 'OPENSHIFT_APP_NAME' OPENSHIFT_APP_NAME - environment variable (link: <https://www.openshift.com/page/openshift-environment-variables>) Can you help me? Answer: It looks like it can't find the environment variable `OPENSHIFT_APP_NAME`. You should try setting it and see if that fixes the problem. Django can't import your settings because it can't find that environment variable. Those environment variables look like they are set by openshift. You are probably running that collectstatic command in a shell that has not had them set. You'll either need to set them in the shell or edit your settings.py to be able to handle this situation. Something like this would work: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get('OPENSHIFT_APP_NAME', 'A sensible default'),
TypeError: unhashable type: 'list' (a few frames into program) Question: So as my first project in python outside of Code Academy, I decided to make a basic molecular dynamics simulator on pygame. It works fine for a while, but as soon as electrons start to move too fast, and strip all the other electrons off their atoms, I get the TypeError in the title. I have no idea where this comes from, and only appears after the program has been running long enough for me to mess up all the physics. Now I know that the error is telling me that I'm trying to pass a list somewhere I shouldn't, but I've looked over the program and can't figure out where. The error pops up in the bit that tells electrons how to orbit their atom `angle = findA(particles[el], particles[nuc]) + 0.001`, which is controlled by the block of code near the end that tells the program in which order to do physics, and the list of what each electron is meant to orbit is controlled by another point, and so on. So I decided just to give you all the code. import sys, pygame, math from pygame.locals import * pygame.init() sizeScreen = width, height = 1000, 700 sizeMenu = width, height = 652, 700 e = 1.6 * 10 ** -19 particles = {} mx, my = 0, 0 selected = [] def findOrbital(el): for a in particles: if a != el and particles[a][4] != 'el': if findD(particles[el], particles[a]) < 5 * 10 ** -11 and PTI[particles[a][4]][7] > len(particles[a][5]): particles[a][5].append(el) particles[el][5].append(a) def searcher(List, item): for a in List: if a == item: return True return False def moveAtEls(el, nuc): angle = findA(particles[el], particles[nuc]) + 0.001 particles[el][0] = particles[nuc][0] + 50 * math.cos(angle) particles[el][1] = particles[nuc][1] + 50 * math.sin(angle) def check(each): if particles[each][0] < 175: particles[each][2] = -particles[each][2] particles[each][0] = 175 elif particles[each][0] > 1000: particles[each][2] = -particles[each][2] particles[each][0] = 1000 if particles[each][1] < 0: particles[each][3] = -particles[each][3] particles[each][1] = 0 elif particles[each][1] > 700: particles[each][3] = -particles[each][3] particles[each][1] = 700 if particles[each][4] == 'el': a = 'n' findOrbital(each) if a != 'n': particles[each][5].append(a) particles[a][5].append(each) def findD(self, other): return math.hypot((self[0] - other[0]), (self[1] - other[1])) * 0.62 * 10 ** -12 def findA(self, other): return math.atan2((self[1] - other[1]), (self[0] - other[0])) def move(self): for other in particles: if particles[other] != self and self[5] != particles[other] [5] and not searcher(self[5], other): D = findD(self, particles[other]) if D == 0: self[5].append(other) particles[other][5].append(self) break angle = findA(self, particles[other]) F = 8987550000 * (PTI[self[4]][4] * PTI[particles[other][4]][4] * e ** 2)/D ** 2 a = int(F/PTI[self[4]][5]) ax = a * math.cos(angle) ay = a * math.sin(angle) self[2] += ax/(10 ** 16) self[3] += ay/(10 ** 16) self[0] += self[2]/(10 ** 8) self[1] += self[3]/(10 ** 8) pressed = '' press = {'Katom':[2,148,2,32,0],'Knuc':[2,148,36,66,0],'Kel':[2,148,70,100,0]} PTI = {'el':[0, 0, 0, 0, -1, 9.11 * 10 ** -31, pygame.image.load("electron.png"), 2], 'HNuc' : [185, 214, 8, 37, 1, 1.7 * 10 ** -27, pygame.image.load("nuc/HNuc.png"), 2, 1], 'HeNuc': [586, 613, 8, 37, 2, 6.6 * 10 ** -27, pygame.image.load("nuc/HeNuc.png"), 2, 2], 'LiNuc': [185, 214, 40, 69, 1, 1.16 * 10 ** -26, pygame.image.load("nuc/LiNuc.png"), 8, 1], 'BeNuc': [216, 246, 40, 69, 2, 1.53 * 10 ** -26, pygame.image.load("nuc/BeNuc.png"), 8, 2], 'BNuc' : [428, 457, 40, 69, 3, 1.84 * 10 ** -26, pygame.image.load("nuc/BNuc.png"), 8, 3], 'CNuc' : [460, 489, 40, 69, 4, 2.04 * 10 ** -26, pygame.image.load("nuc/CNuc.png"), 8, 4], 'NNuc' : [492, 520, 40, 69, 5, 2.38 * 10 ** -26, pygame.image.load("nuc/NNuc.png"), 8, 5], 'ONuc' : [523, 551, 40, 69, 6, 2.72 * 10 ** -26, pygame.image.load("nuc/ONuc.png"), 8, 6], 'FNuc' : [554, 583, 40, 69, 7, 3.23 * 10 ** -26, pygame.image.load("nuc/FNuc.png"), 8, 7], 'NeNuc': [586, 613, 40, 69, 8, 3.43 * 10 ** -26, pygame.image.load("nuc/NeNuc.png"), 8, 8]} menu = pygame.display.set_mode(sizeMenu) screenColor = pygame.Color(255, 255, 220) screen = pygame.display.set_mode(sizeScreen) edgeObj = pygame.image.load("edge.png") addEl = [pygame.image.load('addElectron1.png'), pygame.image.load('addElectron2.png')] addAtom = [pygame.image.load("addAtom1.png"), pygame.image.load("addAtom2.png"), pygame.image.load("atomTable.png")] addNucleus = [pygame.image.load("addNuc1.png"), pygame.image.load("addNuc2.png"), pygame.image.load("NucTable.png")] while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit(0) elif event.type == MOUSEMOTION: mx, my = event.pos mouseState = pygame.mouse.get_pressed() if mouseState[0]: for key in press: if press[key][0] < mx <press[key][1] and press[key][2] < my < press[key][3]: pressed = key press[key][4] = 1 if not mouseState[0] and pressed == 'Kel': particles[len(particles)] = [mx, my, 0, 0, 'el', []] pressed = '' press['Kel'][4] = 0 if pressed != '': if not mouseState[0]: if press[pressed][0] < mx <press[pressed][1] and press[pressed][2] < my < press[pressed][3]: press[pressed][4] = 2 pressed = '' if press['Knuc'][4] == 2 or press['Katom'][4] == 2: if mouseState[0]: if 621 < mx < 651 and 2 < my < 14: press['Knuc'][4] = 0 press['Katom'][4] = 0 if press['Knuc'][4] == 2: for nuc in PTI: if PTI[nuc][0] < mx < PTI[nuc][1] and PTI[nuc][2] < my < PTI[nuc][3]: press['Knuc'][4] = 0 selected.append(nuc) if press['Katom'][4] == 2: for nuc in PTI: if PTI[nuc][0] < mx < PTI[nuc][1] and PTI[nuc][2] < my < PTI[nuc][3]: a = 0 selected.append(nuc) while a < PTI[nuc][8]: selected.append('el') a += 1 press['Katom'][4] = 0 if selected != []: if not mouseState[0]: a = len(particles) particles[a] = [mx, my, 0, 0, selected[0], [b for b in range(a+1, len(selected)-1)]] for item in selected: if item != selected[0]: particles[len(particles)] = [mx, my, 0, 0, item, [a]] selected = [] for each in particles: check(each) move(particles[each]) check(each) if len(particles[each][5]) > 0 and particles[each][4] == 'el': moveAtEls(each, particles[each][5][0]) particles[each][5] = [] screen.fill(screenColor) for a in particles: screen.blit(PTI[particles[a][4]][6], (particles[a][0] - 29, particles[a][1] - 31)) menu.blit(edgeObj, (0, 0)) menu.blit(addNucleus[press['Knuc'][4]], (2, 2)) menu.blit(addAtom[press['Katom'][4]], (2, 2)) menu.blit(addEl[press['Kel'][4]], (2, 2)) pygame.display.flip() Sorry if I'm being a nuisance by posting all the code, but I'm a complete n00b and I'm surprised I got this far without help. I know the whole thing is untidy, but if you could help with the error I'd greatly appreciate it. Next time I'll just stick to `print("Hello, World!")` Answer: So, what I believe is happening is that when execute the line `angle = findA(particles[el], particles[nuc]) + 0.001`, either the `el` variable or the `nuc` variable is a list of some sort, rather then a single object. This throws an error because `particles` is a dict, and you cannot have a list or any mutable type as a key in a dict. So, given that this error does not execute immediately, I suspect that somewhere along the line, in a piece of code that is not immediately executed, you are accidentally passing in a `list` of some sort. * * * If you did mean to look things up in the `particles` dict by using a list as a key, then you should convert the list to a `tuple` first: tuples are like lists, but are immutable, and so can be hashed and used as a key of a dict.
sl4a python make a Toast for android phone Question: I wrote only this 3 lines in python using [SL4A](http://code.google.com/p/android-scripting/): import android droid = android.Android() droid.makeToast(u"ascc4r") When this code runs, I get the following error: pydev debugger: starting Traceback (most recent call last): File "C:\Users\Tibi\Desktop\adt-bundle-windows-x86_64-20130917\eclipse\plugins \org.python.pydev_2.8.2.2013090511\pysrc\pydevd.py", line 1446, in <module> debugger.run(setup['file'], None, None) File "C:\Users\Tibi\Desktop\adt-bundle-windows-x86_64-20130917\eclipse\plugins org.python.pydev_2.8.2.2013090511\pysrc\pydevd.py", line 1092, in run pydev_imports.execfile(file, globals, locals) #execute the script File "C:\Users\Tibi\workspace\26\src\26module.py", line 7, in <module> droid = android.Android() File "C:\Python26\lib\android.py", line 34, in __init__ self.conn = socket.create_connection(addr) File "C:\Python26\lib\socket.py", line 547, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): socket.gaierror: [Errno 11001] getaddrinfo failed Environment setup: \- Python 2.6.6 \- set ap_port=9999 \- adb forward tcp:9999 tcp:xxxx (xxxx where I started the server on the phone) My android.py is in the Python/Lib folder. Update: I tried this 3 instruction in CMD and it's work, making a Toast. So I think the fault is in the ADT bundle, or Eclipse Python plugin. What is this Errno 11001? Answer: > What is this Errno 11001? I don't know about that error, but I suggest to use the correct syntax which is import android droid = android.Android() droid.makeToast('my text to print should be inside the quotes') see also the [API Overview](http://code.google.com/p/android- scripting/wiki/AndroidFacadeAPI)
Python 'shelve' that writes itself to disk after each operation Question: I'm doing a project in Python that involves a lot of interactive work with a persistent dictionary. If I weren't doing interactive development, I could use contextlib.closing and be fairly confident that the shelf would get written to disk eventually. But as it stands there's no chunk of code that I can easily wrap within a 'with' statement. I'd prefer not to have to trust myself to call close() on my shelf at the end of a session. The amount of data involved is not large, and I would happily sync a shelf to disk after each operation. I've found myself writing a wrapper for shelve that does just that but I'm not a strong enough Python programmer to identify the correct set of dict methods that I'd need to override. And it seems to me that if what I'm doing is a good idea, it's probably been done before. What is the paradigmatically correct way to handle this? I'll add that I like using shelve because it's a simple module, and it comes with Python. If possible I'd prefer to avoid doing something that requires (for example) pulling in a complicated library for dealing with databases. I'm using WinXP with SP3, Python 2.7.5 via Anaconda 1.6.2 (32-bit), and running inside Spyder. I can tell by looking at the modified times for the file backing my shelf that the shelf isn't updating until I call sync or close. Answer: What you can do is subclass `DbfilenameShelf` and override `__setitem__` and `__delitem__` to automatically sync after each change. Something like this would probably work (untested): from shelve import DbfilenameShelf class AutoSyncShelf(DbfilenameShelf): # default to newer pickle protocol and writeback=True def __init__(self, filename, protocol=2, writeback=True): DbfilenameShelf.__init__(self, filename, protocol=protocol, writeback=writeback) def __setitem__(self, key, value): DbfilenameShelf.__setitem__(self, key, value) self.sync() def __delitem__(self, key): DbfilenameShelf.__delitem__(self, key) self.sync() my_shelf = AutoSyncShelf("myshelf") I can't vouch for the performance of this, of course.
Python coding - list index out of range Question: lots of code up here ... if c==excelfiles[1]: b ==excelfiles[1] wb = xlrd.open_workbook(a) wb.sheet_names() sh = wb.sheet_by_index(0) for rownum in range(sh.nrows): print sh.row_values(rownum) for i in range(sheet.nrows): cashflow = [sheet.cell_value(i,0)],[sheet.cell_value(i,1)],[sheet.cell_value(i,2)] print cashflow def npv(rate, cashflow): value = cashflow[1] * ((1 + rate/100) ** (12 - cashflow[0])) FV = 0 FV += value return FV def irr(cashflow, iterations = 100): rate = 1.0 i = 0 while (cashflow[0][1] == 0): i += 1 investment = cashflow[i][1] for i in range(1, iterations+1): rate *= (1 - (npv(rate, cashflow) / investment)) return rate r = irr(cashflow) print r Error/Output: File "<pyshell#90>", line 1, in <module> import quarterZ File "quarterZ.py", line 65, in <module> r = irr(cashflow) # why is list index out of range? File "quarterZ.py", line 56, in irr while (cashflow[0][1] == 0): IndexError: list index out of range Can someone please explain why my list index is out of range? And can you show me how to fix this? I am relatively new to python so I'm sure it's a stupid mistake. Thanks so much! I've also attached the code here: <http://ideone.com/G5hGuK> Answer: `cashflow[0]` is set to `[sheet.cell_value(i,0)]` in your for loop on line 10, which is a list with length 1. The expression `cashflow[0][1]` is trying to read the second value in that list.
More elegant/Pythonic way of printing elements of tuple? Question: I have a function which returns a large set of integer values as a tuple. For example: def solution(): return 1, 2, 3, 4 #etc. I want to elegantly print the solution without the tuple representation. (i.e. parentheses around the numbers). I tried the following two pieces of code. print ' '.join(map(str, solution())) # prints 1 2 3 4 print ', '.join(map(str, solution())) # prints 1, 2, 3, 4 They both work but they look somewhat ugly and I'm wondering if there's a better way of doing this. Is there a way to "unpack" tuple arguments and pass them to the `print` statement in Python 2.7.5? I would really love to do something like this: print(*solution()) # this is not valid syntax in Python but I wish it was kind of like tuple unpacking so that it's equivalent to: print sol[0], sol[1], sol[2], sol[3] # etc. Except without the ugly indexes. Is there any way to do that? I know this is a stupid question because I'm just trying to get rid of parentheses but I was just wondering if there was something I was missing. Answer: `print(*solution())` actually _can be_ valid on python 2.7, just put: from __future__ import print_function On the top of your file. You could also iterate through the tuple: for i in solution(): print i, This is equivalent to: for i in solution(): print(i, end= ' ') If you ever use Python 3 or the import statement above.
Python: Print using ascii codes Question: I'm a beginner in python and I'm having a problem in this program: Here's the NodeList first: class Node: def __init__(self,initdata): self.data = initdata self.next = None def getData(self): return self.data def getNext(self): return self.next def setData(self,newdata): self.data = newdata def setNext(self,newnext): self.next = newnext My problem is in this program: (The print) from NodeList import Node class StackLL: def __init__(self): self.head = None def pushSLL(self,item): temp = Node(str(item)) temp.setNext(self.head) self.head = temp node = self.head print(chr(0x2510)+(chr(0x0000)*(len(item)))+chr(0x250c)) while node!=None: stackeditem = chr(0x2502)+node.data+chr(0x2502) print(stackeditem) node = node.next print(chr(0x2514)+(chr(0x2500)*(len(item)-1))+chr(0x2518)) ![here's the output](http://i.stack.imgur.com/ssB7D.jpg) Everytime I print, the lines just seems off. I tried to experiment using len() just to make it accurate, but everytime the item adds more characters it gets off again. Any help would be greatly appreciated. Thank you. Answer: Use a monospace font in IDLE settings and you are all good.
Getting different result in different runs with multithreading Question: why when the code executed, the result different every time? i tried to follow how the code is executed, and i confused, i feel this is not sense. and the result appear randomly every time #!/usr/bin/python import Queue import threading import time exitFlag = 0 class myThread (threading.Thread): def __init__(self, threadID, name, q): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.q = q def run(self): print "Starting " + self.name process_data(self.name, self.q) print "Exiting " + self.name def process_data(threadName, q): while not exitFlag: queueLock.acquire() if not workQueue.empty(): data = q.get() queueLock.release() print "%s processing %s" % (threadName, data) else: queueLock.release() time.sleep(1) threadList = ["Thread-1", "Thread-2", "Thread-3"] nameList = ["One", "Two", "Three", "Four", "Five"] queueLock = threading.Lock() workQueue = Queue.Queue(10) threads = [] threadID = 1 # Create new threads for tName in threadList: thread = myThread(threadID, tName, workQueue) thread.start() threads.append(thread) threadID += 1 # Fill the queue queueLock.acquire() for word in nameList: workQueue.put(word) queueLock.release() # Wait for queue to empty while not workQueue.empty(): pass # Notify threads it's time to exit exitFlag = 1 # Wait for all threads to complete for t in threads: t.join() print "Exiting Main Thread" code source <http://www.tutorialspoint.com/python/python_multithreading.htm> * * * **update** Sorry, i mean the order of result like this: Starting Thread-1 Starting Thread-2 Starting Thread-3 Thread-3 processing One Thread-2 processing Two Thread-1 processing Three Thread-3 processing Four Thread-2 processing Five Exiting Thread-1 Exiting Thread-3 Exiting Thread-2 Exiting Main Thread [Finished in 3.0s] and when try again, the result Starting Thread-1 Starting Thread-2 Starting Thread-3 Thread-3 processing One Thread-2 processing Two Thread-1 processing Three Thread-3 processing Four Thread-3 processing Five Exiting Thread-1 Exiting Thread-2 Exiting Thread-3 Exiting Main Thread [Finished in 3.0s] Answer: I assume, by "result" you mean the execution order. One idea behind mutithreading is, that you don't have to care about execution order unless you want to specify it explicitely. You are totally dependent on the underlying operating system, system load, ... etc.
Python, OpenCV: classify gender using ORB features and KNN Question: **Task:** Classify images of human faces as female or male. Training images with labels are available, obtain the test image from webcam. **Using:** Python 2.7, OpenCV 2.4.4 I am using ORB to extract features from a grayscale image which I hope to use for training a K-Nearest Neighbor classifier. Each training image is of a different person so the number of keypoints and descriptors for each image are obviously different. My problem is that I'm not able to understand the OpenCV docs for KNN and ORB. I've seen other SO questions about ORB, KNN and FLANN but they didn't help much. What exactly is the nature of the descriptor given by ORB? How is it different than descriptors obtained by BRIEF, SURF, SIFT, etc.? It seems that the feature descriptors should be of the same size for each training sample in KNN. How do I make sure that the descriptors are of the same size for each image? More generally, in what format should features be presented to KNN for training with given data and labels? Should the data be an int or float? Can it be char? The training data can be found [here](https://drive.google.com/folderview?id=0B2AJ7rliSQubRmRXd2dJa0pXTnc&usp=sharing). I am also using the `haarcascade_frontalface_alt.xml` from opencv samples Right now the KNN model is given just 10 images for training to see if my program passes without errors which, it does not. Here is my code: import cv2 from numpy import float32 as np.float32 def chooseCascade(): # TODO: Option for diferent cascades # HAAR Classifier for frontal face _cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') return _cascade def cropToObj(cascade,imageFile): # Load as 1-channel grayscale image image = cv2.imread(imageFile,0) # Crop to the object of interest in the image objRegion = cascade.detectMultiScale(image) # TODO: What if multiple ojbects in image? x1 = objRegion[0,0] y1 = objRegion[0,1] x1PlusWidth = objRegion[0,0]+objRegion[0,2] y1PlusHeight = objRegion[0,1]+objRegion[0,3] _objImage = image[y1:y1PlusHeight,x1:x1PlusWidth] return _objImage def recognizer(fileNames): # ORB contructor orb = cv2.ORB(nfeatures=100) keyPoints = [] descriptors = [] # A cascade for face detection haarFaceCascade = chooseCascade() # Start processing images for imageFile in fileNames: # Find faces using the HAAR cascade faceImage = cropToObj(haarFaceCascade,imageFile) # Extract keypoints and description faceKeyPoints, faceDescriptors = orb.detectAndCompute(faceImage, mask = None) #print faceDescriptors.shape descRow = faceDescriptors.shape[0] descCol = faceDescriptors.shape[1] flatFaceDescriptors = faceDescriptors.reshape(descRow*descCol).astype(np.float32) keyPoints.append(faceKeyPoints) descriptors.append(flatFaceDescriptors) print descriptors # KNN model and training on descriptors responses = [] for name in fileNames: if name.startswith('BF'): responses.append(0) # Female else: responses.append(1) # Male knn = cv2.KNearest() knnTrainSuccess = knn.train(descriptors, responses, isRegression = False) # isRegression = false, implies classification # Obtain test face image from cam capture = cv2.VideoCapture(0) closeCamera = -1 while(closeCamera < 0): _retval, _camImage = capture.retrieve() # Find face in camera image testFaceImage = haarFaceCascade.detectMultiScale(_camImage) # TODO: What if multiple faces? # Keyponts and descriptors of test face image testFaceKP, testFaceDesc = orb.detectAndCompute(testFaceImage, mask = None) testDescRow = testFaceDesc.shape[0] flatTestFaceDesc = testFaceDesc.reshape(1,testDescRow*testDescCol).astype(np.float32) # Args in knn.find_nearest: testData, neighborhood returnedValue, result, neighborResponse, distance = knn.find_nearest(flatTestFaceDesc,3) print returnedValue, result, neighborResponse, distance # Display results # TODO: Overlay classification text cv2.imshow("testImage", _camImage) closeCamera = cv2.waitKey(1) cv2.destroyAllWindows() if __name__ == '__main__': fileNames = ['BF09NES_gray.jpg', 'BF11NES_gray.jpg', 'BF13NES_gray.jpg', 'BF14NES_gray.jpg', 'BF18NES_gray.jpg', 'BM25NES_gray.jpg', 'BM26NES_gray.jpg', 'BM29NES_gray.jpg', 'BM31NES_gray.jpg', 'BM34NES_gray.jpg'] recognizer(fileNames) Currently I am getting an error at the line with `knn.train()` where `descriptors` is not detected as a numpy array. Also, is this approach completely wrong? Am I supposed to use some other way for gender classification? I wasn't satisfied with the fisherface and eigenface example in the opencv facerec demo so please don't direct me to those. Any other help is much appreciated. Thanks. **\--- EDIT ---** I've tried a few things and come up with an answer. I am still hoping that someone in SO community can help me by suggesting an idea so that I don't have to hardcode things into my solution. I also suspect that knn.match_nearest() isn't doing what I need it to do. And as expected, the recognizer is not at all accurate and very prone to giving misclassification due to rotation, lighting, etc. Any suggestions on improving this approach would be really appreciated. The database I am using for training is: [Karolinska Directed Emotional Faces](http://www.emotionlab.se/resources/kdef) Answer: i have some doubts on the effectiveness/workability of the described approach. here's a another approach that you might want to consider. the contents of `gen` folder is @ <http://www1.datafilehost.com/d/0f263abc>. as you will note when the data size gets bigger(~10k training samples), the size of the model may become unacceptable(~100-200mb). then you will need to look into pca/lda etc. import cv2 import numpy as np import os def feaCnt(): mat = np.zeros((400,400,3),dtype=np.uint8) ret = extr(mat) return len(ret) def extr(img): return sobel(img) def sobel(img): gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) klr = [[-1,0,1],[-2,0,2],[-1,0,1]] kbt = [[1,2,1],[0,0,0],[-1,-2,-1]] ktb = [[-1,-2,-1],[0,0,0],[1,2,1]] krl = [[1,0,-1],[2,0,-2],[1,0,-1]] kd1 = [[0,1,2],[-1,0,1],[-2,-1,0]] kd2 = [[-2,-1,0],[-1,0,1],[0,1,2]] kd3 = [[0,-1,-2],[1,0,-1],[2,1,0]] kd4 = [[2,1,0],[1,0,-1],[0,-1,-2]] karr = np.asanyarray([ klr, kbt, ktb, krl, kd1, kd2, kd3, kd4 ]) gray=cv2.resize(gray,(40,40)) res = np.float32([cv2.resize(cv2.filter2D(gray, -1,k),(15,15)) for k in karr]) return res.flatten() root = 'C:/data/gen' model='c:/data/models/svm/gen.xml' imgs = [] idx =0 for path, subdirs, files in os.walk(root): for name in files: p =path[len(root):].split('\\') p.remove('') lbl = p[0] fpath = os.path.join(path, name) imgs.append((fpath,int(lbl))) idx+=1 samples = np.zeros((len(imgs),feaCnt()),dtype = np.float32) labels = np.zeros(len(imgs),dtype = np.float32) i=0. for f,l in imgs: print i img = cv2.imread(f) samples[i]=extr(img) labels[i]=l i+=1 svm = cv2.SVM() svmparams = dict( kernel_type = cv2.SVM_POLY, svm_type = cv2.SVM_C_SVC, degree=3.43, gamma=1.5e-4, coef0=1e-1, ) print 'svm train' svm.train(samples,labels,params=svmparams) svm.save(model) print 'done' result = np.float32( [(svm.predict(s)) for s in samples]) correct=0. total=0. for i,j in zip(result,labels): total+=1 if i==j: correct+=1 print '%f'%(correct/total)
Python logging root handler does not capture all Question: I've got an issue with a root logger which I expected to work as a catch-all logger for anything that doesn't match other places. It's not working as I expected however. Here's a simplified logging configuration I use: [loggers] keys = root, specific [handlers] keys = syslog [formatters] keys = default [logger_root] level = WARNING handlers = syslog [logger_specific] level = DEBUG handlers = syslog qualname = specific [handler_syslog] class = handlers.SysLogHandler args = (('localhost',514), handlers.SysLogHandler.LOG_LOCAL0) formatter = default [formatter_default] format = %(message)s Now when I log anything from a module called `specific.something.else`, it gets logged properly. If I log from a `different.module`, I don't get that line at all. I can add more of the "specific" loggers and they capture the additional messages just fine... but how can I make the root logger a "catch- all" one? I was under the impression that it should do that role by default. Answer: It's probably because your `different.module` loggers were created _before_ the `fileConfig` call, which results in those loggers being disabled in the call. You need to ensure that you call `fileConfig` with `disable_existing_loggers=False`, and be running Python 2.6 or later so that you can use this keyword argument. If you can't do this, you'll need to avoid creating any loggers (other than those which are named, or whose ancestors are named, in the configuration) until _after_ `fileConfig` has been called. See also [this answer](http://stackoverflow.com/questions/9608717/incompatibility-between- import-time-logger-naming-with-logging-configuration).
Python BeautifulSoup Ampersand issue Mac vs. Linux Ubuntu Question: I've read that BeautifulSoup has problems with ampersands (&) which are not strictly correct in HTML but still interpreted correctly by most browsers. However weirdly I'm getting different behaviour on a Mac system and on a Ubuntu system, both using bs4 version 4.3.2: html='<td>S&P500</td>' s=bs4.BeautifulSoup(html) On the Ubuntu system s is equal to: <td>S&amp;P500;</td> Notice the added semicolon at the end which is a real problem On the mac system: <html><head></head><body>S&amp;P500</body></html> Never mind the html/head/body tags, I can deal with that, but notice S&P 500 is correctly interpreted this time, without the added ";". Any idea what's going on? How to make cross-platform code without resorting to an ugly hack? Thanks a lot, Answer: First I can't reproduce the mac results using python2.7.1 and beautifulsoup4.3.2, that is I am getting the extra semicolon on all systems. The easy fix is a) use strictly valid HTML, or b) add a space after the ampersand. Chances are you can't change the source, and if you could parse out and replace these in python you wouldn't be needing BeautifulSoup ;) So the problem is that the BeautifulSoupHTMLParser first converts `S&P500` to `S&P500;` because it assumes `P500` is the character name and you just forgot the semicolon. Then later it reparses the string and finds `&P500;`. Now it doesn't recognize `P500` as a valid name and converts the `&` to `&amp;` without touching the rest. Here is a stupid monkeypatch **only to demonstrate my point**. I don't know the inner workings of BeautifulSoup well enough to propose a proper solution. from bs4 import BeautifulSoup from bs4.builder._htmlparser import BeautifulSoupHTMLParser from bsp.dammit import EntitySubstitution def handle_entityref(self, name): character = EntitySubstitution.HTML_ENTITY_TO_CHARACTER.get(name) if character is not None: data = character else: # Previously was # data = "&%s;" % name data = "&%s" % name self.handle_data(data) html = '<td>S&P500</td>' # Pre monkeypatching # <td>S&amp;P500;</td> print(BeautifulSoup(html)) BeautifulSoupHTMLParser.handle_entityref = handle_entityref # Post monkeypatching # <td>S&amp;P500</td> print(BeautifulSoup(html)) Hopefully someone more versed in bs4 can give you a proper solution, good luck.
Downloading PDF's with Webdriver Question: I am trying to download pdfs with selenium webdriver with python bindings on OS X 10.8. I actually need the pdf file, not just check if it the download link works. As I understand it, I need to set the firefox profile to download the pdf content type, rather than 'preview' which is the default. My code to open an instance of firefox is: def Engage(): print "Start Up FIREFOX" ## Create a new instance of the Firefox driver profile = webdriver.firefox.firefox_profile.FirefoxProfile() profile.set_preference('browser.download.folderList', 2) profile.set_preference('browser.download.dir', os.path.expanduser("~/Documents/PYTHON/Download_Files/tmp/")) profile.set_preference('browser.helperApps.neverAsk.saveToDisk', ('application/pdf')) driver = webdriver.Firefox(firefox_profile=profile) return driver I have also tried initially setting the profile as : profile = webdriver.FirefoxProfile() ## replacing :: profile = webdriver.firefox.firefox_profile.FirefoxProfile() ## the other attributes remained This has the same results This profile opens the pdf in preview mode in a new window, rather than download it. I double checked the content type through requests and was able to confirm it as "application/pdf": import requests print requests.head('mywebsite.com').headers['content-type'] Any idea of what I am doing wrong? Answer: Was facing a similar situation sometime back. Solution is quite easy. By default the settings in firefox opens pdf files rather than allowing you to download it. To overcome this type config:about in the browser and type pdfjs.disabled double click on the option. The value should change from false to true. Restart the browser and try opening any pdf file. It will download the file instead of opening it in the browser. Happy coding.
Seeming discrepancy in shutil.disk_usage() Question: Hello StackOverflow folks, Longtime reader, first time poster. Hopefully I've got all the info here to make a useful question. I am using the shutil.disk_usage() function to find the current disk usage of a particular path (amount available, used, etc.). As far as I can find, this is a wrapper around os.statvfs() calls. I'm finding that it is not giving the answers I'd expect, as comparing to the output of "du" in Linux. I have obscured some of the paths below for company privacy reasons, but the output and code are otherwise undoctored. I am using Python 3.3.2 64-bit version. #!/apps/python/3.3.2_64bit/bin/python3 # test of shutils.diskusage module import shutil BytesPerGB = 1024 * 1024 * 1024 (total, used, free) = shutil.disk_usage("/data/foo/") print ("Total: %.2fGB" % (float(total)/BytesPerGB)) print ("Used: %.2fGB" % (float(used)/BytesPerGB)) (total1, used1, free1) = shutil.disk_usage("/data/foo/utils/") print ("Total: %.2fGB" % (float(total1)/BytesPerGB)) print ("Used: %.2fGB" % (float(used1)/BytesPerGB)) Which outputs: /data/foo/drivecode/me % disk_usage_test.py Total: 609.60GB Used: 291.58GB Total: 609.60GB Used: 291.58GB As you can see, the main problem is I would expect the second amount for "Used" to be much smaller, as it is a subset of the first directory. /data/foo/drivecode/me % du -sh /data/foo/utils 2.0G /data/foo/utils As much as I trust "du," I find it hard to believe the Python module would be incorrect either. So perhaps it is just my understanding of Linux filesystems that could be the issue. :) I wrote a module (based heavily on someone's code here at SO) which recursively gets the disk_usage, which I was using until now. It appears to match the "du" output but is MUCH, much slower than the shutil.disk_usage() function, so I'm hoping I can make that one work. Thanks much in advance. Answer: The problem is that shutil uses the [`statvfs`](http://man7.org/linux/man- pages/man2/statvfs.2.html) system call underneath to determine the space used. This system call has no file-path granularity as far as I'm aware, only file- system granularity. What this means is that the path you provide it with only helps to identify the file system you want to query, not the path's. In other words, you gave it the path `/data/foo/utils` and then it determined which file system backs this file path. Then it queried _the file system_. This becomes apparent when you consider how the `used` parameter is defined in shutil: used = (st.f_blocks - st.f_bfree) * st.f_frsize Where: fsblkcnt_t f_blocks; /* size of fs in f_frsize units */ fsblkcnt_t f_bfree; /* # free blocks */ unsigned long f_frsize; /* fragment size */ This is why it's giving you the _total_ space used on the entire file system. Indeed, it seems to me like the `du` command itself also traverses the file structure and adds up the file sizes. Here is GNU coreutils `du` command's [source code](https://github.com/goj/coreutils/blob/rm-d/src/du.c).
python + opencv "dll load failed" Question: I'm trying to install opencv on my machine as explained in the book: "Packtpub OpenCV Computer Vision with Python Apr 2013" It says that in order to run kinect you need to compile openCV with some stuff in it, so I downloaded openCV .exe that extracts to a 3.2gb folder and proceeded with all the steps... Used CMaker, used the compiler MinGW, and everything as the book said Than it tells me to try running some examples... but when I try to run drawing.py as recommended by the book, and all the others, it says: python drawing.py * * * OpenCV Python version of drawing traceback< most recent call last>: File "drawing.py", line 7, in import cv2.cv as cv ImportError: DLL load failed: Invalid access to memory location. * * * I saw a lot of people saying this problem is fixed by adding the path to the bin of openCV dlls to path... how do I find out which dll name is missing so I can find the name of it and find the folder where it is? I have a x64 computer but the book tells me to install everything x86 because it is harder to get some minor bugs, maybe a version incompatibility between openCV, compiler, cmaker, and python? I've tried to add a lot of folders to "path" variable and it didn't work please tell me how I find out which dlls are missing so I can search for them on the computer or some other way to solve this problem because I'm just out of ideas Answer: I don't have a high enough rep to add a comment otherwise I would but something you can do is start python with the -v option. doing that will add a bit more to the output console and it will cause the python VM to output where it is looking for things when it tries looking for things, especially when failures occur. I've found that to be helpful when trying to hunt problems such as path problems down. It also sounds like you haven't got your paths setup correctly. Have you looked at [ImportError: DLL load failed: %1 is not a valid Win32 application](http://stackoverflow.com/questions/14629818/importerror-dll-load- failed-1-is-not-a-valid-win32-application?rq=1) ? If a DLL was expected in a certain location but wasn't loaded or present but then 'called' via a LoadLibrary (without checking to see if it was actually loaded) that might cause such an error. It is probably the fault of the original DLL that failed to verify the subsequent DLL was loaded instead of just assuming the LoadLibrary call succeeded. In addition to the python -v yourmodule.py option you could also try running an strace (if you are on unix -- but it doesn't sound like you are). I used to use SoftICE on Windows for digging down deep. If you know the package or the DLL that is at the root of the problem, and have access to a dll export tool, you should be able to get a list of the dependencies the dll needs (external functions it relies on). Then you just need to know or find those functions it relies on from other DLLs. It's been awhile since I used to had do this sort of stuff all the time to locate functions in other DLLs but it is something that is entirely doable from a spelunkers perspective. But there are probably easier ways to go about it. I'd start with the python -v approach first.
Generating a random email using python 3.2 Question: I would like to generate a 64 letter for a random email. There are a few restriction so as to follow the email syntax. But I am not sure why doesnt my output display anything. Is there something wrong with my if statement? import random y=" " for x in range (0,64): z = random.randint(33,127) if z in [32,34,40,41,44,58,59,60,62,64,91,92,93] == False: b = chr(z) print(b) Answer: This: if z in [32,34,40,41,44,58,59,60,62,64,91,92,93] == False: is equivalent to: if z in [32,34,40,41,44,58,59,60,62,64,91,92,93] and [32,34,40,41,44,58,59,60,62,64,91,92,93] == False: which never evaluates to True, you probably meant to do: if z not in [32,34,40,41,44,58,59,60,62,64,91,92,93]:
Conflicting versions of python in ubuntu Question: So i had python 2.7.2 on my server and i needed to update it to python 2.7.3. So i've tried to remove the 2.7.2 version and then install the new one using the sources. I wasn't able to remove the 2.7.2 version cause the system uses it to run crucial services on server, so i installed the 2.7.3 version in hope that after that i would be able to remove the old version. Still i cant remove the old version, although i'm able to execute the python 2.7.3 when i install any module i cant import it. I added the path to sys.path and i started finding the module but importing it causes another errors. My python executes the /usr/local/bin/python which is the 2.7.3 version where the problems are. If i try to execute python like this /usr/bin/python it executes the old version and everything works fine there, i can import the new installed modules. So what can i do to make python 2.7.3 work? I've searched a lot of tutorials and tried things like add the library in .pth files on python and i started finding the modules but when importing it i get errors like this: >>> import numpy Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/numpy/__init__.py", line 137, in <module> import add_newdocs File "/usr/local/lib/python2.7/dist-packages/numpy/add_newdocs.py", line 9, in <module> from numpy.lib import add_newdoc File "/usr/local/lib/python2.7/dist-packages/numpy/lib/__init__.py", line 4, in <module> from type_check import * File "/usr/local/lib/python2.7/dist-packages/numpy/lib/type_check.py", line 8, in <module> import numpy.core.numeric as _nx File "/usr/local/lib/python2.7/dist-packages/numpy/core/__init__.py", line 5, in <module> import multiarray ImportError: /usr/local/lib/python2.7/dist-packages/numpy/core/multiarray.so: undefined symbol: PyUnicodeUCS4_AsUnicodeEscapeString Thanks for the help EDIT PROBLEM SOLvED So to solve the missing import modules i created a .pth file under /usr/local/lib/python2.7/site-packages/ with the directories where the python modules are and the python starts to find them. To fix the comptability problems you can install python from sources and specify the unicode doing ./configure --enable-unicode more information [here](http://bytes.com/topic/python/answers/163553-undefined-symbol- pyunicodeucs4) Answer: Do not EVER mess with system python, EVER. What you should do is install python 2.7.3 with a --prefix into your home directory, then use `virtualenv -p /home/myuser/path/to/python`. In any case, using virtualenv to run your own application is almost always a good idea, as it avoids polluting the system package directories with libraries you use in your own applications.
Python lxml and parsing a subtree Question: I've got a xml which looks like this: <root> <foo> <a></a> <b></b> <c></c> </foo> <bars> <bar> <one>interesting</one> <two>interesting</two> <three>interesting</three> </bar> <bar> <one>interesting</one> <two>interesting</two> <three>interesting</three> </bar> <bar> <one>interesting</one> <two>interesting</two> <three>interesting</three> </bar> </bars> <root> I want to extract the interesting text from all the bars. Can you tell me how to start? I've tried to use bars = etree.iterparse(xml_data, tag="bars") but I couldn't iterate through it. Answer: Use `findall` method to return all matching elements. xml_data = '''<?xml version='1.0' encoding='ASCII' ?> <root> <foo> <a></a> <b></b> <c></c> </foo> <bars> <bar> <one>interesting</one> <two>interesting</two> <three>interesting</three> </bar> <bar> <one>interesting</one> <two>interesting</two> <three>interesting</three> </bar> <bar> <one>interesting</one> <two>interesting</two> <three>interesting</three> </bar> </bars> </root> ''' from lxml import etree root = etree.fromstring(xml_data) for bars in root.findall('.//bars'): print(etree.tostring(bars, method='text'))
TCL in Python: can't find package Question: I am trying to run a TCL script from python. There is a very specific TCL package embedded in some software I am using and I need to tell the python interpreter (or TKinter ?) where this package is. Here is what I have tried so far. >>> import Tkinter >>> r = Tkinter.Tk() >>> r.tk.eval('lappend auto_path C:/Program Files (x86)/Ixia/IxNetwork/7.0-EA/tcl8.4/bin') >>> r.tk.eval('lappend auto_path C:\\Program Files (x86)\\Ixia\\IxNetwork\7.0-EA\\tcl8.4\\bin\\') '{C:\\Python26\\tcl\\tcl8.5} C:/Python26/tcl C:/lib {C:\\Python26\\tcl\\tk8.5} {C:\\Python26\\tcl\\tk8.5/ttk} C:/Program Files (x86)/Ixia/IxNetwork/7.0-EA/tcl8.4/bin C:Program Files (x86)IxiaIxNetwork\x07.0-EA\\tcl8.4\x08in\\\\' I want to use the following TCL shell which I copied from the windows start menu: "C:\Program Files (x86)\Ixia\IxOS\6.40-EA\TclScripts\bin\wish84.exe" "C:\Program Files (x86)\Ixia\IxOS\6.40-EA\TclScripts\bin\IxiaWish.tcl" Firstly, can someone tell me why there are two items being referred to in the start menu shortcut target? Will I be able to access this for my TCL in python? As you can see from above, I have tried appending this package to the auto_path, but there are problems with characters. Does anyone know why the characters are mixed up? Answer: I don't understand what you are trying to accomplish. If all you want to do is to execute the following command: "C:\Program Files (x86)\Ixia\IxOS\6.40-EA\TclScripts\bin\wish84.exe" "C:\Program Files (x86)\Ixia\IxOS\6.40-EA\TclScripts\bin\IxiaWish.tcl" Then why not use `subprocess`? Something along this line: import subprocess command = [ r'C:\Program Files (x86)\Ixia\IxOS\6.40-EA\TclScripts\bin\wish84.exe', r'C:\Program Files (x86)\Ixia\IxOS\6.40-EA\TclScripts\bin\IxiaWish.tcl' ] p = subprocess.Popen(commands, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate()
How to convert occurence matrix to co-occurence matrix in Python Question: I asked this question here: [How to convert occurence matrix to co-occurence matrix](http://stackoverflow.com/questions/19253300/how-to-convert-occurence- matrix-to-co-occurence-matrix) I realized that my data is so big that it is not possible to do this using R. My computer hangs. The actual data is a text file with ~5 million rows and 600 columns. I think Python may be an alternate option to do this. Answer: This would be the way you translate the `R` code to `Python` code. >>> import numpy as np >>> a=np.array([[0, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 1], [1, 1, 1, 1, 0, 0], [1, 1, 1, 0, 1, 1]]) >>> acov=np.dot(a.T, a) >>> acov[np.diag_indices_from(acov)]=0 >>> acov array([[0, 2, 2, 1, 1, 1], [2, 0, 2, 1, 2, 2], [2, 2, 0, 2, 1, 2], [1, 1, 2, 0, 0, 1], [1, 2, 1, 0, 0, 2], [1, 2, 2, 1, 2, 0]]) However, you have a very big dataset. If you don't want to assemble the co- occurence matrix piece by piece and you store your values in `int64`, with 3e+9 numbers it will take 24GB of RAM alone just to hold the data <http://www.wolframalpha.com/input/?i=3e9+>*+8+bytes. So you probably want to think over and decide which `dtype` you want to store your data in: <http://docs.scipy.org/doc/numpy/user/basics.types.html>. Using `int16` probably will make the `dot` product operation possible on a decent desktop PC nowadays.
tab delimited to csv Question: I am able to get this to output my MYSQL command which I have removed for security, however I keep getting an error when I try and write this tab delimited output to a CSV. Any help to boost the Python rookie would be appreciated. #!/usr/bin/pytho import sys, csv import MySQLdb import os import mysql.connector import subprocess import string if __name__ == '__main__': du = sys.argv[1] csv_home = '/home/oatey/bundle_' + du + '.csv' input = sys.stdin output = sys.stdout #read and rewrite to file with arguement new = open("/home/oatey/valid.sql2", "w") with open("/home/oatey/bundle.sql")as write_query: #read_file = write_query.read() for line in write_query: lr = line.replace('{$$}', du) print lr new.write(lr) new.close() write_query.close() with open("/home/oatey/valid.sql2") as w: mysql_output = subprocess.check_output(MYSQL_COMMAND, stdin=w) #print mysql_output b = open("/home/oatey/" + du + ".txt", "r+") #",".join("%s" % i for i in mysql_output b.write(mysql_output) print mysql_output b.close() #read tab-delimited file with open("/home/oatey/" + du + ".txt", 'rb') as data: cr = data.readlines() contents = [line for line in cr] with open("/home/oatey/" + du + ".csv", "wb") as wd: cw = csv.writer(wd, quotechar='', quoting=csv.QUOTE_NONE) wd.write(contents) Answer: I bet the error you are getting is: > TypeError: must be string or buffer, not list `contents` is a list, you cannot write a list via `write()`. Quote from [docs](http://docs.python.org/2/library/stdtypes.html#file.write): > file.write(str) > > Write a string to the file. Instead, use [csvwriter.writerows()](http://docs.python.org/2/library/csv.html#csv.csvwriter.writerows): with open("/home/oatey/" + du + ".csv", "wb") as wd: cw = csv.writer(wd, quotechar='', quoting=csv.QUOTE_NONE) cw.writerows(contents)
Unintented multithreading in python (scikit-learn) Question: I'm using mixture submodule of sklearn module for Gaussian Mixture Model... When I run my code on a multicore system, it uses multiple cores even though I do not ask for it in the code. Is this a default behavior? And more important, how can I disable it? Thanks Answer: thanks @prgao the answer is there [Python: How do you stop numpy from multithreading?](http://stackoverflow.com/questions/17053671/python-how-do- you-stop-numpy-from-multithreading) setting "export MKL_NUM_THREADS=1" seems to be working
How i should store simple objects using python and redis? Question: Lets suppose that I have a lot of(hundreds) _big_ python dictionaries. Pickled file size is about 2Mb. I want to draw chart using data from this dictionaries so i have to load them all. What is the most efficent (at first speed, at second memory) way to store my data? May be I should use another caching tool? This how i am solving this task now: 1. Pickle every my dictionary. Just pickle(dict) 2. Load the pickled string to redis. redis.set(key, dict) 3. When user needs chart, i am creating array and fill it with unpickled data from redis. Just like that: array = [] for i in range(iteration_count): array.append(unpickle(redis.get(key))) Now i have both problems: with memory, cause my array is very big, but its not important and easy to solve. The main problem - speed. A lot of objects unpickling more than 0.3 seconds. I even have bottlenecks with more than 1 second unpickling time. And getting this string from redis rather expensive (more than 0.01 sec). When i have lots of objects, my user have to wait a lot of seconds. Answer: If it can be assumed that you are asking in the context of a web application and that you are displaying your charts in a browser, I would definitely recommend storing your dictionaries as JSON in redis. Again, you have not provided too many details about your application, but I have implemented charting over very large data sets before (100,000's of sensor data points per second over several minutes of time). To help performance when rendering the datasets, I stored each type of data into their own dictionary or 'series'. This strategy allows you to render only portions of the data as required. Perhaps if you share more about your particular application we may be able to provide more help.
How to solve UnicodeDecodeError in mezzanine? Question: I am using mezzanine cms. When I scrap the data from the blogspot I got this error blog_id: sanavitastudio Traceback (most recent call last): File "/home/nyros/hs/git_br/2013/Oct-9/healersource/apps/blog_hs/forms.py", line 226, in save blog_id=blog_id) File "/home/nyros/hs/1a9pinaxenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 150, in call_command return klass.execute(*args, **defaults) File "/home/nyros/hs/1a9pinaxenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute output = self.handle(*args, **options) File "/home/nyros/hs/git_br/mezzanine/mezzanine/blog/management/base.py", line 172, in handle post, created = BlogPost.objects.get_or_create(**initial) File "/home/nyros/hs/1a9pinaxenv/local/lib/python2.7/site-packages/django/db/models/manager.py", line 134, in get_or_create return self.get_query_set().get_or_create(**kwargs) File "/home/nyros/hs/1a9pinaxenv/local/lib/python2.7/site-packages/django/db/models/query.py", line 452, in get_or_create obj.save(force_insert=True, using=self.db) File "/home/nyros/hs/git_br/mezzanine/mezzanine/core/models.py", line 221, in save super(Displayable, self).save(*args, **kwargs) File "/home/nyros/hs/git_br/mezzanine/mezzanine/core/models.py", line 77, in save super(Slugged, self).save(*args, **kwargs) File "/home/nyros/hs/git_br/mezzanine/mezzanine/core/models.py", line 46, in save super(SiteRelated, self).save(*args, **kwargs) File "/home/nyros/hs/git_br/mezzanine/mezzanine/core/models.py", line 116, in save self.description = strip_tags(self.description_from_content()) File "/home/nyros/hs/git_br/mezzanine/mezzanine/core/models.py", line 146, in description_from_content description = unicode(self) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 5: ordinal not in range(128) Code: import xmltest blog_id = xmltest.blogname(self.cleaned_data['blog_id']) print(type(blog_id)) call_command( 'import_blogger_hs', mezzanine_user=request.user.username, blog_id=blog_id) return False And blogname method for If you give blogname it will automatically scrap the blogID and it is represented as blog_id. Answer: Ah, so now with the code the problem is most likely with `request.user.username` unfortunately the mezzanine code assumes it is receiving an ascii object (what `unicode(self)` in the stacktrace is doing) and is "double encoding" it... grrr! I would call your method the same way but do this: call_command( 'import_blogger_hs', mezzanine_user=request.user.username.decode('utf-8'), blog_id=blog_id) Does that fix the issue?
UnicodeDecodeError: 'ascii' codec can't decode byte 0xec in position Question: When I am programming in Ubuntu with python2.7 and MySQLdb, I had an error when I use other languages in python. English only doesn't make this error. Traceback (most recent call last): File "crawl.py", line 242, in <module> parseArticle( u ) File "crawl.py", line 146, in parseArticle gatherNeighborInfo( soup ) File "crawl.py", line 69, in gatherNeighborInfo db.updateURL( url , '자신의 글 주소들을 db에 저장합니다' ) File "crawl.py", line 211, in updateURL self.cursor.execute("UPDATE urls SET state=%d,content='%s' WHERE url='%s'"%(state,content,url)) UnicodeDecodeError: 'ascii' codec can't decode byte 0xec in position 33: ordinal not in range(128) So i tried to change ascii to utf-8. I made a file named sitecustomize.py on the /usr/local/lib/python2.7/site-packages. and sitecustomize.py source code is below. import sys sys.setdefaultencoding("utf-8") but there's nothing changed. please help me. here is the whole source code. # -*- coding: utf-8 -*- from bs4 import BeautifulSoup import robotparser import urllib2 import time, traceback, re import MySQLdb crawler_name = 'daum_blog_crawler' mainpage = 'http://blog.daum.net/' # robot parser setting. rp = robotparser.RobotFileParser( mainpage + 'robots.txt' ) rp.read() def canFetch( url ): return rp.can_fetch( crawler_name, url ) def getContent( url, delay=1): time.sleep( delay ) if not canFetch( url ): #print 'This url can NOT be fetched by our crawler :', url return None try: opener = urllib2.build_opener() opener.addheaders = [('User-agent',crawler_name)] contents = opener.open(url).read() except: traceback.print_exc() return None return contents def getArticleInfo( soup ): rBlog = re.compile('.+blog.daum.net/\w+/\d+.*?') URLs = soup('a',{'href':rBlog}) return [ u.get('href').split('?')[0] for u in URLs ] def getOwnArticles( contents ): ret = [] soup = BeautifulSoup( contents ) rBlog = re.compile('.+/BlogTypeView.+') for u in soup('a',{'href':rBlog}): href = u.get('href') article = href.split('articleno=')[1].split('&')[0] if ret.count(article)<1: ret.append( article ) return ret def gatherNeighborInfo( soup ): rBlog = re.compile('http://blog.daum.net/\w+') Neighbors = soup('a',{'href':rBlog}) cnt = 0 for n in Neighbors: url = n.get('href') blogname = url.split('/')[-1] if url and url.startswith('http://') and db.isCrawledURL(url)<1: db.insertURL( url, 1 ) db.updateURL( url , '자신의 글 주소들을 db에 저장합니다' ) url2 = getRedirectedURL( url ) if not url2: continue re_url = 'http://blog.daum.net' + url2 body = getContent( re_url, 0 ) if body: for u in getOwnArticles( body ): fullpath = 'http://blog.daum.net/'+blogname+'/'+u cnt+=db.insertURL( fullpath ) if cnt>0: print '%d neighbor articles inserted'%cnt def getRedirectedURL( url ): contents = getContent( url ) if not contents: return None #redirect try: soup = BeautifulSoup( contents ) frame = soup('frame') src = frame[0].get('src') except: src = None return src def getBody( soup, parent ): rSrc = re.compile('.+/ArticleContentsView.+') iframe = soup('iframe',{'src':rSrc}) if len(iframe)>0: src = iframe[0].get('src') iframe_src = 'http://blog.daum.net'+src req = urllib2.Request( iframe_src ) req.add_header('Referer', parent ) body = urllib2.urlopen(req).read() soup = BeautifulSoup( body ) return str(soup.body) else: print 'NULL contents' return '' def parseArticle( url ): article_id = url.split('/')[-1] blog_id = url.split('/')[-2] if blog_id.isdigit(): print 'digit:', url.split('/') newURL = getRedirectedURL( url ) if newURL: newURL = 'http://blog.daum.net'+newURL print 'redirecting', newURL contents = getContent( newURL, 0 ) if not contents: print 'Null Contents...' db.updateURL( url, -1 ) return soup = BeautifulSoup( contents ) gatherNeighborInfo( soup ) n=0 for u in getArticleInfo( soup ): n+=db.insertURL( u ) if n>0: print 'inserted %d urls from %s'%(n,url) sp = contents.find('<title>') if sp>-1: ep = contents[sp+7:].find('</title>') title = contents[sp+7:sp+ep+7] else: title = '' contents = getBody( soup, newURL ) pStyle = re.compile('<style(.*?)>(.*?)</style>', re.IGNORECASE | re.MULTILINE | re.DOTALL ) contents = pStyle.sub('', contents) pStyle = re.compile('<script(.*?)>(.*?)</script>', re.IGNORECASE | re.MULTILINE | re.DOTALL ) contents = pStyle.sub('', contents) pStyle = re.compile("<(.*?)>", re.IGNORECASE | re.MULTILINE | re.DOTALL ) contents = pStyle.sub("", contents) db.updateURL( url , '처리했다고 db에 표시합니다.' ) else: print 'Invalid blog article...' db.updateURL( url, 'None', -1 ) class DB: "MySQL wrapper class" def __init__(self): self.conn = MySQLdb.connect(db='crawlDB', user='root', passwd='......') self.cursor = self.conn.cursor() self.cursor.execute('CREATE TABLE IF NOT EXISTS urls(url CHAR(150), state INT, content TEXT)') def commit(self): self.conn.commit() def __del__(self): self.conn.commit() self.cursor.close() def insertURL(self, url, state=0, content=None): if url[-1]=='/': url=url[:-1] try: self.cursor.execute("INSERT INTO urls VALUES ('%s',%d,'%s')"%(url,state,content)) except: return 0 else: return 1 def selectUncrawledURL(self): self.cursor.execute('SELECT * FROM urls where state=0') return [ row[0] for row in self.cursor.fetchall() ] def updateURL(self, url, content, state=1): if url[-1]=='/': url=url[:-1] self.cursor.execute("UPDATE urls SET state=%d,content='%s' WHERE url='%s'"%(state,content,url)) def isCrawledURL(self, url): if url[-1]=='/': url=url[:-1] self.cursor.execute("SELECT COUNT(*) FROM urls WHERE url='%s' AND state=1"%url) ret = self.cursor.fetchone() return ret[0] db = DB() if __name__=='__main__': print 'starting crawl.py...' contents = getContent( mainpage ) URLs = getArticleInfo( BeautifulSoup( contents ) ) nSuccess = 0 for u in URLs: nSuccess += db.insertURL( u ) print 'inserted %d new pages.'%nSuccess while 1: uncrawled_urls = db.selectUncrawledURL() if not uncrawled_urls: break for u in uncrawled_urls: print 'downloading %s'%u try: parseArticle( u ) except: traceback.print_exc() db.updateURL( u, -1 ) db.commit() #bs.UpdateIndex() Answer: Specify `charset` when connect self.conn = MySQLdb.connect(db='crawlDB', user='root', passwd='......', charset='utf8') Replace following line: self.cursor.execute("UPDATE urls SET state=%d,content='%s' WHERE url='%s'"%(state,content,url)) with (separating the sql from the parameters): self.cursor.execute("UPDATE urls SET state=%s, content=%s WHERE url=%s", (state,content,url)) Example session: >>> import MySQLdb >>> db = MySQLdb.connect('localhost', db='test', charset='utf8') >>> cursor = db.cursor() >>> cursor.execute('DROP TABLE IF EXISTS urls') 0L >>> cursor.execute('CREATE TABLE urls(url char(200), state int, content text)') 0L >>> cursor.execute('INSERT INTO urls(url, state, content) VALUES(%s, %s, %s)', ('http://daum.net/', 1, u'\uc548\ub155')) 1L >>> cursor.execute('SELECT * FROM urls') 1L >>> for row in cursor.fetchall(): ... print row ... (u'http://daum.net/', 1L, u'\uc548\ub155')
Cannot print alt and az using pyephem in function Question: I'm working on building a simple python program for a class which will run on a Raspberry Pi and an Arduino to direct a telescope. I had started to learn python some time ago, and I'm having trouble getting my functions to work properly. Right now, I have this: import ephem def const(p, d): # find the constellation # def loc(): sbend = ephem.Observer() sbend.lat = '41.67' sbend.lon = '86.26' p = getattr(ephem, p) p.compute(sbend) print p.alt, p.az o = getattr(ephem, p) print ephem.constellation(o(d)) return loc() const(raw_input('Planet: '), raw_input('yyyy/mm/dd: ')) From what I remember, a function inside another can call a variable from the parent. Can it also work the other way round like I have at the end? I'd like to be able to print the constellation (which is working) as well as the alt and az of the planet based on the hardcoded location. For some reason, it isn't calculating the altitude and azimuth though. Thoughts? **EDIT** I added `return loc()` on line 14. I was doing more reading and some other threads said that to get to an inner function, it needs to be returned at the end of the parent. But, it's still not working for me. Answer: I am not clear on why you have one function inside of another, so I might be missing part of the problem that you are trying to solve; but if I wanted to determine in what constellation a planet lies, where the planet's name and the date are provided as inputs, then I would simply perform those steps all in a row, without any complicated functions-inside-of-functions: import ephem def const(planet_name, date_string): planet_class = getattr(ephem, planet_name) planet = planet_class() south_bend = ephem.Observer() south_bend.lat = '41.67' south_bend.lon = '-86.26' # west is negative south_bend.date = date_string planet.compute(south_bend) return ephem.constellation((planet.ra, planet.dec)) print const(raw_input('Planet: '), raw_input('yyyy/mm/dd: '))
How function is getting called without defining in python Question: Here is the program: import sys def IndexSearchString(): ''' This function search a string in a password file through index and gives the result. :return: none :return type: none :author: Neeraj ''' fieldindex = int(sys.argv[1])-1 stringsrch = sys.argv[2] file_name = open("passwd", "r") for store_file in file_name: temp = store_file.split(":") search = temp[fieldindex] #print search if stringsrch in search: print store_file #print sys.stdout.write(store_file) return #IndexSearchString() Answer: Make sure your code is exactly as it is now in the question (including the edit by @Haidro) The code, as you pasted it in the question, suggests your indentation was something like this: def my_function(): ''' docstring ''' code_intended_for_my_function() #my_function() This would cause `code_intended_for_my_function` to be executed. This is "valid" because the `docstring` makes the definition for `my_fuction` valid (it just does nothing), then immediately executes `code_intended_for_my_function`. To test this, in the code you have, remove the `docstring` and check if you get an `IndentationError`, or just copy the code as it is currently from the question and see if it works as you expect.
google app engine python hello world application not displaying any thing on the localhost:8080 Question: I ran the following hello world code in python but localhost:8080 doesnot print anything i'm using ubuntu 12.04 localhost:8080 shows a blank page helloworld.py import webapp2 class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.write('Hello, World!') application = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True) app.yaml application: your-app-id version: 1 runtime: python27 api_version: 1 threadsafe: true handlers: - url: /.* script: helloworld.application output is as follows kiran@kiru-Lenovo-G480:~/google$ dev_appserver.py helloworld/ INFO 2013-10-09 12:22:03,559 sdk_update_checker.py:245] Checking for updates to the SDK. INFO 2013-10-09 12:22:03,565 __init__.py:94] Connecting through tunnel to: appengine.google.com:443 INFO 2013-10-09 12:22:03,571 sdk_update_checker.py:261] Update check failed: <urlopen error Tunnel connection failed: 407 Proxy Authentication Required> INFO 2013-10-09 12:22:03,595 api_server.py:138] Starting API server at: http://localhost:44748 INFO 2013-10-09 12:22:03,610 dispatcher.py:168] Starting module "default" running at: http://localhost:8080 INFO 2013-10-09 12:22:03,614 admin_server.py:117] Starting admin server at: http://localhost:8000 Answer: You are calling `write` directly on the `Response` object. You'll want to do something like this instead: self.response.out.write('Hello, World!')
How to open a file on mac OSX 10.8.2 in python Question: I am writing a python code on eclipse and want to open a file that is present in Downloads folder. I am using MAC OSX 10.8.2. I tried with `f=os.path.expanduser("~/Downloads/DeletingDocs.txt")` and also with ss=subprocess.Popen("~/Downloads/DeletingDocs.txt",shell=True) ss.communicate() I basically want to open a file in subprocess, to listen to the changes in the opened file.But, the file is not opening in either case. Answer: from os.path import baspath, expanduser filepath = abspath(expanduser("~/") + '/Downloads/DeletingDocs.txt') print('Opening file', filepath) with open(filepath, 'r') as fh: print(fh.read()) Take note of OSX file-handling tho, the IO is a bit different depending on the filetype. For instance, a `.txt` file which under Windows would be considered a "plain text-file" is actually a compressed data-stream under OSX because OSX tries to be "smart" about the storage space. This can literately ruin your day unless you know about it (been there, had the headache.. moved on) When double-clicking on a `.txt` file in OSX for instance normally the text- editor pops up and what it does is call for a `os.open()` instead of accessing it on a lower level which lets OSX middle layers do `disk-area|decompression pipe|file-handle -> Texteditor` but if you access the file-object on a lower level you'll end up opening the disk-area where the file is stored and if you print the data you'll get garbage because it's not the data you'd expect. So try using: import os fd = os.open( "foo.txt", os.O_RDONLY ) print(os.read(fd, 1024)) os.close( fd ) And fiddle around with the flags. I honestly can't remember which of the two opens the file as-is from disk (`open()` or `os.open()`) but one of them makes your data look like garbage and sometimes you just get the pointer to the decompression pipe (giving you like 4 bytes of data even tho the text-file is hughe). # If it's tracking/catching updates on a file you want from time import ctime from os.path import getmtime, expanduser, abspath from os import walk for root, dirs, files in walk(expanduser('~/')): for fname in files: modtime = ctime(getmtime(abspath(root + '/' + fname))) print('File',fname,'was last modified at',modtime) And if the time differs from your last check, well then do something cool with it. For instance, you have these libraries for Python to work with: * [.csv](http://docs.python.org/2/library/csv.html) * [.pdf](http://pybrary.net/pyPdf/) * [.odf](https://pypi.python.org/pypi/odfpy) * [.xlsx](https://pypi.python.org/pypi/XlsxWriter) And MANY more, so instead of opening an external application as your first fix, try opening them via Python and modify to your liking instead, and only as a last resort (if even then) open external applications via Popen. But since you requested it (sort of... erm), here's a **Popen approach** : from subprocess import Popen, PIPE, STDOUT from os.path import abspath, expanduser from time import sleep run = Popen('open -t ' + abspath(expanduser('~/') + '/example.txt'), shell=True, stdout=PIPE, stdin=PIPE, stderr=STDOUT) ##== Here's an example where you could interact with the process: ##== run.stdin.write('Hey you!\n') ##== run.stdin.flush() while run.poll() == None: sleep(1) # Over-explaining your job: This will print a files contents every time it's changed. with open('test.txt', 'r') as fh: import time while 1: new_data = fh.read() if len(new_data) > 0: fh.seek(0) print(fh.read()) time.sleep(5) **How it works:** The regular file opener `with open() as fh` will open up the file and place it as a handle in `fh`, once you call `.read()` without any parameters it will fetch the entire contents of the file. This in turn doesn't close the file, it simply places the "reading" pointer at the back of the file (lets say at position 50 for convenience). So now your pointer is at character 50 in your file, at the end. Wherever you write something in your file, that will put more data into it so the next `.read()` will fetch data from position 50+ making the `.read()` not empty, so we place the "reading" pointer back to position 0 by issuing `.seek(0)` and then we print all the data. **Combine that with`os.path.getmtime()`** to fine any reversed changes or 1:1 ratio changes (replacing a character mis-spelling etc).
Why aren't my tables available during Django unitests? Question: When I try to run my unittests, I'm getting an error that says a table is not available in the database. My tests were running fine a day ago, and a brainstorm around what I've changed since then isn't bringing to mind anything that gets close to causing this issue. I'm seeing this as a problem with `syncdb` and `South` not creating the table properly in the `sqlite` database, and have tried to troubleshoot around that. ## Error message with traceback $ ./manage.py test --settings=settings.test -v2 Creating test database for alias 'default' (':memory:')... Syncing... Creating tables ... Creating table django_admin_log Creating table auth_permission Creating table auth_group_permissions Creating table auth_group Creating table django_content_type Creating table django_session Creating table django_site Creating table south_migrationhistory Installing custom SQL ... Installing indexes ... Synced: > grappelli > django.contrib.admin > django.contrib.admindocs > django.contrib.auth > django.contrib.contenttypes > django.contrib.messages > django.contrib.sessions > django.contrib.sites > django.contrib.staticfiles > crispy_forms > floppyforms > south > subdomains > widget_tweaks Not synced (use migrations): - apps.application - apps.app_app - apps.accounts - apps.rampup - apps.students - apps.automated_responses (use ./manage.py migrate to migrate these) ====================================================================== ERROR: test_can_save_form_with_clean_passwords (apps.accounts.tests.test_admin.TestCreateUserForm) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/chaz/dev/projects/si/apps/accounts/tests/test_admin.py", line 17, in setUp self.user = SIDummyUserFactory.create() File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/factory/base.py", line 452, in create attrs = cls.attributes(create=True, extra=kwargs) File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/factory/base.py", line 316, in attributes force_sequence=force_sequence, File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/factory/containers.py", line 263, in build sequence = self.factory._generate_next_sequence() File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/factory/base.py", line 287, in _generate_next_sequence cls._next_sequence = cls._setup_next_sequence() File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/factory/django.py", line 71, in _setup_next_sequence ).order_by('-pk')[0] File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/django/db/models/query.py", line 231, in __getitem__ return list(qs)[0] File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/django/db/models/query.py", line 108, in __len__ self._result_cache.extend(self._iter) File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/django/db/models/query.py", line 1140, in iterator for row in self.query.get_compiler(self.db).results_iter(): File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 775, in results_iter for rows in self.execute_sql(MULTI): File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql cursor.execute(sql, params) File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 366, in execute six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2]) File "/Users/chaz/dev/envs/startupinst/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 362, in execute return Database.Cursor.execute(self, query, params) DatabaseError: no such table: accounts_siuser ## Relevent settings ### INSTALLED_APPS In [2]: settings.INSTALLED_APPS Out[2]: ('grappelli', 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.staticfiles', 'crispy_forms', 'floppyforms', 'south', 'subdomains', 'widget_tweaks', 'gunicorn', 'apps.application', 'apps.app_app', 'apps.automated_responses', 'apps.accounts', 'apps.rampup', 'apps.students', 'utils.context_processors', 'discover_runner') ### `pip freeze --local` Django==1.5.4 Pygments==1.6 South==0.7.6 argparse==1.2.1 bpython==0.12 coverage==3.6 dj-database-url==0.2.1 django-braces==1.2.2 django-crispy-forms==1.2.2 django-debug-toolbar==0.9.4 django-discover-runner==0.4 django-filepicker==0.1.4 django-floppyforms==1.1 django-grappelli==2.4.4 django-parsley==0.0.2a0 django-subdomains==2.0.1 django-templated-email==0.4.7 django-widget-tweaks==1.1.2 envoy==0.0.2 factory-boy==2.1.1 gunicorn==0.16.1 ipdb==0.7 ipython==0.13.2 psycopg2==2.4.5 pytz==2013b requests==2.0.0 simplejson==3.3.1 six==1.4.1 stripe==1.7.7 zulip==0.2.1 ## settings/test.py """ Test settings and globals which allow us to write our tests locally.""" from .common import * ######## # APPS # ######## INSTALLED_APPS += ( 'discover_runner', ) ################# # TEST SETTINGS # ################# #TEST_RUNNER = 'django_pytest.test_runner.TestRunner' TEST_RUNNER = "discover_runner.DiscoverRunner" TEST_DISCOVER_TOP_LEVEL = PROJECT_ROOT TEST_DISCOVER_PATTERN = "test_*" SOUTH_TESTS_MIGRATE = False ########################### # IN MEMORY TEST DATABASE # ########################### DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", }, } ## Similar SO questions that didn't solve the problem * [Does South foul up the Django test runner framework](http://stackoverflow.com/questions/6900007/does-south-foul-up-the-django-test-runner-framework) * [Disable South when running Django unit tests](http://stackoverflow.com/questions/5798446/disable-django-south-when-running-unit-tests) * [Missing table when running django unittest with sqlite2](http://stackoverflow.com/questions/7336130/missing-table-when-running-django-unittest-with-sqlite3) ## What I've tried so far * Running the tests on another branch, that wasn't changed during the time when this happened _Result: Getting the same exact error and trackback_ * Blowing away my virtual environment and starting a new one _Result: No change_ Answer: I ended up removing `South` from my `settings/test.py` file*, and the database was created properly. Would love to hear if anybody has any ideas about why this was happening. The setting below should have disabled South, causing Django's `syncdb` to create the proper tables. SOUTH_TESTS_MIGRATE = False SOUTH_SKIP_TESTS = True *I have settings files for each environment, so just put South in the ones that need it, instead of having it in the `base.py`, which is where they all inherit from.
Stepping through date in Python Question: Let's say I have a starting date of `datetime(2007, 2, 15)`. I want to step this date in a loop so that it's advanced to the 1st and 15th of each month. So `datetime(2007, 2, 15)` would step to `datetime(2007, 3, 1)`. In the next iteration, it would step to `datetime(2007, 3, 15)`... then to `datetime(2007, 4, 1)` and so forth. Is there any possible way to do this with `timedelta` or `dateutils` considering that, the number of days it has to step by, continuously changes? Answer: from datetime import datetime for m in range(1, 13): for d in (1, 15): print str(datetime(2013, m, d)) 2013-01-01 00:00:00 2013-01-15 00:00:00 2013-02-01 00:00:00 2013-02-15 00:00:00 2013-03-01 00:00:00 2013-03-15 00:00:00 2013-04-01 00:00:00 2013-04-15 00:00:00 2013-05-01 00:00:00 2013-05-15 00:00:00 2013-06-01 00:00:00 2013-06-15 00:00:00 2013-07-01 00:00:00 2013-07-15 00:00:00 2013-08-01 00:00:00 2013-08-15 00:00:00 2013-09-01 00:00:00 2013-09-15 00:00:00 2013-10-01 00:00:00 2013-10-15 00:00:00 2013-11-01 00:00:00 2013-11-15 00:00:00 2013-12-01 00:00:00 2013-12-15 00:00:00 I tend to work with datetime more than date objects, but you could use datetime.date depending on your needs.
Selenium - Drag and Drop Question: I am looking to automate the dropping of a file from the desktop to the page using Firefox as the browser, and Selenium on Python for automation. Here is the code for the drag-and-drop on the page: <div id="dropbox">...</div> <script type="text/javascript"> ... dropbox.addEventListener("drop", dropUpload, false); <script> ... function dropUpload(event) { ... files = event.dataTransfer.files; ... } Most of the threads out there deal with dropping some other element besides a file from the filesystem. The problem is that I need the event to contain a file object with the actual data. I've tried just typing into the dropbox element, as others have suggested, but this obviously doesn't work with a div element. Answer: This is very painful to do with Selenium alone. If using a commercial add-on to Selenium is an option for you, you can try [Helium](http://heliumhq.com). It lets you drag your file via the following code: from helium.api import drag_file drag_file(r"C:\Documents\notes.txt", to=driver.find_element_by_id("dropbox")) Nicer still is if your `#dropbox` div contains some text, eg. `Drop files here`. Then you can do drag_file(r"C:\Documents\notes.txt", to="Drop files here")
Python TkInter Button Command Return Question: I'm having trouble returning a variable from a TkInter button command. This here is my code: class trip_calculator: def gui(self): returned_values = {} def open_file_dialog(): returned_values['filename'] = askopenfilename() root = Tk() Button(root, text='Browse', command= open_file_dialog).pack() filepath = returned_values.get('filename') root.mainloop() return filepath root.quit() I just want to return the filepath of a TXT file. The TkInter window is open and I can browse and choose the file but it then doesn't return the path. I'm going nuts! def __init__(self): file = self.gui() Any ideas? Thanks a bunch! Answer: The way your code is now, `filepath` is assigned its value before your window even appears to the user. So there's no way the dictionary could contain the filename that the user eventually selects. The easiest fix is to put `filepath = returned_values.get('filename')` after `mainloop`, so it won't be assigned until mainloop ends when the user closes the window. from Tkinter import * from tkFileDialog import * class trip_calculator: def gui(self): returned_values = {} def open_file_dialog(): returned_values['filename'] = askopenfilename() root = Tk() Button(root, text='Browse', command= open_file_dialog).pack() root.mainloop() filepath = returned_values.get('filename') return filepath root.quit() print(trip_calculator().gui())
trouble installing pycurl on mac 10.8.5 Question: I really have trouble installing pycurl on the mac of my girlfriend, I managed to do it on my own but I did not remember which command brought the success. Everything I tried on her mac wont't work. I looked up every answer I could find on how to install pycurl, nothing worked for me :(. I tried macports, didn't work as well. The problem is, I am not that into using the terminal Here is what I've tried so far: sudo port install py27-yaml sudo port install py27-curl /opt/local/bin/python2.7 import pycurl but id didn't ' work :( trying `sudo env ARCHFLAGS="-arch x86_64" easy_install setuptools pycurl==7.19.0` brings me this Last login: Wed Oct 9 23:51:34 on ttys000 Loras-MacBook-Air:~ Lora$ sudo env ARCHFLAGS="-arch x86_64" easy_install setuptools pycurl==7.19.0 Searching for setuptools Best match: setuptools 0.6c12dev-r88846 setuptools 0.6c12dev-r88846 is already the active version in easy-install.pth Installing easy_install script to /usr/local/bin Installing easy_install-2.7 script to /usr/local/bin Using /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python Processing dependencies for setuptools Finished processing dependencies for setuptools Searching for pycurl==7.19.0 Reading http://pypi.python.org/simple/pycurl/ Reading http://pycurl.sourceforge.net/ Reading http://pycurl.sourceforge.net/download/ Best match: pycurl 7.19.0 Downloading http://pycurl.sourceforge.net/download/pycurl-7.19.0.tar.gz Processing pycurl-7.19.0.tar.gz Running pycurl-7.19.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-r7sdRe/pycurl-7.19.0/egg-dist-tmp-DKaHyW Using curl-config (libcurl 7.32.0) clang: warning: argument unused during compilation: '-mno-fused-madd' src/pycurl.c:1168:16: warning: implicit conversion loses integer precision: 'long' to 'int' [-Wshorten-64-to-32] ret = dup(PyInt_AsLong(fileno_result)); ~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~ src/pycurl.c:1912:31: warning: implicit conversion loses integer precision: 'long' to 'int' [-Wshorten-64-to-32] val = PyLong_AsLong(PyTuple_GET_ITEM(t, j)); ~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ src/pycurl.c:2904:22: warning: implicit conversion loses integer precision: 'long' to '__darwin_suseconds_t' (aka 'int') [-Wshorten-64-to-32] tv.tv_usec = (long)(timeout*1000000.0); ~ ^~~~~~~~~~~~~~~~~~~~~~~~~ 3 warnings generated. zip_safe flag not set; analyzing archive contents... Adding pycurl 7.19.0 to easy-install.pth file Installed /Library/Python/2.7/site-packages/pycurl-7.19.0-py2.7-macosx-10.8-x86_64.egg Processing dependencies for pycurl==7.19.0 Finished processing dependencies for pycurl==7.19.0 Loras-MacBook-Air:~ Lora$ i just cant get i done :( Answer: The Apple LLVM compiler in Xcode 5.1 treats unrecognized command-line options as errors. This issue has been seen when building both Python native extensions and Ruby Gems, where some invalid compiler options are currently specified. from [Kasper Munck](http://kaspermunck.github.io/2014/03/fixing- clang-error/) sudo ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future easy_install-2.7 pycurl
Python: Dynamically Update Array Cells from Parent Program Question: I previously asked a question about updating a single value in a parallel process from a parent program. Great answers to this can be found at [Python: Update Local Variable in a Parallel Process from Parent Program](http://stackoverflow.com/questions/19233246/python-update-local- variable-in-a-parallel-process-from-parent- program/19234437?noredirect=1#19234437). Now I would like to extend this question to arrays. Say I have the following simple program that iterates through the first cell of an defined array (similar to the link provided): import time def loop(i): while 1: print i[0] i[0] += 1 time.sleep(1) if __name__ == "__main__": from multiprocessing import Process, Array i = Array("i", [1,2,3,4]) p = Process(target=loop, args=(i,)) p.start() time.sleep(2) # update i in shared memory??? From this program, how can I update "i" so the "loop" function continues to run and reads the new array? For example, if I want to set "i" to [50,51,52,53]. Is there an equivalent attribute like "value" that can do this? I did much searching around and could not find any solutions. Thank you very much in advance. Answer: To update `i` _in-place_ use i[:] = [50, 51, 52,53] Note that it is important that you modify `i` in-place because if you were to assign `i` to a new value, such as by using i = [50, 51, 52, 53] Then `i` would simply point to a new list, without modifying the shared array. The Python idiom `i[:] = [...]` is also used for modifying Python lists in- place, by the way. * * * import time def loop(i): while 1: print list(i) # i[0] += 1 i[:] = [50,51,52,53] time.sleep(1) if __name__ == "__main__": from multiprocessing import Process, Array i = Array("i", [1,2,3,4]) p = Process(target=loop, args=(i,)) p.start()
Python3 Qt unicode file name problems Question: Similar to [QDir and QDirIterator ignore files with non-ASCII filenames](http://stackoverflow.com/questions/1641994/qdir-and-qdiriterator- ignore-files-with-non-ascii-filenames) and [UnicodeEncodeError: 'latin-1' codec can't encode character](http://stackoverflow.com/questions/3942888/unicodeencodeerror- latin-1-codec-cant-encode-character) With regard to the second link above, I added test0() below. My understanding was that utf-8 was the solution I was searching for, but alas trying to encode the filename fails. def test0(): print("test0...using unicode literal") name = u"123c\udcb4.wav" test("test0b", name) n = name.encode('utf-8') print(n) n = QtCore.QFile.decodeName(n) print(n) # From http://docs.python.org/release/3.0.1/howto/unicode.html # This will indeed overwrite the correct file! # f = open(name, 'w') # f.write('blah\n') # f.close() Test0 results... test0...using unicode literal test0b QFile.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' False test0b QFileInfo.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' False test0b os.path.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' True test0b os.path.isfile 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' True Traceback (most recent call last): File "unicode.py", line 157, in <module> test0() File "unicode.py", line 42, in test0 n = name.encode('utf-8') UnicodeEncodeError: 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed **EDIT** Further reading from <http://tools.ietf.org/html/rfc3629> tells me that "The definition of UTF-8 prohibits encoding character numbers between U+D800 and U+DFFF". So if uft-8 doesn't allow these characters. How are you supposed to deal with a file that is so named? Python can create and test existence for them. So this points me at an issue with my Qt api usage or the Qt api itself?! I am struggling to wrap my head around proper handling of unicode file name in Python3. Ultimately, I'm working on a Phonon based music player. I've tried to isolate the problem(s) from that as much as possible. From the code below you will see that I've tried as many alternatives as I can find. My initial response is that there are bugs here....maybe mine...maybe in one or more libraries. Any help would be much appreciated! I have a directory with 3 unicode file names 123[abc]U.wav. The first 2 files are handled properly...mostly...the third one 123c is just wrong. from PyQt4 import QtGui, QtCore import sys, os def test(_name, _file): # print(_name, repr(_file)) f = QtCore.QFile(_file) # f = QtCore.QFile(QtCore.QFile.decodeName(test)) exists = f.exists() try: print(_name, "QFile.exists", f.fileName(), exists) except UnicodeEncodeError as e: print(e, repr(_file), exists) fileInfo = QtCore.QFileInfo(_file) exists = fileInfo.exists() try: print(_name, "QFileInfo.exists", fileInfo.fileName(), exists) except UnicodeEncodeError as e: print(e, repr(_file), exists) exists = os.path.exists(_file) try: print(_name, "os.path.exists", _file, exists) except UnicodeEncodeError as e: print(e, repr(_file), exists) exists = os.path.isfile(_file) try: print(_name, "os.path.isfile", _file, exists) except UnicodeEncodeError as e: print(e, repr(_file), exists) print() def test1(): args = QtGui.QApplication.arguments() print("test1...using QtGui.QApplication.arguments()") test("test1", args[1]) def test2(): print("test2...using sys.argv") test("test2", sys.argv[1]) def test3(): print("test3...QtGui.QFileDialog.getOpenFileName()") name = QtGui.QFileDialog.getOpenFileName() test("test3", name) def test4(): print("test4...QtCore.QDir().entryInfoList()") p = os.path.abspath(__file__) p, _ = os.path.split(p) d = QtCore.QDir(p) for inf in d.entryInfoList(QtCore.QDir.AllEntries|QtCore.QDir.NoDotAndDotDot|QtCore.QDir.System): print("test4", inf.fileName()) # if str(inf.fileName()).startswith("123c"): if u"123c\ufffd.wav" == inf.fileName(): # if u"123c\udcb4.wav" == inf.fileName(): # This check fails..even tho that is what is reported in error messages for test2 test("test4a", inf.fileName()) test("test4b", inf.absoluteFilePath()) def test5(): print("test5...os.listdir()") p = os.path.abspath(__file__) p, _ = os.path.split(p) dirList = os.listdir(p) for file in dirList: fullfile = os.path.join(p, file) try: print("test5", file) except UnicodeEncodeError as e: print(e) print("test5", repr(fullfile)) # if u"123c\ufffd.wav" == file: # This check fails..even tho it worked in test4 if u"123c\udcb4.wav" == file: test("test5a", file) test("test5b", fullfile) print() def test6(): print("test6...Phonon and QtGui.QFileDialog.getOpenFileName()") from PyQt4.phonon import Phonon class Window(QtGui.QDialog): def __init__(self): QtGui.QDialog.__init__(self, None) self.mediaObject = Phonon.MediaObject(self) self.audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self) Phonon.createPath(self.mediaObject, self.audioOutput) self.mediaObject.stateChanged.connect(self.handleStateChanged) name = QtGui.QFileDialog.getOpenFileName()# works with python3..not for 123c # name = QtGui.QApplication.arguments()[1] # works with python2..but not python3...not for 123c # name = sys.argv[1] # works with python3..but not python2...not for 123c # p = os.path.abspath(__file__) # p, _ = os.path.split(p) # print(p) # name = os.path.join(p, str(name)) self.mediaObject.setCurrentSource(Phonon.MediaSource(name)) self.mediaObject.play() def handleStateChanged(self, newstate, oldstate): if newstate == Phonon.PlayingState: source = self.mediaObject.currentSource().fileName() print('test6 playing: :', source) elif newstate == Phonon.StoppedState: source = self.mediaObject.currentSource().fileName() print('test6 stopped: :', source) elif newstate == Phonon.ErrorState: source = self.mediaObject.currentSource().fileName() print('test6 ERROR: could not play:', source) win = Window() win.resize(200, 100) # win.show() win.exec_() def timerTick(): QtGui.QApplication.exit() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) app.setApplicationName('unicode_test') test1() test2() test3() test4() test5() test6() timer = QtCore.QTimer() timer.timeout.connect(timerTick) timer.start(1) sys.exit(app.exec_()) Test results with 123a... python3 unicode.py 123a�.wav test1...using QtGui.QApplication.arguments() test1 QFile.exists unknown False test1 QFileInfo.exists unknown False test1 os.path.exists unknown False test1 os.path.isfile unknown False test2...using sys.argv test2 QFile.exists 123a�.wav True test2 QFileInfo.exists 123a�.wav True test2 os.path.exists 123a�.wav True test2 os.path.isfile 123a�.wav True test3...QtGui.QFileDialog.getOpenFileName() test3 QFile.exists /home/mememe/Desktop/test/unicode/123a�.wav True test3 QFileInfo.exists 123a�.wav True test3 os.path.exists /home/mememe/Desktop/test/unicode/123a�.wav True test3 os.path.isfile /home/mememe/Desktop/test/unicode/123a�.wav True test4...QtCore.QDir().entryInfoList() test4 123a�.wav test4 123bÆ.wav test4 123c�.wav test4a QFile.exists 123c�.wav False test4a QFileInfo.exists 123c�.wav False test4a os.path.exists 123c�.wav False test4a os.path.isfile 123c�.wav False test4b QFile.exists /home/mememe/Desktop/test/unicode/123c�.wav False test4b QFileInfo.exists 123c�.wav False test4b os.path.exists /home/mememe/Desktop/test/unicode/123c�.wav False test4b os.path.isfile /home/mememe/Desktop/test/unicode/123c�.wav False test4 unicode.py test5...os.listdir() test5 unicode.py test5 '/home/mememe/Desktop/test/unicode/unicode.py' test5 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed test5 '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' test5a QFile.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' False test5a QFileInfo.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' False test5a os.path.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' True test5a os.path.isfile 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' True test5b QFile.exists 'utf-8' codec can't encode character '\udcb4' in position 38: surrogates not allowed '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' False test5b QFileInfo.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' False test5b os.path.exists 'utf-8' codec can't encode character '\udcb4' in position 38: surrogates not allowed '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' True test5b os.path.isfile 'utf-8' codec can't encode character '\udcb4' in position 38: surrogates not allowed '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' True test5 123bÆ.wav test5 '/home/mememe/Desktop/test/unicode/123bÆ.wav' test5 123a�.wav test5 '/home/mememe/Desktop/test/unicode/123a�.wav' test6...Phonon and QtGui.QFileDialog.getOpenFileName() test6 stopped: : /home/mememe/Desktop/test/unicode/123a�.wav test6 playing: : /home/mememe/Desktop/test/unicode/123a�.wav test6 stopped: : /home/mememe/Desktop/test/unicode/123a�.wav Test results with 123b... python3 unicode.py 123bÆ.wav test1...using QtGui.QApplication.arguments() test1 QFile.exists 123b.wav False test1 QFileInfo.exists 123b.wav False test1 os.path.exists 123b.wav False test1 os.path.isfile 123b.wav False test2...using sys.argv test2 QFile.exists 123bÆ.wav True test2 QFileInfo.exists 123bÆ.wav True test2 os.path.exists 123bÆ.wav True test2 os.path.isfile 123bÆ.wav True test3...QtGui.QFileDialog.getOpenFileName() test3 QFile.exists /home/mememe/Desktop/test/unicode/123bÆ.wav True test3 QFileInfo.exists 123bÆ.wav True test3 os.path.exists /home/mememe/Desktop/test/unicode/123bÆ.wav True test3 os.path.isfile /home/mememe/Desktop/test/unicode/123bÆ.wav True test4...QtCore.QDir().entryInfoList() test4 123a�.wav test4 123bÆ.wav test4 123c�.wav test4a QFile.exists 123c�.wav False test4a QFileInfo.exists 123c�.wav False test4a os.path.exists 123c�.wav False test4a os.path.isfile 123c�.wav False test4b QFile.exists /home/mememe/Desktop/test/unicode/123c�.wav False test4b QFileInfo.exists 123c�.wav False test4b os.path.exists /home/mememe/Desktop/test/unicode/123c�.wav False test4b os.path.isfile /home/mememe/Desktop/test/unicode/123c�.wav False test4 unicode.py test5...os.listdir() test5 unicode.py test5 '/home/mememe/Desktop/test/unicode/unicode.py' test5 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed test5 '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' test5a QFile.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' False test5a QFileInfo.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' False test5a os.path.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' True test5a os.path.isfile 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' True test5b QFile.exists 'utf-8' codec can't encode character '\udcb4' in position 38: surrogates not allowed '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' False test5b QFileInfo.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' False test5b os.path.exists 'utf-8' codec can't encode character '\udcb4' in position 38: surrogates not allowed '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' True test5b os.path.isfile 'utf-8' codec can't encode character '\udcb4' in position 38: surrogates not allowed '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' True test5 123bÆ.wav test5 '/home/mememe/Desktop/test/unicode/123bÆ.wav' test5 123a�.wav test5 '/home/mememe/Desktop/test/unicode/123a�.wav' test6...Phonon and QtGui.QFileDialog.getOpenFileName() test6 stopped: : /home/mememe/Desktop/test/unicode/123bÆ.wav test6 playing: : /home/mememe/Desktop/test/unicode/123bÆ.wav test6 stopped: : /home/mememe/Desktop/test/unicode/123bÆ.wav Test results with 123c... python3 unicode.py 123c�.wav test1...using QtGui.QApplication.arguments() test1 QFile.exists unknown False test1 QFileInfo.exists unknown False test1 os.path.exists unknown False test1 os.path.isfile unknown False test2...using sys.argv test2 QFile.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' False test2 QFileInfo.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' False test2 os.path.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' True test2 os.path.isfile 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' True test3...QtGui.QFileDialog.getOpenFileName() test3 QFile.exists /home/mememe/Desktop/test/unicode/123c�.wav False test3 QFileInfo.exists 123c�.wav False test3 os.path.exists /home/mememe/Desktop/test/unicode/123c�.wav False test3 os.path.isfile /home/mememe/Desktop/test/unicode/123c�.wav False test4...QtCore.QDir().entryInfoList() test4 123a�.wav test4 123bÆ.wav test4 123c�.wav test4a QFile.exists 123c�.wav False test4a QFileInfo.exists 123c�.wav False test4a os.path.exists 123c�.wav False test4a os.path.isfile 123c�.wav False test4b QFile.exists /home/mememe/Desktop/test/unicode/123c�.wav False test4b QFileInfo.exists 123c�.wav False test4b os.path.exists /home/mememe/Desktop/test/unicode/123c�.wav False test4b os.path.isfile /home/mememe/Desktop/test/unicode/123c�.wav False test4 unicode.py test5...os.listdir() test5 unicode.py test5 '/home/mememe/Desktop/test/unicode/unicode.py' test5 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed test5 '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' test5a QFile.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' False test5a QFileInfo.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' False test5a os.path.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' True test5a os.path.isfile 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '123c\udcb4.wav' True test5b QFile.exists 'utf-8' codec can't encode character '\udcb4' in position 38: surrogates not allowed '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' False test5b QFileInfo.exists 'utf-8' codec can't encode character '\udcb4' in position 4: surrogates not allowed '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' False test5b os.path.exists 'utf-8' codec can't encode character '\udcb4' in position 38: surrogates not allowed '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' True test5b os.path.isfile 'utf-8' codec can't encode character '\udcb4' in position 38: surrogates not allowed '/home/mememe/Desktop/test/unicode/123c\udcb4.wav' True test5 123bÆ.wav test5 '/home/mememe/Desktop/test/unicode/123bÆ.wav' test5 123a�.wav test5 '/home/mememe/Desktop/test/unicode/123a�.wav' test6...Phonon and QtGui.QFileDialog.getOpenFileName() test6 stopped: : /home/mememe/Desktop/test/unicode/123c�.wav Interesting things to note about the test results... * Test1 failed for all 3 files. * Test2 passed for all 3 files...except for the QFile and QFileInfo tests for 123c * Test3 passed for 123a and 123b but failed for 123c * Test4 ...QDir found all 4 files in the directory * Test4a and Test4b failed for all files * Test5 ...os.listdir found all 4 files in the directory * NOTE: The Test5a and test5b checks had to use a different unicode check?! * Test5a and Test5b failed the QFile and QfileInfo tests, but passed the os.path checks. * Test6 passed for 123a and 123b, but failed for 123c...the phonon player got a stopped only message vs the stopped playing stopped the 123a and 123b files got. I know that is a lot of information...I wast trying to be thorough. So, if there is one final question is what is the right way to deal with unicode file names in Python3? Answer: You're right, `123c` is just wrong. The evidence shows that the filename on disk contains an [invalid Unicode codepoint U+DCB4](http://www.fileformat.info/info/unicode/char/dcb4/index.htm). When Python tries to print that character, it rightly complains that it can't. When Qt processes the character in test4 it can't handle it either, but instead of throwing an error it converts it to the [Unicode REPLACEMENT CHARACTER U+FFFD](http://www.fileformat.info/info/unicode/char/fffd/index.htm). Obviously the new filename no longer matches what's on disk. Python can also use the replacement character in a string instead of throwing an error if you do the conversion yourself and specify the proper error handling. I don't have Python 3 on hand to test this but I think it will work: filename = filename.encode('utf-8').decode('utf-8', 'replace')
Save EACH regex match to a new txt file (batch)? Question: I basically need a program/script that will search a file for regex matches and then save each match to a newly created text file (ie. match_01.txt, match_02.txt, match_03.txt, etc.). NB: it must support multiline matching! **EDIT :** This is what I tried using Josha's help (thx:): I get an error when I try this **Python Script:** import re pattern = re.compile(r'(?s)(?<=Sample)(.*?)(?=EndSample)', flags=re.S) with open('test.txt', 'r') as f: matches = pattern.findall(f.read()) for i, match in enumerate(matches): with open('Split/match{0:04d}.txt'.format(i), 'w') as nf: nf.write(match) **Command Prompt:** C:\Test\python test.py Traceback (most recent call last): File "test.py", line 31, in <module> nf.write(match) TypeError: expected a character buffer object test.txt looks something like this: Sample A1 ... ... ... ... ... EndSample Sample B4 ... ... ... ... ... EndSample Sample X6 ... ... ... ... ... EndSample So I need to match everything between "Sample" and "EndSample" (hundreds of lines in-between) and write each match to its own txt file. So far it only works if my regex pattern is ie. "Sample". There is 15 matches and it does create 15 txt files in the Split folder but they all contain just the word Sample and nothing more. Multiline still not working looks like.. And if my regex is this: > (?s)(Sample)(.*?) then it also gives me the same error as above. Its like it doesnt like (.*?) Strange..? Answer: In Python (assuming matches do not span lines): import re pattern = re.compile(r'(?s)(?<=Sample)((?:.+?)?)(?=EndSample)', flags=re.S) # Your regex goes here with open('path/to/your/file.txt', 'r') as f: matches = pattern.findall(f.read()) for i, match in enumerate(matches): with open('/path/to/your/match{0:04d}.txt'.format(i), 'w') as nf: nf.write(match)
Python SetCursorPos error? Or online game cause it? Question: The code works perfectly with no errors until I unminimize the game.After a lot of tries to locate why SetCursorPos doesnt work , I understoud that it did not have a problem with the cords , but it refuses to move to the location when its on the window of the game. The code so far is: from PIL import ImageGrab import os import time import win32con , win32api x_pad = 2 y_pad = 27 def start(): #location of first menu mousePos((682, 519)) leftClick() time.sleep(.1) leftClick() time.sleep(.5) #location of second menu mousePos((1208, 528)) leftClick() time.sleep(.5) #location of third menu mousePos((921, 479)) leftClick() time.sleep(.5) #location of fourth menu mousePos((651, 350)) leftClick() time.sleep(.5) def screenGrab(): box = (x_pad+1,y_pad+1,x_pad+1362,y_pad+770) im = ImageGrab.grab(box) im.save(os.getcwd() + '\\full_snap__' + str(int(time.time())) + '.png', 'PNG') def mousePos(cord): win32api.SetCursorPos((x_pad + cord[0], y_pad + cord[1])) def get_cords(): x,y = win32api.GetCursorPos() x = x - x_pad y = y - y_pad print x,y def leftClick(): win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0) time.sleep(.1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0) print "Click." def main(): pass if __name__ == "__MAIN__": main() And when i run start() i get this: Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================ >>> >>> start() 'Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> start() File "C:\Users\User\Desktop\py\game.py", line 12, in start mousePos((682, 519)) File "C:\Users\User\Desktop\py\game.py", line 42, in mousePos win32api.SetCursorPos((x_pad + cord[0], y_pad + cord[1])) error: (0, 'SetCursorPos', 'No error message is available')' >>> I have no idea why this happens and i have tryed many solutions from this site ,could it be the game? What i want to know is if the game is the cause of the error or I have missed something , and if there is a posible solution. Answer: are you running through the tutorial from <http://dev.tutsplus.com/tutorials/how-to-build-a-python-bot-that-can-play- web-games--active-11117>? Shouldn't be an issue with it, i went through the same and it worked.
how can I get the gap colum in python? Question: the log format is like that 100 0 0 1 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 15 1 16 1 17 1 18 1 19 1 20 1 21 1 22 1 23 1 24 1 25 1 26 1 27 1 28 1 29 1 30 1 31 1 32 1 33 1 34 1 35 1 And I write python code, def read_data(filename, sep=" ", filt=int): def split_line(line): return line.split(sep) def apply_filt(values): return map(filt, values) def process_line(line): return apply_filt(split_line(line)) f = open(filename) lines = map(process_line, f.readlines()) # "[1]" below corresponds to x0 X = np.array([ l[3:] for l in lines]) # "or -1" converts 0 values to -1 Y = np.array([l[1] or -1 for l in lines]) f.close() return X, Y X are getted from 3 colums,and Now I want to get every gap colum from the third colums,how can I change the code,and the X will be 1 1 1 1 1 1 1 1 1 1 Y are getted l[1] or -1.But I want to get 1 if l1 is greater than 0,and get -1 if l1 is equal to 0.How can I change it again? Answer: I'm going to guess you want something like this: import numpy as np try: from cStringIO import StringIO except: from StringIO import StringIO def read_data(f, sep=" ", filt=int): def split_line(line): return line.split(sep) def apply_filt(values): return map(filt, values) def process_line(line): return apply_filt(split_line(line)) #f = open(filename) lines = np.array(map(process_line, f.readlines()), dtype=int) # "[1]" below corresponds to x0 X = lines[:,3::2] # "or -1" converts 0 values to -1 Y = lines[:,:] Y[Y<=0]=-1 f.close() return X, Y reader = StringIO('100 0 0 1 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 15 1 16 1 17 1 18 1 19 1 20 1 21 1 22 1 23 1 24 1 25 1 26 1 27 1 28 1 29 1 30 1 31 1 32 1 33 1 34 1 35 1\n') x,y = read_data(reader) reader.close print 'X:', x print 'Y:', y which gives: X: [[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]] Y: [[100 -1 -1 1 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 15 1 16 1 17 1 18 1 19 1 20 1 21 1 22 1 23 1 24 1 25 1 26 1 27 1 28 1 29 1 30 1 31 1 32 1 33 1 34 1 35 1]]
ImportError: No module named redis Question: I have installed redis using `sudo apt-get install redis-server` command but I am receiving this error when I run my Python program: `ImportError: No module named redis` Any idea what's going wrong or if I should install any other package as well? I am using Ubuntu 13.04 and I have Python 2.7. Answer: To install redis-py, simply: $ sudo pip install redis or alternatively (you really should be using pip though): $ sudo easy_install redis or from source: $ sudo python setup.py install Getting Started >>> import redis >>> r = redis.StrictRedis(host='localhost', port=6379, db=0) >>> r.set('foo', 'bar') True >>> r.get('foo') 'bar' Details:<https://pypi.python.org/pypi/redis>
wxpython panel size and titles Question: When I apply the following code, the second panel is showed over the first one. I would like to know how I can get the two panels without overlapping and with the appropriate size of the window (frame). I would also like to know if there is any suitable way to draw some kind of titles in a panel (in this case, "Inputs:" and "Outputs:"). Thanks! import wx class Input_Panel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) # Input variables self.tittle1 = wx.StaticText(self, label="Inputs:") self.lblname1 = wx.StaticText(self, label="Input 1:") self.format1 = ['Option 1','Option 2'] self.combo1 = wx.ComboBox(self, size=(200, -1),value='', choices=self.format1, style=wx.CB_DROPDOWN) self.lblname2 = wx.StaticText(self, label="Input 2") self.format2 = ['Option 1','Option 2', 'Option 3'] self.combo2 = wx.ComboBox(self, size=(200, -1),value='', choices=self.format2, style=wx.CB_DROPDOWN) # Set sizer for the panel content self.sizer = wx.GridBagSizer(2, 2) self.sizer.Add(self.tittle1, (1, 2)) self.sizer.Add(self.lblname1, (2, 1)) self.sizer.Add(self.combo1, (2, 2)) self.sizer.Add(self.lblname2, (3, 1)) self.sizer.Add(self.combo2, (3, 2)) self.SetSizer(self.sizer) class Output_Panel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) # Output variables self.tittle2 = wx.StaticText(self, label="Outputs:") self.lblname3 = wx.StaticText(self, label="Output1") self.result3 = wx.StaticText(self, label="", size=(100, -1)) # Set sizer for the panel content self.sizer = wx.GridBagSizer(2, 2) self.sizer.Add(self.tittle2, (1, 2)) self.sizer.Add(self.lblname3, (2, 1)) self.sizer.Add(self.result3, (2, 2)) self.SetSizer(self.sizer) class Main_Window(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title = title) # Set variable panels self.splitter = wx.SplitterWindow(self) self.panel1 = Input_Panel(self.splitter) self.panel2 = Output_Panel(self.splitter) self.splitter.SplitVertically(self.panel1, self.panel2) self.windowSizer = wx.BoxSizer(wx.VERTICAL) self.windowSizer.Add(self.splitter, 1, wx.ALL | wx.EXPAND) self.SetSizerAndFit(self.windowSizer) def main(): app = wx.App(False) frame = Main_Window(None, "App GUI") frame.Show() app.MainLoop() if __name__ == "__main__" : main() Answer: You can use the Widget Inspection Tool to help you figure out what's going on. I used its highlight functionality to figure out where and what size each of the panels were. You can read more about it here: <http://wiki.wxpython.org/Widget%20Inspection%20Tool> The SplitterWindow does not split items equally. You will need to call the splitter's SetMinimumPaneSize to make them both visible. I modified your code to show you what I'm talking about and also to demonstrate how to add the inspection tool: import wx class Input_Panel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) # Input variables self.tittle1 = wx.StaticText(self, label="Inputs:") self.lblname1 = wx.StaticText(self, label="Input 1:") self.format1 = ['Option 1','Option 2'] self.combo1 = wx.ComboBox(self, size=(200, -1),value='', choices=self.format1, style=wx.CB_DROPDOWN) self.lblname2 = wx.StaticText(self, label="Input 2") self.format2 = ['Option 1','Option 2', 'Option 3'] self.combo2 = wx.ComboBox(self, size=(200, -1),value='', choices=self.format2, style=wx.CB_DROPDOWN) # Set sizer for the panel content self.sizer = wx.GridBagSizer(2, 2) self.sizer.Add(self.tittle1, (1, 2)) self.sizer.Add(self.lblname1, (2, 1)) self.sizer.Add(self.combo1, (2, 2)) self.sizer.Add(self.lblname2, (3, 1)) self.sizer.Add(self.combo2, (3, 2)) self.SetSizer(self.sizer) class Output_Panel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) # Output variables self.tittle2 = wx.StaticText(self, label="Outputs:") self.lblname3 = wx.StaticText(self, label="Output1") self.result3 = wx.StaticText(self, label="", size=(100, -1)) # Set sizer for the panel content self.sizer = wx.GridBagSizer(2, 2) self.sizer.Add(self.tittle2, (1, 2)) self.sizer.Add(self.lblname3, (2, 1)) self.sizer.Add(self.result3, (2, 2)) self.SetSizer(self.sizer) class Main_Window(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title = title, size=(800,600)) # Set variable panels self.splitter = wx.SplitterWindow(self, style = wx.SP_LIVE_UPDATE) self.panel1 = Input_Panel(self.splitter) self.panel2 = Output_Panel(self.splitter) self.splitter.SplitVertically(self.panel1, self.panel2) w, h = self.GetSize() self.splitter.SetMinimumPaneSize(w/2) self.windowSizer = wx.BoxSizer(wx.VERTICAL) self.windowSizer.Add(self.splitter, 1, wx.ALL | wx.EXPAND) #self.SetSizerAndFit(self.windowSizer) def main(): import wx.lib.inspection app = wx.App(False) frame = Main_Window(None, "App GUI") frame.Show() wx.lib.inspection.InspectionTool().Show() app.MainLoop() if __name__ == "__main__" : main()
packaging with numpy and test suite Question: # Introduction Disclaimer: I'm very new to python packaging with distutils. So far I've just stashed everything into modules, and packages manually and developed on top of that. I never wrote a `setup.py` file before. I have a Fortran module that I want to use in my python code with numpy. I figured the best way to do that would be f2py, since it is included in numpy. To automate the build process I want to use distutils and the corresponding numpy enhancement, which includes convenience functions for f2py wrappers. I do not understand how I should organize my files, and how to include my test suite. What I want is the possibility to use `./setup.py` for building, installing, and testing, and developing. My directory structure looks as follows: volterra ├── setup.py └── volterra ├── __init__.py ├── integral.f90 ├── test │   ├── __init__.py │   └── test_volterra.py └── volterra.f90 And the `setup.py` file contains this: def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('volterra', parent_package, top_path) config.add_extension('_volterra', sources=['volterra/integral.f90', 'volterra/volterra.f90']) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) After running `./setup.py build` I get. build/lib.linux-x86_64-2.7/ └── volterra └── _volterra.so Which includes neither the `__init__.py` file, nor the tests. # Questions * Is it really necessary to add the path to every single source file of the extension? (I.e. `volterra/integral.f90`) Can't I give a parameter which says, look for stuff in `volterra/`? The `top_path`, and `package_dir` parameters didn't do the trick. * Currently, the `__init__.py` file is not included in the build. Why is that? * How can I run my tests in this setup? * What's the best workflow for doing development in such an environment? I don't want to _install_ my package for every single change I do. How do you do development in the source directory when you need to compile some extension modules? Answer: Here is setup.py from a project I made. I have found figuring out setup.py / packaging to be frustrating with no solid answers and definitely not pythonic in the sense of having one and only one obvious way to do something. Hopefully this will help a little. The points you may find useful are: * `find_packages` which removes the drudgery of including lots of files or messing around with generating manifest. * `package_data` which allows you to easily specify non .py files to be included * `install_requires` / `tests_require` You'll need to find the source for distribute_setup.py if you don't have it already. > * Is it really necessary to add the path to every single source file of > the extension? (I.e. volterra/integral.f90) Can't I give a parameter which > says, look for stuff in volterra/? The top_path, and package_dir parameters > didn't do the trick. > * Currently, the **init**.py file is not included in the build. Why is > that? > Hopefully `find_packages()` will solve both of those. I don't have much experience packaging but I haven't had to go back to manual inclusion yet. > * How can I run my tests in this setup? > I think this is probably a different question with many answers depending on how you are doing tests. Maybe you can ask it separately? As a side note, I am under the impression that the standard is to put your tests directory at the top level. I.e. `volterra/volterra` and `volterra/tests`. > * What's the best workflow for doing development in such an environment? I > don't want to install my package for every single change I do. How do you do > development in the source directory when you need to compile some extension > modules? > This might be worth another question as well. I don't see why you would need to install your package for every single change. If you are uploading the package, just don't install it on your dev system (except to test installation) and work directly from your development copy. Maybe I'm missing something though since I don't work with compiled extensions. * * * Here is the example try: from setuptools import setup, find_packages except ImportError: from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( # ... other stuff py_modules=['distribute_setup'], packages=find_packages(), package_data={'': ['*.png']}, # for me to include anything with png install_requires=['numpy', 'treenode', 'investigators'], tests_require=['mock', 'numpy', 'treenode', 'investigators'], )
Python match a string with regex Question: I need a python regular expression to check if a word is present in a string. The string is separated by commas, potentially. So for example, line = 'This,is,a,sample,string' I want to search based on "sample", this would return true. I am crappy with reg ex, so when I looked at the python docs, I saw something like import re re.match(r'sample', line) But I don't know why there was an 'r' before the text to be matched. Can someone help me with the regular expression? Answer: Are you sure you need a regex? It seems that you only need to know if a word is present in a string, so you can do: >>> line = 'This,is,a,sample,string' >>> "sample" in line True
Using python ctypes invoke gtk_builder Question: my python code is: gtk = CDLL('/usr/lib/x86_64-linux-gnu/libgtk-x11-2.0.so') builder = gtk.gtk_builder_new() print gtk.gtk_builder_add_from_file(builder, './mainui.glade', None) I tested the c code, it works. But with python ctype, the result of gtk_builder_add_from_file is always 0, e.g there is an error. I'm very confused.. Answer: Why don't you use the introspection feature? There is a reason it exists. from gi.repository import Gtk as gtk class Foo (object): def __init__(self): self.builder = gtk.Builder() self.builder.add_from_file("someui.glade") self.builder.connect_signals(self) def run(self, *args): self.builder.get_object("mainwindow").show() gtk.main() def quit(self, *args): gtk.main_quit() Foo().run() * * * if that is not an option, pass a `GError **` instead of none to get some more information regarding the issue (might be in your `*.glade` file or missing permissions)