input_text
stringlengths
1
40.1k
target_text
stringlengths
1
29.4k
What do the different values of the kind argument mean in scipy interpolate interp1d? The <a href="http://docs scipy org/doc/scipy-0 14 0/reference/generated/scipy interpolate interp1d html#scipy interpolate interp1d" rel="nofollow">SciPy documentation</a> explains that `interp1d`'s `kind` argument can take the values `‘linear’` `‘nearest’` `‘zero’` `‘slinear’` `‘quadratic’` `‘cubic’` The last three are spline orders and `'linear'` is self-explanatory What do `'nearest'` and `'zero'` do?
‘nearest’ returns data point from X nearest to the argument or `interpolates function y=f(x) at the point x using the data point nearest to x` 'zero' I would guess is equivalent to truncation of argument and thus using data point closest toward zero
How to compare keys of two different dictionaries in Python? I have two dictionaries and I want to compare the values of the corresponding keys For example if I have ````dict1 = {'a':1 'b':0 'c':3} dict2 = {'a':0 'b':0 'c':4} ```` then this should return `False` because `dict2` cannot have a corresponding value larger than that of `dict11` (it was okay in `dict2` that `'a'` had a smaller value than that of `dict1` but not okay that `'c'` in `dict2` had value larger than that of `dict1`) Also it is not allowed if `dict2` has a value that is not listed in `dict1` For instance: ````dict1 = {'a':1 'b':0 'c':3} dict2 = {'a':0 'b':0 would':2} ```` (But it is okay if `dict1` has values that `dict2` does not) In other words `dict2` has to be a subset of `dict1` in regards to both keys and values As soon as the code catches one of these violations I want to immediately stop everything from running and just return False This is what I tried: ````condition = True #True by default for letter in dict2: if dict2[letter] &gt; dict1[letter] or dict1[letter] == None: condition = False break break ```` But I get a `KeyError` when I run into a key that is listed in `dict1` and not in `dict2` How do I fix this?
I think you are looking for something like this: ````condition = all(k in dict1 and dict2[k] <= dict1[k] for k in dict2) ```` You asked in the comments how to read this That is difficult to answer because not everyone would look at it the same way Perhaps if I tell you how I got to that expression it may help I read your question as saying "every key in dict2 must be in dict1 and the value in dict2 must not be greater than the value from dict1" which I re-expressed as "for all k in dict2 k in dict1 and dict2[k] <= dict1[k]" which seemed a clear case for the `all()` function and the `for` move to the end
Where are poachers located in the rain forest area originally from?
null
How to call Qt Thread (QThread) from another python file? (QThread is destroyed) How should I call a `QThread` that is defined in another python file? here is my code mymain py ````from PyQt4 import QtCore QtGui import PyQt4 import sys import os from time import sleep try: _fromUtf8 = QtCore QString fromUtf8 except AttributeError: _ fromUtf8 = lambda s: s class Ui_MainWindow(QtGui QMainWindow): def __init__(self): QtGui QWidget __init__(self) self setupUi(self) def setupUi(self MainWindow): MainWindow setObjectName(_fromUtf8("MainWindow")) self showMaximized() MainWindow setStyleSheet(_fromUtf8("background-color: rgb(0 0 0);")) self centralwidget = QtGui QWidget(MainWindow) self centralwidget setObjectName(_fromUtf8("centralwidget")) self horizontalLayout = QtGui QHBoxLayout(self centralwidget) self horizontalLayout setObjectName(_fromUtf8("horizontalLayout")) self gridLayout = QtGui QGridLayout() self gridLayout setObjectName(_fromUtf8("gridLayout")) spacerItem = QtGui QSpacerItem(20 40 QtGui QSizePolicy Minimum QtGui QSizePolicy Expanding) self gridLayout addItem(spacerItem 2 0 1 1) self horizontalLayout_2 = QtGui QHBoxLayout() self horizontalLayout_2 setObjectName(_fromUtf8("horizontalLayout_2")) self verticalLayout = QtGui QVBoxLayout() self verticalLayout setObjectName(_fromUtf8("verticalLayout")) self lblNowServing = QtGui QLabel(self centralwidget) font = QtGui QFont() font setFamily(_fromUtf8("Bebas Neue")) font setPointSize(140) self lblNowServing setFont(font) self lblNowServing setStyleSheet(_fromUtf8("color: rgb(170 0 0);")) self lblNowServing setObjectName(_fromUtf8("lblNowServing")) self lblNowServing setAlignment(QtCore Qt AlignCenter) self verticalLayout addWidget(self lblNowServing) self lblNowServingNumber = QtGui QLabel(self centralwidget) font = QtGui QFont() font setFamily(_fromUtf8("DS-Digital")) font setPointSize(350) self lblNowServingNumber setFont(font) self lblNowServingNumber setStyleSheet(_fromUtf8("color: rgb(170 0 0);")) self lblNowServingNumber setObjectName(_fromUtf8("lblNowServingNumber")) self lblNowServingNumber setAlignment(QtCore Qt AlignCenter) self verticalLayout addWidget(self lblNowServingNumber) self horizontalLayout_2 addLayout(self verticalLayout) self verticalLayout_2 = QtGui QVBoxLayout() self verticalLayout_2 setObjectName(_fromUtf8("verticalLayout_2")) self lblCounter = QtGui QLabel(self centralwidget) font = QtGui QFont() font setFamily(_fromUtf8("Bebas Neue")) font setPointSize(140) self lblCounter setFont(font) self lblCounter setStyleSheet(_fromUtf8("color: rgb(170 0 0);")) self lblCounter setObjectName(_fromUtf8("lblCounter")) self lblCounter setAlignment(QtCore Qt AlignCenter) self verticalLayout_2 addWidget(self lblCounter) self lblCounterNumber = QtGui QLabel(self centralwidget) font = QtGui QFont() font setFamily(_fromUtf8("DS-Digital")) font setPointSize(350) self lblCounterNumber setFont(font) self lblCounterNumber setStyleSheet(_fromUtf8("color: rgb(170 0 0);")) self lblCounterNumber setObjectName(_fromUtf8("lblCounterNumber")) self lblCounterNumber setAlignment(QtCore Qt AlignCenter) self verticalLayout_2 addWidget(self lblCounterNumber) self horizontalLayout_2 addLayout(self verticalLayout_2) self gridLayout addLayout(self horizontalLayout_2 0 0 1 1) spacerItem = QtGui QSpacerItem(20 40 QtGui QSizePolicy Minimum QtGui QSizePolicy Expanding) self gridLayout addItem(spacerItem 1 0 1 1) self horizontalLayout addLayout(self gridLayout) MainWindow setCentralWidget(self centralwidget) self retranslateUi(MainWindow) QtCore QMetaObject connectSlotsByName(MainWindow) def retranslateUi(self MainWindow): MainWindow setWindowTitle(QtGui QApplication translate("MainWindow" "MainWindow" None QtGui QApplication UnicodeUTF8)) self lblNowServing setText(QtGui QApplication translate("MainWindow" " NOW SERVING " None QtGui QApplication UnicodeUTF8)) self lblCounter setText(QtGui QApplication translate("MainWindow" "COUNTER" None QtGui QApplication UnicodeUTF8)) self lblCounterNumber setText(str(1)) self lblNowServingNumber setText(str(1)) class valChange(QtCore QThread): def __init__(self): QtCore QThread __init__(self) def run(self): self myctr = 0 self myval = 0 self lblNowServingNumber setText(str(myval)) self lblCounterNumber setText(str(myctr)) if __name__=='__main__': app = QtGui QApplication(sys argv) ex = Ui_MainWindow() ex show() sys exit(app exec_()) ```` exarg py ````from PyQt4 import QtCore QtGui import mymain import sys getopt def main(argv): ctr = '' val = '' try: opts args = getopt getopt(argv "hi:o:" ["ifile=" "ofile="]) except getopt GetoptError: print 'test py -i <ctr&gt; -o <val&gt;' sys exit(2) for opt arg in opts: if opt == '-h': print 'test py -i <ctr&gt; -o <val&gt;' sys exit() elif opt in ("-i" "--ifile"): ctr = arg elif opt in ("-o" "--ofile"): val = arg m = mymain valChange() m myctr = ctr m myval = val m start() if __name__ == "__main__": app = QtGui QApplication(sys argv) main(sys argv[1:]) ```` this is what i did I run the mymain py in she will and i run the exarg py in terminal/command line using this command <blockquote> sudo python exarg py -i 3 -o 4 </blockquote> but I always got an error saying: <blockquote> 'QThread: Destroyed while thread is still running' </blockquote> any comments/suggestions would be highly appreciated thanks
There are a couple of things wrong with your code as it currently stands The first is that you do not appear to call `app exec_()` anywhere (at least when you run `exarg py`) to actually start your `QApplication` But perhaps you just forgot to include that? Second is that you create your thread inside a function and assign it to the variable `m` As soon as the function `main` ends that local variable is garbage collected and your thread is destroyed You need to make sure this does not happen Either by making `m` a global variable or returning `m` from the function and holding a reference to it or you could not create it inside the function As long as you always hold a reference to your thread it will not be destroyed and you will not see that error message! Finally you should <strong>never</strong> modify GUI objects from a thread directly Qt widgets are not thread safe! What you need to do is define a signal in your thread and connect a slot (from the main thread) to that signal when you create the thread You can then `emit` a signal from your thread (this is thread-safe) which will call a slot in the main thread where you are allowed to modify the GUI <a href="http://stackoverflow com/q/29269539/1994235">This</a> question/answer demonstrates approximately how to do this EDIT: Also the `global myctr` etc code is confusing You should not need that Just access them as `self myctr` from within the thread since you have written `m myctr = ctr` before calling `m start()`
Best solution to get and store user's real time position? Hi I am writing an Android lbs game I need to: - store user's real time position(lat lon) - get users that are near to a given position I have wrote some back-end api with django and mysql(for example get user name and age by his id) what is the best solution to do what I said above (with django/python)? Should I use a nosql database like redis? And how should the positions be stored in database so I can quickly get positions that is near to a given position?
Hav you considered <a href="https://docs djangoproject com/en/dev/ref/contrib/gis/tutorial/#" rel="nofollow">geodjango</a>? From the docs : <blockquote> GeoDjango is an add-on for Django that turns it into a world-class geographic Web framework GeoDjango strives to make it as simple as possible to create geographic Web applications like location-based services </blockquote>
OpenOPC on Windows: Clas not registered I am having problems with OpenOPC library (OpenOPC-1 2 0 win32-py2 7) on Windows 7 64bit machine ````&gt;&gt;&gt; import OpenOPC &gt;&gt;&gt; i =OpenOPC client() Traceback (most recent call last): File "<stdin&gt;" line 1 in <module&gt; File "OpenOPC py" line 170 in __init__ raise OPCError error_msg OpenOPC OPCError: Dispatch: Class not registered ```` What could be the because of this error? My command line opc client works fine
<strong>Class not registered error</strong> is due to wrong OPC server class ID or the OPC server not exists
How many women were in the top twelve on season nine of American Idol?
six
Who declared the King capable of excersizing power again after a brief lapse in 1990?
both houses of parliament
What type of industrial activity was evident in Greece in the period researched?
shipbuilding
How to override save() method of modelform class and added missing information? I just started to learn Django and I had a question I am trying to automatically add the missing information when saving form data I get to change/add the desired "cleaned_data" information by overriding save() method of modelform class but changes are not recorded in the database Actually how to write the modified information? This is code: ````def save(self commit = True *args **kwargs): temp = ServiceMethods(url = self cleaned_data get('url') wsdl_url = self cleaned_data get('wsdl_url')) if not temp get_wsdl_url(): temp make_wsdl_url() if temp get_wsdl_url(): temp make_wsdl() self cleaned_data['wsdl_url'] = temp get_wsdl_url() self cleaned_data['wsdl_description'] = temp get_wsdl_description() super(ServiceForm self) save(commit = commit *args **kwargs) ```` And model: ````class Services(models Model): name = models CharField('Имя' max_length=256) url = models URLField('Ссылка' unique = True) wsdl_url = models URLField('Ссылка на WSDL-документ' blank=True) description = models TextField('Описание сервиса' blank=True) wsdl_description = models TextField('WSDL описание' blank=True editable=False) added = models DateTimeField('Добавлено' auto_now_add=True) ```` TIA
Try setting the data on `self instance` instead of in `self cleaned_data` and let me know if that works
Pyramid setting mako imports not working I am trying to use the <a href="http://pyramid readthedocs org/en/latest/narr/environment html#mako-import" rel="nofollow">mako imports</a> setting to avoid importing modules in every template file Originally I had a module-level block at the top of every template like: ````<%! import logging %&gt; ```` And I would like to replace that with a setting in the ini file: ````mako imports = 'import logging' ```` This does not work as the template just throws `NameError: name 'logging' is not defined` when I attempt to use it It appears the mako imports does not even get called since a setting like: ````mako imports = 'import SpamAndEggs' ```` does not throw an error I am using Pyramid 1 3 and Mako 0 7 0
Ok so looking at the Pyramid-generated Mako template code it just literally outputs what is in that config setting quotes brackets and all So the syntax has to be: `mako imports = import logging` with multiple imports as: `mako imports = import logging some other module` and <strong>not</strong> any of these: ````mako imports = 'import logging' mako imports = ['import logging' 'some other module'] mako imports = import logging import some other module ```` The last throws a `mako exceptions SyntaxException` since it is not valid Python but the first 2 fail silently doing nothing since they just output a literal as a line of code I did not infer this from the <a href="http://pyramid readthedocs org/en/latest/narr/environment html#mako-import" rel="nofollow">documentation</a> that reads "String list of Python statements typically individual “import” lines" (but maybe I just did not understand it correctly) Thanks to Mike Bayer for his <a href="https://groups google com/forum/#!topic/mako-discuss/RNUfqX12YHE" rel="nofollow">post</a> on Mako
Which entity runs Nigeria's bone marrow donation program?
the University of Nigeria
ssh by a python cgi script is not working I have a couple of things to ask I am getting following error while trying to ssh remote host from a python CGI ````Could not create directory '/var/www/ ssh' Failed to add the RSA host key for IP address '17 172 221 39' to the list of known hosts (/var/www/ ssh/known_hosts) Permission denied (gssapi-keyex gssapi-with-mic publickey keyboard-interactive) ```` Is this becuse its not taking my password or is it because of apache eing user and ssh is not allowed How to make sure ssh happens without having to do ssh key initiation for this on all hosts how can i Run a cgi script as root user and not as apache user I have to run few scripts only as root I cannot use SuExec etc Please provide the work around for these 2 issues i am facing
Web server process is owned by apache user not as root - Make sure that apache user have password less access to other server - SELinux should be disabled Refer : <a href="http://wccandlinux blogspot in/2016/07/how-to-run-ssh-command-from-apache html" rel="nofollow">http://wccandlinux blogspot in/2016/07/how-to-run-ssh-command-from-apache html</a>
python functions ````class Test: def func(): print('func') test1 = Test() test2 = Test() test1 func() #TypeError: fun1() takes no arguments (1 given) test2 newfunc = Test func test2 newfunc()#It goes well # update part def foo(self): pass Test foo = foo test1 foo # it is bound method test2 foo = foo test2 foo # it is function # end ```` Is there any difference between the two ways ? Thanks ````# update part def foo(self): pass Test foo = foo test1 foo # it is bound method test2 foo = foo test2 foo # it is function # end ```` Note that what is important is that the retrieval should take place in class instead of instance
Methods of a class that are called on an instance of the class are passed the instance reference as an argument automatically Thus they are usually declared with a `self` argument: ````class Test: def func(self): print('func') test1 = Test() test1 func() # self = test1 ````
Python - Remove Square symbol from text string ````a='ÿþ"[]B[]a[]l[]a[]n[]c[]e' ```` NOTE: The open and close square brackets represent this square symbol I cannot however copy and paste the square symbol into here to show you exactly what I am looking at The characters in 'a' represent the beginning of a file I have downloaded It is a csv file unicode How do I remove these unwanted characters? I would just like to recover the word 'balance' from a The code I have used to simply this example: ````fi = open(path+fn 'r') data = fi read() fi close() print(data) ```` Where `fn` is a csv file Tried: ````data=data encode() d=replace('\x00' '') ```` which produced error: ````TypeError: expected bytes bytearray or buffer compatible object ````
You need to specify the right encoding when opening the file Try ````open(path+fn 'r' encoding="utf-16") ```` (I am guessing utf-16 because ASCII characters seem to be encoded in two bytes in the sample string)
Looping over a list in a Jinja2 template I Am trying to make a simple blog website with the Flask framework Each entry in my blog has a title text and comments the title and text are stored in a table named entries and the comments in a table named comments that links the comments to the corresponding entry with a foreign key The problem I have now is that I want to display the comments in my html file To do is I want to call a python function named show_comments in my html file while I am in a for loop The python function looks like this: ````@app route('/comments/<entryid&gt;') def show_comments(entryid): db = get_db() curId = db execute('select id comment from comments where entry_id=entryid order by id desc') comments = [dict(id=row[0] comment=row[1]) for row in curId fetchall()] return render_template('show_entries html' comments=comments) ```` My template looks like this: ````% extends "layout html" %} {% block body %} {% if session logged_in %} <form action="{{ url_for('add_entry') }}" method=post class=add-entry&gt; <dl&gt; <dt&gt;Title: <dd&gt;<input type=text size=30 name=title&gt; <dt&gt;Text: <dd&gt;<textarea name=text rows=5 cols=40&gt;</textarea&gt; <dd&gt;<input type=submit value=Share&gt; </dl&gt; </form&gt; {% endif %} <ul class=entries&gt; {% for entry in entries %} <li&gt;<h2&gt;{{ entry title }}</h2&gt;{{ entry text }} {{ url_for('show_comments' entryid=entry id) }} <ul class=comments&gt; {% for acomment in comments %} <li&gt;{{ acomment comment }} </li&gt; </br&gt; </ul&gt; {% endfor %} {% if session logged_in %} <form action="{{ url_for('add_comment' key=entry id) }}" method=post class=add-entry&gt; <dl&gt; <dt&gt;Comment: <dd&gt;<textarea name=comment rows=2 cols=40&gt;</textarea&gt; <dd&gt;<input type=submit value=Comment&gt; </dl&gt; </form&gt; {% endif %} {% else %} <li&gt;<them&gt;Unbelievable No entries here so far</them&gt; {% endfor %} </ul&gt; {% endblock %} ````
You have not really told us what your problem is so I do not know if this will help But I will point out three specific mistakes here: The first is that you are putting your comments in an unordered list (the `<ul&gt;` tag) but you put the end tag (`</ul&gt;`) inside the loop instead of outside it `</br&gt;` should be written `<br /&gt;` but really that tag does not belong there in the first place Second your HTML is broken HTML attributes (the parts in tags like `type=submit`) should have quotation marks around the values For example it should look like `type="submit"` Most browsers are forgiving when it comes to things like that but it is better not to count on that and write correct HTML
Python stop recursion once solution is found I have a recursive function which tries to form a certain sum given a list of integers The function works but it gives me all possible solutions I want to break out of the recursive function once a solution is found How can I do that? Below is the (pseudo-)code for the function: ````function find_sum(list_of_integers target_sum partial_solution): if partial_solutions == target_sum: return True if partial_solution &gt; target_sum: return for i in range(len(list_of_integers)): n = list_of_integers[i] remaining = list_of_integers[i+1:] find_sum(remaining target_sum partial_solution n) ```` So I just want to know if the target_sum can be formed by the list of integers I do not need all the solutions
You need to check the return value of the recursive call; if `True` is returned propagate that immediately rather than continue to loop: ````for i in range(len(list_of_integers)): n = list_of_integers[i] remaining = list_of_integers[i+1:] found = find_sum(remaining target_sum partial_solution n) if found: return True ````
opencv backgroundsubtractor not updating I am using python 2 7 9 and opencv version 2 4 8 I am trying to detect moving cars from a movie First frame in the movie already has a car and once the car leaves the contour stays there I tried playing with BackgroundSubtractorMOG params but they seemed to be ignored Setting history to 10 does nothing and 200 frames into the movie I still have the original contour Thanks for reading
In reading opencv tickets I found that Sebastian Ramirez found the problem source and a solution The problem is that method "apply" has learningRate set to zero by default Solve the problem by calling it like this: history = 10 # or whatever is appropriate for you fgmask = fgbg apply(frame learningRate = 1 0/history)
How can I override the keyboard interrupt? (Python) Is there anyway I can make my script execute one of my functions when `Ctrl+c` is hit when the script is running?
Take a look at <a href="http://docs python org/library/signal html#example">signal handlers</a> CTRL-C corresponds to <a href="http://en wikipedia org/wiki/SIGINT_%28POSIX%29">SIGINT</a> (signal #2 on posix systems) Example: ````#!/usr/bin/env python import signal import sys def signal_handler(signal frame): print 'You pressed Ctrl+C - or killed me with -2' sys exit(0) signal signal(signal SIGINT signal_handler) print 'Press Ctrl+C' signal pause() ````
Python hold on the HTTP connection before sending files? <strong>Problem</strong> This problem has bothered me quite a long time I am dealing with a web API which provides the function that query the database by some specific conditions fetch the qualified data back and generate an <them><strong> xls</strong></them> file for download However the data amount is really really large so generate the <them><strong> xls</strong></them> file will relatively cost a long time <strong>This may cause an HTTP Timeout</strong> I used to created a generator to yield the records line by line formatted by <them><strong> csv</strong></them> It works well on the aspect of performance(I mean fast to generate and download) with some side effects however As I mentioned in the previous two questions: - <a href="http://stackoverflow com/questions/28070098/how-can-i-adapt-my-code-to-make-it-compatible-to-microsoft-excel">How can I adapt my code to make it compatible to Microsoft Excel?</a> - <a href="http://stackoverflow com/questions/28082937/how-can-i-send-an-xls-file-one-line-per-time-through-http-response">How can I send an xls file one line per time through http response?</a> <strong>Qeustions</strong> <blockquote> After a serious consideration I finally decide to generate the whole <them><strong> xls</strong></them> file on the server side and then provide for download But how can I maintain the http connection during the time for generating the <them><strong> xls</strong></them> file? </blockquote>
<strong>"How can I maintain the http connection during the time for generating the xls file?"</strong> Simple answer: you cannot A least you cannot guarantee that a single simple HTTP GET request (and the underlying TCP connection) work reliably Depending on the client specifics and the network the client is inside your users might often experience errors (connection timeouts which your application does not handle) So the right question is: which technology do you need to let users get this file independent of how long it takes to generate and of how bad their Internet connection is? There are many possible approaches and all of them have their disadvantages Depending on which browsers you want to support there are a couple of options All of them require client-side JavaScript usage You might want to use the modern <a href="http://en wikipedia org/wiki/Server-sent_events" rel="nofollow">Server-Sent events</a> which allows the server to actively trigger an event in the browser to which the browser can respond as desired A more classical approach would be (long) polling over HTTPS where you do as before but configure the timeout times in client as well as server to be quite large Additionally you need to have JavaScript in place that just repeats the request in case it has timed out Also there are dirty techniques established for preventing a timeout You might want to have to do some research using the terms "server push" "comet" "long polling" Doing so you will probably read about WebSockets (which you do not directly need in my opinion) I guess if I were you I would now choose to use Server-sent events But you have to figure this out yourself depending on your exact requirements By a quick glance the introduction to this article may be a good read: <a href="https://jersey java net/documentation/latest/sse html" rel="nofollow">https://jersey java net/documentation/latest/sse html</a> Also the introduction of the <a href="http://www w3 org/TR/2012/WD-eventsource-20120426/" rel="nofollow">W3C Server-Sent Events specification</a> is nice Quote: <blockquote> Event streams requests can be redirected using HTTP 301 and 307 redirects as with normal HTTP requests <strong>Clients will reconnect if the connection is closed</strong>; a client can be told to stop reconnecting using the HTTP 204 No Content response code Using this API rather than emulating it using XMLHttpRequest or an iframe allows the user agent to make better use of network resources in cases where the user agent implementor and the network operator are able to coordinate in advance Amongst other benefits this can result in significant savings in battery life on portable devices This is discussed further in the section below on connectionless push </blockquote>
Parser returns "\n" instead of desired output I have to parse the player names of adelaide crows from <a href="http://www afl com au/news/teams?round=9" rel="nofollow">this link</a> for that I have written a parser like this ````import requests from bs4 import BeautifulSoup href_val = requests get("http://www afl com au/news/teams?round=9") soup1 = BeautifulSoup(href_val content) players_info_adel = soup1 find_all("ul" {"class" : "team1 team-adel"}) for li in players_info_adel: player_names_adel = li find_all("li" {"class" : "player"}) #print player_names_adel #print player_names_adel for span in player_names_adel: if span find(text = True): text = '' join(span find(text = True)) text1 = text encode('ascii') print text ```` but whenever I run this code I always get bunch of `"\n"` printed instead of the names what should I do to get the names of the players?
You do not want to <them>loop</them> over each player `<li&gt;` element; the first element is a text node with just a newline in it Better use `Tag get_text()` to get all text from the element instead Using a CSS selector to simplify the code: ````for player in soup1 select('ul team1 li player'): text = player get_text() strip() print text ```` This includes the player number; you can separate this number and the player name by using: ````number name = player span get_text() strip() player span next_sibling strip() ```` instead Demo: ````&gt;&gt;&gt; import requests &gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;&gt; href_val = requests get("http://www afl com au/news/teams?round=9") &gt;&gt;&gt; soup1 = BeautifulSoup(href_val content) &gt;&gt;&gt; for player in soup1 select('ul team1 li player'): text = player get_text() strip() print text 24 Sam Jacobs 32 Patrick Dangerfield 26 Richard Douglas 41 Kyle Hartigan 25 Ben Rutten 16 Luke Brown 33 Brodie Smith # etc &gt;&gt;&gt; for player in soup1 select('ul team1 li player'): number name = player span get_text() strip() player span next_sibling strip() print name Sam Jacobs Patrick Dangerfield Richard Douglas Kyle Hartigan Ben Rutten Luke Brown Brodie Smith # etc ````
using heroku to deploy an app? Basic queries Ok I started with flask and heroku and I went on to learn more I am extremely naive as I just started it today I found this brilliant blog by Ryan Shea <a href="http://ryaneshea com/lightweight-python-apps-with-flask-twitter-bootstrap-and-heroku" rel="nofollow">http://ryaneshea com/lightweight-python-apps-with-flask-twitter-bootstrap-and-heroku</a> This particular blog explains the following 1> what is flask and heroku 2> how to create and write and connect to heroku using CL I followed it because it was extremely easy I had a lot of problems in the middle regarding the ssh keys and creating procfile etc I used SO to figure it out What I did--> I created virtualenv then i typed the app py created procfile and also the req txt file I connected to heroku and created a stack cedar renamed it too Then comes the HTML files there is one base html then one index and 404 html files I typed all of them and saved them Then When I run the code ````python app py ```` The code runs I try to connect to the IP from different computer on the same network it gets connected and it prints ' Hello from python' Which was the first ````@app route("/") return 'Hello from python' ```` My question is why is not the base html or the other html files exist? I understood how the app was successfully deployed in heroku but what are the other html files and how do they work? Please refer to the above link and answer my questions I am really naive and do bare it Thanks a ton
First if you are just starting out with Flask I would recommend you read <a href="http://blog miguelgrinberg com/post/the-flask-mega-tutorial-part-i-hello-world" rel="nofollow">The Flask Mega-Tutorial</a> by Miguel Grinberg The tutorial goes through the development of a web app including deployment to Heroku and does a good job of explaining why and how different methods are used Regarding your question Flask uses html files as templates using the Jinja 2 template engine which has a markup syntax similar to Django's In order to use a template you need to call it with one of Flask's template rendering hooks most commonly <a href="http://flask pocoo org/docs/api/#flask render_template" rel="nofollow">`render_template`</a> You can see that `render_template` is used in the guide you linked here (third from last code block): ````@app route("/") def index(): return render_template('index html') ```` This tells Flask to generate a page using the 'index html' template located in the templates folder relative to `app py`
Django User Model Methods So I have Auth and Profile implemented into my system however i would like to extend the User model and I do not know what is considered the 'correct' way of doing this I just want to create a method that returns a link for the user like: ````<a href="URL" class="GroupName"&gt;Username</a&gt; ```` I figured that this is probably best done using a method as the link will change and I do not want to be going through all my template files fixing this This may be common to somebody using Django but I have not used it much so I am not well versed in the conventions so any advice would be great
If you are not altering what is stored in the database the easiest way is a proxy model Here is an example straight out of the documentation (<a href="https://docs djangoproject com/en/dev/topics/db/models/#proxy-models" rel="nofollow">https://docs djangoproject com/en/dev/topics/db/models/#proxy-models</a>) ````from django db import models class Person(models Model): first_name = models CharField(max_length=30) last_name = models CharField(max_length=30) class MyPerson(Person): class Meta: proxy = True def do_something(self): # pass ```` If you want to do something more complex than adding methods to the User model such as adding new data fields I would recommend creating a Model with a one-to-one relation to User
adding multiple values of elem attrib into a variable Started playing with Python and ElementTree very recently to acheive something quite specific I am very nearly there I think but there is one thing that I cannot quite work out I am querying an xml file and pulling back the relevant data - then putting that data into a csv file It all works but the issue is that the elem attrib["text"] actually returns multiple lines - when I put it into a variable the variable and export to a csv it only exports the first line - below is the code I am using ````import os import csv import xml etree cElementTree as ET path = "/share/new" c = csv writer(open("/share/redacted csv" "wb")) c writerow(["S" "R" "T" "R2" "R3"]) for filename in os listdir(path): if filename endswith(' xml'): fullname = os path join(path filename) tree = ET ElementTree(file=(fullname)) for elem in tree iterfind('PropertyList/Property[@name="Sender"]'): c1 = elem attrib["value"] for elem in tree iterfind('PropertyList/Property[@name="Recipient"]'): c2 = elem attrib["value"] for elem in tree iterfind('PropertyList/Property[@name="Date"]'): c3 = elem attrib["value"] for elem in tree iterfind('ChildContext/ResponseList/Response/TextualAnalysis/ExpressionList/Expression/Match'): c4 = elem attrib["textView"] for elem in tree iterfind('ChildContext/ResponseList/Response/TextualAnalysis/ExpressionList/Expression/Match/Matched'): c5 = elem attrib["text"] print elem attrib["text"] print c5 c writerow([(c1) (c2) (c3) (c4) (c5)]) ```` The most important part is right near the bottom - the output of print elem atrrib["text"] is: ````Apples Bananas ```` The output of 'print c5' is the same (just to be clear that is Apples and Bananas on seperate lines) But outputting c5 to a csv only outputs the first line and therefore only Apples appears in the csv I hope this makes sense - what I need to do is output both Apples and Bananas to the csv (in the same cell preferably) The below is in Python 2 7 in development but ideally I need it to work in 2 6 (I realise iterfind is not in 2 6 - I have 2 versions of code already) I would post the xml but it is a bit of a beast - As per suggestion in comments here is a cleaned up XML ```` <?xml version="1 0" encoding="UTF-8" standalone="no" ?&gt; <Context&gt; <PropertyList duplicates="true"&gt; <Property name="Sender" type="string" value="S:demo1@no-one local"/&gt; <Property name="Recipient" type="string" value="RPFD:no-one local"/&gt; <Property name="Date" type="string" value="Tue 4 Aug 2015 13:24:16 0100"/&gt; </PropertyList&gt; <ChildContext&gt; <ResponseList&gt; <Response&gt; <Description&gt; <Arg /&gt; <Arg /&gt; </Description&gt; <TextualAnalysis version="2 0"&gt; <ExpressionList&gt; <Expression specified=" CLEAN (Apples)" total="1" &gt; <Match textView="Body" truncated="false"&gt; <Surrounding text=" "/&gt; <Surrounding text="How do you like them "/&gt; <Matched cleaned="true" text="Apples " type="expression"/&gt; <Surrounding text="???????? "/&gt; <Surrounding text=" "/&gt; </Match&gt; </Expression&gt; </ExpressionList&gt; </TextualAnalysis&gt; </Response&gt; </ResponseList&gt; </ChildContext&gt; <ChildContext&gt; <ResponseList&gt; <Response&gt; <Description&gt; <Arg /&gt; <Arg /&gt; </Description&gt; <TextualAnalysis version="2 0"&gt; <ExpressionList&gt; <Expression specified=" CLEAN (Bananas)" total="1" &gt; <Match textView="Attach" truncated="false"&gt; <Surrounding text=" "/&gt; <Surrounding text="Also I do not like "/&gt; <Matched cleaned="true" text="Bananas " type="expression"/&gt; <Surrounding text="!!!!!!! "/&gt; <Surrounding text=" "/&gt; </Match&gt; </Expression&gt; </ExpressionList&gt; </TextualAnalysis&gt; </Response&gt; </ResponseList&gt; </ChildContext&gt; </Context&gt; ````
The following will join together all the text elements and put them on separate lines <them>in the same cell</them> inside your CSV You can change the '\n' separator to ' ' or ' ' to put them on the same line <them>However</them> you might still have issues with some of your other stuff -- you do not have nested loops there and I do not really understand what you are trying to accomplish so maybe you have more than one of each of those other things too Anyway: ```` c5 = [] for elem in tree iterfind('ChildContext/ResponseList/Response/TextualAnalysis/ExpressionList/Expression/Match/Matched'): c5 append(elem attrib["text"]) c writerow([c1 c2 c3 c4 '\n' join(c5)]) ````
Correct path usage in Cygwin : Difference between `python c:\somefile py` & `python /cygdrive/c/somefile py` I am using Django 1 5 &amp; Python 2 7 on Windows Cygwin The following command gives me an error in bash she will ````$ python /cygdrive/c/Python27/Lib/site-packages/django/bin/django-admin py ```` Error: ````C:\Python27\python exe: cannot open file '/cygdrive/c/Python27/Lib/site-packages/django/bin/django-admin py': [Errno 2] No such file or directory ```` However this works ````$ python c:/Python27/Lib/site-packages/django/bin/django-admin py ```` I have seen lots of similar questions on django-admin py errors but none specifically about this So what is the difference between `python c:\somefile py` &amp; `python /cygdrive/c/somefile py` in a bash she will on Cygwin
Well nothing should be different: ````hgs15624@ESCLT0116 ~ $ python /cygdrive/c/test py Hello hgs15624@ESCLT0116 ~ $ python c:/test py Hello ```` I guess you have looked for odd permissions Edit: the below was just referring to a typo in the question The error says: ````/cygdrive/c/Python27/Lib/sitepackages/django/bin/django-admin py ```` Did you miss the hyphen in `site-packages`?
Python write valid json with newlines to file Valid json expects escaped newline characters to be encoded as '\\n' with two backslashes I have data that contains newline characters that I want to save to a file Here is a simplified version: ````data = {'mystring': 'Line 1\nLine 2'} ```` I can encode it with json dumps(): ````import json json_data = json dumps(data) json_data # > '{"mystring": "Line 1\\nLine 2"}' ```` When I print it the newline displays as '\n' not '\\n' (which I find odd but I can live with): ````print(json_data) # > {"mystring": "Line 1\nLine 2"} ```` However (here is the problem) when I output it to a file the content of the file no longer contains valid json: ````f = open('mydata json' 'w') f write(json_data) f close() ```` If I open the file and read it it contains this: ````{"mystring": "Line 1\nLine 2"} ```` but I was hoping for this: ````{"mystring": "Line 1\\nLine 2"} ```` Oddly (I think) if I read the file using python's open() the json data is considered valid: ````f = open('mydata json' 'r') json_data = f read() f close() json_data # > '{"mystring": "Line 1\\nLine 2"}' ```` and it decodes OK: ````json loads(json_data) # > {you'mystring': you'Line 1\nLine 2'} ```` My question is <them>why is the data in the file not valid json</them>? If I need another - non Python - application to read it it would probably be incorrect If I copy and paste the file contents and use json loads() on it it fails: ````import json json loads('{"mystring": "Line 1\nLine 2"}') # > ValueError: Invalid control character at: line 1 column 21 (char 20) ```` Can anybody explain if this is the expected behaviour or am I doing something wrong?
You ran into the pitfall of neglecting the fact that the `\` character is also an escape sequence character in Python Try printing out the last example instead of calling `json loads`: ````&gt;&gt;&gt; print('{"mystring": "Line 1\nLine 2"}') {"mystring": "Line 1 Line 2"} ```` No way the above is valid JSON What if the `\` character is correctly encoded? ````&gt;&gt;&gt; print('{"mystring": "Line 1\\nLine 2"}') {"mystring": "Line 1\nLine 2"} ```` Much better you can then: ````&gt;&gt;&gt; json loads('{"mystring": "Line 1\\nLine 2"}') {'mystring': 'Line 1\nLine 2'} ```` Alternatively if you really appreciate being able to copy some text from some other buffer and paste it into your live interpreter to do decode you may consider using the `r`aw modifier for your string: ````&gt;&gt;&gt; print(r'{"mystring": "Line 1\nLine 2"}') {"mystring": "Line 1\nLine 2"} &gt;&gt;&gt; json loads(r'{"mystring": "Line 1\nLine 2"}') {'mystring': 'Line 1\nLine 2'} ```` See that the `\` is no longer automatically escaping with the newline Also see: <a href="http://stackoverflow com/questions/42068/how-do-i-handle-newlines-in-json">How do I handle newlines in JSON?</a> and note how this is not a problem that exists strictly within Python
What was the most losses the Luftwaffe suffered on any mission?
one- to two-percent losses
How can I use \r to make Python print on the same line? Can someone please thoroughly explain how a '\r' works in Python? Why is not the following code printing out anything on the screen? ````#!/usr/bin/python from time import sleep for x in range(10000): print "%d\r" % x sleep(1) ````
This has nothing to do with `\r` The problem is the trailing ` ` in your `print` statement It is trying to print the last value on the line and the ` ` is creating a tuple where the last value is empty Lose the ` ` and it will work as intended <strong>Edit:</strong> I am not sure it is actually correct to say that it is creating a tuple but either way that is the source of your problem
string options when using argparse with python I am not quite understanding the following behavior of argparse ````parser add_argument("-option1" type=int nargs='?' const=1 default=1 choices=xrange(1 20) help="help message of option1") parser add_argument("-option2" type=str nargs=1 help="help message of option2") ```` in case of option1 args option1 is an integer when provided in case of option2 args option2 looks like an array of strings I have to use args option2[0] if I want to get the actual string passed with option2
This is explained directly in the documentation on <a href="https://docs python org/3/library/argparse html#nargs" rel="nofollow">`nargs`</a> Summarizing: For `nargs=N` if `N` is an integer you get a list of `N` values Even if `N` is `1` For `nargs='?'` you get a single value (which may be the default) For `nargs` left off entirely you get whatever the default is for the action If the action is e g `store` that means a single value not a list of one value It even explicitly points out exactly the part that is surprised you: <blockquote> Note that nargs=1 produces a list of one item This is different from the default in which the item is produced by itself </blockquote>
Downloading images with gevent My task is to download 1M+ images from a given list of urls What is the recommended way to do so? After having read <a href="http://stackoverflow com/questions/15556718/greenlet-vs-threads">Greenlet Vs Threads</a> I looked into `gevent` but I fail to get it reliably to run I played around with a test set of 100 urls and sometimes it finishes in 1 5s but sometimes it takes over 30s which is strange as the timeout* per request is 0 1 so it should never take more than 10s *see below in code I also looked into `grequests` but they seem to have <a href="https://github com/kennethreitz/grequests/issues/61">issues with exception handling </a> My 'requirements' are that I can - inspect the errors raised while downloading (timeouts corrupt images ) - monitor the progress of the number of processed images and - be as fast as possible <pre class="lang-python prettyprint-override">`from gevent import monkey; monkey patch_all() from time import time import requests from PIL import Image import cStringIO import gevent hub POOL_SIZE = 300 def download_image_wrapper(task): return download_image(task[0] task[1]) def download_image(image_url download_path): raw_binary_request = requests get(image_url timeout=0 1) content image = Image open(cStringIO StringIO(raw_binary_request)) image save(download_path) def download_images_gevent_spawn(list_of_image_urls base_folder): download_paths = ['/' join([base_folder url split('/')[-1]]) for url in list_of_image_urls] parameters = [[image_url download_path] for image_url download_path in zip(list_of_image_urls download_paths)] tasks = [gevent spawn(download_image_wrapper parameter_tuple) for parameter_tuple in parameters] for task in tasks: try: task get() except Exception: print 'x' continue print ' ' test_urls = # list of 100 urls t1 = time() download_images_gevent_spawn(test_urls 'download_temp') print time() - t1 ````
I will suggest to pay attention to Grablib <a href="http://grablib org/" rel="nofollow">http://grablib org/</a> It is an asynchronic parser based on pycurl and multicurl Also it tryes to automatically solve network error (like try again if timeout etc) I believe the Grab:Spider module will solve your problems for 99% <a href="http://docs grablib org/en/latest/index html#spider-toc" rel="nofollow">http://docs grablib org/en/latest/index html#spider-toc</a>
Set of dict values I have the following dict: ````d = {'a': set([1 2 3]) 'b': set([3 4 5])} ```` How would I get a set of the unique values that is `set([1 2 3 4 5])` So far I have: ````all_values = set([]) for item in d values(): all_values = all_values union(item) &gt;&gt;&gt; all_values set([1 2 3 4 5]) ```` Is there a way to do this in one line?
You may use list comprehension ````&gt;&gt;&gt; d = {'a': set([1 2 3]) 'b': set([3 4 5])} &gt;&gt;&gt; set([j for i in d values() for j in i]) {1 2 3 4 5} ````
Django 1 2 object level permissions - third party solutions? Since Django 1 2 final is almost out I am curious if there are already projects that use the new object level permissions / row level permissions system <a href="http://packages python org/django-authority/">Django-authority</a> which is a possible solution for Django up to 1 1 has not been updated for a while and does not (yet) use the new permissions system It seems to me that <a href="http://packages python org/django-authority/">Django-Authority</a> is in a comatose state Does someone know about upcoming or maybe even finished solutions? I would appreciate any good links to active projects with at least some downloadable content very much
I tried using <a href="http://code google com/p/django-granular-permissions/" rel="nofollow">django-granular-permissions</a> for a site a while ago but was unable to get it to do what I needed (this may have been my own inability to understand what I needed to do rather than the app) Looking at the google code site's updates tab it looks to not have had any work done on it since Summer/Autumn last year so it may be another dead duck
Alphabetically sorting keys with their matching values I have a textfile of names and values typed like: <blockquote> ````Sam:3 Ben:6 Ben:5 Alice:7 ```` </blockquote> I have tried to 'print' it from the file in alphabetical order but I also need to get rid of duplicates and only show the top score of each name I have started but it does not seem to work I am using python 3 4 1 ````AClass1=open("Class1 txt") line=AClass1 readlines() for lines in line: key=lines split(":")[0] val=lines split(":")[1] for names in sorted(key): print(names ":" val) AClass1 close() ````
You can use a dictionary (and <a href="https://docs python org/2/library/stdtypes html#dict setdefault" rel="nofollow">dict setdefault</a> method ) to preserve your names and scores then print the max score for each name : ````d={} with open("Class1 txt") as f : for line in f: for i j in [t split(':') for t in line split()]: d setdefault(i []) append(int(j)) for i j in d iteritems(): print '{}:{}' format(i max(j)) ```` <them>Note</them> that if you'r scores may be float you need to use `float` instead of `int` within `append` method
Python deduplicate list of Dictionaries by Value of a Key I have a pretty basic (but not quite working) function to dedupe a list of dictionaries from key values by adding the key value to a list for keeping track ````def dedupe(rs): delist = [] for r in rs: if r['key'] not in delist: delist append(r['key']) else: rs remove(r) return rs ```` Which gets used in the script just below on two lists of dictionaries: ````from pprint import pprint records = [ {'key': 'Item 1' 'name': 'Item 1' 'positions': [['00:00:00' '00:05:54'] ['00:05:55' '00:07:54'] ['00:16:47' '00:20:04']]} {'key': 'Item 1' 'name': 'Item 1' 'positions': [['00:05:55' '00:07:54'] ['00:00:00' '00:05:54'] ['00:16:47' '00:20:04']]} {'key': 'Item 1' 'name': 'Item 1' 'positions': [['00:16:47' '00:20:04'] ['00:00:00' '00:05:54'] ['00:05:55' '00:07:54']]} {'key': 'Item 2' 'name': 'Item 2' 'positions': [['00:07:55' '00:11:23'] ['00:11:24' '00:16:46']]} {'key': 'Item 2' 'name': 'Item 2' 'positions': [['00:11:24' '00:16:46'] ['00:07:55' '00:11:23']]} {'key': 'Item 3' 'name': 'Item 3' 'positions': [['00:20:05' '00:25:56']]} ] records2 = [ {'key': 'Item 1' 'name': 'Item 1' 'positions': [['00:00:00' '00:05:54'] ['00:05:55' '00:07:54'] ['00:16:47' '00:20:04']]} {'key': 'Item 1' 'name': 'Item 1' 'positions': [['00:05:55' '00:07:54'] ['00:00:00' '00:05:54'] ['00:16:47' '00:20:04']]} {'key': 'Item 2' 'name': 'Item 2' 'positions': [['00:07:55' '00:11:23'] ['00:11:24' '00:16:46']]} {'key': 'Item 1' 'name': 'Item 1' 'positions': [['00:16:47' '00:20:04'] ['00:00:00' '00:05:54'] ['00:05:55' '00:07:54']]} {'key': 'Item 2' 'name': 'Item 2' 'positions': [['00:11:24' '00:16:46'] ['00:07:55' '00:11:23']]} {'key': 'Item 3' 'name': 'Item 3' 'positions': [['00:20:05' '00:25:56']]} ] def dedupe(rs): delist = [] for r in rs: if r['key'] not in delist: delist append(r['key']) else: rs remove(r) return rs if __name__ == '__main__': res = dedupe(records) res2 = dedupe(records2) pprint(res) pprint(res2) ```` For either `records` or `records2` I would expect to get: ````[ {'key': 'Item 1' 'name': 'Item 1' 'positions': [['00:00:00' '00:05:54'] ['00:05:55' '00:07:54'] ['00:16:47' '00:20:04']]} {'key': 'Item 2' 'name': 'Item 2' 'positions': [['00:07:55' '00:11:23'] ['00:11:24' '00:16:46']]} {'key': 'Item 3' 'name': 'Item 3' 'positions': [['00:20:05' '00:25:56']]} ] ```` But instead I get (for each of the two inputs): ````[ {'key': 'Item 1' 'name': 'Item 1' 'positions': [['00:00:00' '00:05:54'] ['00:05:55' '00:07:54'] ['00:16:47' '00:20:04']]} {'key': 'Item 1' 'name': 'Item 1' 'positions': [['00:16:47' '00:20:04'] ['00:00:00' '00:05:54'] ['00:05:55' '00:07:54']]} {'key': 'Item 2' 'name': 'Item 2' 'positions': [['00:07:55' '00:11:23'] ['00:11:24' '00:16:46']]} {'key': 'Item 3' 'name': 'Item 3' 'positions': [['00:20:05' '00:25:56']]} ] [ {'key': 'Item 1' 'name': 'Item 1' 'positions': [['00:00:00' '00:05:54'] ['00:05:55' '00:07:54'] ['00:16:47' '00:20:04']]} {'key': 'Item 2' 'name': 'Item 2' 'positions': [['00:07:55' '00:11:23'] ['00:11:24' '00:16:46']]} {'key': 'Item 2' 'name': 'Item 2' 'positions': [['00:11:24' '00:16:46'] ['00:07:55' '00:11:23']]} {'key': 'Item 3' 'name': 'Item 3' 'positions': [['00:20:05' '00:25:56']]} ] ```` I keep staring at and tweaking this but it is not clear to me why it is not deleting the third instance if they are in sequence (`records`) or works for the one with three but fails on the one with two if the one with three instances are broken up (`records2`)
I would not remove elements from an iterator while iterating it Instead do this: ````def dedupe(rs): delist = [] new_rs = [] for r in rs: if r['key'] not in delist: print r['key'] delist append(r['key']) new_rs append(r) return new_rs ````
Is there any way to make the Bottle servers less verbose? Is there any option <them>on the Bottle side</them> that can keep servers like <them>WSGIRef</them> and <them>Paste</them> from outputting a line for every request received? <strong>NB:</strong> I know there is a <them>quiet</them> option but I do not want the entire appication to be silent just the request log It gets very messy very quickly especially considering that I would like to print debug information now and then and it just gets lost in the chaos Here is the output for a single page-load and it will probably get a lot bigger when my project grows a little: ``` Bottle server starting up (using WSGIRefServer()) Listening on http://0 0 0 0:8080/ Hit Ctrl-C to quit localhost - - [28/Jul/2012 04:05:59] "GET /clients HTTP/1 1" 200 3129 localhost - - [28/Jul/2012 04:05:59] "GET /static/css/main css HTTP/1 1" 304 0 localhost - - [28/Jul/2012 04:05:59] "GET /static/js/jquery-1 7 2 js HTTP/1 1" 304 0 localhost - - [28/Jul/2012 04:05:59] "GET /static/js/jquery cookie js HTTP/1 1" 304 0 localhost - - [28/Jul/2012 04:05:59] "GET /static/js/jquery qtip min js HTTP/1 1" 304 0 localhost - - [28/Jul/2012 04:05:59] "GET /static/js/showdown js HTTP/1 1" 304 0 localhost - - [28/Jul/2012 04:05:59] "GET /static/js/proj js HTTP/1 1" 304 0 localhost - - [28/Jul/2012 04:05:59] "GET /static/css/reset css HTTP/1 1" 304 0 localhost - - [28/Jul/2012 04:06:00] "GET /static/images/flag_gb png HTTP/1 1" 304 0 localhost - - [28/Jul/2012 04:06:00] "GET /static/images/flag_no png HTTP/1 1" 304 0 localhost - - [28/Jul/2012 04:06:00] "GET /static/images/icon_add png HTTP/1 1" 304 0 localhost - - [28/Jul/2012 04:06:00] "GET /favicon ico HTTP/1 1" 404 742 ```
I have done something like this in the past For the different kind of servers you can overwrite the log handler to filter out logs you do not want I copied the code from Bottle and make my own ServerAdapter Below is the code for a WSGI server Similiar to the quiet feature overriding the log_request function my own handler class and overriding the original log_request then filtering out the message based on the response code passed to the function i copied the log_request function from the built in BaseHTTPServer module and added the if statement then when you start bottle pass it your customer serverAdapter ````from bottle import route run template import bottle @route('/hello/:name') def index(name='World'): print "Debug Print Statement" return template('<b&gt;Hello {{name}}</b&gt;!' name=name) class WSGIRefServer(bottle ServerAdapter): def run(self handler): # pragma: no cover from wsgiref simple_server import make_server WSGIRequestHandler class LogHandler(WSGIRequestHandler): def log_request(self code='-' size='-'): """Log an accepted request This is called by send_response() """ if code not in ["200" "304"]: self log_message('"%s" %s %s' self requestline str(code) str(size)) self options['handler_class'] = LogHandler srv = make_server(self host self port handler **self options) srv serve_forever() run(host='localhost' server=WSGIRefServer port=8080) ````
What nationality was Saleh Ali Saleh Nabhan?
Kenyan
How to lock file without creating temp files? I try to use python lockfile module but this module create temprorary file to locking If script was interrupt ( server reboot for example ) this temp file not deleted and file remains locked
You can use the fcntl module ````import fcntl fcntl flock('myfile' fcntl LOCK_EX | fcntl LOCK_NB) ```` the second parameter here are flags which define in which way you want to lock the file see <a href="https://docs python org/2/library/fcntl html#fcntl flock" rel="nofollow">The doc</a> I am not sure this works on non Unix-like systems
row_pop() function in pysqlite? Need to <them>get one row from a table and delete the same row</them> It does not matter which row it is The function should be generic so the column names are unknown and there are no identifiers (Rows as a whole can be assumed to be unique ) The resulting function would be like a pop() function for a stack except that the order of elements does not matter <strong>Possible solutions:</strong> - Delete into a temporary table (Can this be done in pysqlite?) - `Get *` with 1 as limit and the `Delete *` with 1 as limit (Is this safe if there is just one user?) - Get one row then delete with a `WHERE` clause that compares the whole row (Can this be done in pysqlite?) Suggestions?
Well every table in a sqlite has a rowid Select one and delete it?
What was turned into a monument after the war?
"the main dome of Diazs new senate hall"
Too many values to unpack (expected 2) python django tastypie Here is my dict: ````{'interno__exact': False 'formulario__protocolo__id__exact': '5' 'autor__funcionario__funcao__id__exact': '2'} ```` I am getting this error: `too many values to unpack (expected 2)` on this execution: ````count = Avaliacao objects filter( applicable_filters ) ```` Does someone know what am I doing wrong?
too many values too unpack means that you have to have equal amounts of values on each side of the equal sign watch this: ````a b = 1 2 ```` then a would equal 1 and b would equal 2 you need to have an equal amount of things to unpack and thing to make them mean if i type in: ````print(a) print(b) ```` it would say ````1 2 ````
Python re compile between two html tags This should be quite straightforward but I cannot quite twig it I want to get the name from this html string: ```` soup = </ul&gt; Brian <p class="f"&gt; ```` I have tried: ````namePattern = re compile(r'(?<=</ul&gt;)( *?)(?<=<p)') rev reviewerName = re findall(namePattern str(soup)) ```` and ````namePattern = re compile(r'</ul&gt;( *?)<p') ```` Can you tell me how to do it? Thanks
By default ` ` does not match newlines You need to specify <a href="http://docs python org/2/library/re html#re S" rel="nofollow">`re DOTALL`</a> as the second argument to <a href="http://docs python org/2/library/re html#re compile" rel="nofollow">`re compile()`</a> Note that this will include the newlines as part of your capture group If you do not want that you can explicitly match them with `\s*`: ````In [5]: re findall(r'</ul&gt;\s*( *?)\s*<p' s) Out[5]: ['Brian'] ````
improve upon mapped lambdas in Python (pandas) I am digesting several csv files (each with one or more year of data) to categorize medical treatments into broad categories while also keeping only a subset of the original information and even aggregate up to a monthly number (by AR=year and month) of treatments per person (LopNr) Many treatments belong to different categories at the same time (multiple diagnosis codes are listed in the relevant column in the csv thus I separate that field into a column of lists and categorize rows by any diagnosis codes belonging to a relevant range of ICD-9 codes) I am using IOPro to save on memory but I am still running into a segfault (still investigating) The text files are several GBs each but this machine has 256 GB RAM Either one of the packages is buggy or I need a more memory efficient solution I am using versions pandas 0 16 2 np19py26_0 iopro 1 7 1 np19py27_p0 and python 2 7 10 0 under Linux So the original data would look something like this: ````LopNr AR INDATUMA DIAGNOS … 1 2007 20070812 C32 F17 1 2007 20070816 C36 ```` And I hope to see aggregates like this: ````LopNr AR month tobacco … 1 2007 8 2 ```` By the way I would need Stata dta files in the end but I go through cvs because pandas DataFrame to_stata seemed flaky in my experience but maybe I am missing something there too ````# -*- coding: utf-8 -*- import iopro import numpy as np from pandas import * all_treatments = DataFrame() filelist = ['oppenvard20012005' 'oppenvard20062010' 'oppenvard2011' 'oppenvard2012' 'slutenvard1997' 'slutenvard2011' 'slutenvard2012' 'slutenvard19982004' 'slutenvard20052010'] tobacco = lambda lst: any( (((x &gt;= 'C30') and (x<'C40')) or ((x &gt;= 'F17') and (x<'F18'))) for x in lst) nutrition = lambda lst: any( (((x &gt;= 'D50') and (x<'D54')) or ((x &gt;= 'E10') and (x<'E15')) or ((x &gt;= 'E40') and (x<'E47')) or ((x &gt;= 'E50') and (x<'E69'))) for x in lst) mental = lambda lst: any( (((x &gt;= 'F') and (x<'G')) ) for x in lst) alcohol = lambda lst: any( (((x &gt;= 'F10') and (x<'F11')) or ((x &gt;= 'K70') and (x<'K71'))) for x in lst) circulatory = lambda lst: any( (((x &gt;= 'I') and (x<'J')) ) for x in lst) dental = lambda lst: any( (((x &gt;= 'K02') and (x<'K04')) ) for x in lst) accident = lambda lst: any( (((x &gt;= 'V01') and (x<'X60')) ) for x in lst) selfharm = lambda lst: any( (((x &gt;= 'X60') and (x<'X85')) ) for x in lst) cancer = lambda lst: any( (((x &gt;= 'C') and (x< WOULD')) ) for x in lst) endonutrimetab = lambda lst: any( (((x &gt;= 'E') and (x<'F')) ) for x in lst) pregnancy = lambda lst: any( (((x &gt;= 'OF) and (x<'P')) ) for x in lst) other_stress = lambda lst: any( (((x &gt;= 'J00') and (x<'J48')) or ((x &gt;= 'L20') and (x<'L66')) or ((x &gt;= 'K20') and (x<'K60')) or ((x &gt;= 'R') and (x<'S')) or ((x &gt;= 'X86') and (x<'Z77'))) for x in lst) for file in filelist: filename = 'PATH' file ' txt' adapter = iopro text_adapter(filename parser='csv' field_names=True output='dataframe' delimiter='\t') treatments = adapter[['LopNr' 'AR' 'DIAGNOS' 'INDATUMA']][:] treatments['month'] = treatments['INDATUMA'] % 10000 treatments['day'] = treatments['INDATUMA'] % 100 treatments['month'] = (treatments['month']-treatments['day'])/100 del treatments['day'] diagnoses = treatments['DIAGNOS'] str split(' ') del treatments['DIAGNOS'] treatments['tobacco'] = diagnoses map(tobacco) treatments['nutrition'] = diagnoses map(nutrition) treatments['mental'] = diagnoses map(mental) treatments['alcohol'] = diagnoses map(alcohol) treatments['circulatory'] = diagnoses map(circulatory) treatments['dental'] = diagnoses map(dental) treatments['accident'] = diagnoses map(accident) treatments['selfharm'] = diagnoses map(selfharm) treatments['cancer'] = diagnoses map(cancer) treatments['endonutrimetab'] = diagnoses map(endonutrimetab) treatments['pregnancy'] = diagnoses map(pregnancy) treatments['other_stress'] = diagnoses map(other_stress) all_treatments = all_treatments append(treatments) all_treatments = all_treatments groupby(['LopNr' 'AR' 'month']) aggregate(np count_nonzero) # sum() all_treatments = all_treatments astype(int copy=False raise_on_error=False) all_treatments to_csv('PATH csv') ````
A few comments: - As noted above you should simplify your lambda expressions for readability possibly using `def` Example: ````def tobacco(codes): return any( 'C30' <= x < 'C40' or 'F17' <= x < 'F18' for x in codes) ```` You can also vectorize these functions as follows: ````def tobacco(codes_column): return [any('C30' <= code < 'C40' or 'F17' <= code < 'F18' for code in codes) if codes else False for codes in codes_column] diagnoses = all_treatments['DIAGNOS'] str split(' ') tolist() all_treatments['tobacco'] = tobacco(diagnoses) ```` <old start="2"> - You initialize `all_treatments` to a DataFrame and then append to it This is very inefficient Try `all_treatments = list()` and add `all_treatments = pd concat(all_treatments ignore_index=True)` outside the loop just before your `groupby` In addition it should be `all_treatments append(treatments)` (vs `all_treatments = all_treatments append(treatments)`) - To calculate the month for the purpose of grouping you can use: `all_treatments['month'] = all_treatments INDATUMA % 10000 // 100` - Lastly instead of applying your lambda functions to each file once its read try applying them to the `all_treatments` DataFrame instead p s You may also want to try ` sum()` on your `groupby` statement instead of ` aggregate(np count_nonzero)`
how do i stop the while function from looping and go onto the next condition ````def guess(n): import random x = random randint(1 1000000) while n != x: if n < x: print("Too Low Try Again") elif n &gt; x: print("Too High Try Again") if n == x : print("Congrats") again = print(input(str("Play Again Y/N?: "))) if again == Y: n = print(input(str("Input Number 'n': "))) print(guess(n)) elif again == N: print("Goodbye") ```` How do i make the while loops stop looping if the condition is matched and move onto the next condition that i have stated Thank you!
Use the <a href="http://docs python org/2/reference/simple_stmts html#break" rel="nofollow">`break`</a> statement (it terminates the nearest enclosing loop) e g ````if n < x: print("Too Low Try Again") elif n &gt; x: print("Too High Try Again") else: break ````
Python: Inherit class functions (property getter) does not work Consider the following code: ````class BaseClass(object): def _del_property(attr): """Abstract deller""" def del_attr(self): setattr(self attr None) return del_attr def _set_property(attr): """Abstract setter """ def set_attr(self x): setattr(self attr x) return set_attr def _get_property(attr): """Abstract getter""" def get_attr(self): getattr(self attr) return get_attr _name = None name = property(fget=_get_property('_name') fset=_set_property('_name')) class Component(BaseClass): _material = None material = property(fget=_get_property('_material') fset=_set_property('_material') fdel=_del_property('_material')) ```` How come _get_property _set_property and _del_property are not inherited? How can it be achieved? It should work for derived classes in the same source file as well as for derived classes in a separate file which import this source file with a ````from filename import * ````
When creating a class a new namespace is created Python reads the block of code inside your class block and then passes the information to `type` (or the corresponding metaclass) In this case python complains because when setting up the `Component` class `_get_property` is not defined within that scope -- perhaps `BaseClass _get_property` but that probably will not work like you want it to either One easy fix is to make those functions module level functions since the class namespace has access to the module namespace: ````def _del_property(attr): """Abstract deller""" def del_attr(self): setattr(self attr None) return del_attr def _set_property(attr): """Abstract setter """ def set_attr(self x): setattr(self attr x) return set_attr def _get_property(attr): """Abstract getter""" def get_attr(self): getattr(self attr) return get_attr class BaseClass(object): _name = None name = property(fget=_get_property('_name') fset=_set_property('_name')) class Component(BaseClass): _material = None material = property(fget=_get_property('_material') fset=_set_property('_material') fdel=_del_property('_material')) ```` Perhaps it is more instructive to look at the class while we are creating it: ````class BaseClass(object): def _del_property(attr): """Abstract deller""" def del_attr(self): setattr(self attr None) return del_attr print type(_del_property) print type(BaseClass _del_property) ```` This will print: ````<type 'function'&gt; <type 'instancemethod'&gt; ```` So you are dealing with a regular function inside `BaseClass` but it becomes an `instancemethod` after `type` does it is magic <hr> Personally I would just create a convenience function: ````def property_api(name fget=True fset=True fdel=True): return property(fget=_get_property(name) if fget else None fset=_set_property(name) if fset else None fdel=_del_property(name) if fdel else None) ```` Which you can then use If you really want to you could even put it on `BaseClass` as a `staticmethod`: ```` class BaseClass(object): property_api = staticmethod(property_api) ```` Then your derived classes would look like: ```` class DerivedClass(BaseClass): _material = None material = BaseClass property_api('_material') ````
Import pyglet on python I have downloaded the pyglet dmg file from <a href="http://www pyglet org/" rel="nofollow">pyglet website</a> and simply installed it The folder on which it is saved is: `/Developer/pyglet` And on the pydev editor i simply state the location i want to use by: ````import sys sys path append('Developer/pyglet') import pyglet music = pyglet resource media('music mp3') music play() pyglet app run() ```` But for some reason i cannot get this import: ````python sound py Traceback (most recent call last): File "sound py" line 3 in <module&gt; import pyglet ImportError: No module named pyglet ```` Any idea on how to make it work?
Ok got it I just downloaded the <a href="http://www pyglet org/download html" rel="nofollow">source files</a> and compiled it by myself by invoking: ````sudo python setup py install ```` And then simply used the sys import as described in the question
matplotlib and PyQt ploting a suface I created a 3D plot using matplotlib as this: ````fig = pylab figure() ax = Axes3D( fig ) surf = ax plot_surface( X Y Z cmap=cm gray_r linewidth=0 antialiased=True ) fig canvas set_window_title( "Distance" ) pylab show() ```` It is fantastic: I see the surface in grays-cale and I can interact with it ( turn the surface move plot ) Now I need to put this plot in a PyQt form I created a class inherit from QMainWindow doing this: ````class ViewerForm(QMainWindow): def __init__(self p_parent=None p_data=None): QMainWindow __init__( self parent=p_parent ) self main_frame = QWidget( ) self figure = pyplot figure() self axis = Axes3D( self figure ) self canvas = FigureCanvas( self figure ) self canvas setParent( self main_frame ) self mpl_toolbar = NavigationToolbar( self canvas self main_frame ) self X self Y = np meshgrid( p_data[ "axis_x" ] p_data[ "axis_y" ] ) self Z = p_data[ "values_z" ] self surface = self axis plot_surface( self X self Y self Z cmap=cm gray linewidth=0 antialiased=True ) vbox = QVBoxLayout( ) vbox addWidget( self canvas ) vbox addWidget( self mpl_toolbar ) self main_frame setLayout( vbox ) self setCentralWidget( self main_frame ) ```` When I show this form I can see the surface in gray-scale as the first plot but I cannot interact with this: I cannot move the surface clicking with mouse Anyone can say me what I am doing wrong or what I misunderstood?
I think you need to register a callback function for the mouse clicks like in this cookbook example: <a href="http://www scipy org/Cookbook/Matplotlib/Interactive_Plotting" rel="nofollow">http://www scipy org/Cookbook/Matplotlib/Interactive_Plotting</a>
Python: create dictionary using dict() with integer keys? In Python I see people creating dictionaries like this: ````d = dict( one = 1 two = 2 three = 3 ) ```` What if my keys are integers? When I try this: ````d = dict (1 = 1 2 = 2 3 = 3 ) ```` I get an error Of course I could do this: ````d = { 1:1 2:2 3:3 } ```` which works fine but my main question is this: is there a way to set <them>integer</them> keys using the dict() function/constructor?
Yes but not with that version of the constructor You can do this: ````&gt;&gt;&gt; dict([(1 2) (3 4)]) {1: 2 3: 4} ```` There are several different ways to make a dict As <a href="https://docs python org/2/library/stdtypes html#mapping-types-dict" rel="nofollow">documented</a> "providing keyword arguments [ ] only works for keys that are valid Python identifiers "
Is this a valid method for CPU time comparison between C++ and Python? I am interested in comparing CPU times some code portions written C++ vs Python (running on Linux) Will the following methods produce a "fair" comparison between the two? <h1>Python</h1> Using the <a href="https://docs python org/2/library/resource html" rel="nofollow">resource module</a>: ````import resource def cpu_time(): return resource getrusage(resource RUSAGE_SELF)[0]+\ # time in user mode resource getrusage(resource RUSAGE_SELF)[1] # time in system mode ```` which allows for timing like so: ````def timefunc( func ): start=cpu_time() func() return (cpu_time()-start) ```` Then I test like: ````def f(): for i in range(int(1e6)): pass average = 0 for k in range(10): average = timefunc( f ) / 10 0 print average =&gt; 0 002199700000000071 ```` <h1>C++</h1> Using the `ctime` lib: ````#include <ctime&gt; #include <iostream&gt; int main() { double average = 0 0; int N = (int) 1e6; for (int k=0; k<10; k++) { clock_t start; start = clock(); for (int i=0; i<N; i++) continue; average = (double)(clock()-start) / 10 0 / CLOCKS_PER_SEC; } std::cout << average << '\n'; return 0; } ```` which yields `0 002` Concerns: - I have read that C++ `clock()` measures CPU time which is what I am after but I cannot seem to find if it includes both user and system times - Results from C++ are much less precise Why is that? - Overall fairness of comparison as mentioned <h1>Update</h1> updated the c++ code as per David's suggestion in the comments: ````#include <sys/resource h&gt; #include <iostream&gt; int main() { double average = 0 0; int N = (int) 1e6; int tally = 0; struct rusage usage; struct timeval ustart ustop sstart sstop; getrusage(RUSAGE_SELF &amp;usage); ustart = usage ru_utime; sstart = usage ru_stime; for (int k=0; k<10; k++) { ustart = usage ru_utime; sstart = usage ru_stime; for (int i=0; i<N; i++) continue; getrusage(RUSAGE_SELF &amp;usage); ustop = usage ru_utime; sstop = usage ru_stime; average = ( (ustop tv_sec+ustop tv_usec/1e6+ sstop tv_sec+sstop tv_usec/1e6) - (ustart tv_sec+ustart tv_usec/1e6+ sstart tv_sec+sstart tv_usec/1e6) ) / 10 0; } std::cout << average << '\n'; return 0; } ```` Running: ````g++ -O0 cpptimes cpp ; /a out =&gt; 0 0020996 g++ -O1 cpptimes cpp ; /a out =&gt; 0 ```` So I suppose `getrusage` gets me a little bit better resolution but I am not sure how much I should read into it Setting the optimization flag certainly makes a big difference
The <a href="http://en cppreference com/w/cpp/chrono/c/clock" rel="nofollow">documentation</a> says: "<them>Returns the approximate processor time used by the process since the beginning of an implementation-defined era related to the program's execution To convert result value to seconds divide it by CLOCKS_PER_SEC </them>" That is pretty vague `CLOCK_PER_SEC` is set to `10^6` and the approximate stands for poor resolution not that the current clocks tick over 1000 faster and the results are rounded That might be not a very technical term but it is appropriate The actual resolution everywhere I tested was about 100Hz = 0 01s It is been like that for years Note date here <a href="http://www guyrutenberg com/2007/09/10/resolution-problems-in-clock/" rel="nofollow">http://www guyrutenberg com/2007/09/10/resolution-problems-in-clock/</a> Then the doc follows with: "<them>On POSIX-compatible systems clock_gettime with clock id CLOCK_PROCESS_CPUTIME_ID offers better resolution </them>" So: - It is CPU time only But 2 threads = 2*CPU time See the example on cppreference - It is not suited for fine grain measurements at all as explained above You were on the verge of its accuracy - I AM GOING TO measuring wall-clock is the only sensible thing but its a rather personal opinion Especially with multithreaded applications and multiprocessing in general Otherwise results of `system`+`user` should be similar anyways EDIT: At 3 This of course holds for computational tasks If your process uses `sleep` or give up execution back to system it might be more feasible measuring CPU time Also regarding the comment that `clock` resolution is erm bad It is but to be fair one could argue you should not measure such short computations I AM GOING TO its too bad but if you measure times over few seconds I guess its fine I would personally use others available tools
WSDL XSD and soappy I have the following WSDL and XSD ````from SOAPpy import WSDL import os # you will need to configure these two values; # see http://www google com/apis/ WSDLFILE = os path join(os path dirname(__file__) "getiwsAesPayment wsdl") _server = WSDL Proxy(WSDLFILE) print _server ```` Which gives me the error: ```` schema load(reader) File "/home/gregory/ virtualenvs/casadeal/src/soappy/SOAPpy/wstools/XMLSchema py" line 1205 in load tp fromDom(childNode) File "/home/gregory/ virtualenvs/casadeal/src/soappy/SOAPpy/wstools/XMLSchema py" line 1322 in fromDom raise SchemaError 'namespace of schema and import match' SOAPpy wstools XMLSchema SchemaError: namespace of schema and import match ```` Apparently it may come from the fact that the targetNamespace are the same for wsdl and xsd ? WSDL ````<?xml version="1 0" encoding="UTF-8"?&gt; <definitions name="getiwsAesPayment" targetNamespace="http://ws AMANTY m2t biz/" xmlns:soap="http://schemas xmlsoap org/wsdl/soap/" xmlns:xsd="http://www w3 org/2001/XMLSchema" xmlns:tns="http://ws AMANTY m2t biz/" xmlns="http://schemas xmlsoap org/wsdl/"&gt; <types&gt; <xsd:schema&gt; <xsd:import namespace="http://ws AMANTY m2t biz/" schemaLocation="getiwsAesPayment xsd"/&gt; </xsd:schema&gt; </types&gt; <message name="getiwsaespayment"&gt; <part name="parameters" element="tns:getiwsaespayment"&gt; </part&gt; </message&gt; <message name="getiwsaespaymentResponse"&gt; <part name="parameters" element="tns:getiwsaespaymentResponse"&gt; </part&gt; </message&gt; <portType name="getiwsAesPayment"&gt; <operation name="getiwsaespayment"&gt; <input message="tns:getiwsaespayment"&gt; </input&gt; <output message="tns:getiwsaespaymentResponse"&gt; </output&gt; </operation&gt; </portType&gt; <binding name="getiwsAesPaymentPortBinding" type="tns:getiwsAesPayment"&gt; <soap:binding style="document" transport="http://schemas xmlsoap org/soap/http"/&gt; <operation name="getiwsaespayment"&gt; <soap:operation soapAction=""/&gt; <input&gt; <soap:body use="literal"/&gt; </input&gt; <output&gt; <soap:body use="literal"/&gt; </output&gt; </operation&gt; </binding&gt; <service name="getiwsAesPaymentService"&gt; <port name="getiwsAesPaymentPort" binding="tns:getiwsAesPaymentPortBinding"&gt; <soap:address location="http://partner ma:8080/AMANTYWebServicesWAR/getiwsAesPayment"/&gt; </port&gt; </service&gt; </definitions&gt; ```` XSD ````<?xml version="1 0" encoding="UTF-8"?&gt; <xs:schema version="1 0" targetNamespace="http://ws AMANTY m2t biz/" xmlns:xs="http://www w3 org/2001/XMLSchema" xmlns:tns="http://ws AMANTY m2t biz/"&gt; <xs:element name="commandReg" type="tns:commandReg"/&gt; </xs:schema&gt; ````
try to include (not import) other xsd's in your wsdl
What did an Arkansas law make it a crime to teach the theory of?
that mankind ascended or descended from a lower order of animals
How many rivers are in Multan?
null
Python inheritance parent child not equal type I am playing with Python but am not getting the inheritance right In my package I have User py ````class User(object): """This is the base user This is where all the dirty stuff happens """ def __init__(self mail=None password=None): self _build({"mail": mail "password": password "fields": dict({})}) def _build(self props): """Private method for building objects based on dicts """ props["uuid"] = uuid uuid4() for k v in props iteritems(): setattr(self k v) @staticmethod def get_or_create(**kwargs): """This method fetches a matching User or creates on based on email and password """ db = utils get_client() users if kwargs get("mail") is None: raise ValueError("%s mail cannot be None" % self __class__ __name__) cursor = db users find_one({"mail": kwargs get("mail" None)}) if cursor is None: user = User() user _build({"mail": kwargs get("mail" None) "password": kwargs get("password" None)}) user save() else: if cursor get("_type") == "Customer": user = Customer() else: user = User() user _build(cursor) return user ```` And then I have Customer py inheriting from User ````from gearbroker user import User class Customer(User): def __init__(self **kwargs): User __init__(self mail=kwargs get("mail" None) password=kwargs get("password" None)) ```` both in the same package at root level My test gives me this ````AssertionError: <class 'mypackage user Customer'&gt; != <class 'mypackage customer Customer'&gt; ```` when I run this test ```` customer = Customer(mail="foo@bar com" password="foobar") customer save() user = User get_or_create(mail="foo@bar com" password="foobar") assert_equal(type(user) type(Customer())) ```` in this test file I import the objects like this ````from gearbroker user import User from gearbroker customer import Customer ```` How do I go about this? The customer should be a child of the User class and when comparing their type they should both be users This was working until I decided to move the Customer and the User class into 2 different files to increase readability Am I importing the objects wrong?
It sounds like you have two different definitions of the `Customer` class Your tests seems to be showing that you are getting them mixed up What I suspect your error comes down to is that you are wanting to refer to unqualified names `User` and `Customer` in all your modules and you are using some kind of `from module import Name` syntax to get it That breaks when you have circular dependencies (the `user` module needs to access the `Customer` class but the `customer` module needs to access the `User` class) To work around the issue I suggest using regular `import module` statements and changing the unqualified class names to qualified versions (`user User` and `customer Customer`) Or just keep your classes both in the same module! Python is not like Java where each class definition needs to be in its own file If your `User` and `Customer` classes are closely bound to each other by all means keep them in the same module!
Django Guardian assign_perm and DoesNotExist error I am using <a href="https://github com/lukaszb/django-guardian" rel="nofollow">django-guardian</a> to implement object level permissions I created custom permissions in the Models and I have migrated &amp; tried resetting migrations and re-migrating but I still run into a `DoesNotExist` error: <blockquote> <a href="http://i stack imgur com/IRHl1 png" rel="nofollow">Permission matching query does not exist </a> </blockquote> Can anyone help me fix this?
As <a href="http://django-guardian readthedocs org/en/v1 2/userguide/assign html#prepare-permissions" rel="nofollow">django-guardian uses django for creation of permissions</a> you would have to first create custom permissions as with any Django app What version of Django are you using? If it is 1 6 or lower you might have to run `syncdb --all` to create the permissions See <a href="https://docs djangoproject com/en/1 6/topics/auth/customizing/#custom-permissions" rel="nofollow">documentation here</a>
Python: how to remove every n-th element from list? I had already looked through this post: <a href="http://stackoverflow com/questions/16406772/python-building-new-list-from-existing-by-dropping-every-n-th-element">Python: building new list from existing by dropping every n-th element</a> but for some reason it does not work for me: I tried this way: ````def drop(mylist n): del mylist[0::n] print(mylist) ```` This function takes a list and `n` Then it removes every n-th element by using n-step from list and prints result Here is my function call: ````drop([1 2 3 4] 2) ```` Wrong output: `[2 4]` instead of `[1 3]` <hr> Then I tried a variant from the link above: ````def drop(mylist n): new_list = [item for index item in enumerate(mylist) if index % n != 0] print(new_list) ```` Again function call: ````drop([1 2 3 4] 2) ```` Gives me the same wrong result: `[2 4]` instead of `[1 3]` <hr> How to correctly remove <strong>n-th</strong> element from a list?
The output is correct you are removing the the elements with index 0 n 2n So 1 and 3 are removed 2 and 4 are left So if you want to print the 0 n 2n element just write ````print(mylist[::n]) ````
A Djangoic method of checking if it is an allowed subdomain I have to solve this little problem in Python/Django and I am wondering which is the best way to go about it I have a list of allowed domains e g `www google com` `mail google com` I would like to check if a domain is allowed or not Now a request from either `www google com` is valid and a request from `mail google com` is valid too However I would like to count `www` as a wildcard which means that if I had the same list of allowed domains as above A request from `docs google com` would be considered valid and so a request from `google com` even though they do not exist in the list but since `www google com` exists and `www ` is a leading wildcard both domains match What would be the best way to implement this? Here is a snippet of mine where I am trying to implement this: ````def dispatch(self request *args **kwargs): url = request REQUEST['url'] host = urlparse urlparse(url) netloc lower() strip() domains = [domain host lstrip('www ') for domain in Domain objects all()] for domain in domains: if host endswith(domain): return super(ProcessRequestView self) dispatch(request *args **kwargs) return HttpResponseForbidden() ```` My `Domain` model has just one field called `host` This solution of mine make just one DB hit but I am sure if it is the best or the most efficient Thanks
First of all if i would like to use wildcard it would not be "www" since www is nothing but a subdomain For example if i would like to let all google domains my record would be "<strong> google com</strong>" This would show for example <strong>www google com au</strong> as not allowed It is possible for you to put wildcard to the end but then <strong>google com example com</strong> would be allowed which is not good idea Or maybe you would like to allow all UK sites with domain name ending with <them>co uk</them> with "<strong> co uk</strong>" record Thus you should be looking for subdomains specific to general: Lest assume the domain name is docs google co uk and you have only the "<strong> co uk</strong>" record - Query for docs google co uk - check whether full host name allowed or not - Query for docs google co uk in case of any wildcard definition - Query for google co uk - Query for co uk - Bingo you find a wildcard its allowed! Anyway in your code you are selecting every domain objects from db and then looking for appropriate domain name with a loop This operation would unnecessarily slow down your process Instead of selecting them all you should let database to handle the elimination of not related domains ````def dispatch(self request *args **kwargs): url = request REQUEST['url'] host = urlparse urlparse(url) netloc lower() strip() domains = Domain objects filter(domain=host) if len(domains): return super(ProcessRequestView self) dispatch(request *args **kwargs) else: newHost = ' %s' %host dotPosition = -1 for i in range(newHost count(' ')): dotPosition = newHost find(' ' dotPosition 1) domains = Domain objects filter(domain=newHost[dotPosition:]) if len(domains): return super(ProcessRequestView self) dispatch(request *args **kwargs) return HttpResponseForbidden() ```` I hope it will help
When did the Romans leave Utrecht
Around 275 the Romans could no longer maintain the northern border and Utrecht was abandoned
Python Matplotlib line plot aligned with contour/imshow How can I set the visual width of one subplot equal to the width of another subplot using Python and Matplotlib? The first plot has a fixed aspect ratio and square pixels from imshow I would then like to put a lineplot below that but am not able to do so and have everything aligned I am fairly sure the solution involves the information on this <a href="http://matplotlib org/users/transforms_tutorial html">Transform Tutorial</a> page I have tried working with fig transFigure ax transAxes ax transData etc but have not been successful I need to find the width and height and offsets of the axes in the upper panel and then be able to set the width height and offsets of the axes in the lower panel Axis labels and ticks and etc should not be included or change the alignment For example the following code ````fig = plt figure(1) fig clf() data = np random random((3 3)) xaxis = np arange(0 3) yaxis = np arange(0 3) ax = fig add_subplot(211) ax imshow(data interpolation='none') c = ax contour(xaxis yaxis data colors='k') ax2 = fig add_subplot(212) ```` <img src="http://i stack imgur com/NrKDd png" alt="enter image description here">
The outline of matplotlib axes are controlled by three things: - The axes' bounding box within the figure (controlled by a subplot specification or a specific extent such as `fig add_axes([left bottom width height])` The axes limits (not counting tick labels) will always be within this box - The `adjustable` parameter that controls whether changes in limits or aspect ratio are accomodated by changing data limits or the shape of the axes "box" This can be `"datalim"` `"box"` or `"box-forced"` (The latter is for use with shared axes ) - The axes limits and aspect ratio For plots with a fixed aspect ratio the axes box or data limits (depending on `adjustable`) will be changed to maintain the specified aspect ratio The aspect ratio refers to data coordinates <them>not</them> the shape of the axes directly For the simplest case: ````import numpy as np import matplotlib pyplot as plt fig axes = plt subplots(nrows=2) data = np random random((3 3)) xaxis = np arange(0 3) yaxis = np arange(0 3) axes[0] imshow(data interpolation='none') c = axes[0] contour(xaxis yaxis data colors='k') axes[1] set_aspect(1) plt show() ```` <img src="http://i stack imgur com/fDxoF png" alt="enter image description here"> <hr> <h2>Shared Axes</h2> However if you want to ensure that it stays the same shape regardless and you are okay with both plots having the same data limits you can do: ````import numpy as np import matplotlib pyplot as plt fig axes = plt subplots(nrows=2) sharex=True sharey=True) plt setp(axes flat adjustable='box-forced') data = np random random((5 3)) xaxis = np arange(0 3) yaxis = np arange(0 5) axes[0] imshow(data interpolation='none') c = axes[0] contour(xaxis yaxis data colors='k') axes[1] plot([-0 5 2 5] [-0 5 4 5]) axes[1] set_aspect(1) plt show() ```` <img src="http://i stack imgur com/aE9aq png" alt="enter image description here"> However you may notice that this does not look quite right That is because the second subplot is controlling the extents of the first subplot due to the order we plotted things in Basically with shared axes whatever we plot last will control the initial extent so if we just swap the order we are plotting in: ```` import numpy as np import matplotlib pyplot as plt fig axes = plt subplots(nrows=2 sharex=True sharey=True) plt setp(axes flat adjustable='box-forced') data = np random random((5 3)) xaxis = np arange(0 3) yaxis = np arange(0 5) axes[1] plot([-0 5 2 5] [-0 5 4 5]) axes[1] set_aspect(1) axes[0] imshow(data interpolation='none') c = axes[0] contour(xaxis yaxis data colors='k') plt show() ```` <img src="http://i stack imgur com/IVzy2 png" alt="enter image description here"> Of course if you do not care about the interactive zooming/panning of the plots being linked you can skip the shared axes altogether and just to: ````import numpy as np import matplotlib pyplot as plt fig axes = plt subplots(nrows=2) data = np random random((5 3)) xaxis = np arange(0 3) yaxis = np arange(0 5) axes[0] imshow(data interpolation='none') c = axes[0] contour(xaxis yaxis data colors='k') axes[1] plot([-0 5 2 5] [-0 5 4 5]) # Copy extents and aspect from the first axes axes[1] set_aspect(axes[0] get_aspect()) axes[1] axis(axes[0] axis()) plt show() ```` <hr> <h2>Non-Shared Axes</h2> If you do not want the two axes to have the same data extents it is possible to force them to be the same size (though if you interactively zoom they will not be linked) To do this you need to calculate what the aspect ratio for the second plot should be based on its extents and the extents/aspect of the first plot ````import numpy as np import matplotlib pyplot as plt fig axes = plt subplots(nrows=2) data = np random random((3 3)) xaxis = np arange(0 3) yaxis = np arange(0 3) axes[0] imshow(data interpolation='none') c = axes[0] contour(xaxis yaxis data colors='k') axes[1] plot(np linspace(0 10 100) np random normal(0 1 100) cumsum()) # Calculate the proper aspect for the second axes aspect0 = axes[0] get_aspect() if aspect0 == 'equal': aspect0 = 1 0 dy = np abs(np different(axes[1] get_ylim())) dx = np abs(np different(axes[1] get_xlim())) aspect = aspect0 / (float(dy) / dx) axes[1] set_aspect(aspect) plt show() ```` <img src="http://i stack imgur com/pOD3f png" alt="enter image description here">
get all elements in a loop through xpath I am currently learning selenium using python html is: ````<old class="item-section"&gt; <li&gt; <div class="abc xyz"&gt; <div class="foo qwe"&gt; <a href="/watch123"&gt;</a&gt; </div&gt; </div&gt; </li&gt; <li&gt; <div class="abc xyz"&gt; <div class="foo qwe"&gt; <a href="/watch456"&gt;</a&gt; </div&gt; </div&gt; </li&gt; <li&gt; <div class="abc xyz"&gt; <div class="foo qwe"&gt; <a href="/watch678"&gt;</a&gt; </div&gt; </div&gt; </li&gt; </old&gt; ```` I want to get all hrefs from the list through xpath I tried ````html_list = driver find_element_by_class_name("item-section") items = html_list find_elements_by_tag_name("li") stack=[] index = 1 for item in items: index+=1 link = item find_element_by_xpath("//div[@class='foo qwe']["+index+"]/a") print (index "--> " link get_attribute("href")) ```` but it gives error `Cannot convert 'int' object to str implicitly` If I just use ````link = item find_element_by_xpath("//div[@class='foo qwe']/a") ```` I get the first href multiple times
You can get the list of elements using ````driver find_elements_by_xpath("//div[@class='foo qwe']/a") or from selenium webdriver common by import By inputs = driver find_elements(By XPATH "//div[@class='foo qwe']/a") ````
Check whether a path is valid in Python Is there any easy way to check whether a path is valid? The file does not have to exist now I am wondering if it could exist my current version is this: ````try: f = open(path) except: <path invalid&gt; ```` I am considering simply checking whether the path contains any of <a href="http://en wikipedia org/wiki/Filename#Reserved_characters_and_words">these</a> characters
Attempting it first is the best way I recommend doing that ````try: open(filename 'w') except OSError: # handle error here ```` I believe you will get OSError catch that explicitly and test on the platform you are using this on
python set manipulation :the simple script does not output right set after unioning or disjoining? ````all_tags = ['24' '02' '26' '03' '33' '32' '31' '30' '29' '68' '11'] ref_tag = str('24') union_tags = set(all_tags) | set(ref_tag) left_tags = set(all_tags) - set(ref_tag) print(union_tags) print(left_tags) ```` The above is the simple code which I expect elements in union_tags should be the same as those in all_tags However the result is set ````(['24' '02' '26' '03' '33' '32' '31' '30' '29' '68' '2' '4' '11']) ```` The union_tags instead contains two extra elements '2' and '4' which I think it is the result splitting the str '24' Again left_tags should exclude element '24' However the result still have the '24' Please let me know why I use the python 2 7 as the interpreter
Set function accept an iterable with hashable items and convert it to a set object and since strings are iterables when you pass the string `24` to your set function it converts your string to following set: ````{'2' '4'} ```` And at last the unioin of this set with `all_tags` would contain items `2` and `4` If you want to put the `24` in a set as one item you can use `{}` in order to create your expected set: ````&gt;&gt;&gt; ref_tag = {'24'} set(['24']) ````
Processing a HTML file using Python I wanted to remove all the tags in HTML file For that I used re module of python For example consider the line `<h1&gt;Hello World!</h1&gt;` I want to retain only "Hello World!" In order to remove the tags I used `re sub('< *&gt;' '' string)` For obvious reasons the result I get is an empty string (The regexp identifies the first and last angle brackets and removes everything in between) How could I get over this issue?
Parse the HTML using BeautifulSoup then only retrieve the text
Views in Django with arbitrary number of url parameters I want to write universal View with Django in this function i want to handle several situations: first when i have url like vkusers3/11122233/1/2/ and also i want it working when 2 or third arguments is missing in url like: vkusers3/11122233/ or vkusers3/11122233/1/ I cannot find it tutorials how to do that (<a href="https://docs djangoproject com/en/1 6/topics/http/urls/" rel="nofollow">https://docs djangoproject com/en/1 6/topics/http/urls/</a> etc) The problem that this became a nightmare when you have more than 5 combinations in url parameters then you should write 5 different url configurations 5 times in html template hardcode this pattern BUT wait even more! what about combinatorics: i want /user/group/sex/smoking/ but also i want /user/group/smoking/ i e all users from group who is smoking of both man and woman So the number is huge ````def list_groupmembers_sex(request group_id sex=None smoking=None): success = False if group_id and sex and smoking==None: vkusers = Vkuser _get_collection() find({"member_of_group": int(group_id) 'sex': int(sex)})# 62740364 81099158 success = True elif group_id and sex and smoking!=None: vkusers = Vkuser _get_collection() find({"member_of_group": int(group_id) 'sex': int(sex) 'personal smoking': int(smoking)}) success = True else: vkusers = Vkuser _get_collection() find({'personal smoking': 1}) ctx = {'vkuser_list': vkusers 'group_id': group_id 'sex': sex 'smoking':smoking 'success': success} return render_to_response('blog/vkuser_list html' ctx context_instance = RequestContext(request)) ```` In my urls py: ````url(r'^vkusers3/(\d{1 8})/(\d{1})/(\d{1})/$' 'blog views list_groupmembers_sex' name='vkuser-list3') ```` In my base html: ````<li class="menu-level-1"&gt;<a href="{% url 'vkuser-list3' group_id sex smoking %}"&gt;users</a&gt;</li&gt; ```` Django 1 6 10 MongoDB 2 7 1 mongoengine
At this point you should probably bite the bullet and just go for query parameters - `vkusers3/?sex=1&amp;smoking=2&amp;group= 11122233` You can drop the parameters completely from the URL and the view definition and just use `request GET['sex']` etc in the view body
Casper js unable to open JSON file when activated through python script I have a CasperJS script that opens a JSON file of search terms and parses a page looking for them It works fine when I run it from the command line ````var casper = require('casper') create(); var fs = require('fs') var names = fs read('/var/www/html/tracker/names json'); ```` But when I try to run it through a she will script using Python it has difficulty reading the JSON file `fs read` returns `""` The Python script: ````app = subprocess Popen("/usr/local/bin/casperjs /var/www/html/tracker/scraper js" she will=True) app wait() out errs = app communicate() ````
Figured it out Naturally my own boneheaded mistake Did not make this clear in the question but the Python script first prepares `names json` before running the scraper through a subprocess So if we add a little bit to the code snippet shown above: ````# Save JSON file f = open('names json' 'w') f write( json dumps(json_ready sort_keys=True indent=4) ) # Query scraper app = subprocess Popen("/usr/local/bin/casperjs /var/www/html/tracker/scraper js" she will=True) app wait() out errs = app communicate() ```` The problem? I forgot to close `f` ````# Save JSON file f = open('names json' 'w') f write( json dumps(json_ready sort_keys=True indent=4) ) f close() ````
Cannot set class attributes in python using a method Initialising the Foo object does run the method func() but the value of self a gets set to None anyway How can I get the following code to work? ````#!/usr/bin/env python class Foo(object): def __init__(self num): self a = self func(num) print self a def func(self num): self a = range(num) print self a def __str__(self): return str(self a) def main(): f = Foo(20) print f if __name__ == "__main__": main() ```` The output is: ````[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] None None ````
You are resetting `self a` to the return value of the function Since the function returns nothing the value gets set to `None` ````def __init__(self num): self a = self func(num) # return value of function is None print self a # self a is now None def func(self num): self a = range(num) # sets self a to [0 19] print self a # prints [0 19] # implicit "return None" ````
Python - default arguments in function Looking at the python doc <a href="http://docs python org/library/urllib2 html" rel="nofollow">http://docs python org/library/urllib2 html</a> urllib2 urlopen(url[ data][ timeout]) So I pass in a url then optional data and timeout variables (from how I read it) So if I want to pass a timeout but not the data what is the default variable for data? Do you just do ````urlopen('http://www example com/' 5) ```` Thanks :)
You use the parameter names: ````urlopen('http://www exmaple com/' timeout=5) ````
How come in Django uniques are not holding up? ````class A(models Model): title = models CharField(max_length=240 null=True blank=True db_index=True) body = models TextField(blank=True null=True) adinfo = models CharField(max_length=240 null=True blank=True db_index=True) url = models CharField(max_length=10000 null=True blank=True) img = models CharField(max_length=10000 null=True blank=True) created_at = models DateTimeField(auto_now_add=True null=True db_index=True) updated_at = models DateTimeField(auto_now=True null=True) class Meta: unique_together = (('title' 'adinfo') ) mysql&gt; select * from mo_a where id = 1113\G; *************************** 1 row *************************** id: 1113 title: Tides Tavern body: Come in and enjoy the morning sun or a nice sunset with breakfast lunch or dinner Find a seat put your feet up &amp;amp; enjoy Click here! adinfo: NULL url: img: http://creative ak fbcdn net/v41818/flyers/125/47/13039135731061564765_1_89254352 jpg created_at: 2011-07-08 00:41:18 updated_at: 2011-07-08 00:41:18 1 row in set (0 00 sec) ERROR: No query specified mysql&gt; select * from mo_a where id = 1114\G; *************************** 1 row *************************** id: 1114 title: Tides Tavern body: Come in and enjoy the morning sun or a nice sunset with breakfast lunch or dinner Find a seat put your feet up &amp;amp; enjoy Click here! adinfo: NULL url: img: http://creative ak fbcdn net/v41818/flyers/125/47/13039135731061564765_1_89254352 jpg created_at: 2011-07-08 00:41:22 updated_at: 2011-07-08 00:41:22 1 row in set (0 00 sec) ERROR: No query specified ```` Is this normal? As you can see I have title and adinfo uniqued I did NOT want #1114 to be inserted But it did How do I remove all the duplicates in the database?
The way you specified your UNIQUE constraint you are stating that you do not allow insertion of duplicates for pairs As you specified you would be able to insert the pairs: ````(1113 'Tides Tavern') and (1114 'Tides Tavern') ```` or ````(1113 'Roman road') and (1113 'Tides Tavern') ```` but not: ````(1113 'Tides Tavern') and (1113 'Tides Tavern') ```` In other words from Postgresql docs: <strong>"A multicolumn unique index will only reject cases where all of the indexed columns are equal in two rows "</strong>
What are now often the most economic solution for old generating capacity?
null
cannot read /var/mail/com android monkeyrunner on terminal I am getting an /monkeytest py from: cannot read /var/mail/com android monkeyrunner error when trying to run an stress test on MonkeyRunner in terminal Anyone know what this could be about?
It looks like you are running it as a she will script instead of a Python script Make sure the first line of the Python file contains something like ````#!/usr/bin/env python ```` and not ````#!/bin/sh ```` (or nothing at all which is probably the problem here) The <a href="https://en wikipedia org/wiki/Shebang_%28Unix%29" rel="nofollow">shebang</a> tells the kernel which interpreter to run; in its absence an executable script is handed to the she will If you do not want to make changes to the script for whatever reason using ````python monkeytest py ```` instead of just ```` /monkeytest py ```` is a workaround as well (In the she will the `from` command attempts to tell you whom you have unread email from It does this by examining your local mail spool file which is traditionally in something like `/var/mail/you` where `you` is your login ID )
Flask-restful: marshal complex object to json I have a question regarding flask restful extension I am just started to use it and faced one problem I have `flask-sqlalchemy` entities that are connected many-to-one relation and I want that restful endpoint return parent entity with all its children in `json` using marshaller In my case Set contains many parameters I looked at flask-restful <a href="http://flask-restful readthedocs org/en/latest/fields html">docs</a> but there was not any explanation how to solve this case Seems like I am missing something obvious but cannot figure out any solution Here is my code: ````# entities class Set(db Model): id = db Column("id" db Integer db Sequence("set_id_seq") primary_key=True) title = db Column("title" db String(256)) parameters = db relationship("Parameters" backref="set" cascade="all") class Parameters(db Model): id = db Column("id" db Integer db Sequence("parameter_id_seq") primary_key=True) flag = db Column("flag" db String(256)) value = db Column("value" db String(256)) set_id = db Column("set_id" db Integer db ForeignKey("set id")) # marshallers from flask ext restful import fields parameter_marshaller = { "flag": fields String "value": fields String } set_marshaller = { 'id': fields String 'title': fields String 'parameters': fields List(fields Nested(parameter_marshaller)) } # endpoint class SetApi(Resource): @marshal_with(marshallers set_marshaller) def get(self set_id): entity = Set query get(set_id) return entity restful_api = Api(app) restful_api add_resource(SetApi "/api/set/<int:set_id&gt;") ```` Now when i call `/api/set/1` I get server error: `TypeError: 'Set' object is unsubscriptable` So I need a way to correctly define set_marshaller that endpoint return this json: ````{ "id": : "1" "title": "any-title" "parameters": [ {"flag": "any-flag" "value": "any-value" } {"flag": "any-flag" "value": "any-value" } ] } ```` I appreciate any help
I found solution to that problem myself After playing around with `flask-restful` i find out that i made few mistakes: Firstly `set_marshaller` should look like this: ````blob_marshaller = { 'id': fields String 'title': fields String 'parameters': fields Nested(parameter_marshaller) } ```` Restless marshaller can handle case if parameter is list and marshals to `json` list Another problem was that in API Set parameters has lazy loading so when i try to marshall Set i got `KeyError: 'parameters'` so I need explicitly load parameters like this: ````class SetApi(Resource): @marshal_with(marshallers set_marshaller) def get(self set_id): entity = Set query get(set_id) entity parameters # loads parameters from db return entity ```` Or another option is to change model relationship: ````parameters = db relationship("Parameters" backref="set" cascade="all" lazy="joined") ````
In which area in London is Imperial's main campus located?
South Kensington
what is the best way to make my folders invisible / restricted in twistd? a fews days ago i tried to learn the python twisted and this is how i make my webserver : ````from twisted application import internet service from twisted web import static server script from twisted web resource import Resource import os class NotFound(Resource): isLeaf=True def render(self request): return "Sorry the page you are requesting is not found / forbidden" class myStaticFile(static File): def directoryListing(self): return self childNotFound #root=static file(os getcwd()+"/www") root=myStaticFile(os getcwd()+"/www") root indexNames=['index py'] root ignoreExt(" py") root processors = {' py': script ResourceScript} root childNotFound=NotFound() application = service Application('web') sc = service IServiceCollection(application) i = internet TCPServer(8080 server Site(root))#@UndefinedVariable i setServiceParent(sc) ```` in my code i make an instance class for twisted web static File and `override` the `directoryListing` so when user try to access my resource folder (`http://localhost:8080/resource/` or `http://localhost:8080/resource/css`) it will return a notFound page but he can still open/read the `http://localhost:8080/resource/css/style css` it works what i want to know is is this the correct way to do that??? is there another 'perfect' way ? i was looking for a config that disable directoryListing like `root dirListing=False` but no luck
Yes that is a reasonable way to do it You can also use `twisted web resource NoResource` or `twisted web resource Forbidden` instead of defining your own `NotFound`
Ignore background noise? I am making a voice recognition software for my computer but I have some problems: 1) Is there a way to ignore background noise? I want the program to end when there is x amount of time without noise but background noise could keep it awake indefinitely 2) same thing but reverse I want it to start when it hears a voice but loud enough background noise will start it as well
Sorry I cannot provide any code only pseudocode You can create en enum or a list of possible phonemes spoken Activate the program only when the ADSR pattern of the phoneme is recognized with volume as a secondary indicator to separate "background" phonemes If the background noise is so loud that it interferes with the recognition of the phoneme then it should not be considered a background sound in the first place ````Aah = 1 Ahh = 2 Ehh = 3 if soundEvent == true: if phoneme type = Aah: what_i_said = "a" ````
Python mySQL - escaping quotes I have seen this question asked in various ways on this website but none of them exactly addressed my issue I have an sql statement with single quotes inside it and am trying to use recommended practices before making database queries with it So the statement is like ````val2="abc 'dostuff'" sql="INSERT INTO TABLE_A(COL_A COL_B) VALUES(%s '%s')" %(val1 val2) a_cursor execute(sql) ```` However when I run this I get ````ProgrammingError: (1064 "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'dostuff' ```` What am I doing wrong? Thanks very much Nupur
Use parameters instead of string interpolation to ensure that your values are properly escaped by the database connector: ````sql = "INSERT INTO TABLE_A(COL_A COL_B) VALUES(%s %s)" a_cursor execute(sql (val1 val2)) ```` The mysqldb sql parameter style uses the same syntax as used by the python string formatting operator which is a little confusing
global question (python) I have the code: ````from Tkinter import * admin = Tk() a = 1 def up(): global a a = 1 def upp(): up() print a print 'its ' a buttton = Button(admin text='up' command=upp) buttton pack() mainloop() ```` I want to have the "its " a go up each time i press the button so kind of replay the code so that its # would go up by one each time help
I tested this: ````from Tkinter import * import itertools admin = Tk() a = itertools count(1) next def upp(): print a() buttton = Button(admin text='up' command=upp) buttton pack() mainloop() ```` This will start a at a value of 1 and each time its printed it will add one more So the first time you press it it will display 1 in standard out
how to get the two '111 = ' using python Regular Expressions this is mu\y code: ````a = '111 = dw11qdwq\n111 = aaaaa' print re search(r'111 = (\S*)' a) group(1) ```` it show : `dw11qdwq` but i want get `dw11qdwq` and `aaaaa` so what can i do thanks <strong>updated</strong> ````a = '111 = dw11qdwq\n111 = aaaaa' b=re findall(r'111 = (\S*)' a) d = ['qqqqqq' 'wwwwwww'] a= re sub(r'111 = (\S*)' lambda x: d[] a) ```` and how to replace the `dw11qdwq` to `qqqqqq` `aaaaa` to `wwwwwww` i want to get `'111 = qqqqqq\n111 = wwwwwww'` <strong>updated:</strong> it is ok now : ````d = {'dw11qdwq':'qqqqqq' 'aaaaa':'wwwwwww'} a = '111 = dw11qdwq\n111 = aaaaa' print repr(a) a= re sub('(111\s*=\s*)(\S*)' lambda mat: mat group(1)+d[mat group(2)] a) print repr(a) ````
````a = '111 = dw11qdwq\n111 = aaaaa' print re findall(r'111 = (\S+)' a) ```` This matches any word with 1 or more non-space characters (I am fairly sure you do not want to match 0 or more characters(which is what '*' provide)) <strong>Edit:</strong> Code for your update: ````replacements = {"dw11qdwq":"qqqqqq" "aaaaa" : "wwwwwww"} a = '111 = dw11qdwq\n111 = aaaaa' for key value in replacements iteritems(): a = a replace(key value) ```` a is now: ````"111 = qqqqqq\n111 = wwwwwww" ````
How many members does the Alliance 90 have?
null
Emacs: python-she will does not respond to RET When I start python-she will (or even just start python from M-x she will) Emacs gives the expected prompt: ````bash-3 2$ python Python 2 7 1 (r271:86832 Jun 16 2011 16:59:05) [GCC 4 2 1 (Based on Apple Inc build 5658) (LLVM build 2335 15 00)] on darwin Type "help" "copyright" "credits" or "license" for more information &gt;&gt;&gt; ```` But when I type something at the prompt and press RET the cursor moves down a line but the command is not executed The only commands I can get the subprocess to respond to are interrupts like C-C C-c After an interrupt another prompt (>>>) appears and I can use M-n and M-p to navigate the lines I "entered" earlier ````&gt;&gt;&gt; test hmmm definitely pressed enter there C-c C-c KeyboardInterrupt &gt;&gt;&gt; ```` Curiously this occurs both in Aquaemacs and in emacs -nw I have tried moving my emacs and emacs d files and the behavior is the same Any ideas on what might be causing this?
After you do "M-x she will" and then "python RET" do "C-h k RET" and then what is displayed? the Help buffer should say that "comint-send-input" is the command that is executed for RET If it is not showing "comint-send-input" as the command executed by "RET" then there is probably something in one of your init files (the emacs file is not the only init file) that is overriding this binding So then try running emacs with "emacs -nw -q -no-site-file" and repeat the above If it was not displaying "comint-send-input" previously and is displaying "comint-send-input" now then it is definitely something in one of your init files Look at both your local (http://www gnu org/software/emacs/emacs-lisp-intro/elisp/Init-File html#Init-File) and site-wide (http://www gnu org/software/emacs/emacs-lisp-intro/html_node/Site_002dwide-Init html#Site_002dwide-Init) init files to try to find the culprit If it is not obvious after examining the files your best bet is to rename any init files you find and gradually re-introduce the code until you find what is causing the "breakage"
Hangman Tkinter GUI - Trouble with for loop I am coding a GUI with Tkinter for a python <a href="http://pastebin com/wAMUsxka" rel="nofollow" title="Full project">hangman game</a> I am running into some trouble with my `for` loop that I use to replace the blanks of the hidden word with the actual letter that corresponds with the blank when the letter is guessed by the user This is the loop: ````def reveal(self start=False full=False): global hiddenWord charList if start == True: for i in answerWord: if i == " ": charList append(" ") else: charList append("__") hiddenWord set(" " join(charList)) elif full == True: hiddenWord set(answerWord) else: c = guess get() for i in answerWord: if i == c lower(): charList[answerWord index(i)] = i elif i == c upper(): charList[answerWord index(i)] = i hiddenWord set(" " join(charList)) ```` The problem that I am having is that when I run the program and the hidden word is one with multiple occurrences of the same letter occasionally only the first occurrence of the letter will be replaced Here is one instance where this issue occurred when the word was 'california': <a href="http://i stack imgur com/Tkf3l gif" rel="nofollow">california missing second 'i' and second 'a'</a> Now this does not happen all of the time and I have not been able to debug the problem because I cannot seem to find any common factors between the instances where it does occur I am a novice when it comes to Tkinter so I acknowledge that my program is a little sloppy as I am still trying to get into the swing of things Does anyone know what might be causing this problem?
For some reason I was able to solve my problem by editing the logic of the `for` loop as such: ````else: c = guess get() for i in range(0 len(answerWord)): if answerWord[i] == c lower(): charList[i] = answerWord[i] elif answerWord[i] == c upper(): charList[i] = answerWord[i] hiddenWord set(" " join(charList)) ````
How to check for pipes in directory traversal? I have a Python program that traverses a directory and generates md5sums On one file it gets stuck Running `ls -lA` I found that it has the attributes `prw-------` Some googling later I found that this indicates a pipe How to check for pipes in my traversal? I just want to skip this file <hr> My code for traversing is: ````for dirpath _ files in walk(folder): for fname in files: print join(dirpath fname) if not islink(join(dirpath fname)): # do something with the file here I pass it to myClass myClass addFile(dirpath fname) ````
You do not really need to test for pipes explicitly you only want to look for files Use `os path isfile()`; it will return `False` for a pipe but `True` for an actual file: ````$ ls -l total 0 -rw-rw-r-- 1 mj mj 0 Sep 7 12:27 actualfile prw-rw-r-- 1 mj mj 0 Sep 7 12:25 pipe &gt;&gt;&gt; os path isfile('pipe') False &gt;&gt;&gt; os path isfile('actualfile') True ````
Who does Yasuhare say was influenced by Western Universities?
null
Python decompress gzip data in memory without file I have gzipped data from HTTP reply I have following code: ````def gzipDecode(self content): import StringIO import gzip outFilePath = 'test' compressedFile = StringIO StringIO(content) decompressedFile = gzip GzipFile(fileobj=compressedFile) with open(outFilePath 'w') as outfile: outfile write(decompressedFile read()) data = '' with open(outFilePath 'r') as myfile: data=myfile read() replace('\n' '') return data ```` which decompress input gzipped content and return string (http reply is gzipped json) - It works But I need it without creating <strong>test</strong> file - all in memory I modified it to: ````def gzipDecode(self content): import StringIO from io import BytesIO import gzip outFile = StringIO StringIO() compressedFile = StringIO StringIO(content) decompressedFile = gzip GzipFile(fileobj=compressedFile) outFile write(decompressedFile read()) outFile flush() data = outFile read() replace('\n' '') print "_" data "_" return data ```` but it crash (<strong>gzipDecode</strong> produce empty output) in parsing json: ````Traceback (most recent call last): __ File "/usr/lib/python2 7/SocketServer py" line 593 in process_request_thread self finish_request(request client_address) ---------------------------------------- File "/usr/lib/python2 7/SocketServer py" line 334 in finish_request Exception happened during processing of request from ('10 123 66 3' 39853) self RequestHandlerClass(request client_address self) ---------------------------------------- File "/usr/lib/python2 7/SocketServer py" line 649 in __init__ self handle() File "/usr/lib/python2 7/BaseHTTPServer py" line 340 in handle self handle_one_request() File "/usr/lib/python2 7/BaseHTTPServer py" line 328 in handle_one_request method() File "/tmp/test_server py" line 92 in do_POST data = json loads(file_content) File "/usr/lib/python2 7/json/__init__ py" line 338 in loads return _default_decoder decode(s) File "/usr/lib/python2 7/json/decoder py" line 366 in decode obj end = self raw_decode(s idx=_w(s 0) end()) File "/usr/lib/python2 7/json/decoder py" line 384 in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded ```` What I do bad?
You need to seek back to the start before you can read: ````outFile write(decompressedFile read()) outFile flush() outFile seek(0) data = outFile read() replace('\n' '') ````
Cython: Nesting a union within a struct In Cython glue declarations how do I represent a C `struct` type containing an anonymous union? For example if I have a C header file `mystruct h` containing ````struct mystruct { union { double da; uint64_t ia; }; }; ```` then in the corresponding ` pyd` file ````cdef extern from "mystruct h": struct mystruct: # what goes here??? ```` I tried this: ````cdef extern from "mystruct h": struct mystruct: union {double da; uint64_t ia;}; ```` but that only gave me "Syntax error in C variable declaration" on the `union` line
You cannot nest declarations to the best of my knowledge and Cython does not support anonymous unions AFAIK Try the following: ````cdef union mystruct_union: double lower_d uint64_t lower cdef struct mystruct: mystruct_union un ```` Now access the union members as `un lower_d` and `un lower`
how to generate rectangle from a plane equation ax+by+cz=d? given a plane equation how can you generate four points that comprise a rectangle? I only have the plane equation ax+by+cz=d I am following the approach listed here <a href="http://stackoverflow com/questions/22769430/find-corners-of-rectangle-given-plane-equation-height-and-width">Find Corners of Rectangle Given Plane equation height and width</a> ````#generate horizontal vector YOU temp_normal=np array([a b c]) temp_vertical=np array([0 0 1]) YOU=np cross(temp_normal temp_vertical) # for corner 3 and 4 neg_U=np multiply([-1 0 -1 0 -1 0] YOU) #generate vertical vector W W=np cross(temp_normal YOU) #for corner 2 and 4 neg_W=np multiply([-1 0 -1 0 -1 0] W) #make the four corners #C1 = P0 (width / 2) * YOU (height / 2) * W C1=np sum([centroid np multiply(YOU width_array) np multiply(W height_array)] axis=0) corner1=C1 tolist() #C2 = P0 (width / 2) * YOU - (height / 2) * W C2=np sum([centroid np multiply(YOU width_array) np multiply(neg_W height_array)] axis=0) corner2=C2 tolist() #C3 = P0 - (width / 2) * YOU (height / 2) * W C3=np sum([centroid np multiply(neg_U width_array) np multiply(W height_array)] axis=0) corner3=C3 tolist() #C4 = P0 - (width / 2) * YOU - (height / 2) * W C4=np sum([centroid np multiply(neg_U width_array) np multiply(neg_W height_array)] axis=0) self theLw WriteLine("C4 is " str(type(C4))+" "+str(C4 tolist())) corner4=C4 tolist() corners_list append([corner1 corner2 corner3 corner4]) ````
Find a vector inside that plane using the equation Find a second one inside that plane perpendicular to the first one using the <a href="https://en wikipedia org/wiki/Cross_product" rel="nofollow">cross-product</a> (of the first and a <a href="https://en wikipedia org/wiki/Normal_%28geometry%29" rel="nofollow">normal vector to the plane</a>) Then add these vectors (with - signs 4 possibilities) to generate 4 corners Edit: to help you a bit more: - (a b c) is the vector normal to the plane; - (0 0 d/c) (0 d/b 0) and (d/a 0 0) are points belonging to the plane i e for instance b1 = (0 d/b -d/c) is a vector tangent to the plane; - The cross-product of two vectors returns a vector that is perpendicular to both So the product b2 = (a b c) x (0 d/b -d/c) is a vector tangent to the plane perpendicular to the other one With that you have constructed a normal basis of the plane [b1 b2] - Start from a point say (0 0 d/c) and add b1+b2 b1-b2 -b1+b2 -b1-b2 to have 4 corners Ok here is the answer: ````import numpy as np a = 2; b = 3; c = 4; d = 5 n = np array([a b c]) x1 = np array([0 0 d/c]) x2 = np array([0 d/b 0]) def is_equal(n m): return n-m < 1e-10 def is_on_the_plane(v): return is_equal(v[0]*a v[1]*b v[2]*c d) assert is_on_the_plane(x1) assert is_on_the_plane(x2) # Get the normal basis b1 = x2 - x1 b2 = np cross(n b1) c1 = x1 b1 b2 c2 = x1 b1 - b2 c3 = x1 - b1 b2 c4 = x1 - b1 - b2 assert is_on_the_plane(c1) assert is_on_the_plane(c2) assert is_on_the_plane(c3) assert is_on_the_plane(c4) assert is_equal(np dot(c1-c3 c1-x2) 0) assert is_equal(np dot(c2-c1 c2-c4) 0) # etc : # c3 c1 # # x1 # # c4 c2 ```` It is actually a square but you can surely find out how to make it a less specific rectangle
matplotlib LogFormatterExponent -- 'e' in the exponent labels of cbar So I am modifying someone else's library to setup a cbar with log (values) I thought I could use LogFormatterExponent() But it seemingly randomly adds and 'e' to the exponents that it uses for the cbar What is going on? How can I suppress/fix this? <blockquote> ```` if show_cbar: if log: l_f = LogFormatterExponent() else: l_f = ScalarFormatter() if qtytitle is not None: plt colorbar(ims format=l_f) set_label(qtytitle) else: plt colorbar(ims format=l_f) set_label(units) ```` </blockquote> Here is what I am seeing for log=True: <a href="http://i stack imgur com/u4zRp png" rel="nofollow"><img src="http://i stack imgur com/u4zRp png" alt="enter image description here"></a> And another plot where log = False: <a href="http://i stack imgur com/tcj1r png" rel="nofollow"><img src="http://i stack imgur com/tcj1r png" alt="enter image description here"></a> At first I thought the 'e's were being cut-off by the label at right but over several plots this does not appear to be the case I usually get 1-2 'e's But on a plot with only 3 color bar ticks I see none! <a href="http://i stack imgur com/u2tjI png" rel="nofollow"><img src="http://i stack imgur com/u2tjI png" alt="enter image description here"></a>
A minimal example is ````import numpy as np import matplotlib pyplot as plt import matplotlib colors as cm import matplotlib ticker as ct data = np exp(np random rand(20 20) * 100) fig ax = plt subplots() log_norm = cm LogNorm() i am = ax imshow(data interpolation='nearest' cmap='viridis' norm=log_norm) fig colorbar(i am format=ct LogFormatterExponent()) ```` This looks like a bug in mpl If you already have a large library I would just include a fixed version of the formatter ````class LogFormatterExponentFixed(LogFormatter): """ Format values for log axis; using ``exponent = log_base(value)`` """ def __call__(self x pos=None): """Return the format for tick val *x* at position *pos*""" vmin vmax = self axis get_view_interval() vmin vmax = mtransforms nonsingular(vmin vmax expander=0 05) d = abs(vmax - vmin) b = self _base if x == 0: return '0' sign = np sign(x) # only label the decades fx = math log(abs(x)) / math log(b) isDecade = is_close_to_int(fx) if not isDecade and self labelOnlyBase: s = '' elif abs(fx) &gt; 10000: s = '%1 0g' % fx elif abs(fx) < 1: s = '%1 0g' % fx else: # this is the added line fd = math log(abs(d)) / math log(b) s = self pprint_val(fx fd) if sign == -1: s = '-%s' % s return self fix_minus(s) ```` Working on a <a href="https://github com/matplotlib/matplotlib/pull/5594" rel="nofollow">fix for upstream</a>
How to prevent injection attack in CREATE query in python mysql I know the proper way to avoid injection attack in SELECT or INSERT queries using python module MySQLdb is: `cursor execute("SELECT spam eggs sausage FROM breakfast WHERE price < %s" (max_price ))` However when I tried to apply the same rule in CREATE query it returns error My code: `cursor execute("CREATE DATABASE %s;" ("test" ))` It reports syntax error: `_mysql_exceptions ProgrammingError: (1064 "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test'' at line 1")` It seems it is because the query adds single quote to the db name and Mysql does not allow that in CREATE query? So what is the proper way to CREATE database or table using python MySQLdb module then given the db name or table name is not fixed?
Try square brackets; ````cursor execute("CREATE DATABASE %s;" ["test"]) ````
Index error: list assignment index out of range I have written this function: ````def replace(self pos note): """ Replace the score of the participant at the given position with a new score Input: pos note - integer Output: the old score was replaced """ scores = self repo getAll() scores[pos] = note return scores ```` Where getAll is defined in class participantRepo as follows: ```` def getAll(self): return self _participantList[:] ```` My problem is that I do not understand the error I keep getting
If list does not already have at least `pos+1` elements `list[pos]` would try to assign `note` to an index outside the list You can use the <a href="https://docs python org/2/tutorial/datastructures html" rel="nofollow">`append()`</a> method to add items to the list
python fractions - dash being parsed as "2013" => Invalid literal for Fraction: Using scrapy to get recipes having trouble parsing the strings: I am attempting to parse this string "1 – 1 1/2 cup Grated Raw Cauliflower" and the dash is being interpreted by python as a the following "ValueError: Invalid literal for Fraction: you'\u2013' " Is there anyway I can error handle so the whole program does not throw? Overview: use regex to parse string into number measurement item convert to float detect fraction convert fraction to float I used a try/except to simply err on the "min" side of the range provided though I would ideally like to have both somehow ````if re compile("[^\W\d]") search(quantity): match = re compile("[^\W\d]") search(quantity) amount = s[:match start()] grocery = s[item start():] if '/' not in amount: amount = float(amount) elif '/' in amount: def tryAmount(amount): try: return round(float(sum(Fraction(s) for s in amount split())) 2) except ValueError: return amount[0] amount= tryAmount(amount) else: amount = amount[0] ````
Let us work it through: ````quantity = "1 – 1 1/2 cup Grated Raw Cauliflower" match = re compile("[^\W\d]") search(quantity) ```` So `match group(0)` is `c` meaning `amount = s[:match start()]` sets `amount` to be `"1 – 1 1/2 "` `amount split()` would then be `['1' '\xe2\x80\x93' '1' '1/2']` (or `['1' '–' '1' '1/2']` if printed) and you are passing each value to `Fraction()` which cannot take the them-dash or even a hyphen: ````&gt;&gt;&gt; Fraction('–') ValueError: Invalid literal for Fraction: '\xe2\x80\x93' ```` The comprehension `sum(Fraction(s) for s in amount split()))` will not do what you want anyway: If it worked as written it would add up `1` `1` and `0 5` to give `2 5` which is above the suggested value of 'between 1 and 1 5' I think you may need to revisit your approach to extracting numbers and interpreting ranges in the recipes!
Python 3 3 2 tkinter ttk TreeView per-column sorting only sorts by last column? I am trying to get a simplistic ttk TreeView table going with per-column sorting using the heading 'command' tag but it does not seem to work right I am using the answer to this question for implementing the functionality: <a href="http://stackoverflow com/questions/1966929/tk-treeview-column-sort">Tk treeview column sort</a> My code: ````import tkinter as tk from tkinter import ttk def treeview_sort_column(tv col reverse): print('sorting %s!' % col) l = [(tv set(k col) k) for k in tv get_children('')] l sort(reverse=reverse) # rearrange items in sorted positions for index (val k) in enumerate(l): print('Moving Index:%are Value:%are k:%r' % (index val k)) tv move(k '' index) # reverse sort next time tv heading(col command=lambda: treeview_sort_column(tv col not reverse)) cols = ('name' 'path' 'time' 'pb') root = tk Tk() root geometry("700x500") listbox = ttk Treeview(root columns=cols show="headings") for each in ('name' 'path' 'time' 'pb'): listbox heading(each text=each capitalize() command=lambda: treeview_sort_column(listbox each False)) listbox column( each width=tk font Font() measure(each title() )) if not each == 'path': listbox column(each stretch=False) if not each == 'name': listbox column( each anchor='center') listbox pack(expand=True fill=tk BOTH) root mainloop() ```` The problem I am running into is every time I run this it only sorts by the last column not by the column your clicking on (verified with the print statement in the treeview_sort_column function) Output I get from clicking on any column in the resulting window: ````sorting pb! sorting pb! sorting pb! sorting pb! sorting pb! sorting pb! sorting pb! sorting pb! ```` If I change from dynamic creation of each command in the for loop to explicit ones by adding this after the loop then it works as expected (i e each column sorts itself) ````listbox heading('name' command=lambda: treeview_sort_column(listbox 'name' False)) listbox heading('path' command=lambda: treeview_sort_column(listbox 'path' False)) listbox heading('time' command=lambda: treeview_sort_column(listbox 'time' False)) listbox heading('pb' command=lambda: treeview_sort_column(listbox 'pb' False)) ```` produces: ````sorting name! sorting name! sorting path! sorting path! sorting time! sorting time! sorting pb! sorting pb! ```` Obviously this is a very simplistic example and my final application actually inserts data into the columns (also has more columns) but since I cannot even get this simplified version to work I am at a loss What is wrong with my loop that is causing the lambda functions to get screwed up? My system: - Windows 7 64 bit - Python 3 3 2
You should use lambda in other way In your code every lambda gets a pointer to the same variable that is why all functions do the same thing You should e g copy variable to make lambda unique An example how to do it: ````for each in ('name' 'path' 'time' 'pb'): listbox heading(each text=each capitalize() command=lambda each_=each: treeview_sort_column(listbox each_ False)) ```` Simple example: ````funcs = [] for item in ('abc' 'def' 'ghi'): funcs append(lambda : print(item)) for f in funcs: f() ```` It prints: ````ghi ghi ghi ```` But version with fixed lambda: ````funcs = [] for item in ('abc' 'def' 'ghi'): funcs append(lambda item_=item: print(item_)) for f in funcs: f() ```` prints ````abc def ghi ````
append 2 hex values in python I am trying to append some hex values in python and I always seem to get 0x between the number From what I searched either this is not possible without converting it into a lit of values ?? I am not sure ````a = 0x7b b = 0x80000 hex(a) hex(b) = 0x7b0x80000 ```` I do not want the 0x in the middle - I need `0x7b80000` is there any other way to do this? If I convert to integer I get the sum of the two and converting it to hex is a different value than `0x7b80000`
I do not think you want to "append" them Doing integer arithmetic by using strings is a bad idea I think you want to bit-shift `a` into the right place and OR them together: ````&gt;&gt;&gt; a = 0x7B &gt;&gt;&gt; b = 0x80000 &gt;&gt;&gt; &gt;&gt;&gt; hex( (a<<20) | b ) '0x7b80000' ```` Perhaps if you were more specific about what these numbers are and what exactly you are trying to accomplish I could provide a more general answer
Circular Hough Transform misses circles I have read a lot about the Circular Hough transform on Stack Overflow but I seem to be missing something I wrote a program that is supposed to detect the circles of a "Bull's Eye" target However even after playing with the parameters the algorithm is quite bad - it ignores most of the circles and one time it finds a circle but seems to "wander off" I have even tried applying an "Unsharp Mask" to no avail I have added my code the image I started with and the output I hope someone can point me at the right direction ````import cv2 import cv2 cv as cv import numpy as np import math # Load Image img = cv2 imread('circles1 png' 0) # Apply Unsharp Mask tmp = cv2 medianBlur(img 5) img = cv2 addWeighted(img 1 5 tmp -0 5 0) cimg = cv2 cvtColor(img cv2 COLOR_GRAY2BGR) # Hough Transform circles = cv2 HoughCircles(img cv CV_HOUGH_GRADIENT 1 5 param1=100 param2=100 minRadius=0 maxRadius=0) circles = np uint16(np around(circles)) # Go over circles eliminating the ones that are not cocentric enough height width = img shape center = (width/2 height/2) for i in circles[0 :]: # draw the outer circle if math sqrt((center[0]-i[0])**2 (center[1]-i[1])**2) < 15: cv2 circle(cimg (i[0] i[1]) i[2] (0 255 0) 1) # draw the center of the circle cv2 circle(cimg (i[0] i[1]) 2 (0 0 255) 3) cv2 imshow('detected circles' cimg) cv2 waitKey(0) cv2 destroyAllWindows() ```` Quick explanation: I load the image apply Unsharp Mask use the Hough Transfrom to detect circles then draw the circles that are close to the center (I found that the other circles are false circles) I tried playing with the parameters and this is the best I got I feel like this is a simple enough problem which has me buffled I appriciate any help My input image: <a href="http://i stack imgur com/Fvarg png" rel="nofollow"><img src="http://i stack imgur com/Fvarg png" alt="Input image"></a> My output image: <a href="http://i stack imgur com/DaH8r png" rel="nofollow"><img src="http://i stack imgur com/DaH8r png" alt="Output image"></a>
As I mentioned in my comment you will need to run successive iterations of `cv2 HoughCircles` for different range of radii to ensure that you get all of the circles With the way the Circular Hough Transform works specifying a minimum and maximum radius that has quite a large range will be inaccurate and will also be slow They do not tell you this in the documentation but for the Circular Hough Transform to work successfully the following two things need to be valid: ````maxRadius < 3*minRadius maxRadius - minRadius < 100 ```` With the above blindly making the minimum radius very small and the maximum radius very large will not give you great results Therefore what you could do is start at say `radius=1` then iterate up to `radius=300` in steps of 20 Between each chunk of 20 run `cv2 HoughCircles` and update your image with these contours Doing this requires very little modification to your code BY THE WAY I removed the unsharp masking it because I was getting poor results with it I also changed a couple of parameters in `cv2 HoughCircles` slightly to get this to work as best as possible given your situation: ````import cv2 import cv2 cv as cv import numpy as np import math # Load Image img = cv2 imread('circles1 png' 0) cimg = cv2 cvtColor(img cv2 COLOR_GRAY2BGR) # Specify different radii radii = np arange(0 310 10) # For each pair of radii for idx in range(len(radii)-1): # Get the minimum and maximum radius # Note you need to add 1 to each minimum # as the maximum of the previous pair covers this new minimum minRadius = radii[idx]+1 maxRadius = radii[idx+1] # Hough Transform - Change here circles = cv2 HoughCircles(img cv CV_HOUGH_GRADIENT 1 5 param1=25 param2=75 minRadius=minRadius maxRadius=maxRadius) # Skip if no circles are detected - Change here if circles is None: continue circles = np uint16(np around(circles)) # Go over circles eliminating the ones that are not cocentric enough height width = img shape center = (width/2 height/2) for i in circles[0 :]: # draw the outer circle if math sqrt((center[0]-i[0])**2 (center[1]-i[1])**2) < 15: cv2 circle(cimg (i[0] i[1]) i[2] (0 255 0) 1) # draw the center of the circle cv2 circle(cimg (i[0] i[1]) 2 (0 0 255) 3) cv2 imshow('detected circles' cimg) cv2 waitKey(0) cv2 destroyAllWindows() ```` I get this figure: <a href="http://i stack imgur com/GQzDU png" rel="nofollow"><img src="http://i stack imgur com/GQzDU png" alt="enter image description here"></a> Unfortunately it is not perfect as it does not detect all of the circles You will have to play around with the `cv2 HoughCircles` function until you get good results <hr> However I would not recommend using `cv2 HoughCircles` here May I suggest using <a href="http://docs opencv org/modules/imgproc/doc/structural_analysis_and_shape_descriptors html#findcontours" rel="nofollow">`cv2 findContours`</a> instead? This finds all of the contours in the image In this case these will be the black circles However you need to reverse the image because `cv2 findContours` assumes non-zero pixels are object pixels so we can subtract 255 from the image assuming a `np uint8` type: ````# Make copy of original image cimg2 = cv2 cvtColor(img cv2 COLOR_GRAY2BGR) # Find contours contours _ = cv2 findContours(255 - img cv2 RETR_LIST cv CV_CHAIN_APPROX_NONE) # Draw all detected contours on image in green with a thickness of 1 pixel cv2 drawContours(cimg2 contours -1 color=(0 255 0) thickness=1) # Show the image cv2 imshow('detected circles' cimg2) cv2 waitKey(0) cv2 destroyAllWindows() ```` This is what I get: <a href="http://i stack imgur com/6jOJ3 png" rel="nofollow"><img src="http://i stack imgur com/6jOJ3 png" alt="enter image description here"></a>
Who was responsible for crafting a new look for all Microsoft products?
null
How to use Python to count comment line in a java source code? This is my code to count blank lines source code lines and total lines and comment lines I use to check if there is '//' in a line to check if it is a comment line but I know it is wrong Because '/<them> </them>/' can form a comment block How to count the number of lines in a comment block? ````def FileLineCount(self filename): (filepath tempfilename) = os path split(filename); (shotname extension) = os path splitext(tempfilename); if extension == ' java' : # file type file = open(filename); self sourceFileCount = 1; allLines = file readlines(); file close(); lineCount = 0; commentCount = 0; blankCount = 0; codeCount = 0; for eachLine in allLines: if eachLine != " " : eachLine = eachLine replace(" " ""); #remove space #remove tabIndent if eachLine find('//') == 0 : #LINECOMMENT commentCount = 1; else : if eachLine == "": blankCount = 1; else : codeCount = 1; lineCount = lineCount 1; self all = lineCount; self allComment = commentCount; self allBlank = blankCount; self allSource = codeCount; print filename; print ' Total :' lineCount ; print ' Comment :' commentCount; print ' Blank :' blankCount; print ' Source :' codeCount; ````
There are problems with your code e g you cannot just remove all whitespaces (you might consider `/{whitespace}/` a comment) I am not going to provide actual code but this should give you a rough idea ````for each line of code 1 Remove all white space from the beginning (left trimming) 2 If mode is not multi-line and the line contains `//` increment counter 3 else if mode is not multi-line and the line contains `/*` go to multi-line mode 4 else if mode is multi-line increment coutner if line contains `*/` exit multi-line mode ```` The conditions could be simplified but I think you can get it to work
Adding mpl_toolkits basemap canvas to Pyside I have generated a map using mpl_toolkits basemap and it works However after trying to integrate it into Pyside I am having trouble displaying it as a QWidget I am not getting any errors the program just hangs while I wait for it to launch I have looked online and there is not much documentation on this subject ````from PySide QtGui import (QWidget QVBoxLayout QFormLayout QLineEdit QPushButton QFileDialog QGroupBox QApplication) import sys import matplotlib matplotlib use('Qt4Agg') matplotlib rcParams['backend qt4']='PySide' from matplotlib figure import Figure from matplotlib backends backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib backends backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar from mpl_toolkits basemap import Basemap import matplotlib pyplot as plt import numpy as np class Map(QWidget): def __init__(self parent=None): super(Map self) __init__(parent) self setupUI() def setupUI(self): self fig = Figure() self canvas = FigureCanvas(self fig) self layout = QVBoxLayout(self) self mpl_toolbar = NavigationToolbar(self canvas self coordinates = False) self layout addWidget(self canvas) self layout addWidget(self mpl_toolbar) self axes = self fig add_subplot(111) self setLayout(self layout) # make sure the value of resolution is a lowercase L # for 'low' not a numeral 1 map = Basemap(projection='robin' lat_0=0 lon_0=-100 resolution='l' area_thresh=1000 0 ax=self axes) map drawcoastlines() map drawcountries() map fillcontinents(color='green') map drawmapboundary() # lat/lon coordinates of five cities lats = [40 02 32 73 38 55 48 25 17 29] lons = [-105 16 -117 16 -77 00 -114 21 -88 10] cities=['Boulder CO' 'San Diego CA' 'Washington DC' 'Whitefish MT' 'Belize City Belize'] # compute the native map projection coordinates for cities x y = map(lons lats) # plot filled circles at the locations of the cities map plot(x y 'bo') # plot the names of those five cities for name xpt ypt in zip(cities x y): plt text(xpt+50000 ypt+50000 name) self canvas draw() def main(): app = QApplication(sys argv) map = Map() app exec_() main() ````
You forgot to show your widget Add `self show()` to the end of `setupUI`
Method to download json object as json file python I am trying to extract the data from this <a href="http://api coindesk com/v1/bpi/currentprice/EUR json" rel="nofollow">json bitcoin api</a> stored in a json file First I tried ````import urllib json url = "http://api coindesk com/v1/bpi/currentprice json" response = urllib urlopen(url) data = json loads(response read()) print data ```` it worked at first but if I run it again I get this error: ````Traceback (most recent call last): File "btc_api py" line 4 in <module&gt; data = json loads(response read()) File "/usr/lib/python2 7/json/__init__ py" line 338 in loads return _default_decoder decode(s) File "/usr/lib/python2 7/json/decoder py" line 366 in decode obj end = self raw_decode(s idx=_w(s 0) end()) File "/usr/lib/python2 7/json/decoder py" line 384 in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded ```` I have to run the code periodically to get the newest currency and store it in a database Can someone help me with this issue or any ideas how to do it better?
You can use <a href="http://docs python-requests org/en/master/" rel="nofollow"><strong>`requests`</strong></a> with <strong>`json`</strong> method it provides: ````import requests url = "http://api coindesk com/v1/bpi/currentprice json" data = requests get(url) json() ```` Though if you still want to use <strong>`urllib`</strong> use <a href="https://docs python org/2/library/json html#json load" rel="nofollow"><strong>`json load`</strong></a>: ````import urllib import json url = "http://api coindesk com/v1/bpi/currentprice json" response = urllib urlopen(url) data = json load(response) ````
What did Ibn Tufil write in response to the novel by Ibn al-Nafis
null
accessing a variable from outside the function in python ````#!/usr/bin/env python import roslib import rospy import time from nav_msgs message import Odometry def position_callback(data): global q2 q2=data pose pose position x q1=data pose pose position y q3=data pose pose position z def position(): rospy init_node('position' anonymous=True) #initialize the node" rospy Subscriber("odom" Odometry position_callback) if __name__ == '__main__': try: position() print q2 rospy spin() except rospy ROSInterruptException: pass ```` the error i get is like this: ````print q2 NameError: global name 'q2' is not defined ```` I defined `q2` as global variable already
Declaring `q2` as a global variable does make the global variable exist Actually calling the function and execution of the assignment statement `q2 = ` because the creation of the variable Until then the code cannot access the variable `position` function does not call the `position_callback` but pass it to `rospy Subscriber` (which probably register the callback function and not call it directly) <hr> Initialize `q2` if you want to access the variable before it is set ````q2 = None def position_callback(data): global q2 q2 = data pose pose position x q1 = data pose pose position y q3 = data pose pose position z ````
as I add a symbol to a label that has textVariable ````from tkinter import * v=Tk() a=IntVar() a set(5) l=Label(textvariable=a) l pack() ```` How I can add the simbol "$" to the label
First of all you should take a look at the <a href="http://effbot org/tkinterbook/label htm" rel="nofollow">docs</a> and discover how `Label`s the `textvariable` option and the <a href="http://effbot org/tkinterbook/variable htm" rel="nofollow">Tkinter Variable Classes</a> are working since you mixed a few things up However if you just want to display a `$` in the label you should use the Label's `text` option instead of the `textvariable` option: ````from tkinter import * v = Tk() l = Label(text='$') l pack() ```` If you want to connect a Tkinter Variable with the Label you could use the textvariable option However you mixed those up a bit To display characters like the `$` you do not need a `IntVar()` but a `StringVar()` Using the `textvariable` option gives you the possibility to auto update the Label's content if the variable's content (`IntVar()` `StringVar()` `DoubleVar()`) changes For the sake of completeness using a `StringVar()` to display `$` in the label which does not seem to make much sense in your case would be like the following: ````from tkinter import * v = Tk() a = StringVar() a set('$') l = Label(textvariable=a) l pack() ````
Who showed up on the editorial floor of the Independent?
James Murdoch and Rebekah Wade
DOM parsing a document: adding and removing comma based on condition I am using Python's <a href="http://www clips ua ac be/pages/pattern-web" rel="nofollow">pattern web</a> module to perform some basic web mining tasks I am trying to extract only first 15 keywords and append each keyword with a comma `" "` So my resulting file contains a list of keywords that looks like: ````scallops scallop shells sea scallops scallop she will how to cook scallops scallop shells for sale frozen scallops fresh scallops dry scallops cooking scallops baptism she will scallop recipe large scallop shells diver scallops bay scallops ```` Now I do not want the comma `" "` after the 15th/last keyword `"bay scallops "` I need a little help to modify my code below so that at the 15th iteration the code does not add the comma If it were a simple for loop iterating an array I could use `iteritems()` to extract key and value and add an if condition but here I cannot figure out how to do it ````from pattern web import URL DOM plaintext extension folder = ' /some_folder' dom = DOM(content) print "traversing " for e in dom('td spgb-f')[:15]: for a in e('span sptc-e'): File = open(os path join(folder "meta_keywords html") mode="a") print ('adding %s' %(plaintext(a content))) File write(plaintext(a content) " ") File close() ````
Instead of writing each individual string to the file you can add them to a list without the comma and use `" " join(your_list_here)` to create the string that will be written to the file The `join` method takes care of placing the comma just between the elements
How can I properly copy nested dictionary objects? I am working on a project with <strong>Python 2 7</strong> where I have a "complex" dictionary structure and I was trying to do something like this: ````generic_dict = { 'user': {'created': {} 'modified': {} 'errors': {}} 'usermon': {'created': {} 'modified': {} 'ignored': {} 'errors': {}} log_data = { 'esp': generic_dict 'por': generic_dict 'sui': generic_dict 'ben': generic_dict 'mex': generic_dict 'arg': generic_dict } ```` I was trying to use the generic dict to avoid repeating code but I have a problem if I do like this when I modify any of the country dicts (esp ben por) all are modifying at the same time Let us assume the dictionary is empty and I do this ````log_data['esp']['user']['created']['today'] = 'asdasdasda' ```` all the other dicts now have the same value like generic_dict is the same all of them ````print log_data['ben']['user']['created'] Output: {'today': 'asdasdasda'} print log_data['ben']['user']['created'] Output: {'today': 'asdasdasda'} ```` I understand what is happening but I do not know how to avoid that - Which is the best way copy nested dictionary objects ?
You can use <a href="https://docs python org/2/library/copy html#copy deepcopy" rel="nofollow">`copy deepcopy`</a> to create a new copy of the `generic_dict` object like this ````from copy import deepcopy log_data = { 'esp': deepcopy(generic_dict) 'por': deepcopy(generic_dict) 'sui': deepcopy(generic_dict) 'ben': deepcopy(generic_dict) 'mex': deepcopy(generic_dict) 'arg': deepcopy(generic_dict) } ```` <hr> Otherwise you can have a constructor function like this ````def generic_dict(): return {'user': {'created': {} 'modified': {} 'errors': {}} 'usermon': {'created': {} 'modified':{} 'ignored': {} 'errors': {}}} ```` And then call it to create a new dictionary object every time like this ````log_data = { 'esp': generic_dict() 'por': generic_dict() 'sui': generic_dict() 'ben': generic_dict() 'mex': generic_dict() 'arg': generic_dict() } ````