title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Selenium leaves behind running processes?
38,518,998
<p>When my selenium program crashes due to some error, it seems to leave behind running processes. </p> <p>For example, here is my process list:</p> <pre><code>carol 30186 0.0 0.0 103576 7196 pts/11 Sl 00:45 0:00 /home/carol/test/chromedriver --port=51789 carol 30322 0.0 0.0 102552 7160 pts/11 Sl 00:45 0:00 /home/carol/test/chromedriver --port=33409 carol 30543 0.0 0.0 102552 7104 pts/11 Sl 00:48 0:00 /home/carol/test/chromedriver --port=42567 carol 30698 0.0 0.0 102552 7236 pts/11 Sl 00:50 0:00 /home/carol/test/chromedriver --port=46590 carol 30938 0.0 0.0 102552 7496 pts/11 Sl 00:55 0:00 /home/carol/test/chromedriver --port=51930 carol 31546 0.0 0.0 102552 7376 pts/11 Sl 01:16 0:00 /home/carol/test/chromedriver --port=53077 carol 31549 0.5 0.0 0 0 pts/11 Z 01:16 0:03 [chrome] &lt;defunct&gt; carol 31738 0.0 0.0 102552 7388 pts/11 Sl 01:17 0:00 /home/carol/test/chromedriver --port=55414 carol 31741 0.3 0.0 0 0 pts/11 Z 01:17 0:02 [chrome] &lt;defunct&gt; carol 31903 0.0 0.0 102552 7368 pts/11 Sl 01:19 0:00 /home/carol/test/chromedriver --port=54205 carol 31906 0.6 0.0 0 0 pts/11 Z 01:19 0:03 [chrome] &lt;defunct&gt; carol 32083 0.0 0.0 102552 7292 pts/11 Sl 01:20 0:00 /home/carol/test/chromedriver --port=39083 carol 32440 0.0 0.0 102552 7412 pts/11 Sl 01:24 0:00 /home/carol/test/chromedriver --port=34326 carol 32443 1.7 0.0 0 0 pts/11 Z 01:24 0:03 [chrome] &lt;defunct&gt; carol 32691 0.1 0.0 102552 7360 pts/11 Sl 01:26 0:00 /home/carol/test/chromedriver --port=36369 carol 32695 2.8 0.0 0 0 pts/11 Z 01:26 0:02 [chrome] &lt;defunct&gt; </code></pre> <p>Here is my code:</p> <pre><code>from selenium import webdriver browser = webdriver.Chrome("path/to/chromedriver") browser.get("http://stackoverflow.com") browser.find_element_by_id('...').click() browser.close() </code></pre> <p>Sometimes, the browser doesn't load the webpage elements quickly enough so Selenium crashes when it tries to click on something it didn't find. Other times it works fine.</p> <p>This is a simple example for simplicity sake, but with a more complex selenium program, what is a guaranteed clean way of exiting and not leave behind running processes? It should cleanly exit on an unexpected crash and on a successful run.</p>
2
2016-07-22T05:43:15Z
38,536,238
<p>Whats happening is that your code is throwing an exception, halting the python process from continuing on. As such, the close/quit methods never get called on the browser object, so the chromedrivers just hang out indefinitely.</p> <p>You need to use a try/except block to ensure the close method is called every time, even when an exception is thrown. A very simplistic example is:</p> <pre><code>from selenium import webdriver browser = webdriver.Chrome("path/to/chromedriver") try: browser.get("http://stackoverflow.com") browser.find_element_by_id('...').click() except: browser.close() browser.quit() # I exclusively use quit </code></pre> <p>There are a number of much more sophisticated approaches you can take here, such as creating a context manager to use with the <code>with</code> statement, but its difficult to recommend one without having a better understanding of your codebase. </p>
0
2016-07-22T22:43:43Z
[ "python", "python-2.7", "selenium", "selenium-webdriver", "selenium-chromedriver" ]
Convert an american style minute string into integer value
38,519,086
<p>I got an american format string showing seconds of an elapsed event, like <code>4,942.221s</code>. How would be the most pythonic way to convert this into an integer without parsing and removing comma. I want to get the plain seconds, which in this case would be <code>4942</code>, ms can be truncated.</p>
1
2016-07-22T05:50:48Z
38,519,263
<p>You could use float first and then convert to int as below</p> <pre><code>&gt;&gt;&gt;a= '4,942.221s' &gt;&gt;&gt;int(float(a.replace(',', '').replace('s',''))) &gt;&gt;&gt;4942 </code></pre>
1
2016-07-22T06:05:21Z
[ "python", "string", "data-type-conversion" ]
Convert an american style minute string into integer value
38,519,086
<p>I got an american format string showing seconds of an elapsed event, like <code>4,942.221s</code>. How would be the most pythonic way to convert this into an integer without parsing and removing comma. I want to get the plain seconds, which in this case would be <code>4942</code>, ms can be truncated.</p>
1
2016-07-22T05:50:48Z
38,522,971
<p>You could achieve this using the <a href="https://docs.python.org/3.5/library/locale.html" rel="nofollow"><code>locale</code></a> library, which </p> <blockquote> <p>allows programmers to deal with certain cultural issues in an application, without requiring the programmer to know all the specifics of each country where the software is executed.</p> </blockquote> <p>Normally, this would be used to deal with certain issues of formatting strings and such while being agnostic about the locale, however, if your system supports the American English locality settings, then you could do the following, which is a bit hackey, to solve your problem:</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; locale.setlocale(locale.LC_NUMERIC, 'en_US.UTF-8') 'en_US.UTF-8' &gt;&gt;&gt; locale.atoi('123,456,789') 123456789 &gt;&gt;&gt; locale.atof('123,456.787') 123456.787 &gt;&gt;&gt; locale.setlocale(locale.LC_NUMERIC, 'de_DE') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/juan/anaconda3/lib/python3.5/locale.py", line 595, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting &gt;&gt;&gt; american_string = '4,942.221s' &gt;&gt;&gt; int(locale.atof(american_string[:-1])) 4942 </code></pre> <p>You might have to figure out the exact argument to pass to the second parameter of the <code>setlocale</code> function, because it will depend on your system. For example, note the error when I tried to set the German locale, which isn't currently supported on my system. In case you are on Ubuntu, the following should work: <code>sudo apt-get install language-pack-en-base</code> </p>
1
2016-07-22T09:31:27Z
[ "python", "string", "data-type-conversion" ]
Python parse text help- beginner
38,519,152
<p>I have only used Linux/ Python for a couple weeks so I am very new at this. I have a large file that is named "python.test". In the file I am trying to write code so that it tells me how many times a certain word appears in the files. For example the word is help. I am using Linux with Python and have tried several methods but have all failed. How would I do this? Thanks in advance!</p>
-1
2016-07-22T05:55:16Z
38,519,285
<p>In this case, your file should be a .py file (ie <strong>YOURFILENAME.py</strong>). Then to run it in the terminal type <code>$ python yourfile.py</code> Please upload the code, it could be caused by of many other issues too </p>
0
2016-07-22T06:08:03Z
[ "python", "coding-style" ]
random.choice with a list
38,519,240
<p>I have a list of 30 strings. I want to use the choice method of the random module and generate a new string from the list they are stored in. I don't want to repeat any strings and I want to print all the unique strings once. I am trying to make a chat bot but I can only get 1 string to print over and over every time I run the program </p> <pre><code>print("you are speaking with Donald Trump. If you wish to finish your conversation at any time, type good bye") greetings = ["hello", "hey", "what's up ?", "how is it going?", ] #phrase_list = ["hello", "the wisdom you seek is inside you", "questions are more important than answers"] random_greeting = random.choice(greetings) print(random_greeting) open_article = open(filePath, encoding= "utf8") read_article = open_article.read() toks = read_article.split('"') random_tok = random.choice(toks) conversation_length = 0 responses = '' while True: #getting stuck in infinite loops get out and make interative user_response = input(" ") if user_response != "" or user_response != "good bye": responses = responses + user_response conversation_length = conversation_length + 1 while conversation_length &lt; 31: print(random_tok) if conversation_length &gt;= 31: print("bye bye") </code></pre>
0
2016-07-22T06:03:06Z
38,519,511
<p>You need "random selection without replacement." This function, called on a list of strings, will return a random string. Called more than once, it won't ever return the same item.</p> <pre><code>import random def choose_one(poss): """ Remove a randomly chosen item from the given list, and return it. """ if not poss: raise ValueError('cannot choose from empty list') i = random.randint(0, len(poss) - 1) return poss.pop(i) </code></pre>
0
2016-07-22T06:22:21Z
[ "python", "random", "nlp" ]
random.choice with a list
38,519,240
<p>I have a list of 30 strings. I want to use the choice method of the random module and generate a new string from the list they are stored in. I don't want to repeat any strings and I want to print all the unique strings once. I am trying to make a chat bot but I can only get 1 string to print over and over every time I run the program </p> <pre><code>print("you are speaking with Donald Trump. If you wish to finish your conversation at any time, type good bye") greetings = ["hello", "hey", "what's up ?", "how is it going?", ] #phrase_list = ["hello", "the wisdom you seek is inside you", "questions are more important than answers"] random_greeting = random.choice(greetings) print(random_greeting) open_article = open(filePath, encoding= "utf8") read_article = open_article.read() toks = read_article.split('"') random_tok = random.choice(toks) conversation_length = 0 responses = '' while True: #getting stuck in infinite loops get out and make interative user_response = input(" ") if user_response != "" or user_response != "good bye": responses = responses + user_response conversation_length = conversation_length + 1 while conversation_length &lt; 31: print(random_tok) if conversation_length &gt;= 31: print("bye bye") </code></pre>
0
2016-07-22T06:03:06Z
38,519,572
<p>Don't use <code>random.choice()</code>. Use <code>random.shuffle()</code> instead to put the (unique) words in random order instead, then repeatedly take from that list. That ensures that a) you use all the words, and b) don't repeat any picks:</p> <pre><code>random_greetings = greetings[:] # create a copy random.shuffle(random_greetings) </code></pre> <p>and then whenever you want a random word, just use:</p> <pre><code>random_greeting = random.greetings.pop() </code></pre>
0
2016-07-22T06:25:35Z
[ "python", "random", "nlp" ]
file doesnt exists in routes Http directory laravel 5
38,519,305
<p>I have a python script beside 'routes.php' and I want to execute that from 'routes.php' file . when i use exec() function it does not work correctly . so , i try <code>file_exists()</code> : </p> <pre><code>Route::get('/py', function(){ if (file_exists( "new.py" )) echo "succeed"; else echo "failed"; }); </code></pre> <p>it only returns failed , so how can I get output from .py file via exec function ?</p>
0
2016-07-22T06:09:18Z
38,519,399
<p>You need to use the absolute path, try with</p> <pre><code> file_exists(__DIR__.'/new.py') </code></pre> <p>Assuming that it is in the same directory as routes.php</p>
0
2016-07-22T06:15:40Z
[ "php", "python", "laravel", "laravel-5", "routing" ]
file doesnt exists in routes Http directory laravel 5
38,519,305
<p>I have a python script beside 'routes.php' and I want to execute that from 'routes.php' file . when i use exec() function it does not work correctly . so , i try <code>file_exists()</code> : </p> <pre><code>Route::get('/py', function(){ if (file_exists( "new.py" )) echo "succeed"; else echo "failed"; }); </code></pre> <p>it only returns failed , so how can I get output from .py file via exec function ?</p>
0
2016-07-22T06:09:18Z
38,519,484
<p>The file path you are giving is not correct. <strong>file_exists()</strong> will check the file inside the <strong>public</strong> folder in laravel. If you are placed the <strong>py</strong> inside your public folder , then give the exact path to the file. </p>
0
2016-07-22T06:20:51Z
[ "php", "python", "laravel", "laravel-5", "routing" ]
Python27 how to batch read dictionary to execute command
38,519,373
<p><strong>I just need help with how to work with <em>X</em> rows at a time.</strong></p> <p>i have a task to parse a 10000 line csv file -> convert it to dictionary -> then process 100 rows at a time making an API call. For this example lets just output to <strong><em>print</em></strong> function. i will need to execute on every 100 or less as some nested dictionaries will not exactly work out to 100 each, so the code will need to be flexible for this. im using python2.7 with no fancy extra modules like beautiful sup etc. I was given the <strong>api_worker</strong> for loop code block to help me with this task but have no idea how to get it work. Where do i place the print (to be substituted with the api code later)? everything i tried so far prints all, nothing, or every individual string. </p> <p><em>ill cut out a lot of unneeded code:</em> </p> <pre><code>import * # assume i have all the right modules def parseCSV(filename): # this i have working return result def api_worker(readerObj): for majorkey in readerObj.keys(): listof100 = [] for idx, line in enumerate(readerObj.get(majorkey)): if (idx+1 % 100) != 0: listof100.append(line) else: print listof100 #tried here makes no difference del listof100[:] listof100.append(line) print listof100 #tried here but outputs all def main(): readerObj = parseCSV('somefile.csv') api_worker(readerObj) if __name__ == '__main__': main() </code></pre> <p><strong>example source:</strong></p> <pre><code>{'majorkey1': [{'name':'j','age':'3','height':'6feet'}, {'name':'r','age':'4','height':'5feet'}, {'name':'o','age':'5','height':'3feet'}], 'majorkey2':[{'name':'n','age':'6','height':'4feet'}, {'name':'s','age':'7','height':'7feet'}, {'name':'q','age':'7','height':'8feet'}]} </code></pre> <p><strong>desired output:</strong></p> <p>if using this small sample, and i want to print 2 rows at a time the desired output from <strong>print</strong> would be:</p> <p><strong>from majorkey1 group</strong></p> <pre><code>{'name':'j','age':'3','height':'6feet'}{'name':'r','age':'4','height':'5feet'} </code></pre> <p><em>sleep 1 second...</em></p> <pre><code>{'name':'o','age':'5','height':'3feet'} </code></pre> <p><strong>from majorkey2 group</strong></p> <p><em>sleep 1 second...</em></p> <pre><code>{'name':'n','age':'6','height':'4feet'}{'name':'s','age':'7','height':'7feet'} </code></pre> <p><em>sleep 1 second...</em></p> <pre><code>{'name':'q','age':'7','height':'8feet'} </code></pre> <p>Help is greatly appreciated.</p>
0
2016-07-22T06:13:54Z
38,519,548
<p>Sounds like you need to break up a list into fixed-length chunks, without loading the whole list into memory? This is possible using some help from the <code>itertools</code> module. This is taken from the <a href="https://docs.python.org/2/library/itertools.html#recipes" rel="nofollow">Python docs</a>:</p> <pre><code>from itertools import izip_longest def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --&gt; ABC DEF Gxx args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) </code></pre>
0
2016-07-22T06:24:34Z
[ "python", "csv", "parsing", "dictionary" ]
Python27 how to batch read dictionary to execute command
38,519,373
<p><strong>I just need help with how to work with <em>X</em> rows at a time.</strong></p> <p>i have a task to parse a 10000 line csv file -> convert it to dictionary -> then process 100 rows at a time making an API call. For this example lets just output to <strong><em>print</em></strong> function. i will need to execute on every 100 or less as some nested dictionaries will not exactly work out to 100 each, so the code will need to be flexible for this. im using python2.7 with no fancy extra modules like beautiful sup etc. I was given the <strong>api_worker</strong> for loop code block to help me with this task but have no idea how to get it work. Where do i place the print (to be substituted with the api code later)? everything i tried so far prints all, nothing, or every individual string. </p> <p><em>ill cut out a lot of unneeded code:</em> </p> <pre><code>import * # assume i have all the right modules def parseCSV(filename): # this i have working return result def api_worker(readerObj): for majorkey in readerObj.keys(): listof100 = [] for idx, line in enumerate(readerObj.get(majorkey)): if (idx+1 % 100) != 0: listof100.append(line) else: print listof100 #tried here makes no difference del listof100[:] listof100.append(line) print listof100 #tried here but outputs all def main(): readerObj = parseCSV('somefile.csv') api_worker(readerObj) if __name__ == '__main__': main() </code></pre> <p><strong>example source:</strong></p> <pre><code>{'majorkey1': [{'name':'j','age':'3','height':'6feet'}, {'name':'r','age':'4','height':'5feet'}, {'name':'o','age':'5','height':'3feet'}], 'majorkey2':[{'name':'n','age':'6','height':'4feet'}, {'name':'s','age':'7','height':'7feet'}, {'name':'q','age':'7','height':'8feet'}]} </code></pre> <p><strong>desired output:</strong></p> <p>if using this small sample, and i want to print 2 rows at a time the desired output from <strong>print</strong> would be:</p> <p><strong>from majorkey1 group</strong></p> <pre><code>{'name':'j','age':'3','height':'6feet'}{'name':'r','age':'4','height':'5feet'} </code></pre> <p><em>sleep 1 second...</em></p> <pre><code>{'name':'o','age':'5','height':'3feet'} </code></pre> <p><strong>from majorkey2 group</strong></p> <p><em>sleep 1 second...</em></p> <pre><code>{'name':'n','age':'6','height':'4feet'}{'name':'s','age':'7','height':'7feet'} </code></pre> <p><em>sleep 1 second...</em></p> <pre><code>{'name':'q','age':'7','height':'8feet'} </code></pre> <p>Help is greatly appreciated.</p>
0
2016-07-22T06:13:54Z
38,519,599
<p>One possibility:</p> <pre><code>from itertools import islice d = { 'majorkey1': [ { 'name':'j','age':'3','height':'6feet' }, { 'name':'r','age':'4','height':'5feet' }, { 'name':'o','age':'5','height':'3feet' }, ], 'majorkey2': [ { 'name':'n','age':'6','height':'4feet' }, { 'name':'s','age':'7','height':'7feet' }, { 'name':'q','age':'7','height':'8feet' }, ], } n = 2 for k, v in d.items(): print '{}:'.format(k) it = iter(v) while True: rows = list(islice(it, n)) if len(rows) == 0: break print '\t{}'.format(rows) # Output: # majorkey1: # [{'age': '3', 'name': 'j', 'height': '6feet'}, {'age': '4', 'name': 'r', 'height': '5feet'}] # [{'age': '5', 'name': 'o', 'height': '3feet'}] # majorkey2: # [{'age': '6', 'name': 'n', 'height': '4feet'}, {'age': '7', 'name': 's', 'height': '7feet'}] # [{'age': '7', 'name': 'q', 'height': '8feet'}] </code></pre> <p>(BTW, if you really want the format you gave above, you could replace that list <code>print</code> with <code>print ''.join(map(repr, rows))</code>, and of course you could insert a sleep wherever you want.)</p>
0
2016-07-22T06:27:22Z
[ "python", "csv", "parsing", "dictionary" ]
How to pass a URL parameter using python, Flask, and the command line
38,519,475
<p>I am having a lot of trouble passing a URL parameter using request.args.get. </p> <p>My code is the following: </p> <pre><code>from flask import Flask, request app= Flask(__name__) @app.route('/post?id=post_id', methods=["GET"]) def show_post(): post_id=1232 return request.args.get('post_id') if __name__=="__main__": app.run(host='0.0.0.0') </code></pre> <p>After saving, I always type python filename.py in the command line, see Running on <a href="http://0.0.0.0:5000/" rel="nofollow">http://0.0.0.0:5000/</a> (Press CTRL+C to quit) as the return on the command line, and then type in the url (<a href="http://ip_addres:5000/post?id=1232">http://ip_addres:5000/post?id=1232</a>) in chrome to see if it will return 1232, but it won't do it! Please help.</p>
0
2016-07-22T06:20:26Z
38,519,543
<p><code><a href="http://flask.pocoo.org/docs/0.11/api/#flask.Request.args" rel="nofollow">request.args</a></code> is what you are looking for.</p> <pre><code>@app.route('/post', methods=["GET"]) def show_post() post_id = request.args.get('id') </code></pre> <p>request.args is get all the GET parameters and construct <code><a href="http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.MultiDict" rel="nofollow">Multidict</a></code> like this <code>MultiDict([('id', '1232'),])</code> so using <code>get</code> you can <code>get</code> the id </p>
0
2016-07-22T06:24:21Z
[ "python", "http", "command-line", "flask" ]
How to pass a URL parameter using python, Flask, and the command line
38,519,475
<p>I am having a lot of trouble passing a URL parameter using request.args.get. </p> <p>My code is the following: </p> <pre><code>from flask import Flask, request app= Flask(__name__) @app.route('/post?id=post_id', methods=["GET"]) def show_post(): post_id=1232 return request.args.get('post_id') if __name__=="__main__": app.run(host='0.0.0.0') </code></pre> <p>After saving, I always type python filename.py in the command line, see Running on <a href="http://0.0.0.0:5000/" rel="nofollow">http://0.0.0.0:5000/</a> (Press CTRL+C to quit) as the return on the command line, and then type in the url (<a href="http://ip_addres:5000/post?id=1232">http://ip_addres:5000/post?id=1232</a>) in chrome to see if it will return 1232, but it won't do it! Please help.</p>
0
2016-07-22T06:20:26Z
38,519,554
<p>You should leave the query parameters out of the route as they aren't part of it.</p> <pre><code>@app.route('/post', methods=['GET']) def show_post(): post_id = request.args.get('id') return post_id </code></pre> <p><code>request.args</code> is a dictionary containing all of the query parameters passed in the URL.</p>
1
2016-07-22T06:24:47Z
[ "python", "http", "command-line", "flask" ]
How to generate HL7 message?
38,519,553
<p>I want to send the data of patient to the dcm4chee using the python code, Currently I am able to send the data to the modality worklist using the "MLLPClient" but I have HL7 message which is generated by the openMRS, can any one help to know that how can I generate custom HL7 message using the patient data in python (odoo). </p>
0
2016-07-22T06:24:43Z
38,559,392
<p>Maybe Hapi could help you: <a href="http://hl7api.sourceforge.net/hapi-testpanel/install.html" rel="nofollow">http://hl7api.sourceforge.net/hapi-testpanel/install.html</a> . It generates HL7 messages and I guess it could build hL7 messages with your own data. </p> <p>Good luck!</p>
0
2016-07-25T03:44:25Z
[ "python", "openerp", "hl7", "hl7-v3" ]
How to generate HL7 message?
38,519,553
<p>I want to send the data of patient to the dcm4chee using the python code, Currently I am able to send the data to the modality worklist using the "MLLPClient" but I have HL7 message which is generated by the openMRS, can any one help to know that how can I generate custom HL7 message using the patient data in python (odoo). </p>
0
2016-07-22T06:24:43Z
38,670,231
<p>Here is the blog which helps me to create HL7 message.</p> <p><a href="https://msarfati.wordpress.com/2015/06/22/python-hl7-v2-x-and-hl7apy-hl7-construction-with-ormo01-and-orur01-part-2/" rel="nofollow">https://msarfati.wordpress.com/2015/06/22/python-hl7-v2-x-and-hl7apy-hl7-construction-with-ormo01-and-orur01-part-2/</a></p> <p>In this blog the given code for OBR segment, You need to do: OrderDetailGroup before adding and populating the OBR segment.</p>
0
2016-07-30T04:04:15Z
[ "python", "openerp", "hl7", "hl7-v3" ]
Scikit-learn SVM digit recognition
38,519,716
<p>I want to make a program to <strong>recognize the digit</strong> in an image. I follow the tutorial in <a href="http://scikit-learn.org/stable/auto_examples/classification/plot_digits_classification.html">scikit learn</a> .</p> <p>I can <strong>train and fit the svm classifier</strong> like the following.</p> <p>First, I import the libraries and dataset</p> <pre><code>from sklearn import datasets, svm, metrics digits = datasets.load_digits() n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1)) </code></pre> <p>Second, I create the SVM model and train it with the dataset.</p> <pre><code>classifier = svm.SVC(gamma = 0.001) classifier.fit(data[:n_samples], digits.target[:n_samples]) </code></pre> <p>And then, I try to read my own image and use the function <code>predict()</code> to recognize the digit.</p> <p>Here is my image: <a href="http://i.stack.imgur.com/0bgQX.jpg"><img src="http://i.stack.imgur.com/0bgQX.jpg" alt="enter image description here"></a></p> <p>I <strong>reshape</strong> the image into (8, 8) and then convert it to a <strong>1D array.</strong></p> <pre><code>img = misc.imread("w1.jpg") img = misc.imresize(img, (8, 8)) img = img[:, :, 0] </code></pre> <p>Finally, when I print out the <strong>prediction</strong>, it returns [1]</p> <pre><code>predicted = classifier.predict(img.reshape((1,img.shape[0]*img.shape[1] ))) print predicted </code></pre> <p>Whatever I user others images, it still returns [1]</p> <p><a href="http://i.stack.imgur.com/0LhHb.jpg"><img src="http://i.stack.imgur.com/0LhHb.jpg" alt="enter image description here"></a> <a href="http://i.stack.imgur.com/caGUx.jpg"><img src="http://i.stack.imgur.com/caGUx.jpg" alt="enter image description here"></a></p> <p>When I print out the "<strong>default" dataset</strong> of number "9", it looks like:<a href="http://i.stack.imgur.com/90MOj.jpg"><img src="http://i.stack.imgur.com/90MOj.jpg" alt="enter image description here"></a></p> <p><strong>My image</strong> number "9" : </p> <p><a href="http://i.stack.imgur.com/RDg94.jpg"><img src="http://i.stack.imgur.com/RDg94.jpg" alt="enter image description here"></a></p> <p>You can see the non-zero number is quite large for my image.</p> <p>I dont know why. I am looking for help to solve my problem. Thanks</p>
4
2016-07-22T06:35:10Z
38,521,182
<p>It's just a guess but... The Training set from Sk-Learn are <strong>black numbers</strong> on a <strong>white background</strong>. And you are trying to predict numbers which are white on a black background...</p> <p>I think you should either train on your training set, or train on the negative version of your pictures.</p> <p>I hope this help !</p>
1
2016-07-22T07:59:01Z
[ "python", "image", "image-processing", "scikit-learn" ]
Scikit-learn SVM digit recognition
38,519,716
<p>I want to make a program to <strong>recognize the digit</strong> in an image. I follow the tutorial in <a href="http://scikit-learn.org/stable/auto_examples/classification/plot_digits_classification.html">scikit learn</a> .</p> <p>I can <strong>train and fit the svm classifier</strong> like the following.</p> <p>First, I import the libraries and dataset</p> <pre><code>from sklearn import datasets, svm, metrics digits = datasets.load_digits() n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1)) </code></pre> <p>Second, I create the SVM model and train it with the dataset.</p> <pre><code>classifier = svm.SVC(gamma = 0.001) classifier.fit(data[:n_samples], digits.target[:n_samples]) </code></pre> <p>And then, I try to read my own image and use the function <code>predict()</code> to recognize the digit.</p> <p>Here is my image: <a href="http://i.stack.imgur.com/0bgQX.jpg"><img src="http://i.stack.imgur.com/0bgQX.jpg" alt="enter image description here"></a></p> <p>I <strong>reshape</strong> the image into (8, 8) and then convert it to a <strong>1D array.</strong></p> <pre><code>img = misc.imread("w1.jpg") img = misc.imresize(img, (8, 8)) img = img[:, :, 0] </code></pre> <p>Finally, when I print out the <strong>prediction</strong>, it returns [1]</p> <pre><code>predicted = classifier.predict(img.reshape((1,img.shape[0]*img.shape[1] ))) print predicted </code></pre> <p>Whatever I user others images, it still returns [1]</p> <p><a href="http://i.stack.imgur.com/0LhHb.jpg"><img src="http://i.stack.imgur.com/0LhHb.jpg" alt="enter image description here"></a> <a href="http://i.stack.imgur.com/caGUx.jpg"><img src="http://i.stack.imgur.com/caGUx.jpg" alt="enter image description here"></a></p> <p>When I print out the "<strong>default" dataset</strong> of number "9", it looks like:<a href="http://i.stack.imgur.com/90MOj.jpg"><img src="http://i.stack.imgur.com/90MOj.jpg" alt="enter image description here"></a></p> <p><strong>My image</strong> number "9" : </p> <p><a href="http://i.stack.imgur.com/RDg94.jpg"><img src="http://i.stack.imgur.com/RDg94.jpg" alt="enter image description here"></a></p> <p>You can see the non-zero number is quite large for my image.</p> <p>I dont know why. I am looking for help to solve my problem. Thanks</p>
4
2016-07-22T06:35:10Z
38,576,947
<p>My best bet would be that there is a problem with your data types and array shapes.</p> <p>It looks like you are training on numpy arrays that are of the type <code>np.float64</code> (or possibly <code>np.float32</code> on 32 bit systems, I don't remember) and where each image has the shape <code>(64,)</code>.</p> <p>Meanwhile your input image for prediction, after the resizing operation in your code, is of type <code>uint8</code> and shape <code>(1, 64)</code>.</p> <p>I would first try changing the shape of your input image since dtype conversions often just work as you would expect. So change this line:</p> <p><code>predicted = classifier.predict(img.reshape((1,img.shape[0]*img.shape[1] )))</code></p> <p>to this:</p> <p><code>predicted = classifier.predict(img.reshape(img.shape[0]*img.shape[1]))</code></p> <p>If that doesn't fix it, you can always try recasting the data type as well with </p> <p><code>img = img.astype(digits.images.dtype)</code>.</p> <p>I hope that helps. Debugging by proxy is a lot harder than actually sitting in front of your computer :)</p> <p>Edit: According to the SciPy documentation, the training data contains integer values from 0 to 16. The values in your input image should be scaled to fit the same interval. (<a href="http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits</a>)</p>
4
2016-07-25T20:32:44Z
[ "python", "image", "image-processing", "scikit-learn" ]
Scikit-learn SVM digit recognition
38,519,716
<p>I want to make a program to <strong>recognize the digit</strong> in an image. I follow the tutorial in <a href="http://scikit-learn.org/stable/auto_examples/classification/plot_digits_classification.html">scikit learn</a> .</p> <p>I can <strong>train and fit the svm classifier</strong> like the following.</p> <p>First, I import the libraries and dataset</p> <pre><code>from sklearn import datasets, svm, metrics digits = datasets.load_digits() n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1)) </code></pre> <p>Second, I create the SVM model and train it with the dataset.</p> <pre><code>classifier = svm.SVC(gamma = 0.001) classifier.fit(data[:n_samples], digits.target[:n_samples]) </code></pre> <p>And then, I try to read my own image and use the function <code>predict()</code> to recognize the digit.</p> <p>Here is my image: <a href="http://i.stack.imgur.com/0bgQX.jpg"><img src="http://i.stack.imgur.com/0bgQX.jpg" alt="enter image description here"></a></p> <p>I <strong>reshape</strong> the image into (8, 8) and then convert it to a <strong>1D array.</strong></p> <pre><code>img = misc.imread("w1.jpg") img = misc.imresize(img, (8, 8)) img = img[:, :, 0] </code></pre> <p>Finally, when I print out the <strong>prediction</strong>, it returns [1]</p> <pre><code>predicted = classifier.predict(img.reshape((1,img.shape[0]*img.shape[1] ))) print predicted </code></pre> <p>Whatever I user others images, it still returns [1]</p> <p><a href="http://i.stack.imgur.com/0LhHb.jpg"><img src="http://i.stack.imgur.com/0LhHb.jpg" alt="enter image description here"></a> <a href="http://i.stack.imgur.com/caGUx.jpg"><img src="http://i.stack.imgur.com/caGUx.jpg" alt="enter image description here"></a></p> <p>When I print out the "<strong>default" dataset</strong> of number "9", it looks like:<a href="http://i.stack.imgur.com/90MOj.jpg"><img src="http://i.stack.imgur.com/90MOj.jpg" alt="enter image description here"></a></p> <p><strong>My image</strong> number "9" : </p> <p><a href="http://i.stack.imgur.com/RDg94.jpg"><img src="http://i.stack.imgur.com/RDg94.jpg" alt="enter image description here"></a></p> <p>You can see the non-zero number is quite large for my image.</p> <p>I dont know why. I am looking for help to solve my problem. Thanks</p>
4
2016-07-22T06:35:10Z
38,610,838
<p>1) You need to create your own training set - based on data similar to what you will be making predictions. The call to <code>datasets.load_digits()</code> in scikit-learn is loading a preprocessed version of the MNIST Digits dataset, which, for all we know, could have very different images to the ones that you are trying to recognise.</p> <p>2) You need to set the parameters of your classifier properly. The call to <code>svm.SVC(gamma = 0.001)</code> is just choosing an arbitrary value of the gamma parameter in SVC, which may not be the best option. In addition, you are not configuring the C parameter - which is pretty important for SVMs. I'd bet that this is one of the reasons why your output is 'always 1'.</p> <p>3) Whatever final settings you choose for your model, you'll need to use a cross-validation scheme to ensure that the algorithm is effectively learning </p> <p>There's a lot of Machine Learning theory behind this, but, as a good start, I would really recommend to have a look at <a href="http://scikit-learn.org/stable/modules/svm.html" rel="nofollow">SVM - scikit-learn</a> for a more in-depth description of how the SVC implementation in sickit-learn works, and <a href="http://scikit-learn.org/stable/modules/grid_search.html#grid-search" rel="nofollow">GridSearchCV</a> for a simple technique for parameter setting.</p>
3
2016-07-27T10:49:08Z
[ "python", "image", "image-processing", "scikit-learn" ]
Scikit-learn SVM digit recognition
38,519,716
<p>I want to make a program to <strong>recognize the digit</strong> in an image. I follow the tutorial in <a href="http://scikit-learn.org/stable/auto_examples/classification/plot_digits_classification.html">scikit learn</a> .</p> <p>I can <strong>train and fit the svm classifier</strong> like the following.</p> <p>First, I import the libraries and dataset</p> <pre><code>from sklearn import datasets, svm, metrics digits = datasets.load_digits() n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1)) </code></pre> <p>Second, I create the SVM model and train it with the dataset.</p> <pre><code>classifier = svm.SVC(gamma = 0.001) classifier.fit(data[:n_samples], digits.target[:n_samples]) </code></pre> <p>And then, I try to read my own image and use the function <code>predict()</code> to recognize the digit.</p> <p>Here is my image: <a href="http://i.stack.imgur.com/0bgQX.jpg"><img src="http://i.stack.imgur.com/0bgQX.jpg" alt="enter image description here"></a></p> <p>I <strong>reshape</strong> the image into (8, 8) and then convert it to a <strong>1D array.</strong></p> <pre><code>img = misc.imread("w1.jpg") img = misc.imresize(img, (8, 8)) img = img[:, :, 0] </code></pre> <p>Finally, when I print out the <strong>prediction</strong>, it returns [1]</p> <pre><code>predicted = classifier.predict(img.reshape((1,img.shape[0]*img.shape[1] ))) print predicted </code></pre> <p>Whatever I user others images, it still returns [1]</p> <p><a href="http://i.stack.imgur.com/0LhHb.jpg"><img src="http://i.stack.imgur.com/0LhHb.jpg" alt="enter image description here"></a> <a href="http://i.stack.imgur.com/caGUx.jpg"><img src="http://i.stack.imgur.com/caGUx.jpg" alt="enter image description here"></a></p> <p>When I print out the "<strong>default" dataset</strong> of number "9", it looks like:<a href="http://i.stack.imgur.com/90MOj.jpg"><img src="http://i.stack.imgur.com/90MOj.jpg" alt="enter image description here"></a></p> <p><strong>My image</strong> number "9" : </p> <p><a href="http://i.stack.imgur.com/RDg94.jpg"><img src="http://i.stack.imgur.com/RDg94.jpg" alt="enter image description here"></a></p> <p>You can see the non-zero number is quite large for my image.</p> <p>I dont know why. I am looking for help to solve my problem. Thanks</p>
4
2016-07-22T06:35:10Z
38,611,859
<p>If you look at: <a href="http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html#sklearn.datasets.load_digits</a></p> <p>you can see that each point in the matrix as a value between 0-16.</p> <p>You can try to transform the values of the image to between 0-16. I did it and now the prediction works well for the digit 9 but not for 8 and 6. It doesn't give 1 any more.</p> <pre><code>from sklearn import datasets, svm, metrics import cv2 import numpy as np # Load digit database digits = datasets.load_digits() n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1)) # Train SVM classifier classifier = svm.SVC(gamma = 0.001) classifier.fit(data[:n_samples], digits.target[:n_samples]) # Read image "9" img = cv2.imread("w1.jpg") img = img[:,:,0]; img = cv2.resize(img, (8, 8)) # Normalize the values in the image to 0-16 minValueInImage = np.min(img) maxValueInImage = np.max(img) normaliizeImg = np.floor(np.divide((img - minValueInImage).astype(np.float),(maxValueInImage-minValueInImage).astype(np.float))*16) # Predict predicted = classifier.predict(normaliizeImg.reshape((1,normaliizeImg.shape[0]*normaliizeImg.shape[1] ))) print predicted </code></pre>
1
2016-07-27T11:36:50Z
[ "python", "image", "image-processing", "scikit-learn" ]
Scikit-learn SVM digit recognition
38,519,716
<p>I want to make a program to <strong>recognize the digit</strong> in an image. I follow the tutorial in <a href="http://scikit-learn.org/stable/auto_examples/classification/plot_digits_classification.html">scikit learn</a> .</p> <p>I can <strong>train and fit the svm classifier</strong> like the following.</p> <p>First, I import the libraries and dataset</p> <pre><code>from sklearn import datasets, svm, metrics digits = datasets.load_digits() n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1)) </code></pre> <p>Second, I create the SVM model and train it with the dataset.</p> <pre><code>classifier = svm.SVC(gamma = 0.001) classifier.fit(data[:n_samples], digits.target[:n_samples]) </code></pre> <p>And then, I try to read my own image and use the function <code>predict()</code> to recognize the digit.</p> <p>Here is my image: <a href="http://i.stack.imgur.com/0bgQX.jpg"><img src="http://i.stack.imgur.com/0bgQX.jpg" alt="enter image description here"></a></p> <p>I <strong>reshape</strong> the image into (8, 8) and then convert it to a <strong>1D array.</strong></p> <pre><code>img = misc.imread("w1.jpg") img = misc.imresize(img, (8, 8)) img = img[:, :, 0] </code></pre> <p>Finally, when I print out the <strong>prediction</strong>, it returns [1]</p> <pre><code>predicted = classifier.predict(img.reshape((1,img.shape[0]*img.shape[1] ))) print predicted </code></pre> <p>Whatever I user others images, it still returns [1]</p> <p><a href="http://i.stack.imgur.com/0LhHb.jpg"><img src="http://i.stack.imgur.com/0LhHb.jpg" alt="enter image description here"></a> <a href="http://i.stack.imgur.com/caGUx.jpg"><img src="http://i.stack.imgur.com/caGUx.jpg" alt="enter image description here"></a></p> <p>When I print out the "<strong>default" dataset</strong> of number "9", it looks like:<a href="http://i.stack.imgur.com/90MOj.jpg"><img src="http://i.stack.imgur.com/90MOj.jpg" alt="enter image description here"></a></p> <p><strong>My image</strong> number "9" : </p> <p><a href="http://i.stack.imgur.com/RDg94.jpg"><img src="http://i.stack.imgur.com/RDg94.jpg" alt="enter image description here"></a></p> <p>You can see the non-zero number is quite large for my image.</p> <p>I dont know why. I am looking for help to solve my problem. Thanks</p>
4
2016-07-22T06:35:10Z
38,612,384
<p>Hi in addition to @carrdelling respond, i will add that you may use the same training set, if you normalize your images to have the same range of value. For example you could binaries your data ( 1 if > 0, 0 else ) or you could divide by the maximum intensity in your image to have an arbitrary interval [0;1]. </p>
0
2016-07-27T12:01:36Z
[ "python", "image", "image-processing", "scikit-learn" ]
Scikit-learn SVM digit recognition
38,519,716
<p>I want to make a program to <strong>recognize the digit</strong> in an image. I follow the tutorial in <a href="http://scikit-learn.org/stable/auto_examples/classification/plot_digits_classification.html">scikit learn</a> .</p> <p>I can <strong>train and fit the svm classifier</strong> like the following.</p> <p>First, I import the libraries and dataset</p> <pre><code>from sklearn import datasets, svm, metrics digits = datasets.load_digits() n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1)) </code></pre> <p>Second, I create the SVM model and train it with the dataset.</p> <pre><code>classifier = svm.SVC(gamma = 0.001) classifier.fit(data[:n_samples], digits.target[:n_samples]) </code></pre> <p>And then, I try to read my own image and use the function <code>predict()</code> to recognize the digit.</p> <p>Here is my image: <a href="http://i.stack.imgur.com/0bgQX.jpg"><img src="http://i.stack.imgur.com/0bgQX.jpg" alt="enter image description here"></a></p> <p>I <strong>reshape</strong> the image into (8, 8) and then convert it to a <strong>1D array.</strong></p> <pre><code>img = misc.imread("w1.jpg") img = misc.imresize(img, (8, 8)) img = img[:, :, 0] </code></pre> <p>Finally, when I print out the <strong>prediction</strong>, it returns [1]</p> <pre><code>predicted = classifier.predict(img.reshape((1,img.shape[0]*img.shape[1] ))) print predicted </code></pre> <p>Whatever I user others images, it still returns [1]</p> <p><a href="http://i.stack.imgur.com/0LhHb.jpg"><img src="http://i.stack.imgur.com/0LhHb.jpg" alt="enter image description here"></a> <a href="http://i.stack.imgur.com/caGUx.jpg"><img src="http://i.stack.imgur.com/caGUx.jpg" alt="enter image description here"></a></p> <p>When I print out the "<strong>default" dataset</strong> of number "9", it looks like:<a href="http://i.stack.imgur.com/90MOj.jpg"><img src="http://i.stack.imgur.com/90MOj.jpg" alt="enter image description here"></a></p> <p><strong>My image</strong> number "9" : </p> <p><a href="http://i.stack.imgur.com/RDg94.jpg"><img src="http://i.stack.imgur.com/RDg94.jpg" alt="enter image description here"></a></p> <p>You can see the non-zero number is quite large for my image.</p> <p>I dont know why. I am looking for help to solve my problem. Thanks</p>
4
2016-07-22T06:35:10Z
38,675,371
<p>You probably want to extract features relevant to to your data set from the images and train your model on them. One example I copied from <a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_surf_intro/py_surf_intro.html" rel="nofollow">here.</a></p> <p><code>surf = cv2.SURF(400) kp, des = surf.detectAndCompute(img,None)</code></p> <p>But the SURF features may not be the most useful or relevant to your dataset and training task. You should try others too like <a href="https://en.wikipedia.org/wiki/Histogram_of_oriented_gradients" rel="nofollow">HOG</a> or others.</p> <p>Remember this more high level the features you extract the more general/error-tolerant your model will be to unseen images. However, you may be sacrificing accuracy in your known samples and test cases.</p>
0
2016-07-30T15:07:14Z
[ "python", "image", "image-processing", "scikit-learn" ]
Beautifulsoup loop through HTML
38,519,975
<p>As mentioned in the previous question, I am using Beautiful soup with python to retrieve weather data from a website.</p> <p>Here's how the website looks like:</p> <pre><code>&lt;channel&gt; &lt;title&gt;2 Hour Forecast&lt;/title&gt; &lt;source&gt;Meteorological Services Singapore&lt;/source&gt; &lt;description&gt;2 Hour Forecast&lt;/description&gt; &lt;item&gt; &lt;title&gt;Nowcast Table&lt;/title&gt; &lt;category&gt;Singapore Weather Conditions&lt;/category&gt; &lt;forecastIssue date="18-07-2016" time="03:30 PM"/&gt; &lt;validTime&gt;3.30 pm to 5.30 pm&lt;/validTime&gt; &lt;weatherForecast&gt; &lt;area forecast="TL" lat="1.37500000" lon="103.83900000" name="Ang Mo Kio"/&gt; &lt;area forecast="SH" lat="1.32100000" lon="103.92400000" name="Bedok"/&gt; &lt;area forecast="TL" lat="1.35077200" lon="103.83900000" name="Bishan"/&gt; &lt;area forecast="CL" lat="1.30400000" lon="103.70100000" name="Boon Lay"/&gt; &lt;area forecast="CL" lat="1.35300000" lon="103.75400000" name="Bukit Batok"/&gt; &lt;area forecast="CL" lat="1.27700000" lon="103.81900000" name="Bukit Merah"/&gt;` &lt;channel&gt; </code></pre> <p>I managed to retrieve forecastIssue date &amp; validTime. However, I am not able to retrieve the different area forecast.</p> <p>Here are my python codes :</p> <pre><code>import requests from bs4 import BeautifulSoup import urllib3 outfile = open('C:\scripts\idk.xml','w') #getting the time r = requests.get('http://www.nea.gov.sg/api/WebAPI/? dataset=2hr_nowcast&amp;keyref=&lt;keyrefno&gt;') soup = BeautifulSoup(r.content, "xml") time = soup.find('validTime').string print time #print issue date and time for currentdate in soup.findAll('item'): string = currentdate.find('forecastIssue') print string </code></pre> <p>This is the part where I want to retrieve area forecast eg. <strong>area forecast="TL" lat="1.37500000" lon="103.83900000" name="Ang Mo Kio"/</strong></p> <pre><code>for area in soup.findAll('weatherForecast'): areastring = area.find('area') print areastring </code></pre> <p>When I run my codes in python, it only retrieved the first area which is Ang Mo Kio</p> <p>Sample output: </p> <pre><code>2.30 pm to 5.30 pm &lt;forecastIssue date="22-07-2016" time="02:30 PM"/&gt; &lt;area forecast="RA" lat="1.37500000" lon="103.83900000" name="Ang Mo Kio"/&gt; </code></pre> <p><a href="http://i.stack.imgur.com/RM7wb.png" rel="nofollow">Inspect element of the website</a></p> <p>As you can see, area forecast is within <strong>div class</strong></p> <ol> <li><p>How do I loop through all the areas? I've tried googling but apparently findAll doesn't seem to work for my codes </p></li> <li><p>Is there any way to split the date and time?</p></li> <li><p>Is there any way I can parse data retrieved by beautifulsoup into a xml file? As my output doesn't contain any data when I run the codes.</p></li> </ol> <p>Thank you.</p>
0
2016-07-22T06:51:27Z
38,520,401
<p>1.To loop through all the areas,</p> <pre><code>areas = soup.select('area') for data in areas: print(data.get('name')) </code></pre> <p>Output</p> <pre><code>Ang Mo Kio Bedok Bishan Boon Lay Bukit Batok Bukit Merah </code></pre> <p>2.You can individually extact data as well</p> <pre><code>date = soup.select('forecastissue')[0].get('date') time = soup.select('forecastissue')[0].get('time') </code></pre>
1
2016-07-22T07:16:50Z
[ "python", "beautifulsoup" ]
Beautifulsoup loop through HTML
38,519,975
<p>As mentioned in the previous question, I am using Beautiful soup with python to retrieve weather data from a website.</p> <p>Here's how the website looks like:</p> <pre><code>&lt;channel&gt; &lt;title&gt;2 Hour Forecast&lt;/title&gt; &lt;source&gt;Meteorological Services Singapore&lt;/source&gt; &lt;description&gt;2 Hour Forecast&lt;/description&gt; &lt;item&gt; &lt;title&gt;Nowcast Table&lt;/title&gt; &lt;category&gt;Singapore Weather Conditions&lt;/category&gt; &lt;forecastIssue date="18-07-2016" time="03:30 PM"/&gt; &lt;validTime&gt;3.30 pm to 5.30 pm&lt;/validTime&gt; &lt;weatherForecast&gt; &lt;area forecast="TL" lat="1.37500000" lon="103.83900000" name="Ang Mo Kio"/&gt; &lt;area forecast="SH" lat="1.32100000" lon="103.92400000" name="Bedok"/&gt; &lt;area forecast="TL" lat="1.35077200" lon="103.83900000" name="Bishan"/&gt; &lt;area forecast="CL" lat="1.30400000" lon="103.70100000" name="Boon Lay"/&gt; &lt;area forecast="CL" lat="1.35300000" lon="103.75400000" name="Bukit Batok"/&gt; &lt;area forecast="CL" lat="1.27700000" lon="103.81900000" name="Bukit Merah"/&gt;` &lt;channel&gt; </code></pre> <p>I managed to retrieve forecastIssue date &amp; validTime. However, I am not able to retrieve the different area forecast.</p> <p>Here are my python codes :</p> <pre><code>import requests from bs4 import BeautifulSoup import urllib3 outfile = open('C:\scripts\idk.xml','w') #getting the time r = requests.get('http://www.nea.gov.sg/api/WebAPI/? dataset=2hr_nowcast&amp;keyref=&lt;keyrefno&gt;') soup = BeautifulSoup(r.content, "xml") time = soup.find('validTime').string print time #print issue date and time for currentdate in soup.findAll('item'): string = currentdate.find('forecastIssue') print string </code></pre> <p>This is the part where I want to retrieve area forecast eg. <strong>area forecast="TL" lat="1.37500000" lon="103.83900000" name="Ang Mo Kio"/</strong></p> <pre><code>for area in soup.findAll('weatherForecast'): areastring = area.find('area') print areastring </code></pre> <p>When I run my codes in python, it only retrieved the first area which is Ang Mo Kio</p> <p>Sample output: </p> <pre><code>2.30 pm to 5.30 pm &lt;forecastIssue date="22-07-2016" time="02:30 PM"/&gt; &lt;area forecast="RA" lat="1.37500000" lon="103.83900000" name="Ang Mo Kio"/&gt; </code></pre> <p><a href="http://i.stack.imgur.com/RM7wb.png" rel="nofollow">Inspect element of the website</a></p> <p>As you can see, area forecast is within <strong>div class</strong></p> <ol> <li><p>How do I loop through all the areas? I've tried googling but apparently findAll doesn't seem to work for my codes </p></li> <li><p>Is there any way to split the date and time?</p></li> <li><p>Is there any way I can parse data retrieved by beautifulsoup into a xml file? As my output doesn't contain any data when I run the codes.</p></li> </ol> <p>Thank you.</p>
0
2016-07-22T06:51:27Z
38,520,413
<blockquote> <p>When I run my codes in python, it only retrieved the first area which is Ang Mo Kio</p> </blockquote> <p><code>findAll('weatherForecast')</code> will return a sequence of <strong>one</strong> element, given provided XML. You then proceed to iterate through this sequence and use <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find" rel="nofollow"><code>find('area')</code></a>, which stops after finding 1 element and returns that, if any. To find all the <em>area</em> elements in <em>weatherForecast</em>:</p> <pre><code>for area in soup.find('weatherForecast').find_all('area'): print area </code></pre> <blockquote> <p>Is there any way to split the date and time?</p> </blockquote> <p>Not entirely sure what you mean, perhaps you want to extract the values from the element:</p> <pre><code>for currentdate in soup.find_all('item'): element = currentdate.find('forecastIssue') print element['date'], element['time'] </code></pre>
1
2016-07-22T07:17:28Z
[ "python", "beautifulsoup" ]
Unable to stream data from twitter using tweepy in python
38,520,067
<pre><code>from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener #consumer key, consumer secret, access token, access secret. ckey="" csecret="" atoken="" asecret="" class listener(StreamListener): def on_data(self, data): print(data) return(True) def on_error(self, status): print (status) auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) twitterStream = Stream(auth, listener()) twitterStream.filter(track=["car"]) </code></pre> <p>I have used the consumer keys and access tokens using apps.twitter.com I am trying this code to stream data from twitter but getting error</p> <p><a href="http://i.stack.imgur.com/adskO.jpg" rel="nofollow">Error screenshot in python 3.4 shell </a></p>
-1
2016-07-22T06:57:38Z
38,527,347
<p>Your screenshot shows an SSL <code>VERIFY_CERTIFICATE_FAILED</code> error. Twitter requires that you connect to the streaming API endpoint using TLS.</p>
0
2016-07-22T13:10:59Z
[ "python", "twitter", "tweepy" ]
theano and lambda functions
38,520,143
<p>I am having some strange behaviour when I have a list of lambda functions which evaluate theano expressions. The code is below:</p> <pre><code># Equivalent functions (or at least I assume so) def tilted_loss(q,y,f): e = (y-f) return (q*tt.sum(e)-tt.sum(e[(e&lt;0).nonzero()]))/e.shape[0] def tilted_loss2(y,f): q = 0.05 e = (y-f) return (q*tt.sum(e)-tt.sum(e[(e&lt;0).nonzero()]))/e.shape[0] def tilted_loss_np(q,y,f): e = (y-f) return (q*sum(e)-sum(e[e&lt;0]))/e.shape[0] # lambda functions which uses above functions qs = np.arange(0.05,1,0.05) q_loss_f = [lambda y,f: tilted_loss(q,y,f) for q in qs] q_loss_f2 = lambda y,f:tilted_loss(0.05,y,f) q_loss_f3 = lambda y,f:tilted_loss(qs[0],y,f) # Test the functions np.random.seed(1) a = np.random.randn(1000,1) b = np.random.randn(1000,1) print(q_loss_f[0](a,b).eval()) print(q_loss_f2(a,b).eval()) print(q_loss_f3(a,b).eval()) print(tilted_loss2(a,b).eval()) print(tilted_loss_np(qs[0],a,b)[0]) </code></pre> <p>This gives the output:</p> <pre><code>0.571973847658054 0.5616355181780912 0.5616355181695327 0.5616355181780912 0.56163551817 </code></pre> <ol> <li>I must be doing something wrong with the way that the list of functions <code>q_loss_f</code> is defined. </li> <li>Is the way that q is defined ok? i.e. its a numpy variable that I'm sending in, but this seems to be fine in <code>q_loss_f3</code>.</li> </ol> <p>Any thoughts?</p>
0
2016-07-22T07:01:09Z
38,520,306
<p>Is a common error, the <code>q</code> value in the lambda expresion will just take the last value from the comprehension loop, you better use <a href="https://docs.python.org/2/library/functools.html#functools.partial" rel="nofollow">partial</a>:</p> <pre><code>q_loss_f = [partial(tilted_loss, q=q) for q in qs] </code></pre>
1
2016-07-22T07:11:06Z
[ "python", "lambda", "theano" ]
How exactly does Python resolve "from X import Y" if there are multiple Ys in X?
38,520,210
<p>I have a package X which contains two different things named Y</p> <p>One is a module:</p> <pre><code># X/Y.py print 'hello' </code></pre> <p>The other is a variable:</p> <pre><code># X/__init__.py Y = 'world' </code></pre> <p>If I execute <code>from X import Y</code> which Y do I get and <em>why</em>? What determines the order and shadowing rules for import statements?</p> <p>Lastly, is there anything I might do accidentally that would change the answer?</p> <p>Basically I got a bug report that indicates on a user's machine this code results in the opposite Y importing from what I get on my machine. I don't have access to the user's machine, so I am trying to figure out what happened.</p> <p>I am wondering if there are clues in this previous question: <a href="http://stackoverflow.com/questions/37317153/python-from-x-import-y-changes-previous-import-result">python: from x import y changes previous import result</a></p>
3
2016-07-22T07:05:12Z
38,520,290
<p>A name in the module will take precedence. From <a href="https://docs.python.org/3/tutorial/modules.html#packages" rel="nofollow">the Python tutorial</a>.</p> <blockquote> <p>Note that when using from package import item, the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it.</p> </blockquote> <p>The same information is given in <a href="https://docs.python.org/3/reference/simple_stmts.html#the-import-statement" rel="nofollow">the language reference</a>.</p> <p>However, if any code imports the submodule (by other, more explicit means, such as <code>import X.Y</code>, where <code>Y</code> can only refer to a module), then the submodule will also exist as a name in the package. So in that case it will depend on the order of the code: once you import the module, it will overwrite the variable of the same name.</p>
1
2016-07-22T07:10:34Z
[ "python" ]
How exactly does Python resolve "from X import Y" if there are multiple Ys in X?
38,520,210
<p>I have a package X which contains two different things named Y</p> <p>One is a module:</p> <pre><code># X/Y.py print 'hello' </code></pre> <p>The other is a variable:</p> <pre><code># X/__init__.py Y = 'world' </code></pre> <p>If I execute <code>from X import Y</code> which Y do I get and <em>why</em>? What determines the order and shadowing rules for import statements?</p> <p>Lastly, is there anything I might do accidentally that would change the answer?</p> <p>Basically I got a bug report that indicates on a user's machine this code results in the opposite Y importing from what I get on my machine. I don't have access to the user's machine, so I am trying to figure out what happened.</p> <p>I am wondering if there are clues in this previous question: <a href="http://stackoverflow.com/questions/37317153/python-from-x-import-y-changes-previous-import-result">python: from x import y changes previous import result</a></p>
3
2016-07-22T07:05:12Z
38,520,308
<p>Modules in packages, once imported, are also set as an attribute on the parent module object. The <code>from module import name</code> syntax, however, will <em>first</em> look at the attributes of the imported module object (the globals of <code>X</code>) to resolve <code>name</code>.</p> <p>So, the answer is that it depends. If you have not imported the <code>X.Y</code> module yet, then you'll end up with <code>Y</code> bound to <code>'world'</code>. If you have imported <code>X.Y</code> (with <code>import X.Y</code> or <code>from X.Y import some_name</code>), then <code>Y</code> is bound to the <code>X.Y</code> submodule. The latter is a side-effect of <code>Y</code> in <code>X</code> having been set as a global.</p> <p>Demo:</p> <pre><code>$ mkdir foo $ cat &lt;&lt; EOF &gt; foo/__init__.py &gt; bar = 'from the foo package' &gt; EOF $ cat &lt;&lt; EOF &gt; foo/bar.py &gt; baz = 'from the foo.bar module' &gt; EOF $ bin/python -c 'from foo import bar; print(bar)' from the foo package $ bin/python -c 'import foo.bar; from foo import bar; print(bar); print(bar.baz)' &lt;module 'foo.bar' from 'foo/bar.py'&gt; from the foo.bar module </code></pre>
5
2016-07-22T07:11:10Z
[ "python" ]
How exactly does Python resolve "from X import Y" if there are multiple Ys in X?
38,520,210
<p>I have a package X which contains two different things named Y</p> <p>One is a module:</p> <pre><code># X/Y.py print 'hello' </code></pre> <p>The other is a variable:</p> <pre><code># X/__init__.py Y = 'world' </code></pre> <p>If I execute <code>from X import Y</code> which Y do I get and <em>why</em>? What determines the order and shadowing rules for import statements?</p> <p>Lastly, is there anything I might do accidentally that would change the answer?</p> <p>Basically I got a bug report that indicates on a user's machine this code results in the opposite Y importing from what I get on my machine. I don't have access to the user's machine, so I am trying to figure out what happened.</p> <p>I am wondering if there are clues in this previous question: <a href="http://stackoverflow.com/questions/37317153/python-from-x-import-y-changes-previous-import-result">python: from x import y changes previous import result</a></p>
3
2016-07-22T07:05:12Z
38,520,333
<p>Python looks first on the current working directory for any file Y.py under X folder, then it looks for the installed libraries for X package to import Y file. If there is a Y variable in the package X then it is imported and then replaced by the content on file Y.py of that package</p>
-1
2016-07-22T07:12:34Z
[ "python" ]
KIVY language: multiple commands in a single line
38,520,218
<p>I have to do:</p> <pre><code>TextInput: on_text: something ; something_else </code></pre> <p>How can I perform this without getting errors in kv language?</p>
0
2016-07-22T07:05:27Z
38,520,572
<p>You could just add more <code>on_text</code> bindings, line by line:</p> <pre><code>TextInput: on_text: something on_text: something_else </code></pre> <p>But I'd prefer binding custom function call, because I'm not sure order of execution is always the same with the above example. Something like this:</p> <pre><code>MyTextInput: on_text: self.custom_function() </code></pre> <p>and in python:</p> <pre><code>class MyTextInput(TextInput): def custom_function(self): something() something_else() </code></pre>
1
2016-07-22T07:26:41Z
[ "python", "syntax", "kivy", "kivy-language" ]
How to access a file from python when the OS opens the script to handle opening that file?
38,520,278
<p>When I open an HTML file, for instance, I have it set such that it opens in Chrome. Now if I set a given python script to be the thing that opens a given filetype, how do I access this file in the script? Where is it available from?</p>
-4
2016-07-22T07:10:04Z
38,520,642
<p>When opening a file, the operating system starts the responsible opener program and passes the file(s) to be opened as <a href="https://en.wikipedia.org/wiki/Command-line_interface#Arguments" rel="nofollow">command line arguments</a>:</p> <pre><code>path/to/opener_executable path/to/file1_to_be_opened path/to/file2_to_be_opened ... </code></pre> <p>You can access the command line arguments through <a href="https://docs.python.org/2/library/sys.html#sys.argv" rel="nofollow"><code>sys.argv</code></a> in your python script. A minimal example:</p> <pre><code>import sys print("I'm supposed to open the following file(s):") print('\n'.join(sys.argv[1:])) </code></pre>
0
2016-07-22T07:30:24Z
[ "python", "python-3.x" ]
How to access a file from python when the OS opens the script to handle opening that file?
38,520,278
<p>When I open an HTML file, for instance, I have it set such that it opens in Chrome. Now if I set a given python script to be the thing that opens a given filetype, how do I access this file in the script? Where is it available from?</p>
-4
2016-07-22T07:10:04Z
38,522,140
<p>To prove <code>Rawing</code>'s point, on Linux, you "open with Other Application" and select your python script, which you made executable.<br> <code>sys.argv</code> provides the name of the script as argument 0 and thereafter a list of any other parameters. </p> <p>myopener.py </p> <pre><code>#!/usr/bin/env python import sys, os x=os.open('/home/rolf/myopener.output',os.O_RDWR|os.O_CREAT) xx = os.fdopen(x,'w+') y=str(sys.argv) xx.write(y) xx.close() </code></pre> <p>Opening the file abc.ddd with <code>myopener.py</code> creates the file <code>myopener.output</code> contents: </p> <pre><code>['/home/rolf/myopener.py', '/home/rolf/abc.ddd'] </code></pre>
0
2016-07-22T08:51:02Z
[ "python", "python-3.x" ]
Why does my scrapy not scrape anything?
38,520,312
<p>I don't know where the issues lies probably super easy to fix since I am new to scrapy. I hope to find a solution. Thanks in advance.</p> <p>I am using utnutu 14.04, python 3.4</p> <p>My Spider:</p> <pre><code>import scrapy from scrapy.linkextractors import LinkExtractor from name.items import Actress class ActressSpider(scrapy.Spider): name = "name_list" allowed_domains = ["dmm.co.jp"] start_urls = ["http://actress.dmm.co.jp/-/list/=/keyword=%s/" % c for c in ['a', 'i', 'u', 'e', 'o', 'ka', 'ki', 'ku', 'ke', 'ko', 'sa', 'si', 'su', 'se', 'so', 'ta', 'ti', 'tu', 'te', 'to', 'na', 'ni', 'nu', 'ne', 'no', 'ha', 'hi', 'hu', 'he', 'ho', 'ma', 'mi', 'mu', 'me', 'mo', 'ya', 'yu', 'yo', 'ra', 'ri', 'ru', 're', 'ro', 'wa']] def parse(self, response): for sel in response.xpath('//*[@id="mu"]/table[2]/tr/td[2]/a/@href'): url = response.urljoin(sel.extract()) yield scrapy.Request(url, callback = self.parse_actress_detail) next_page = response.xpath('//*[@id="mu"]/table[1]/tr[2]/td[2]/a/@href') for urlnext in next_page: if urlnext: pagination = response.urljoin(urlnext.extract()) yield scrapy.Request(pagination, callback = self.parse) def parse_actress_detail(self, response): for sel in response.xpath('//*[@id="mu"]/table[1]'): item = Actress() url = resposne.url name = sel.xpath('tr[3]/td/table/tr/td[1]/img/@alt').extract() item['name'] = name[0].encode('utf-8') item['name_en'] = sel.xpath('tr[3]/td/table/tr/td[1]/img/@src').extract() birth = sel.xpath('tr[3]/td/table/tr/td[2]/table/tr[1]/td[2]/text()').extract() item['birth'] = birth[0].encode('utf-8') starsign = sel.xpath('tr[3]/td/table/tr/td[2]/table/tr[2]/td[2]/text()').extract() item['starsign'] = starsign[0].encode('utf-8') bloodtype = sel.xpath('tr[3]/td/table/tr/td[2]/table/tr[3]/td[2]/text()').extract() item['bloodtype'] = bloodtype[0].encode('utf-8') boobs = sel.xpath('tr[3]/td/table/tr/td[2]/table/tr[4]/td[2]/text()').extract() item['boobs'] = boobs[0].encode('utf-8') home = sel.xpath('tr[3]/td/table/tr/td[2]/table/tr[5]/td[2]/text()').extract() item['home'] = home[0].encode('utf-8') hobby = sel.xpath('tr[3]/td/table/tr/td[2]/table/tr[6]/td[2]/text()').extract() item['hobby'] = hobby[0].encode('utf-8') item['image_urls'] = sel.xpath('tr[3]/td/table/tr/td[1]/img/@src').extract() request = scrapy.Request(url, callback=self.parse_actress_detail2, meta={'item':item}) yield request # another link section of parse's request url def parse_actress_detail2(self, response): for sel in response.xpath('//*[@id="mu"]/table[4]/tr/td[1]/a/@href'): url = response.urljoin(sel.extract()) request = scrapy.Request(url, callback = self.parse_movie_detail, meta={'item':item}) yield request next_page = response.xpath('//*[@id="mu"]/table[5]/tr/td/a/@href') for urlnext in next_page: if urlnext: pagination = response.urljoin(urlnext.extract()) yield scrapy.Request(pagination, callback = self.parse_actress_detail2) def parse_movie_detail(self, response): for sel in response.xpath('//*[@id="content"]/tr[1]/td[1]'): item = response.meta['item'] release_date = sel.xpath('table/tr[1]/td[2]/text()').extract() item['release_date'] = release_date[0].encode('utf-8') running_time = sel.xpath('table/tr[2]/td[2]/text()').extract() item['running_time'] = running_time[0].encode('utf-8') cast = sel.xpath('table/tr[3]/td[2]/a/text()').extract() castjoin = [n.encode('utf-8') for n in cast] item['cast'] = b', '.join(castjoin) series = sel.xpath('table/tr[4]/td[2]/text()').extract() item['series'] = series[0].encode('utf-8') manufacturer = sel.xpath('table/tr[5]/td[2]/text()').extract() item['manufacturer'] = manufacturer[0].encode('utf-8') label = sel.xpath('table/tr[6]/td[2]/text()').extract() item['label'] = label[0].encode('utf-8') number = sel.xpath('//*[@id="cid_block"]/text()').extract() item['number'] = number[0].encode('utf-8') yield item </code></pre> <p>log:</p> <pre><code>'downloader/request_bytes': 4350197, 'downloader/request_count': 10107, 'downloader/request_method_count/GET': 10107, 'downloader/response_bytes': 169329414, 'downloader/response_count': 10107, 'downloader/response_status_count/200': 9905, 'downloader/response_status_count/301': 202, 'dupefilter/filtered': 3212, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2016, 7, 22, 5, 41, 0, 920779), 'log_count/DEBUG': 203, 'log_count/INFO': 13, 'request_depth_max': 5, 'response_received_count': 9905, 'scheduler/dequeued': 10107, 'scheduler/dequeued/memory': 10107, 'scheduler/enqueued': 10107, 'scheduler/enqueued/memory': 10107, 'spider_exceptions/NameError': 9659, 'start_time': datetime.datetime(2016, 7, 22, 5, 28, 25, 342801) </code></pre> <p>Any help is greatly appreciated.</p>
1
2016-07-22T07:11:18Z
38,521,877
<p>In your stats, <code>'spider_exceptions/NameError': 9659,</code> looks suspicious.</p> <p>I believe the problem is in your <code>parse_actress_detail2</code> callback. In the first loop, <code>item</code> is not defined:</p> <pre><code>def parse_actress_detail2(self, response): for sel in response.xpath('//*[@id="mu"]/table[4]/tr/td[1]/a/@href'): url = response.urljoin(sel.extract()) request = scrapy.Request(url, callback = self.parse_movie_detail, meta={'item':item}) # ^ # | # here yield request </code></pre> <p>You probably meant <code>meta={'item': response.meta['item']}</code> like you do in <code>parse_movie_detail</code>.</p>
1
2016-07-22T08:39:07Z
[ "python", "scrapy" ]
Python lxml: insert text at given position relatively to subelements
38,520,331
<p>I'd like to build the following XML element (in order to customize figure number formatting):</p> <pre><code>&lt;figcaption&gt; &lt;span class="fignum"&gt;Figura 1.2&lt;/span&gt; - Description of figure. &lt;/figcaption&gt; </code></pre> <p>but I don't know how to specify position of text. In fact, if I create the subelement before creating text,</p> <pre><code>import lxml.etree as et fc = et.Element("figcaption") fn = et.SubElement(fc, "span", {'class':'fignum'}) fn.text = "Figure 1.2" fc.text = " - Description of figure." </code></pre> <p>I get an undesired result (text is positioned before subelement):</p> <pre><code>&lt;figcaption&gt; - Description of figure.&lt;span class="fignum"&gt;Figure 1.2&lt;/span&gt; &lt;/figcaption&gt; </code></pre> <p>How can I specify position of text relatively to subelements?</p>
1
2016-07-22T07:12:27Z
38,520,471
<p>You need to use the <code>tail</code> property of the <code>span</code> element:</p> <pre><code>from lxml import etree as et fc = et.Element("figcaption") fn = et.SubElement(fc, "span", {'class':'fignum'}) fn.text = "Figure 1.2" fn.tail = " - Description of figure." print(et.tostring(fc)) </code></pre> <blockquote> <pre><code>b'&lt;figcaption&gt;&lt;span class="fignum"&gt;Figure 1.2&lt;/span&gt; - Description of figure.&lt;/figcaption&gt;' </code></pre> </blockquote> <p>with ElementTree, elements have a <code>text</code> inside the element, and a <code>tail</code> after and outside the element.</p> <p>With multiple children, the <code>text</code> of the parent is the text before the first child, all the other text inside the element will be assigned to the childrens' <code>tail</code>.</p> <p>Some examples from another answer to this question which has since been deleted:</p> <pre><code>&lt;elem&gt;.text of elem&lt;/elem&gt;.tail of elem &lt;elem&gt;.text of elem&lt;child1/&gt;&lt;child2/&gt;&lt;/elem&gt;.tail of elem &lt;elem&gt;.text of elem&lt;child1/&gt;.tail of child1&lt;child2/&gt;.tail of child2&lt;/elem&gt;.tail of elem &lt;elem&gt;.text of elem&lt;child1&gt;.text of child1&lt;/child1&gt;.tail of child1&lt;child2/&gt;.tail of child2&lt;/elem&gt;.tail of elem </code></pre>
3
2016-07-22T07:20:48Z
[ "python", "xml", "lxml" ]
How to overlap wxStaticBitmap images in wxGridBagSizer using wxFormBuilder in wxPython
38,520,337
<p>I need to create an OR Gate by using 4 images(3 lines and Gate symbol). This requires overlapping of images placed in cells in wxGridBagSizer. How can I achieve that?</p> <p><a href="http://i.stack.imgur.com/eQNv9.png" rel="nofollow">Attempt using wxFormBuilder</a></p> <p>I am trying to set negative vgap and hgap using wxFormBuilder to overlap the images but wxFormBuilder is not accepting negative values.</p> <p>Then I tried to write raw code to achieve the same:</p> <pre><code> self.widgetSizer = wx.GridBagSizer(hgap=-6,vgap=-20) self.orGateImage = wx.StaticBitmap(self, -1, self.orGateImageBitmap, style=wx.BITMAP_TYPE_PNG) self.LineImageOffA = wx.StaticBitmap(self, -1, self.LineImageOffBitmap, style=wx.BITMAP_TYPE_PNG) self.LineImageOffB = wx.StaticBitmap(self, -1, self.LineImageOffBitmap, style=wx.BITMAP_TYPE_PNG) self.LineImageOffX = wx.StaticBitmap(self, -1, self.LineImageOffBitmap, style=wx.BITMAP_TYPE_PNG) self.LetterAImage = wx.StaticBitmap(self, -1, self.LetterAImageBitmap, style=wx.BITMAP_TYPE_PNG) self.LetterBImage = wx.StaticBitmap(self, -1, self.LetterBImageBitmap, style=wx.BITMAP_TYPE_PNG) self.LetterXImage = wx.StaticBitmap(self, -1, self.LetterXImageBitmap, style=wx.BITMAP_TYPE_PNG) self.widgetSizer.Add(self.LineImageOffA, pos=(0,1), border=10) self.widgetSizer.Add(self.LineImageOffB, pos=(2,1), border=2) self.widgetSizer.Add(self.LineImageOffX, pos=(1,3), flag=wx.ALIGN_CENTER,border=2) self.widgetSizer.Add(self.orGateImage, pos=(1,2), border=10) self.widgetSizer.Add(self.LetterAImage, pos=(0,0), border=10) self.widgetSizer.Add(self.LetterBImage, pos=(2,0), border=10) self.widgetSizer.Add(self.LetterXImage, pos=(1,4), flag=wx.ALIGN_CENTER, border=10) self.frame.fSizer.Layout() </code></pre> <p>And it worked. I could get the following output:</p> <p><a href="http://i.stack.imgur.com/szuQ6.png" rel="nofollow">Attempt using raw code</a></p> <p>Please help me achieve this using wxFormBuilder as I need to create such elements quickly in my project. Is there any other alternative to get this done?</p> <p>The code generated by wxFormBuilder is as follows:</p> <pre><code>MyFrame1::MyFrame1( wxWindow* parent, wxWindowID id, const wxString&amp; title, const wxPoint&amp; pos, const wxSize&amp; size, long style ) : wxFrame( parent, id, title, pos, size, style ) { this-&gt;SetSizeHints( wxDefaultSize, wxDefaultSize ); wxBoxSizer* bSizer1; bSizer1 = new wxBoxSizer( wxVERTICAL ); wxGridBagSizer* gbSizer1; gbSizer1 = new wxGridBagSizer( 0, 0 ); gbSizer1-&gt;SetFlexibleDirection( wxBOTH ); gbSizer1-&gt;SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED ); m_bitmap1 = new wxStaticBitmap( this, wxID_ANY, wxBitmap( wxT("../../home/ece/Desktop/scripts/fromPI/GREEN_LINE_OFF_SMALL.png"), wxBITMAP_TYPE_ANY ), wxDefaultPosition, wxSize( 85,5 ), 0 ); gbSizer1-&gt;Add( m_bitmap1, wxGBPosition( 0, 0 ), wxGBSpan( 1, 1 ), wxALL, 5 ); m_bitmap2 = new wxStaticBitmap( this, wxID_ANY, wxBitmap( wxT("../../home/ece/Desktop/scripts/fromPI/GREEN_LINE_OFF_SMALL.png"), wxBITMAP_TYPE_ANY ), wxDefaultPosition, wxSize( 85,5 ), 0 ); gbSizer1-&gt;Add( m_bitmap2, wxGBPosition( 2, 0 ), wxGBSpan( 1, 1 ), wxALL, 5 ); m_bitmap3 = new wxStaticBitmap( this, wxID_ANY, wxBitmap( wxT("../../home/ece/Desktop/scripts/fromPI/OR_GATE_SMALL.png"), wxBITMAP_TYPE_ANY ), wxDefaultPosition, wxDefaultSize, 0 ); gbSizer1-&gt;Add( m_bitmap3, wxGBPosition( 1, 2 ), wxGBSpan( 1, 1 ), wxALL, 5 ); m_bitmap4 = new wxStaticBitmap( this, wxID_ANY, wxBitmap( wxT("../../home/ece/Desktop/scripts/fromPI/GREEN_LINE_OFF_SMALL.png"), wxBITMAP_TYPE_ANY ), wxDefaultPosition, wxSize( 85,5 ), 0 ); gbSizer1-&gt;Add( m_bitmap4, wxGBPosition( 1, 3 ), wxGBSpan( 1, 1 ), wxALIGN_CENTER|wxALL, 5 ); bSizer1-&gt;Add( gbSizer1, 1, wxEXPAND, 5 ); this-&gt;SetSizer( bSizer1 ); this-&gt;Layout(); } MyFrame1::~MyFrame1() { } </code></pre>
0
2016-07-22T07:12:57Z
38,574,382
<p>wxWidgets does not support overlapping sibling widgets (your <code>wx.StaticBitmaps</code> in this case,) and the behavior of what happens when you try to do so is undefined. In addition, sizers are not designed to be able to overlap items, that goes against their fundamental purpose IMO.</p> <p>However, you can easily draw the bitmaps yourself without using a widget for each one, and have them overlap as much or as little as you need. To do this you can handle the <code>EVT_PAINT</code> method in a class based on <code>wx.Window</code> or <code>wx.Panel</code> and draw the bitmaps in that paint handler, and then put an instance of that window in your frame. There are lots of examples of drawing in a paint handler in the demo and various tutorials.</p>
1
2016-07-25T17:51:24Z
[ "python", "wxpython", "wxwidgets" ]
Converting from long to wide in python
38,520,482
<p>I think this a pretty simple question. I am new to python and I am unable to find the perfect answer. </p> <p>I have a dataframe :</p> <pre><code>A B C D E 203704 WkDay 00:00 0.247 2015 203704 WkDay 00:30 0.232 2015 203704 Wkend 00:00 0.102 2015 203704 Wkend 00:30 0.0907 2015 203704 WkDay 00:00 0.28 2016 203704 WkDay 00:30 0.267 2016 203704 Wkend 00:00 0.263 2016 203704 Wkend 00:30 0.252 2016 </code></pre> <p>I need :</p> <pre><code>A B 00:00 00:30 E 203704 Wkday 0.247 0.232 2015 203704 Wkend 0.102 0.0907 2015 203704 Wkday 0.28 0.267 2016 203704 Wkday 0.263 0.252 2016 </code></pre> <p>I have gone through various links like <a href="http://stackoverflow.com/questions/18969034/parsing-data-from-long-to-wide-format-in-python">this</a> and <a href="http://stackoverflow.com/questions/22798934/pandas-long-to-wide-reshape">this</a>. However, implementing them I am getting various errors. </p> <p>I was able to run this successfully</p> <pre><code>pandas.pivot_table(df,values='D',index='A',columns='C') </code></pre> <p>but it does not give what exactly I want. </p> <p>Any help on this would be helpful. </p>
3
2016-07-22T07:21:18Z
38,520,560
<p>You can add multiple columns to list as argument of parameter <code>index</code>:</p> <pre><code>print (pd.pivot_table(df,index=['A', 'B', 'E'], columns='C',values='D').reset_index()) C A B E 00:00 00:30 0 203704 WkDay 2015 0.247 0.2320 1 203704 WkDay 2016 0.280 0.2670 2 203704 Wkend 2015 0.102 0.0907 3 203704 Wkend 2016 0.263 0.2520 </code></pre> <p>If need change order of columns:</p> <pre><code>#reset only last level of index df1 = pd.pivot_table(df,index=['A', 'B', 'E'], columns='C',values='D').reset_index(level=-1) #reorder first column to last df1.columns = df1.columns[-1:] | df1.columns[:-1] #reset other columns print (df1.reset_index()) C A B 00:00 00:30 E 0 203704 WkDay 2015 0.247 0.2320 1 203704 WkDay 2016 0.280 0.2670 2 203704 Wkend 2015 0.102 0.0907 3 203704 Wkend 2016 0.263 0.2520 </code></pre>
3
2016-07-22T07:26:13Z
[ "python", "pandas" ]
Converting from long to wide in python
38,520,482
<p>I think this a pretty simple question. I am new to python and I am unable to find the perfect answer. </p> <p>I have a dataframe :</p> <pre><code>A B C D E 203704 WkDay 00:00 0.247 2015 203704 WkDay 00:30 0.232 2015 203704 Wkend 00:00 0.102 2015 203704 Wkend 00:30 0.0907 2015 203704 WkDay 00:00 0.28 2016 203704 WkDay 00:30 0.267 2016 203704 Wkend 00:00 0.263 2016 203704 Wkend 00:30 0.252 2016 </code></pre> <p>I need :</p> <pre><code>A B 00:00 00:30 E 203704 Wkday 0.247 0.232 2015 203704 Wkend 0.102 0.0907 2015 203704 Wkday 0.28 0.267 2016 203704 Wkday 0.263 0.252 2016 </code></pre> <p>I have gone through various links like <a href="http://stackoverflow.com/questions/18969034/parsing-data-from-long-to-wide-format-in-python">this</a> and <a href="http://stackoverflow.com/questions/22798934/pandas-long-to-wide-reshape">this</a>. However, implementing them I am getting various errors. </p> <p>I was able to run this successfully</p> <pre><code>pandas.pivot_table(df,values='D',index='A',columns='C') </code></pre> <p>but it does not give what exactly I want. </p> <p>Any help on this would be helpful. </p>
3
2016-07-22T07:21:18Z
38,520,711
<p>Use <code>set_index</code> and <code>unstack</code></p> <pre><code>df.set_index(['A', 'B', 'E', 'C']).D.unstack().reset_index() </code></pre> <p><a href="http://i.stack.imgur.com/5ro4d.png" rel="nofollow"><img src="http://i.stack.imgur.com/5ro4d.png" alt="enter image description here"></a></p> <p>If you insist on the exact format</p> <pre><code>df.set_index(['A', 'B', 'E', 'C']) \ .D.unstack().reset_index() \ .rename_axis(None, 1).iloc[:, [0, 1, 3, 4, 2]] </code></pre> <p><a href="http://i.stack.imgur.com/OrU8Q.png" rel="nofollow"><img src="http://i.stack.imgur.com/OrU8Q.png" alt="enter image description here"></a></p>
2
2016-07-22T07:33:45Z
[ "python", "pandas" ]
how to detect spaces, special characters in html tags in python
38,520,570
<p>For the following input</p> <pre><code>I/O 1&lt; img &gt; '&lt; input &gt; I/O 1&lt;' img &gt; '&lt; input &gt; </code></pre> <p>I want the required output as below and this should happen if <code>&lt;</code> followed by space is present.</p> <pre><code>I/O 1&lt;img&gt;'&lt;input&gt; </code></pre> <p>Can anyone help me with regular expression?</p>
-4
2016-07-22T07:26:39Z
38,520,651
<p>Try <code>&lt;\s+</code>, <code>\s+&gt;</code>, and <code>&gt;\s+</code>:</p> <pre><code>import re s = "I/O 1&lt; img &gt; '&lt; input &gt;" s = re.sub(r"&lt;\s+", "&lt;", s) s = re.sub(r"\s+&gt;", "&gt;", s) s = re.sub(r"&gt;\s+", "&gt;", s) print(s) </code></pre> <p>Output:</p> <pre><code>I/O 1&lt;img&gt;'&lt;input&gt; </code></pre>
2
2016-07-22T07:31:06Z
[ "python", "html", "regex" ]
how to detect spaces, special characters in html tags in python
38,520,570
<p>For the following input</p> <pre><code>I/O 1&lt; img &gt; '&lt; input &gt; I/O 1&lt;' img &gt; '&lt; input &gt; </code></pre> <p>I want the required output as below and this should happen if <code>&lt;</code> followed by space is present.</p> <pre><code>I/O 1&lt;img&gt;'&lt;input&gt; </code></pre> <p>Can anyone help me with regular expression?</p>
-4
2016-07-22T07:26:39Z
38,561,914
<pre><code>s= "I/O 1&lt; img &gt; '&lt; input &gt;" </code></pre> <p>Find the starting of the html tag using s.find('&lt;') </p> <p>s[0 : s.find('&lt;')] will select the substring from 0 to an index before the start of the html tag</p> <p>s[s.find('&lt;'):] will select the substring beginning from start of the html tag till the end.</p> <p>s.replace(' ','') will replace spaces with no_spaces</p> <pre><code>( s[0:s.find('&lt;')] ) + ( s[s.find('&lt;'):].replace(' ','') ) </code></pre>
0
2016-07-25T07:26:58Z
[ "python", "html", "regex" ]
Redraw a matplotlib figure with new rc params
38,520,641
<p>is there a conventient way to update an already existing matplotlib figure with new rcParams? Background is that i want to export figures with different properties (e.g. line-width, fonts ..). Is there something like a 'redraw()' option? Thank you!</p>
0
2016-07-22T07:30:17Z
38,530,792
<p>use <code>fig.canvas.draw()</code></p> <p>See <a href="http://stackoverflow.com/questions/4098131/how-to-update-a-plot-in-matplotlib">How to update a plot in matplotlib?</a> or <a href="http://stackoverflow.com/questions/20936817/how-do-i-redraw-an-image-using-pythons-matplotlib">how do I redraw an image using python&#39;s matplotlib?</a></p> <p>In a jupyter notebook:</p> <pre><code>%matplotlib inline import matplotlib.pyplot as plt import matplotlib as mpl mpl.rcParams['figure.figsize']=(5,5) mpl.rcParams['font.size']=50 fig = plt.figure() x = [1,2,3] y = [3,4,5] plt.plot(x,y,label='data') plt.legend() plt.show() mpl.rcParams['font.size']=5 fig.canvas.draw() fig.savefig('saved.png') from IPython.display import Image Image('saved.png') </code></pre> <p><a href="http://i.stack.imgur.com/gouDj.png" rel="nofollow"><img src="http://i.stack.imgur.com/gouDj.png" alt="enter image description here"></a></p>
0
2016-07-22T15:56:28Z
[ "python", "matplotlib" ]
Why does my code not return anything
38,520,662
<p>fairly new to programming and trying to learn Python at the moment. I have this code and I don't understand why I don't get a return value :(</p> <pre><code>balance = 3200 annualInterestRate = 0.2 monthlyInterestRate = (annualInterestRate/12 + 1) def f(x): m = 0 ba = balance while m &lt; 12: ba = (ba - x)*monthlyInterestRate m += 1 return ba def bisection(): a = 0 b = balance c = (a+b)/2 while a != b: if f(c) == 0: return c elif f(c) &lt; 0: a = c else: b = c c = (a+b)/2 return c bisection() </code></pre>
-6
2016-07-22T07:31:39Z
38,520,730
<p>You have to explicitly use the <code>return</code> keyword. Probably where you currently have <code>print c</code>.</p> <p><code>f</code> needs to return <code>ba</code> after the while loop.</p>
1
2016-07-22T07:34:52Z
[ "python", "return" ]
Why does my code not return anything
38,520,662
<p>fairly new to programming and trying to learn Python at the moment. I have this code and I don't understand why I don't get a return value :(</p> <pre><code>balance = 3200 annualInterestRate = 0.2 monthlyInterestRate = (annualInterestRate/12 + 1) def f(x): m = 0 ba = balance while m &lt; 12: ba = (ba - x)*monthlyInterestRate m += 1 return ba def bisection(): a = 0 b = balance c = (a+b)/2 while a != b: if f(c) == 0: return c elif f(c) &lt; 0: a = c else: b = c c = (a+b)/2 return c bisection() </code></pre>
-6
2016-07-22T07:31:39Z
38,520,815
<p>You're being unclear about what function you expect to return a value, but as I cannot comment and prod yet I'll provide a possible answer.</p> <p>First of all, in this code you never actually call any of the functions. I'm assuming this is done elsewhere.</p> <p>As for <code>f(x)</code>, there's no <code>return value</code> because you have not made a <code>Return</code> statement. I would also refrain from using variables as Globals, it's typically bad practice. Instead, if you want to modify <code>MonthlyInterestRate</code> send it as a parameter to <code>f()</code> and return the new value.</p> <p><code>bisection</code> only returns if <code>f(c) == 0</code> but <code>f()</code> does not have a <code>Return</code> statement, so that will never happen. Past that, once it exits the loop it will only print c so no return value there either.</p> <p>If you want to compare a function, it NEEDS a <code>Return</code>statement.</p>
0
2016-07-22T07:39:31Z
[ "python", "return" ]
Why does my code not return anything
38,520,662
<p>fairly new to programming and trying to learn Python at the moment. I have this code and I don't understand why I don't get a return value :(</p> <pre><code>balance = 3200 annualInterestRate = 0.2 monthlyInterestRate = (annualInterestRate/12 + 1) def f(x): m = 0 ba = balance while m &lt; 12: ba = (ba - x)*monthlyInterestRate m += 1 return ba def bisection(): a = 0 b = balance c = (a+b)/2 while a != b: if f(c) == 0: return c elif f(c) &lt; 0: a = c else: b = c c = (a+b)/2 return c bisection() </code></pre>
-6
2016-07-22T07:31:39Z
38,520,861
<p>First you should add <code>return ba</code> to function <code>f</code> to make <code>f</code> return someting:</p> <pre><code>def f(x): m = 0 ba = balance while m &lt; 12: ba = (ba - x)*monthlyInterestRate m += 1 retrun ba </code></pre> <p>Then, add <code>bisection()</code> at the last of your script file to call it:</p> <pre><code>bisection() </code></pre>
0
2016-07-22T07:41:46Z
[ "python", "return" ]
Why does my code not return anything
38,520,662
<p>fairly new to programming and trying to learn Python at the moment. I have this code and I don't understand why I don't get a return value :(</p> <pre><code>balance = 3200 annualInterestRate = 0.2 monthlyInterestRate = (annualInterestRate/12 + 1) def f(x): m = 0 ba = balance while m &lt; 12: ba = (ba - x)*monthlyInterestRate m += 1 return ba def bisection(): a = 0 b = balance c = (a+b)/2 while a != b: if f(c) == 0: return c elif f(c) &lt; 0: a = c else: b = c c = (a+b)/2 return c bisection() </code></pre>
-6
2016-07-22T07:31:39Z
38,520,940
<p>First of all, in your function <code>f</code> you don't have the return statement that you need if you want to check the equality with 0.</p> <p>After add the return statement in the <code>f</code> function you have to write the body of your program because you just have two functions but you don't call them to get a result value...</p> <p>I understand that your program has to use the <code>bisection function</code> writing </p> <pre><code>bisection() </code></pre>
0
2016-07-22T07:44:58Z
[ "python", "return" ]
Why does my code not return anything
38,520,662
<p>fairly new to programming and trying to learn Python at the moment. I have this code and I don't understand why I don't get a return value :(</p> <pre><code>balance = 3200 annualInterestRate = 0.2 monthlyInterestRate = (annualInterestRate/12 + 1) def f(x): m = 0 ba = balance while m &lt; 12: ba = (ba - x)*monthlyInterestRate m += 1 return ba def bisection(): a = 0 b = balance c = (a+b)/2 while a != b: if f(c) == 0: return c elif f(c) &lt; 0: a = c else: b = c c = (a+b)/2 return c bisection() </code></pre>
-6
2016-07-22T07:31:39Z
38,521,069
<p>Two reasons. One, your function f(x) does not have an explicit return statement. If a function doesn't contain an explicit return it will have an implicit one, that is "None" (None is a python object). Second, the only place where f(x) is called is in bisection() which itself is never being called. So, since none of your functions are ever called, your code isn't going to return anything. Try calling bisection() after defining it</p>
0
2016-07-22T07:52:25Z
[ "python", "return" ]
Want to update document in reThinkDB using setInsert Python
38,520,752
<pre><code> r.db('usersData').table('smsRaw').get("3413b71c-1628-47eb-83fa-6a3cccdb3e62").update({"MESSAGE": r.row('MESSAGE').setInsert({"DATE":"20160111","MESSAGE":[{"ADDR":"LONDON","date":"1468385398746"}]})}) </code></pre> <p>This is what i am able to run on console.I want to convert it to python code.</p> <p>Below is python code i tried r.db(dbName).table(tableName).get(id).update({'MESSAGE':r.row.get_field('MESSAGE').setInsert(Doc)}).run(con)</p> <p>its throwing exception. AttributeError 'GetField' object has no attribute 'setInsert</p>
-1
2016-07-22T07:36:16Z
38,521,756
<p>You probably want <code>setInsert</code> to be <code>set_insert</code>.</p>
0
2016-07-22T08:32:19Z
[ "python", "rethinkdb", "rethinkdb-python" ]
Read a list from txt file in Python
38,520,884
<p>I need to read a list from a txt file and import as a list variable into my .py file. I could use the import function, but the program must be compiled and when it's compiled to an exe, all the imports ends converted into a non-modificable files, so the solution is to read from a txt. The code that I use is similar to this</p> <p>First, I got my list in a txt file like this:</p> <pre><code>[['preset1','a1','b1'],['preset2','a2','b2'],['preset3','a3','b3'],['preset4','a4','b4']] </code></pre> <p>Then, I read the list in python:</p> <pre><code>file = open('presets.txt','r') content = file.readline() newpresets = content.split("'") file.close() </code></pre> <p>And I supposed that with the split function to delete the ' symbols, the program take the content as a list and not as a string but this not works... So, I need how to read the content of the file and not interpretate as a string.</p> <p>Anyone could help me?</p> <p>Thanks</p>
0
2016-07-22T07:42:48Z
38,521,224
<p>try to use <code>ast.literal_eval</code> :</p> <pre><code>&gt;&gt;&gt; a = str([['preset1','a1','b1'],['preset2','a2','b2'],['preset3','a3','b3'],['preset4','a4','b4']]) &gt;&gt;&gt; a "[['preset1', 'a1', 'b1'], ['preset2', 'a2', 'b2'], ['preset3', 'a3', 'b3'], ['preset4', 'a4', 'b4']]" &gt;&gt;&gt; import ast &gt;&gt;&gt; ast.literal_eval(a) [['preset1', 'a1', 'b1'], ['preset2', 'a2', 'b2'], ['preset3', 'a3', 'b3'], ['preset4', 'a4', 'b4']] &gt;&gt;&gt; </code></pre>
2
2016-07-22T08:01:19Z
[ "python", "list", "file" ]
Python "TypeError: can only concatenate tuple (not "int") to tuple"
38,520,887
<p>I wrote a piece python code like this</p> <pre><code>import random val_hist = [] for i in range(100): val_hist.append(random.randint(0,1000)) def print__(x): print type(x[1]) map(lambda x: print__(x), list(enumerate(val_hist))) l_tmp = list(enumerate(val_hist)) idx_list = map(lambda x: x[0], l_tmp) val_list = map(lambda x: x[1], l_tmp) print idx_list print val_list reduce(lambda sum, x: sum + x[1], list(enumerate(val_hist))) print reduce(lambda sum, x: sum + x, val_hist) print reduce(lambda sum, x: sum + x[1], list(enumerate(val_hist))) </code></pre> <p>When I ran this code, I got this error "TypeError: can only concatenate tuple (not "int") to tuple". Does anyone know how this happened? Or does anyone know how python function reduce works exactly?</p>
1
2016-07-22T07:43:00Z
38,521,174
<p>You need to provide a third argument to reduce, which is the <code>initializer</code>. From the <a href="https://docs.python.org/2/library/functions.html#reduce" rel="nofollow">docs</a>:</p> <blockquote> <p>If initializer is not given and iterable contains only one item, the first item is returned.</p> </blockquote> <p>Since you aren't explicitly providing an <code>initializer</code> parameter, <code>reduce</code> is using the first element from <code>list(enumerate(val_hist))</code>, which happens to be a tuple. You're trying to add this tuple together with <code>x[1]</code> which is an integer.</p> <p>So, simply update your <code>reduce</code> with an <code>initializer</code> value of 0, like so:</p> <pre><code>&gt;&gt;&gt; reduce(lambda sum, x: sum + x[1], list(enumerate(val_hist)), 0) &gt;&gt;&gt; 48279 </code></pre>
2
2016-07-22T07:58:21Z
[ "python", "lambda" ]
How to take arbitrary number of parentheses from user for add function
38,520,900
<pre><code>add(5)(10)(20) </code></pre> <p>How can I to supply an arbitrary number of parentheses to add numbers?</p>
-4
2016-07-22T07:43:20Z
38,521,034
<p>It's impossible, or at least it <em>should</em> be if the language you're using is worth anything. You're asking for a function to return two different types, which is inviting a a disaster.</p> <ol> <li>sometimes it should return a function that takes the next number to add</li> <li>other times it should return the sum of the previous inputs.</li> </ol> <p>What? Take a step back and ask yourself what kind of design that is. You would need need some way to notify the function that you're done giving inputs and now you want the computed value.</p> <p>Think about it, the function might look like this </p> <pre><code>def add (sum): print(sum) return lambda x: add(sum + x) add(1)(3)(4)(5)(10)(20) # 1 # 4 # 8 # 13 # 23 # 43 # =&gt; None </code></pre> <p>But there's no way to let the function know to return a final value unless you change the api somehow.</p> <hr> <p>You could change the api to return the computed value when the users enters a <code>0</code> or something. Great idea right? Very clever.</p> <pre><code>def add (x): def loop(sum, x): if x == 0: return sum else: return lambda x: loop(sum + x, x) return loop(0, x) print(add(1)(3)(4)(5)(10)(20)(0)) # 42 </code></pre> <p>Hey look, it works where @Rawling's clever code fails. All without adding a bunch of tricks to a class</p> <pre><code>print(add(5)(10)(20)(0) + add(5)(10)(20)(0)) # 70 </code></pre> <hr> <p>But still, this is garbage code. No well-designed function should ever behave like this.</p> <p>Or if your content with being insane, create a class like @Rawing's answer suggests. </p>
2
2016-07-22T07:50:04Z
[ "python" ]
How to take arbitrary number of parentheses from user for add function
38,520,900
<pre><code>add(5)(10)(20) </code></pre> <p>How can I to supply an arbitrary number of parentheses to add numbers?</p>
-4
2016-07-22T07:43:20Z
38,521,068
<p>You could create a class like so:</p> <pre><code>class add(object): def __init__(self, value): self.value= value def __call__(self, value): self.value+= value return self def __repr__(self): return str(self.value) print add(5)(10)(20) # output: 35 </code></pre>
3
2016-07-22T07:52:23Z
[ "python" ]
How to take arbitrary number of parentheses from user for add function
38,520,900
<pre><code>add(5)(10)(20) </code></pre> <p>How can I to supply an arbitrary number of parentheses to add numbers?</p>
-4
2016-07-22T07:43:20Z
38,521,276
<p>What you could do is this:</p> <pre><code>class add(object): def __init__(self, val): self.val= val def __call__(self, val=None): if not val: return self.val self.val += val return self add(5)(10)() &gt;&gt;&gt; 15 </code></pre>
-1
2016-07-22T08:04:20Z
[ "python" ]
Supervisord configuration for Django rq not working
38,520,957
<p>I am following : <a href="http://python-rq.org/patterns/supervisor/" rel="nofollow">Putting RQ under supervisor</a></p> <p>My job:</p> <pre><code>@job("default") def send_mail(subject, body, sender, receivers, cc=None, bcc=None, content_type='plain', class_name=None): """Send email to users.""" *code to send mail.* </code></pre> <p>When I run </p> <blockquote> <p>python manage.py rqworker</p> </blockquote> <p>I am able to perform tasks using rq queues. But not with supervisord configuration. Supervisord configuration:</p> <p>path: /etc/supervisord/conf.d/filename.conf</p> <pre><code>[program:myworker] ; Point the command to the specific rq command you want to run. ; If you use virtualenv, be sure to point it to ; /path/to/virtualenv/bin/rq ; Also, you probably want to include a settings module to configure this ; worker. For more info on that, see http://python-rq.org/docs/workers/ command= /home/user/.virtualenvs/my_project/bin/rq worker process_name=%(program_name)s stdout_logfile = /var/log/my_project/redis.log ; If you want to run more than one worker instance, increase this numprocs=1 ; This is the directory from which RQ is ran. Be sure to point this to the ; directory where your source code is importable from directory=/home/user/github_my_projects/projects/my_project ; RQ requires the TERM signal to perform a warm shutdown. If RQ does not die ; within 10 seconds, supervisor will forcefully kill it stopsignal=TERM ; These are up to you autostart=true autorestart=true </code></pre>
0
2016-07-22T07:45:49Z
38,657,858
<p>Answering my own question.</p> <p>So here is the example configuration i used in local and development servers. You can create this file using : </p> <p><code>sudo touch /etc/supervisor/conf.d/djangorq.conf</code></p> <p>Configuration for development server:</p> <pre><code>[program:djangorq] command=/root/.virtualenvs/my_project/bin/rqworker stdout_logfile=/var/log/my_project/redis.log user=root numprocs=1 directory=/var/www/cast-core/my_project environment=DJANGO_CONFIGURATION=Local,DJANGO_SETTINGS_MODULE=config.local,PYTHONPATH=/var/www/projects/my_project stopsignal=TERM ; These are up to you autostart=true autorestart=true </code></pre> <p>For local environment:</p> <pre><code>[program:myworker] command= /home/user/.virtualenvs/my_project/bin/rqworker stdout_logfile = /var/log/my_project/redis.log numprocs=1 directory=/home/user/github_projects/projects/my_project environment=DJANGO_CONFIGURATION=Local,DJANGO_SETTINGS_MODULE=config.local,PYTHONPATH=/home/user/github_projects/cast-core/my_project user = root stopsignal=TERM autostart=true autorestart=true </code></pre> <p>After this you start supervisor and supervisorctl</p> <p><code>sudo service supervisor start</code></p> <p>and then</p> <p><code>supervisorctl reload</code></p> <p>Then enqueue you jobs using :</p> <p><code>send_mail.delay(#params_required_for_send_mail_method)</code></p>
0
2016-07-29T11:36:49Z
[ "python", "django", "supervisord", "supervisor" ]
Limit number of displayed float digits in pyQT QLineEdit without sacrificing internal accuracy
38,520,962
<p>I'm using QLineEdit widgets in my application to enter and edit numeric (float) values. I would like to <em>display</em> a rounded version of the float value while keeping the full internal accuracy. Only when editing a QLineEdit field, the full number of digits should be displayed.</p> <p>This is needed for three reasons:</p> <ul> <li><p>complex values need way too much space for my GUI</p></li> <li><p>The UI allows to select between log and linear representation and I'd like to hide the resulting numeric inaccuracies.</p></li> <li><p>Simply rounding the value contained and displayed in QLineEdit is not an option as I would lose accuracy when editing the displayed value</p></li> </ul> <p>Does anybody know a neat solution for this problem?</p> <p>Below you find a MWE, the full code (<a href="https://github.com/chipmuenk/pyfda" rel="nofollow">pyfda</a>) uses dynamic instantiation of widgets and other ugly stuff.</p> <pre><code># -*- coding: utf-8 -*- from __future__ import print_function, division import numpy as np import sys from PyQt4 import QtGui class InputNumFields(QtGui.QWidget): def __init__(self, parent): super(InputNumFields, self).__init__(parent) self.edit_input_float = 10*np.log10(np.pi) # store in log format self._init_UI() def _init_UI(self): self.edit_input = QtGui.QLineEdit() self.edit_input.editingFinished.connect(self.store_entries) self.lay_g_main = QtGui.QGridLayout() self.lay_g_main.addWidget(self.edit_input, 0, 0) self.setLayout(self.lay_g_main) self.get_entries() def store_entries(self): """ Store text entry as log float""" self.edit_input_float = 10*np.log10(float(self.edit_input.text())) self.get_entries() def get_entries(self): """ Retrieve float value, delog and convert to string """ self.edit_input.setText(str(10**(self.edit_input_float/10))) if __name__ == '__main__': app = QtGui.QApplication(sys.argv) mainw = InputNumFields(None) app.setActiveWindow(mainw) mainw.show() sys.exit(app.exec_()) </code></pre>
1
2016-07-22T07:46:13Z
38,529,773
<p>It seems that the behaviour should be this:</p> <ul> <li>When the line-edit <strong>loses</strong> input focus, display the stored value rounded</li> <li>When the line-edit <strong>gains</strong> input focus, display the stored value in full</li> <li>Whenever editing finishes, store the full current value in log format</li> </ul> <p>This implies that rounding <strong>must not</strong> occur when return or enter is pressed (because the line-edit would not lose focus in that case).</p> <p>The above behaviour can be achieved with the following changes:</p> <pre><code>from PyQt4 import QtCore, QtGui class InputNumFields(QtGui.QWidget): ... def _init_UI(self): self.edit_input = QtGui.QLineEdit() self.edit_input.installEventFilter(self) ... def eventFilter(self, source, event): if (event.type() == QtCore.QEvent.FocusIn and source is self.edit_input): self.get_entries() return super(InputNumFields, self).eventFilter(source, event) def get_entries(self): value = 10**(self.edit_input_float/10) if not self.edit_input.hasFocus(): value = round(value, 3) self.edit_input.setText(str(value)) </code></pre> <p>PS:</p> <p>You should probably add a button or something to your example, so you can test the effects of changing focus.</p>
0
2016-07-22T15:06:23Z
[ "python", "floating-point", "pyqt", "qlineedit" ]
Limit number of displayed float digits in pyQT QLineEdit without sacrificing internal accuracy
38,520,962
<p>I'm using QLineEdit widgets in my application to enter and edit numeric (float) values. I would like to <em>display</em> a rounded version of the float value while keeping the full internal accuracy. Only when editing a QLineEdit field, the full number of digits should be displayed.</p> <p>This is needed for three reasons:</p> <ul> <li><p>complex values need way too much space for my GUI</p></li> <li><p>The UI allows to select between log and linear representation and I'd like to hide the resulting numeric inaccuracies.</p></li> <li><p>Simply rounding the value contained and displayed in QLineEdit is not an option as I would lose accuracy when editing the displayed value</p></li> </ul> <p>Does anybody know a neat solution for this problem?</p> <p>Below you find a MWE, the full code (<a href="https://github.com/chipmuenk/pyfda" rel="nofollow">pyfda</a>) uses dynamic instantiation of widgets and other ugly stuff.</p> <pre><code># -*- coding: utf-8 -*- from __future__ import print_function, division import numpy as np import sys from PyQt4 import QtGui class InputNumFields(QtGui.QWidget): def __init__(self, parent): super(InputNumFields, self).__init__(parent) self.edit_input_float = 10*np.log10(np.pi) # store in log format self._init_UI() def _init_UI(self): self.edit_input = QtGui.QLineEdit() self.edit_input.editingFinished.connect(self.store_entries) self.lay_g_main = QtGui.QGridLayout() self.lay_g_main.addWidget(self.edit_input, 0, 0) self.setLayout(self.lay_g_main) self.get_entries() def store_entries(self): """ Store text entry as log float""" self.edit_input_float = 10*np.log10(float(self.edit_input.text())) self.get_entries() def get_entries(self): """ Retrieve float value, delog and convert to string """ self.edit_input.setText(str(10**(self.edit_input_float/10))) if __name__ == '__main__': app = QtGui.QApplication(sys.argv) mainw = InputNumFields(None) app.setActiveWindow(mainw) mainw.show() sys.exit(app.exec_()) </code></pre>
1
2016-07-22T07:46:13Z
38,667,280
<p>I have tried to use a mix of signal-slot connections (<code>editingFinished</code>) and eventFilter. However, I ran into some strange bugs that may have been caused by some race conditions or simply because the logic behind the code became too warped. Anyway, the following snippet works great, maybe it is helpful for somebody:</p> <pre><code>def eventFilter(self, source, event): """ Filter all events generated by the QLineEdit widgets. Source and type of all events generated by monitored objects are passed to this eventFilter, evaluated and passed on to the next hierarchy level. - When a QLineEdit widget gains input focus (QEvent.FocusIn`), display the stored value with full precision - When a key is pressed inside the text field, set the `spec_edited` flag to True. - When a QLineEdit widget loses input focus (QEvent.FocusOut`), store current value in linear format with full precision (only if `spec_edited`== True) and display the stored value in selected format """ if isinstance(source, QtGui.QLineEdit): # could be extended for other widgets if event.type() == QEvent.FocusIn: self.spec_edited = False self.get_entries() elif event.type() == QEvent.KeyPress: self.spec_edited = True elif event.type() == QEvent.FocusOut: self._store_entries(source) # Call base class method to continue normal event processing: return super(InputAmpSpecs, self).eventFilter(source, event) </code></pre>
0
2016-07-29T20:51:22Z
[ "python", "floating-point", "pyqt", "qlineedit" ]
Submitting a Form using Selenium in Python
38,520,970
<p>I need to scrape some data behind those hyperlinks from <a href="http://www.echemportal.org/echemportal/propertysearch/treeselect_input.action?queryID=PROQ3h3n" rel="nofollow">this Site</a>. However, those hyperlinks are <code>javascript function calls</code>, which later submits a <code>form</code> using <code>post</code> method. After some search, <code>selenium</code> seems to be a candidate. So my question is that how should I properly set a value to an input tag and submit the form which does not a submit a button.</p> <pre><code>from selenium import webdriver url = "http://www.echemportal.org/echemportal/propertysearch/treeselect_input.action?queryID=PROQ3h3n" driver = webdriver.Firefox() driver.get(url) treePath_tag = driver.find_element_by_name("treePath") </code></pre> <p>Before submitting the form, I need to assign value to tag <code>&lt;input&gt;</code>. However, I got an error </p> <blockquote> <p>Message: Element is not currently visible and so may not be interacted with</p> </blockquote> <pre><code>treePath_tag.send_keys('/TR.SE00.00/QU.SE.DATA_ENV/QU.SE.ENV_ENVIRONMENT_DATA/QU.SE.EN_MONITORING') </code></pre> <p>IF above is correct, I would like to submit form this way. Is it correct?</p> <pre><code>selenium.find_element_by_name("add_form").submit() </code></pre> <p>Below are sources from the web page.</p> <h3>JavaScript function</h3> <pre><code>&lt;script type="text/javascript"&gt; function AddBlock(path){ document.add_form.treePath.value=path; document.add_form.submit(); } &lt;/script&gt; </code></pre> <h3>form "add_form"</h3> <pre><code>&lt;form id="addblock_input" name="add_form" action="/echemportal/propertysearch/addblock_input.action" method="post" style="display:none;"&gt; &lt;table class="wwFormTable" style="display:none;"&gt;&lt;tr style="display:none;"&gt; &lt;td colspan="2"&gt; &lt;input type="hidden" name="queryID" value="PROQ3h1w" id="addblock_input_queryID"/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr style="display:none;"&gt; &lt;td colspan="2"&gt; &lt;input type="hidden" name="treePath" value="" id="addblock_input_treePath"/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;/form&gt; </code></pre> <h3>div with javascript call</h3> <pre><code>&lt;div id="querytree"&gt; &lt;h1&gt;Property Search&lt;/h1&gt; &lt;h2&gt;Select Query Block Type&lt;/h2&gt; &lt;p&gt;Select a section for which to define query criteria.&lt;/p&gt; &lt;div class="queryblocktools"&gt;&lt;a href="javascript:document.load_form.submit();"&gt;&lt;img style="vertical-align:top;" alt="Load" src="/echemportal/etc/img/load.gif"/&gt;&amp;nbsp;Load Query&lt;/a&gt;&lt;/div&gt; &lt;ul class="listexpander"&gt; &lt;li&gt;Physical and chemical properties&lt;ul&gt; &lt;li&gt;&lt;a href="javascript:AddBlock('/TR.SE00.00/QU.SE.DATA_PHYS/QU.SE.PC_MELTING');"&gt;Melting point/freezing point&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="javascript:AddBlock('/TR.SE00.00/QU.SE.DATA_PHYS/QU.SE.PC_BOILING');"&gt;Boiling point&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre>
0
2016-07-22T07:46:38Z
38,521,635
<p>You are trying to set value on <code>hidden</code> input is which not visible on the page, that's why error has occurred. If you want to set value on <code>hidden</code> field try using <code>execute_script</code> as below :-</p> <pre><code>treePath_tag = driver.find_element_by_name("treePath") driver.execute_script('arguments[0].value = arguments[1]', treePath_tag, '/TR.SE00.00/QU.SE.DATA_ENV/QU.SE.ENV_ENVIRONMENT_DATA/QU.SE.EN_MONITORING') </code></pre> <p>After setting value on <code>hidden</code> field you can use following to <code>submit</code> the form :-</p> <pre><code>selenium.find_element_by_name("add_form").submit() </code></pre> <p>Hope it helps..:)</p>
1
2016-07-22T08:25:52Z
[ "javascript", "python", "forms", "selenium" ]
Python Selenium - AttributeError : WebElement object has no attribute sendKeys
38,521,136
<p>I'm trying to pass through "ENTER" to a text field, using <code>Selenium</code> (Python). The text box requires that each phone number be entered on a new line, so it will look something like:</p> <pre><code>#Add the phone number# Webelement.sendKeys(Keys.ENTER) </code></pre> <p>I've imported the following library:</p> <pre><code>from selenium.webdriver.common.keys import Keys </code></pre> <p>The problem I'm getting is that it fails with:</p> <blockquote> <p>AttributeError: 'WebElement' object has no attribute 'sendKeys'</p> </blockquote> <p>Does anyone know how to resolve this? I've been searching for a solution, but haven't been able to find anything.</p>
0
2016-07-22T07:56:19Z
38,521,249
<p>Try using <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webelement.WebElement.send_keys" rel="nofollow"><code>WebElement::send_keys()</code></a> instead of <code>sendKeys</code> as below :-</p> <pre><code>from selenium.webdriver.common.keys import Keys Webelement.send_keys(Keys.ENTER) </code></pre>
3
2016-07-22T08:02:38Z
[ "python", "selenium", "selenium-webdriver", "sendkeys" ]
Have to manually start worker on heroku?
38,521,160
<p>In my Procfile I have the following:</p> <pre><code>worker: cd appname &amp;&amp; celery -A appname worker -l info --app=appname.celery_setup:app </code></pre> <p>However, when my app submits a task it never happens, but I think the celery worker is at least sort of working, because </p> <pre><code>heroku logs --app appname </code></pre> <p>every so often gives me one of these:</p> <pre><code>2016-07-22T07:53:21+00:00 app[heroku-redis]: source=REDIS sample#active-connections=14 sample#load-avg-1m=0.03 sample#load-avg-5m=0.09 sample#load-avg-15m=0.085 sample#read-iops=0 sample#write-iops=0 sample#memory-total=15664884.0kB sample#memory-free=13458244.0kB sample#memory-cached=187136kB sample#memory-redis=566800bytes sample#hit-rate=0.17778 sample#evicted-keys=0 </code></pre> <p>Also, when I open up bash by running</p> <pre><code>heroku run bash --app appname </code></pre> <p>and then type in </p> <pre><code>cd appname &amp;&amp; celery -A appname worker -l info --app=appname.celery_setup:app </code></pre> <p>It immediately tells me the task has been received and then executes it. I would like to have this happen without me having to manually log in and execute the command - is that possible? Do I need a paid account on heroku to do that?</p>
0
2016-07-22T07:57:16Z
38,537,122
<p>I figured it out. Turns out you also have to do </p> <pre><code>heroku ps:scale worker=1 --app appname </code></pre> <p>Or else you won't actually be running a worker.</p>
1
2016-07-23T00:57:21Z
[ "python", "django", "heroku", "celery", "django-celery" ]
How can i call syntaxnet from python file?
38,521,181
<p>We have successfully installed syntaxnet and we are able to get the parsed output by calling the command <code>echo 'open Book, which I have written with laboratory writer, with libreoffice writer.' | syntaxnet/demo.sh</code>.</p> <p>Ideally what we want is calling syntaxnet from python file (more specifically from flask) and expose syntaxnet service as api for internal team.</p>
0
2016-07-22T07:59:00Z
38,533,083
<p>Apperently it is exactly like the example I have used in my <a href="http://stackoverflow.com/questions/37753980/how-to-use-syntaxnet-output-to-operate-an-executive-command-for-example-save-a/38444785#38444785">answer</a>. using <code>subprocess</code> module can help you to do call this command in your python file and see the result. I have explained how to use this module in my <a href="http://stackoverflow.com/questions/37753980/how-to-use-syntaxnet-output-to-operate-an-executive-command-for-example-save-a/38444785#38444785">answer</a></p>
0
2016-07-22T18:24:29Z
[ "python", "tensorflow", "syntaxnet" ]
Python not finding modules after installing with pip
38,521,214
<p>I have installed various third party modules with pip and they worked fine until I then ran ccleaner today. Now I cannot import any of these modules. </p> <p>I've added site-packages to the PATH variable: C:\Python27\;C:\Users\Rick\PythonScripts;C:\Python27\Scripts;C:\Python27\Lib;C:\Python27\Lib\site-packages\</p> <p>I can import the modules when I run python through command line, but not when I run a script or in a terminal window. They are all running the same version of python: 2.7.12 (in Windows 7).</p> <p>Any suggestions for how I can fix this? Thanks</p>
-2
2016-07-22T08:00:41Z
38,521,936
<p>Your Path variable needs to modify. This is only used to find binary, not python standard library.</p> <p>Remove:</p> <pre><code>C:\Python27\;C:\Users\Rick\PythonScripts;C:\Python27\Scripts;C:\Python27\Lib;C:\Python27\Lib\site-packages\ </code></pre> <p>Add:</p> <pre><code>C:\Python27\;C:\Python27\Scripts; </code></pre> <p>Edit: do a work-around.</p> <pre><code>import sys pathLst = [r"C:\Python27\lib\site-packages", r"C:\Python27\lib\site-packages\PIL", r"C:\Python27\lib\site-packages\win32", r"C:\Python27\lib\site-packages\win32\lib", r"C:\Python27\lib\site-packages\Pythonwin"] sys.path.extend(pathLst) </code></pre>
0
2016-07-22T08:41:31Z
[ "python", "python-2.7" ]
use json in cherrpy
38,521,258
<p>I am new to creating API's in cherrypy.So,I am just making a simple API to add numbers and display the answer.</p> <p>I used this :</p> <pre><code> import cherrypy import json def add(b,c): return a+b class addition: exposed = True def POST(self,c,d): result=add(c,d) return('addition result is' % result) if __name__=='__main__': cherrypy.tree.mount( addition(),'/api/add', {'/': {'request.dispatch':cherrypy.dispatch.MethodDispatcher()} } ) cherrypy.engine.start() </code></pre> <p>and then on a different file,to call the POST method,I wrote this code:</p> <pre><code> import requests import json url = "http://127.0.0.1:8080/api/add/" data={'c':12, 'd':13 } payload = json.dumps(data) headers = {'content-type':"application/json"} response = requests.request("POST",url,data=payload,headers=headers) print(response.text) </code></pre> <p>but I am getting an error :HTTPError: (404, 'Missing parameters: c,d')</p> <p>Please may I know where I am going wrong.</p>
0
2016-07-22T08:03:27Z
38,998,730
<p>First start without JSON to make sure your code works. Then update your code to work with JSON. Here is a working example of your calculator.</p> <p>This example shows it without JSON. Example with JSON is below.</p> <h1>Working example without JSON</h1> <p>Server side in cherrypy (<code>server1.py</code>):</p> <pre><code>#!/usr/bin/env python # -*- coding: UTF-8 -*- import cherrypy def add(a, b): return a + b class Calculator: exposed = True def POST(self, a, b): result = add(int(a), int(b)) return 'result is {}'.format(result) if __name__=='__main__': app_config = { '/': {'request.dispatch':cherrypy.dispatch.MethodDispatcher()} } cherrypy.tree.mount(Calculator(), '/api/add', config=app_config) cherrypy.config.update({ 'server.socket_host' : '127.0.0.1', 'server.socket_port' : 9090, }) cherrypy.engine.start() cherrypy.engine.block() </code></pre> <p>Run the cherrypy server as a separate process. Open another terminal window, command line or whatever you use and use this API client to send a request. Name it <code>client1.py</code></p> <pre><code>#!/usr/bin/env python # -*- coding: UTF-8 -*- import requests url = 'http://127.0.0.1:9090/api/add' data = { 'a': 12, 'b': 13 } response = requests.request('POST', url, data=data) print(response.text) </code></pre> <p>If you send the request, you get this response:</p> <pre><code>$ python send.py result is 25 </code></pre> <h1>Working example with JSON</h1> <p>CherryPy server side (<code>server2.py</code>):</p> <pre><code>#!/usr/bin/env python # -*- coding: UTF-8 -*- import cherrypy import json def add(a, b): return a + b class Calculator: exposed = True @cherrypy.tools.json_in() def POST(self): input_json = cherrypy.request.json result = add(input_json['a'], input_json['b']) return 'result is {}'.format(result) if __name__=='__main__': app_config = { '/': {'request.dispatch':cherrypy.dispatch.MethodDispatcher()} } cherrypy.tree.mount(Calculator(), '/api/add', config=app_config) cherrypy.config.update({ 'server.socket_host' : '127.0.0.1', 'server.socket_port' : 9090, }) cherrypy.engine.start() cherrypy.engine.block() </code></pre> <p>API client, name it <code>client2.py</code></p> <pre><code>#!/usr/bin/env python # -*- coding: UTF-8 -*- import requests url = 'http://127.0.0.1:9090/api/add' data = { 'a': 12, 'b': 13 } headers = {'content-type': 'application/json'} # Note that there is json=data not data=data. # This automatically converts input data to JSON r = requests.request('POST', url, json=data, headers=headers) print(r.status_code) print(r.text) </code></pre>
0
2016-08-17T13:55:18Z
[ "python", "json", "http", "post", "cherrypy" ]
OpenERP - Odoo - How to have the percentage of quote that become a sale orders
38,521,380
<p>Is it possible to have easily the percentage of sales orders / quotes per users?</p> <p>The objective it is to know what the percentage of quote that become a sale order per user.</p> <p>I have not a clue how I can do it. I am using OpenERP 7</p>
0
2016-07-22T08:09:44Z
38,689,879
<p>Yes it is possible by using status bar. In order for you to compute the percentage of sales order, you should determine how much is the quota for each sale order.</p>
0
2016-08-01T01:30:46Z
[ "python", "openerp", "openerp-7" ]
How to search through tree to find the maximum sum of a set of nodes' value
38,521,381
<pre><code> G B H A D E C I F 1 2 3 (level) </code></pre> <p>Suppose there is a Tree in the above structure.<br> Each node is linked with the nodes of their parent and children. Also each node is linked with one node previously added and somewhat related to the current node.</p> <p>Suppose now that each node has five properties: </p> <ol> <li>the name of the node (e.g. 'A', 'B', 'C', etc)</li> <li>the node of their parent (e.g. if <code>node.name == 'B'</code>, then <code>node.parent.name == 'A'</code> is True)</li> <li>the node beneath them (e.g. if <code>node.name == 'G'</code>, then <code>node.previous.name == 'H'</code> is True, However if <code>node.name == 'H'</code>, then <code>node.previous.name == 'B'</code> is True)</li> <li>list of children nodes (e.g. if <code>node.name == 'A'</code>, then <code>[c.name for c in node.children] == ['B', 'D', 'C']</code> is True)</li> <li>node.value (e.g. isinstance(node.value, int) is True)</li> </ol> <p>Now if I want to search through the Tree to find the maximum value of a group of related nodes with the given number n which denotes the group size. (e.g. node E relates to node I and node C, but node F, however, node I doesn't relate to node E, but does relate to node F and node C) </p> <p>How exactly can I design this function</p>
1
2016-07-22T08:10:14Z
38,522,046
<p><strike>Here is my understanding of your problem: You want to enumerate all groups of related nodes of size n, and find the maximum sum of the values of the nodes in such a group.</p> <p>Here is an algorithm: For each node keep a sorted list of its children, sorted with respect to the values of the children. Iterate over all the nodes. For each node, compute the maximum of the following four numbers:</p> <ol> <li><p>current node + largest n-1 children</p></li> <li><p>current node + largest n-2 children + parent</p></li> <li><p>current node + largest n-2 children + previous</p></li> <li><p>current node + largest n-3 children + parent + previous</p></li> </ol> <p>Remember to take care of special cases, e.g., if a node has few children, parent=previous etc. (actually you might just put all related nodes of a node in one sorted list and pick the n-1 largest). </strike></p> <hr> <p>Since a node apparently can be related to its childrens children, the above will not work.</p> <hr> <p>I have given it another go: For each node keep a list <code>l</code>, whose index is the maximum value obtained using the node + up to i-1 children. For each leaf node this is simply going to be <code>[0, leaf.value, ...]</code>. For each node, assume that is has one child. Then <code>node.l</code> is easy to compute, it is simply:</p> <pre><code>node.l[i] = child.l[i-1] + node.value </code></pre> <p>If we then add another child to this node, we may use 0 through n-1 nodes from the child, depeneding on what is optimal. This is computed using (kind of, see the code below)</p> <pre><code>node.l[i] = max(node.l[i], node.l[i-k] + child.l[i]) </code></pre> <p>This is implemented below. It is easy to accomodate for the extra connectedness due to <code>node.previous</code>. We just make an extra pass through the list of nodes at the end, when all <code>node.l</code>'s are computed.</p> <pre><code>for node in nodes: # l[i] = maximum value obatined using node + up to i-1 children node.l = [0 for i in xrange(n+1)] node.visited = False Q = [] # Queue for leaf in nodes: if len(leaf.children) &gt; 0: continue Q.append(leaf) leaf.visited = True while Q: t = Q.pop(0) l = [0] for i in xrange(1, n+1): l.append(t[i-1] + t.value) t.l = l if not t.parent: break for l in xrange(0, n+1): for i in xrange(l, n+1): t.parent.l[i] = max(t.parent[i], t.parent[i-l] + t[l]) if not t.parent.visited: t.parent.visited = True Q.append(t.parent) m = 0 for node in nodes: m = max(m, node[n], node[n-1] \ + (node.previous.value if node.previous else 0)) print m </code></pre> <p>The running time is <code>n*n*(number of nodes)</code>.</p>
0
2016-07-22T08:46:48Z
[ "python", "python-3.x", "tree" ]
How to change the sampling rate of the data
38,521,537
<p>How to change the sampling rate of the data in the list <code>result</code>.</p> <p>The current sampling rate is 256, but the desired sampling rate is 250.</p> <p>Given:</p> <ul> <li><code>result</code> - a list of data with a sampling frequency of 256.</li> <li><code>buf.size</code> - the amount of signal in the channel</li> </ul> <p>I tried to use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.resample.html" rel="nofollow"><code>scipy.signal.resample</code></a></p> <pre><code>from scipy import signal result250 = signal.resample(result, buf.size, t=None, axis=0, window=None) Traceback (most recent call last): File "****.py", line 82, in &lt;module&gt; result250 = signal.resample(result, buf.size, t=None, axis=0, window=None) File "****\scipy\signal\signaltools.py", line 1651, in resample X = fft(x, axis=axis) File "****\scipy\fftpack\basic.py", line 249, in fft tmp = _asfarray(x) File "****\scipy\fftpack\basic.py", line 134, in _asfarray return numpy.asfarray(x) File "****\numpy\lib\type_check.py", line 105, in asfarray return asarray(a, dtype=dtype) File "****\numpy\core\numeric.py", line 482, in asarray return array(a, dtype, copy=False, order=order) ValueError: invalid literal for float(): 3.3126, 6.6876, 9.3126, 10.0627, **** </code></pre> <p>There is another option of linear interpolation (preferable), but I also can not figure out how to use. <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html" rel="nofollow"><code>scipy.interpolate.interp1d</code></a></p>
0
2016-07-22T08:19:23Z
38,524,822
<p>I'll try here since the comments are small and I think I'll answer you:</p> <p>As I was saying python lists are just that, lists, a collection of stuff (not necessarily numerical values) they don't know or care about what is inside and as such they don't know what sampling frequency even means. Once you accept that the numbers in your list are just a representation of stuff you can sample them at whatever rate you want, it's just a matter of what you plot it against or how many values you consider per unit time.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt data = [3.3126, 6.6876, 9.3126, 10.0627, 9.0626, 6.6876, 4.0626, 2.0625, 0.9375, 0.5625, 0.4375, 0.3125, 0.1875, 0.1875, 0.9375, 2.4375, 4.5626, 6.6876, 7.9376, 7.3126, 4.9376, 1.0625, -3.3126, -6.9376, -8.9376, -8.6876, -6.5626, -3.1875, 0.3125, 2.6875, 3.5626, 2.6875, 0.5625, -2.0625, -4.3126, -5.6876, -5.9376, -5.3126, -4.4376, -3.6876, -3.4376, -3.5626, -3.6876, -3.4376, -2.6875, -1.4375, -0.5625, -0.4375, -1.4375, -3.3126, -5.3126, -6.5626, -6.4376, -5.1876, -3.5626, -2.6875, -3.0625, -4.4376, -5.9376, -6.3126, -5.3126, -2.9375, -0.1875] x256 = np.arange(0, 1, 1/256)[:len(data)] x200 = np.arange(0, 1, 1/200)[:len(data)] plt.plot(x256, data, label='x256') plt.plot(x200, data, label='x200') plt.legend() </code></pre> <p>Output: <a href="http://i.stack.imgur.com/hsn1j.png" rel="nofollow"><img src="http://i.stack.imgur.com/hsn1j.png" alt="!["></a></p> <p>Does this solve your resampling problem?</p>
0
2016-07-22T11:01:54Z
[ "python", "python-2.7", "numpy", "scipy", "resampling" ]
How to change the sampling rate of the data
38,521,537
<p>How to change the sampling rate of the data in the list <code>result</code>.</p> <p>The current sampling rate is 256, but the desired sampling rate is 250.</p> <p>Given:</p> <ul> <li><code>result</code> - a list of data with a sampling frequency of 256.</li> <li><code>buf.size</code> - the amount of signal in the channel</li> </ul> <p>I tried to use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.resample.html" rel="nofollow"><code>scipy.signal.resample</code></a></p> <pre><code>from scipy import signal result250 = signal.resample(result, buf.size, t=None, axis=0, window=None) Traceback (most recent call last): File "****.py", line 82, in &lt;module&gt; result250 = signal.resample(result, buf.size, t=None, axis=0, window=None) File "****\scipy\signal\signaltools.py", line 1651, in resample X = fft(x, axis=axis) File "****\scipy\fftpack\basic.py", line 249, in fft tmp = _asfarray(x) File "****\scipy\fftpack\basic.py", line 134, in _asfarray return numpy.asfarray(x) File "****\numpy\lib\type_check.py", line 105, in asfarray return asarray(a, dtype=dtype) File "****\numpy\core\numeric.py", line 482, in asarray return array(a, dtype, copy=False, order=order) ValueError: invalid literal for float(): 3.3126, 6.6876, 9.3126, 10.0627, **** </code></pre> <p>There is another option of linear interpolation (preferable), but I also can not figure out how to use. <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html" rel="nofollow"><code>scipy.interpolate.interp1d</code></a></p>
0
2016-07-22T08:19:23Z
38,612,066
<p>You must record the time (in seconds - <code>f.file_duration</code>). My answer:</p> <pre><code>x250 = np.arange(0, f.file_duration, 0.004) #frequency 250 x256 = np.arange(0, f.file_duration, 0.00390625) #frequency 256 result256 = np.interp(x256, x250, result) </code></pre>
0
2016-07-27T11:46:30Z
[ "python", "python-2.7", "numpy", "scipy", "resampling" ]
How to print out only records with intervals, from one file, not overlapping with those from another file
38,521,553
<p>I have two files representing records with intervals.</p> <p>file1.txt</p> <pre class="lang-none prettyprint-override"><code>a 5 10 a 13 19 a 27 39 b 4 9 b 15 19 c 20 33 c 39 45 </code></pre> <p>and</p> <p>file2.txt</p> <pre class="lang-none prettyprint-override"><code>something id1 a 4 9 commentx something id2 a 14 18 commenty something id3 a 1 4 commentz something id5 b 3 9 commentbla something id6 b 16 18 commentbla something id7 b 25 29 commentblabla something id8 c 5 59 hihi something id9 c 40 45 hoho something id10 c 32 43 haha </code></pre> <p>What I would like to do is to make a file representing only records of the file2 for which, if the column 3 of the file2 is identical to the column 1 of the file1, the range (column 4 and 5) is not overlapping with that of the file1 (column 2 and 3).</p> <p>The expected output file should be in a file</p> <p>test.result</p> <pre class="lang-none prettyprint-override"><code>something id3 a 1 4 commentz something id7 b 25 29 commentblabla </code></pre> <p>I have tried to use the following python code:</p> <pre><code>import csv with open ('file2') as protein, open('file1') as position, open ('test.result',"r+") as fallout: writer = csv.writer(fallout, delimiter=' ') for rowinprot in csv.reader(protein, delimiter=' '): for rowinpos in csv.reader(position, delimiter=' '): if rowinprot[2]==rowinpos[0]: if rowinprot[4]&lt;rowinpos[1] or rowinprot[3]&gt;rowinpos[2]: writer.writerow(rowinprot) </code></pre> <p>This did not seem to work...I had the following result:</p> <pre class="lang-none prettyprint-override"><code>something id1 a 4 9 commentx something id1 a 4 9 commentx something id1 a 4 9 commentx </code></pre> <p>which apparently is not what I want.</p> <p>What did I do wrong? It seems to be in the conditional loops. Still, I couldn't figure it out...</p>
4
2016-07-22T08:20:31Z
38,522,474
<p>For your code to work, you will have to change three things:</p> <ol> <li>Your loop over the position reader is only run once, because the reader runs through the file, the first time the loop is run. Afterwards, he searches for the next item at the end of the file. You'll have to rewind the file each time, before the loop is run. See e.g. (<a href="http://stackoverflow.com/questions/431752/python-csv-reader-how-do-i-return-to-the-top-of-the-file">Python csv.reader: How do I return to the top of the file?</a>)</li> <li>The csv reader returns string objects. If you compare them via smaller/larger signs, it compares them as if they were words. So it checks first digit vs first digit, and so on. To get the comparison right, you'll have to cast to integer first.</li> <li>Lastly, your program now would return a line out of the protein file every time it does not overlap with a line in the position file that has the same identifier. So for example the first protein line would be printed twice for the second and third position line. As I understand, this is not what you want, so you'll have to check ALL position lines to be valid, before printing.</li> </ol> <p>Generally, the code is probably not the most elegant way to do it but to get correct results with something close to what you wrote, you might want to try something along the lines of:</p> <pre><code>with open ('file2.txt') as protein, open('file1.txt') as position, open ('test.result',"r+") as fallout: writer = csv.writer(fallout, delimiter=' ') for rowinprot in csv.reader(protein, delimiter=' '): position.seek(0) valid = True for rowinpos in csv.reader(position, delimiter=' '): if rowinprot[2]==rowinpos[0]: if not (int(rowinprot[4])&lt;int(rowinpos[1]) or int(rowinprot[3])&gt;int(rowinpos[2])): valid = False if valid: writer.writerow(rowinprot) </code></pre>
0
2016-07-22T09:06:46Z
[ "python" ]
How to print out only records with intervals, from one file, not overlapping with those from another file
38,521,553
<p>I have two files representing records with intervals.</p> <p>file1.txt</p> <pre class="lang-none prettyprint-override"><code>a 5 10 a 13 19 a 27 39 b 4 9 b 15 19 c 20 33 c 39 45 </code></pre> <p>and</p> <p>file2.txt</p> <pre class="lang-none prettyprint-override"><code>something id1 a 4 9 commentx something id2 a 14 18 commenty something id3 a 1 4 commentz something id5 b 3 9 commentbla something id6 b 16 18 commentbla something id7 b 25 29 commentblabla something id8 c 5 59 hihi something id9 c 40 45 hoho something id10 c 32 43 haha </code></pre> <p>What I would like to do is to make a file representing only records of the file2 for which, if the column 3 of the file2 is identical to the column 1 of the file1, the range (column 4 and 5) is not overlapping with that of the file1 (column 2 and 3).</p> <p>The expected output file should be in a file</p> <p>test.result</p> <pre class="lang-none prettyprint-override"><code>something id3 a 1 4 commentz something id7 b 25 29 commentblabla </code></pre> <p>I have tried to use the following python code:</p> <pre><code>import csv with open ('file2') as protein, open('file1') as position, open ('test.result',"r+") as fallout: writer = csv.writer(fallout, delimiter=' ') for rowinprot in csv.reader(protein, delimiter=' '): for rowinpos in csv.reader(position, delimiter=' '): if rowinprot[2]==rowinpos[0]: if rowinprot[4]&lt;rowinpos[1] or rowinprot[3]&gt;rowinpos[2]: writer.writerow(rowinprot) </code></pre> <p>This did not seem to work...I had the following result:</p> <pre class="lang-none prettyprint-override"><code>something id1 a 4 9 commentx something id1 a 4 9 commentx something id1 a 4 9 commentx </code></pre> <p>which apparently is not what I want.</p> <p>What did I do wrong? It seems to be in the conditional loops. Still, I couldn't figure it out...</p>
4
2016-07-22T08:20:31Z
38,522,927
<p>Here is an algorithm working for you:</p> <pre><code>def is_overlapping(x, y): return len(range(max(x[0], y[0]), min(x[-1], y[-1])+1)) &gt; 0 position_file = r"file1.txt" positions = [line.strip().split() for line in open(position_file).read().split('\n')] protein_file = r"file2.txt" proteins = [(line.strip().split()[2:5], line) for line in open(protein_file).read().split('\n')] fallout_file = r"result.txt" with open(fallout_file, 'w') as fallout: for index, protein_info in enumerate(proteins): try: test_position = positions[index] except IndexError: # If files do not have the same size the loop will end break protein_position, protein_line = protein_info # If identifier is different, write line and check next line if protein_position[0] != test_position[0]: print(protein_line) fallout.write(protein_line) continue # Here identifiers are identical, then we check if they overlap test_range = range(int(test_position[1]), int(test_position[2])) protein_range = range(int(protein_position[1]), int(protein_position[2])) if not is_overlapping(protein_range, test_range): print(protein_line) fallout.write(protein_line + '\n') </code></pre> <p>Concerning the overlapping test, a good snippet was given here: <a href="http://stackoverflow.com/a/6821298/2531279">http://stackoverflow.com/a/6821298/2531279</a></p>
0
2016-07-22T09:29:02Z
[ "python" ]
How to print out only records with intervals, from one file, not overlapping with those from another file
38,521,553
<p>I have two files representing records with intervals.</p> <p>file1.txt</p> <pre class="lang-none prettyprint-override"><code>a 5 10 a 13 19 a 27 39 b 4 9 b 15 19 c 20 33 c 39 45 </code></pre> <p>and</p> <p>file2.txt</p> <pre class="lang-none prettyprint-override"><code>something id1 a 4 9 commentx something id2 a 14 18 commenty something id3 a 1 4 commentz something id5 b 3 9 commentbla something id6 b 16 18 commentbla something id7 b 25 29 commentblabla something id8 c 5 59 hihi something id9 c 40 45 hoho something id10 c 32 43 haha </code></pre> <p>What I would like to do is to make a file representing only records of the file2 for which, if the column 3 of the file2 is identical to the column 1 of the file1, the range (column 4 and 5) is not overlapping with that of the file1 (column 2 and 3).</p> <p>The expected output file should be in a file</p> <p>test.result</p> <pre class="lang-none prettyprint-override"><code>something id3 a 1 4 commentz something id7 b 25 29 commentblabla </code></pre> <p>I have tried to use the following python code:</p> <pre><code>import csv with open ('file2') as protein, open('file1') as position, open ('test.result',"r+") as fallout: writer = csv.writer(fallout, delimiter=' ') for rowinprot in csv.reader(protein, delimiter=' '): for rowinpos in csv.reader(position, delimiter=' '): if rowinprot[2]==rowinpos[0]: if rowinprot[4]&lt;rowinpos[1] or rowinprot[3]&gt;rowinpos[2]: writer.writerow(rowinprot) </code></pre> <p>This did not seem to work...I had the following result:</p> <pre class="lang-none prettyprint-override"><code>something id1 a 4 9 commentx something id1 a 4 9 commentx something id1 a 4 9 commentx </code></pre> <p>which apparently is not what I want.</p> <p>What did I do wrong? It seems to be in the conditional loops. Still, I couldn't figure it out...</p>
4
2016-07-22T08:20:31Z
38,524,016
<p>Do looping in a loop is not a good way. Try to avoid to do such things. I think you could cache the content of file1 first use a dict object. Then, when looping file2 you can use the dict object to find your need things.So, i will code like bellow:</p> <pre><code>with open("file1.csv", "r") as protein, open("file2.csv", "r") as postion, open("result.csv", "w") as fallout: writer = csv.writer(fallout, delimiter=' ') protein_dict = {} for rowinprt in csv.reader(protein, delimiter=' '): key = rowinprt[0] sub_value = (int(rowinprt[1]), int(rowinprt[2])) protein_dict.setdefault(key, []) protein_dict[key].append(sub_value) for pos in csv.reader(postion, delimiter=' '): id_key = pos[2] id_min = int(pos[3]) id_max = int(pos[4]) if protein_dict.has_key(id_key) and all([ id_max &lt; _min or _max &lt; id_min for _min, _max in protein_dict[id_key]]): writer.writerow(pos) </code></pre>
0
2016-07-22T10:22:17Z
[ "python" ]
How to print out only records with intervals, from one file, not overlapping with those from another file
38,521,553
<p>I have two files representing records with intervals.</p> <p>file1.txt</p> <pre class="lang-none prettyprint-override"><code>a 5 10 a 13 19 a 27 39 b 4 9 b 15 19 c 20 33 c 39 45 </code></pre> <p>and</p> <p>file2.txt</p> <pre class="lang-none prettyprint-override"><code>something id1 a 4 9 commentx something id2 a 14 18 commenty something id3 a 1 4 commentz something id5 b 3 9 commentbla something id6 b 16 18 commentbla something id7 b 25 29 commentblabla something id8 c 5 59 hihi something id9 c 40 45 hoho something id10 c 32 43 haha </code></pre> <p>What I would like to do is to make a file representing only records of the file2 for which, if the column 3 of the file2 is identical to the column 1 of the file1, the range (column 4 and 5) is not overlapping with that of the file1 (column 2 and 3).</p> <p>The expected output file should be in a file</p> <p>test.result</p> <pre class="lang-none prettyprint-override"><code>something id3 a 1 4 commentz something id7 b 25 29 commentblabla </code></pre> <p>I have tried to use the following python code:</p> <pre><code>import csv with open ('file2') as protein, open('file1') as position, open ('test.result',"r+") as fallout: writer = csv.writer(fallout, delimiter=' ') for rowinprot in csv.reader(protein, delimiter=' '): for rowinpos in csv.reader(position, delimiter=' '): if rowinprot[2]==rowinpos[0]: if rowinprot[4]&lt;rowinpos[1] or rowinprot[3]&gt;rowinpos[2]: writer.writerow(rowinprot) </code></pre> <p>This did not seem to work...I had the following result:</p> <pre class="lang-none prettyprint-override"><code>something id1 a 4 9 commentx something id1 a 4 9 commentx something id1 a 4 9 commentx </code></pre> <p>which apparently is not what I want.</p> <p>What did I do wrong? It seems to be in the conditional loops. Still, I couldn't figure it out...</p>
4
2016-07-22T08:20:31Z
38,524,264
<p>It might be overkill, but you could create a class to represent intervals and use it to make fairly readable code:</p> <pre><code>import csv class Interval(object): """ Representation of a closed interval. a &amp; b can be numeric, a datetime.date, or any other comparable type. """ def __init__(self, a, b): self.lowerbound, self.upperbound = (a, b) if a &lt; b else (b, a) def __contains__(self, val): return self.lowerbound &lt;= val &lt;= self.upperbound def __repr__(self): return '{}({}, {})'.format(self.__class__.__name__, self.lowerbound, self.upperbound) filename1 = 'afile1.txt' filename2 = 'afile2.txt' filename3 = 'test.result' intervals = {} # master dictionary of intervals with open(filename1, 'rb') as f: reader = csv.reader(f, delimiter=' ') for row in reader: cls, a, b = row[0], int(row[1]), int(row[2]) intervals.setdefault(cls, []).append(Interval(a, b)) with open(filename2, 'rb') as f1, open(filename3, 'wb') as f2: reader = csv.reader(f1, delimiter=' ') writer = csv.writer(f2, delimiter=' ') for row in reader: cls, a, b = row[2], int(row[3]), int(row[4]) if cls in intervals: for interval in intervals[cls]: # check for overlap if ((a in interval) or (b in interval) or (a &lt; interval.lowerbound and b &gt; interval.upperbound)): break # skip else: writer.writerow(row) # no overlaps </code></pre>
1
2016-07-22T10:34:13Z
[ "python" ]
imshow resize + count white pixels
38,521,571
<p>This is a simple program to read video files from your computer. My original video is 1080p resolution. When I run the code, the program's screen (imshow) exceeds my pc's screen which is only 720p. How to resize it from 1080p to 720 or 480p. Second question, how to find the number of pixels in the screen?</p> <p>My code:</p> <pre><code>import numpy as np import cv2 cap = cv2.VideoCapture('apple.mp4') while(cap.isOpened()): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() </code></pre>
0
2016-07-22T08:21:38Z
38,521,637
<p>You can use <code>cv2.resize()</code> to resize the image before <code>imshow()</code> to fit in the screen, and to get the total number of pixels in the Mat you can use <code>gray.shape[0] * gray.shape[1]</code></p> <pre><code>import numpy as np import cv2 cap = cv2.VideoCapture('apple.mp4') total_white_pixels_in_video_sequence = 0 while(cap.isOpened()): ret, frame = cap.read() frame = cv2.resize(frame, None, fx = 0.5, fy = 0.5, interpolation = cv2.INTER_CUBIC) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) print "No. of pixels : ", gray.shape[0] * gray.shape[1] # Counting the number of pixels with given value total_white_pixels_in_video_sequence += np.count_nonzero(gray == 255) cv2.imshow('frame',gray) if cv2.waitKey(1) &amp; 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() print "total_white_pixels_in_video_sequence : ", total_white_pixels_in_video_sequence </code></pre>
1
2016-07-22T08:25:58Z
[ "python", "opencv" ]
What is the equivalent operator to `in` in the `operator` module?
38,521,669
<p>The module <code>operator</code> offers equivalent functions for almost all standard operations.</p> <p>I have not been able to find the equivalent for the <code>in</code> (<code>if x in y:</code>) operator.</p> <p>Can anyone point me in the right direction?</p>
0
2016-07-22T08:28:05Z
38,521,702
<p>In the python data model, the <code>in</code> operator is implemented via the <a href="https://docs.python.org/2/reference/datamodel.html#object.__contains__" rel="nofollow"><code>__contains__</code></a> hook. Operator follows suit so the method is <a href="https://docs.python.org/2/library/operator.html#operator.contains" rel="nofollow"><code>operator.contains</code></a>.</p>
3
2016-07-22T08:29:27Z
[ "python" ]
What is the equivalent operator to `in` in the `operator` module?
38,521,669
<p>The module <code>operator</code> offers equivalent functions for almost all standard operations.</p> <p>I have not been able to find the equivalent for the <code>in</code> (<code>if x in y:</code>) operator.</p> <p>Can anyone point me in the right direction?</p>
0
2016-07-22T08:28:05Z
38,521,714
<p>It is <a href="https://docs.python.org/2/library/operator.html#operator.contains" rel="nofollow"><code>operator.contains</code></a>:</p> <pre><code>if x in y: </code></pre> <p>Is equivalent to:</p> <pre><code>if operator.contains(y, x): # Note the reversed operand! </code></pre>
2
2016-07-22T08:29:50Z
[ "python" ]
Why can python not take unicode inputs on windows console?
38,521,808
<p>I have a python file named 'কাজ.py'. The file does nothing fancy. I am not concerned for that. The thing is when i try to run the file by copying and pasting the file name, it does not show 'কাজ.py' rather it shows some boxes </p> <pre><code>&gt; python [?][?][?].py </code></pre> <p>and it raises an error like this</p> <pre><code>python: can't open file '???.py': [Errno 22] Invalid argument </code></pre> <p>but on the same console, if i write <code>git add কাজ.py</code>, it shows </p> <pre><code>&gt; git add [?][?][?].py </code></pre> <p>but surprisingly it works and does not give any error.</p> <p>My question is how come git can take unicode input on the same console where python cannot? Please note that i am on Windows platform and using cmd.exe</p>
0
2016-07-22T08:35:06Z
38,523,259
<p>It depends whether the command uses internally the UNICODE or MBCS command line application interface. Assuming it is a C (or C++) program, it depends whether it uses a <code>main</code> or <code>wmain</code>. If it uses a unicode interface, it will get the true unicode characters (even if it cannot displays them and only displays <code>?</code>) and as such will open the correct file. But if it uses the so-called MBCS interface, characters with a code above 255 will be translated in true <code>?</code> (character code 0x63) and it will try to open a wrong file.</p> <p>The difference of behaviour simply proves that your git implementation is unicode compatible while you Python version (I assume 2.x) is not. Untested, but I think that Python 3 is natively Unicode compatible on Windows.</p> <p>Here is a small C program that demonstrates what happens:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;windows.h&gt; #include &lt;tchar.h&gt; int _tmain(int argc, LPTSTR argv[]) { int i; _tprintf(_T("Arguments")); for(i=0; i&lt;argc; i++) { _tprintf(_T(" &gt;%s&lt;"), argv[i]); } _tprintf(_T("\n")); if (argc &gt; 1) { LPCTSTR ix = argv[1]; _tprintf(_T("Dump param 1 :")); while (*ix != 0) { _tprintf(_T(" %c(%x)"), *ix, ((unsigned int) *ix) &amp; 0xffff); ix += 1; } _tprintf(_T("\n")); } return 0; } </code></pre> <p>If you call it (by pasting the <code>কাজ</code> characters in the console) as <code>cmdline কাজ</code>) you see:</p> <pre><code>...&gt;cmdline ab???cd Arguments &gt;cmdline&lt; &gt;ab???cd&lt; Dump param 1 : a(61) b(62) ?(3f) ?(3f) ?(3f) c(63) d(64) </code></pre> <p>when built in MBCS mode and</p> <pre><code>...&gt;cmdline ab???cd Arguments &gt;cmdline&lt; &gt;ab???cd&lt; Dump param 1 : a(61) b(62) ?(995) ?(9be) ?(99c) c(63) d(64) </code></pre> <p>when build in UNICODE mode (the 3 characters <code>কাজ</code> are respectively U+0995, U+09BE and U+099C in unicode)</p> <p>As the information is lost in the C run time code that processes the command line arguments, nothing can be done to recover it. So you can only pass to Python3 if you want to be able to use unicode names for your scripts.</p>
2
2016-07-22T09:45:22Z
[ "python", "git", "unicode" ]
click button on website using scrapy
38,521,864
<p>I want to ask how about (do crawling) clicking next button(change number page of website) (then do crawling more till the end of page number) from <a href="https://n0where.net/" rel="nofollow">this site</a> </p> <p>I've try to combining scrape with selenium,but its still error and says <code>"line 22 self.driver = webdriver.Firefox() ^ IndentationError: expected an indented block"</code></p> <p>I don't know why it happens, i think i code is so well.Anybody can resolve this problem?</p> <p><strong>This my source :</strong></p> <pre><code>from selenium import webdriver from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from now.items import NowItem class MySpider(BaseSpider): name = "nowhere" allowed_domains = ["n0where.net"] start_urls = ["https://n0where.net/"] def parse(self, response): for article in response.css('.loop-panel'): item = NowItem() item['title'] = article.css('.article-title::text').extract_first() item['link'] = article.css('.loop-panel&gt;a::attr(href)').extract_first() item['body'] ='' .join(article.css('.excerpt p::text').extract()).strip() #item['date'] = article.css('[itemprop="datePublished"]::attr(content)').extract_first() yield item def __init__(self): self.driver = webdriver.Firefox() def parse2(self, response): self.driver.get(response.url) while True: next = self.driver.find_element_by_xpath('/html/body/div[4]/div[3]/div/div/div/div/div[1]/div/div[6]/div/a[8]/span') try: next.click() # get the data and write it to scrapy items except: break self.driver.close()` </code></pre> <p><strong>This my capture of my program mate :</strong> <a href="http://i.stack.imgur.com/6Y1YC.png" rel="nofollow"><img src="http://i.stack.imgur.com/6Y1YC.png" alt="capture program"></a></p>
0
2016-07-22T08:38:32Z
38,522,107
<p>This is a indentation error. Look the lines near the error:</p> <pre><code> def parse2(self, response): self.driver.get(response.url) </code></pre> <p>The first of these two lines ends with a colon. So, the second line should be more indented than the first one.</p> <p>There are two possible fixes, depending on what you want to do. Either add an indentation level to the second one:</p> <pre><code> def parse2(self, response): self.driver.get(response.url) </code></pre> <p>Or move the <code>parse2 function out of the</code><strong>init</strong>` function:</p> <pre><code>def parse2(self, response): self.driver.get(response.url) def __init__(self): self.driver = webdriver.Firefox() # etc. </code></pre>
1
2016-07-22T08:49:20Z
[ "python", "selenium", "scrapy", "web-crawler" ]
click button on website using scrapy
38,521,864
<p>I want to ask how about (do crawling) clicking next button(change number page of website) (then do crawling more till the end of page number) from <a href="https://n0where.net/" rel="nofollow">this site</a> </p> <p>I've try to combining scrape with selenium,but its still error and says <code>"line 22 self.driver = webdriver.Firefox() ^ IndentationError: expected an indented block"</code></p> <p>I don't know why it happens, i think i code is so well.Anybody can resolve this problem?</p> <p><strong>This my source :</strong></p> <pre><code>from selenium import webdriver from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from now.items import NowItem class MySpider(BaseSpider): name = "nowhere" allowed_domains = ["n0where.net"] start_urls = ["https://n0where.net/"] def parse(self, response): for article in response.css('.loop-panel'): item = NowItem() item['title'] = article.css('.article-title::text').extract_first() item['link'] = article.css('.loop-panel&gt;a::attr(href)').extract_first() item['body'] ='' .join(article.css('.excerpt p::text').extract()).strip() #item['date'] = article.css('[itemprop="datePublished"]::attr(content)').extract_first() yield item def __init__(self): self.driver = webdriver.Firefox() def parse2(self, response): self.driver.get(response.url) while True: next = self.driver.find_element_by_xpath('/html/body/div[4]/div[3]/div/div/div/div/div[1]/div/div[6]/div/a[8]/span') try: next.click() # get the data and write it to scrapy items except: break self.driver.close()` </code></pre> <p><strong>This my capture of my program mate :</strong> <a href="http://i.stack.imgur.com/6Y1YC.png" rel="nofollow"><img src="http://i.stack.imgur.com/6Y1YC.png" alt="capture program"></a></p>
0
2016-07-22T08:38:32Z
38,525,624
<p>Ignoring the syntax and indentation errors you have an issue with your code logic in general.</p> <p>What you do is create webdriver and never use it. What your spider does here is:</p> <ol> <li>Create webdriver object.</li> <li>Schedule a request for every url in <code>self.start_urls</code>, in your case it's only one.</li> <li>Download it, make <code>Response</code> object and pass it to the <code>self.parse()</code></li> <li>Your parse method seems to find some xpaths and makes some items, so scrapy yields you some items that were found if any</li> <li>Done</li> </ol> <p>Your parse2 was never called and so your selenium webdriver was never used. </p> <p>Since you are not using scrapy to download anything in this case you can just override <code>start_requests()</code>(&lt;- that's where your spider starts) method of your spider to do the whole logic.</p> <p>Something like: </p> <pre><code>from selenium import webdriver import scrapy from scrapy import Selector class MySpider(scrapy.Spider): name = "nowhere" allowed_domains = ["n0where.net"] start_url = "https://n0where.net/" def start_requests(self): driver = webdriver.Firefox() driver.get(self.start_url) while True: next_url = driver.find_element_by_xpath( '/html/body/div[4]/div[3]/div/div/div/div/div[1]/div/div[6]/div/a[8]/span') try: # parse the body your webdriver has self.parse(driver.page_source) # click the button to go to next page next_url.click() except: break driver.close() def parse(self, body): # create Selector from html string sel = Selector(text=body) # parse it for article in sel.css('.loop-panel'): item = dict() item['title'] = article.css('.article-title::text').extract_first() item['link'] = article.css('.loop-panel&gt;a::attr(href)').extract_first() item['body'] = ''.join(article.css('.excerpt p::text').extract()).strip() # item['date'] = article.css('[itemprop="datePublished"]::attr(content)').extract_first() yield item </code></pre>
1
2016-07-22T11:44:35Z
[ "python", "selenium", "scrapy", "web-crawler" ]
DJANGO Trouble to inject the MultipleChoiceField initial value
38,522,040
<p>I've a form, clicking the button "info" from a table, i get the user information and inject into the form, all of this works as well, but not for the <strong>MultipleChoiceField</strong>:</p> <pre><code>data = {'name': name_surname[0], 'surname': name_surname[1], 'c02': retrieved.c02, 'dep': retrieved.dept_no, 'job': retrieved.job_code, 'location': retrieved.c03, 'fbd_role': retrieved.c04, 'team_id': TEAM_ID_RETRIEVED} form = RegForm(initial=data) form.set_readonly() return render(request, insert_form_address, {'form': form, 'action': 'info', 'pk': pk, 'profiles': profile_list}) </code></pre> <p>this is my view code, the one I use to fill the form with the user values, every field have been valued correctly with the initial value, but not the last one, team_id.</p> <p>An example of data to fill the team_id field is(This is the default list declared into the form):</p> <pre><code>TEAM_ID = {('POCM_A09', 'POCM_A09'), ('POCM_A11', 'POCM_A11'), ('POCM_A13', 'POCM_A13'), ('POCM_A15', 'POCM_A15'), ('POCM_A16', 'POCM_A16'), ('POCM_A18', 'POCM_A18')} </code></pre> <p>And let's suppose i want to init it with just some values, the ones related to that user (this list has beene passed to the init mode, it does not work, it still takes the default list..)</p> <pre><code>TEAM_ID_RETRIEVED = {('POCM_A09', 'POCM_A09')} </code></pre> <p>This is the form:</p> <pre><code>class RegForm(forms.Form): name = forms.CharField(label='Name', max_length=100) surname = forms.CharField(label='Surname', max_length=100) c02 = forms.CharField(label='AD ID', max_length=100) dep = CustomModelChoiceField(label='Department', queryset=Department.objects.all()) fbd_role = forms.ChoiceField(label='FBD Role', choices=FBD_ROLES, initial=None) location = forms.ChoiceField(label='Location', choices=LOCATION, initial=None) job = forms.ChoiceField(label='Job', choices=JOBS) ## Unable to pass a initial value for this field.. team_id= forms.MultipleChoiceField(label='Team', choices=TEAM_ID) action = None user_id = None def __init__(self, *args, **kwargs): self.user_id = kwargs.pop('pk', None) self.action = kwargs.pop('action', None) super(RegForm, self).__init__(*args, **kwargs) def set_readonly(self): for field in self.fields: self.fields[field].required = False self.fields[field].widget.attrs['disabled'] = 'disabled' </code></pre> <p>Any idea, i think should be something easy to fix... but i don't understand where is the problem...</p> <p><strong><em>For Tiny:</em></strong></p> <pre><code> data = {'name': name_surname[0], 'surname': name_surname[1], 'c02': retrieved.c02, 'dep': retrieved.dept_no, 'job': retrieved.job_code, 'location': retrieved.c03, 'fbd_role': retrieved.c04, 'team_id': 'POCM_A09'} form = RegForm(initial=data) </code></pre> <p>it always shows</p> <p><a href="http://i.stack.imgur.com/bv3Ue.png" rel="nofollow"><img src="http://i.stack.imgur.com/bv3Ue.png" alt="enter image description here"></a></p> <p>THANKS! :)</p>
0
2016-07-22T08:46:33Z
38,522,763
<p>You only need to set the values, like:</p> <pre><code>initial = { ... "team_id": ['POCM_A09', ...] # list of all the values selected ... } </code></pre> <p>As per our chat discussion I'm updating the answer. </p> <p>You can override the choices of the "<em>MultipleChoiceField</em>" inside form <code>__init__()</code> method. First pass your <code>new_choices</code> to the form, then:</p> <pre><code>def __init__(self, *args, **kwargs): new_choices = kwargs.pop('new_choices', None) super(FORM_NAME, self).__init__(*args, **kwargs) ... self.fields['team_id'].choices = new_choices ... </code></pre>
2
2016-07-22T09:20:51Z
[ "python", "django", "django-forms", "multiplechoicefield" ]
xml.etree.ElementTree.ParseError: not well-formed (invalid token) in Python
38,522,270
<p>I am trying to open an XML file using <code>ElementTree</code> but an error occurred: </p> <blockquote> <p>xml.etree.ElementTree.ParseError: not well-formed (invalid token)</p> </blockquote> <p>And here is my code:</p> <pre><code># -*- coding: utf-8 -*- import xml.etree.ElementTree as etree def main(): tree = etree.parse('test.xml') print 'parsing Success!' if __name__ == "__main__": main() </code></pre> <p>How can I fix this error?</p>
-1
2016-07-22T08:57:04Z
38,522,947
<p>The <a href="http://www.w3schools.com/xml/xml_syntax.asp" rel="nofollow">XML format rules</a> state that you have to have one root element. Your document has two of them, <code>pdml</code> and <code>packet</code>. I'm not familiar with PDML, but a XML parser probably will choke on that. </p>
0
2016-07-22T09:30:14Z
[ "python", "xml", "parsing", "elementtree" ]
xml.etree.ElementTree.ParseError: not well-formed (invalid token) in Python
38,522,270
<p>I am trying to open an XML file using <code>ElementTree</code> but an error occurred: </p> <blockquote> <p>xml.etree.ElementTree.ParseError: not well-formed (invalid token)</p> </blockquote> <p>And here is my code:</p> <pre><code># -*- coding: utf-8 -*- import xml.etree.ElementTree as etree def main(): tree = etree.parse('test.xml') print 'parsing Success!' if __name__ == "__main__": main() </code></pre> <p>How can I fix this error?</p>
-1
2016-07-22T08:57:04Z
38,523,033
<p>You are missing the closing <code>&lt;/pdml&gt;</code> tag at the end of the xml file.</p>
0
2016-07-22T09:34:07Z
[ "python", "xml", "parsing", "elementtree" ]
xml.etree.ElementTree.ParseError: not well-formed (invalid token) in Python
38,522,270
<p>I am trying to open an XML file using <code>ElementTree</code> but an error occurred: </p> <blockquote> <p>xml.etree.ElementTree.ParseError: not well-formed (invalid token)</p> </blockquote> <p>And here is my code:</p> <pre><code># -*- coding: utf-8 -*- import xml.etree.ElementTree as etree def main(): tree = etree.parse('test.xml') print 'parsing Success!' if __name__ == "__main__": main() </code></pre> <p>How can I fix this error?</p>
-1
2016-07-22T08:57:04Z
38,524,548
<p>Try to set the proper encoding ie:</p> <pre><code>etree.parse('test.xml', etree.XMLParser(encoding='utf-8')) </code></pre>
0
2016-07-22T10:48:01Z
[ "python", "xml", "parsing", "elementtree" ]
Remove empty sub plots in matplotlib figure
38,522,408
<p>How can I determine whether a subplot (<code>AxesSubplot</code>) is empty or not? I would like to deactivate empty axes of empty subplots and remove completely empty rows.</p> <p>For instance, in this figure only two subplots are filled and the remaining subplots are empty.</p> <pre><code>import matplotlib.pyplot as plt # create figure wit 3 rows and 7 cols; don't squeeze is it one list fig, axes = plt.subplots(3, 7, squeeze=False) x = [1,2] y = [3,4] # plot stuff only in two SubAxes; other axes are empty axes[0][1].plot(x, y) axes[1][2].plot(x, y) # save figure plt.savefig('image.png') </code></pre> <p>Note: It is mandatory to set <code>squeeze</code> to <code>False</code>.</p> <p>Basically I want a sparse figure. Some subplots in rows can be empty, but they should be deactivated (no axes must be visible). Completely empty rows must be removed and must not be set to invisible.</p>
0
2016-07-22T09:03:30Z
38,522,888
<p>One way of achieving what you require is to use matplotlibs <a href="http://matplotlib.org/users/gridspec.html" rel="nofollow">subplot2grid</a> feature. Using this you can set the total size of the grid (3,7 in your case) and choose to only plot data in certain subplots in this grid. I have adapted your code below to give an example:</p> <pre><code>import matplotlib.pyplot as plt x = [1,2] y = [3,4] fig = plt.subplots(squeeze=False) ax1 = plt.subplot2grid((3, 7), (0, 1)) ax2 = plt.subplot2grid((3, 7), (1, 2)) ax1.plot(x,y) ax2.plot(x,y) plt.show() </code></pre> <p>This gives the following graph:</p> <p><a href="http://i.stack.imgur.com/R8qxT.png" rel="nofollow"><img src="http://i.stack.imgur.com/R8qxT.png" alt="enter image description here"></a></p> <p><strong>EDIT:</strong></p> <p>Subplot2grid, in effect, does give you a list of axes. In your original question you use <code>fig, axes = plt.subplots(3, 7, squeeze=False)</code> and then use <code>axes[0][1].plot(x, y)</code> to specifiy which subplot your data will be plotted in. That is the same as what subplot2grid does, apart from it only shows the subplots with data in them which you have defined.</p> <p>So take <code>ax1 = plt.subplot2grid((3, 7), (0, 1))</code> in my answer above, here I have specified the shape of the 'grid' which is 3 by 7. That means I can have 21 subplots in that grid if I wanted, exactly like you original code. The difference is that your code displays all the subplots whereas subplot2grid does not. The <code>(3,7)</code> in <code>ax1 = ...</code> above specifies the shape of the whole grid and the <code>(0,1)</code> specifies where <strong>in</strong> that grid the subplot will be shown.</p> <p>You can use any position the subplot wherever you like within that 3x7 grid. You can also fill all 21 spaces of that grid with subplots that have data in them if you require by going all the way up to <code>ax21 = plt.subplot2grid(...)</code>.</p>
1
2016-07-22T09:27:06Z
[ "python", "matplotlib" ]
Can pandas with MySQL support text indexes?
38,522,513
<p>If I try to store a dataframe with a text index in a MySQL database I get the error "BLOB/TEXT column used in key specification without a key length", for example:</p> <pre><code>import pandas as pd import sqlalchemy as sa df = pd.DataFrame( {'Id': ['AJP2008H', 'BFA2010Z'], 'Date': pd.to_datetime(['2010-05-05', '2010-07-05']), 'Value': [74.2, 52.3]}) df.set_index(['Id', 'Date'], inplace=True) engine = sa.create_engine(db_connection) conn = engine.connect() df.to_sql('test_table_index', conn, if_exists='replace') conn.close() </code></pre> <p>Will generate the error:</p> <pre><code>InternalError: (pymysql.err.InternalError) (1170, "BLOB/TEXT column 'Id' used in key specification without a key length") [SQL: 'CREATE INDEX `ix_test_table_index_Id` ON test_table_index (`Id`)'] </code></pre> <p>If I don't set the index it works fine. Is there any way to store it without dropping directly down to SQLAlchemy to create the table first?</p> <p>(This is my current SQLAlchemy workaround:</p> <pre><code>table = Table( name, self.metadata, Column('Id', String(ID_LENGTH), primary_key=True), Column('Date', DateTime, primary_key=True), Column('Value', String(VALUE_LENGTH))) sa.MetaData().create_all(engine) # Creates the table if it doens't exist </code></pre> <p>)</p>
1
2016-07-22T09:08:53Z
38,524,884
<p>you can specify a <a href="http://docs.sqlalchemy.org/en/latest/core/type_basics.html" rel="nofollow">SQLAlchemy data type</a> explicitly, using <code>dtype</code> argument when calling <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html" rel="nofollow">to_sql()</a> method:</p> <pre><code>In [48]: from sqlalchemy.types import VARCHAR In [50]: df Out[50]: Value Id Date AJP2008H 2010-05-05 74.2 BFA2010Z 2010-07-05 52.3 In [51]: df.to_sql('test_table_index', conn, if_exists='replace', dtype={'Id': VARCHAR(df.index.get_level_values('Id').str.len().max())}) </code></pre> <p>Let's check it on the MySQL side:</p> <pre><code>mysql&gt; show create table test_table_index\G *************************** 1. row *************************** Table: test_table_index Create Table: CREATE TABLE `test_table_index` ( `Id` varchar(8) DEFAULT NULL, `Date` datetime DEFAULT NULL, `Value` double DEFAULT NULL, KEY `ix_test_table_index_Id` (`Id`), KEY `ix_test_table_index_Date` (`Date`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 1 row in set (0.00 sec) mysql&gt; select * from test_table_index; +----------+---------------------+-------+ | Id | Date | Value | +----------+---------------------+-------+ | AJP2008H | 2010-05-05 00:00:00 | 74.2 | | BFA2010Z | 2010-07-05 00:00:00 | 52.3 | +----------+---------------------+-------+ 2 rows in set (0.00 sec) </code></pre> <p>now let's read it back into a new DF:</p> <pre><code>In [52]: x = pd.read_sql('test_table_index', conn, index_col=['Id','Date']) In [53]: x Out[53]: Value Id Date AJP2008H 2010-05-05 74.2 BFA2010Z 2010-07-05 52.3 </code></pre> <p>you can find the maximum length of your object column this way:</p> <pre><code>In [75]: df.index.get_level_values('Id').str.len().max() Out[75]: 8 </code></pre>
1
2016-07-22T11:05:46Z
[ "python", "mysql", "pandas", "sqlalchemy" ]
How do I determine if current server time isn't within a specified range using Python ?
38,522,514
<p>I need to check in Python if the current time on the server isn't in the time range of 22:00PM - 04:00AM.</p> <p>What is the correct way to write this code ?</p> <p>Thanks !</p>
-1
2016-07-22T09:08:56Z
38,522,765
<p>Try this below:</p> <pre><code>import time def isWithinRange(): hour = time.localtime(time.time()).tm_hour return hour &gt;= 22 or hour &lt;= 4 </code></pre>
0
2016-07-22T09:20:55Z
[ "python" ]
RuntimeError: maximum recursion depth exceeded py2app
38,522,643
<p>I'm trying to create a standalone app using py2app 0.10 but a RuntimeError: maximum recursion depth exceeded error show creating my app. </p> <pre><code> File "build/bdist.macosx-10.5-x86_64/egg/modulegraph/modulegraph.py", line 947, in import_hook File "build/bdist.macosx-10.5-x86_64/egg/modulegraph/modulegraph.py", line 973, in _determine_parent File "build/bdist.macosx-10.5-x86_64/egg/modulegraph/modulegraph.py", line 872, in findNode File "build/bdist.macosx-10.5-x86_64/egg/altgraph/ObjectGraph.py", line 139, in findNode RuntimeError: maximum recursion depth exceeded </code></pre>
-1
2016-07-22T09:14:35Z
38,522,673
<p>You have not implemented a stop condition in your recursion function. Without your posting code I cannot answer much further. See the <a class='doc-link' href="http://stackoverflow.com/documentation/python/1716/recursion#t=201607220918022936079&amp;a=remarks">remarks</a> section of recursion.</p>
0
2016-07-22T09:16:00Z
[ "python", "py2app" ]
A Flask-WTF form that does not send an email when the user submit the form
38,522,725
<p>I decided to follow this tutorial(<a href="http://www.boxcontrol.net/adding-contact-form-to-your-site-using-flask-and-python3.html" rel="nofollow">https://www.boxcontrol.net/adding-contact-form-to-your-site-using-flask-and-python3.html</a>) but create a different type of form where the user inputs their personal information and the submitted form is emailed to my G-mail account. However after submitting the form I receivce no email or error.<br><br> The first thing I did was to create ContactForm class.</p> <pre><code>from flask_wtf import Form from wtforms import TextField, TextAreaField, SubmitField from wtforms.validators import InputRequired class ContactForm(Form): name = TextField("Fullname", validators=[InputRequired('Please enter your name.')]) email = TextField("Email", validators=[InputRequired("Please enter your email address.")]) NoChildren = TextField("Number of children dependants (if applicable):", validators=[InputRequired("Please enter a subject.")]) NoAdults = TextField("Number of adult dependants (if applicable):", validators=[InputRequired("Please enter a subject.")]) travel = TextField("Will you be travelling alone?", validators=[InputRequired("Please enter a subject.")]) marriage = TextField("What is your marital status?", validators=[InputRequired("Please enter a subject.")]) nation = TextField("Current nationality(ies):", validators=[InputRequired("Please enter a subject.")]) dob = TextField("Date of birth:", validators=[InputRequired("Please enter a subject.")]) phone = TextField("Phone number:", validators=[InputRequired("Please enter a subject.")]) nonukaddress = TextField("Your current non-UK address:", validators=[InputRequired("Please enter a subject.")]) ukaddress = TextField("UK address:", validators=[InputRequired("Please enter a subject.")]) history = TextField("Do you have any criminal history?", validators=[InputRequired("Please enter a subject.")]) hadvisa = TextField("Have you ever had any other visas?", validators=[InputRequired("Please enter a subject.")]) refusevisa = TextField("Have you been refused a visa before?", validators=[InputRequired("Please enter a subject.")]) medical = TextField("Did you receive any medical treatment in the UK?", validators=[InputRequired("Please enter a subject.")]) letter = TextField("Do you have a letter from a UK regulated financial institution confirming that original evidence of funds has been supplied?", validators=[InputRequired("Please enter a subject.")]) sole = TextField("Are you the sole owner of the money?", validators=[InputRequired("Please enter a subject.")]) additional = TextAreaField("Additional information/questions/requests:", validators=[InputRequired("Please enter a message.")]) submit = SubmitField("Send") </code></pre> <p>Then I created the HTML template for my form.</p> <pre><code>{% block content %} &lt;h2&gt;Contact&lt;/h2&gt; {% if success %} &lt;p&gt;Thank you for your message. We'll get back to you shortly.&lt;/p&gt; {% else %} {% for message in form.name.errors %} &lt;div class="flash"&gt;{{ message }}&lt;/div&gt; {% endfor %} {% for message in form.email.errors %} &lt;div class="flash"&gt;{{ message }}&lt;/div&gt; {% endfor %} &lt;form action="{{ url_for('contact') }}" method=post&gt; {{ form.hidden_tag() }} {{ form.name.label }} {{ form.name }} {{ form.email.label }} {{ form.email }} {{ form.NoChildren.label }} {{ form.NoChildren }} {{ form.travel.label }} {{ form.travel }} {{ form.marriage.label }} {{ form.marriage }} {{ form.nation.label }} {{ form.nation }} {{ form.dob.label }} {{ form.dob }} {{ form.phone.label }} {{ form.phone }} {{ form.nonukaddress.label }} {{ form.nonukaddress }} {{ form.ukaddress.label }} {{ form.ukaddress }} {{ form.history.label }} {{ form.history }} {{ form.hadvisa.label }} {{ form.hadvisa }} {{ form.refusevisa.label }} {{ form.refusevisa }} {{ form.parents.label }} {{ form.parents }} {{ form.medical.label }} {{ form.medical }} {{ form.letter.label }} {{ form.letter }} {{ form.sole.label }} {{ form.sole }} {{ form.ukbank.label }} {{ form.ukbank }} {{ form.additional.label }} {{ form.additional }} {{ form.submit }} &lt;/form&gt; {% endif %} {% endblock %} </code></pre> <p>My main flask file looks like this.</p> <pre><code>from flask import Flask, render_template, request, flash from forms import ContactForm from flask_mail import Message, Mail import os mail = Mail() app = Flask(__name__) app.secret_key = 'development key' app.config["MAIL_SERVER"] = "smtp.gmail.com" app.config["MAIL_PORT"] = 465 app.config["MAIL_USE_SSL"] = True app.config["MAIL_USERNAME"] = 'your_email@example.com' app.config["MAIL_PASSWORD"] = '*******' mail.init_app(app) @app.route('/') def index(): return render_template('index.html') @app.route('/contact', methods=['GET', 'POST']) def contact(): form = ContactForm() if request.method == 'POST': if form.validate() == False: flash('All fields are required.') return render_template('contact.html', form=form) else: msg = Message(form.subject.data, sender='contact@example.com', recipients=['your_email@example.com']) msg.body = """ From:%s &lt;%s&gt;, %s """ % (form.name.data, form.email.data, form.message.data,form.NoChildren.data,form.travel.data,form.marriage.data, form.nation.data, form.dob.data, form.phone.data, form.nonukaddress.data, form.ukaddress.data, form.history.data, form.hadvisa.data, form.refusevisa.data, form.parents.data, form.medical.data, form.letter.data, form.sole.data, form.ukbank.data, form.additional.data) mail.send(msg) return render_template('contact.html', success=True) elif request.method == 'GET': return render_template('contact.html', form=form) if __name__ == '__main__': app.run() </code></pre>
0
2016-07-22T09:18:26Z
38,526,740
<p>Break the problem down— at the moment you have a lot of moving parts. If you're not getting an error, my initial thought would be that your emails are getting sent to junk/spam.</p> <p>If you create a new view that just sends a static email, does it work?</p> <pre><code>@app.route('/testemail') def send_test_email(): msg = Message('Title',sender='you@yours.com', recipients=['you@yours.com']) msg.body('Hello...') mail.send(msg) </code></pre> <p>If it doesn't-- then you know the problem relates to your email side of your code, then you can start looking into the <code>MAIL_DEBUG</code> options available in <code>Flask-Mail</code>, checking spam folders etc.</p> <p>Generally you might find it easier and more reliable to use services like that handle email delivery for you, rather then sending SMTP requests yourself, you use their Python library to send them your email data, then they take care of the rest. I personally use <a href="https://sendgrid.com/" rel="nofollow">Sendgrid</a> but there are a myriad of companies that provide a similar service.</p>
0
2016-07-22T12:41:48Z
[ "python", "flask", "flask-wtforms" ]
A Flask-WTF form that does not send an email when the user submit the form
38,522,725
<p>I decided to follow this tutorial(<a href="http://www.boxcontrol.net/adding-contact-form-to-your-site-using-flask-and-python3.html" rel="nofollow">https://www.boxcontrol.net/adding-contact-form-to-your-site-using-flask-and-python3.html</a>) but create a different type of form where the user inputs their personal information and the submitted form is emailed to my G-mail account. However after submitting the form I receivce no email or error.<br><br> The first thing I did was to create ContactForm class.</p> <pre><code>from flask_wtf import Form from wtforms import TextField, TextAreaField, SubmitField from wtforms.validators import InputRequired class ContactForm(Form): name = TextField("Fullname", validators=[InputRequired('Please enter your name.')]) email = TextField("Email", validators=[InputRequired("Please enter your email address.")]) NoChildren = TextField("Number of children dependants (if applicable):", validators=[InputRequired("Please enter a subject.")]) NoAdults = TextField("Number of adult dependants (if applicable):", validators=[InputRequired("Please enter a subject.")]) travel = TextField("Will you be travelling alone?", validators=[InputRequired("Please enter a subject.")]) marriage = TextField("What is your marital status?", validators=[InputRequired("Please enter a subject.")]) nation = TextField("Current nationality(ies):", validators=[InputRequired("Please enter a subject.")]) dob = TextField("Date of birth:", validators=[InputRequired("Please enter a subject.")]) phone = TextField("Phone number:", validators=[InputRequired("Please enter a subject.")]) nonukaddress = TextField("Your current non-UK address:", validators=[InputRequired("Please enter a subject.")]) ukaddress = TextField("UK address:", validators=[InputRequired("Please enter a subject.")]) history = TextField("Do you have any criminal history?", validators=[InputRequired("Please enter a subject.")]) hadvisa = TextField("Have you ever had any other visas?", validators=[InputRequired("Please enter a subject.")]) refusevisa = TextField("Have you been refused a visa before?", validators=[InputRequired("Please enter a subject.")]) medical = TextField("Did you receive any medical treatment in the UK?", validators=[InputRequired("Please enter a subject.")]) letter = TextField("Do you have a letter from a UK regulated financial institution confirming that original evidence of funds has been supplied?", validators=[InputRequired("Please enter a subject.")]) sole = TextField("Are you the sole owner of the money?", validators=[InputRequired("Please enter a subject.")]) additional = TextAreaField("Additional information/questions/requests:", validators=[InputRequired("Please enter a message.")]) submit = SubmitField("Send") </code></pre> <p>Then I created the HTML template for my form.</p> <pre><code>{% block content %} &lt;h2&gt;Contact&lt;/h2&gt; {% if success %} &lt;p&gt;Thank you for your message. We'll get back to you shortly.&lt;/p&gt; {% else %} {% for message in form.name.errors %} &lt;div class="flash"&gt;{{ message }}&lt;/div&gt; {% endfor %} {% for message in form.email.errors %} &lt;div class="flash"&gt;{{ message }}&lt;/div&gt; {% endfor %} &lt;form action="{{ url_for('contact') }}" method=post&gt; {{ form.hidden_tag() }} {{ form.name.label }} {{ form.name }} {{ form.email.label }} {{ form.email }} {{ form.NoChildren.label }} {{ form.NoChildren }} {{ form.travel.label }} {{ form.travel }} {{ form.marriage.label }} {{ form.marriage }} {{ form.nation.label }} {{ form.nation }} {{ form.dob.label }} {{ form.dob }} {{ form.phone.label }} {{ form.phone }} {{ form.nonukaddress.label }} {{ form.nonukaddress }} {{ form.ukaddress.label }} {{ form.ukaddress }} {{ form.history.label }} {{ form.history }} {{ form.hadvisa.label }} {{ form.hadvisa }} {{ form.refusevisa.label }} {{ form.refusevisa }} {{ form.parents.label }} {{ form.parents }} {{ form.medical.label }} {{ form.medical }} {{ form.letter.label }} {{ form.letter }} {{ form.sole.label }} {{ form.sole }} {{ form.ukbank.label }} {{ form.ukbank }} {{ form.additional.label }} {{ form.additional }} {{ form.submit }} &lt;/form&gt; {% endif %} {% endblock %} </code></pre> <p>My main flask file looks like this.</p> <pre><code>from flask import Flask, render_template, request, flash from forms import ContactForm from flask_mail import Message, Mail import os mail = Mail() app = Flask(__name__) app.secret_key = 'development key' app.config["MAIL_SERVER"] = "smtp.gmail.com" app.config["MAIL_PORT"] = 465 app.config["MAIL_USE_SSL"] = True app.config["MAIL_USERNAME"] = 'your_email@example.com' app.config["MAIL_PASSWORD"] = '*******' mail.init_app(app) @app.route('/') def index(): return render_template('index.html') @app.route('/contact', methods=['GET', 'POST']) def contact(): form = ContactForm() if request.method == 'POST': if form.validate() == False: flash('All fields are required.') return render_template('contact.html', form=form) else: msg = Message(form.subject.data, sender='contact@example.com', recipients=['your_email@example.com']) msg.body = """ From:%s &lt;%s&gt;, %s """ % (form.name.data, form.email.data, form.message.data,form.NoChildren.data,form.travel.data,form.marriage.data, form.nation.data, form.dob.data, form.phone.data, form.nonukaddress.data, form.ukaddress.data, form.history.data, form.hadvisa.data, form.refusevisa.data, form.parents.data, form.medical.data, form.letter.data, form.sole.data, form.ukbank.data, form.additional.data) mail.send(msg) return render_template('contact.html', success=True) elif request.method == 'GET': return render_template('contact.html', form=form) if __name__ == '__main__': app.run() </code></pre>
0
2016-07-22T09:18:26Z
38,596,163
<p>If you are not receiving any errors and no email is being sent, set <code>MAIL_DEBUG=True</code>. Flask-Mail uses the <code>smtplib</code> module which can <a href="https://github.com/mattupstate/flask-mail/blob/master/flask_mail.py#L153" rel="nofollow">set</a> debug level. Also try updating <code>config</code> before initializing mail.</p> <pre><code>app = Flask(__name__) app.config.update(dict( DEBUG = True, MAIL_SERVER = 'smtp.gmail.com', MAIL_PORT = 587, MAIL_USE_TLS = True, MAIL_USE_SSL = False, MAIL_USERNAME = 'my_username@gmail.com', MAIL_PASSWORD = 'my_password', )) mail = Mail(app) </code></pre> <p>See <a href="http://flask.pocoo.org/snippets/85/" rel="nofollow">this</a>.</p>
0
2016-07-26T17:17:20Z
[ "python", "flask", "flask-wtforms" ]
Error Code 1 While Loading Python Pillow Module
38,522,811
<p>I'm using python 3.6 64 bit. The python installation went down with no problem. But when I try to install pillow module using command prompt I get the "error 1". I googled It and couldn't find any explanations on this issue on windows. A youtube video shortly referred to it as "This issue is common if you're using windows 64bit your visual studio might not be up to date, but It's your problem." So I couldn't find a solution. Here are the screenshots of my command prompt.Can anyone help me with this problem? Thanks!</p> <p><a href="http://i.stack.imgur.com/Twenw.png" rel="nofollow"><img src="http://i.stack.imgur.com/Twenw.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/burak.png" rel="nofollow"><img src="http://i.stack.imgur.com/burak.png" alt="enter image description here"></a></p>
0
2016-07-22T09:23:18Z
38,523,055
<p>Try to <code>-- disable-</code> with installation.<br> And add to disable all traceback errors that You see in console. for example: <code>pip install Pillow --disable-zlib</code> and so on. I`m not installed Pillow on Windows. You can try just to install Anaconda 3.</p>
0
2016-07-22T09:35:29Z
[ "python", "pillow" ]
How to print color box on the console in python?
38,522,909
<p>I want to plot HeatMap on the console. For that purpose I want to plot small boxex of different colors i.e | | this size. I got different color Unicode symbols to plot HeatMap on the console but they are not working good. whenever I'm printing color on the 1st line it gets reflected on the 2nd line also. </p> <p><strong>I have following Unicode's-</strong> </p> <pre><code>'\033[0;37;40m ' '\033[0;37;46m ' '\033[0;37;44m ' '\033[0;37;45m ' '\033[0;37;42m ' '\033[48;5;226m ' '\033[48;5;214m ' '\033[48;5;202m ' '\033[48;5;196m ' '\033[0;37;41m ' </code></pre> <p><strong>program-code-</strong></p> <pre><code>print('\033[0;37;40m ') print 'hello' </code></pre> <p>Whenever I'm trying to print some text between color code It get fetched. Anyone have any Idea about How I can plot a different colors of empty box i.e. only color not text on the python console in a efficient way?</p>
0
2016-07-22T09:28:18Z
38,523,272
<p>That's not "unicode", they're called <a href="https://en.wikipedia.org/wiki/ANSI_escape_code" rel="nofollow">ANSI escape codes</a>.</p> <p>For your purpose, you can print a space character with a modified background color, and don't forget to set the colors back to normal afterwards (with <code>\033[0m</code>):</p> <pre><code>print('\033[;41m ') print('\033[0mhello') </code></pre> <p>A list of colors can be found <a href="https://en.wikipedia.org/wiki/ANSI_escape_code#Colors" rel="nofollow">here</a>. 42 would be green, 43 would be yellow, etc.</p>
0
2016-07-22T09:46:16Z
[ "python", "unicode", "colors", "console" ]
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
38,522,939
<p>I cannot request a popular SSL site without geting the error <code>[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed</code>.</p> <p>The requests <a href="http://docs.python-requests.org/en/master/user/advanced/" rel="nofollow">documentation</a> states that</p> <blockquote> <p>By default Requests bundles a set of root CAs that it trusts, sourced from the Mozilla trust store. However, these are only updated once for each Requests version. This means that if you pin a Requests version your certificates can become extremely out of date.</p> </blockquote> <p>As this is a popular site it should be in the store when I use <code>verify=True</code>, however it keeps failing. I have also tried with other SSL addresses and it also fails with this error.</p> <pre><code>import requests headers = { 'User-agent': 'Mozilla/5.0' } proxies = { 'http' : 'http://1.2.3.4:80', 'https' : 'http://1.2.3.4:443' } r = requests.get('https://www.example.com', proxies=proxies, verify=True) </code></pre> <p>Note that <a href="https://www.example.com" rel="nofollow">https://www.example.com</a> is a popular UK news website, so it should be in the CA store.</p> <p><strong>Python Version:</strong> Python 2.7.11</p> <p><strong>Requests Version:</strong> requests (2.10.0)</p> <p><strong>OS:</strong> Windows 8</p> <p>Am I doing something fundamentally wrong?</p>
1
2016-07-22T09:29:52Z
38,523,433
<pre><code>r = requests.get('https://www.example.com', proxies=proxies, verify=False) </code></pre> <p>Change this line and it will work.</p>
-2
2016-07-22T09:54:38Z
[ "python", "http", "ssl", "https", "python-requests" ]
Fastest way to query huge list in mongodb
38,523,087
<p>I want to get details of large set of users from mongodb. The user list is of more than 100 thousands. As mongodb dose not support very huge data query in one go. I want to know which is the best way to get the data.</p> <ol> <li>Divide list in groups and get data</li> </ol> <blockquote> <p><em>groups_of_list contains list of userId with bunches of 10000</em></p> <pre><code>for group in groups_of_list: curr_data = db.collection.find({'userId': {'$in': group}}) data.append(curr_data) </code></pre> </blockquote> <ol start="2"> <li>Loop over collection</li> </ol> <blockquote> <pre><code>for doc in db.collection.find({}): if i['userId'] in set_of_userIds: data.append(doc) </code></pre> </blockquote> <p>I want to get the fasted method.</p> <p>If there is any better method/way, please point it out.</p>
0
2016-07-22T09:37:15Z
38,593,449
<p>IMHO you should probably separate into "reasonable sized" chunks as in the method 1 you pointed out, not so much for Mongo's limitations, but for your own machine's memory limitations.</p> <p>It should probably be something like this:</p> <pre><code>def get_user_slice_data(groups_of_list): for group in groups_of_list: yield list(db.collection.find({'userId': {'$in': group}})) </code></pre> <p>This generator function can be used like this:</p> <pre><code>for use_slice_data in get_user_slice_data(groups_of_list): # do stuff </code></pre> <p>By doing this, you will be both avoiding having a big amount of data in memory, and reducing the size of the Mongo transaction as well.</p> <p>pd: you should probably consider adding an index on 'userId' first, like:</p> <pre><code>db.collection.ensure_index('userId') </code></pre>
1
2016-07-26T15:01:30Z
[ "python", "mongodb", "performance", "search", "pymongo" ]
Fastest way to query huge list in mongodb
38,523,087
<p>I want to get details of large set of users from mongodb. The user list is of more than 100 thousands. As mongodb dose not support very huge data query in one go. I want to know which is the best way to get the data.</p> <ol> <li>Divide list in groups and get data</li> </ol> <blockquote> <p><em>groups_of_list contains list of userId with bunches of 10000</em></p> <pre><code>for group in groups_of_list: curr_data = db.collection.find({'userId': {'$in': group}}) data.append(curr_data) </code></pre> </blockquote> <ol start="2"> <li>Loop over collection</li> </ol> <blockquote> <pre><code>for doc in db.collection.find({}): if i['userId'] in set_of_userIds: data.append(doc) </code></pre> </blockquote> <p>I want to get the fasted method.</p> <p>If there is any better method/way, please point it out.</p>
0
2016-07-22T09:37:15Z
38,596,872
<p>You can use cursors with fixed limit and iterate over the results using the cursor. You can find more info here - <a href="https://docs.mongodb.com/v3.2/tutorial/iterate-a-cursor/" rel="nofollow">https://docs.mongodb.com/v3.2/tutorial/iterate-a-cursor/</a></p> <p>But actual code implementation depends on the language you are using. If it's Spring, Java application for example you can use Pageable request, something like </p> <pre><code>Pageable pageable = new PageRequest(0, 50); Query query = new Query(); query.with(pageable); mongoTemplate.find(query, User.class); //get the next page pageable = pageable.next(); </code></pre> <p>Though, do keep in mind that if you are updating your data as you are iterating over it, it could give inconsistent results. So, in that case you have to do a query using snapshot. <a href="https://docs.mongodb.com/manual/reference/method/cursor.snapshot/" rel="nofollow">https://docs.mongodb.com/manual/reference/method/cursor.snapshot/</a></p> <p>Hope it helps!</p>
0
2016-07-26T17:59:59Z
[ "python", "mongodb", "performance", "search", "pymongo" ]
implement of siftdown function violates heap formal definition?
38,523,099
<p>I am trying to understand the implementation of heap right now, and I look into heapq module of python.<br/> <a href="https://github.com/python-git/python/blob/master/Lib/heapq.py" rel="nofollow">https://github.com/python-git/python/blob/master/Lib/heapq.py</a> <br/> Line236 is the start of the code of siftdown, the strange thing is, it looks like a siftup to me, because it adds a newitem on the last element of the heap array and tries to move the last element upward to its proper position.<br/></p> <pre><code>while pos &gt; startpos: parentpos = (pos - 1) &gt;&gt; 1 parent = heap[parentpos] if newitem &lt; parent: heap[pos] = parent pos = parentpos continue break </code></pre> <p>It reduces the index of the current position to (pos-1)//2 and finally the pos may go to index 0. So it looks like a siftup to me. Do I misunderstand something?</p>
0
2016-07-22T09:37:48Z
38,595,477
<p>It's just a nomenclature clash. What they call "siftup" is sifting towards the leaves. Perhaps the thinking is that in a min-heap, larger items move "up" towards the leaves.</p> <p>Their "siftdown" moves towards the root.</p> <p>It's upside-down from what we computer people normally (?) think of as a tree, but it's consistent. And it makes sense if you picture a physical tree--the thing that grows in the yard and in autumn drops leaves that I have to rake up and dispose of.</p>
1
2016-07-26T16:39:51Z
[ "python", "heap" ]
regular expression is_fraction : Python : regex
38,523,110
<p>please help me with this:</p> <p>Is Fraction</p> <p>Create a function is_fraction that accepts a string and returns True if the string represents a fraction.</p> <p>By our definition a fraction consists of:</p> <p>An optional - character Followed by 1 or more digits Followed by a / Followed by 1 or more digits, at least one of which is non-zero (the denominator cannot be the number 0).</p> <p>Tip</p> <p>Modify the is_fraction function in the validation module.</p> <p>Your function should work like this:</p> <pre><code>&gt;&gt;&gt; is_fraction("") False &gt;&gt;&gt; is_fraction("5000") False &gt;&gt;&gt; is_fraction("-999/1") True &gt;&gt;&gt; is_fraction("+999/1") False &gt;&gt;&gt; is_fraction("00/1") True &gt;&gt;&gt; is_fraction("/5") False &gt;&gt;&gt; is_fraction("5/0") False &gt;&gt;&gt; is_fraction("5/010") True &gt;&gt;&gt; is_fraction("5/105") True &gt;&gt;&gt; is_fraction("5 / 1") False </code></pre> <p>This is what I've got so far:</p> <pre><code>def is_fraction(string): """Return True iff the string represents a valid fraction.""" return bool(re.search(r'^-?[0-9]+\/[0-9]+$', string)) </code></pre>
-1
2016-07-22T09:38:09Z
38,523,361
<p>Right, you need your denominator to be a sequence of digits, at least one of which is not <code>0</code>. This can be modeled using the regex <code>0*[1-9][0-9]*</code></p> <p>So your validation method now becomes:</p> <pre><code>def is_fraction(string): """Return True iff the string represents a valid fraction.""" return bool(re.search(r'^-?[0-9]+/0*[1-9][0-9]*$', string)) </code></pre>
2
2016-07-22T09:51:02Z
[ "python", "regex" ]
Pandas: sum if columns values coincides
38,523,193
<p>I'm trying to do an, apparently, simple operation in python:</p> <p>I have some datasets, say 6, and I want to sum the values of one column if the values of the other two columns coincides. After that, I want to divide the values of the column which has been summed by the number of datasets I have, in this case, 6 (i.e. Calculate the arithmetic mean). Also I want to sum 0 if the values of the other columns doesn't coincide.</p> <p>I write down here two dataframes, as example:</p> <p><code>Code1 Code2 Distance 0 15.0 15.0 2 1 15.0 60.0 3 2 15.0 69.0 2 3 15.0 434.0 1 4 15.0 842.0 0</code></p> <p><code>Code1 Code2 Distance 0 14.0 15.0 4 1 14.0 60.0 7 2 15.0 15.0 0 3 15.0 60.0 1 4 15.0 69.0 9</code></p> <p>The first column is the df.index column. Then , I want to sum 'Distance' column only if 'Code1' and 'Code2' columns coincide. In this case the desired output would be something like:</p> <p><code>Code1 Code2 Distance 0 14.0 15.0 2 1 14.0 60.0 3.5 2 15.0 15.0 1 3 15.0 60.0 2 4 15.0 69.0 5.5 5 15.0 434.0 0.5 6 15.0 842.0 0 </code></p> <p>I've tried to do this using conditionals, but for more than two df is really hard to do. Is there any method in Pandas to do it faster? </p> <p>Any help would be appreciated :-)</p>
0
2016-07-22T09:42:17Z
38,526,272
<p>You could put all your data frames in a list and then use <code>reduce</code> to either <code>append</code> or <code>merge</code> them all. Take a look at reduce <a href="https://docs.python.org/2/library/functions.html#reduce" rel="nofollow">here</a>.</p> <p>First, below some functions are defined for sample data generation.</p> <pre><code>import pandas import numpy as np # GENERATE DATA # Code 1 between 13 and 15 def generate_code_1(n): return np.floor(np.random.rand(n,1) * 3 + 13) # Code 2 between 1 and 1000 def generate_code_2(n): return np.floor(np.random.rand(n,1) * 1000) + 1 # Distance between 0 and 9 def generate_distance(n): return np.floor(np.random.rand(n,1) * 10) # Generate a data frame as hstack of 3 arrays def generate_data_frame(n): data = np.hstack([ generate_code_1(n) ,generate_code_2(n) ,generate_distance(n) ]) df = pandas.DataFrame(data=data, columns=['Code 1', 'Code 2', 'Distance']) # Remove possible duplications of Code 1 and Code 2. Take smallest distance in case of duplications. # Duplications will break merge method however will not break append method df = df.groupby(['Code 1', 'Code 2'], as_index=False) df = df.aggregate(np.min) return df # Generate n data frames each with m rows in a list def generate_data_frames(n, m, with_count=False): df_list = [] for k in range(0, n): df = generate_data_frame(m) # Add count column, needed for merge method to keep track of how many cases we have seen if with_count: df['Count'] = 1 df_list.append(df) return df_list </code></pre> <p>Append method (faster, shorter, nicer)</p> <pre><code>df_list = generate_data_frames(94, 5) # Append all data frames together using reduce df_append = reduce(lambda df_1, df_2 : df_1.append(df_2), df_list) # Aggregate by Code 1 and Code 2 df_append_grouped = df_append.groupby(['Code 1', 'Code 2'], as_index=False) df_append_result = df_append_grouped.aggregate(np.mean) df_append_result </code></pre> <p>Merge method</p> <pre><code>df_list = generate_data_frames(94, 5, with_count=True) # Function to be passed to reduce. Merge 2 data frames and update Distance and Count def merge_dfs(df_1, df_2): df = pandas.merge(df_1, df_2, on=['Code 1', 'Code 2'], how='outer', suffixes=('', '_y')) df = df.fillna(0) df['Distance'] = df['Distance'] + df['Distance_y'] df['Count'] = df['Count'] + df['Count_y'] del df['Distance_y'] del df['Count_y'] return df # Use reduce to apply merge over the list of data frames df_merge_result = reduce(merge_dfs, df_list) # Replace distance with its mean and drop Count df_merge_result['Distance'] = df_merge_result['Distance'] / df_merge_result['Count'] del df_merge_result['Count'] df_merge_result </code></pre>
1
2016-07-22T12:19:57Z
[ "python", "pandas" ]
Python Crash Course : Using int() to accept numerical input
38,523,285
<p>i am new to programming. According to my book, this code should get an error. </p> <pre><code>&gt;&gt;&gt; age = input("How old are you? ") How old are you? 21 &gt;&gt;&gt; age &gt;= 18 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; vTypeError: unorderable types: str() &gt;= int() </code></pre> <p>In Sublime i saved a .py file:<a href="http://i.stack.imgur.com/FbCch.png" rel="nofollow">This is my .py file.</a></p> <p>Then , in the terminal when i tried running it. It did not give me an error. First time , i ran it by entering the age 21 without the quots , it returned True. Then , i entered 17 , it returned False. </p> <p><strong>Firstly , How does my computer know that they are integers? I did not enter age=int(age).</strong></p> <p>Secondly when i input "21", its returning True. No error. Why is that happening?</p> <p><strong>How is it comparing a string and an integer?</strong><br> and when i input "17" as my age, it returned True again . **Why is that happening?</p> <p>It is not only comparing a sting and an integer but giving the wrong answer also this time.** </p> <p><a href="http://i.stack.imgur.com/LH1U4.png" rel="nofollow">This is the screenshot of my terminal window</a></p> <p><a href="http://i.stack.imgur.com/806lP.png" rel="nofollow"><img src="http://i.stack.imgur.com/806lP.png" alt="This is the respective terminal window after i installed python 3"></a> <a href="http://i.stack.imgur.com/erkRd.png" rel="nofollow"><img src="http://i.stack.imgur.com/erkRd.png" alt="This is my new .py file after installing python 3."></a></p>
-5
2016-07-22T09:46:56Z
38,523,337
<p>You are using Python 2 and the book author is using Python 3.</p> <p>In Python 2 <code>input</code> tries to evaluate the entered value, so the string <code>'21'</code> actually becomes <code>21</code> as an <code>int</code>.</p> <p>As @Siddharth pointed out in the comments, <code>str &gt; int</code> will always evaluate to <code>True</code> in Python 2. In Python 3 it will raise the error that is mentioned in the book.</p>
2
2016-07-22T09:49:39Z
[ "python" ]
How to reload a Flask app each time it's accessed
38,523,303
<p>I have a flask app that is accessed using the <code>/get_data</code> endpoint and providing a number as an id (<code>127.0.0.1:55555/get_data=56</code>) </p> <pre><code>@app.route('/get_data=&lt;id&gt;') def get_vod_tree(id): ... return render_template('index.html') </code></pre> <p>It invokes a function that fetches some data under that id and creates one json file [static/data.json] with the collected data and then returns render_template('index.html').</p> <p>In the index.html there is a call to ../static/data_tree.js which in turn reads the json file and outputs a visualization in the browser using d3.js.</p> <p>When the app runs, I get the same output on the browser even when I use a different id and the json file changes. It only works if I reload the app and then access the url.</p> <p><strong>My question is:</strong> How can I make sure that multiple users get the different outputs according to the id or how can I reload the app when I hit the endpoint.</p> <p>Afterthought: If multiple users are using the app then there is only one file created each time</p>
0
2016-07-22T09:48:04Z
38,523,616
<p>If you set <code>app.run(debug=True)</code> in your test/dev environment, it will automatically reload your Flask app every time a code change happens.</p> <p>To reload the application when a static file changes, use the <code>extra_files</code> parameter. See <a href="http://werkzeug.pocoo.org/docs/0.10/serving/?highlight=run_simple#werkzeug.serving.run_simple" rel="nofollow">here</a>.</p> <p>Example code:</p> <pre><code>extra_dirs = ['directory/to/watch',] extra_files = extra_dirs[:] for extra_dir in extra_dirs: for dirname, dirs, files in os.walk(extra_dir): for filename in files: filename = path.join(dirname, filename) if path.isfile(filename): extra_files.append(filename) app.run(extra_files=extra_files) </code></pre> <p><a href="http://stackoverflow.com/a/9511655/4675937">Source</a></p>
0
2016-07-22T10:03:10Z
[ "python", "d3.js", "flask" ]
How to reload a Flask app each time it's accessed
38,523,303
<p>I have a flask app that is accessed using the <code>/get_data</code> endpoint and providing a number as an id (<code>127.0.0.1:55555/get_data=56</code>) </p> <pre><code>@app.route('/get_data=&lt;id&gt;') def get_vod_tree(id): ... return render_template('index.html') </code></pre> <p>It invokes a function that fetches some data under that id and creates one json file [static/data.json] with the collected data and then returns render_template('index.html').</p> <p>In the index.html there is a call to ../static/data_tree.js which in turn reads the json file and outputs a visualization in the browser using d3.js.</p> <p>When the app runs, I get the same output on the browser even when I use a different id and the json file changes. It only works if I reload the app and then access the url.</p> <p><strong>My question is:</strong> How can I make sure that multiple users get the different outputs according to the id or how can I reload the app when I hit the endpoint.</p> <p>Afterthought: If multiple users are using the app then there is only one file created each time</p>
0
2016-07-22T09:48:04Z
38,524,695
<p>Thanks for the answers. It helped getting to the bottom of this. It works now like this:</p> <pre><code>@app.after_request def apply_caching(response): response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate' return response </code></pre> <p>So by disabling the cache the application can treat each request as unique.</p>
1
2016-07-22T10:55:10Z
[ "python", "d3.js", "flask" ]
AttributeError: '_io.TextIOWrapper' object has no attribute 'reader'
38,523,325
<p>Couldn't get what wrong in the code, as <code>csv</code> module has a <code>csv.reader()</code> function as per <a href="https://docs.python.org/3.4/library/csv.html" rel="nofollow">the documentation</a>. But I am still getting this error:</p> <pre><code>Traceback (most recent call last): File "test_csv.py", line 4, in &lt;module&gt; read = csv.reader(csv, delimiter = ',') AttributeError: '_io.TextIOWrapper' object has no attribute 'reader' </code></pre> <p>My code:</p> <pre><code>import csv with open('test_csv.csv') as csv: read = csv.reader(csv, delimiter = ',') for row in read: print(row) </code></pre>
0
2016-07-22T09:49:19Z
38,523,398
<p>You re-bound the name <code>csv</code> in the <code>as</code> target:</p> <pre><code>with open('test_csv.csv') as csv: </code></pre> <p>This masks the module name, so <code>csv.reader</code> is resolved <em>on the file object</em>.</p> <p>Use a different target:</p> <pre><code>with open('test_csv.csv') as csvfile: read = csv.reader(csvfile, delimiter = ',') for row in read: print(row) </code></pre>
0
2016-07-22T09:52:52Z
[ "python", "csv" ]
Multiple condition in domain is not working - OpenERP 7 - Odoo
38,523,363
<p>I am trying to use multiple condition for my domain but I got this error:</p> <p>ValueError: Invalid leaf ('&amp;', ('A', '=', True), ('B', '=', False)</p> <p>I have no idea why. Everything looks well. I would like to have (A &amp; !B) OR (C &amp; !D )</p> <p>This is my code (OpenERP 7):</p> <pre><code> &lt;field name="domain"&gt;['|',('&amp;amp;',('A','=', True),('B','=', False)),('&amp;amp;',('C','!=', True),('D','=', False))]&lt;/field&gt; </code></pre> <p>What is wrong with my code? Some idea?</p>
0
2016-07-22T09:51:05Z
38,544,740
<p>You're using extra brackets. Prefix Notation (AKA Polish notation) is all about discarding necessity of brackets. You should use proper <a href="https://www.google.com/search?q=prefix%20notation" rel="nofollow">"prefix notation"</a> in condition statement. In order to correct a syntax, we have to remove extra brackets, so the above posted condition becomes <code>['|','&amp;amp;',('A','=', True),('B','=', False),'&amp;amp;',('C','!=', True),('D','=', False)]</code>. It'll solve the <code>Invalid leaf</code> error. See also my <a href="https://www.odoo.com/es_ES/forum/ayuda-1/question/how-to-write-a-domain-in-a-filter-solved-85100#answer-85108" rel="nofollow">answer to the similar question</a>.</p>
0
2016-07-23T17:40:32Z
[ "python", "xml", "openerp", "openerp-7" ]
Not able to install numpy or nltk python-modules
38,523,385
<p>I am having a strange issue installing numpy or nltk python-modules in my windows-7 machine. I have successfully installed Python 2.7.12 but I get this error when I type <code>pip install numpy</code> as in this <a href="http://i.stack.imgur.com/9KAI0.png" rel="nofollow">screenshot</a>. I have also included the directory of <code>pip.exe</code> in the <code>PATH</code>. Any help would be appreciated.Thank you :)</p>
0
2016-07-22T09:52:22Z
38,529,960
<p>Installing such these things in windows are sometime difficult, specially for someone new to python packages(also for some experts!)</p> <p>Try to use Anaconda for windows: <a href="https://www.continuum.io/downloads#_windows" rel="nofollow">https://www.continuum.io/downloads#_windows</a> This install a python for you and many requirement packages(e.g Numpy, Scipy, Scikit and many more)</p> <p>You can use older version of Anaconda, for python2.x if you want strictly python2.x</p> <hr> <p>An alternative way is to download Numpy from github and then install it as a python package, that contain setup.py file</p> <pre><code>python setup.py install </code></pre> <p>Or you can download Numpy wheel package, then install it localy with pip</p>
0
2016-07-22T15:14:30Z
[ "python", "windows", "numpy", "nltk" ]
How to put in a profile picture in django
38,523,456
<p>im following <a href="http://stackoverflow.com/questions/6396442/add-image-avatar-to-users-in-django">Add image/avatar to users in django</a> tip to have users upload their profile pictures, and to display the user's profile picture when a user log in.</p> <p><a href="http://stackoverflow.com/questions/28197051/adding-profile-picture-to-django-user">Adding profile picture to django user</a></p> <p>But for some reason, it comes with an error saying "Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form UserProfileForm needs updating."</p> <p>Is there anyway i can directly modify the django.contrib.auth.models's User model so that i can add only the profile picture and have it displayed on index.html?</p> <p>there is not a whole lot of information regarding this profile picture system.</p> <p>and it's only been days since i started learning about django and python.</p> <p>could anyone explain with examples, how i can achieve this?</p> <p>Thanks.</p> <p>(this is the forms.py that's implementing the tip above)</p> <pre><code>from django import forms from django.contrib.auth.models import User from django.contrib.auth import authenticate, get_user_model, login, logout class UserSignupForm(forms.ModelForm): email = forms.EmailField(label='Confirm Email') password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'username', 'email', 'password' ] def clean_email(self): email = self.cleaned_data.get('email') email_qs = User.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError("This email has already been registered") return email from django.core.files.images import get_image_dimensions from .models import UserProfile class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) #validate dimensions max_width = max_height = 100 if w &gt; max_width or h &gt; max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) #validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): raise forms.ValidationError(u'Please use a JPEG, ' 'GIF or PNG image.') #validate file size if len(avatar) &gt; (20 * 1024): raise forms.ValidationError( u'Avatar file size may not exceed 20k.') except AttributeError: """ Handles case when we are updating the user profile and do not supply a new avatar """ pass return avatar </code></pre>
0
2016-07-22T09:55:58Z
38,524,753
<p>Example: models.py:</p> <pre><code>class YouModel(models.Model): .............You field ................ user_avatar = models.ImageField((upload_to="You/media/uploads", blank=True) # You need to configure media in settings.py ........... You fields .............. class YouModelForm(ModelForm) class Meta: model = YouModel fields = ['user_avatar'] </code></pre> <p>views.py:</p> <p>from .models import YouModel, YouModelForm</p> <pre><code>def youfunc(request): youtemplate = YouModelForm() if request.method == POST: youform = YouModelForm(request.POST, request.FILES) if youform.is_valid(): youform.save() return HttpResponseRedirect('http://www.You.url') # or other youquery = .objects.order_by('user_avatar').last() return render(request, "YouProject/YouHtml.html", {'youtemplate': youtemplate, 'youquery': youquery}) </code></pre> <p>I tired to write. You need configure django and write first file upload from user. You can visit to my website and look and decide - this is what You want? my website <a href="http://www.webmamoffice.org/en" rel="nofollow">http://www.webmamoffice.org/en</a> and go to UperVote or <a href="http://www.webmamoffice.org/en/upervote" rel="nofollow">http://www.webmamoffice.org/en/upervote</a></p>
2
2016-07-22T10:58:31Z
[ "python", "django" ]
Invalid operator '$size' in aggregation
38,523,546
<p>I got the following piece of code: </p> <pre><code>from pymongo import MongoClient client = MongoClient('ipOfServer') db = client.admin db.authenticate('login', 'password', source='admin_') heh = list(db.events.aggregate( [ {"$match": {"status": 'start'}}, {"$group": {"_id": "$eventName", "players": {"$addToSet": "$uid"}}}, {"$project": {"_id": 1, "Count": {"$size": "$players"}}} ])) print(heh) </code></pre> <p>and this is worked for the original programmer who wrote and tested it <a href="http://i.stack.imgur.com/zRiah.png" rel="nofollow">code result while testing</a>. But when I try to run it I'm getting this error:</p> <pre><code>pymongo.errors.OperationFailure: exception: invalid operator '$size' </code></pre> <p>I'm using mongo version 2.4.14 and python 2.7.12 with the sublime text editor. Could anyone suggest ways to solve this problem, it would be appreciated.</p>
0
2016-07-22T09:59:28Z
38,525,739
<p>The reason is because the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/size/" rel="nofollow"><code>$size</code></a> array aggregation operator is new in MongoDB 2.6 and you are actually running MongoDB 2.4. </p> <p>I suggest you upgrade your MongoDB server to at least 3.0. But if for some reason you don't want to upgrade now, you will need to <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/unwind" rel="nofollow"><code>$unwind</code></a> the "players" array and <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/group" rel="nofollow"><code>$group</code></a> by "_id" then return the count using the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sum" rel="nofollow"><code>$sum</code></a> accumulator operator.</p> <pre><code>heh = list(db.events.aggregate( [ {"$match": {"status": 'start'}}, {"$group": {"_id": "$eventName", "players": {"$addToSet": "$uid"}}}, {"$unwind": "$players"}, {"$group": {"_id": "$_id", "Count": {"$sum": 1}}}, ])) </code></pre>
0
2016-07-22T11:50:02Z
[ "python", "mongodb", "pymongo", "aggregation-framework" ]
Tensorflow + Matplotlib animation
38,523,596
<p>I am trying to implement the Game of Life using tensorflow and use matplotlib.animation to depict the animation. Although the image gets displayed but it is not animating for some reason. Below is the code I am using:</p> <p>Ref: <a href="http://learningtensorflow.com/lesson8/" rel="nofollow">http://learningtensorflow.com/lesson8/</a></p> <p>IDE: Pycharm Community Edition</p> <p>I am passing blit=False in FuncAnimation as it is not working on Mac with blit=True</p> <pre><code>shape = (50, 50) initial_board = tf.random_uniform(shape, minval=0, maxval=2, dtype=tf.int32) board = tf.placeholder(tf.int32, shape=shape, name='board') def update_board(X): # Check out the details at: https://jakevdp.github.io/blog/2013/08/07/conways-game-of-life/ # Compute number of neighbours, N = convolve2d(X, np.ones((3, 3)), mode='same', boundary='wrap') - X # Apply rules of the game X = (N == 3) | (X &amp; (N == 2)) return X board_update = tf.py_func(update_board, [board], [tf.int32]) fig = plt.figure() if __name__ == '__main__': with tf.Session() as sess: initial_board_values = sess.run(initial_board) X = sess.run(board_update, feed_dict={board: initial_board_values})[0] def game_of_life(*args): A = sess.run(board_update, feed_dict={board: X})[0] plot.set_array(A) return plot, ani = animation.FuncAnimation(fig, game_of_life, interval=100, blit=False) plot = plt.imshow(X, cmap='Greys', interpolation='nearest') plt.show() </code></pre>
0
2016-07-22T10:01:44Z
38,532,102
<p>When you are displaying the image, you are displaying the static image not the animation. You need to remove this line, as stated in the tutorial:</p> <pre><code>plot = plt.imshow(X, cmap='Greys', interpolation='nearest') </code></pre> <p><code>Hint: you will need to remove the plt.show() from the earlier code to make this run!</code></p> <p>Hope that helps!</p>
0
2016-07-22T17:20:16Z
[ "python", "animation", "matplotlib", "tensorflow", "conways-game-of-life" ]
Slideshow of web pages (python)
38,523,633
<p>I'm trying to make a simple slideshow in Python to view 0.html, 1.html and 2.html with 3 seconds delay between them.</p> <p>The script below shows 0.html in 3 seconds, then I get a "Segmentation fault (core dumped)" error. Any ideas?</p> <p><strong>My code so far:</strong></p> <pre><code>#!/usr/bin/python import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * import urllib class Window(QWidget): def __init__(self, url, dur): super(Window, self).__init__() view = QWebView(self) layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(view) html = urllib.urlopen(url).read() view.setHtml(html) QTimer.singleShot(dur * 1000, self.close) def playWidget(url, dur): app = QApplication(sys.argv) window = Window(url, dur) window.showFullScreen() app.exec_() x = 0 while (x &lt; 3): page = "%s.html" % x playWidget(page , 3) x = x + 1 </code></pre>
0
2016-07-22T10:03:59Z
38,530,447
<p>You cannot create more than one <code>QApplication</code>, which is why your example dumps core. But in any case, it's a rather poor design if your program needs to create a whole new browser window to display each page. What you should do is load each new page into the same browser.</p> <p>Here's a re-write of your script that does that:</p> <pre><code>#!/usr/bin/python import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * import urllib class Window(QWidget): def __init__(self, urls, dur): super(Window, self).__init__() self.urls = urls self.duration = dur * 1000 self.view = QWebView(self) layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.view) self.nextUrl() def nextUrl(self): if self.urls: url = self.urls.pop(0) html = urllib.urlopen(url).read() self.view.setHtml(html) QTimer.singleShot(self.duration, self.nextUrl) else: self.close() def playWidget(urls, dur): app = QApplication(sys.argv) window = Window(urls, dur) window.showFullScreen() app.exec_() urls = [ 'https://tools.ietf.org/html/rfc20', 'https://tools.ietf.org/html/rfc768', 'https://tools.ietf.org/html/rfc791', ] playWidget(urls, 3) </code></pre>
0
2016-07-22T15:37:45Z
[ "python", "pyqt4", "urllib", "sys" ]