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
list
TypeError: 'module' object is not callable in Spacy Python
39,318,400
<p>I want to print <code>Parse Tree</code> using <code>Spacy</code>. But the code below is giving the error </p> <blockquote> <p>en_nlp = spacy.language('English') TypeError: 'module' object is not callable</p> </blockquote> <p>The error is on this <code>en_nlp = spacy.loads('en')</code> line. I tried to shake off as <code>en_nlp = spacy.language(English)</code> by importing <code>from spacy.en import English</code> But still it is not working. Can someone help?</p> <p>Code: </p> <pre><code>import spacy from nltk import Tree en_nlp = spacy.loads('en') doc = en_nlp("The quick brown fox jumps over the lazy dog.") def to_nltk_tree(node): if node.n_lefts + node.n_rights &gt; 0: return Tree(node.orth_, [to_nltk_tree(child) for child in node.children]) else: return node.orth_ [to_nltk_tree(sent.root).pretty_print() for sent in doc.sents] </code></pre>
0
2016-09-04T15:14:25Z
39,318,532
<pre><code>Is it spacy.load('en') or spacy.loads('en') ? </code></pre> <p>The official doc <a href="https://spacy.io/docs/" rel="nofollow">https://spacy.io/docs/</a> says : spacy.load('en'). It may be the problem.</p>
0
2016-09-04T15:28:15Z
[ "python", "nlp", "spacy" ]
Error using Arabic Wordnet in nltk
39,318,499
<p>I am using NLTK Wordnet for Arabic language. When I run the following code :</p> <pre><code># -*- coding: UTF-8 -*- from nltk.corpus import wordnet as wn print wn.synsets('bank')[0].lemma_names('arb') print wn.synsets('ضِفَّة', lang='arb')0].hypernyms()0].lemma_names(lang='arb') #PROBLEM HERE </code></pre> <p>I get this error:</p> <pre><code>Traceback (most recent call last): File "nltk_wordnet.py", line 7, in &lt;module&gt; print wn.synsets('ضِفَّة', lang='arb')[0].hypernyms() [0].lemma_names(lang='arb') IndexError: list index out of range </code></pre>
0
2016-09-04T15:24:28Z
39,318,610
<p>Your code assumes that word <code>'ضِفَّة'</code> will find a conceptual relationship using <code>synsets</code> and that the first item in the set will have hypernym(s). That may not be true. You can instead check if the results returned are non-empty before <em>indexing</em>:</p> <pre><code>word_synsets = wn.synsets('ضِفَّة', lang='arb') if word_synsets: # False if word_synsets is an empty list word_hyp = word_synsets[0].hypernyms() if word_hyp: # False if word_hyp is an empty list print(word_hyp[0].lemma_names(lang='arb')) else: print('first item in ضِفَّة synset has no hypernym(s)') else: print('synset for ضِفَّة returned no result') </code></pre>
0
2016-09-04T15:35:35Z
[ "python", "nltk", "wordnet" ]
Python restFUL web service - routing to a specific function in a file
39,318,569
<p>I am implementing a simple API in python using werkzeug. I have created a simple application 'localhost'. I want to execute a function after a GET request. I am confused with URL routing. I have gone through <a href="http://werkzeug.pocoo.org/docs/0.11/routing/" rel="nofollow">this</a> tutorial and implemented routing but still can't figure out how to send a request to another file. Here is my code:</p> <pre><code>url_map = Map([ Rule('/spell', endpoint='spell_checker.py'), Rule('/he', endpoint='hello/test') ]) @Request.application def application(request): urls = url_map.bind_to_environ(environ) try: endpoint, args = urls.match() print(endpoint + " " + args) #urls.dispatch('test') except httplib.HTTPException, e: return e(environ, start_response) start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Rul1e points to %r with arguments %r' % (endpoint, args)] if __name__ == '__main__': from werkzeug.serving import run_simple run_simple('127.0.0.1', 4000, application) </code></pre> <p>I have another another in a file named hello.py in the same directory</p> <pre><code>def index(): print 'This is the test' </code></pre> <p>I want to call index function from URL like localhost:4000/hello which will call the index function of the file hello.py Kindly assist me.</p>
0
2016-09-04T15:31:14Z
39,318,791
<p>If you want to use a function from an external library first of all you have to import the external library </p> <pre><code>import foo #your library </code></pre> <p>And then for calling a function "foo_function" you have to call this function using:</p> <pre><code>foo.foo_function(args) #where args are declared in the hello.py file </code></pre>
0
2016-09-04T15:55:23Z
[ "python", "web-services", "rest", "http", "werkzeug" ]
Python restFUL web service - routing to a specific function in a file
39,318,569
<p>I am implementing a simple API in python using werkzeug. I have created a simple application 'localhost'. I want to execute a function after a GET request. I am confused with URL routing. I have gone through <a href="http://werkzeug.pocoo.org/docs/0.11/routing/" rel="nofollow">this</a> tutorial and implemented routing but still can't figure out how to send a request to another file. Here is my code:</p> <pre><code>url_map = Map([ Rule('/spell', endpoint='spell_checker.py'), Rule('/he', endpoint='hello/test') ]) @Request.application def application(request): urls = url_map.bind_to_environ(environ) try: endpoint, args = urls.match() print(endpoint + " " + args) #urls.dispatch('test') except httplib.HTTPException, e: return e(environ, start_response) start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Rul1e points to %r with arguments %r' % (endpoint, args)] if __name__ == '__main__': from werkzeug.serving import run_simple run_simple('127.0.0.1', 4000, application) </code></pre> <p>I have another another in a file named hello.py in the same directory</p> <pre><code>def index(): print 'This is the test' </code></pre> <p>I want to call index function from URL like localhost:4000/hello which will call the index function of the file hello.py Kindly assist me.</p>
0
2016-09-04T15:31:14Z
39,319,371
<blockquote> <p>The endpoint is typically a string and can be used to uniquely identify the URL</p> </blockquote> <p>So it doesn't bind a function to a url, you have to do it yourself. After this line</p> <pre><code>endpoint, args = urls.match() </code></pre> <p>you can put some kind of control statements to run specific functions, in your case:</p> <pre><code>if endpoint == "hello/test": hello.index(request, **args) </code></pre> <p>assuming you have imported <code>hello</code> module when you point your browser to <code>\he</code> the program will call <code>hello.index</code> function.</p> <p><a href="http://werkzeug.pocoo.org/docs/0.11/tutorial/#step-4-the-routing" rel="nofollow">http://werkzeug.pocoo.org/docs/0.11/tutorial/#step-4-the-routing</a></p>
0
2016-09-04T16:59:11Z
[ "python", "web-services", "rest", "http", "werkzeug" ]
File not uploading with Flask-wtforms in cookiecutter-flask app
39,318,572
<p>I am having a problem getting a file upload to work in a <a href="https://github.com/sloria/cookiecutter-flask">cookiecutter-flask</a> app (v. 0.10.1). Right now, it is not saving the file uploaded.</p> <p>Cookiecutter-Flask by default installs WTForms and Flask-WTForms. I have tried adding Flask-Uploads to this but I'm not convinced that module adds anything at this point so I have uninstalled it. This is the Flask-WTF file upload documentation: <a href="http://flask-wtf.readthedocs.io/en/latest/form.html#module-flask_wtf.file">http://flask-wtf.readthedocs.io/en/latest/form.html#module-flask_wtf.file</a></p> <p>The main difference between the documentation and my app is that I seem to have information across more files, in keeping with the conventions of the cookiecutter.</p> <p>In <code>app_name/spreadsheet/forms.py</code>:</p> <pre><code>from flask_wtf import Form from wtforms.validators import DataRequired from flask_wtf.file import FileField, FileAllowed, FileRequired class UploadForm(Form): """Upload form.""" csv = FileField('Your CSV', validators=[FileRequired(),FileAllowed(['csv', 'CSVs only!'])]) def __init__(self, *args, **kwargs): """Create instance.""" super(UploadForm, self).__init__(*args, **kwargs) self.user = None def validate(self): """Validate the form.""" initial_validation = super(UploadForm, self).validate() if not initial_validation: return False </code></pre> <p>In <code>app_name/spreadsheet/views.py</code>:</p> <pre><code>from flask import Blueprint, render_template from flask_login import login_required from werkzeug.utils import secure_filename from app_name.spreadsheet.forms import UploadForm from app_name.spreadsheet.models import Spreadsheet from app_name.utils import flash, flash_errors blueprint = Blueprint('spreadsheet', __name__, url_prefix='/spreadsheets', static_folder='../static') @blueprint.route('/upload', methods=['GET', 'POST']) #TODO test without GET since it won't work anyway @login_required def upload(): uploadform = UploadForm() if uploadform.validate_on_submit(): filename = secure_filename(form.csv.data.filename) uploadform.csv.data.save('uploads/csvs/' + filename) flash("CSV saved.") return redirect(url_for('list')) else: filename = None return render_template('spreadsheets/upload.html', uploadform=uploadform) </code></pre> <p>This is the command line output showing no errors when I upload a file:</p> <pre><code> * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) 127.0.0.1 - - [04/Sep/2016 10:29:10] "GET /spreadsheets/upload HTTP/1.1" 200 - 127.0.0.1 - - [04/Sep/2016 10:29:10] "GET /_debug_toolbar/static/css/toolbar.css?0.3058158586562558 HTTP/1.1" 200 - 127.0.0.1 - - [04/Sep/2016 10:29:14] "POST /spreadsheets/upload HTTP/1.1" 200 - 127.0.0.1 - - [04/Sep/2016 10:29:14] "GET /_debug_toolbar/static/css/toolbar.css?0.3790246965220061 HTTP/1.1" 200 - </code></pre> <p>For the <code>uploads/csvs</code> directory I have tried absolute and relative paths and the directory is permissioned 766.</p> <p>The template file is:</p> <pre><code>{% extends "layout.html" %} {% block content %} &lt;h1&gt;Welcome {{ session.username }}&lt;/h1&gt; {% with uploadform=uploadform %} {% if current_user and current_user.is_authenticated and uploadform %} &lt;form id="uploadForm" method="POST" class="" action="{{ url_for('spreadsheet.upload') }}" enctype="multipart/form-data"&gt; &lt;input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/&gt; &lt;div class="form-group"&gt; {{ uploadform.csv(class_="form-control") }} &lt;/div&gt; &lt;button type="submit" class="btn btn-default"&gt;Upload&lt;/button&gt; &lt;/form&gt; {% endif %} {% endwith %} {% endblock %} </code></pre> <p>Which generates this HTML:</p> <pre><code> &lt;form id="uploadForm" method="POST" class="" action="/spreadsheets/upload" enctype="multipart/form-data"&gt; &lt;input type="hidden" name="csrf_token" value="LONG_RANDOM_VALUE"/&gt; &lt;div class="form-group"&gt; &lt;input class="form-control" id="csv" name="csv" type="file"&gt; &lt;/div&gt; &lt;button type="submit" class="btn btn-default"&gt;Upload&lt;/button&gt; &lt;/form&gt; </code></pre>
10
2016-09-04T15:31:19Z
39,530,150
<p>Looking through the documentation, the link you provided indicates that the <code>data</code> field of <code>csv</code> is an instance of <code>werkzeug.datastructures.FileStorage</code>. The documentation for <a href="http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage.save" rel="nofollow"><code>FileStorage.save()</code></a> suggests that:</p> <blockquote> <p>If the destination is a file object you have to close it yourself after the call. </p> </blockquote> <p>Could it be that because you aren't closing the file, it isn't being written to disk?</p>
0
2016-09-16T11:15:55Z
[ "python", "flask", "flask-wtforms", "flask-uploads" ]
File not uploading with Flask-wtforms in cookiecutter-flask app
39,318,572
<p>I am having a problem getting a file upload to work in a <a href="https://github.com/sloria/cookiecutter-flask">cookiecutter-flask</a> app (v. 0.10.1). Right now, it is not saving the file uploaded.</p> <p>Cookiecutter-Flask by default installs WTForms and Flask-WTForms. I have tried adding Flask-Uploads to this but I'm not convinced that module adds anything at this point so I have uninstalled it. This is the Flask-WTF file upload documentation: <a href="http://flask-wtf.readthedocs.io/en/latest/form.html#module-flask_wtf.file">http://flask-wtf.readthedocs.io/en/latest/form.html#module-flask_wtf.file</a></p> <p>The main difference between the documentation and my app is that I seem to have information across more files, in keeping with the conventions of the cookiecutter.</p> <p>In <code>app_name/spreadsheet/forms.py</code>:</p> <pre><code>from flask_wtf import Form from wtforms.validators import DataRequired from flask_wtf.file import FileField, FileAllowed, FileRequired class UploadForm(Form): """Upload form.""" csv = FileField('Your CSV', validators=[FileRequired(),FileAllowed(['csv', 'CSVs only!'])]) def __init__(self, *args, **kwargs): """Create instance.""" super(UploadForm, self).__init__(*args, **kwargs) self.user = None def validate(self): """Validate the form.""" initial_validation = super(UploadForm, self).validate() if not initial_validation: return False </code></pre> <p>In <code>app_name/spreadsheet/views.py</code>:</p> <pre><code>from flask import Blueprint, render_template from flask_login import login_required from werkzeug.utils import secure_filename from app_name.spreadsheet.forms import UploadForm from app_name.spreadsheet.models import Spreadsheet from app_name.utils import flash, flash_errors blueprint = Blueprint('spreadsheet', __name__, url_prefix='/spreadsheets', static_folder='../static') @blueprint.route('/upload', methods=['GET', 'POST']) #TODO test without GET since it won't work anyway @login_required def upload(): uploadform = UploadForm() if uploadform.validate_on_submit(): filename = secure_filename(form.csv.data.filename) uploadform.csv.data.save('uploads/csvs/' + filename) flash("CSV saved.") return redirect(url_for('list')) else: filename = None return render_template('spreadsheets/upload.html', uploadform=uploadform) </code></pre> <p>This is the command line output showing no errors when I upload a file:</p> <pre><code> * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) 127.0.0.1 - - [04/Sep/2016 10:29:10] "GET /spreadsheets/upload HTTP/1.1" 200 - 127.0.0.1 - - [04/Sep/2016 10:29:10] "GET /_debug_toolbar/static/css/toolbar.css?0.3058158586562558 HTTP/1.1" 200 - 127.0.0.1 - - [04/Sep/2016 10:29:14] "POST /spreadsheets/upload HTTP/1.1" 200 - 127.0.0.1 - - [04/Sep/2016 10:29:14] "GET /_debug_toolbar/static/css/toolbar.css?0.3790246965220061 HTTP/1.1" 200 - </code></pre> <p>For the <code>uploads/csvs</code> directory I have tried absolute and relative paths and the directory is permissioned 766.</p> <p>The template file is:</p> <pre><code>{% extends "layout.html" %} {% block content %} &lt;h1&gt;Welcome {{ session.username }}&lt;/h1&gt; {% with uploadform=uploadform %} {% if current_user and current_user.is_authenticated and uploadform %} &lt;form id="uploadForm" method="POST" class="" action="{{ url_for('spreadsheet.upload') }}" enctype="multipart/form-data"&gt; &lt;input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/&gt; &lt;div class="form-group"&gt; {{ uploadform.csv(class_="form-control") }} &lt;/div&gt; &lt;button type="submit" class="btn btn-default"&gt;Upload&lt;/button&gt; &lt;/form&gt; {% endif %} {% endwith %} {% endblock %} </code></pre> <p>Which generates this HTML:</p> <pre><code> &lt;form id="uploadForm" method="POST" class="" action="/spreadsheets/upload" enctype="multipart/form-data"&gt; &lt;input type="hidden" name="csrf_token" value="LONG_RANDOM_VALUE"/&gt; &lt;div class="form-group"&gt; &lt;input class="form-control" id="csv" name="csv" type="file"&gt; &lt;/div&gt; &lt;button type="submit" class="btn btn-default"&gt;Upload&lt;/button&gt; &lt;/form&gt; </code></pre>
10
2016-09-04T15:31:19Z
39,531,721
<p>Try this:</p> <pre><code>from flask import request if uploadform.validate_on_submit(): if 'csv' in request.files: csv = request.files['csv'] csv.save('uploads/csvs/' + csv.filename) </code></pre>
0
2016-09-16T12:36:35Z
[ "python", "flask", "flask-wtforms", "flask-uploads" ]
File not uploading with Flask-wtforms in cookiecutter-flask app
39,318,572
<p>I am having a problem getting a file upload to work in a <a href="https://github.com/sloria/cookiecutter-flask">cookiecutter-flask</a> app (v. 0.10.1). Right now, it is not saving the file uploaded.</p> <p>Cookiecutter-Flask by default installs WTForms and Flask-WTForms. I have tried adding Flask-Uploads to this but I'm not convinced that module adds anything at this point so I have uninstalled it. This is the Flask-WTF file upload documentation: <a href="http://flask-wtf.readthedocs.io/en/latest/form.html#module-flask_wtf.file">http://flask-wtf.readthedocs.io/en/latest/form.html#module-flask_wtf.file</a></p> <p>The main difference between the documentation and my app is that I seem to have information across more files, in keeping with the conventions of the cookiecutter.</p> <p>In <code>app_name/spreadsheet/forms.py</code>:</p> <pre><code>from flask_wtf import Form from wtforms.validators import DataRequired from flask_wtf.file import FileField, FileAllowed, FileRequired class UploadForm(Form): """Upload form.""" csv = FileField('Your CSV', validators=[FileRequired(),FileAllowed(['csv', 'CSVs only!'])]) def __init__(self, *args, **kwargs): """Create instance.""" super(UploadForm, self).__init__(*args, **kwargs) self.user = None def validate(self): """Validate the form.""" initial_validation = super(UploadForm, self).validate() if not initial_validation: return False </code></pre> <p>In <code>app_name/spreadsheet/views.py</code>:</p> <pre><code>from flask import Blueprint, render_template from flask_login import login_required from werkzeug.utils import secure_filename from app_name.spreadsheet.forms import UploadForm from app_name.spreadsheet.models import Spreadsheet from app_name.utils import flash, flash_errors blueprint = Blueprint('spreadsheet', __name__, url_prefix='/spreadsheets', static_folder='../static') @blueprint.route('/upload', methods=['GET', 'POST']) #TODO test without GET since it won't work anyway @login_required def upload(): uploadform = UploadForm() if uploadform.validate_on_submit(): filename = secure_filename(form.csv.data.filename) uploadform.csv.data.save('uploads/csvs/' + filename) flash("CSV saved.") return redirect(url_for('list')) else: filename = None return render_template('spreadsheets/upload.html', uploadform=uploadform) </code></pre> <p>This is the command line output showing no errors when I upload a file:</p> <pre><code> * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) 127.0.0.1 - - [04/Sep/2016 10:29:10] "GET /spreadsheets/upload HTTP/1.1" 200 - 127.0.0.1 - - [04/Sep/2016 10:29:10] "GET /_debug_toolbar/static/css/toolbar.css?0.3058158586562558 HTTP/1.1" 200 - 127.0.0.1 - - [04/Sep/2016 10:29:14] "POST /spreadsheets/upload HTTP/1.1" 200 - 127.0.0.1 - - [04/Sep/2016 10:29:14] "GET /_debug_toolbar/static/css/toolbar.css?0.3790246965220061 HTTP/1.1" 200 - </code></pre> <p>For the <code>uploads/csvs</code> directory I have tried absolute and relative paths and the directory is permissioned 766.</p> <p>The template file is:</p> <pre><code>{% extends "layout.html" %} {% block content %} &lt;h1&gt;Welcome {{ session.username }}&lt;/h1&gt; {% with uploadform=uploadform %} {% if current_user and current_user.is_authenticated and uploadform %} &lt;form id="uploadForm" method="POST" class="" action="{{ url_for('spreadsheet.upload') }}" enctype="multipart/form-data"&gt; &lt;input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/&gt; &lt;div class="form-group"&gt; {{ uploadform.csv(class_="form-control") }} &lt;/div&gt; &lt;button type="submit" class="btn btn-default"&gt;Upload&lt;/button&gt; &lt;/form&gt; {% endif %} {% endwith %} {% endblock %} </code></pre> <p>Which generates this HTML:</p> <pre><code> &lt;form id="uploadForm" method="POST" class="" action="/spreadsheets/upload" enctype="multipart/form-data"&gt; &lt;input type="hidden" name="csrf_token" value="LONG_RANDOM_VALUE"/&gt; &lt;div class="form-group"&gt; &lt;input class="form-control" id="csv" name="csv" type="file"&gt; &lt;/div&gt; &lt;button type="submit" class="btn btn-default"&gt;Upload&lt;/button&gt; &lt;/form&gt; </code></pre>
10
2016-09-04T15:31:19Z
39,602,539
<p>The main reason of your problem lands here:</p> <pre><code>def validate(self): """Validate the form.""" initial_validation = super(UploadForm, self).validate() if not initial_validation: return False </code></pre> <p>so in <code>validate</code> method of <code>UploadForm</code> class.</p> <p>Let's quick investigate what is happening here. </p> <p>In <code>views.py</code> in line: </p> <pre><code>if uploadform.validate_on_submit(): </code></pre> <p><code>flask_wtf</code> package calls <code>validate</code> method. So take a look again on your overwritten method:</p> <pre><code>def validate(self): """Validate the form.""" initial_validation = super(UploadForm, self).validate() if not initial_validation: return False </code></pre> <p>what is wrong here? In case <code>initial_validation</code> would be <code>True</code>, your <code>validate</code> method will return <code>None</code>. So what should happen? Only html rendering:</p> <pre><code>def upload(): uploadform = UploadForm() if uploadform.validate_on_submit(): # &lt;--- here it's None filename = secure_filename(form.csv.data.filename) uploadform.csv.data.save('uploads/csvs/' + filename) flash("CSV saved.") return redirect(url_for('list')) else: # &lt;--- so this block runs filename = None # And your app will only render the same view as when using HTTP GET on that method return render_template('spreadsheets/upload.html', uploadform=uploadform) </code></pre> <p>So if overwriting <code>validate</code> method is not necessary, then just remove it, and if is, then adjust it to return <code>True</code>:</p> <pre><code>def validate(self): """Validate the form.""" initial_validation = super(UploadForm, self).validate() if not initial_validation: return False return True # &lt;-- this part is missing </code></pre> <p>Of course you can use shortened and I think more appropriate version:</p> <pre><code>def validate(self): """Validate the form.""" initial_validation = super(UploadForm, self).validate() return not initial_validation </code></pre>
0
2016-09-20T19:42:36Z
[ "python", "flask", "flask-wtforms", "flask-uploads" ]
Get short version of error message with requests
39,318,631
<p>I'm using requests and I need a shortened description of the exception,</p> <pre><code> try: resp = requests.get(url) except Exception, e: data['error'] = str(e) </code></pre> <p>e.g for a connection error, <code>str(e)</code> becomes <code>('Connection aborted.', error(61, 'Connection refused'))</code></p> <p>I want to retrieve only the <code>Connection aborted.</code> part.</p> <p>According to the document of <code>Exception</code> class, the <code>e.strerror</code> should work, but <code>print (e.strerror)</code> shows <code>None</code></p> <p>Any ideas?</p>
0
2016-09-04T15:38:19Z
39,319,191
<p>The <code>Exception</code> class is the base class of all user-defined exceptions (it a recommandation).</p> <p>This class inherits the <code>BaseException</code> which has a <a href="https://docs.python.org/2/library/exceptions.html#exceptions.BaseException" rel="nofollow"><code>args</code></a> attributes. This attribute is defined as follow:</p> <blockquote> <p><strong>args</strong></p> <p>The tuple of arguments given to the exception constructor. Some built-in exceptions (like OSError) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message.</p> </blockquote> <p>If the error message is in <code>args[0]</code>, you can try:</p> <pre><code>try: resp = requests.get(url) except Exception as e: data['error'] = e.args[0] </code></pre> <p>Your are not speaking of the standard exception, because <code>print (e.strerror)</code> should raise <code>AttributeError</code>.</p> <p>For your answer, you ought to consider the answer of this qestion: <a href="http://stackoverflow.com/questions/16511337/correct-way-to-try-except-using-python-requests-module?answertab=votes#tab-top">Correct way to try/except using Python requests module?</a></p> <p>All Requests exceptions inherit <a href="http://docs.python-requests.org/en/master/_modules/requests/exceptions/" rel="nofollow"><code>requests.exceptions.RequestException</code></a>, which inherits <code>IOError</code>.</p> <p>About <code>IOError</code>, the documentation says:</p> <blockquote> <p><strong>exception EnvironmentError</strong></p> <p>The base class for exceptions that can occur outside the Python system: IOError, OSError. <strong>When exceptions of this type are created with a 2-tuple</strong>, the first item is available on the instance’s <em>errno</em> attribute (it is assumed to be an error number), and the second item is available on the <em>strerror</em> attribute (it is usually the associated error message). The tuple itself is also available on the args attribute.</p> </blockquote> <p>But <code>RequestException</code> doesn't seems to be created with a 2-tuple, so <em>strerror</em> is <code>None</code>.</p> <p><strong>EDIT: add some examples:</strong></p> <p>If you have <code>HTTPError</code>, the original message is in <code>args[0]</code>. See this sample of code in <code>requests.models.Response.raise_for_status</code>:</p> <pre><code>if http_error_msg: raise HTTPError(http_error_msg, response=self) </code></pre> <p>If you have <code>ConnectionError</code>, the <code>args[0]</code> contains the original error. See this sample in <code>requests.adapters.HTTPAdapter.send</code>:</p> <pre><code>except (ProtocolError, socket.error) as err: raise ConnectionError(err, request=request) </code></pre> <p>It’s the same for <code>ProxyError</code>, <code>SSLError</code>, <code>Timeout</code>: <code>args[0]</code> contains the original error.</p> <p>...</p> <p>Browse the source code in the <a href="https://github.com/kennethreitz/requests/tree/master/requests" rel="nofollow">GitHub repo</a>.</p> <p><strong>One solution could be:</strong></p> <pre><code>try: resp = requests.get(url) except requests.exceptions.HTTPError as e: data['error'] = e.args[0] except requests.exceptions.RequestException as e: cause = e.args[0] data['error'] = str(cause.args[0]) </code></pre>
0
2016-09-04T16:40:25Z
[ "python", "python-requests" ]
Bokeh plots not showing in nbviewer
39,318,640
<p>I am working on some visualizations using Bokeh in a Jupyter (ipython) notebook. Though the plots run well within my notebook, it is important for me to make them accessible for users not running the code. I was counting on nbviewer for this, but am having trouble. </p> <p>Using a simple plot for example, I get this great output in my running notebook: </p> <p><a href="http://i.stack.imgur.com/dyJwF.png" rel="nofollow">Running notebook in chrome</a></p> <p>After pushing to github I view the notebook in nbviewer but my plots are gone: <a href="http://nbviewer.jupyter.org/github/kaplann/bokeh_trouble/blob/master/.ipynb_checkpoints/bokeh%20error-checkpoint.ipynb" rel="nofollow">http://nbviewer.jupyter.org/github/kaplann/bokeh_trouble/blob/master/.ipynb_checkpoints/bokeh%20error-checkpoint.ipynb</a></p> <p>I am using chrome Version 52.0.2743.82 (64-bit) on fedora 23, Bokeh - 0.12.1, Python 3.5.1, Anaconda 2.5.0 (64-bit), IPython - 5.1.0</p> <p>I have a very strong feeling I am missing something, hopefully I am and the fix will be simple. Thanks!</p>
0
2016-09-04T15:39:26Z
39,334,594
<p>The notebook is an extremely difficult and challenging environment to develop and test Bokeh for. There have been some recent regressions and work to fix them, please refer to GitHub issues <a href="https://github.com/bokeh/bokeh/issues/5014" rel="nofollow">#5014</a> and <a href="https://github.com/bokeh/bokeh/issues/5081" rel="nofollow">#5081</a> for more information. </p>
0
2016-09-05T16:31:16Z
[ "python", "plot", "jupyter", "bokeh" ]
Selenium Python Chromedriver Change File Download Path
39,318,701
<p>I'm looking for a way to save different files to different locations in python using chromedriver. The code below sets chrome to download to folder_path without pop the download location dialogue first. After clicking and downloading one file into folder_path (I skipped pasting this part of code cause I have no issue), I want to download another file into new_folder_path. But the code below gives me AttributeError: 'WebDriver' object has no attribute 'Chrome'. Any ideas if I can change download location for Chrome under the same webdriver?</p> <pre><code>folder_path = "C:\\Document" def give_chrome_option(folder_path): chromeOptions = webdriver.ChromeOptions() #setup chrome option prefs = {"download.default_directory" : folder_path, "download.prompt_for_download": False, "download.directory_upgrade": True} #set path chromeOptions.add_experimental_option("prefs", prefs) #set option return chromeOptions driver = webdriver.Chrome(chrome_options = give_chrome_option(folder_path) driver.get(sample_url) driver.Chrome(chrome_options = give_chrome_option(new_folder_path)) </code></pre>
1
2016-09-04T15:46:26Z
39,318,889
<p>No, you have to re-instantiate WebDriver if you want to download to a different directory. Depending on what exactly do you need to do, a workaround described in the first answer <a href="http://stackoverflow.com/a/23897531/1733471">here</a> might be suitable for you (download to a temporary directory then move file using <code>os.rename()</code>)</p>
0
2016-09-04T16:05:34Z
[ "python", "google-chrome", "selenium", "download", "selenium-chromedriver" ]
How can I notify RxPY observers on separate threads using asyncio?
39,318,723
<p>(Note: The background for this problem is pretty verbose, but there's an SSCCE at the bottom that can be skipped to)</p> <h2>Background</h2> <p>I'm trying to develop a Python-based CLI to interact with a web service. In my codebase I have a <code>CommunicationService</code> class that handles all direct communication with the web service. It exposes a <code>received_response</code> property that returns an <code>Observable</code> (from RxPY) that other objects can subscribe to in order to be notified when responses are received back from the web service.</p> <p>I've based my CLI logic on the <a href="http://click.pocoo.org/5/" rel="nofollow"><code>click</code></a> library, where one of my subcommands is implemented as below:</p> <pre><code>async def enabled(self, request: str, response_handler: Callable[[str], Tuple[bool, str]]) -&gt; None: self._generate_request(request) if response_handler is None: return None while True: response = await self.on_response success, value = response_handler(response) print(success, value) if success: return value </code></pre> <p>What's happening here (in the case that <code>response_handler</code> is not <code>None</code>) is that the subcommand is behaving as a coroutine that awaits responses from the web service (<code>self.on_response == CommunicationService.received_response</code>) and returns some processed value from the first response it can handle.</p> <p>I'm trying to test the behaviour of my CLI by creating test cases in which <code>CommunicationService</code> is completely mocked; a fake <code>Subject</code> is created (which can act as an <code>Observable</code>) and <code>CommunicationService.received_response</code> is mocked to return it. As part of the test, the subject's <code>on_next</code> method is invoked to pass mock web service responses back to the production code:</p> <pre><code>@when('the communications service receives a response from TestCube Web Service') def step_impl(context): context.mock_received_response_subject.on_next(context.text) </code></pre> <p>I use a click 'result callback' function that gets invoked at the end of the CLI invocation and blocks until the coroutine (the subcommand) is done:</p> <pre><code>@cli.resultcallback() def _handle_command_task(task: Coroutine, **_) -&gt; None: if task: loop = asyncio.get_event_loop() result = loop.run_until_complete(task) loop.close() print('RESULT:', result) </code></pre> <h2>Problem</h2> <p>At the start of the test, I run <code>CliRunner.invoke</code> to fire off the whole shebang. The problem is that this is a blocking call and will block the thread until the CLI has finished and returned a result, which isn't helpful if I need my test thread to carry on so it can produce mock web service responses concurrently with it.</p> <p>What I guess I need to do is run <code>CliRunner.invoke</code> on a new thread using <code>ThreadPoolExecutor</code>. This allows the test logic to continue on the original thread and execute the <code>@when</code> step posted above. However, <em>notifications published with</em> <code>mock_received_response_subject.on_next</code> <em>do not seem to trigger execution to continue within the subcommand</em>.</p> <p>I believe the solution would involve making use of RxPY's <code>AsyncIOScheduler</code>, but I'm finding the documentation on this a little sparse and unhelpful.</p> <h2>SSCCE</h2> <p>The snippet below captures what I hope is the essence of the problem. If it can be modified to work, I should be able to apply the same solution to my actual code to get it to behave as I want.</p> <pre><code>import asyncio import logging import sys import time import click from click.testing import CliRunner from rx.subjects import Subject web_response_subject = Subject() web_response_observable = web_response_subject.as_observable() thread_loop = asyncio.new_event_loop() @click.group() def cli(): asyncio.set_event_loop(thread_loop) @cli.resultcallback() def result_handler(task, **_): loop = asyncio.get_event_loop() result = loop.run_until_complete(task) # Should block until subject publishes value loop.close() print(result) @cli.command() async def get_web_response(): return await web_response_observable def test(): runner = CliRunner() future = thread_loop.run_in_executor(None, runner.invoke, cli, ['get_web_response']) time.sleep(1) web_response_subject.on_next('foo') # Simulate reception of web response. time.sleep(1) result = future.result() print(result.output) logging.basicConfig( level=logging.DEBUG, format='%(threadName)10s %(name)18s: %(message)s', stream=sys.stderr, ) test() </code></pre> <p><strong>Current Behaviour</strong></p> <p>The program hangs when run, blocking at <code>result = loop.run_until_complete(task)</code>.</p> <p><strong>Acceptance Criteria</strong></p> <p>The program terminates and prints <code>foo</code> on <code>stdout</code>.</p> <h2>Update 1</h2> <p>Based on Vincent's help I've made some changes to my code.</p> <p><code>Relay.enabled</code> (the subcommand that awaits responses from the web service in order to process them) is now implemented like this:</p> <pre><code>async def enabled(self, request: str, response_handler: Callable[[str], Tuple[bool, str]]) -&gt; None: self._generate_request(request) if response_handler is None: return None return await self.on_response \ .select(response_handler) \ .where(lambda result, i: result[0]) \ .select(lambda result, index: result[1]) \ .first() </code></pre> <p>I wasn't quite sure how <code>await</code> would behave with <code>RxPY</code> observables - would they return execution to the caller on each element generated, or only when the observable has completed (or errored?). I now know it's the latter, which honestly feels like the more natural choice and has allowed me to make the implementation of this function feel a lot more elegant and reactive.</p> <p>I've also modified the test step that generates mock web service responses:</p> <pre><code>@when('the communications service receives a response from TestCube Web Service') def step_impl(context): loop = asyncio.get_event_loop() loop.call_soon_threadsafe(context.mock_received_response_subject.on_next, context.text) </code></pre> <p>Unfortunately, <em>this will not work as it stands</em>, since the CLI is being invoked in its own thread...</p> <pre><code>@when('the CLI is run with "{arguments}"') def step_impl(context, arguments): loop = asyncio.get_event_loop() if 'async.cli' in context.tags: context.async_result = loop.run_in_executor(None, context.cli_runner.invoke, testcube.cli, arguments.split()) else: ... </code></pre> <p>And the CLI creates its own thread-private event loop when invoked...</p> <pre><code>def cli(context, hostname, port): _initialize_logging(context.meta['click_log.core.logger']['level']) # Create a new event loop for processing commands asynchronously on. loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) ... </code></pre> <p>What I think I need is a way to allow my test steps to invoke the CLI on a new thread <em>and then fetch the event loop it's using</em>:</p> <pre><code>@when('the communications service receives a response from TestCube Web Service') def step_impl(context): loop = _get_cli_event_loop() # Needs to be implemented. loop.call_soon_threadsafe(context.mock_received_response_subject.on_next, context.text) </code></pre> <h2>Update 2</h2> <p>There doesn't seem to be an easy way to get the event loop that a particular thread creates and uses for itself, so instead I took Victor's advice and mocked <code>asyncio.new_event_loop</code> to return an event loop that my test code creates and stores:</p> <pre><code>def _apply_mock_event_loop_patch(context): # Close any already-existing exit stacks. if hasattr(context, 'mock_event_loop_exit_stack'): context.mock_event_loop_exit_stack.close() context.test_loop = asyncio.new_event_loop() print(context.test_loop) context.mock_event_loop_exit_stack = ExitStack() context.mock_event_loop_exit_stack.enter_context( patch.object(asyncio, 'new_event_loop', spec=True, return_value=context.test_loop)) </code></pre> <p>I change my 'mock web response received' test step to do the following:</p> <pre><code>@when('the communications service receives a response from TestCube Web Service') def step_impl(context): loop = context.test_loop loop.call_soon_threadsafe(context.mock_received_response_subject.on_next, context.text) </code></pre> <p>The great news is that I'm actually getting the <code>Relay.enabled</code> coroutine to trigger when this step gets executed!</p> <p>The only problem now is the final test step in which I await the future I got from executing the CLI in its own thread and validate that the CLI is sending this on <code>stdout</code>:</p> <pre><code>@then('the CLI should print "{output}"') def step_impl(context, output): if 'async.cli' in context.tags: loop = asyncio.get_event_loop() # main loop, not test loop result = loop.run_until_complete(context.async_result) else: result = context.result assert_that(result.output, equal_to(output)) </code></pre> <p>I've tried playing around with this but I can't seem to get <code>context.async_result</code> (which stores the future from <code>loop.run_in_executor</code>) to transition nicely to <code>done</code> and return the result. With the current implementation, I get an error for the first test (<code>1.1</code>) and indefinite hanging for the second (<code>1.2</code>):</p> <pre><code> @mock.comms @async.cli @wip Scenario Outline: Querying relay enable state -- @1.1 # testcube/tests/features/relay.feature:45 When the user queries the enable state of relay 0 # testcube/tests/features/steps/relay.py:17 0.003s Then the CLI should query the web service about the enable state of relay 0 # testcube/tests/features/steps/relay.py:48 0.000s When the communications service receives a response from TestCube Web Service # testcube/tests/features/steps/core.py:58 0.000s """ {'module':'relays','path':'relays[0].enabled','data':[True]}' """ Then the CLI should print "True" # testcube/tests/features/steps/core.py:94 0.003s Traceback (most recent call last): File "/Users/davidfallah/testcube_env/lib/python3.5/site-packages/behave/model.py", line 1456, in run match.run(runner.context) File "/Users/davidfallah/testcube_env/lib/python3.5/site-packages/behave/model.py", line 1903, in run self.func(context, *args, **kwargs) File "testcube/tests/features/steps/core.py", line 99, in step_impl result = loop.run_until_complete(context.async_result) File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/asyncio/base_events.py", line 387, in run_until_complete return future.result() File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/asyncio/futures.py", line 274, in result raise self._exception File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/concurrent/futures/thread.py", line 55, in run result = self.fn(*self.args, **self.kwargs) File "/Users/davidfallah/testcube_env/lib/python3.5/site-packages/click/testing.py", line 299, in invoke output = out.getvalue() ValueError: I/O operation on closed file. Captured stdout: RECEIVED WEB RESPONSE: {'module':'relays','path':'relays[0].enabled','data':[True]}' &lt;Future pending cb=[_chain_future.&lt;locals&gt;._call_check_cancel() at /usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/asyncio/futures.py:431]&gt; @mock.comms @async.cli @wip Scenario Outline: Querying relay enable state -- @1.2 # testcube/tests/features/relay.feature:46 When the user queries the enable state of relay 1 # testcube/tests/features/steps/relay.py:17 0.005s Then the CLI should query the web service about the enable state of relay 1 # testcube/tests/features/steps/relay.py:48 0.001s When the communications service receives a response from TestCube Web Service # testcube/tests/features/steps/core.py:58 0.000s """ {'module':'relays','path':'relays[1].enabled','data':[False]}' """ RECEIVED WEB RESPONSE: {'module':'relays','path':'relays[1].enabled','data':[False]}' Then the CLI should print "False" # testcube/tests/features/steps/core.py:94 </code></pre> <h2>Chapter 3: Finale</h2> <p>Screw all this asynchronous multi-threaded stuff, I'm too dumb for it.</p> <p>First off, instead of describing the scenario like this...</p> <pre><code>When the user queries the enable state of relay &lt;relay_id&gt; Then the CLI should query the web service about the enable state of relay &lt;relay_id&gt; When the communications service receives a response from TestCube Web Service: """ {"module":"relays","path":"relays[&lt;relay_id&gt;].enabled","data":[&lt;relay_enabled&gt;]} """ Then the CLI should print "&lt;relay_enabled&gt;" </code></pre> <p>We describe it like this:</p> <pre><code>Given the communications service will respond to requests: """ {"module":"relays","path":"relays[&lt;relay_id&gt;].enabled","data":[&lt;relay_enabled&gt;]} """ When the user queries the enable state of relay &lt;relay_id&gt; Then the CLI should query the web service about the enable state of relay &lt;relay_id&gt; And the CLI should print "&lt;relay_enabled&gt;" </code></pre> <p>Implement the new given step:</p> <pre><code>@given('the communications service will respond to requests') def step_impl(context): response = context.text def publish_mock_response(_): loop = context.test_loop loop.call_soon_threadsafe(context.mock_received_response_subject.on_next, response) # Configure the mock comms service to publish a mock response when a request is made. instance = context.mock_comms.return_value instance.send_request.on_next.side_effect = publish_mock_response </code></pre> <p><strong>BOOM</strong></p> <pre><code>2 features passed, 0 failed, 0 skipped 22 scenarios passed, 0 failed, 0 skipped 58 steps passed, 0 failed, 0 skipped, 0 undefined Took 0m0.111s </code></pre>
1
2016-09-04T15:48:23Z
39,329,176
<p>I can see two problems with your code:</p> <ul> <li>asyncio is not thread-safe, unless you use <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.call_soon_threadsafe" rel="nofollow">call_soon_threadsafe</a> or <a href="https://docs.python.org/3/library/asyncio-task.html?highlight=run_coroutine#asyncio.run_coroutine_threadsafe" rel="nofollow">run_coroutine_threadsafe</a>. <code>RxPy</code> doesn't use any of those in <a href="https://github.com/ReactiveX/RxPY/blob/3e44b48f84f851ab37bbffdd4725d41d88061ef2/rx/linq/observable/tofuture.py#L7" rel="nofollow">Observable.to_future</a>, so you have to access <code>RxPy</code> objects in the same thread that runs the asyncio event loop.</li> <li><code>RxPy</code> sets the result of the future when <code>on_completed</code> is called, so that awaiting for an observable returns the last object emitted. This means you have to call both <code>on_next</code> and <code>on_completed</code> to get <code>await</code> to return.</li> </ul> <p>Here is a working example:</p> <pre><code>import click import asyncio from rx.subjects import Subject from click.testing import CliRunner web_response_subject = Subject() web_response_observable = web_response_subject.as_observable() main_loop = asyncio.get_event_loop() @click.group() def cli(): pass @cli.resultcallback() def result_handler(task, **_): future = asyncio.run_coroutine_threadsafe(task, main_loop) print(future.result()) @cli.command() async def get_web_response(): return await web_response_observable def test(): runner = CliRunner() future = main_loop.run_in_executor( None, runner.invoke, cli, ['get_web_response']) main_loop.call_later(1, web_response_subject.on_next, 'foo') main_loop.call_later(2, web_response_subject.on_completed) result = main_loop.run_until_complete(future) print(result.output, end='') if __name__ == '__main__': test() </code></pre>
1
2016-09-05T11:00:20Z
[ "python", "multithreading", "python-3.x", "python-asyncio", "rx-py" ]
QTreeWidget - excluding top level items from sort
39,318,827
<p>I have a 2-level QTreeWidget. The top level only has one column and is just used for grouping the second level, which holds the actual multi-column data.</p> <p>When I sort by clicking on a header (or any other way, really), I only want the second level to be sorted, as the top-level items have a fixed order set elsewhere in the app and shouldn't be affected.</p> <p>How do I achieve this?</p>
2
2016-09-04T15:59:21Z
39,320,200
<p>You can use the <a href="http://doc.qt.io/qt-5/qtreewidgetitem.html#sortChildren" rel="nofollow"><code>sortChildren</code></a> method of QTreeWidgetItem(s) like this:</p> <pre><code>sort_column = 1 # Iterate top-level elements for index in range(tree.topLevelItemCount()): # Obtain the actual top-level item top_level_item = tree.topLevelItem(index) # Sort top_level_item.sortChildren(sort_column) </code></pre> <p>Notice that if you add new children to an item you need to sort it again (only the changed item)</p> <p><strong>EDIT</strong></p> <blockquote> <p>Thanks, that's a step in the right direction, but the question now is how to override the default sort behavior. I'm doing self.treeWidget.header().sortIndicatorChanged.connect(self.s‌​ortChanged), but since that's a signal it just triggers after the widget does its regular sort, so in the end it has no effect - the top level items get sorted before the function is called</p> </blockquote> <p><s>Unless you go for a custom model/view, you may try two approaches (I don't have tested them):</p> <p><strong>1. Override the "sorting" method of the <code>QTreeWidget</code></strong></p> <p>try to replace the <code>sortItems()</code> method with some no-op, but probably the widget have other private methods that are called internally.</p> <p><strong>2. Override the root-item <code>sortChildren()</code></strong></p> <p>It's possible that the sorting is implemented calling the (hidden) root-item sortChildren(), that will sort the top-level-items and call the sortChildren() of those. You may be able to figure out how to get/set this item using <code>rootIndex()</code>/<code>setRootIndex()</code> and then override the sort method (e.g. <code>root.sortChildren = lambda c, o: None</code>).</s></p>
1
2016-09-04T18:30:33Z
[ "python", "sorting", "pyqt", "pyqt4", "qtreewidget" ]
QTreeWidget - excluding top level items from sort
39,318,827
<p>I have a 2-level QTreeWidget. The top level only has one column and is just used for grouping the second level, which holds the actual multi-column data.</p> <p>When I sort by clicking on a header (or any other way, really), I only want the second level to be sorted, as the top-level items have a fixed order set elsewhere in the app and shouldn't be affected.</p> <p>How do I achieve this?</p>
2
2016-09-04T15:59:21Z
39,334,199
<p>I found a solution based on the answer for <a href="http://stackoverflow.com/questions/33676893/qt-qtreewidget-disabling-interaction-for-a-single-column">this</a> question. Catch the sectionClicked signal and check if the clicked column is the first one. If so, force the static sort direction and then manually sort the children. Also needed a variable to manually track the sort direction for that column. Relevant code:</p> <pre><code>self.lastSortDir = 1 self.treeWidget.header().sectionClicked.connect(self.headerSectionClicked) def headerSectionClicked(self, colId): flip = {0:1, 1:0} if colId == 0: self.treeWidget.header().setSortIndicator(0,1) sortDir = flip[self.lastSortDir] for gId in self.groupWidgets: self.groupWidgets[gId].sortChildren(0, sortDir) self.lastSortDir = sortDir </code></pre> <p>This still isn't ideal for two main reasons:</p> <ol> <li><p>Every time you sort by the first column, two sorts will be performed, one to force the static direction and then another for the children. Could be an issue with larger data sets and is just inelegant.</p></li> <li><p>The sort indicator for the first column will be stuck displaying the static sort direction instead of the actual direction the children are sorted by. Mostly just a cosmetic issue but it still triggers me.</p></li> </ol> <p>Not ideal, but considering everything else I tried didn't work at all, I'll take it for now. I wasted enough time on it already, and imperfect but working is better than perfect but not working.</p>
0
2016-09-05T16:03:13Z
[ "python", "sorting", "pyqt", "pyqt4", "qtreewidget" ]
QTreeWidget - excluding top level items from sort
39,318,827
<p>I have a 2-level QTreeWidget. The top level only has one column and is just used for grouping the second level, which holds the actual multi-column data.</p> <p>When I sort by clicking on a header (or any other way, really), I only want the second level to be sorted, as the top-level items have a fixed order set elsewhere in the app and shouldn't be affected.</p> <p>How do I achieve this?</p>
2
2016-09-04T15:59:21Z
39,335,184
<p>The simplest solution is to create a subclass of <code>QTreeWidgetItem</code> and reimplement its <code>__lt__</code> method so that it always returns <code>False</code>. Qt uses a stable sort algorithm, so this means the items will always retain their original order. This subclass should be used for the top-level items only.</p> <p>Here is a working demo that seems to meet your spec:</p> <pre><code>import sys from random import randint from PyQt4 import QtCore, QtGui class TreeWidgetItem(QtGui.QTreeWidgetItem): def __lt__(self, other): return False class Window(QtGui.QTreeWidget): def __init__(self): super(Window, self).__init__() self.setHeaderLabels('Name X Y'.split()) for text in 'One Two Three Four'.split(): parent = TreeWidgetItem([text]) for text in 'Red Blue Green Yellow'.split(): child = QtGui.QTreeWidgetItem([ text, str(randint(0, 9)), str(randint(0, 9))]) parent.addChild(child) self.addTopLevelItem(parent) self.expandAll() self.setSortingEnabled(True) self.sortByColumn(0, QtCore.Qt.AscendingOrder) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) window = Window() window.setGeometry(800, 100, 320, 400) window.show() sys.exit(app.exec_()) </code></pre>
2
2016-09-05T17:19:09Z
[ "python", "sorting", "pyqt", "pyqt4", "qtreewidget" ]
Creating node in py2neo shows up blank in Neo4j
39,318,900
<p>I am new to Neo4j and py2neo. I used the GraphObject model like so:</p> <pre><code>class Capability(GraphObject): __primarykey__ = "term" term = Property() child_of = RelatedTo("Capability") parent_to = RelatedTo("Capability") </code></pre> <p>After I create a "Capability":</p> <pre><code>c = Capability() c.term = name graph.push(c) </code></pre> <p>Querying the database in the Neo4j browser gives me this:</p> <p><a href="http://i.stack.imgur.com/CGeDR.png" rel="nofollow"><img src="http://i.stack.imgur.com/CGeDR.png" alt="enter image description here"></a></p> <p>Where the nodes are blank. Furthermore if I change the model to this:</p> <pre><code>class Capability(GraphObject): __primarylabel__ = "name" __primarykey__ = "term" term = Property() child_of = RelatedTo("Capability") parent_to = RelatedTo("Capability") </code></pre> <p>Where the "<strong>primarylabel</strong>" I get names in the nodes in Neo4J like expected, but the node is no longer considered a "Capability" - which means I also can't search for "Capability":</p> <p><a href="http://i.stack.imgur.com/rRQLB.png" rel="nofollow"><img src="http://i.stack.imgur.com/rRQLB.png" alt="enter image description here"></a></p> <p>... which makes sense since I overrided the primary label, but it seems odd that the only way I can see the label of the Capability in Neo4J is by not having the node be considered a Capability. </p> <p>So the questions is: in py2neo, how can I create a node that is considered a Capability based on the model as well as have the term label show up in the Neo4J node graph (instead of blank)? </p>
0
2016-09-04T16:06:47Z
39,357,682
<p>After hours of trying to figure out what I don't fully understand regarding Neo4j and the question above - I finally figured it out: "Capability" is some sort of reserved word!</p> <p>Once I changed the class name from "Capability" to "CapabilityZ" it started working as expected. Ouch. </p> <p>Still confused since "Capability" is not in the docs anywhere....</p> <p>Hopefully this saves some poor schmuck like me out there.</p>
0
2016-09-06T20:54:13Z
[ "python", "neo4j", "graph-databases", "py2neo" ]
Json response data doesn't append to div
39,318,907
<p>I dont understand what is the problem with the success function as the ajax call works fine and the data is processed in the view, but in the success function, data doesn't get appended to the div.</p> <p>My jquery</p> <pre><code>$(document).ready(function() { $('#other').click(function() { var filename = "{{filename}}"; var count = $("#count").val(); $.ajax({ type: 'POST', url: '/increment_page/', data: {'name':filename,'count':count,'csrfmiddlewaretoken': '{{ csrf_token }}',}, dataType: 'jsonp', success: function(data) { $( "#show" ).html(data.result); } }); }); }); </code></pre> <p>Template</p> <pre><code>&lt;div id="filename"&gt;{{filename}}&lt;/div&gt; &lt;input type="text" id ="count" value='1'&gt; &lt;button id="other"&gt;Click &lt;/button&gt; &lt;div id="show"&gt; {{result|first|slice:"1:"}} &lt;/div&gt; </code></pre> <p>Views.py</p> <pre><code>def increment_page(request): #If the AJAX request if request.is_ajax() and request.POST: try: #Get the filename name = request.POST['name'] pdf = pyPdf.PdfFileReader(open(name, "rb")) result=[] #Extract the file contents for page in pdf.pages: result.append(page.extractText()) result = [x for x in result if x != ''] #Get the count count = int(request.POST['count']) #Increment the count #Get the list item at the count(position)p result=result[count] my_dict={} my_dict={'result':result,'count':count} #print(my_dict) data =json.dumps(my_dict) return HttpResponse(data,content_type='application/json') except: e = sys.exc_info() return HttpResponse(e) else: raise Http404 #return render(request,'view2.html',{'my_dict':my_dict,'result':result}) </code></pre>
0
2016-09-04T16:07:12Z
39,325,595
<p>Since you commented that you're response is getting printed to the command prompt I assume that you're success function is getting called exactly how it should. Just in case please add following line to your ajax call to log error and if any please comment it.</p> <pre><code>error: function(xhr, status, error) { var err = eval("(" + xhr.responseText + ")"); alert(err.Message); } </code></pre> <p>If you're calling your ajax from the click of a button and your form is getting submitted prevent that event.</p> <pre><code> $(document).ready(function() { $('#other').click(function(e) { e.preventDefault(); var filename = "{{filename}}"; var count = $("#count").val(); $.ajax({ type: 'POST', url: '/increment_page/', data: {'name':filename,'count':count,'csrfmiddlewaretoken': '{{ csrf_token }}',}, dataType: 'jsonp', success: function(data) { $( "#show" ).html(data.result); }, error: function(xhr, status, error) { var err = eval("(" + xhr.responseText + ")"); console.log(err.Message); //alert(err.Message); //you can use either of these to display error } }); }); }); </code></pre> <p>Sorry for asking you to comment any error. I cannot post comments to the questions yet so I have to include it within my answer.</p>
0
2016-09-05T07:21:28Z
[ "javascript", "jquery", "python", "html", "django" ]
Maintain generator object across function calls
39,318,953
<p>let me highlight the problem with the following code:</p> <pre><code>def genny(): yield 1 yield 2 yield 3 def middleman(input_gen=None): if input_gen: gen = input_gen else: gen = genny() return [next(gen), gen] if __name__ == '__main__': pro_list = middleman() pro_value = pro_list[0] print pro_value pro_gen_id = pro_list[1] for i in range(2): pro_list = middleman(pro_gen_id) pro_value = pro_list[0] print pro_value </code></pre> <p>The restriction I have is that the middleman() function cannot be a generator but I need to display all values from the generator genny(). I did this by passing back the generator object to the main() function and then sending that back again to middleman(). Is this the optimum way to do this or are there any better ways?</p>
1
2016-09-04T16:14:18Z
39,319,326
<p>It's a bit hard to say without the larger context to which your example (which is understandably a toy example), is referring.</p> <p>In general, it's perfectly fine to return multiple values from a function (although a <a href="http://stackoverflow.com/questions/354883/how-do-you-return-multiple-values-in-python">tuple or namedtuple are a bit more common</a>).</p> <p>In your specific case, though, the <code>middelman</code> function simply <code>next</code>s the generator (either received or internally constructed), then returns both this value and the generator. I don't think there's any advantage to just letting <code>middleman</code> create or return the generator, and let the client code do the <code>next</code>. The following code is equivalent to yours (see it on <a href="https://ideone.com/bfMFJt" rel="nofollow">ideone</a>):</p> <pre><code>def genny(): yield 1 yield 2 yield 3 def middleman(input_gen=None): return genny() if input_gen is None else input_gen if __name__ == '__main__': pro = middleman() for e in pro: pro = middleman(pro) print e </code></pre> <p>It's objectively shorter, and to me also clearer. </p>
1
2016-09-04T16:54:22Z
[ "python", "generator" ]
Geany - Python execution error: "is not recognized as an internal or external command"
39,318,985
<p>I'm trying to run my scripts in Geany and get the following message:</p> <pre><code>"'C:\Users\Krishn' is not recognized as an internal or external command, operable program or batch file" </code></pre> <p>Please see my build configuration as below:</p> <pre><code>Compile - C:\Users\Krishn Patel\AppData\Local\Programs\Python\Python35-32 -m py_compile "%f" Execute - C:\Users\Krishn Patel\AppData\Local\Programs\Python\Python35-32 "%f" </code></pre> <p>Thanks in advance.</p>
0
2016-09-04T16:18:12Z
39,319,028
<p>The problem is you have a space in your windows user name<code>Krishn Patel</code>. You should escape that space by putting <code>^</code> behind it or putting the command between <code>"</code>. <a href="http://superuser.com/questions/279008/how-do-i-escape-spaces-in-command-line-in-windows-without-using-quotation-marks">http://superuser.com/questions/279008/how-do-i-escape-spaces-in-command-line-in-windows-without-using-quotation-marks</a></p>
1
2016-09-04T16:22:48Z
[ "python", "python-3.x", "geany" ]
Geany - Python execution error: "is not recognized as an internal or external command"
39,318,985
<p>I'm trying to run my scripts in Geany and get the following message:</p> <pre><code>"'C:\Users\Krishn' is not recognized as an internal or external command, operable program or batch file" </code></pre> <p>Please see my build configuration as below:</p> <pre><code>Compile - C:\Users\Krishn Patel\AppData\Local\Programs\Python\Python35-32 -m py_compile "%f" Execute - C:\Users\Krishn Patel\AppData\Local\Programs\Python\Python35-32 "%f" </code></pre> <p>Thanks in advance.</p>
0
2016-09-04T16:18:12Z
39,322,315
<p>Setting to default resolved the issue Exec : python "%f"</p>
0
2016-09-04T23:23:54Z
[ "python", "python-3.x", "geany" ]
How to use a wildcard in python to check for any extension
39,319,019
<p>I am trying to check the input to see if it has any extension here is the code I used:</p> <pre><code>filename=input() if "." in filename: print ("There is") </code></pre> <p>However this will return "there is" even if the input is ends with just a full stop.<br> Is there any way to check if the input has any letters after the "."? I can't specify what the extension should be (as it is up to the user), just that there should be an extension. </p>
0
2016-09-04T16:21:53Z
39,319,112
<p>An easy option would be to check for "." in <code>filename</code> with the last character removed:</p> <pre><code>if len(filename)&gt;1 and "." in filename[:-1]: print("there is") </code></pre> <p>This would allow "file..", which may or may not be what you want. Another idea would be, to split <code>filename</code> at every "." and check that you get at least two parts, the last of which is non-empty:</p> <pre><code>parts = filename.split(".") if len(parts) &gt; 1 and parts[-1]: print("there is") </code></pre> <p>This will not allow "file..", but will allow "file.,". If you want to only allow extensions which consist of letters, you should probably use regular expressions. For example, you could try the following:</p> <pre><code>import re m = re.match('[a-z]*\.[a-z]+', filename) if m: print("there is") </code></pre> <p>This will allow "file.txt", but not "a.b.c". Regular expressions are very flexible and this approach can be extended to check for quite specific name formats.</p>
2
2016-09-04T16:32:15Z
[ "python", "wildcard" ]
How to use a wildcard in python to check for any extension
39,319,019
<p>I am trying to check the input to see if it has any extension here is the code I used:</p> <pre><code>filename=input() if "." in filename: print ("There is") </code></pre> <p>However this will return "there is" even if the input is ends with just a full stop.<br> Is there any way to check if the input has any letters after the "."? I can't specify what the extension should be (as it is up to the user), just that there should be an extension. </p>
0
2016-09-04T16:21:53Z
39,319,123
<p>I used the <code>find</code> function to locate the character <code>.</code> in <code>me</code>. If the character doesn't exist in <code>me</code>, the function returns <code>-1</code>. Then, with the index of the <code>.</code> character, I see if there are any characters after that index with <code>len(me[index + 1:])</code>. If the <code>len</code> function returns a positive number, then you know there are characters after the <code>.</code> character.</p> <pre><code>me=input() index = me.find(".") if (index != -1 and len(me[index + 1:]) &gt; 0): print ("There is") </code></pre> <p>It might not be the most elegant way to solve this with Python, but it covers the basics of your problem without getting too fancy.</p>
0
2016-09-04T16:33:21Z
[ "python", "wildcard" ]
How to use a wildcard in python to check for any extension
39,319,019
<p>I am trying to check the input to see if it has any extension here is the code I used:</p> <pre><code>filename=input() if "." in filename: print ("There is") </code></pre> <p>However this will return "there is" even if the input is ends with just a full stop.<br> Is there any way to check if the input has any letters after the "."? I can't specify what the extension should be (as it is up to the user), just that there should be an extension. </p>
0
2016-09-04T16:21:53Z
39,319,628
<p>Split the string on the dot and check to see if there was anything after it.</p> <pre><code>s = 'aaa.' if s.strip().split('.')[-1]: print('extension') else: print('no extension') s = 'aaa.bbb' if s.strip().split('.')[-1]: print('extension') else: print('no extension') </code></pre>
0
2016-09-04T17:28:59Z
[ "python", "wildcard" ]
is "from flask import request" identical to "import requests"?
39,319,070
<p>In other words, is the flask request class identical to the requests library?</p> <p>I consulted:</p> <p><a href="http://flask.pocoo.org/docs/0.11/api/" rel="nofollow">http://flask.pocoo.org/docs/0.11/api/</a></p> <p><a href="http://docs.python-requests.org/en/master/" rel="nofollow">http://docs.python-requests.org/en/master/</a></p> <p>but cannot tell for sure. I see code examples where people seem to use them interchangeably.</p>
-1
2016-09-04T16:26:46Z
39,319,106
<p>No these are not only completely different libraries, but completely different purposes.</p> <p>Flask is a web framework which clients make requests to. The Flask <code>request</code> object contains the data that the client (eg a browser) has sent to your app - ie the URL parameters, any POST data, etc.</p> <p>The requests library is for your app to make HTTP request to <em>other</em> sites, usually APIs. It makes an outgoing request and returns the response from the external site.</p>
4
2016-09-04T16:31:48Z
[ "python", "flask", "python-requests" ]
is "from flask import request" identical to "import requests"?
39,319,070
<p>In other words, is the flask request class identical to the requests library?</p> <p>I consulted:</p> <p><a href="http://flask.pocoo.org/docs/0.11/api/" rel="nofollow">http://flask.pocoo.org/docs/0.11/api/</a></p> <p><a href="http://docs.python-requests.org/en/master/" rel="nofollow">http://docs.python-requests.org/en/master/</a></p> <p>but cannot tell for sure. I see code examples where people seem to use them interchangeably.</p>
-1
2016-09-04T16:26:46Z
39,322,497
<p>Just want to add something that I think it might be useful, when we use: <code>from some_module import something</code>, it means we import just a part of the module, <code>something</code> might be a function for example, so if we need only one function from a specific module, it is better to import just that one function instead of importing the whole module (I mean from optimization perspective). So this gives another difference between the two imports you mentioned above.</p> <p>The following one means you are importing only a part (request) of the module / library (flask)</p> <pre><code>from flask import request </code></pre> <p>And the second one means you are importing the entire module / library (requests)</p> <pre><code>import requests </code></pre>
2
2016-09-04T23:58:41Z
[ "python", "flask", "python-requests" ]
How to convert to Bytes Simply
39,319,071
<p>With the file size given to me in MegaBytes (MB) I go ahead and convert it to Bytes:</p> <pre><code>in_MB = 999.991 in_KB = in_MB * 1024**2 </code></pre> <p>The resulted value is: 1048566562.82</p> <p>To verify my calculation is correct I navigate to <a href="https://www.google.com/?ion=1&amp;espv=2#q=1048566562.82%20Bytes%20to%20MB" rel="nofollow">Google Digital Storage Converter</a>: and convert the calculated value in Bytes back to MegaBytes expecting to get the same input value I had: 999.991 MB. But surpassingly Google returns another value: 1048.56656282 MB instead of 999.991 MB.</p> <p>Is there a mistake in my calculations?</p> <p><a href="http://i.stack.imgur.com/LczPK.png" rel="nofollow"><img src="http://i.stack.imgur.com/LczPK.png" alt="enter image description here"></a></p>
0
2016-09-04T16:26:52Z
39,319,116
<p><a href="https://en.wikipedia.org/wiki/Binary_prefix" rel="nofollow">Check out</a> the difference between Mebibyte (1024*1024 Byte) and Megabyte(1000*1000 Byte).</p> <p>your calculation is correct:<br> <a href="https://www.google.com/?ion=1&amp;espv=2#q=1048566562.82%20Bytes%20to%20Mebibyte" rel="nofollow"> Google Digital Storage Converter</a></p>
2
2016-09-04T16:32:37Z
[ "python" ]
How to convert to Bytes Simply
39,319,071
<p>With the file size given to me in MegaBytes (MB) I go ahead and convert it to Bytes:</p> <pre><code>in_MB = 999.991 in_KB = in_MB * 1024**2 </code></pre> <p>The resulted value is: 1048566562.82</p> <p>To verify my calculation is correct I navigate to <a href="https://www.google.com/?ion=1&amp;espv=2#q=1048566562.82%20Bytes%20to%20MB" rel="nofollow">Google Digital Storage Converter</a>: and convert the calculated value in Bytes back to MegaBytes expecting to get the same input value I had: 999.991 MB. But surpassingly Google returns another value: 1048.56656282 MB instead of 999.991 MB.</p> <p>Is there a mistake in my calculations?</p> <p><a href="http://i.stack.imgur.com/LczPK.png" rel="nofollow"><img src="http://i.stack.imgur.com/LczPK.png" alt="enter image description here"></a></p>
0
2016-09-04T16:26:52Z
39,319,270
<p>You didn't make a mistake. Historically, memory and disk sizes were calculated using binary (base 2) numbers (2 ^ 20 or 1,048,576 bytes in a megabyte). Google is using the more recent decimal (base 10) representation of a megabyte (10 ^ 6 or 1,000,000) bytes.</p> <pre><code>&gt;&gt;&gt; megabyte_size = 999.991 &gt;&gt;&gt; bytes_size = megabyte_size * 2 ** 20 &gt;&gt;&gt; bytes_size / 10 ** 6 1048.566562816 &gt;&gt;&gt; bytes_size / 2 ** 20 999.991 </code></pre> <p>Further reading:</p> <p><a href="https://en.wikipedia.org/wiki/Binary_prefix" rel="nofollow">https://en.wikipedia.org/wiki/Binary_prefix</a></p>
1
2016-09-04T16:49:14Z
[ "python" ]
What is the difference between request.GET['q'] ,request.GET('q'),and request.GET('q',)
39,319,117
<p>What is the difference between request.GET['q'] ,request.GET('q'),and request.GET('q',).Thanks</p> <pre><code>def search(request): if 'q' in request.GET and request.GET['q']: q=request.GET['q'] books=Book.objects.filter(title__icontains=q) return render(request,'search_results.html',{'book':books,'query':q}) else: return HttpResponse('please submit a search term') </code></pre>
-1
2016-09-04T16:32:41Z
39,319,148
<p><code>if 'q' in request.GET and request.GET['q']</code> it just check for dictionary contains that <code>q</code> key. But it looks ugly. You can do it more pythonic: </p> <pre><code>q = request.GET.get('q') # returns None if q not in GET if q: do your logic </code></pre>
1
2016-09-04T16:35:19Z
[ "python", "django" ]
Can't read data on TensorFlow
39,319,197
<p>Prior to this I converted my input images to TFRecords files. Now I have the following methods that I've mostly gathered from the tutorials and modified a little:</p> <pre><code>def read_and_decode(filename_queue): reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) features = tf.parse_single_example( serialized_example, # Defaults are not specified since both keys are required. features={ 'image/encoded': tf.FixedLenFeature([], tf.string), 'image/class/label': tf.FixedLenFeature([], tf.int64), }) image = tf.decode_raw(features['image/encoded'], tf.uint8) label = tf.cast(features['image/class/label'], tf.int32) reshaped_image = tf.reshape(image,[size[0], size[1], 3]) reshaped_image = tf.image.resize_images(reshaped_image, size[0], size[1], method = 0) reshaped_image = tf.image.per_image_whitening(reshaped_image) return reshaped_image, label def inputs(train, batch_size, num_epochs): filename = os.path.join(FLAGS.train_dir, TRAIN_FILE if train else VALIDATION_FILE) filename_queue = tf.train.string_input_producer( [filename], num_epochs=num_epochs) # Even when reading in multiple threads, share the filename # queue. image, label = read_and_decode(filename_queue) # Shuffle the examples and collect them into batch_size batches. # (Internally uses a RandomShuffleQueue.) # We run this in two threads to avoid being a bottleneck. images, sparse_labels = tf.train.shuffle_batch( [image, label], batch_size=batch_size, num_threads=2, capacity=1000 + 3 * batch_size, # Ensures a minimum amount of shuffling of examples. min_after_dequeue=1000) return images, sparse_labels </code></pre> <p>But when I try to call a batch on iPython/Jupyter, the process never ends (there appears to be a loop). I call it this way:</p> <pre><code>batch_x, batch_y = inputs(True, 100,1) print batch_x.eval() </code></pre>
0
2016-09-04T16:41:03Z
39,319,342
<p>It looks like you are missing a call to <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#start_queue_runners" rel="nofollow"><code>tf.train.start_queue_runners()</code></a>, which starts the background threads that drive the input pipeline (e.g. some of these are the threads implied by <code>num_threads=2</code> in the call to <code>tf.train.shuffle_batch()</code>, and the <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/io_ops.html#string_input_producer" rel="nofollow"><code>tf.train.string_input_producer()</code></a> also requires a background thread). The following small change should unblock things:</p> <pre><code>batch_x, batch_y = inputs(True, 100,1) tf.initialize_all_variables.run() # Initializes variables. tf.initialize_local_variables.run() # Needed after TF version 0.10. tf.train.start_queue_runners() # Starts the necessary background threads. print batch_x.eval() </code></pre>
1
2016-09-04T16:57:05Z
[ "python", "tensorflow" ]
GtkOverlay hides GtkTextView
39,319,292
<p>I'm trying to develop an application using <code>Gtk</code>, and I have run into a problem using <code>GtkOverlay</code>. If I have a <code>GtkOverlay</code> with a <code>GtkTextView</code> that was added using the standard container <code>add</code> method, the text is hidden. However, all other widgets, say for example, buttons, appear just fine. Even more odd is the fact that this behavior is only present if at least one widget was adding using <code>add_overlay</code>.</p> <p><a href="http://i.stack.imgur.com/SG7up.png" rel="nofollow"><img src="http://i.stack.imgur.com/SG7up.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/CjYgD.png" rel="nofollow"><img src="http://i.stack.imgur.com/CjYgD.png" alt="enter image description here"></a></p> <pre><code>#!/usr/bin/env python import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk USE_OVERLAY = False win = Gtk.Window() text_view = Gtk.TextView() overlay = Gtk.Overlay() top_button = Gtk.Button() bottom_button = Gtk.Button() top_container = Gtk.VBox() bottom_container = Gtk.VBox() overlay_str = "( USE_OVERLAY = " + str(USE_OVERLAY) + ")" win.set_title(overlay_str) top_button.set_label("I'm a button on top!") bottom_button.set_label("I'm a button on bottom!") text_view.get_buffer().set_text("This should be visible") win.add(overlay) overlay.add(bottom_container) bottom_container.pack_start(bottom_button, False, False, 0) bottom_container.pack_end(text_view, True, True, 0) if USE_OVERLAY: overlay.add_overlay(top_container) top_container.pack_end(top_button, False, False, 0) win.connect("delete-event", Gtk.main_quit) overlay.show_all() win.show_all() Gtk.main() </code></pre> <p>I have reason to believe that this is not a python problem, as the actual application is written using <code>haskell-gi</code>, however I figured more people would be familiar with python.</p>
1
2016-09-04T16:51:21Z
39,320,180
<p>I don't know on what system your a running this example but it is working fine for me. The only caveat is that the top button appears over the bottom button and the <code>TextView</code> widget so I have to manually resize the <code>Window</code> to see the text. You can see a screen cast of my situation in this video: <a href="https://youtu.be/xoAH4OuEM0E" rel="nofollow">https://youtu.be/xoAH4OuEM0E</a></p> <p>Now depending on what you really want there may be few different answers. What I would suggest is putting the <code>TextView</code> inside a <a href="https://lazka.github.io/pgi-docs/Gtk-3.0/classes/ScrolledWindow.html" rel="nofollow"><code>ScrolledWindow</code></a>. This way the TextView will be at least visible before you would need the resize the window. It would also have the consequence to provide scrollbars if the text overflow the visible area.</p> <p>It could look like this:</p> <pre><code>import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk USE_OVERLAY = True win = Gtk.Window() text_view = Gtk.TextView() overlay = Gtk.Overlay() top_button = Gtk.Button() bottom_button = Gtk.Button() top_container = Gtk.VBox() bottom_container = Gtk.VBox() overlay_str = "( USE_OVERLAY = " + str(USE_OVERLAY) + ")" win.set_title(overlay_str) top_button.set_label("I'm a button on top!") bottom_button.set_label("I'm a button on bottom!") text_view.get_buffer().set_text("This should be visible") # This is where the text_view is inserted in a ScrolledWindow scrolled_window = Gtk.ScrolledWindow() scrolled_window.add(text_view) win.add(overlay) overlay.add(bottom_container) bottom_container.pack_start(bottom_button, False, False, 0) # The scrolled_window is inserted in the bottom_container bottom_container.pack_end(scrolled_window, True, True, 0) if USE_OVERLAY: overlay.add_overlay(top_container) top_container.pack_end(top_button, False, False, 0) win.connect("delete-event", Gtk.main_quit) overlay.show_all() win.show_all() Gtk.main() </code></pre> <p>You can also see the result on the aforementioned screencast. The only drawback is that the top button won't be able to overlay as much the bottom layer as in your script. But maybe it won't bother you.</p>
1
2016-09-04T18:27:41Z
[ "python", "user-interface", "haskell", "gtk" ]
How do I use a cookie session with pyramid & beaker to properly store a session_id?
39,319,295
<p>I am using the pyramid framework with beaker as a back-end for session management, and I want to store a session_id within a signed cookie. The session-id is associated with a real user_id, and the association mappings will be stored in something like redis. Can I simply use the configuration below to achieve this? The documentation doesn't provide a full implementation and only shows an example using an unsecure session factory. </p> <p>Here is my configuration file, redacted to session details:</p> <pre><code>session.type = cookie session.data_dir = %(here)s/data/sessions/data session.lock_dir = %(here)s/data/sessions/lock session.key = session_key session.secret = as98&amp;$Hh94 session.cookie_on_exception = true </code></pre> <p>Here is my <strong>init</strong>.py:</p> <pre><code>config = Configurator(settings=settings) config.include('pyramid_jinja2') config.include('pyramid_beaker') config.include('.models') config.include('.routes') config.include('polatick.models') config.scan() return config.make_wsgi_app() </code></pre> <p>Do I simply use the forget and remember functions in pyramid to do this properly?</p> <p>I was thinking of the process going something along the lines of something simple like this:</p> <pre><code>if user_authenticates(): session_id = create_session_id() redis.put_entry(session_id, user_id) request.session['session_id'] = session_id headers = remember(request, login) return HTTPFound('/', headers=headers) </code></pre> <p>I've been following this documentation:<br> <a href="http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/pylons/sessions.html" rel="nofollow">http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/pylons/sessions.html</a></p>
1
2016-09-04T16:51:50Z
39,326,333
<p>The Pyramid Community Cookbook is not official documentation. It is a collection of user-contributed recipes. That one in particular is targeted toward users of the web framework Pylons who are migrating solutions to Pyramid.</p> <p>Instead you should look at the official documentation on <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/sessions.html" rel="nofollow">Sessions</a>. This provides session implementation out of the box, and allows you to implement your own session factory.</p> <p>Following that, there is an implementation of sessions with authentication (and later on with authorization) in the <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/tutorials/wiki2/authentication.html" rel="nofollow">wiki tutorial</a>.</p> <p><a href="http://docs.pylonsproject.org/projects/pyramid-nacl-session/en/latest/" rel="nofollow">pyramid_nacl_session</a> defines an encrypting, pickle-based cookie serializer, using PyNaCl to generate the symmetric encryption for the cookie state.</p> <p>There is also <a href="http://pyramid-redis-sessions.readthedocs.io/en/latest/index.html" rel="nofollow">pyramid_redis_sessions</a>, a Pyramid add-on, which implements Pyramid's ISession interface, using Redis as its backend.</p> <p>Finally for a list of packages that provide sessions, authorization, or authentication, see <a href="https://trypyramid.com/resources-extending-pyramid.html" rel="nofollow">Try Pyramid - Extending Pyramid</a>.</p>
1
2016-09-05T08:12:53Z
[ "python", "session", "pyramid", "beaker" ]
Remove \n from python string
39,319,412
<p>I have scraped a webpage using beautiful soup. I'm trying to get rid of a '<code>\n</code>' character which isnt eliminated despite whatever I try. </p> <p>My effort so far:</p> <pre><code>wr=str(loc[i-1]).strip() wr=wr.replace(r"\[|'u|\\n","") print(wr) </code></pre> <p>Output:</p> <pre><code> [u'\nWong; Voon Hon (Singapore, SG Kandasamy; Ravi (Singapore, SG Narasimalu; Srikanth (Singapore, SG Larsen; Gerner (Hinnerup, DK Abeyasekera; Tusitha (Aarhus N, DK </code></pre> <p>How do I eliminate the [u'\n? What am I doing wrong?</p> <p>The full code is <a href="http://pastebin.com/Q9xREXUV" rel="nofollow">here</a>. </p>
-1
2016-09-04T17:03:44Z
39,319,482
<p>You need to escape the backslash or use a raw string. Otherwise, it's a newline character, not a literal <code>\n</code></p> <p>Also, I don't think beautifulsoup is outputting unicode strings. You see the string representation in python as <code>u'blah'</code></p> <p>And you shouldn't need a list of elements to remove. The expression can be </p> <pre><code>r"\[|'u|\n" </code></pre>
0
2016-09-04T17:11:38Z
[ "python", "parsing", "strip" ]
Remove \n from python string
39,319,412
<p>I have scraped a webpage using beautiful soup. I'm trying to get rid of a '<code>\n</code>' character which isnt eliminated despite whatever I try. </p> <p>My effort so far:</p> <pre><code>wr=str(loc[i-1]).strip() wr=wr.replace(r"\[|'u|\\n","") print(wr) </code></pre> <p>Output:</p> <pre><code> [u'\nWong; Voon Hon (Singapore, SG Kandasamy; Ravi (Singapore, SG Narasimalu; Srikanth (Singapore, SG Larsen; Gerner (Hinnerup, DK Abeyasekera; Tusitha (Aarhus N, DK </code></pre> <p>How do I eliminate the [u'\n? What am I doing wrong?</p> <p>The full code is <a href="http://pastebin.com/Q9xREXUV" rel="nofollow">here</a>. </p>
-1
2016-09-04T17:03:44Z
39,319,639
<p>You need to escape the newline character (double "\"):</p> <pre><code>rep=["[","u'","\\n"] for r in rep: wr=wr.replace(r,"") </code></pre> <p>This is the same as @cricket_007's answer, however, the second part from his answer does not work for me. To my knowledge, str.replace() does not support these kind of regular expression lookups.</p>
1
2016-09-04T17:30:49Z
[ "python", "parsing", "strip" ]
DataFrame Groupby while maintaining original DataFrame
39,319,556
<p>I have a DataFrame that has 9 columns which are encoded values for Day of the week(1-7), Week of the Year(1-52), Month of the Year (1-12), Time bin (every 3 hours), Salary Day(0,1) and Holiday(0,1) and Amount(real number). The time is placed in a time bin e.g. 15:00 is placed in 6th time bin and 7:34 is placed in the 3rd time bin. </p> <pre><code>Day Week Month Time Salary Holiday Amount 1 5 2 1 0 0 700.0 1 5 2 1 0 0 800.0 3 18 5 7 1 0 90.0 </code></pre> <p>Basically, I need to group the data by the first 6 columns and create a new column which is the summed value of Amount. However, this amount is will be repeated since I need to maintain the original dataframe. So, it must only sum purchases that have the same Day, Week, Month, Time, Salary and Holiday i.e. sum in that group. </p> <pre><code>Day Week Month Time Salary Holiday Amount Sum 1 5 2 1 0 0 700.0 1500.0 1 5 2 1 0 0 800.0 1500.0 3 18 5 7 1 0 90.0 90.0 </code></pre> <p>I have grouped the data frame by Day, Week, Month, Time, Salary, Holiday and summed Amount.</p> <pre><code>temp= features.groupby(by=["Day", "Week", "Month", "Time", "Salary", "Holiday"])["Amount"].sum() </code></pre>
0
2016-09-04T17:21:40Z
39,319,588
<p>You can reset the index on temp and then do an outer merge with the original feature dataframe on all the columns you grouped by.</p> <pre><code>result = features.merge(temp.reset_index(), on=["Day", "Week", "Month", "Time", "Salary", "Holiday"]) </code></pre>
0
2016-09-04T17:25:15Z
[ "python", "pandas", "dataframe", "group-by" ]
DataFrame Groupby while maintaining original DataFrame
39,319,556
<p>I have a DataFrame that has 9 columns which are encoded values for Day of the week(1-7), Week of the Year(1-52), Month of the Year (1-12), Time bin (every 3 hours), Salary Day(0,1) and Holiday(0,1) and Amount(real number). The time is placed in a time bin e.g. 15:00 is placed in 6th time bin and 7:34 is placed in the 3rd time bin. </p> <pre><code>Day Week Month Time Salary Holiday Amount 1 5 2 1 0 0 700.0 1 5 2 1 0 0 800.0 3 18 5 7 1 0 90.0 </code></pre> <p>Basically, I need to group the data by the first 6 columns and create a new column which is the summed value of Amount. However, this amount is will be repeated since I need to maintain the original dataframe. So, it must only sum purchases that have the same Day, Week, Month, Time, Salary and Holiday i.e. sum in that group. </p> <pre><code>Day Week Month Time Salary Holiday Amount Sum 1 5 2 1 0 0 700.0 1500.0 1 5 2 1 0 0 800.0 1500.0 3 18 5 7 1 0 90.0 90.0 </code></pre> <p>I have grouped the data frame by Day, Week, Month, Time, Salary, Holiday and summed Amount.</p> <pre><code>temp= features.groupby(by=["Day", "Week", "Month", "Time", "Salary", "Holiday"])["Amount"].sum() </code></pre>
0
2016-09-04T17:21:40Z
39,319,617
<p>You can use <code>transform</code> to return a column of the same size of the original data frame, from <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">the docs</a>:</p> <blockquote> <p>The transform method returns an object that is indexed the same (same size) as the one being grouped. Thus, the passed transform function should return a result that is the same size as the group chunk.</p> </blockquote> <pre><code>df['Sum'] = df.groupby(["Day", "Week", "Month", "Time", "Salary", "Holiday"]).transform('sum') df # Day Week Month Time Salary Holiday Amount Sum #0 1 5 2 1 0 0 700 1500 #1 1 5 2 1 0 0 800 1500 #2 3 18 5 7 1 0 90 90 </code></pre>
1
2016-09-04T17:28:04Z
[ "python", "pandas", "dataframe", "group-by" ]
Is there any way to let sympy simplify root(-1, 3) to -1?
39,319,584
<pre><code>root(-1, 3).simplify() (-1)**(1/3)//Output </code></pre> <p>This is not what I want, any way to simplify this to -1?</p>
4
2016-09-04T17:24:50Z
39,319,682
<p>Try </p> <pre><code>real_root(-1, 3) </code></pre> <p>It's referred to in the doc string of the root function too.</p> <p>The reason is simple: sympy, like many symbolic algebra systems, takes the complex plane into account when calculating "the root". There are 3 complex numbers that, when raised to the power of 3, result in -1. If you're just interested in the real-valued root, be as explicit as you can.</p>
8
2016-09-04T17:35:21Z
[ "python", "sympy" ]
Change all values exceeding threshold to the negative of itself
39,319,812
<p>I have an array with a bunch of rows and three columns. I have this code below which changes every value exceeding the threshold, to 0. Is there a trick to make the replace value to the negative of which number exceeds the threshold? Lets say i have an array <code>np.array([[1,2,3],[4,5,6],[7,8,9]])</code>. I choose column one and get an array with the values 1,4,7(first values of each row) If the threshold is 5, is there a way to make every value larger than 5 to the negative of it self, so that 1,4,7 changes to 1,4,-7?</p> <pre><code>import numpy as np arr = np.ndarray(my_array) threshold = 5 column_id = 0 replace_value = 0 arr[arr[:, column_id] &gt; threshold, column_id] = replace_value </code></pre>
0
2016-09-04T17:48:26Z
39,319,949
<p>Try this</p> <pre><code>In [37]: arr = np.array([[1,2,3],[4,5,6],[7,8,9]]) In [38]: arr[:, column_id] *= (arr[:, column_id] &gt; threshold) * -2 + 1 In [39]: arr Out[39]: array([[ 1, 2, 3], [ 4, 5, 6], [-7, 8, 9]]) </code></pre> <hr> <p>Sorry for editing later. I recommend below, which may be faster.</p> <pre><code>In [48]: arr Out[48]: array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) In [49]: col = arr[:, column_id] In [50]: col[col &gt; threshold] *= -1 In [51]: arr Out[51]: array([[ 1, 2, 3], [ 4, 5, 6], [-7, 8, 9]]) </code></pre>
2
2016-09-04T18:04:38Z
[ "python", "numpy" ]
Change all values exceeding threshold to the negative of itself
39,319,812
<p>I have an array with a bunch of rows and three columns. I have this code below which changes every value exceeding the threshold, to 0. Is there a trick to make the replace value to the negative of which number exceeds the threshold? Lets say i have an array <code>np.array([[1,2,3],[4,5,6],[7,8,9]])</code>. I choose column one and get an array with the values 1,4,7(first values of each row) If the threshold is 5, is there a way to make every value larger than 5 to the negative of it self, so that 1,4,7 changes to 1,4,-7?</p> <pre><code>import numpy as np arr = np.ndarray(my_array) threshold = 5 column_id = 0 replace_value = 0 arr[arr[:, column_id] &gt; threshold, column_id] = replace_value </code></pre>
0
2016-09-04T17:48:26Z
39,320,610
<pre><code> import numpy as np x= list(np.arange(1,10)) b = [] for i in x: if i &gt; 4: b.append(-i) else: b.append(i) print(b) e = np.array(b).reshape(3,3) print('changed array') print(e[:,0]) output : [1, 2, 3, 4, -5, -6, -7, -8, -9] changed array : [ 1 4 -7] </code></pre>
0
2016-09-04T19:19:14Z
[ "python", "numpy" ]
Translating email templates in Django
39,319,837
<p>I have an HTML template which I send through email using a Django installation. I'm trying to translate the content of the template (I've loaded i18n and all strings are in po files), but I keep getting the email rendered in English. </p> <p>I have the following code:</p> <pre><code>htmly = get_template(self.html_content) self.values_dict['LANGUAGE_CODE'] = 'es' d = Context(self.values_dict) html_content = htmly.render(d) process_mail.delay(subject=self.subject, message=self.message, from_email=self.from_email, recipient_list=self.recipient_list, html_content=html_content, html_type=self.html_type, attaches=self.attaches, mass=mass) </code></pre> <p>For debugging reasons, I've also put this on the template: </p> <pre><code>{% get_language_info for LANGUAGE_CODE as lang %} Language code: {{ lang.code }}&lt;br /&gt; Name of language: {{ lang.name_local }}&lt;br /&gt; Name in English: {{ lang.name }}&lt;br /&gt; Bi-directional: {{ lang.bidi }} Name in the active language: {{ lang.name_translated }} </code></pre> <p>Which outputs</p> <pre><code>Language code: es Name of language: español Name in English: Spanish Bi-directional: False Name in the active language: </code></pre> <p>Do you know what am I doing wrong?</p>
1
2016-09-04T17:51:10Z
39,319,923
<p>You don't seem to be actually activating the translation anywhere; all you've done is send a string, "es", as the LANGUAGE_CODE variable. In order to actually make things translated, you need to <a href="https://docs.djangoproject.com/en/1.10/topics/i18n/translation/#explicitly-setting-the-active-language" rel="nofollow">make that language the active one</a>:</p> <pre><code>from django.utils import translation translation.activate('es') </code></pre>
1
2016-09-04T18:01:37Z
[ "python", "django", "email", "internationalization", "translation" ]
Running multiple (i.e. normal and reversed) iterators simultaneously in a "for" loop
39,319,851
<p>Haven't found a satisfactory answer so far, hence posting this as a new question. </p> <p>I have to do the following:</p> <p>I have a parameter, e.g. <code>test_num = 5</code>. Now, in a single iteration of a <code>for</code> loop, I want the iterator to run both forwards and backwards simultaneously.</p> <p>So as an output, i want something like this:</p> <pre><code>Forward is 0, backward is 5. Forward is 1, backward is 4. Forward is 2, backward is 3. Forward is 3, backward is 2. Forward is 4, backward is 1. </code></pre> <p>The only thing that i could think up of, is:</p> <pre><code>test_num = 5 for j in range(test_num): for i in range(test_num, 0, -1): print "Forward is ", i, ", Backward is ", j </code></pre> <p>But this is obviously not the right approach. Is using <code>zip</code> the only option? Because <code>zip</code> only works in case if i'm using the same parameter or in case of two parameters which are equal. I'm looking for something that's flexible enough. </p>
-2
2016-09-04T17:52:55Z
39,319,892
<p>Looks like your code is pretty good but you only need 1 iterator.</p> <pre><code>for x in range(5): print(str(x)+'_'+str(5-x)) </code></pre> <p>That will give you the right idea</p>
1
2016-09-04T17:58:18Z
[ "python", "for-loop", "iterator" ]
Running multiple (i.e. normal and reversed) iterators simultaneously in a "for" loop
39,319,851
<p>Haven't found a satisfactory answer so far, hence posting this as a new question. </p> <p>I have to do the following:</p> <p>I have a parameter, e.g. <code>test_num = 5</code>. Now, in a single iteration of a <code>for</code> loop, I want the iterator to run both forwards and backwards simultaneously.</p> <p>So as an output, i want something like this:</p> <pre><code>Forward is 0, backward is 5. Forward is 1, backward is 4. Forward is 2, backward is 3. Forward is 3, backward is 2. Forward is 4, backward is 1. </code></pre> <p>The only thing that i could think up of, is:</p> <pre><code>test_num = 5 for j in range(test_num): for i in range(test_num, 0, -1): print "Forward is ", i, ", Backward is ", j </code></pre> <p>But this is obviously not the right approach. Is using <code>zip</code> the only option? Because <code>zip</code> only works in case if i'm using the same parameter or in case of two parameters which are equal. I'm looking for something that's flexible enough. </p>
-2
2016-09-04T17:52:55Z
39,319,926
<p>If you really want to use two iterators, try using the <code>zip()</code> function:</p> <pre><code>for i,j in zip(range(5), range(5, 0, -1)): print "Forward is {0}, backward is {1}".format(i, j) #Forward is 0, backward is 5. #Forward is 1, backward is 4. #Forward is 2, backward is 3. #Forward is 3, backward is 2. #Forward is 4, backward is 1. </code></pre> <p>However, your particular use case seems easy enough to do using 1 iterator:</p> <pre><code>for i in range(5) print "Forward is {0}, backward is {1}".format(i, 5-i) #Forward is 0, backward is 5. #Forward is 1, backward is 4. #Forward is 2, backward is 3. #Forward is 3, backward is 2. #Forward is 4, backward is 1. </code></pre>
0
2016-09-04T18:02:05Z
[ "python", "for-loop", "iterator" ]
Running multiple (i.e. normal and reversed) iterators simultaneously in a "for" loop
39,319,851
<p>Haven't found a satisfactory answer so far, hence posting this as a new question. </p> <p>I have to do the following:</p> <p>I have a parameter, e.g. <code>test_num = 5</code>. Now, in a single iteration of a <code>for</code> loop, I want the iterator to run both forwards and backwards simultaneously.</p> <p>So as an output, i want something like this:</p> <pre><code>Forward is 0, backward is 5. Forward is 1, backward is 4. Forward is 2, backward is 3. Forward is 3, backward is 2. Forward is 4, backward is 1. </code></pre> <p>The only thing that i could think up of, is:</p> <pre><code>test_num = 5 for j in range(test_num): for i in range(test_num, 0, -1): print "Forward is ", i, ", Backward is ", j </code></pre> <p>But this is obviously not the right approach. Is using <code>zip</code> the only option? Because <code>zip</code> only works in case if i'm using the same parameter or in case of two parameters which are equal. I'm looking for something that's flexible enough. </p>
-2
2016-09-04T17:52:55Z
39,319,972
<p>fastest solution:</p> <pre><code>test_num = 5 for i in range(test_num): print("Forward is %d, backward is %d."%(i, test_num-i)) </code></pre> <p>another fast solution(my solution if you wont use <code>test_num-i</code> expression) :</p> <pre><code>test_num = 5 for i,j in enumerate(range(test_num,0,-1)): print("Forward is %d, backward is %d."%(i, j)) </code></pre> <p>another solution using zip (if you want use zip! but is slow):</p> <pre><code>test_num = 5 for i,j in zip(range(test_num), range(test_num, 0, -1)): print("Forward is %d, backward is %d."%(i, j)) </code></pre> <p><strong>benchmarks:</strong></p> <pre><code>timeit.timeit('for i in range(5):pass', number=10000) # 0.004307041002903134 timeit.timeit('for i,j in enumerate(range(5,0,-1)): pass', number=10000) # 0.007563826999103185 timeit.timeit('for i,j in zip(range(5), range(5, 0, -1)): pass', number=10000) # 0.010275325999828056 </code></pre>
0
2016-09-04T18:07:05Z
[ "python", "for-loop", "iterator" ]
python regex find matched string
39,319,897
<p>I am trying to find the matched string in a string using regex in Python. The <code>string</code> looks like this:</p> <pre><code>band 1 # energy -53.15719532 # occ. 2.00000000 ion s p d tot 1 0.000 0.995 0.000 0.995 2 0.000 0.000 0.000 0.000 tot 0.000 0.996 0.000 0.996 band 2 # energy -53.15719532 # occ. 2.00000000 ion s p d tot 1 0.000 0.995 0.000 0.995 2 0.000 0.000 0.000 0.000 tot 0.000 0.996 0.000 0.996 band 3 # energy -53.15719532 # occ. 2.00000000 </code></pre> <p>My goal is to find the string after <code>tot</code>. So the matched string will be something like:</p> <pre><code>['0.000 0.996 0.000 0.996', '0.000 0.996 0.000 0.996'] </code></pre> <p>Here is my current code:</p> <pre><code>pattern = re.compile(r'tot\s+(.*?)\n', re.DOTALL) pattern.findall(string) </code></pre> <p>However, the output gives me:</p> <pre><code>['1 0.000 0.995 0.000 0.995', '0.000 0.996 0.000 0.996', '1 0.000 0.995 0.000 0.995', '0.000 0.996 0.000 0.996'] </code></pre> <p>Any idea of what I am doing wrong?</p>
1
2016-09-04T17:59:02Z
39,319,931
<p>You don't want the <code>DOTALL</code> flag. Remove it and use <a href="https://docs.python.org/2/library/re.html#re.MULTILINE" rel="nofollow"><code>MULTILINE</code></a> instead.</p> <pre><code>pattern = re.compile(r'^\s*tot(.*)', re.MULTILINE) </code></pre> <p>This matches all lines that start with <code>tot</code>. The rest of the line will be in group 1.</p> <p>Citing the <a href="https://docs.python.org/2/library/re.html#re.DOTALL" rel="nofollow">documentation</a>, emphasis mine:</p> <blockquote> <p><code>re.DOTALL</code></p> <p>Make the <code>'.'</code> special character match any character at all, <strong>including a newline</strong>; without this flag, <code>'.'</code> will match anything except a newline.</p> </blockquote> <p>Note that you can easily do this without regex.</p> <pre><code>with open("input.txt", "r") as data_file: for line in data_file: items = filter(None, line.split(" ")) if items[0] == "tot": # etc </code></pre>
4
2016-09-04T18:02:41Z
[ "python", "regex" ]
python regex find matched string
39,319,897
<p>I am trying to find the matched string in a string using regex in Python. The <code>string</code> looks like this:</p> <pre><code>band 1 # energy -53.15719532 # occ. 2.00000000 ion s p d tot 1 0.000 0.995 0.000 0.995 2 0.000 0.000 0.000 0.000 tot 0.000 0.996 0.000 0.996 band 2 # energy -53.15719532 # occ. 2.00000000 ion s p d tot 1 0.000 0.995 0.000 0.995 2 0.000 0.000 0.000 0.000 tot 0.000 0.996 0.000 0.996 band 3 # energy -53.15719532 # occ. 2.00000000 </code></pre> <p>My goal is to find the string after <code>tot</code>. So the matched string will be something like:</p> <pre><code>['0.000 0.996 0.000 0.996', '0.000 0.996 0.000 0.996'] </code></pre> <p>Here is my current code:</p> <pre><code>pattern = re.compile(r'tot\s+(.*?)\n', re.DOTALL) pattern.findall(string) </code></pre> <p>However, the output gives me:</p> <pre><code>['1 0.000 0.995 0.000 0.995', '0.000 0.996 0.000 0.996', '1 0.000 0.995 0.000 0.995', '0.000 0.996 0.000 0.996'] </code></pre> <p>Any idea of what I am doing wrong?</p>
1
2016-09-04T17:59:02Z
39,319,969
<p>You are using re.DOTALL, which means that the dot "." will match anything, even newlines, in essence finding both "tot"-s and everything that follows until the next newline:</p> <pre><code> tot 1 0.000 0.995 0.000 0.995 </code></pre> <p>and</p> <pre><code>tot 0.000 0.996 0.000 0.996 </code></pre> <p>Removing re.DOTALL should fix your problem.</p> <p>Edit: Actually, the DOTALL flag is not really the issue (though unnecessary). The problem in the pattern is that the \s+ matches the newline. Replacing that with a single space solves that issue:</p> <pre><code>pattern = re.compile(r'tot (.*?)\n') </code></pre>
1
2016-09-04T18:06:42Z
[ "python", "regex" ]
python regex find matched string
39,319,897
<p>I am trying to find the matched string in a string using regex in Python. The <code>string</code> looks like this:</p> <pre><code>band 1 # energy -53.15719532 # occ. 2.00000000 ion s p d tot 1 0.000 0.995 0.000 0.995 2 0.000 0.000 0.000 0.000 tot 0.000 0.996 0.000 0.996 band 2 # energy -53.15719532 # occ. 2.00000000 ion s p d tot 1 0.000 0.995 0.000 0.995 2 0.000 0.000 0.000 0.000 tot 0.000 0.996 0.000 0.996 band 3 # energy -53.15719532 # occ. 2.00000000 </code></pre> <p>My goal is to find the string after <code>tot</code>. So the matched string will be something like:</p> <pre><code>['0.000 0.996 0.000 0.996', '0.000 0.996 0.000 0.996'] </code></pre> <p>Here is my current code:</p> <pre><code>pattern = re.compile(r'tot\s+(.*?)\n', re.DOTALL) pattern.findall(string) </code></pre> <p>However, the output gives me:</p> <pre><code>['1 0.000 0.995 0.000 0.995', '0.000 0.996 0.000 0.996', '1 0.000 0.995 0.000 0.995', '0.000 0.996 0.000 0.996'] </code></pre> <p>Any idea of what I am doing wrong?</p>
1
2016-09-04T17:59:02Z
39,319,992
<p>The alternative solution using <code>re.findall</code> function with specific regex pattern:</p> <pre><code># str is your inital string result = re.findall('tot [0-9 .]+(?=\n|$)', str) print(result) </code></pre> <p>The output:</p> <pre><code>['tot 0.000 0.996 0.000 0.996', 'tot 0.000 0.996 0.000 0.996'] </code></pre>
1
2016-09-04T18:09:04Z
[ "python", "regex" ]
Python 3 - float(X) * i = int(Z)
39,320,068
<p>I have a very large number, both before and after the decimal, but for this I'll just call it 4.58.</p> <p>I want to know the number, Y, that will yield me an integer if multiplied by X and not any sort of float number.</p> <p>Here is my code:</p> <pre><code>from decimal import * setcontext(ExtendedContext) getcontext().prec = 300 x=Decimal('4.58') while True: i=1 a=Decimal(i*x) if float(a).is_integer(): print(i*x) break else: i=+1 </code></pre> <p>However, this method is incredibly slow and inefficient. I was wondering how could I implement continued fractions or some other method to make it predict the value of Y?</p> <p><em>Edit</em></p> <p>The decimal module stores float numbers more accurately (As strings), so 0.5 <em>won't</em> become 0.499999999.</p> <p><em>Edit 2</em></p> <p>I've got X (4.58).</p> <p>I want to know what number will multiply by X to make an integer; as efficiently as possible.</p> <p><strong>Edit 3</strong></p> <p>Okay, maybe not my best question yet.</p> <p>Here's my dilemma.</p> <p>I've got a number spat out from a trivial programme I made. That number is a decimal number, 1.5.</p> <p>All I want to do is find what integer will multiply by my decimal to yield another integer.</p> <p>For 1.5, the best answer will be 2. (1.5*2=3) (float*int=int)</p> <p>My while-loop above will do that, eventually, but I just wanted to know whether there was a better way to do this, such as continued fractions; and if there was, how could I implement it.</p> <p><em>Edit 4</em></p> <p>Here's my code thanks to user6794072. It's lengthy but functional.</p> <pre><code>from gmpy2 import mpz, isqrt from fractions import Fraction import operator import functools from decimal import * setcontext(ExtendedContext) getcontext().prec = 300 def factors(n): n = mpz(n) result = set() result |= {mpz(1), n} def all_multiples(result, n, factor): z = n f = mpz(factor) while z % f == 0: result |= {f, z // f} f += factor return result result = all_multiples(result, n, 2) result = all_multiples(result, n, 3) for i in range(1, isqrt(n) + 1, 6): i1 = i + 1 i2 = i + 5 if not n % i1: result |= {mpz(i1), n // i1} if not n % i2: result |= {mpz(i2), n // i2} return result j=Decimal('4.58') a=(Fraction(j).numerator) b=(Fraction(j).denominator) y=(factors(a)) x=(factors(b)) q=([item for item in x if item not in y]) w=([item for item in y if item not in x]) q.extend(w) p=(functools.reduce(operator.mul, q, 1)) ans=(p*j) print(ans) </code></pre>
-4
2016-09-04T18:16:20Z
39,320,106
<p>Well think of what if you wanted to reach <code>z = 1</code> and then use the fact that <code>z == z * 1</code> to scale the answer. For any float <code>x != 0.0</code>, <code>y = 1/x</code> will yield <code>z = 1</code>, so for arbitrary integer <code>z</code>, just use <code>y = z/x</code>.</p>
0
2016-09-04T18:19:54Z
[ "python", "python-3.x", "loops", "math", "floating-point" ]
Python 3 - float(X) * i = int(Z)
39,320,068
<p>I have a very large number, both before and after the decimal, but for this I'll just call it 4.58.</p> <p>I want to know the number, Y, that will yield me an integer if multiplied by X and not any sort of float number.</p> <p>Here is my code:</p> <pre><code>from decimal import * setcontext(ExtendedContext) getcontext().prec = 300 x=Decimal('4.58') while True: i=1 a=Decimal(i*x) if float(a).is_integer(): print(i*x) break else: i=+1 </code></pre> <p>However, this method is incredibly slow and inefficient. I was wondering how could I implement continued fractions or some other method to make it predict the value of Y?</p> <p><em>Edit</em></p> <p>The decimal module stores float numbers more accurately (As strings), so 0.5 <em>won't</em> become 0.499999999.</p> <p><em>Edit 2</em></p> <p>I've got X (4.58).</p> <p>I want to know what number will multiply by X to make an integer; as efficiently as possible.</p> <p><strong>Edit 3</strong></p> <p>Okay, maybe not my best question yet.</p> <p>Here's my dilemma.</p> <p>I've got a number spat out from a trivial programme I made. That number is a decimal number, 1.5.</p> <p>All I want to do is find what integer will multiply by my decimal to yield another integer.</p> <p>For 1.5, the best answer will be 2. (1.5*2=3) (float*int=int)</p> <p>My while-loop above will do that, eventually, but I just wanted to know whether there was a better way to do this, such as continued fractions; and if there was, how could I implement it.</p> <p><em>Edit 4</em></p> <p>Here's my code thanks to user6794072. It's lengthy but functional.</p> <pre><code>from gmpy2 import mpz, isqrt from fractions import Fraction import operator import functools from decimal import * setcontext(ExtendedContext) getcontext().prec = 300 def factors(n): n = mpz(n) result = set() result |= {mpz(1), n} def all_multiples(result, n, factor): z = n f = mpz(factor) while z % f == 0: result |= {f, z // f} f += factor return result result = all_multiples(result, n, 2) result = all_multiples(result, n, 3) for i in range(1, isqrt(n) + 1, 6): i1 = i + 1 i2 = i + 5 if not n % i1: result |= {mpz(i1), n // i1} if not n % i2: result |= {mpz(i2), n // i2} return result j=Decimal('4.58') a=(Fraction(j).numerator) b=(Fraction(j).denominator) y=(factors(a)) x=(factors(b)) q=([item for item in x if item not in y]) w=([item for item in y if item not in x]) q.extend(w) p=(functools.reduce(operator.mul, q, 1)) ans=(p*j) print(ans) </code></pre>
-4
2016-09-04T18:16:20Z
39,320,131
<p>I'm not a Python programmer, but what about <a href="https://docs.python.org/3/library/functions.html#round" rel="nofollow">round</a> function?</p>
0
2016-09-04T18:22:04Z
[ "python", "python-3.x", "loops", "math", "floating-point" ]
Python 3 - float(X) * i = int(Z)
39,320,068
<p>I have a very large number, both before and after the decimal, but for this I'll just call it 4.58.</p> <p>I want to know the number, Y, that will yield me an integer if multiplied by X and not any sort of float number.</p> <p>Here is my code:</p> <pre><code>from decimal import * setcontext(ExtendedContext) getcontext().prec = 300 x=Decimal('4.58') while True: i=1 a=Decimal(i*x) if float(a).is_integer(): print(i*x) break else: i=+1 </code></pre> <p>However, this method is incredibly slow and inefficient. I was wondering how could I implement continued fractions or some other method to make it predict the value of Y?</p> <p><em>Edit</em></p> <p>The decimal module stores float numbers more accurately (As strings), so 0.5 <em>won't</em> become 0.499999999.</p> <p><em>Edit 2</em></p> <p>I've got X (4.58).</p> <p>I want to know what number will multiply by X to make an integer; as efficiently as possible.</p> <p><strong>Edit 3</strong></p> <p>Okay, maybe not my best question yet.</p> <p>Here's my dilemma.</p> <p>I've got a number spat out from a trivial programme I made. That number is a decimal number, 1.5.</p> <p>All I want to do is find what integer will multiply by my decimal to yield another integer.</p> <p>For 1.5, the best answer will be 2. (1.5*2=3) (float*int=int)</p> <p>My while-loop above will do that, eventually, but I just wanted to know whether there was a better way to do this, such as continued fractions; and if there was, how could I implement it.</p> <p><em>Edit 4</em></p> <p>Here's my code thanks to user6794072. It's lengthy but functional.</p> <pre><code>from gmpy2 import mpz, isqrt from fractions import Fraction import operator import functools from decimal import * setcontext(ExtendedContext) getcontext().prec = 300 def factors(n): n = mpz(n) result = set() result |= {mpz(1), n} def all_multiples(result, n, factor): z = n f = mpz(factor) while z % f == 0: result |= {f, z // f} f += factor return result result = all_multiples(result, n, 2) result = all_multiples(result, n, 3) for i in range(1, isqrt(n) + 1, 6): i1 = i + 1 i2 = i + 5 if not n % i1: result |= {mpz(i1), n // i1} if not n % i2: result |= {mpz(i2), n // i2} return result j=Decimal('4.58') a=(Fraction(j).numerator) b=(Fraction(j).denominator) y=(factors(a)) x=(factors(b)) q=([item for item in x if item not in y]) w=([item for item in y if item not in x]) q.extend(w) p=(functools.reduce(operator.mul, q, 1)) ans=(p*j) print(ans) </code></pre>
-4
2016-09-04T18:16:20Z
39,320,761
<p>If I understand your question correctly, you want to find the smallest integer (i) that can be multiplied to a non-integer number (n) so that:</p> <p>i*n is an integer</p> <p>I would do this by finding the factors of the numerator and denominator for n. In your example, if n = 4.58, then you can extract 458 for the numerator and 100 for the denominator.</p> <p>The multiples of 458 are 2 and 229 The multiples of 100 are 2, 2, 5, 5</p> <p>You can cross off one instance of 2 for the numerator and denominator. Then your solution is just multiplying the remaining factors in the denominator: in this case, 2*5*5 or 50. </p>
1
2016-09-04T19:36:20Z
[ "python", "python-3.x", "loops", "math", "floating-point" ]
imputing missing values using a predictive model
39,320,135
<p>I am trying to impute missing values in Python and <code>sklearn</code> does not appear to have a method beyond average (mean, median, or mode) imputation. <a href="http://docs.orange.biolab.si/2/reference/rst/Orange.feature.imputation.html#Orange.feature.imputation.Model" rel="nofollow">Orange imputation model</a> seems to provide a viable option. However, it appears <code>Orange.data.Table</code> is not recognizing <code>np.nan</code> or somehow the imputation is failing.</p> <pre><code>import Orange import numpy as np tmp = np.array([[1, 2, np.nan, 5, 8, np.nan], [40, 4, 8, 1, 0.2, 9]]) data = Orange.data.Table(tmp) imputer = Orange.feature.imputation.ModelConstructor() imputer.learner_continuous = Orange.classification.tree.TreeLearner(min_subset=20) imputer = imputer(data ) impdata = imputer(data) for i in range(0, len(tmp)): print impdata[i] </code></pre> <p>Output is </p> <pre><code>[1.000, 2.000, 1.#QO, 5.000, 8.000, 1.#QO] [40.000, 4.000, 8.000, 1.000, 0.200, 9.000] </code></pre> <p>Any idea what I am missing? Thanks!</p>
2
2016-09-04T18:23:01Z
39,322,615
<p>It seems the issue is that a missing value in Orange is represented as <code>?</code> or <code>~</code>. Oddly enough, the <code>Orange.data.Table(numpy.ndarray)</code> constructor does not infer that <code>numpy.nan</code> should be converted to <code>?</code> or <code>~</code> and instead converts them to <code>1.#QO</code>. The custom function below, <code>pandas_to_orange()</code>, addresses this problem. </p> <pre><code>import Orange import numpy as np import pandas as pd from collections import OrderedDict # Adapted from https://github.com/biolab/orange3/issues/68 def construct_domain(df): columns = OrderedDict(df.dtypes) def create_variable(col): if col[1].__str__().startswith('float'): return Orange.feature.Continuous(col[0]) if col[1].__str__().startswith('int') and len(df[col[0]].unique()) &gt; 50: return Orange.feature.Continuous(col[0]) if col[1].__str__().startswith('date'): df[col[0]] = df[col[0]].values.astype(np.str) if col[1].__str__() == 'object': df[col[0]] = df[col[0]].astype(type("")) return Orange.feature.Discrete(col[0], values = df[col[0]].unique().tolist()) return Orange.data.Domain(list(map(create_variable, columns.items()))) def pandas_to_orange(df): domain = construct_domain(df) df[pd.isnull(df)]='?' return Orange.data.Table(Orange.data.Domain(domain), df.values.tolist()) df = pd.DataFrame({'col1':[1, 2, np.nan, 4, 5, 6, 7, 8, 9, np.nan, 11], 'col2': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110.]}) tmp = pandas_to_orange(df) for i in range(0, len(tmp)): print tmp[i] </code></pre> <p>The output is:</p> <pre><code>[1.000, 10.000] [2.000, 20.000] [?, 30.000] [4.000, 40.000] [5.000, 50.000] [6.000, 60.000] [7.000, 70.000] [8.000, 80.000] [9.000, 90.000] [?, 100.000] [11.000, 110.000] </code></pre> <p>The reason I wanted to properly encode the missing values is so I can use the Orange imputation library. However, it appears that the predictive tree model in the library does not do much more than simple mean imputation. Specifically, it imputes the same value for all missing values. </p> <pre><code>imputer = Orange.feature.imputation.ModelConstructor() imputer.learner_continuous = Orange.classification.tree.TreeLearner(min_subset=20) imputer = imputer(tmp ) impdata = imputer(tmp) for i in range(0, len(tmp)): print impdata[i] </code></pre> <p>Here's the output:</p> <pre><code>[1.000, 10.000] [2.000, 20.000] [5.889, 30.000] [4.000, 40.000] [5.000, 50.000] [6.000, 60.000] [7.000, 70.000] [8.000, 80.000] [9.000, 90.000] [5.889, 100.000] [11.000, 110.000] </code></pre> <p>I was looking for something that will fit a model, say kNN, on the complete cases and use the fitted model to predict the missing cases. <a href="https://pypi.python.org/pypi/fancyimpute" rel="nofollow"><code>fancyimpute</code> (a Python 3 package)</a> does this but throws <code>MemoryError</code> on my 300K+ input.</p> <pre><code>from fancyimpute import KNN df = pd.DataFrame({'col1':[1, 2, np.nan, 4, 5, 6, 7, 8, 9, np.nan, 11], 'col2': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110.]}) X_filled_knn = KNN(k=3).complete(df) X_filled_knn </code></pre> <p>Output is:</p> <pre><code>array([[ 1. , 10. ], [ 2. , 20. ], [ 2.77777784, 30. ], [ 4. , 40. ], [ 5. , 50. ], [ 6. , 60. ], [ 7. , 70. ], [ 8. , 80. ], [ 9. , 90. ], [ 9.77777798, 100. ], [ 11. , 110. ]]) </code></pre> <p>I can probably find a workaround or split the dataset into chunks (not ideal).</p>
1
2016-09-05T00:28:10Z
[ "python", "python-2.7", "scikit-learn", "orange", "imputation" ]
imputing missing values using a predictive model
39,320,135
<p>I am trying to impute missing values in Python and <code>sklearn</code> does not appear to have a method beyond average (mean, median, or mode) imputation. <a href="http://docs.orange.biolab.si/2/reference/rst/Orange.feature.imputation.html#Orange.feature.imputation.Model" rel="nofollow">Orange imputation model</a> seems to provide a viable option. However, it appears <code>Orange.data.Table</code> is not recognizing <code>np.nan</code> or somehow the imputation is failing.</p> <pre><code>import Orange import numpy as np tmp = np.array([[1, 2, np.nan, 5, 8, np.nan], [40, 4, 8, 1, 0.2, 9]]) data = Orange.data.Table(tmp) imputer = Orange.feature.imputation.ModelConstructor() imputer.learner_continuous = Orange.classification.tree.TreeLearner(min_subset=20) imputer = imputer(data ) impdata = imputer(data) for i in range(0, len(tmp)): print impdata[i] </code></pre> <p>Output is </p> <pre><code>[1.000, 2.000, 1.#QO, 5.000, 8.000, 1.#QO] [40.000, 4.000, 8.000, 1.000, 0.200, 9.000] </code></pre> <p>Any idea what I am missing? Thanks!</p>
2
2016-09-04T18:23:01Z
39,333,351
<p>In Orange v2 you can pass numpy masked arrays into the Orange.data.Table constructor. Modifying your example:</p> <pre class="lang-python prettyprint-override"><code>import Orange import numpy as np tmp = np.array([[1, 2, np.nan, 5, 8, np.nan], [40, 4, 8, 1, 0.2, 9]]) tmp_masked = np.ma.masked_array(tmp, mask=np.isnan(tmp)) data = Orange.data.Table(tmp_masked) imputer = Orange.feature.imputation.ModelConstructor() imputer.learner_continuous = Orange.classification.tree.TreeLearner(min_subset=20) imputer = imputer(data ) impdata = imputer(data) for i in range(0, len(tmp)): print impdata[i] </code></pre>
0
2016-09-05T15:04:36Z
[ "python", "python-2.7", "scikit-learn", "orange", "imputation" ]
Update a label in tkinter from a button press
39,320,190
<p>My question is regarding GUI programming in python by using tkinter. I believe this is Python 3x. </p> <p>My question: While we're executing a program to run the GUI, can a button update a label? More specifically, is there a way to change the labels displayed text after pushing the button? I have consulted stack overflow on this before and adopted the StringVar() method, but it doesn't seem to fix my problem, in fact it omits the text from the GUI completely!</p> <p>Here is the code below</p> <pre><code>from tkinter import * root = Tk() root.title('Copy Text GUI Program') copiedtext = StringVar() copiedtext.set("Text is displayed here") def copytext(): copiedtext.set(textentered.get()) # Write 'Enter Text Here' entertextLabel = Label(root, text="Enter Text Here") entertextLabel.grid(row=0, column=0) # For the user to write text into the gui textentered = Entry(root) textentered.grid(row=0, column=1) # The Copy Text Button copytextButton = Button(root, text="Copy Text") copytextButton.grid(row=1, columnspan=2) # Display the copied text displaytextLabel = Label(root, textvariable=copiedtext) displaytextLabel.grid(row=2,columnspan=2) copytextButton.configure(command=copytext()) root.mainloop() </code></pre> <p>Any help would be appreciated!</p>
0
2016-09-04T18:29:23Z
39,320,291
<p>What you have to do is to bind a Button event to the copytextButton object like so:</p> <pre><code>copytextButton.bind('&lt;Button-1&gt;', copytext) </code></pre> <p>This means that a callback function - copytext() will be called when you left-click the button.</p> <p>A slight modification is needed in the function itself, since the callback sends an event argument:</p> <pre><code>def copytext(event): copiedtext.set(textentered.get()) </code></pre> <p>Edit: This line is not needed:</p> <pre><code>copytextButton.configure(command=copytext()) </code></pre>
0
2016-09-04T18:40:46Z
[ "python", "tkinter" ]
selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with
39,320,283
<p>Currently working to use Python to login with Twitter.</p> <p>Twitter's login page is <a href="https://twitter.com/login" rel="nofollow">here</a>. The source code where the Username and Password input fields are:</p> <pre><code>&lt;div class="LoginForm-input LoginForm-username"&gt; &lt;input type="text" class="text-input email-input js-signin-email" name="session[username_or_email]" autocomplete="username" placeholder="Phone, email or username" /&gt; &lt;/div&gt; &lt;div class="LoginForm-input LoginForm-password"&gt; &lt;input type="password" class="text-input" name="session[password]" placeholder="Password" autocomplete="current-password"&gt; &lt;/div&gt; </code></pre> <p>So when I write my code in Python utilizing the Selenium module:</p> <pre><code># -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("https://twitter.com/login") elem = driver.find_element_by_name("session[username_or_email]") elem.clear() elem.send_keys(username) elem = driver.find_element_by_name("session[password]") elem.clear() elem.send_keys(password) elem.send_keys(Keys.RETURN) sleep(delay) </code></pre> <p>The error that is returned:</p> <blockquote> <p>selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with</p> </blockquote> <p>Any help? Thanks! I have read of the responses of other similar questions, but have not helped much.</p> <p><strong>Edit:</strong></p> <p>Full error message:</p> <pre><code>Traceback (most recent call last): File "main.py", line 154, in &lt;module&gt; main() File "main.py", line 143, in main twitterBruteforce(username, wordlist, delay) File "src/twitterLib.py", line 27, in twitterBruteforce elem.clear() File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 88, in clear self._execute(Command.CLEAR_ELEMENT) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 457, in _execute return self._parent.execute(command, params) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 233, in execute self.error_handler.check_response(response) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with Stacktrace: at fxdriver.preconditions.visible (file:///tmp/tmpurkUhr/extensions/fxdriver@googlecode.com/components/command-processor.js:10092) at DelayedCommand.prototype.checkPreconditions_ (file:///tmp/tmpurkUhr/extensions/fxdriver@googlecode.com/components/command-processor.js:12644) at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpurkUhr/extensions/fxdriver@googlecode.com/components/command-processor.js:12661) at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpurkUhr/extensions/fxdriver@googlecode.com/components/command-processor.js:12666) at DelayedCommand.prototype.execute/&lt; (file:///tmp/tmpurkUhr/extensions/fxdriver@googlecode.com/components/command-processor.js:12608) </code></pre>
1
2016-09-04T18:39:50Z
39,323,178
<p>You should try using <code>WebDriverWait</code> to wait until element visible before interaction to the element as below :-</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) user = wait.until(EC.visibility_of_element_located((By.NAME, "session[username_or_email]"))) user.clear() user.send_keys(username) pass = wait.until(EC.visibility_of_element_located((By.NAME, "session[password]"))) pass.clear() pass.send_keys(password) </code></pre> <p><strong>Note</strong> :- instead of <code>send_keys(Keys.RETURN)</code> try using <code>click()</code> to the login button element as <code>login_button_element.click()</code> or try using <code>submit()</code> to the form element as <code>form_element.submit()</code> after locating these elements.</p>
1
2016-09-05T02:29:46Z
[ "python", "selenium" ]
How to pip install a celery task module
39,320,288
<p>I have a django REST API setup on one machine (currently in test on local machine but will be on a web server eventually). Let's call this machine "client". I also have a computing server to run CPU-intensive tasks that requires a long execution time. Let's call this machine "run-server".</p> <p>"run-server" runs a celery worker connected to a local rabbitmq server. The worker currently is in a git module with this structure:</p> <pre><code>proj/ client.py cmd.sh requirements.txt tasks.py </code></pre> <p>The whole thing runs in a virtualenv for what it's worth. The <code>cmd.sh</code> basically executes <code>celery multi start workername -A tasks -l info</code> on "run-server". The <code>client.py</code> is a cli script that can submit a tasks to the "run-server" manually from the shell from any machine (i.e. the "client"). </p> <p>I want to run the equivalent of the client script from a django setup <em>without</em> having to copy the <code>tasks.py</code> and <code>client.py</code> code in the django repository. Ideally I would <code>pip install proj</code> from the django code and import proj to use it just like the client script does.</p> <p><strong><em>How can I package proj to achieve that?</em></strong></p> <p>I am used to package my own python module with a structure roughly looking like:</p> <pre><code>proj/ bin/ proj proj/ __init__.py __main__.py script.py setup.py requirements.txt </code></pre>
0
2016-09-04T18:40:32Z
39,334,680
<p>I managed to make it work on my own. The structure above just works. Instead of <code>celery multi start workername -A tasks -l info</code>, you simply replace with <code>celery multi start workername -A proj.tasks -l info</code> and everything works. The same version of the module have to be installed within django and as the worker because the job queuein is done via duck-typing (i.e. the path and names must match)</p>
0
2016-09-05T16:38:52Z
[ "python", "django", "rabbitmq", "celery" ]
python - ImportError: No module named scipy on Mac
39,320,344
<p>It's been so hard to find solution for this problem.</p> <p>I've been reading on the internet and found this questions on Stackoverflow:</p> <p><a href="http://stackoverflow.com/questions/29223187/importerror-no-module-named-scipy-after-installing-the-scipy-package">Solution #1</a> and <a href="http://stackoverflow.com/questions/24808043/importerror-no-module-named-scipy">Solution #2</a> with no results.</p> <p>When I use:</p> <pre><code>pip install scipy </code></pre> <p>It outputs</p> <pre><code>Requirement already satisfied (use --upgrade to upgrade): scipy in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python </code></pre> <p>Then I do</p> <pre><code>pip install scipy --updrage </code></pre> <p>And it outputs</p> <pre><code>OSError: [Errno 1] Operation not permitted: '/var/folders/y3/r_j97_g91494mm7r9th0zycm0000gn/T/pip-paR57c-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy-1.8.0rc1-py2.7.egg-info' </code></pre> <p>I even try to install using <code>port</code>:</p> <pre><code>sudo port install py27-numpy py27-scipy py27-matplotlib py27-ipython +notebook py27-pandas py27-sympy py27-nose </code></pre> <p>Same result, it says it's been installed but when I try to run my Python project, prints the same error.</p> <p>Hope you guys can help me.</p>
0
2016-09-04T18:46:28Z
39,325,706
<p>I believe that your issue may be how you are running your code - OS-X can have <strong>both</strong> the system python and a user python installation.</p> <p>From the command prompt, (the same one that pip tells you that you already have scipy installed), try running your script, <em>which I will assume is called <code>your_script.py</code></em> with:</p> <pre><code>python your_script.py </code></pre> <p>And it should work, however if you run:</p> <pre><code>your_script.py </code></pre> <p>it may not work.</p> <p>I don't have a Mac to experiment on but you should do some reading on this issue online - <a href="https://docs.python.org/3/using/mac.html" rel="nofollow">here</a> </p>
0
2016-09-05T07:30:24Z
[ "python", "pip", "homebrew" ]
Comparing member of a list in Python
39,320,362
<p>I'm writing a function (the long way) to test if a number I type in is in the list. I don't want to use the 'in' function. The question is why it only works when I type in numbers that are in the list and I get an error in line <code>if x == a[i]:</code> when a number is not in the list.</p> <pre><code>def is_member(x): a = [1,5,3,9,4,100] i = 0 found = False while found == False: if x == a[i]: found = True break i += 1 if found == True: return "True" else: return "False" </code></pre>
0
2016-09-04T18:48:29Z
39,320,390
<p>If there is no element in the list, then your <code>i</code> gets bigger and bigger until it becomes <code>i = len(a)</code>. At this point <code>a[i]</code> throws an <code>IndexError</code> since you went above the list size. Simple fix would be to use <code>while i &lt; len(a):</code> instead of <code>while found == false:</code> since you break the loop at <code>x == a[i]</code> anyway.</p>
2
2016-09-04T18:52:00Z
[ "python" ]
Comparing member of a list in Python
39,320,362
<p>I'm writing a function (the long way) to test if a number I type in is in the list. I don't want to use the 'in' function. The question is why it only works when I type in numbers that are in the list and I get an error in line <code>if x == a[i]:</code> when a number is not in the list.</p> <pre><code>def is_member(x): a = [1,5,3,9,4,100] i = 0 found = False while found == False: if x == a[i]: found = True break i += 1 if found == True: return "True" else: return "False" </code></pre>
0
2016-09-04T18:48:29Z
39,320,391
<p>You need to add a condition that <code>if (i == len(a)-1): return False</code>. Because the index can not exceed the length of list <code>a</code>.</p>
1
2016-09-04T18:52:02Z
[ "python" ]
Comparing member of a list in Python
39,320,362
<p>I'm writing a function (the long way) to test if a number I type in is in the list. I don't want to use the 'in' function. The question is why it only works when I type in numbers that are in the list and I get an error in line <code>if x == a[i]:</code> when a number is not in the list.</p> <pre><code>def is_member(x): a = [1,5,3,9,4,100] i = 0 found = False while found == False: if x == a[i]: found = True break i += 1 if found == True: return "True" else: return "False" </code></pre>
0
2016-09-04T18:48:29Z
39,320,425
<p>That's because you are going outside the bounds of the list.</p> <p>You should add a check so you can return when <code>i &gt; len(a)</code>.</p>
2
2016-09-04T18:56:14Z
[ "python" ]
Comparing member of a list in Python
39,320,362
<p>I'm writing a function (the long way) to test if a number I type in is in the list. I don't want to use the 'in' function. The question is why it only works when I type in numbers that are in the list and I get an error in line <code>if x == a[i]:</code> when a number is not in the list.</p> <pre><code>def is_member(x): a = [1,5,3,9,4,100] i = 0 found = False while found == False: if x == a[i]: found = True break i += 1 if found == True: return "True" else: return "False" </code></pre>
0
2016-09-04T18:48:29Z
39,320,426
<pre><code>def is_member(x): a = [1,5,3,9,4,100] i = 0 found = False while found == False: if i &gt;= len(a): return False # end of list reached if x == a[i]: found = True break i += 1 if found == True: return "True" else: return "False" </code></pre> <p>to handle end of list, a piece of code has been added</p> <p>In fact you do not another variable like <code>Found</code>, you can do it in below way.</p> <pre><code>def is_member(x): a = [1,5,3,9,4,100] i = 0 while True: if i &gt;= len(a): print 'test' return False # end of list reached if x == a[i]: return True i += 1 </code></pre>
1
2016-09-04T18:56:15Z
[ "python" ]
Comparing member of a list in Python
39,320,362
<p>I'm writing a function (the long way) to test if a number I type in is in the list. I don't want to use the 'in' function. The question is why it only works when I type in numbers that are in the list and I get an error in line <code>if x == a[i]:</code> when a number is not in the list.</p> <pre><code>def is_member(x): a = [1,5,3,9,4,100] i = 0 found = False while found == False: if x == a[i]: found = True break i += 1 if found == True: return "True" else: return "False" </code></pre>
0
2016-09-04T18:48:29Z
39,320,796
<p>Try something like this instead:</p> <pre><code>def is_member(x): a = [1,5,3,9,4,100] for i in a: if i == x: return "True" return "False" </code></pre> <p>Here we iterate over a, and if any member <code>== x</code> we return "True" right away. If we have not returned by the end of the loop then the element is not present.</p>
1
2016-09-04T19:40:08Z
[ "python" ]
Comparing member of a list in Python
39,320,362
<p>I'm writing a function (the long way) to test if a number I type in is in the list. I don't want to use the 'in' function. The question is why it only works when I type in numbers that are in the list and I get an error in line <code>if x == a[i]:</code> when a number is not in the list.</p> <pre><code>def is_member(x): a = [1,5,3,9,4,100] i = 0 found = False while found == False: if x == a[i]: found = True break i += 1 if found == True: return "True" else: return "False" </code></pre>
0
2016-09-04T18:48:29Z
39,320,873
<p>You can also use a for loop to avoid the index error, try this</p> <pre><code>def is_member(x): a = [1,5,3,9,4,100] for i in range(len(a)): if x == a[i]: return True return False </code></pre>
2
2016-09-04T19:48:52Z
[ "python" ]
ggplot2 plots not rendering points if alpha in geom_points is set to other value than 1 in anaconda
39,320,372
<p>I am trying to use R through Anaconda python. rpy2 is installed. The problem I am running into is when I set alpha to a value other than 1 in geom_point the points do not show in the plot but will show if alpha is set to 1. Am I missing something? Here is the code that I am running (Ubuntu16.04):</p> <pre><code>from rpy2 import robjects from rpy2.robjects.packages import importr import rpy2.robjects.lib.ggplot2 as ggplot2 from rpy2.robjects.packages import importr base = importr('base') #mtcars = datasets.__rdata__.fetch('mtcars')['mtcars'] rnorm = stats.rnorm dataf_rnorm = robjects.DataFrame({'value': rnorm(300, mean=0) + rnorm(100, mean=3), 'other_value': rnorm(300, mean=0) + rnorm(100, mean=3), 'mean': IntVector([0, ]*300 + [3, ] * 100)}) gp = ggplot2.ggplot(dataf_rnorm) pp = gp + \ ggplot2.aes_string(x='value', y='other_value') + \ ggplot2.geom_point(alpha = 1) + \ ggplot2.geom_density2d(ggplot2.aes_string(col = '..level..')) + \ ggplot2.ggtitle('point + density') pp.plot() </code></pre> <p>Thanks for any insight.</p> <p><a href="http://i.stack.imgur.com/qvd9N.png" rel="nofollow">alpha set to 0.4</a></p> <p><a href="http://i.stack.imgur.com/JNRDl.png" rel="nofollow">alpha set to 1</a></p>
0
2016-09-04T18:49:25Z
39,332,017
<p>This can happen if the R "graphics device" is not able to handle alpha transparency (this is most likely settled at build time, depending on the libraries used to compile the R devices).</p> <p>For PNG, try specifying the use of /cairo/:</p> <pre><code># rpy2 version 2.8.4 of later # (see https://bitbucket.org/rpy2/rpy2/issues/371)) from rpy2.robjects.lib import grdevices with grdevices.render_to_file(grdevices.png, filename="my-plot.png", type="cairo-png") as p: pp.plot() # Earlier versions of rpy2 where issue #371 is still present from rpy2.robjects.lib import grdevices grdevices.png("my-plot.png", type="cairo-png") pp.plot() grdevices.dev_off() </code></pre>
1
2016-09-05T13:47:08Z
[ "python", "anaconda" ]
ggplot2 plots not rendering points if alpha in geom_points is set to other value than 1 in anaconda
39,320,372
<p>I am trying to use R through Anaconda python. rpy2 is installed. The problem I am running into is when I set alpha to a value other than 1 in geom_point the points do not show in the plot but will show if alpha is set to 1. Am I missing something? Here is the code that I am running (Ubuntu16.04):</p> <pre><code>from rpy2 import robjects from rpy2.robjects.packages import importr import rpy2.robjects.lib.ggplot2 as ggplot2 from rpy2.robjects.packages import importr base = importr('base') #mtcars = datasets.__rdata__.fetch('mtcars')['mtcars'] rnorm = stats.rnorm dataf_rnorm = robjects.DataFrame({'value': rnorm(300, mean=0) + rnorm(100, mean=3), 'other_value': rnorm(300, mean=0) + rnorm(100, mean=3), 'mean': IntVector([0, ]*300 + [3, ] * 100)}) gp = ggplot2.ggplot(dataf_rnorm) pp = gp + \ ggplot2.aes_string(x='value', y='other_value') + \ ggplot2.geom_point(alpha = 1) + \ ggplot2.geom_density2d(ggplot2.aes_string(col = '..level..')) + \ ggplot2.ggtitle('point + density') pp.plot() </code></pre> <p>Thanks for any insight.</p> <p><a href="http://i.stack.imgur.com/qvd9N.png" rel="nofollow">alpha set to 0.4</a></p> <p><a href="http://i.stack.imgur.com/JNRDl.png" rel="nofollow">alpha set to 1</a></p>
0
2016-09-04T18:49:25Z
39,440,578
<p>I still haven't managed to get ggplot2 to render correctly on the display ( I am not sure if this is a bug in rpy2 or something else). However, I can get ggplot2 to render correctly to file in this case png--I also tested tiff but not pdf or ps. Below is the code. Matplotlib opens the file, reads the image and displays it (this allows me to see the image that is written rather than opening it with an image viewer).</p> <pre><code>from rpy2 import robjects from rpy2.robjects.packages import importr import rpy2.robjects.lib.ggplot2 as ggplot2 from rpy2.robjects.packages import importr from rpy2.robjects import Formula, Environment from rpy2.robjects.vectors import IntVector, FloatVector from rpy2.robjects.lib import grid base = importr('base') rprint = robjects.globalenv.get("print") stats = importr('stats') lattice = importr('lattice') datasets = importr('datasets') mtcars = datasets.__rdata__.fetch('mtcars')['mtcars'] rnorm = stats.rnorm dataf_rnorm = robjects.DataFrame({'value': rnorm(300, mean=0) + rnorm(100, mean=3), 'other_value': rnorm(300, mean=0) + rnorm(100, mean=3), 'mean': IntVector([0, ]*300 + [3, ] * 100)}) gp = ggplot2.ggplot(dataf_rnorm) pp = gp +\ ggplot2.aes_string(x='value', y='other_value') +\ ggplot2.geom_point(alpha = 0.4) +\ ggplot2.geom_density2d(ggplot2.aes_string(col = '..level..')) + \ ggplot2.ggtitle('point + density') from rpy2.robjects.lib import grdevices cairo = importr("Cairo") cairo.Cairo(600, 600, file="test.png", type="png", bg="white" ) pp.plot() grdevices.dev_off() #%matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np img = mpimg.imread("test.png") plt.imshow(img) plt.show() </code></pre>
0
2016-09-11T20:56:25Z
[ "python", "anaconda" ]
Saving wide and deep tensorflow model
39,320,405
<p>I'm playing with <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/learn/wide_n_deep_tutorial.py" rel="nofollow">Wide and Deep learning example from Tensorflow</a>. I would like to save the trained classifier to be used for prediction tasks later on but I don't really see how. The <code>DNNLinearCombinedClassifier</code> doesn't have a save method available and pickling the object fails as well.</p> <p>Any ideas how to save it?</p>
-1
2016-09-04T18:53:33Z
39,332,892
<p>Are you looking for <a href="https://www.tensorflow.org/versions/r0.10/how_tos/variables/index.html#saving-and-restoring" rel="nofollow">https://www.tensorflow.org/versions/r0.10/how_tos/variables/index.html#saving-and-restoring</a>?</p> <p>Specifically <strong>Saving Variables</strong> and <strong>Restoring Variables</strong>. Additionally, you can use the <strong>Checkpoint Files</strong> to save the weights periodically (useful if your computer stops training halfway through, you don't have to start from the beginning).</p>
0
2016-09-05T14:35:58Z
[ "python", "tensorflow" ]
Saving wide and deep tensorflow model
39,320,405
<p>I'm playing with <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/learn/wide_n_deep_tutorial.py" rel="nofollow">Wide and Deep learning example from Tensorflow</a>. I would like to save the trained classifier to be used for prediction tasks later on but I don't really see how. The <code>DNNLinearCombinedClassifier</code> doesn't have a save method available and pickling the object fails as well.</p> <p>Any ideas how to save it?</p>
-1
2016-09-04T18:53:33Z
39,358,945
<p>The checkpoint saving section of <a href="https://www.tensorflow.org/versions/r0.10/tutorials/monitors/index.html" rel="nofollow">this doc</a> should answer your question.</p>
1
2016-09-06T22:54:39Z
[ "python", "tensorflow" ]
How can I determine when Bloomd will scale the bloom filter?
39,320,415
<p>I'm using Bloomd and its scalable bloom filter to store/check billions of urls for our broad crawler. It was working very good for first 1-1.5 billion urls and it has been using around 16 GB of memory but it seems that more than 2 billion urls will be added to it soon and I would like to understand when Bloomd will try to scale filter to 32 GB (and we will upgrade our server memory to 64 GB or more).</p> <p>The "info" command provides some data but I'm not sure which key represents what and how can I understand how many url's I can add to it before it scales up.</p> <p>Here is my "info" command results</p> <pre><code>START capacity 5461000000 checks 5893888032 check_hits 5400239954 check_misses 493648078 in_memory 1 page_ins 7 page_outs 6 probability 0.000100 sets 493648075 set_hits 493648016 set_misses 59 size 1859303638 storage 17205844037 END </code></pre> <p>Also I'll appreciate if someone knows better approach than using Scalable Bloom Filters for that kind of massive URL sets.</p>
1
2016-09-04T18:54:52Z
39,336,306
<p>Your filter is using only 34% of its capacity (size/capacity = 1859303638/5461000000).</p>
0
2016-09-05T18:59:15Z
[ "python", "web-scraping", "web-crawler", "bloom-filter" ]
Google AppEngine - Pull Queue - Impossible to delete task: "project name is invalid"
39,320,437
<p>I have create a pull queue in the GAE that works fine, I'm able to add elements from the app &amp; retrieve them from my instance with the code below:</p> <pre><code>from apiclient.discovery import build from oauth2client.client import GoogleCredentials credentials = GoogleCredentials.get_application_default() PROJECT_NAME = "my-project" QUEUE_NAME = 'my-queue' q = build('taskqueue', 'v1beta2', credentials=credentials) l = q.tasks().lease(project=PROJECT_NAME, taskqueue=QUEUE_NAME, leaseSecs=600, numTasks=1) result = l.execute() task = result['items'][0] task_id = task['id'] </code></pre> <p>The problem comes when I try to delete the task after processing it, this code that should work </p> <pre><code>d = q.tasks().delete(project=PROJECT_NAME, taskqueue=QUEUE_NAME, task=task_id) d.execute() </code></pre> <p>return</p> <pre><code>File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 137, in positional_wrapper return wrapped(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/googleapiclient/http.py", line 838, in execute raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: &lt;HttpError 400 when requesting https://www.googleapis.com/taskqueue/v1beta2/projects/my-project/taskqueues/my-queue/tasks/46101672956060486431? returned "project name is invalid"&gt; </code></pre> <p>I don't understand what's wrong because I'm able to get a task from the queue, but when I want to delete it, this error is raised.</p> <p>Does anyone got an insight ?</p>
0
2016-09-04T18:57:12Z
39,320,792
<p>Should be <code>"s~my-project"</code> if your app is in North America, or <code>"e~my-project"</code> if in Europe.</p>
1
2016-09-04T19:39:48Z
[ "python", "google-app-engine", "pull-queue" ]
Account Kit: Error verifying the token in the 'access_token'
39,320,588
<p>I'm trying to retrieve an access token for an authentication code. I'm using the following format:</p> <p>GET <a href="https://graph.accountkit.com/v1.0/access_token?grant_type=authorization_code&amp;code=AUTH_CODE&amp;access_token=AA|APP_ID|APP_SECRET" rel="nofollow">https://graph.accountkit.com/v1.0/access_token?grant_type=authorization_code&amp;code=AUTH_CODE&amp;access_token=AA|APP_ID|APP_SECRET</a></p> <p>where AUTH_CODE, APP_ID, and APP_SECRET are their respective values. Here is the python I use to assemble this URL:</p> <pre><code>url = 'https://graph.accountkit.com/v1.0/access_token?grant_type=authorization_code&amp;code=' + authcode + '&amp;access_token=AA|' + facebook_app_id + '|' + facebook_app_secret </code></pre> <p>But I keep getting the following error:</p> <p><code> { error: { message: "Error verifying the token in the 'access_token'", type: "OAuthException", code: 190, fbtrace_id: "GNhScPPp22t" } } </code></p> <p>I tried googling the fbtrace_id but literally nothing came up. And I don't understand why it's saying it can't verify the token in "access_token", I do <em>exactly</em> what their documentation says to do.</p> <p>Anyone have an idea of where my issue may be?</p>
1
2016-09-04T19:17:08Z
39,321,277
<p>They use a different app secret for AccountKit versus the rest of Facebook.</p>
0
2016-09-04T20:37:37Z
[ "python", "facebook", "api", "http", "facebook-graph-api" ]
Account Kit: Error verifying the token in the 'access_token'
39,320,588
<p>I'm trying to retrieve an access token for an authentication code. I'm using the following format:</p> <p>GET <a href="https://graph.accountkit.com/v1.0/access_token?grant_type=authorization_code&amp;code=AUTH_CODE&amp;access_token=AA|APP_ID|APP_SECRET" rel="nofollow">https://graph.accountkit.com/v1.0/access_token?grant_type=authorization_code&amp;code=AUTH_CODE&amp;access_token=AA|APP_ID|APP_SECRET</a></p> <p>where AUTH_CODE, APP_ID, and APP_SECRET are their respective values. Here is the python I use to assemble this URL:</p> <pre><code>url = 'https://graph.accountkit.com/v1.0/access_token?grant_type=authorization_code&amp;code=' + authcode + '&amp;access_token=AA|' + facebook_app_id + '|' + facebook_app_secret </code></pre> <p>But I keep getting the following error:</p> <p><code> { error: { message: "Error verifying the token in the 'access_token'", type: "OAuthException", code: 190, fbtrace_id: "GNhScPPp22t" } } </code></p> <p>I tried googling the fbtrace_id but literally nothing came up. And I don't understand why it's saying it can't verify the token in "access_token", I do <em>exactly</em> what their documentation says to do.</p> <p>Anyone have an idea of where my issue may be?</p>
1
2016-09-04T19:17:08Z
40,061,771
<p>The error is Because of the Facebook App Configuration.</p> <p>I followed this tutorial regarding <a href="http://mycodde.blogspot.com/2016/10/facebook-accountkit-login-using-mobile.html" rel="nofollow">accountkit setup</a></p> <p>It shows the solution as below</p> <p><a href="https://i.stack.imgur.com/W9lPK.png" rel="nofollow"><img src="https://i.stack.imgur.com/W9lPK.png" alt="enter image description here"></a></p> <p>Alternatively create an Test app under your Main app and you can play with Configuration (It wont affect production)</p>
0
2016-10-15T16:55:48Z
[ "python", "facebook", "api", "http", "facebook-graph-api" ]
alternating control flow with conditionals or preprocessor
39,320,598
<p>Given this code:</p> <pre><code>for i in range(5): foo(i) bar(i) </code></pre> <p>I want to add some code between the two <code>print</code> lines such that I can break the loop into two, but only if a certain flag is true, i.e.:</p> <pre><code>for i in range(5): foo(i) if debug: { continue for i in range(5): } bar(i) </code></pre> <p>Unfortunately this is not valid python. Is there a way I can do that without manually rewriting the loop to:</p> <pre><code>if debug: for i in range(5): foo(i) for i in range(5): bar(i) else: for i in range(5): foo(i) bar(i) </code></pre>
1
2016-09-04T19:18:07Z
39,320,926
<p>If I understand correctly, you want to either call functions in batches (all possible args for first function, then all possible args for second function etc) in first case, and arguments in batches in second case (so all function for first arg, then all functions for second arg etc.)</p> <p>I'd say you have to do it explicitly:</p> <pre><code>def foo(i): print("foo", i) def bar(i): print("bar", i) def stretch(seq, n): """stretch([1,2,3], 3) -&gt; [1,1,1,2,2,2,3,3,3], lazy generator""" for o in seq: for _ in range(n): yield o def run(args, functions, mode): if mode: my_args = list(stretch(args, len(functions))) my_functions = functions * len(args) else: my_args = args * len(functions) my_functions = list(stretch(functions, len(args))) for f, a in zip(my_functions, my_args): f(a) </code></pre> <p>Invocation:</p> <pre><code>run(list(range(5)), [foo, bar], 0) </code></pre> <p>Output:</p> <pre><code>foo 0 foo 1 foo 2 foo 3 foo 4 bar 0 bar 1 bar 2 bar 3 bar 4 </code></pre> <p>Invocation:</p> <pre><code>run(list(range(5)), [foo, bar], 1) </code></pre> <p>Output:</p> <pre><code>foo 0 bar 0 foo 1 bar 1 foo 2 bar 2 foo 3 bar 3 foo 4 bar 4 </code></pre> <p>Here what we've done is that we created pairs for <code>(callable, argument_to_callable)</code> if order determined by your requirement. So essentially you have a boolean that "kind of" duplicated a loop for you.</p> <p>Code is kind of ugly, I wonder if someone comes up with nicer solution.</p>
0
2016-09-04T19:56:08Z
[ "python" ]
alternating control flow with conditionals or preprocessor
39,320,598
<p>Given this code:</p> <pre><code>for i in range(5): foo(i) bar(i) </code></pre> <p>I want to add some code between the two <code>print</code> lines such that I can break the loop into two, but only if a certain flag is true, i.e.:</p> <pre><code>for i in range(5): foo(i) if debug: { continue for i in range(5): } bar(i) </code></pre> <p>Unfortunately this is not valid python. Is there a way I can do that without manually rewriting the loop to:</p> <pre><code>if debug: for i in range(5): foo(i) for i in range(5): bar(i) else: for i in range(5): foo(i) bar(i) </code></pre>
1
2016-09-04T19:18:07Z
39,321,591
<p>Preprocessor derivatives change your code before it ever gets to run. In the C family of languages, for example, the compiler substitutes all expressions within <a href="https://en.wikipedia.org/wiki/C_preprocessor" rel="nofollow">preprocessor</a> blocks before compilation.</p> <p>In your example, <code>debug</code> is a runtime variable, so there is no way you could change the structure of your code based on that variable. At least not in Python anyway.</p> <p>However, there is <strong>always</strong> (well, almost always) a way you can avoid doing something manually. In the same spirit of true preprocessor blocks changing the code before it gets to run, we have to go a level up and add in content before the code gets executed. The simplest way to do that is to manipulate your code as a string, and modify the string on the run. I won't stress enough how unpythonic this contrived example is, but using <code>exec</code> you can inject the code you want. The solution will always work, no matter what function you use. Here it goes:</p> <p>First, define your debug flag</p> <pre><code>if_debug = "" if debug: if_debug = "continue\nfor i in range(5):\n " </code></pre> <p>Finally, wrap your code within a <code>exec("")</code> block. The string substitution happens before the code is sent to the interpreter for evaluation.</p> <pre><code>exec(""" for i in range(5):\n foo(i)\n """ + if_debug + "bar(i)") </code></pre> <p>There are macro libraries that allow you to change the way your code gets interpreted. Have a look at <a href="https://github.com/lihaoyi/macropy" rel="nofollow">MacroPy</a>, for example.</p>
-1
2016-09-04T21:19:16Z
[ "python" ]
alternating control flow with conditionals or preprocessor
39,320,598
<p>Given this code:</p> <pre><code>for i in range(5): foo(i) bar(i) </code></pre> <p>I want to add some code between the two <code>print</code> lines such that I can break the loop into two, but only if a certain flag is true, i.e.:</p> <pre><code>for i in range(5): foo(i) if debug: { continue for i in range(5): } bar(i) </code></pre> <p>Unfortunately this is not valid python. Is there a way I can do that without manually rewriting the loop to:</p> <pre><code>if debug: for i in range(5): foo(i) for i in range(5): bar(i) else: for i in range(5): foo(i) bar(i) </code></pre>
1
2016-09-04T19:18:07Z
39,322,101
<p>Hmmm we can always store mid-air result in list </p> <pre><code>n = range(10) if debug: n = list(map(lambda x: foo(x),n))+list(map(lambda x: bar(x),n)) else: n = list(map(lambda x: [foo(x),bar(x)],n)) </code></pre>
0
2016-09-04T22:40:03Z
[ "python" ]
Theano: when was the filter_flip parameter for conv2d introduced? (TypeError: __init__() got an unexpected keyword argument 'filter_flip')
39,320,675
<p>When was the <code>filter_flip</code> parameter for <code>theano.tensor.nnet.conv2d()</code> introduced in Theano? (i.e., which is the minimum Theano version that supports it?)</p> <p>My version (<code>0.7.0.dev-8d3a67b73fda49350d9944c9a24fc9660131861c</code>) doesn't have it: </p> <pre><code>File "/usr/local/lib/python2.7/dist-packages/theano/tensor/nnet/conv.py", line 146, in conv2d imshp=imshp, kshp=kshp, nkern=nkern, bsize=bsize, **kargs) TypeError: __init__() got an unexpected keyword argument 'filter_flip' </code></pre> <p><a href="http://deeplearning.net/software/theano/NEWS.html" rel="nofollow">Theano's change log</a> doesn't mention <code>filter_flip</code>. The <a href="http://deeplearning.net/software/theano/library/tensor/nnet/conv.html#theano.tensor.nnet.conv2d" rel="nofollow">documentation for <code>theano.tensor.nnet.conv2d()</code></a> doesn't mention the minimum required version.</p>
0
2016-09-04T19:25:48Z
39,321,863
<p>It appears in <a href="https://github.com/Theano/Theano/blob/rel-0.8.0/theano/tensor/nnet/__init__.py#L35" rel="nofollow">version 0.8.0</a>.</p> <p>Note that in that release the implementation of <code>theano.tensor.nnet.conv2d()</code> found in <code>theano/tensor/nnet/conv.py</code> <a href="https://github.com/Theano/Theano/blob/rel-0.8.0/theano/tensor/nnet/conv.py#L43" rel="nofollow">becomes deprecated</a> and is replaced by the new implementation placed into <a href="https://github.com/Theano/Theano/blob/rel-0.8.0/theano/tensor/nnet/__init__.py#L35" rel="nofollow"><code>theano/tensor/nnet/__init__.py</code></a> and <a href="https://github.com/Theano/Theano/blob/rel-0.8.0/theano/tensor/nnet/abstract_conv.py#L115" rel="nofollow"><code>theano/tensor/nnet/abstract_conv.py</code></a>.</p>
1
2016-09-04T22:00:48Z
[ "python", "theano" ]
Search txt file for varying keyword - then assign to variable
39,320,765
<p>I need to search a txt file for keywords in format "i-0xxxyyyzzzz" - where xyz are varying alphanumeric characters. I would like to then assign each match assigned. Currently I can get as far as:</p> <pre><code> f = open("file.txt", "r") searchlines = f.readlines() f.close() for i, line in enumerate(searchlines): if "i-0" in line: for l in searchlines[i:i+1]: print l, print </code></pre> <p>However this prints the whole line, and not just the keyword.</p>
-2
2016-09-04T19:37:22Z
39,320,971
<p>I suggest using regular expressions:</p> <pre><code>import re token_regex = re.compile('i\-0[0-9a-z]*') for line in open('file.txt'): // Note: 'r' is the default // You might find the token several times in the line matches = token_regex.findall(line) if matches: print '\n'.join(matches) </code></pre> <p>I'm not clear what you want to do with the matches. My example would print print them one per line. Also, could you have tokens that span two lines?</p>
0
2016-09-04T20:01:04Z
[ "python", "file", "search", "keyword" ]
Plot date and data continuously matplotlib
39,320,890
<p>I have written the following piece of code that collects the data from a file, timestamps it and plots it. I have the working code below:</p> <pre><code>temp_data=0 x=[datetime.now() + timedelta(hours=-i) for i in range(5)] y=[temp_data+i for i in range(len(x))] while True: f=open("/sys/class/thermal/thermal_zone0/temp", "r") #timestamp the data temp_time=datetime.now() #read the data in the file to a variable and divide by 1000 to get correct value temp_data=int(f.readlines()[0].strip())/1000 x=x[1:] x.append(temp_time) y=y[1:] y.append(temp_data) plt.gcf().autofmt_xdate() plt.plot(x,y) plt.show() sleep(5) print "Good Bye, Exiting the Program" #close file after reading f.close() </code></pre> <p>What happens right now is that, the plot gets displayed and I have to close the plot window for the next set of data to appear on the plot. </p> <p>I want to extend this further, wherein my plot continuously plots the data after reading the file and timestamping it. </p> <p>Thanks in advance.</p>
2
2016-09-04T19:51:37Z
39,321,181
<p>You could open a figure and hold it.</p> <pre><code>temp_data=0 x=[datetime.now() + timedelta(hours=-i) for i in range(5)] y=[temp_data+i for i in range(len(x))] plt.figure() ###### Create figure while True: f=open("/sys/class/thermal/thermal_zone0/temp", "r") #timestamp the data temp_time=datetime.now() #read the data in the file to a variable and divide by 1000 to get correct value temp_data=int(f.readlines()[0].strip())/1000 x=x[1:] x.append(temp_time) y=y[1:] y.append(temp_data) plt.hold(True) ##### Hold it. plt.gcf().autofmt_xdate() plt.plot(x,y) plt.show() sleep(5) print "Good Bye, Exiting the Program" #close file after reading f.close() </code></pre>
1
2016-09-04T20:26:05Z
[ "python", "matplotlib", "plot" ]
Django django.contrib.sites where to put migration?
39,320,897
<p>the django doc says to change the sites name and domain in the django.contrib.sites framework one should use a migration [1].</p> <p>But they forgot to mention where I should put this migration. I tried to create a directory named "sites" and a directory named "django.contrib.sites". But no matter in which directory I put my migration, <code>manage.py migration</code> always says there is nothing to update.</p> <p>I also tried to run <code>python manage.py makemigrations --empty sites</code>, but then the migration is created in the lib directory: <code>ve/lib/python3.5/site-packages/django/contrib/sites/migrations/0003_auto_20160904_2144.py</code>. This may be correct behaviour, but then I cannot set my change under source control.</p> <p>In case something is wrong with my migration, here it is:</p> <pre><code>from __future__ import unicode_literals from django.db import migrations, models def set_site_name(apps, schema_editor): Sites = apps.get_model('django.contrib.sites', 'site') site = Sites.objects.filter(id=1).first() if site != None: site.name = "name" site.domain = "name.com" class Migration(migrations.Migration): initial = True operations = [ migrations.RunPython(set_site_name), ] </code></pre> <p>So my question is: where does django expect to find those migrations?</p> <p>Thank you very much in advance for your help.</p> <p>[1] <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/sites/#enabling-the-sites-framework" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/contrib/sites/#enabling-the-sites-framework</a></p>
0
2016-09-04T19:52:17Z
39,321,347
<p>Each app in a Django project must have a unique <a href="https://docs.djangoproject.com/en/1.10/ref/applications/#django.apps.AppConfig.label" rel="nofollow">label</a>. Naming your app <code>sites</code> isn't a good idea - it will clash with the <code>django.contrib.sites</code> app unless you change the label in the app config class.</p> <p>If you have an existing app specific to your project, you could use that app to store the data migration.</p> <p>Alternatively choose a different name like <code>mysites</code>. Create the app with <code>./manage.py startapp mysite</code>, add the app to your <code>INSTALLED_APPS</code>, then create a blank migration. </p>
1
2016-09-04T20:45:58Z
[ "python", "django", "django-models" ]
django - can't view data on django admin page
39,320,906
<p>Here are the models I am working with:</p> <pre><code>class Customer(models.Model): customer_id = models.AutoField(primary_key=True, unique=True) full_name = models.CharField(max_length=50) user_email = models.EmailField(max_length=50) user_pass = models.CharField(max_length=30) def __str__(self): return "%s" % self.full_name class CustomerDetail(models.Model): phone_regex = RegexValidator(regex = r'^\d{10}$', message = "Invalid format! E.g. 4088385778") date_regex = RegexValidator(regex = r'^(\d{2})[/.-](\d{2})[/.-](\d{2})$', message = "Invalid format! E.g. 05/16/91") customer = models.OneToOneField( Customer, on_delete=models.CASCADE, primary_key=True, ) address = models.CharField(max_length=100) date_of_birth = models.CharField(validators = [date_regex], max_length = 10, blank = True) company = models.CharField(max_length=30) home_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True) work_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True) def __str__(self): return "%s" % self.customer.full_name </code></pre> <p>Here is the <code>forms.py</code>:</p> <pre><code>from django.forms import ModelForm from .models import CustomerDetail class CustomerDetailForm(ModelForm): class Meta: model = CustomerDetail fields = ['address', 'date_of_birth', 'company', 'home_phone', 'work_phone',] </code></pre> <p>I have a view in my application (after user is logged in) called <code>create_profile</code> that asks the user for additional details and I used ModelForm instance to implement it. Here is the snippet from <code>views.py</code>:</p> <pre><code>def create_profile(request): if request.POST: form = CustomerDetailForm(request.POST) if form.is_valid(): address = form.cleaned_data['address'] date_of_birth = form.cleaned_data['date_of_birth'] company = form.cleaned_data['company'] home_phone = form.cleaned_data['home_phone'] work_phone = form.cleaned_data['work_phone'] profdata = CustomerDetail(address = address, date_of_birth = date_of_birth, company = company, home_phone = home_phone, work_phone = work_phone) profdata.save() return render(request, 'newuser/profile_created.html', {form: form}) else: return redirect(create_profile) </code></pre> <p>When I fill the form on the corresponding template html and hit Submit, it shows me the successive page, but when I check the CustomerDetail entries on the admin page, I see a '-' in place of an actual record. Where am I going wrong here? Does it have to do with overriding the clean() method? Please help. Thanks!</p>
0
2016-09-04T19:53:42Z
39,320,960
<p>You don't need to override <code>cleaned_data</code> in your case. Because you already using <code>ModelForm</code> which create <code>CustomerDetail</code> instance after <code>save</code> method called.<br> View might look like this: </p> <pre><code>def create_profile(request): if request.method == 'POST': form = CustomerDetailForm(request.POST) if form.is_valid(): form.save() return render(request, 'newuser/profile_created.html', {'form': form}) else: form = CustomerDetailForm() return render(request, 'path_to_create_profile.html', {'form': form}) </code></pre> <p><a href="https://docs.djangoproject.com/en/1.10/topics/forms/#the-view" rel="nofollow">check the docs about forms</a></p>
0
2016-09-04T19:59:49Z
[ "python", "django", "django-forms", "modelform" ]
Python: Matplotlib twin() issue: plotting spread
39,320,927
<p>I'm having some issue getting my code to run. The two lines in question are as follows (the code runs fine without them). </p> <pre><code>ax1_2 = ax1.twinx() ax1_2.fill_between(date, 0, (ask-bid), alpha = 3, facecolor='g') </code></pre> <p>I'm looking to twin their x's and show another plot ontop of my current graph (displaying spread for my data).</p> <p>Here's my source code. Any help is much appreciated. </p> <pre><code>import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as mticker import matplotlib.dates as mdates import numpy as np from matplotlib import style style.use('ggplot') def bytespdate2num(fmt, encoding='utf-8'): strconverter = mdates.strpdate2num(fmt) def bytesconverter(b): s = b.decode(encoding) return strconverter(s) return bytesconverter date_converter = bytespdate2num("%Y%m%d%H%M%S") def graphRawFX(): date,bid,ask=np.loadtxt('GBPUSD1d.txt', unpack=True, delimiter=',', converters = {0: date_converter}) fig = plt.figure(figsize=(10,7)) ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40) ax1.plot(date,bid) ax1.plot(date,ask) plt.gca().get_yaxis().get_major_formatter().set_useOffset(False) # gca() here because we want to offset here ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S')) for label in ax1.xaxis.get_ticklabels(): label.set_rotation(45) ax1_2 = ax1.twinx() ax1_2.fill_between(date, 0, (ask-bid), alpha = 3, facecolor='g') #fills betwween date and zero, ask-bid is the spread plt.subplots_adjust(bottom=0.23) plt.grid(True) plt.show() graphRawFX() </code></pre>
1
2016-09-04T19:56:16Z
39,325,723
<p>From our comments to the OP, your <code>alpha</code> value is too big. It has to be between 0 and 1. See <a href="http://stackoverflow.com/questions/4320021/matplotlib-transparent-line-plots">here</a> or the <a href="http://matplotlib.org/api/artist_api.html#matplotlib.artist.Artist.set_alpha" rel="nofollow">doc</a>. What you want is</p> <pre><code>ax1_2.fill_between(date, 0, (ask-bid), alpha = 0.3, facecolor='g') </code></pre>
1
2016-09-05T07:32:07Z
[ "python", "matplotlib" ]
Filtering serializer response data
39,321,008
<p>I have a ManyToMany relation with tag and items:</p> <pre><code>class Tag(BaseModel): name = models.CharField(max_length=255) # ToDo Change max length description = models.TextField(blank=True, null=True) class Item(BaseModel): user = models.ForeignKey(settings.AUTH_USER_MODEL) image = models.ImageField(upload_to='items', blank=True) title = models.TextField(blank=False, null=True) message = models.TextField(blank=True, null=True) fav_count = models.IntegerField(default=0) tags = models.ManyToManyField(Tag, related_name='tags') </code></pre> <p>I need all fields to be serialized, but i wish to only limit the response values. Example:</p> <p>What I'm receiving now:</p> <pre><code>{ "user": 2, "image": null, "title": "test3", "message": "testmessage", "fav_count": 0, "tags": [ { "id": 7, "name": "tag1", "description": null }, { "id": 8, "name": "tag2", "description": null } ] } </code></pre> <p>But i only wish to receive the tag ids not the name and description...</p> <p>My simple view:</p> <pre><code>if request.method == 'GET': items = Item.objects.all() serializer = ItemSerializer(items, many=True) return Response(serializer.data) </code></pre> <p>Would i need to rebuild my response data to include/exclude or is there a better way to do this? (or if iv missed the terminology)</p>
0
2016-09-04T20:04:03Z
39,321,109
<p>You probaply using serializer for <code>Tag</code> model and declare it in <code>ItemSerializer</code> so view is showing full <code>TagSerializer</code> info.<br> If you want to show only <code>pk</code> field, just use default representation, don't declare special serializer for <code>Tag</code> in <code>ItemSerializer</code></p>
0
2016-09-04T20:15:23Z
[ "python", "django", "django-rest-framework" ]
Filtering serializer response data
39,321,008
<p>I have a ManyToMany relation with tag and items:</p> <pre><code>class Tag(BaseModel): name = models.CharField(max_length=255) # ToDo Change max length description = models.TextField(blank=True, null=True) class Item(BaseModel): user = models.ForeignKey(settings.AUTH_USER_MODEL) image = models.ImageField(upload_to='items', blank=True) title = models.TextField(blank=False, null=True) message = models.TextField(blank=True, null=True) fav_count = models.IntegerField(default=0) tags = models.ManyToManyField(Tag, related_name='tags') </code></pre> <p>I need all fields to be serialized, but i wish to only limit the response values. Example:</p> <p>What I'm receiving now:</p> <pre><code>{ "user": 2, "image": null, "title": "test3", "message": "testmessage", "fav_count": 0, "tags": [ { "id": 7, "name": "tag1", "description": null }, { "id": 8, "name": "tag2", "description": null } ] } </code></pre> <p>But i only wish to receive the tag ids not the name and description...</p> <p>My simple view:</p> <pre><code>if request.method == 'GET': items = Item.objects.all() serializer = ItemSerializer(items, many=True) return Response(serializer.data) </code></pre> <p>Would i need to rebuild my response data to include/exclude or is there a better way to do this? (or if iv missed the terminology)</p>
0
2016-09-04T20:04:03Z
39,321,126
<p>use <code>PrimaryKeyRelatedField</code> DRF field in your serializer</p> <p>Example</p> <pre><code>class ItemSerializer(serializers.ModelSerializer): tags = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Item fields = ('tags', 'image',.....other fields) </code></pre> <p>Response</p> <pre><code>{ 'image': 'image1', ........... 'tags': [ 89, 90, 91, ... ] .......... } </code></pre> <p>In you want to do it dynamically based on a request parameter. </p> <pre><code> class ItemSerializer(serializers.ModelSerializer): tags = serializers.SerializerMethodField() def get_tags(self, obj): if self.request.get('some_condition'): data_tags = TagSerializer(obj.tags, many=True).data data = map(data.pop('field_to_remove') for data in data_tags) return list(data) else: return TagSerializer(obj.tags, many=True).data </code></pre> <p>Then, pass request to your serializer when you init it in your view.</p> <pre><code>serializer = ItemSerializer(data, context={'request':self.request}) </code></pre>
2
2016-09-04T20:18:06Z
[ "python", "django", "django-rest-framework" ]
Tabulate - How to Cascade tables
39,321,014
<p>I'd like to display two tables next to another using tabulate.</p> <p>My approach:</p> <pre><code>test_table1 = tabulate([['Alice', 24], ['Bob', 19]]) test_table2 = tabulate([['Hans', 45], ['John', 38]]) master_headers = ["table1", "table2"] master_table = tabulate([[test_table1, test_table2]], master_headers, tablefmt="simple") print(master_table) </code></pre> <p>But this results in both tables being displayed in the column of table1.</p> <p>See: <a href="http://i.stack.imgur.com/9eh9l.png" rel="nofollow"><img src="http://i.stack.imgur.com/9eh9l.png" alt="enter image description here"></a></p> <p><strong>Question:</strong> How can i cascade tables in python, preferably using tabulate(or a similar library)?</p> <p>Thanks in advance!</p> <p>Muff</p>
3
2016-09-04T20:04:48Z
39,321,613
<p>I don't really know if this is the best choice that you get, but that's what i came up with</p> <pre><code>test_table1 = str(tabulate([['Alice', 24], ['Bob', 19]])).splitlines() test_table2 = str(tabulate([['Hans', 45], ['John', 38]])).splitlines() master_headers = ["table1", "table2"] master_table = tabulate([list(item) for item in zip(test_table1,test_table2)], master_headers, tablefmt="simple") print(master_table) </code></pre> <p>Output:</p> <pre><code>table1 table2 --------- -------- ----- -- ---- -- Alice 24 Hans 45 Bob 19 John 38 ----- -- ---- -- </code></pre> <p><strong>Explanation</strong>:</p> <p>The purpose was to pass array of strings to <em>master_table</em>'s <code>tabulate</code>, like it was done with <em>test_table1</em> and <em>test_table2</em></p> <p>With <code>.splitlines()</code></p> <pre><code>&gt;&gt;&gt;str(tabulate([['Alice', 24], ['Bob', 19]])) &gt;&gt;&gt;'----- --\nAlice 24\nBob 19\n----- --' &gt;&gt;&gt;str(tabulate([['Alice', 24], ['Bob', 19]])).splitlines() &gt;&gt;&gt;['----- --', 'Alice 24', 'Bob 19', '----- --'] </code></pre> <p>So we had <code>['----- --', 'Alice 24', 'Bob 19', '----- --']</code> and <code>['---- --', 'Hans 45', 'John 38', '---- --']</code>, but we can't pass them that way, because output would be quite strange:</p> <pre><code>table1 table2 --------- --------- --------- --------- ----- -- Alice 24 Bob 19 ----- -- ---- -- Hans 45 John 38 ---- -- </code></pre> <p>So we needed to <code>zip</code> those lists, and convert values to <code>list</code>, because <code>zip</code> return <code>list</code> of <code>tuple</code> objects, that's what happened here: </p> <pre><code>&gt;&gt;&gt;[list(item) for item in zip(test_table1,test_table2)] &gt;&gt;&gt;[['----- --', '---- --'], ['Alice 24', 'Hans 45'], ['Bob 19', 'John 38'], ['----- --', '---- --']] </code></pre> <p>And that is the way how <code>tabulate</code> easily will get data and put as you desired.</p>
1
2016-09-04T21:23:01Z
[ "python", "python-3.x" ]
Python tarfile: how to use tar+gzip compression with follow symbolic link?
39,321,031
<p>How could I use tar+gzip compression with "follow symbolic link" feature in Python 3.4? The problem is:</p> <ul> <li>tarfile.open() supports "w:gz" mode but does not support "dereference" option</li> <li>tarfile.tarfile() supports "dereference" but does not support "w:gz" mode</li> </ul> <p>Code:</p> <pre><code>... mode = "" if bckentry['method'] == "tar": mode = "w" elif bckentry['method'] == "targz": mode = "w:gz" archive = tarfile.TarFile(name=filepath, mode=mode) archive.dereference = True if bckentry['followsym'] == "yes" else False # archive = tarfile.open(filepath, mode=mode) if bckentry['withpath'] == 'yes': for entry in bckentry['include_dirs']: archive.add(entry, filter=self.filter_tar) elif bckentry['withpath'] == 'no': for entry in bckentry['include_dirs']: archive.add(entry, arcname=os.path.basename(entry), filter=self.filter_tar) ... </code></pre>
2
2016-09-04T20:07:28Z
39,321,142
<p><a href="https://docs.python.org/3/library/tarfile.html#tarfile.open" rel="nofollow"><code>tarfile.open</code></a> is a shortcut for the <a href="https://docs.python.org/3/library/tarfile.html#tarfile.TarFile.open" rel="nofollow"><code>TarFile.open</code></a> classmethod, that in turn calls the <a href="https://docs.python.org/3/library/tarfile.html#tarfile-objects" rel="nofollow"><code>TarFile</code></a> constructor. The documentation is a bit vague, but from the code it is apparent that the first two will pass the <code>dereference</code> keyword argument and all other unconsumed kwargs to the <code>TarFile</code> constructor. </p> <p>Thus you can use <code>dereference</code> with any of them, if you just pass it as a keyword argument:</p> <pre><code>archive = tarfile.open(name='foo.tar.gz', mode='w:gz', dereference=True) </code></pre>
1
2016-09-04T20:19:53Z
[ "python", "gzip", "tar", "dereference", "tarfile" ]
How can I interpolate accelerometer data in pandas into fixed sampling rate?
39,321,207
<p>I have a frame with accelerometer data, collected from an iPhone device. The avg sampling rate is 100Hz, but I'd like to have a fixed one with all the data (x, y, z) interpolated. Is that possible in pandas?</p> <p>For example, here is the head of my df:</p> <pre><code>ts x y z 0.006960 -0.075324 -0.175405 0.167105 0.016970 -0.048325 -0.186265 0.180108 0.026949 -0.017635 -0.158964 0.215963 0.036959 -0.097063 -0.063350 0.256945 0.046969 -0.139939 -0.046091 0.179085 ... </code></pre> <p>What I need it to have a fixed sampling rage of 100Hz, so that the ts looks like: <code>0.00, 0.01, 0.02, 0.03 ... 0.99, 1.00, 1.01 ...</code></p> <p>Thank you for you help in advance.</p>
0
2016-09-04T20:29:31Z
39,321,447
<p>Index your dataframe with <code>ts</code>:</p> <pre><code>df = df.set_index('ts') </code></pre> <p>Create the index you need:</p> <pre><code>index2 = pd.Index(pd.np.arange(0.00, 1.00, .01)) </code></pre> <p>Merge it with the current index and reindex the dataframe to get additional rows:</p> <pre><code>df = df.reindex(df.index.union(index2)) </code></pre> <p>Interpolate:</p> <pre><code>df.interpolate() </code></pre>
1
2016-09-04T20:58:22Z
[ "python", "pandas" ]
How can I interpolate accelerometer data in pandas into fixed sampling rate?
39,321,207
<p>I have a frame with accelerometer data, collected from an iPhone device. The avg sampling rate is 100Hz, but I'd like to have a fixed one with all the data (x, y, z) interpolated. Is that possible in pandas?</p> <p>For example, here is the head of my df:</p> <pre><code>ts x y z 0.006960 -0.075324 -0.175405 0.167105 0.016970 -0.048325 -0.186265 0.180108 0.026949 -0.017635 -0.158964 0.215963 0.036959 -0.097063 -0.063350 0.256945 0.046969 -0.139939 -0.046091 0.179085 ... </code></pre> <p>What I need it to have a fixed sampling rage of 100Hz, so that the ts looks like: <code>0.00, 0.01, 0.02, 0.03 ... 0.99, 1.00, 1.01 ...</code></p> <p>Thank you for you help in advance.</p>
0
2016-09-04T20:29:31Z
39,321,588
<p>There's probably a more efficient way to do this, but you could use scipy to interpolate each column to the time array of interest, and then create a new dataframe from the interpolated data.</p> <pre><code>import numpy as np import pandas as pd from scipy import interpolate # define the time points of interest fs = 100 # sampling rate T = 1/fs # period ts = np.arange(0, 0.05, T) # create a dictionary of interpolated data interp_data = {} # loop through the columns and populate for key in ['x', 'y', 'z']: # fit the univariate spline to the data spl = interpolate.UnivariateSpline(df['ts'], df[key]) # compute interpolated values on new time points interp_data[key] = spl(ts) # convert to data frame interp_frame = pd.DataFrame(interp_data, index=ts) interp_frame.index.name = 'ts' interp_frame.head() </code></pre>
1
2016-09-04T21:18:54Z
[ "python", "pandas" ]
Detecting location of translucent black rectangluar area in image matrix Python OpenCV
39,321,336
<p>Say I have an image like this:</p> <p><a href="http://i.stack.imgur.com/G5AlE.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/G5AlE.jpg" alt="enter image description here"></a></p> <p>I want the <strong>location of the start and end points of the black strip in the image matrix</strong>.</p> <p>I have tried several method like <a href="http://stackoverflow.com/questions/7227074/horizontal-line-detection-with-opencv">horizontal line detection in Python OpenCV</a> and have come up with following code that gets me the lines highlighted:</p> <pre><code>import cv2 import numpy as np from numpy import array from matplotlib import pyplot as plt import math img = cv2.imread('caption.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 50, 150, apertureSize = 3) lines = cv2.HoughLinesP(edges, 1,np.pi/180,350); for line in lines[0]: pt1 = (line[0],line[1]) pt2 = (line[2],line[3]) cv2.line(img, pt1, pt2, (0,0,255)) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray,50,150,apertureSize = 3) print img.shape lines = cv2.HoughLines(edges,1,np.pi/180,350) for rho,theta in lines[0]: a = np.cos(theta) b = np.sin(theta) if int(b) == 1: #only horizontal lines with cos theta(theta = 0) = 1 x0 = a*rho y0 = b*rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2) cv2.imshow('edges', img) cv2.waitKey(0) cv2.destroyAllWindows() </code></pre> <p>Result: <a href="http://i.stack.imgur.com/QLKmE.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/QLKmE.jpg" alt="enter image description here"></a></p> <p>If I try <code>print x1, y1, x2, y2</code> i get </p> <blockquote> <p>-1000 781 999 782 -1000 712 999 713</p> </blockquote> <p>So these obviously are not the location points in the image matrix like x is negative. </p> <p><strong>What is the location of the start and endpoints of these lines in the image matrix?</strong> I need to perform some point operation on the pixels in that area and hence need the start and endpoints.</p>
1
2016-09-04T20:44:09Z
39,322,600
<p>These lines will always return -1000 + the original point</p> <pre><code>x1 = int(x0 + 1000*(-b)) x2 = int(x0 - 1000*(-b)) </code></pre> <p>As you only get into this loop if <code>int(b) == 1:</code></p> <p>Which means that you need to print the x0 directly, since the above lines will always be <code>(x0 + (-1000))</code>, <strong>in this case x0 is 0 since it starts from the left of the image.</strong></p>
1
2016-09-05T00:25:09Z
[ "python", "opencv", "image-processing", "opencv-contour" ]
I have a list of files, I want to iterate and import functions from those files, so as to work on them one by one, python
39,321,351
<p>I have a list of files, using command in python <code>from filename import *</code> , works for a single file as I am giving the exact name of the file, but if I want to use it as <code>from list[i] import *</code> to iterate over a list and importing function from files one after the another to work on it, it doesn't work? what changes should I make so as to use it for a list of files, so that I can easily iterate?</p>
-2
2016-09-04T20:46:09Z
39,321,473
<p>If you're looking for dynamic imports, you're looking for the <code>__import__</code> function.</p> <pre><code>for modl in ('foo', 'bar', 'baz', 'bat',): __import__('parent.' + modl) </code></pre>
1
2016-09-04T21:02:13Z
[ "python", "file", "file-handling" ]
I have a list of files, I want to iterate and import functions from those files, so as to work on them one by one, python
39,321,351
<p>I have a list of files, using command in python <code>from filename import *</code> , works for a single file as I am giving the exact name of the file, but if I want to use it as <code>from list[i] import *</code> to iterate over a list and importing function from files one after the another to work on it, it doesn't work? what changes should I make so as to use it for a list of files, so that I can easily iterate?</p>
-2
2016-09-04T20:46:09Z
39,321,499
<p>Use <a href="https://docs.python.org/3/library/importlib.html#importlib.import_module" rel="nofollow">importlib</a> for that:</p> <pre><code>from importlib import import_module module_list = [import_module("test.mod{}".format(i)) for i in range(20)] # OR module_list = [] for i in range(20): module_list.append(import_module("test.mod{}".format(i))) </code></pre> <p>As stated by the <a href="https://docs.python.org/3/library/functions.html#__import__" rel="nofollow">documentation</a>, <strong>do not use internal things such as <code>__import__</code></strong>.</p>
3
2016-09-04T21:05:53Z
[ "python", "file", "file-handling" ]
Why is the order of dict and dict.items() different?
39,321,424
<pre><code>&gt;&gt;&gt; d = {'A':1, 'b':2, 'c':3, 'D':4} &gt;&gt;&gt; d {'A': 1, 'D': 4, 'b': 2, 'c': 3} &gt;&gt;&gt; d.items() [('A', 1), ('c', 3), ('b', 2), ('D', 4)] </code></pre> <p>Does the order get randomized twice when I call d.items()? Or does it just get randomized differently? Is there any alternate way to make d.items() return the same order as d? </p> <p>Edit: Seems to be an IPython thing where it auto sorts the dict. Normally dict and dict.items() should be in the same order.</p>
3
2016-09-04T20:55:17Z
39,321,645
<p>You seem to have tested this on IPython. IPython uses its own specialized pretty-printing facilities for various types, and the pretty-printer for dicts sorts the keys before printing (if possible). The <code>d.items()</code> call doesn't sort the keys, so the output is different.</p> <p>In an ordinary Python session, the order of the items in the dict's <code>repr</code> would match the order of the items from the <code>items</code> method. Dict iteration order is supposed to be stable as long as a dict isn't modified. (This guarantee is not explicitly extended to the dict's <code>repr</code>, but it would be surprising if the implicit iteration in <code>repr</code> broke consistency with other forms of dict iteration.)</p>
9
2016-09-04T21:26:10Z
[ "python", "python-2.7", "dictionary", "ipython" ]
I want to slice my pandas data frame with a variable that contains a pd.date_range, but it is returning Nan for my data
39,321,474
<p>I have loaded data from yahoo finance which includes the headings date, open, high, low, close, volume, adj close. The date is my index for the data frame, and I want to be able to sort this data using the index(date).</p> <p>The variable month will give an array of the dates that I need, and it will print. The problem is I get Nan values for my data. </p> <pre><code>from pandas_datareader import data as dreader import pandas as pd df = pd.read_csv("cde_data.csv",index_col='Date') month = pd.date_range('2010-08-01','2016-08-01',freq='m') print(df.ix[month.values]) </code></pre> <p>This is the output that I get (I only posted the first 4 rows to save space)</p> <pre><code> Open High Low Close Volume Adj Close Date 2010-08-31 NaN NaN NaN NaN NaN NaN 2010-09-30 NaN NaN NaN NaN NaN NaN 2010-10-31 NaN NaN NaN NaN NaN NaN 2010-11-30 NaN NaN NaN NaN NaN NaN </code></pre> <p>This the df.head() </p> <pre><code> Open High Low Close Volume Adj Close Date 1990-04-12 26.875 26.875 26.625 26.625 6100 250.576036 1990-04-16 26.500 26.750 26.375 26.750 500 251.752449 1990-04-17 26.750 26.875 26.750 26.875 2300 252.928863 1990-04-18 26.875 26.875 26.500 26.625 3500 250.576036 1990-04-19 26.500 26.750 26.500 26.750 700 251.752449 </code></pre> <p>Press any key to continue . . .</p>
0
2016-09-04T21:02:26Z
39,324,384
<p>Your index is not of type datetime but object. Convert it before using it:</p> <pre><code>df = df.reset_index() df.Date = pd.to_datetime(df.Date) df = df.set_index('Date') </code></pre>
0
2016-09-05T05:27:49Z
[ "python", "pandas", "dataframe", "slice" ]
AttributeError: 'list' object has no attribute 'isdigit'
39,321,495
<p>I want to extract POS in pandas. I do as below</p> <pre><code>import pandas as pd from nltk.tag import pos_tag df = pd.DataFrame({'pos': ['noun', 'Alice', 'good', 'well', 'city']}) s = df['pos'] tagged_sent = pos_tag(s.str.split()) </code></pre> <p>but get a traceback:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "../lib/python2.7/site-packages/nltk/tag/__init__.py", line 111, in pos_tag return _pos_tag(tokens, tagset, tagger) File "../lib/python2.7/site-packages/nltk/tag/__init__.py", line 82, in _pos_tag tagged_tokens = tagger.tag(tokens) File "/Users/mjpieters/Development/venvs/stackoverflow-2.7/lib/python2.7/site-packages/nltk/tag/perceptron.py", line 152, in tag context = self.START + [self.normalize(w) for w in tokens] + self.END File "../lib/python2.7/site-packages/nltk/tag/perceptron.py", line 224, in normalize elif word.isdigit() and len(word) == 4: AttributeError: 'list' object has no attribute 'isdigit' </code></pre> <p>What's wrong? </p>
0
2016-09-04T21:05:24Z
39,321,547
<p>The expression <code>s.str.split()</code> is a <code>list</code> of strings, not a string (expected by <code>pos_tag</code>. Because <code>isdigit</code> is a method of <code>str</code>. </p>
0
2016-09-04T21:13:30Z
[ "python", "nltk", "pos-tagger" ]
AttributeError: 'list' object has no attribute 'isdigit'
39,321,495
<p>I want to extract POS in pandas. I do as below</p> <pre><code>import pandas as pd from nltk.tag import pos_tag df = pd.DataFrame({'pos': ['noun', 'Alice', 'good', 'well', 'city']}) s = df['pos'] tagged_sent = pos_tag(s.str.split()) </code></pre> <p>but get a traceback:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "../lib/python2.7/site-packages/nltk/tag/__init__.py", line 111, in pos_tag return _pos_tag(tokens, tagset, tagger) File "../lib/python2.7/site-packages/nltk/tag/__init__.py", line 82, in _pos_tag tagged_tokens = tagger.tag(tokens) File "/Users/mjpieters/Development/venvs/stackoverflow-2.7/lib/python2.7/site-packages/nltk/tag/perceptron.py", line 152, in tag context = self.START + [self.normalize(w) for w in tokens] + self.END File "../lib/python2.7/site-packages/nltk/tag/perceptron.py", line 224, in normalize elif word.isdigit() and len(word) == 4: AttributeError: 'list' object has no attribute 'isdigit' </code></pre> <p>What's wrong? </p>
0
2016-09-04T21:05:24Z
39,321,548
<p>You can actually pass <code>Series</code> object to the <code>pos_tag()</code> method directly:</p> <pre><code>s = df['pos'] tagged_sent = pos_tag(s) # or pos_tag(s.tolist()) print(tagged_sent) </code></pre> <p>Prints:</p> <pre><code>[('noun', 'JJ'), ('Alice', 'NNP'), ('good', 'JJ'), ('well', 'RB'), ('city', 'NN')] </code></pre>
2
2016-09-04T21:13:31Z
[ "python", "nltk", "pos-tagger" ]
how to process an upload file in Flask?
39,321,540
<p>I have a simple Flask app and I would like for it to process an uploaded excel file and display it's data in the webpage. So far I got a page to upload the excel file.</p> <p>main.py</p> <pre><code>from flask import Flask, render_template, send_file, request from flask_uploads import UploadSet, configure_uploads, DOCUMENTS, IMAGES app = Flask(__name__) #the name 'datafiles' must match in app.config to DATAFILES docs = UploadSet('datafiles', DOCUMENTS) app.config['UPLOADED_DATAFILES_DEST'] = 'static/uploads' configure_uploads(app, docs) @app.route("/", methods=['GET']) def index(): # return send_file("templates/index.html") return render_template('index.html') @app.route("/upload", methods = ['GET', 'POST']) def upload(): #user_file is the name value in input element if request.method == 'POST' and 'user_file' in request.files: filename = docs.save(request.files['user_file']) return filename return render_template('upload.html') @app.route("/mergedata", methods=['GET']) def merge_data(): return send_file("templates/mergeDataPage.html") if __name__ == "__main__": app.run(host='0.0.0.0', debug=True) </code></pre> <p>upload.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;upload&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="POST" enctype=multipart/form-data action ="{{url_for('upload')}}"&gt; &lt;input type="file" name="user_file"&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Once the file is uploaded, I would like to process this excel data by using another python script - This script will take the excel file, remove special characters and converted to a csv file/output. I would like to display the csv output in the webpage.</p> <p>The idea is for users to upload the file, press a button to clean the data and have the results printed in an output box. How do I go about in building something like this scenario? </p> <p>I'm pretty new to Flask, but so far has been pretty exciting to learn this cool web framework. Your help will be appreciated, thanks!</p>
-1
2016-09-04T21:12:09Z
39,321,640
<p>You can use <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a> module and first convert the excel file.</p> <pre><code>import pandas as pd data_xls = pd.read_excel('your_workbook.xls', 'Sheet1', index_col=None) data_xls.to_csv('your_csv.csv', encoding='utf-8') </code></pre> <p>Pandas is spectacular for dealing with csv files, and the following code would be all you need to read a csv and save an entire column into a variable:</p> <pre><code>import pandas as pd df = pd.read_csv(csv_file) saved_column = df.column_name #you can also use df['column_name'] </code></pre> <p>For instance if you wanted to save all of the info in your column Names into a variable, this is all you need to do:</p> <pre><code>names = df.Names </code></pre>
1
2016-09-04T21:25:54Z
[ "python", "html", "flask" ]
Can't pickle an RSA key to send over a socket
39,321,606
<p>I have a list with a public key and a username that I want to send over a socket.</p> <p>I found <a href="http://stackoverflow.com/questions/24423162/how-to-send-an-array-over-a-socket-in-python">how to send an array over a socket in python</a> but using pickling won't work either.</p> <p>My code:</p> <pre><code>private_key = generateRSA() public_key = private_key.public_key() host = '' port = 8000 username = sys.argv[1] mySocket = socket.socket() mySocket.connect((host, port)) dataToSend = [public_key, username.encode()] dataSend = pickle.dumps(dataToSend) mySocket.send(dataSend) </code></pre> <p>The error in the console says</p> <pre><code> dataSend = pickle.dumps(dataToSend) _pickle.PicklingError: Can't pickle &lt;class '_cffi_backend.CDataGCP'&gt;: attribute lookup CDataGCP on _cffi_backend failed </code></pre> <p>The key was generated with the <a href="https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/" rel="nofollow"><code>cryptography</code> library</a>.</p>
0
2016-09-04T21:20:43Z
39,321,751
<p>You are trying to send a <a href="https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/#cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey" rel="nofollow"><code>RSAPublicKey</code> instance</a>, but this is a data structure managed by SSL, not Python. Because you interact with it through a CFFI proxy, you can't pickle one of these.</p> <p>You'll need to pick a <a href="https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/#key-serialization" rel="nofollow"><em>key serialization format</em></a> to send it instead. You could convert to PEM, for example:</p> <pre><code>from cryptography.hazmat.primitives import serialization pem = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) </code></pre> <p>The above would export your key to a string value you could then convert to bytes and send over the socket directly. The other side would <a href="https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/#key-loading" rel="nofollow">load the key</a> from that string again.</p> <p>Note that the above uses <strong>no encryption whatsoever</strong>. Anyone intercepting the traffic over that socket would be able to read your public key. That may or may not be a problem for your application.</p>
0
2016-09-04T21:44:37Z
[ "python", "sockets", "python-3.x", "pickle" ]
How do I get rid of local variable referenced before assignment error?
39,321,717
<p>I'm trying to make a simple program that generates a board on which you move around as X. Code:</p> <pre><code>from msvcrt import getch import os board = [] for x in range(20): board.append(["O"] * 20) def print_board(board): for row in board: print " ".join(row) def keys(coordx, coordy): global coordY global coordX key = ord(getch()) if key == 97: coordx -= 1 elif key == 100: coordx += 1 elif key == 115: coordy -= 1 elif key == 119: coordy += 1 def play(coordx, coordy): global coordY global coordX while True: board[coordx][coordy] = "X" print_board(board) keys(coordx, coordy) os.system('cls') coordX = 10 coordY = 10 play(coordX, coordY) </code></pre> <p>Every time i want the program to change the value of coordX or coordY i get UnboundLocalError: local variable coordY/coordX refferenced before assignment. I tried different methods - making variables global, making arguments for functions instead of using the variables while defining functions and nothing worked.</p>
-2
2016-09-04T21:38:07Z
39,321,745
<p>Once you call <code>play</code>, you never make any assignments to either <code>coordX</code> or <code>coordY</code>, which would explain why they never change.</p>
1
2016-09-04T21:43:27Z
[ "python", "python-2.7" ]
Globale Variables with Bottlpy (in background)
39,321,833
<p>i need to use global variables in my program with either flask or bottle running as a webservice. so far im using bottle as a thread with a snippet i found here: <a href="http://stackoverflow.com/questions/13021762/starting-python-bottle-in-a-thread-process-and-another-daemon-next-to-it">Starting python bottle in a thread/Process and another daemon next to it</a></p> <p>i basically want to go to localhost:8080/hello to increase the global variable test by one:</p> <pre><code>#!/usr/bin/env python from bottle import route, run from multiprocessing import Process @route('/hello') def hello(): global test test = test + 1 return test def main(): global test test = 0 t = Process(target=bottle.run(host='0.0.0.0', port=8080)) t.daemon = True t.start() while(True) print test time.sleep(0.5) if __name__ == "__main__": main() </code></pre> <p>if i go to localhost:8080/hello with my browser i get: Error 500: Internal Server Error - Unhandled Exception</p> <p>i cant see the exception tho, even with</p> <pre><code>try global test test = test + 1 return test except Exception e print e </code></pre>
1
2016-09-04T21:56:59Z
39,353,690
<p>You're returning an <code>int</code> from <code>hello</code>, but you need to return an iterable (of strings).</p> <p>Tip: add <code>debug=True</code> to your call to <code>run</code> to get better error info in your response.</p> <p><code>t = Process(target=run(host='0.0.0.0', port=8080, debug=True))</code></p>
0
2016-09-06T16:24:00Z
[ "python", "bottle" ]
SpaCy, Parsing, Tagging - Output as List
39,321,886
<p>I am using spacy for nlp and I have issue printing/outputing results in a concise form. At the moment every output from (token.pos_) goes to a new line.</p> <p>I was hoping to get it to print, as a list. I can do this in nltk/stanford pos, but spacy's documentation is very obfuscated. I cant seem to find out how the tokens work or how to call the values I need as in an acceptable manner. Spacy, is so mechanical.</p> <p>This is my code:</p> <pre><code>for token in words: print(token.pos_) Adj Adj Noun Noun [adj,adj] [noun,noun] </code></pre> <p>I have tried</p> <pre><code>for token in words: v,x = token.pos_ </code></pre>
1
2016-09-04T22:03:37Z
39,352,133
<p>Instead of printing, one could add the results to a list, e.g.</p> <pre><code>listOfPos = [] for token in words: listOfPos.append(token.pos_) print listOfPos </code></pre>
0
2016-09-06T14:57:09Z
[ "python", "spacy" ]
Python: Summing Odd/Even Random Numbers Generates TypeError: 'int' object is not iterable
39,321,898
<p>Yes, this question has been asked, but I cannot seem to apply the answers to my problem. There are several parts to this problem, and this is the biggest obstacle I've hit.</p> <p>I need to generate a random list of 10 numbers between 10 &amp; 90. From those random numbers, I need to sum the totals of both the even and odd numbers.</p> <pre><code>def playlist(): nums = [] for nums in range(10): # Get random list of 10 numbers my_nums = random.randint(10, 90) print (my_nums,end=' ') even = [] odd = [] for x in my_nums: if x % 2 == 0: even.append[x] print(even) else: odd.append[x] print(odd) </code></pre> <p>When I run this, sometimes I get one or two numbers (usually the first two odd numbers), but mostly I get TypeError: 'int' object is not iterable. </p> <p>Not gonna lie - my first language is PHP, not Python and that's becoming a huge problem for me :(</p> <p>Any help is appreciated.</p>
0
2016-09-04T22:05:31Z
39,321,946
<p>As mentioned the comments, you can't write <code>for x in</code> followed by a number. I guess what you want is <code>for x in range(my_nums)</code> rather than <code>for x in my_nums</code>.</p>
0
2016-09-04T22:12:53Z
[ "python", "random", "range", "typeerror", "iterable" ]
Python: Summing Odd/Even Random Numbers Generates TypeError: 'int' object is not iterable
39,321,898
<p>Yes, this question has been asked, but I cannot seem to apply the answers to my problem. There are several parts to this problem, and this is the biggest obstacle I've hit.</p> <p>I need to generate a random list of 10 numbers between 10 &amp; 90. From those random numbers, I need to sum the totals of both the even and odd numbers.</p> <pre><code>def playlist(): nums = [] for nums in range(10): # Get random list of 10 numbers my_nums = random.randint(10, 90) print (my_nums,end=' ') even = [] odd = [] for x in my_nums: if x % 2 == 0: even.append[x] print(even) else: odd.append[x] print(odd) </code></pre> <p>When I run this, sometimes I get one or two numbers (usually the first two odd numbers), but mostly I get TypeError: 'int' object is not iterable. </p> <p>Not gonna lie - my first language is PHP, not Python and that's becoming a huge problem for me :(</p> <p>Any help is appreciated.</p>
0
2016-09-04T22:05:31Z
39,321,962
<p>You should be doing this.</p> <pre><code>def playlist(): nums1 = [] for nums in range(10): # Get random list of 10 numbers my_nums = random.randint(10, 90) nums1.append(my_nums) print my_nums even = [] odd = [] for x in nums1: if x % 2 == 0: even.append(x) print(even) else: odd.append(x) print(odd) playlist() </code></pre>
2
2016-09-04T22:15:30Z
[ "python", "random", "range", "typeerror", "iterable" ]
Python: Summing Odd/Even Random Numbers Generates TypeError: 'int' object is not iterable
39,321,898
<p>Yes, this question has been asked, but I cannot seem to apply the answers to my problem. There are several parts to this problem, and this is the biggest obstacle I've hit.</p> <p>I need to generate a random list of 10 numbers between 10 &amp; 90. From those random numbers, I need to sum the totals of both the even and odd numbers.</p> <pre><code>def playlist(): nums = [] for nums in range(10): # Get random list of 10 numbers my_nums = random.randint(10, 90) print (my_nums,end=' ') even = [] odd = [] for x in my_nums: if x % 2 == 0: even.append[x] print(even) else: odd.append[x] print(odd) </code></pre> <p>When I run this, sometimes I get one or two numbers (usually the first two odd numbers), but mostly I get TypeError: 'int' object is not iterable. </p> <p>Not gonna lie - my first language is PHP, not Python and that's becoming a huge problem for me :(</p> <p>Any help is appreciated.</p>
0
2016-09-04T22:05:31Z
39,321,999
<p>Creating list with randoms</p> <pre><code>n = [random.randint(10,90) for x in range(10)] </code></pre> <p>Getting even and odds:</p> <pre><code>even = [x for x in n if x % 2 == 0] odd = [x for x in n if x % 2 == 1] </code></pre>
2
2016-09-04T22:22:21Z
[ "python", "random", "range", "typeerror", "iterable" ]
Python: Summing Odd/Even Random Numbers Generates TypeError: 'int' object is not iterable
39,321,898
<p>Yes, this question has been asked, but I cannot seem to apply the answers to my problem. There are several parts to this problem, and this is the biggest obstacle I've hit.</p> <p>I need to generate a random list of 10 numbers between 10 &amp; 90. From those random numbers, I need to sum the totals of both the even and odd numbers.</p> <pre><code>def playlist(): nums = [] for nums in range(10): # Get random list of 10 numbers my_nums = random.randint(10, 90) print (my_nums,end=' ') even = [] odd = [] for x in my_nums: if x % 2 == 0: even.append[x] print(even) else: odd.append[x] print(odd) </code></pre> <p>When I run this, sometimes I get one or two numbers (usually the first two odd numbers), but mostly I get TypeError: 'int' object is not iterable. </p> <p>Not gonna lie - my first language is PHP, not Python and that's becoming a huge problem for me :(</p> <p>Any help is appreciated.</p>
0
2016-09-04T22:05:31Z
39,322,177
<p>This is ultimately what I needed:</p> <pre><code>def playlist(): nums = [] for nums1 in range(10): # Get random list of 10 numbers my_nums = random.randint(10, 90) nums.append(my_nums) print (my_nums,end=' ') even = [] odd = [] for x in nums: if x % 2 == 0: even.append(x) else: odd.append(x) print ("\n") print("Total of Even Numbers: ",sum(even)) print ("\n") print("Total of Odd Numbers: ",sum(odd)) </code></pre> <p>Thanks to everyone for their help...yes I know the call to run the function is missing - like I said this is just one part of the program :)</p>
0
2016-09-04T22:57:47Z
[ "python", "random", "range", "typeerror", "iterable" ]
Python: Summing Odd/Even Random Numbers Generates TypeError: 'int' object is not iterable
39,321,898
<p>Yes, this question has been asked, but I cannot seem to apply the answers to my problem. There are several parts to this problem, and this is the biggest obstacle I've hit.</p> <p>I need to generate a random list of 10 numbers between 10 &amp; 90. From those random numbers, I need to sum the totals of both the even and odd numbers.</p> <pre><code>def playlist(): nums = [] for nums in range(10): # Get random list of 10 numbers my_nums = random.randint(10, 90) print (my_nums,end=' ') even = [] odd = [] for x in my_nums: if x % 2 == 0: even.append[x] print(even) else: odd.append[x] print(odd) </code></pre> <p>When I run this, sometimes I get one or two numbers (usually the first two odd numbers), but mostly I get TypeError: 'int' object is not iterable. </p> <p>Not gonna lie - my first language is PHP, not Python and that's becoming a huge problem for me :(</p> <p>Any help is appreciated.</p>
0
2016-09-04T22:05:31Z
39,322,255
<p>There are a few things you seem to have misunderstood:</p> <ul> <li><code>range(10)</code> will give you (something that looks like) this list <code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</code>. <ul> <li>You can use it with a for-loop to do something 10 times</li> </ul></li> <li><code>random.randint(10, 90)</code> will give you a single random number between 10 and 90 (not a list)</li> </ul> <p>With this information we can change your script to:</p> <pre><code>import random even_sum = 0 odd_sum = 0 for number_of_turns in range(10): # Get a random number number_this_turn = random.randint(10, 90) print(number_this_turn,end=' ') if number_this_turn % 2 == 0: even_sum += number_this_turn print("Sum of even numbers so far:", even_sum) else: odd_sum += number_this_turn print("Sum of odd numbers so far:", odd_sum) print("Final sum of even numbers:", even_sum) print("Final sum of odd numbers:", odd_sum) </code></pre> <p>But we can do better. You will learn that in Python, you will want very often to define a list (or an iterable) with the terms you need then do something with every term. So we can change your script to:</p> <pre><code>import random even_sum = 0 odd_sum = 0 random_numbers = [random.randint(10, 90) for x in range(10)] for number in random_numbers: print(number,end=' ') if number % 2 == 0: even_sum += number print("Sum of even numbers so far:", even_sum) else: odd_sum += number print("Sum of odd numbers so far:", odd_sum) print("Final sum of even numbers:", even_sum) print("Final sum of odd numbers:", odd_sum) </code></pre> <p><code>random_numbers = [random.randint(10, 90) for x in range(10)]</code> is using a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> to generate a list of 10 random numbers. You can then do a for-loop on each of these numbers where you can add to the evens' sum or to the odds' sum.</p> <p>You can even simplify it even further like in @Take_Care_ 's answer but I guess you have a lot more to learn before you reach this level.</p>
0
2016-09-04T23:12:58Z
[ "python", "random", "range", "typeerror", "iterable" ]
Python: Summing Odd/Even Random Numbers Generates TypeError: 'int' object is not iterable
39,321,898
<p>Yes, this question has been asked, but I cannot seem to apply the answers to my problem. There are several parts to this problem, and this is the biggest obstacle I've hit.</p> <p>I need to generate a random list of 10 numbers between 10 &amp; 90. From those random numbers, I need to sum the totals of both the even and odd numbers.</p> <pre><code>def playlist(): nums = [] for nums in range(10): # Get random list of 10 numbers my_nums = random.randint(10, 90) print (my_nums,end=' ') even = [] odd = [] for x in my_nums: if x % 2 == 0: even.append[x] print(even) else: odd.append[x] print(odd) </code></pre> <p>When I run this, sometimes I get one or two numbers (usually the first two odd numbers), but mostly I get TypeError: 'int' object is not iterable. </p> <p>Not gonna lie - my first language is PHP, not Python and that's becoming a huge problem for me :(</p> <p>Any help is appreciated.</p>
0
2016-09-04T22:05:31Z
39,332,862
<p>Following code works:</p> <pre><code>""" I need to generate a random list of 10 numbers between 10 &amp; 90. From those random numbers, I need to sum the totals of both the even and odd numbers. """ from random import randint MIN = 10 MAX = 90 sum_odds = sum_evens = 0 for i in range(10): r = randint(MIN,MAX) if r % 2: sum_odds += r else: sum_evens += r return sum_evens, sum_odds </code></pre>
0
2016-09-05T14:34:29Z
[ "python", "random", "range", "typeerror", "iterable" ]