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
sequence |
---|---|---|---|---|---|---|---|---|---|
importing issues between modules | 39,970,364 | <pre><code>|--------FlaskApp
|----------------FlaskApp
|----------------__init__.py
|----------------view.py
|----------------models.py
|----------------db_create.py
|-----------------------static
|-----------------------templates
|-----------------------venv
|-----------------------__init__.py
|----------------flaskapp.wsgi
</code></pre>
<p>this is my modules and folder layout i have a import problem in init i have <pre>db = sqlalchemy</pre> im trying to import <strong>db</strong> to <strong>views.py, models.py and db_create.py</strong> but im getting all kinds of importing errors because im not importing thr proper way now my question is if i want to import db to the modules i specified how would i do it without getting a error</p>
<p><strong>some of the code importing db</strong></p>
<p><strong>models.py</strong></p>
<pre><code>from FlaskApp import db
class UserInfo(db.Model):
__tablename_ = 'user_info'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(80), unique=True)
password = db.Column(db.String(100), nullable=False)
posts = relationship('UserPosts', backref='posts')
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = password
def __repr__(self):
return '{}-{}'.format(self.username, self.email)
</code></pre>
<p><strong>views.py</strong></p>
<pre><code>from FlaskApp import db
@app.route('/')
@login_required
def home():
user = db.session.query(UserInfo).all()
return render_template('home.html', user=user)
</code></pre>
<p><strong>__init__.py</strong></p>
<pre><code>from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
tail /var/log/apache2/error.log
[Tue Oct 11 04:17:20.925573 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] Traceback (most recent call last):, referer: http://localhost/
[Tue Oct 11 04:17:20.925618 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] File "/var/www/FlaskApp/flaskapp.wsgi", line 14, in <module>, referer: http://localhost/
[Tue Oct 11 04:17:20.925626 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] from FlaskApp import app as application, referer: http://localhost/
[Tue Oct 11 04:17:20.925638 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] File "/var/www/FlaskApp/FlaskApp/__init__.py", line 4, in <module>, referer: http://localhost/
[Tue Oct 11 04:17:20.925644 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] import FlaskApp.main, referer: http://localhost/
[Tue Oct 11 04:17:20.925653 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] File "/var/www/FlaskApp/FlaskApp/main.py", line 7, in <module>, referer: http://localhost/
[Tue Oct 11 04:17:20.925658 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] from models import UserInfo, referer: http://localhost/
[Tue Oct 11 04:17:20.925668 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] File "/var/www/FlaskApp/FlaskApp/models.py", line 2, in <module>, referer: http://localhost/
[Tue Oct 11 04:17:20.925673 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] from FlaskApp import db, referer: http://localhost/
[Tue Oct 11 04:17:20.925707 2016] [wsgi:error] [pid 5049:tid 139870897813248] [client 174.58.31.189:55884] ImportError: cannot import name 'db', referer: http://localhost/
</code></pre>
<p>my goal is not just to solve one error is to be able to import the right way from now on</p>
| -1 | 2016-10-11T04:07:58Z | 39,988,340 | <p>got this after using the above answer</p>
<pre>RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed to interface with the current application object in a way. To solve this set up an application context with app.app_context(). See the documentation for more information.</pre>
<pre><code> tail -n 40 /var/log/apache2/error.log
[Wed Oct 12 00:20:02.315500 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] import FlaskApp.main
[Wed Oct 12 00:20:02.315510 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] File "/var/www/FlaskApp/FlaskApp/main.py", line 2, in <module>
[Wed Oct 12 00:20:02.315516 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] from .models import UserInfo
[Wed Oct 12 00:20:02.315526 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] File "/var/www/FlaskApp/FlaskApp/models.py", line 7, in <module>
[Wed Oct 12 00:20:02.315532 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] db = app.db
[Wed Oct 12 00:20:02.315542 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] File "/usr/local/lib/python3.5/dist-packages/werkzeug/local.py", line 343, in __getattr__
[Wed Oct 12 00:20:02.315547 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] return getattr(self._get_current_object(), name)
[Wed Oct 12 00:20:02.315557 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] File "/usr/local/lib/python3.5/dist-packages/werkzeug/local.py", line 302, in _get_current_object
[Wed Oct 12 00:20:02.315563 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] return self.__local()
[Wed Oct 12 00:20:02.315573 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] File "/usr/local/lib/python3.5/dist-packages/flask/globals.py", line 51, in _find_app
[Wed Oct 12 00:20:02.315579 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] raise RuntimeError(_app_ctx_err_msg)
[Wed Oct 12 00:20:02.315611 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] RuntimeError: Working outside of application context.
[Wed Oct 12 00:20:02.315620 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784]
[Wed Oct 12 00:20:02.315628 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] This typically means that you attempted to use functionality that needed
[Wed Oct 12 00:20:02.315634 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] to interface with the current application object in a way. To solve
[Wed Oct 12 00:20:02.315641 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] this set up an application context with app.app_context(). See the
[Wed Oct 12 00:20:02.315648 2016] [wsgi:error] [pid 19327:tid 139821662463744] [client 174.58.31.189:51784] documentation for more information.
[Wed Oct 12 00:20:02.813916 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] mod_wsgi (pid=19326): Target WSGI script '/var/www/FlaskApp/flaskapp.wsgi' cannot be loaded as Python module., referer: http://localhost/
[Wed Oct 12 00:20:02.814030 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] mod_wsgi (pid=19326): Exception occurred processing WSGI script '/var/www/FlaskApp/flaskapp.wsgi'., referer: http://localhost/
[Wed Oct 12 00:20:02.814917 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] Traceback (most recent call last):, referer: http://localhost/
[Wed Oct 12 00:20:02.814972 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] File "/var/www/FlaskApp/flaskapp.wsgi", line 14, in <module>, referer: http://localhost/
[Wed Oct 12 00:20:02.814981 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] from FlaskApp import app as application, referer: http://localhost/
[Wed Oct 12 00:20:02.814993 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] File "/var/www/FlaskApp/FlaskApp/__init__.py", line 4, in <module>, referer: http://localhost/
[Wed Oct 12 00:20:02.814998 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] import FlaskApp.main, referer: http://localhost/
[Wed Oct 12 00:20:02.815008 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] File "/var/www/FlaskApp/FlaskApp/main.py", line 2, in <module>, referer: http://localhost/
[Wed Oct 12 00:20:02.815014 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] from .models import UserInfo, referer: http://localhost/
[Wed Oct 12 00:20:02.815024 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] File "/var/www/FlaskApp/FlaskApp/models.py", line 7, in <module>, referer: http://localhost/
[Wed Oct 12 00:20:02.815029 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] db = app.db, referer: http://localhost/
[Wed Oct 12 00:20:02.815040 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] File "/usr/local/lib/python3.5/dist-packages/werkzeug/local.py", line 343, in __getattr__, referer: http://localhost/
[Wed Oct 12 00:20:02.815046 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] return getattr(self._get_current_object(), name), referer: http://localhost/
[Wed Oct 12 00:20:02.815055 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] File "/usr/local/lib/python3.5/dist-packages/werkzeug/local.py", line 302, in _get_current_object, referer: http://localhost/
[Wed Oct 12 00:20:02.815061 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] return self.__local(), referer: http://localhost/
[Wed Oct 12 00:20:02.815071 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] File "/usr/local/lib/python3.5/dist-packages/flask/globals.py", line 51, in _find_app, referer: http://localhost/
[Wed Oct 12 00:20:02.815077 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] raise RuntimeError(_app_ctx_err_msg), referer: http://localhost/
[Wed Oct 12 00:20:02.815107 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] RuntimeError: Working outside of application context., referer: http://localhost/
[Wed Oct 12 00:20:02.815114 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] , referer: http://localhost/
[Wed Oct 12 00:20:02.815118 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] This typically means that you attempted to use functionality that needed, referer: http://localhost/
[Wed Oct 12 00:20:02.815123 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] to interface with the current application object in a way. To solve, referer: http://localhost/
[Wed Oct 12 00:20:02.815139 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] this set up an application context with app.app_context(). See the, referer: http://localhost/
[Wed Oct 12 00:20:02.815143 2016] [wsgi:error] [pid 19326:tid 139821670856448] [client 174.58.31.189:51786] documentation for more information., referer: http://localhost/
</code></pre>
| 0 | 2016-10-11T23:34:04Z | [
"python",
"flask",
"flask-sqlalchemy",
"python-3.5"
] |
Finding a coordinate of matched object from template matching | 39,970,445 | <p>I'm a newbie to computer vision and openCV, just for the heads up.
So I used this code from <a href="http://docs.opencv.org/3.1.0/d4/dc6/tutorial_py_template_matching.html" rel="nofollow">http://docs.opencv.org/3.1.0/d4/dc6/tutorial_py_template_matching.html</a></p>
<p>Below is the code:</p>
<pre><code>import cv2
import numpy as np
image = cv2.imread('new_test.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
template = cv2.imread('new_template.jpg',0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(gray,template,cv2.TM_CCOEFF_NORMED)
threshold = 0.5
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
cv2.imshow('res.png',image)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code></pre>
<p>I modified this code, of course, to match with my own pictures.</p>
<p>So supposed I have 4 objects in 'new_test.jpg' that matches the template 'new_template.jpg'. The next step in my algorithm should be detecting the coordinate of each objects.</p>
<p>How do I do that ?</p>
| 0 | 2016-10-11T04:19:09Z | 39,971,154 | <p>This piece of code:</p>
<pre><code>for pt in zip(*loc[::-1]):
cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
</code></pre>
<p>draws red rectangle at every position where template probably is located. So at every step point <code>pt</code> (from <code>loc</code> list) contains coordinates of the left top corner of one of your objects (if it has been properly detected)</p>
| 0 | 2016-10-11T05:49:26Z | [
"python",
"osx",
"python-2.7",
"opencv",
"opencv3.0"
] |
What to do if a query result is too big | 39,970,487 | <p>I'm using mysql connector of python3 to query from a mysql database. I have so many data that if I collect the recent 7 days' data, the size of the query will be over 10GB and therefore forced my python script to be killed. I think usually we can stream the result however I don't find a way to stream the query result in mysql conncetor. Is there any other way that I can solve the problem?</p>
| -1 | 2016-10-11T04:26:42Z | 39,970,671 | <p>Don't fetch the result set in one go. You can do one of the following or the combination of these:</p>
<ol>
<li>Use <code>LIMIT, OFFSET</code> to generate multiple files using <code>SELECT into</code></li>
<li>Use Date/Hour Functions to generate multiple files using <code>SELECT into</code></li>
</ol>
<p><code>cat</code> all the generated files into one file using <code>cat hugedata_* > hugedata.csv</code></p>
| 0 | 2016-10-11T04:50:12Z | [
"python",
"mysql",
"mysql-connector"
] |
What to do if a query result is too big | 39,970,487 | <p>I'm using mysql connector of python3 to query from a mysql database. I have so many data that if I collect the recent 7 days' data, the size of the query will be over 10GB and therefore forced my python script to be killed. I think usually we can stream the result however I don't find a way to stream the query result in mysql conncetor. Is there any other way that I can solve the problem?</p>
| -1 | 2016-10-11T04:26:42Z | 40,029,516 | <p>@Anthony Kong's comment is correct. To solve this issue, we can do <code>fetchmany</code> function from <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchmany.html" rel="nofollow">https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchmany.html</a></p>
<p>After digging into the code a little bit, I found that the <code>fetchmany</code> function calls many <code>fetchone</code> to achieve "fetchmany". So I decide to use fetchone at last. Also fetchone comes with an example on the document <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchone.html" rel="nofollow">https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchone.html</a></p>
| 0 | 2016-10-13T19:37:25Z | [
"python",
"mysql",
"mysql-connector"
] |
Connect to Database on local host with sqlite3 in python | 39,970,495 | <p>I have a database that I am running on my local machine which I can access through Microsoft SQL Server Manager Studio. I connect to this server "JIMS-LAPTOP\SQLEXPRESS" and then I can run queries through the manager. However I need to be able to connect to this database and work with it through python.
When I try to connect using sqlite3 like </p>
<pre><code>conn = sqlite3.connect("JIMS-LAPTOP\SQLEXPRESS")
</code></pre>
<p>I get an unable to open database file error</p>
<p>I tried accessing the temporary file directly like this</p>
<pre><code>conn = sqlite3.connect("C:\Users\Jim Notaro\AppData\Local\Temp\~vs13A7.sql")
c = conn.cursor()
c.execute("SELECT name FROM sqlite_master WHERE type = \"table\"")
print c.fetchall()
</code></pre>
<p>Which allows me to access a database but it is completely empty (No tables are displayed)</p>
<p>I also tried connecting like this</p>
<pre><code>conn = sqlite3.connect("SQL SERVER (SQLEXPRESS)")
</code></pre>
<p>Which is what the name is in the sql server configuration manager but that also returns a blank database.</p>
<p>I'm not sure how I am suppose to be connecting to the database using python</p>
| 0 | 2016-10-11T04:27:08Z | 39,971,478 | <p>You can't use sqlite3 to connect to SQL server, only to Sqlite databases.
You need to use a driver that can talk to MS SQL, like <code>pyodbc</code>.</p>
| 1 | 2016-10-11T06:22:11Z | [
"python",
"sql",
"sql-server",
"database",
"sqlite3"
] |
Python: Plot a sparse matrix | 39,970,515 | <p>I have a sparse matrix X, shape (6000, 300). I'd like something like a scatterplot which has a dot where the X(i, j) != 0, and blank space otherwise. I don't know how many nonzero entries there are in each row of X. X[0] has 15 nonzero entries, X[1] has 3, etc. The maximum number of nonzero entries in a row is 16.</p>
<p>Attempts:</p>
<ul>
<li><code>plt.imshow(X)</code> results in a tall, skinny graph because of the shape of X. Using <code>plt.imshow(X, aspect='auto)</code> will stretch out the graph horizontally, but the dots get stretched out to become ellipses, and the plot becomes hard to read.</li>
<li><code>ax.spy</code> suffers from the same problem. </li>
<li><code>bokeh</code> seems promising, but really taxes my jupyter kernel. </li>
</ul>
<p>Bonus:</p>
<ul>
<li>The nonzero entries of X are positive real numbers. If there was some way to reflect their magnitude, that would be great as well (e.g. colour intensity, transparency, or across a colour bar).</li>
<li>Every 500 rows of X belong to the same class. That's 12 classes * 500 observations (rows) per class = 6000 rows. E.g. X[:500] are from class A, X[500:1000] are from class B, etc. Would be nice to colour-code the dots by class. For the moment I'll settle for manually including horizontal lines every 500 rows to delineate between classes. </li>
</ul>
| 0 | 2016-10-11T04:29:47Z | 39,971,118 | <p>It seems to me heatmap is the best candidate for this type of plot. imshow() will return u a colored matrix with color scale legend. </p>
<p>I don't get ur stretched ellipses problem, shouldnt it be a colored squred for each data point? </p>
<p>u can try log color scale if it is sparse. also plot the 12 classes separately to analyze if theres any inter-class differences. </p>
| 0 | 2016-10-11T05:44:36Z | [
"python",
"matplotlib"
] |
Python: Plot a sparse matrix | 39,970,515 | <p>I have a sparse matrix X, shape (6000, 300). I'd like something like a scatterplot which has a dot where the X(i, j) != 0, and blank space otherwise. I don't know how many nonzero entries there are in each row of X. X[0] has 15 nonzero entries, X[1] has 3, etc. The maximum number of nonzero entries in a row is 16.</p>
<p>Attempts:</p>
<ul>
<li><code>plt.imshow(X)</code> results in a tall, skinny graph because of the shape of X. Using <code>plt.imshow(X, aspect='auto)</code> will stretch out the graph horizontally, but the dots get stretched out to become ellipses, and the plot becomes hard to read.</li>
<li><code>ax.spy</code> suffers from the same problem. </li>
<li><code>bokeh</code> seems promising, but really taxes my jupyter kernel. </li>
</ul>
<p>Bonus:</p>
<ul>
<li>The nonzero entries of X are positive real numbers. If there was some way to reflect their magnitude, that would be great as well (e.g. colour intensity, transparency, or across a colour bar).</li>
<li>Every 500 rows of X belong to the same class. That's 12 classes * 500 observations (rows) per class = 6000 rows. E.g. X[:500] are from class A, X[500:1000] are from class B, etc. Would be nice to colour-code the dots by class. For the moment I'll settle for manually including horizontal lines every 500 rows to delineate between classes. </li>
</ul>
| 0 | 2016-10-11T04:29:47Z | 39,979,586 | <p>You can use <code>nonzero()</code> to find the non zero elements and use <code>scatter()</code> plot the points:</p>
<pre><code>import pylab as pl
import numpy as np
a = np.random.rand(6000, 300)
a[a < 0.9999] = 0
r, c = np.nonzero(a)
pl.scatter(r, c, c=a[r, c])
</code></pre>
| 0 | 2016-10-11T14:27:12Z | [
"python",
"matplotlib"
] |
Python: Plot a sparse matrix | 39,970,515 | <p>I have a sparse matrix X, shape (6000, 300). I'd like something like a scatterplot which has a dot where the X(i, j) != 0, and blank space otherwise. I don't know how many nonzero entries there are in each row of X. X[0] has 15 nonzero entries, X[1] has 3, etc. The maximum number of nonzero entries in a row is 16.</p>
<p>Attempts:</p>
<ul>
<li><code>plt.imshow(X)</code> results in a tall, skinny graph because of the shape of X. Using <code>plt.imshow(X, aspect='auto)</code> will stretch out the graph horizontally, but the dots get stretched out to become ellipses, and the plot becomes hard to read.</li>
<li><code>ax.spy</code> suffers from the same problem. </li>
<li><code>bokeh</code> seems promising, but really taxes my jupyter kernel. </li>
</ul>
<p>Bonus:</p>
<ul>
<li>The nonzero entries of X are positive real numbers. If there was some way to reflect their magnitude, that would be great as well (e.g. colour intensity, transparency, or across a colour bar).</li>
<li>Every 500 rows of X belong to the same class. That's 12 classes * 500 observations (rows) per class = 6000 rows. E.g. X[:500] are from class A, X[500:1000] are from class B, etc. Would be nice to colour-code the dots by class. For the moment I'll settle for manually including horizontal lines every 500 rows to delineate between classes. </li>
</ul>
| 0 | 2016-10-11T04:29:47Z | 40,127,976 | <p><code>plt.matshow</code> also turned out to be a feasible solution. I could also plot a heatmap with colorbars and all that.</p>
| 0 | 2016-10-19T09:55:31Z | [
"python",
"matplotlib"
] |
How to encode two Pandas dataframes according to the same dummy vectors? | 39,970,517 | <p>I'm trying to encode categorical values to dummy vectors.
pandas.get_dummies does a perfect job, but the dummy vectors depend on the values present in the Dataframe. How to encode a second Dataframe according to the same dummy vectors as the first Dataframe?</p>
<pre><code> import pandas as pd
df=pd.DataFrame({'cat1':['A','N','K','P'],'cat2':['C','S','T','B']})
b=pd.get_dummies(df['cat1'],prefix='cat1').astype('int')
print(b)
cat1_A cat1_K cat1_N cat1_P
0 1 0 0 0
1 0 0 1 0
2 0 1 0 0
3 0 0 0 1
df_test=df=pd.DataFrame({'cat1':['A','N',],'cat2':['T','B']})
c=pd.get_dummies(df['cat1'],prefix='cat1').astype('int')
print(c)
cat1_A cat1_N
0 1 0
1 0 1
</code></pre>
<p>How can I get this output ? </p>
<pre><code> cat1_A cat1_K cat1_N cat1_P
0 1 0 0 0
1 0 0 1 0
</code></pre>
<p>I was thinking to manually compute uniques for each column and then create a dictionary to map the second Dataframe, but I'm sure there is already a function for that...
Thanks!</p>
| 0 | 2016-10-11T04:29:50Z | 39,973,405 | <p>A always use <a href="https://github.com/wdm0006/categorical_encoding" rel="nofollow">categorical_encoding</a> because it has a great choice of encoders. It also works with Pandas very nicely, is pip installable and is written inline with the sklearn API.</p>
<p>If you wish to encode just the first column, like in your example, we can do so.</p>
<pre><code>import pandas as pd
import category_encoders as ce
df = pd.DataFrame({'cat1':['A','N','K','P'], 'cat2':['C','S','T','B']})
enc_ohe = ce.one_hot.OneHotEncoder(cols=['cat1']) # cols=None, all string columns encoded
df_trans = enc_ohe.fit_transform(df)
print(df_trans)
cat1_0 cat1_1 cat1_2 cat1_3 cat2
0 0 1 0 0 C
1 0 0 0 1 S
2 1 0 0 0 T
3 0 0 1 0 B
</code></pre>
<p>The only downside with it here is that it the column names have numerical encoding instead of the original letters. This is helpful though when you have long strings as categories.</p>
<p>Now we can use the <code>transform</code> method to encode your second DataFrame.</p>
<pre><code>df_test = pd.DataFrame({'cat1':['A','N',],'cat2':['T','B']})
df_test_trans = enc_ohe.transform(df_test)
print(df_test_trans)
cat1_1 cat1_3 cat2
0 1 0 T
1 0 1 B
</code></pre>
<p>As commented in line 5, not setting <code>cols</code> defaults to encode all string columns.</p>
| 0 | 2016-10-11T08:38:35Z | [
"python",
"pandas",
"machine-learning"
] |
How to encode two Pandas dataframes according to the same dummy vectors? | 39,970,517 | <p>I'm trying to encode categorical values to dummy vectors.
pandas.get_dummies does a perfect job, but the dummy vectors depend on the values present in the Dataframe. How to encode a second Dataframe according to the same dummy vectors as the first Dataframe?</p>
<pre><code> import pandas as pd
df=pd.DataFrame({'cat1':['A','N','K','P'],'cat2':['C','S','T','B']})
b=pd.get_dummies(df['cat1'],prefix='cat1').astype('int')
print(b)
cat1_A cat1_K cat1_N cat1_P
0 1 0 0 0
1 0 0 1 0
2 0 1 0 0
3 0 0 0 1
df_test=df=pd.DataFrame({'cat1':['A','N',],'cat2':['T','B']})
c=pd.get_dummies(df['cat1'],prefix='cat1').astype('int')
print(c)
cat1_A cat1_N
0 1 0
1 0 1
</code></pre>
<p>How can I get this output ? </p>
<pre><code> cat1_A cat1_K cat1_N cat1_P
0 1 0 0 0
1 0 0 1 0
</code></pre>
<p>I was thinking to manually compute uniques for each column and then create a dictionary to map the second Dataframe, but I'm sure there is already a function for that...
Thanks!</p>
| 0 | 2016-10-11T04:29:50Z | 39,979,704 | <p>I had the same problem before. This is what I did which is not necessary the best way to do this. But this works for me.</p>
<pre><code>df=pd.DataFrame({'cat1':['A','N'],'cat2':['C','S']})
df['cat1'] = df['cat1'].astype('category', categories=['A','N','K','P'])
# then run the get_dummies
b=pd.get_dummies(df['cat1'],prefix='cat1').astype('int')
</code></pre>
<p>Using the function astype with 'categories' values passed in as parameter.</p>
<p>To apply the same category to all DFs, you better store the category values to a variable like</p>
<pre><code>cat1_categories = ['A','N','K','P']
cat2_categories = ['C','S','T','B']
</code></pre>
<p>Then use astype like</p>
<pre><code>df_test=df=pd.DataFrame({'cat1':['A','N',],'cat2':['T','B']})
df['cat1'] = df['cat1'].astype('category', categories=cat1_categories)
c=pd.get_dummies(df['cat1'],prefix='cat1').astype('int')
print(c)
cat1_A cat1_N cat1_K cat1_P
0 1 0 0 0
1 0 1 0 0
</code></pre>
| 1 | 2016-10-11T14:31:57Z | [
"python",
"pandas",
"machine-learning"
] |
Plot a graph in python using common values in dictionary | 39,970,537 | <p>How can I visually represent the common keys when a value is selected. I am creating a form where the user will select a value, say <code>'john'</code>. I want to plot the common keys'a', 'b' and 'c'. Suggestions on how to approach this problem will be very helpful.</p>
<pre><code>d = {
'a': ['john', 'doe', 'jane'],
'b': ['james', 'danny', 'john'],
'C':['john', 'scott', 'jane'],
}
</code></pre>
| 1 | 2016-10-11T04:33:07Z | 39,971,329 | <p>You can create a data frame from the dictionary:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
df = pd.DataFrame({
'a': ['john', 'doe', 'jane'],
'b': ['james', 'danny', 'john'],
'c':['john', 'scott', 'jane'],
})
</code></pre>
<p>Then you can simply plot <code>john</code> like this:</p>
<pre><code>df.apply(lambda x: (x == 'john').sum()).plot(kind='bar')
</code></pre>
<p><a href="http://i.stack.imgur.com/fEQR5.png" rel="nofollow"><img src="http://i.stack.imgur.com/fEQR5.png" alt="enter image description here"></a></p>
<p><em>Since the string <code>john</code> only occurs one time in each column, all the bars are the same length.</em> </p>
| 1 | 2016-10-11T06:09:28Z | [
"python",
"pandas",
"dictionary",
"matplotlib",
"plot"
] |
Plot a graph in python using common values in dictionary | 39,970,537 | <p>How can I visually represent the common keys when a value is selected. I am creating a form where the user will select a value, say <code>'john'</code>. I want to plot the common keys'a', 'b' and 'c'. Suggestions on how to approach this problem will be very helpful.</p>
<pre><code>d = {
'a': ['john', 'doe', 'jane'],
'b': ['james', 'danny', 'john'],
'C':['john', 'scott', 'jane'],
}
</code></pre>
| 1 | 2016-10-11T04:33:07Z | 39,971,446 | <p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.bar.html" rel="nofollow"><code>Series.plot.bar</code></a>:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
'a': ['john', 'doe', 'jane'],
'b': ['james', 'danny', 'john'],
'c':['john', 'scott', 'jane'],
})
#get boolean mask by condition
print (df == 'john')
a b c
0 True False True
1 False False False
2 False True False
#sum values True
print ((df == 'john').sum())
a 1
b 1
c 1
dtype: int64
(df == 'john').sum().plot.bar()
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/d2Eau.png" rel="nofollow"><img src="http://i.stack.imgur.com/d2Eau.png" alt="graph"></a></p>
<p>If need show all data:</p>
<pre><code>df1 = df.apply(pd.value_counts).T
print (df1)
danny doe james jane john scott
a NaN 1.0 NaN 1.0 1.0 NaN
b 1.0 NaN 1.0 NaN 1.0 NaN
c NaN NaN NaN 1.0 1.0 1.0
df1.plot.bar()
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/BaJoy.png" rel="nofollow"><img src="http://i.stack.imgur.com/BaJoy.png" alt="graph1"></a></p>
| 2 | 2016-10-11T06:18:51Z | [
"python",
"pandas",
"dictionary",
"matplotlib",
"plot"
] |
How to divide list of lists by another list of lists in Python? | 39,970,595 | <p>I have <code>q = [[7,2,3],[4,5,6]]</code> and <code>r=[[6,1,2],[3,4,5]]</code>. I need to divide q by the corresponding elements in r. (i.e. <code>[[7/6,2/1,3/2],[4/3,5/4,6/5]]</code>)</p>
<p>Output needed B = [[1.16,2,1.5],[1.33,1.25,1.2]]</p>
<p>Code:</p>
<p><code>B= [[float(j)/float(i) for j in q] for i in r]</code>. </p>
<p>However, I keep getting an error : TypeError: float() argument must be a string or a number. I have imported division from future. Any suggestions? </p>
| 1 | 2016-10-11T04:39:54Z | 39,970,627 | <p>Use <a href="https://docs.python.org/3/library/functions.html#zip"><em>zip</em></a> for bring together the sublists pairwise and then use it again to bring together the corresponding numerators and denominators:</p>
<pre><code>>>> q = [[7,2,3],[4,5,6]]
>>> r = [[6,1,2],[3,4,5]]
>>> [[n/d for n, d in zip(subq, subr)] for subq, subr in zip(q, r)]
[[1.1666666666666667, 2.0, 1.5], [1.3333333333333333, 1.25, 1.2]]
</code></pre>
| 8 | 2016-10-11T04:43:17Z | [
"python",
"algorithm",
"list",
"floating-point",
"division"
] |
How to divide list of lists by another list of lists in Python? | 39,970,595 | <p>I have <code>q = [[7,2,3],[4,5,6]]</code> and <code>r=[[6,1,2],[3,4,5]]</code>. I need to divide q by the corresponding elements in r. (i.e. <code>[[7/6,2/1,3/2],[4/3,5/4,6/5]]</code>)</p>
<p>Output needed B = [[1.16,2,1.5],[1.33,1.25,1.2]]</p>
<p>Code:</p>
<p><code>B= [[float(j)/float(i) for j in q] for i in r]</code>. </p>
<p>However, I keep getting an error : TypeError: float() argument must be a string or a number. I have imported division from future. Any suggestions? </p>
| 1 | 2016-10-11T04:39:54Z | 39,970,678 | <p>You can do:</p>
<pre><code>>>> out=[]
>>> for s1, s2 in zip(q, r):
... inner=[]
... for n, d in zip(s1, s2):
... inner.append(float(n)/d)
... out.append(inner)
...
>>> out
[[1.1666666666666667, 2.0, 1.5], [1.3333333333333333, 1.25, 1.2]]
</code></pre>
<p>Or, use numpy:</p>
<pre><code>>>> q=[[7.,2.,3.],[4.,5.,6.]]
>>> r=[[6.,1.,2.],[3.,4.,5.]]
>>> np.array(q)/np.array(r)
array([[ 1.16666667, 2. , 1.5 ],
[ 1.33333333, 1.25 , 1.2 ]])
</code></pre>
<p>Or, if you have int literals:</p>
<pre><code>>>> q=[[7,2,3],[4,5,6]]
>>> r=[[6,1,2],[3,4,5]]
>>> np.array(q, dtype=float)/np.array(r)
array([[ 1.16666667, 2. , 1.5 ],
[ 1.33333333, 1.25 , 1.2 ]])
</code></pre>
| 2 | 2016-10-11T04:51:01Z | [
"python",
"algorithm",
"list",
"floating-point",
"division"
] |
gaierror: [Errno 8] nodename nor servname provided, or not known (with macOS Sierra) | 39,970,606 | <p>socket.gethostbyname(socket.gethostname()) worked well on OS X El Capitan. However, it's not working now after the Mac updated to macOS Sierra.</p>
<p>Thanks!</p>
<pre><code>import socket
socket.gethostbyname(socket.gethostname())
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
socket.gethostbyname(socket.gethostname())
gaierror: [Errno 8] nodename nor servname provided, or not known
</code></pre>
| 0 | 2016-10-11T04:41:45Z | 40,079,851 | <p>Same problem tome.
I change the code to:</p>
<pre><code>import socket
socket.gethostbyname("")
</code></pre>
<p>And it works now.</p>
| 0 | 2016-10-17T06:33:17Z | [
"python",
"sockets"
] |
Python Get Mouse position in a cron script | 39,970,611 | <p>I am using python3 and I am able to get the mouse position using the following codes in Centos 7:</p>
<pre><code>from Xlib import display
data = display.Display().screen().root.query_pointer()._data
data["root_x"], data["root_y"]
</code></pre>
<p>However, when I run the script using crontab, it shows the following exception:
Xlib.error.DisplayNameError: Bad display name ""</p>
<p>Is there a way I can get the mouse position using python and cron job?</p>
| 0 | 2016-10-11T04:42:05Z | 39,970,961 | <p>It is because the environment variable <code>DISPLAY</code> is not set properly during execution of your python script. Try adding the following line to the beginning of your python script, for example:</p>
<pre><code>import os
os.environ['DISPLAY'] = ':0.0' # the value should match your setting
</code></pre>
| 0 | 2016-10-11T05:23:53Z | [
"python",
"cron"
] |
created CSV file from html page input in python to D3 graph with flask | 39,970,664 | <p>I have a flask application that I am building. On one page a computation is performed and a csv file is created. This page then links to another page that uses d3 and reads the csv file to display a graph. When I do this, the graph does not display. Is it possible to go from python csv to d3 graph with flask?</p>
<p>This is the pipeline I am trying to create:
Home Page --> User info page (here the user submits some information) -->run a python function that creates a csv file -->the user info page re directs to a page called page2 which takes that csv file as data for the d3 graph. </p>
| -1 | 2016-10-11T04:49:02Z | 39,972,774 | <p>The csv needed to be placed in the static folder. Not the templates folder.</p>
| 0 | 2016-10-11T07:59:53Z | [
"python",
"csv",
"d3.js",
"file-io",
"flask"
] |
Identifying closest value in a column for each filter using Pandas | 39,970,703 | <p>I have a data frame with categories and values. I need to find the value in each category closest to a value. I think I'm close but I can't really get the right output when applying the results of argsort to the original dataframe.</p>
<p>For example, if the input was defined in the code below the output should have only <code>(a, 1, True)</code>, <code>(b, 2, True)</code>, <code>(c, 2, True)</code> and all other isClosest <code>Values</code> should be False.</p>
<p>If multiple values are closest then it should be the first value listed marked.</p>
<p>Here is the code I have which works but I can't get it to reapply to the dataframe correctly. I would love some pointers.</p>
<pre><code>df = pd.DataFrame()
df['category'] = ['a', 'b', 'b', 'b', 'c', 'a', 'b', 'c', 'c', 'a']
df['values'] = [1, 2, 3, 4, 5, 4, 3, 2, 1, 0]
df['isClosest'] = False
uniqueCategories = df['category'].unique()
for c in uniqueCategories:
filteredCategories = df[df['category']==c]
sortargs = (filteredCategories['value']-2.0).abs().argsort()
#how to use sortargs so that we set column in df isClosest=True if its the closest value in each category to 2.0?
</code></pre>
| 3 | 2016-10-11T04:53:29Z | 39,970,834 | <p>You can create a column of absolute differences:</p>
<pre><code>df['dif'] = (df['values'] - 2).abs()
df
Out:
category values dif
0 a 1 1
1 b 2 0
2 b 3 1
3 b 4 2
4 c 5 3
5 a 4 2
6 b 3 1
7 c 2 0
8 c 1 1
9 a 0 2
</code></pre>
<p>And then use <code>groupby.transform</code> to check whether the minimum value of each group is equal to the difference you calculated:</p>
<pre><code>df['is_closest'] = df.groupby('category')['dif'].transform('min') == df['dif']
df
Out:
category values dif is_closest
0 a 1 1 True
1 b 2 0 True
2 b 3 1 False
3 b 4 2 False
4 c 5 3 False
5 a 4 2 False
6 b 3 1 False
7 c 2 0 True
8 c 1 1 False
9 a 0 2 False
</code></pre>
<p><code>df.groupby('category')['dif'].idxmin()</code> would also give you the indices of the closest values for each category. You can use that for mapping too. </p>
<p>For selection:</p>
<pre><code>df.loc[df.groupby('category')['dif'].idxmin()]
Out:
category values dif
0 a 1 1
1 b 2 0
7 c 2 0
</code></pre>
<p>For assignment:</p>
<pre><code>df['is_closest'] = False
df.loc[df.groupby('category')['dif'].idxmin(), 'is_closest'] = True
df
Out:
category values dif is_closest
0 a 1 1 True
1 b 2 0 True
2 b 3 1 False
3 b 4 2 False
4 c 5 3 False
5 a 4 2 False
6 b 3 1 False
7 c 2 0 True
8 c 1 1 False
9 a 0 2 False
</code></pre>
<p>The difference between these approaches is that if you check equality against the difference, you would get True for all rows in case of ties. However, with <code>idxmin</code> it will return True for the first occurrence (only one for each group). </p>
| 3 | 2016-10-11T05:08:46Z | [
"python",
"pandas",
"group-by",
"boolean",
"closest"
] |
Identifying closest value in a column for each filter using Pandas | 39,970,703 | <p>I have a data frame with categories and values. I need to find the value in each category closest to a value. I think I'm close but I can't really get the right output when applying the results of argsort to the original dataframe.</p>
<p>For example, if the input was defined in the code below the output should have only <code>(a, 1, True)</code>, <code>(b, 2, True)</code>, <code>(c, 2, True)</code> and all other isClosest <code>Values</code> should be False.</p>
<p>If multiple values are closest then it should be the first value listed marked.</p>
<p>Here is the code I have which works but I can't get it to reapply to the dataframe correctly. I would love some pointers.</p>
<pre><code>df = pd.DataFrame()
df['category'] = ['a', 'b', 'b', 'b', 'c', 'a', 'b', 'c', 'c', 'a']
df['values'] = [1, 2, 3, 4, 5, 4, 3, 2, 1, 0]
df['isClosest'] = False
uniqueCategories = df['category'].unique()
for c in uniqueCategories:
filteredCategories = df[df['category']==c]
sortargs = (filteredCategories['value']-2.0).abs().argsort()
#how to use sortargs so that we set column in df isClosest=True if its the closest value in each category to 2.0?
</code></pre>
| 3 | 2016-10-11T04:53:29Z | 39,970,921 | <p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.idxmin.html" rel="nofollow"><code>DataFrameGroupBy.idxmin</code></a> - get indexes of minimal values per group and then assign boolean mask by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.isin.html" rel="nofollow"><code>Index.isin</code></a> to column <code>isClosest</code>:</p>
<pre><code>idx = (df['values'] - 2).abs().groupby([df['category']]).idxmin()
print (idx)
category
a 0
b 1
c 7
Name: values, dtype: int64
df['isClosest'] = df.index.isin(idx)
print (df)
category values isClosest
0 a 1 True
1 b 2 True
2 b 3 False
3 b 4 False
4 c 5 False
5 a 4 False
6 b 3 False
7 c 2 True
8 c 1 False
9 a 0 False
</code></pre>
| 2 | 2016-10-11T05:19:42Z | [
"python",
"pandas",
"group-by",
"boolean",
"closest"
] |
How to get appname from model in django | 39,970,853 | <p>I have this code</p>
<pre><code>class Option(models.Model):
option_text = models.CharField(max_length=400)
option_num = models.IntegerField()
# add field to hold image or a image url in future
class Meta:
app_label = 'myapp'
</code></pre>
<p>if i have <code>Options</code> model in my view i want to get the <code>appname</code> from it</p>
| 0 | 2016-10-11T05:10:43Z | 39,970,897 | <pre><code>from django.contrib.contenttypes.models import ContentType
ct = ContentType.objects.get_for_model(option_instance)
print(ct.app_label)
</code></pre>
<p>or</p>
<pre><code>option_instance._meta.app_label
</code></pre>
| 3 | 2016-10-11T05:16:50Z | [
"python",
"django"
] |
How to get appname from model in django | 39,970,853 | <p>I have this code</p>
<pre><code>class Option(models.Model):
option_text = models.CharField(max_length=400)
option_num = models.IntegerField()
# add field to hold image or a image url in future
class Meta:
app_label = 'myapp'
</code></pre>
<p>if i have <code>Options</code> model in my view i want to get the <code>appname</code> from it</p>
| 0 | 2016-10-11T05:10:43Z | 39,971,408 | <p>If you have an instance of your object, you can quite easily get the app_label from _meta</p>
<pre><code>o = Option.objects.all()[0]
print o._meta.app_label
</code></pre>
<p>There is a host of other usefull information in there. In the shell type help(a._meta) to see them all</p>
| 2 | 2016-10-11T06:16:00Z | [
"python",
"django"
] |
Filtering a list. Get elements of list only with a certain distance between items? | 39,970,857 | <p>I need to get only those elements that are to some extent distant from each other. For example, I have a list of integers:</p>
<pre><code>data = [-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000]
</code></pre>
<p>Let's assume I want to retrieve only those elements that have have a distance of at least <strong>1000</strong> between each other.
From the list above I need output:</p>
<pre><code>[-2000, 1000, 2000, 3500, 4500, 6000]
</code></pre>
<hr>
<p>For the moment I'm filtering this way:</p>
<pre><code>filtered.append(data[0])
for index, obj in enumerate(data):
if index < (l - 1):
if abs(obj - data[index+1]) > 999:
filtered.append(data[index+1])
print(filtered)
</code></pre>
<p>Undesired output:</p>
<pre><code>[-2000, 1000, 2000, 3500, 6000]
</code></pre>
<hr>
<p>It fails because it compares two adjacent list elements, irregardless of the fact that some elements supposed to be filtered out and should not be taken into account when comparing. </p>
<p>Let me show more clearly.<br>
Original list: <code>[-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000]</code></p>
<p>Filtering process: </p>
<pre><code>-2000 - OK
1000 - OK
2000 - OK
3500 - OK
3800 - Out
4500 - Should be OK, but it filtered out compared to 3800. But it should be compared to 3500 (not 3800 which is Out).
</code></pre>
<hr>
<p>How to fix it?</p>
| 3 | 2016-10-11T05:11:15Z | 39,970,930 | <p>Sorting the data and then comparing to the previous would do it:</p>
<pre><code>data = [-2000, 1000, 2000, 3500, 3800, 4500, 4600, 5000, 6000]
lst = [min(data)] # the min of data goes in solution list
for i in sorted(data[1:]):
if i-lst[-1] > 999: # comparing with last element
lst.append(i) # of the solution list
print (lst)
</code></pre>
<p>ouput:</p>
<pre><code>[-2000, 1000, 2000, 3500, 4500, 6000]
</code></pre>
| 6 | 2016-10-11T05:20:10Z | [
"python",
"list",
"python-3.x",
"distance"
] |
Pygame, move a square on the screen, but can not erase the previous movements | 39,970,906 | <p>This is my first post in StackOverflow, hope you guys can help a newbie programmer. It's Pygame Python simple ask.</p>
<p>I am trying to move a square on the screen, but can not erase the previous movements.</p>
<pre><code>import pygame
pygame.init()
screen = pygame.display.set_mode((400,300))
pygame.display.set_caption("shield hacking")
JogoAtivo = True
GAME_BEGIN = False
# Speed in pixels per frame
x_speed = 0
y_speed = 0
cordX = 10
cordY = 100
def desenha():
quadrado = pygame.Rect(cordX, cordY ,50, 52)
pygame.draw.rect(screen, (255, 0, 0), quadrado)
pygame.display.flip()
while JogoAtivo:
for evento in pygame.event.get():
print(evento);
#verifica se o evento que veio eh para fechar a janela
if evento.type == pygame.QUIT:
JogoAtivo = False
pygame.quit();
if evento.type == pygame.KEYDOWN:
if evento.key == pygame.K_SPACE:
print('GAME BEGIN')
desenha()
GAME_BEGIN = True;
if evento.key == pygame.K_LEFT and GAME_BEGIN:
speedX=-3
cordX+=speedX
desenha()
if evento.key == pygame.K_RIGHT and GAME_BEGIN:
speedX=3
cordX+=speedX
desenha()
</code></pre>
| 0 | 2016-10-11T05:17:35Z | 39,970,939 | <p>You have to draw over the previous image. Easiest is to fill the screen with a background color in the beginning of the game loop, like so:</p>
<pre><code>screen.fill((0, 0, 0))
</code></pre>
| 4 | 2016-10-11T05:21:29Z | [
"python",
"pygame",
"move",
"rect"
] |
Pygame, move a square on the screen, but can not erase the previous movements | 39,970,906 | <p>This is my first post in StackOverflow, hope you guys can help a newbie programmer. It's Pygame Python simple ask.</p>
<p>I am trying to move a square on the screen, but can not erase the previous movements.</p>
<pre><code>import pygame
pygame.init()
screen = pygame.display.set_mode((400,300))
pygame.display.set_caption("shield hacking")
JogoAtivo = True
GAME_BEGIN = False
# Speed in pixels per frame
x_speed = 0
y_speed = 0
cordX = 10
cordY = 100
def desenha():
quadrado = pygame.Rect(cordX, cordY ,50, 52)
pygame.draw.rect(screen, (255, 0, 0), quadrado)
pygame.display.flip()
while JogoAtivo:
for evento in pygame.event.get():
print(evento);
#verifica se o evento que veio eh para fechar a janela
if evento.type == pygame.QUIT:
JogoAtivo = False
pygame.quit();
if evento.type == pygame.KEYDOWN:
if evento.key == pygame.K_SPACE:
print('GAME BEGIN')
desenha()
GAME_BEGIN = True;
if evento.key == pygame.K_LEFT and GAME_BEGIN:
speedX=-3
cordX+=speedX
desenha()
if evento.key == pygame.K_RIGHT and GAME_BEGIN:
speedX=3
cordX+=speedX
desenha()
</code></pre>
| 0 | 2016-10-11T05:17:35Z | 39,977,174 | <p>You also can draw everything from a previous surface, before the square was in place, then draw the square on it always in a different place.
Then draw the new surface to screen each time.</p>
<p>But not really good strategy, it can be slow and/or induce flickering.</p>
<p>For instance:</p>
<pre><code># Draw anything to the display surface named screen, then do:
# By display surface I mean the surface returned by pygame.display.set_mode()
orig = screen.copy()
# Sometimes it will not be filled with a image from screen that you have drawn before, so you draw
# all to orig surface
# Then you make a surface that will be shown on the screen and do:
s = pygame.surface.Surface()
s.blit(orig, 0, 0)
# Then you draw the rectangle or whatever on s, and then:
screen.blit(s, 0, 0)
pygame.display.flip()
# and you keep orig as a starting point for every move
</code></pre>
<p>If you have many movable objects on the screen simultaneously this is good, or if you are refreshing restricted areas only, else redraw over the last image as suggested in other answer.</p>
<p>If you go about drawing directly to the display surface flicker will be bigger and sometimes, especially when display is hardware accelerated you will have problems. On non desktop devices like mobile phones especially. Drawing over and adding new usually works fine directly on display surface and would be the correct approach to your problem.</p>
<p>I know I sound contradictive, but some stuff you simply must see for yourself. Get experience by experimenting.</p>
| 0 | 2016-10-11T12:23:32Z | [
"python",
"pygame",
"move",
"rect"
] |
Pygame, move a square on the screen, but can not erase the previous movements | 39,970,906 | <p>This is my first post in StackOverflow, hope you guys can help a newbie programmer. It's Pygame Python simple ask.</p>
<p>I am trying to move a square on the screen, but can not erase the previous movements.</p>
<pre><code>import pygame
pygame.init()
screen = pygame.display.set_mode((400,300))
pygame.display.set_caption("shield hacking")
JogoAtivo = True
GAME_BEGIN = False
# Speed in pixels per frame
x_speed = 0
y_speed = 0
cordX = 10
cordY = 100
def desenha():
quadrado = pygame.Rect(cordX, cordY ,50, 52)
pygame.draw.rect(screen, (255, 0, 0), quadrado)
pygame.display.flip()
while JogoAtivo:
for evento in pygame.event.get():
print(evento);
#verifica se o evento que veio eh para fechar a janela
if evento.type == pygame.QUIT:
JogoAtivo = False
pygame.quit();
if evento.type == pygame.KEYDOWN:
if evento.key == pygame.K_SPACE:
print('GAME BEGIN')
desenha()
GAME_BEGIN = True;
if evento.key == pygame.K_LEFT and GAME_BEGIN:
speedX=-3
cordX+=speedX
desenha()
if evento.key == pygame.K_RIGHT and GAME_BEGIN:
speedX=3
cordX+=speedX
desenha()
</code></pre>
| 0 | 2016-10-11T05:17:35Z | 40,012,752 | <p>I am also a newbie and I am doing something similar and I hope this helps </p>
<pre><code>import pygame
clock=pygame.time.Clock() #the frames per second BIF in pygame
pygame.init()
FPS=30
display_width=800
display_height=600
white=(255,255,255)
black=(0,0,0)
block_size=10
gameExit=False
lead_x = display_width / 2
lead_y = display_height / 2
lead_x_change = 0 # 0 beacuse we will not be changing the position in the beginning
lead_y_change = 0
gameDisplay=pygame.display.set_mode((display_width,display_height))
while not gameExit: #game loop
for event in pygame.event.get(): #event handling BIF in pygame EVENT LOOP
#print(event) # prints out the position of the mouse and the buttons pressed when in game window
if event.type== pygame.QUIT: #if the user presses the [x] in game window, it quits the window
gameExit=True
if event.key == pygame.K_LEFT:
lead_x_change = -block_size #block size is number of pixels moved in one loop
lead_y_change=0
elif event.key==pygame.K_RIGHT:
lead_x_change= block_size
lead_y_change=0
elif event.key==pygame.K_UP:
lead_y_change= -block_size
lead_x_change=0
elif event.key==pygame.K_DOWN:
lead_y_change= block_size
lead_x_change=0
lead_y+=lead_y_change
lead_x+=lead_x_change
gameDisplay.fill(white) #fills the display surface object, backgroud color is the parameter filled in
pygame.draw.rect(gameDisplay,black,[lead_x,lead_y,block_size,block_size])
pygame.display.update() #after done with all the action,update the surface
clock.tick(FPS) #runs the game at 30FPS
pygame.quit()
quit()
</code></pre>
| 0 | 2016-10-13T05:11:31Z | [
"python",
"pygame",
"move",
"rect"
] |
Where in my code are duplicates being deleted? | 39,970,958 | <p>An important part of my output is being able to identify the length of the <code>finalList</code> but somewhere in my code, duplicates are being deleted and I can't figure out where</p>
<pre><code>from itertools import chain, permutations
allPos = []
first_list = ['a','b','c']
match_list = [['a','b','c'], ['a','b','c']]
for i in range(1,30):
for phrase in permutations(first_list, i):
for ind, letter in enumerate(chain.from_iterable(phrase)):
if ind >= len(match_list) or letter not in match_list[ind]:
break
else:
allPos.append(phrase)
finalList = []
for i in allPos:
if len(i) == len(allPos[-1]):
finalList.append(i)
print(finalList)
</code></pre>
<p>OUTPUT</p>
<pre><code>[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
</code></pre>
<p>I know that it is deleting duplicates, or perhaps my code is just missing something completely because I am missing <code>[('a','a'), ('b','b'), ('c','c')]</code> from my output</p>
| 0 | 2016-10-11T05:23:36Z | 39,971,399 | <p>You can try with this. Change <code>iterable</code> using permutations.</p>
<pre><code>from itertools import chain, permutations
...
...
for i in range(1,30):
# change iterable
for phrase in permutations([j for ele in match_list for j in ele], i):
...
for i in set(allPos):
if len(i) == len(allPos[-1]):
finalList.append(i)
print (sorted(finalList))
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
</code></pre>
| 0 | 2016-10-11T06:14:58Z | [
"python",
"permutation"
] |
Make an object that behaves like a slice | 39,971,030 | <p>How can we make a class represent itself as a slice when appropriate?</p>
<p>This didn't work:</p>
<pre><code>class MyThing(object):
def __init__(self, start, stop, otherstuff):
self.start = start
self.stop = stop
self.otherstuff = otherstuff
def __index__(self):
return slice(self.start, self.stop)
</code></pre>
<p>Expected output:</p>
<pre><code>>>> thing = MyThing(1, 3, 'potato')
>>> 'hello world'[thing]
'el'
</code></pre>
<p>Actual output:</p>
<pre><code>TypeError: __index__ returned non-(int,long) (type slice)
</code></pre>
<p>Inheriting from <code>slice</code> doesn't work either. </p>
| 6 | 2016-10-11T05:33:03Z | 39,971,122 | <p>A slice can't be in your return type as the method just doesn't support this. You can read more about the <code>__index__</code> <a href="https://www.python.org/dev/peps/pep-0357/" rel="nofollow">special method here</a>.
I could only come up with a workaround that directly calls the function in your class:</p>
<pre><code>class MyThing(object):
def __init__(self, start, stop, otherstuff):
self.start = start
self.stop = stop
self.otherstuff = otherstuff
def __index__(self):
return slice(self.start, self.stop)
thing = MyThing(1, 3, 'potato')
print 'Hello World'[thing.__index__()]
</code></pre>
<p>This will return <code>el</code>.</p>
| -2 | 2016-10-11T05:45:34Z | [
"python",
"slice"
] |
Make an object that behaves like a slice | 39,971,030 | <p>How can we make a class represent itself as a slice when appropriate?</p>
<p>This didn't work:</p>
<pre><code>class MyThing(object):
def __init__(self, start, stop, otherstuff):
self.start = start
self.stop = stop
self.otherstuff = otherstuff
def __index__(self):
return slice(self.start, self.stop)
</code></pre>
<p>Expected output:</p>
<pre><code>>>> thing = MyThing(1, 3, 'potato')
>>> 'hello world'[thing]
'el'
</code></pre>
<p>Actual output:</p>
<pre><code>TypeError: __index__ returned non-(int,long) (type slice)
</code></pre>
<p>Inheriting from <code>slice</code> doesn't work either. </p>
| 6 | 2016-10-11T05:33:03Z | 39,971,377 | <p>TLDR: It's impossible to make custom classes replace <code>slice</code> for builtins types such as <code>list</code> and <code>tuple</code>.</p>
<hr>
<p>The <code>__index__</code> method exists purely to provide an <em>index</em>, which is by definition an integer in python (see <a href="https://docs.python.org/3.5/reference/datamodel.html#object.__index__" rel="nofollow">the Data Model</a>). You cannot use it for resolving an object to a <code>slice</code>.</p>
<p>I'm afraid that <code>slice</code> seems to be handled specially by python. The interface requires an actual slice; providing its signature (which also includes the <code>indices</code> method) is not sufficient. As you've found out, you cannot inherit from it, so you cannot create new types of <code>slice</code>s. Even Cython will not allow you to inherit from it.</p>
<hr>
<p>So why is <code>slice</code> special? Glad you asked. Welcome to the innards of CPython. Please wash your hands after reading this.</p>
<p>So slice objects are described in <a href="https://raw.githubusercontent.com/python/cpython/c30098c8c6014f3340a369a31df9c74bdbacc269/Doc/c-api/slice.rst" rel="nofollow"><code>slice.rst</code></a>. Note these two guys:</p>
<blockquote>
<p>.. c:var:: PyTypeObject PySlice_Type</p>
<p>The type object for slice objects. This is the same as :class:<code>slice</code> in the
Python layer.</p>
<p>.. c:function:: int PySlice_Check(PyObject *ob)
Return true if <em>ob</em> is a slice object; <em>ob</em> must not be <em>NULL</em>.</p>
</blockquote>
<p>Now, this is actually implemented in <a href="https://github.com/python/cpython/blob/c30098c8c6014f3340a369a31df9c74bdbacc269/Include/sliceobject.h" rel="nofollow"><code>sliceobject.h</code></a> as :</p>
<pre><code>#define PySlice_Check(op) (Py_TYPE(op) == &PySlice_Type)
</code></pre>
<p>So <em>only</em> the <code>slice</code> type is allowed here. This check is actually used in <a href="https://github.com/python/cpython/blob/c30098c8c6014f3340a369a31df9c74bdbacc269/Objects/listobject.c#L2406" rel="nofollow"><code>list_subscript</code></a> (and <code>tuple subscript</code>, ...) <em>after</em> attempting to use the index protocol (so having <code>__index__</code> on a slice is a bad idea). A custom container class is free to overwrite <code>__getitem__</code> and use its own rules, but that's how <code>list</code> (and <code>tuple</code>, ...) does it.</p>
<p>Now, why is it not possible to subclass <code>slice</code>? Well, <code>type</code> actually has a flag indicating whether something can be subclassed. It is checked <a href="https://github.com/python/cpython/blob/222b935769b07b8e68ec5b0494c39518d90112d1/Objects/typeobject.c#L1971" rel="nofollow">here</a> and generates the error you have seen:</p>
<pre><code> if (!PyType_HasFeature(base_i, Py_TPFLAGS_BASETYPE)) {
PyErr_Format(PyExc_TypeError,
"type '%.100s' is not an acceptable base type",
base_i->tp_name);
return NULL;
}
</code></pre>
<p>I haven't been able to track down how <code>slice</code> (un)sets this value, but the fact that one gets this error means it does. This means you cannot subclass it.</p>
<hr>
<p>Closing remarks: After remembering some long-forgotten C-(non)-skills, I'm fairly sure this is not about optimization in the strict sense. All existing checks and tricks would still work (at least those I've found).</p>
<p>After washing my hands and digging around in the internet, I've found a few references to similar "issues". <a href="http://grokbase.com/t/python/python-list/033r5nks47/type-function-does-not-subtype#20030324rcnwbkfedhzbaf3vmiuer3z4xq" rel="nofollow">Tim Peters has said all there is to say:</a></p>
<blockquote>
<p>Nothing implemented in C is subclassable unless somebody volunteers the work
to make it subclassable; nobody volunteered the work to make the <em>[insert name here]</em>
type subclassable. It sure wasn't at the top of my list <em>wink</em>.</p>
</blockquote>
<p>Also see <a href="http://stackoverflow.com/a/10114382/5349916">this thread</a> for a short discussion on non-subclass'able types.</p>
<p>Practically all alternative interpreters replicate the behavior to various degrees: <a href="https://github.com/nakagami/jython3/blob/master/src/org/python/core/PyType.java#L65" rel="nofollow">Jython</a>, <a href="https://github.com/dropbox/pyston/issues/596" rel="nofollow">Pyston</a>, <a href="https://github.com/IronLanguages/main/blob/eedca3ee3c8260ef205a53c5ee11340b092a250a/Languages/IronPython/IronPython/Runtime/Types/NewTypeInfo.cs#L72" rel="nofollow">IronPython</a> and PyPy (didn't find out how they do it, but they do).</p>
| 5 | 2016-10-11T06:13:02Z | [
"python",
"slice"
] |
Make an object that behaves like a slice | 39,971,030 | <p>How can we make a class represent itself as a slice when appropriate?</p>
<p>This didn't work:</p>
<pre><code>class MyThing(object):
def __init__(self, start, stop, otherstuff):
self.start = start
self.stop = stop
self.otherstuff = otherstuff
def __index__(self):
return slice(self.start, self.stop)
</code></pre>
<p>Expected output:</p>
<pre><code>>>> thing = MyThing(1, 3, 'potato')
>>> 'hello world'[thing]
'el'
</code></pre>
<p>Actual output:</p>
<pre><code>TypeError: __index__ returned non-(int,long) (type slice)
</code></pre>
<p>Inheriting from <code>slice</code> doesn't work either. </p>
| 6 | 2016-10-11T05:33:03Z | 39,987,094 | <blockquote>
<blockquote>
<h1>I'M SORRY FOR THE DARK MAGIC</h1>
</blockquote>
</blockquote>
<p>Using <a href="http://clarete.li/forbiddenfruit/" rel="nofollow">Forbiddenfruit</a> and python python's builtin <code>new</code> method I was able to do this:</p>
<pre><code>from forbiddenfruit import curse
class MyThing(int):
def __new__(cls, *args, **kwargs):
magic_slice = slice(args[0], args[1])
curse(slice, 'otherstuff', args[2])
return magic_slice
thing = MyThing(1, 3, 'thing')
print 'hello world'[thing]
print thing.otherstuff
</code></pre>
<p>output:</p>
<pre><code>>>> el
>>> thing
</code></pre>
<p><em><strong>I wrote it as a challenge just because everybody said it is impossible, I would never use it on production code IT HAS SO MANY SIDE EFFECTS, you should think again on your structure and needs</strong></em></p>
| 3 | 2016-10-11T21:31:27Z | [
"python",
"slice"
] |
Python Type Error: 'List' object is not callable | 39,971,037 | <p>I'm getting this error with this small code content of Python27. Can anyone help me with this? Thanks in advance.</p>
<blockquote>
<p>Run Time Error Traceback (most recent call last): File
"5eb4481881d51d6ece1c375c80f5e509.py", line 57, in
print len(arr) TypeError: 'list' object is not callable</p>
</blockquote>
<pre><code>global maximum
def _lis(arr , n ):
# to allow the access of global variable
global maximum
# Base Case
if n == 1 :
return 1
# maxEndingHere is the length of LIS ending with arr[n-1]
maxEndingHere = 1
"""Recursively get all LIS ending with arr[0], arr[1]..arr[n-2]
IF arr[n-1] is maller than arr[n-1], and max ending with
arr[n-1] needs to be updated, then update it"""
for i in xrange(1, n):
res = _lis(arr , i)
if arr[i-1] < arr[n-1] and res+1 > maxEndingHere:
maxEndingHere = res +1
# Compare maxEndingHere with overall maximum. And
# update the overall maximum if needed
maximum = max(maximum , maxEndingHere)
return maxEndingHere
def lis(arr):
# to allow the access of global variable
global maximum
# lenght of arr
n = len(arr)
# maximum variable holds the result
maximum = 1
# The function _lis() stores its result in maximum
_lis(arr , n)
return maximum
num_t = input()
len = [None]*num_t
arr = []
for i in range(0,num_t):
len[i] = input()
arr.append(map(int, raw_input().split()))
print len(arr)
break
</code></pre>
| 0 | 2016-10-11T05:33:49Z | 39,971,064 | <p>That is what happens when you define a variable that is also a built-in function name.<br>
Change the variable <code>len</code> to something else.</p>
| 1 | 2016-10-11T05:37:23Z | [
"python",
"list"
] |
Python Type Error: 'List' object is not callable | 39,971,037 | <p>I'm getting this error with this small code content of Python27. Can anyone help me with this? Thanks in advance.</p>
<blockquote>
<p>Run Time Error Traceback (most recent call last): File
"5eb4481881d51d6ece1c375c80f5e509.py", line 57, in
print len(arr) TypeError: 'list' object is not callable</p>
</blockquote>
<pre><code>global maximum
def _lis(arr , n ):
# to allow the access of global variable
global maximum
# Base Case
if n == 1 :
return 1
# maxEndingHere is the length of LIS ending with arr[n-1]
maxEndingHere = 1
"""Recursively get all LIS ending with arr[0], arr[1]..arr[n-2]
IF arr[n-1] is maller than arr[n-1], and max ending with
arr[n-1] needs to be updated, then update it"""
for i in xrange(1, n):
res = _lis(arr , i)
if arr[i-1] < arr[n-1] and res+1 > maxEndingHere:
maxEndingHere = res +1
# Compare maxEndingHere with overall maximum. And
# update the overall maximum if needed
maximum = max(maximum , maxEndingHere)
return maxEndingHere
def lis(arr):
# to allow the access of global variable
global maximum
# lenght of arr
n = len(arr)
# maximum variable holds the result
maximum = 1
# The function _lis() stores its result in maximum
_lis(arr , n)
return maximum
num_t = input()
len = [None]*num_t
arr = []
for i in range(0,num_t):
len[i] = input()
arr.append(map(int, raw_input().split()))
print len(arr)
break
</code></pre>
| 0 | 2016-10-11T05:33:49Z | 39,971,067 | <p>You have created a list named <code>len</code> as you can see here from the fact that you're able to index it:</p>
<pre><code>len[i] = input()
</code></pre>
<p>So naturally, <code>len</code> is no longer a function that gets the length of a list, leading to the error you receive.</p>
<p>Solution: name your <code>len</code> list something else.</p>
| 5 | 2016-10-11T05:37:38Z | [
"python",
"list"
] |
Python Django not running | 39,971,084 | <p>Firstly I installed Django using pip in my "CentOS" operating system.
After that I performed these steps using terminal.</p>
<pre><code>django-admin startproject mysite
</code></pre>
<p>a folder mysite is created with :</p>
<pre><code>manage.py and another subfolder mysite
</code></pre>
<p>Then simply I just used these commands :</p>
<pre><code>python manage.py runserver
</code></pre>
<p>and the server was running as clicked on the url :
<a href="http://localhost:portnumber/" rel="nofollow">http://localhost:portnumber/</a></p>
<p>But after that when I made another app to run it is not running, my step are as follows :</p>
<pre><code>python manage.py startapp webapp
</code></pre>
<p>Then one new folder created webapp in same mysite directory is created.</p>
<p>After changing settings.py and urls.py of mysite and also changing urls.py and views.py of webapp.</p>
<p>when I run :</p>
<pre><code>python manage.py runserver
</code></pre>
<p>error is coming</p>
<pre><code> Performing system checks...
Unhandled exception in thread started by <function wrapper at 0x24a7398>
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/django/utils/autoreload.py", line
226, in wrapper
fn(*args, **kwargs)
File "/usr/lib/python2.7/site-
packages/django/core/management/commands/runserver.py", line 121, in
inner_run
self.check(display_num_errors=True)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py",
line 374, in check
include_deployment_checks=include_deployment_checks,
File "/usr/lib/python2.7/site-packages/django/core/management/base.py",
line 361, in _run_checks
return checks.run_checks(**kwargs)
File "/usr/lib/python2.7/site-packages/django/core/checks/registry.py",
line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/usr/lib/python2.7/site-packages/django/core/checks/urls.py", line
14, in check_url_config
return check_resolver(resolver)
File "/usr/lib/python2.7/site-packages/django/core/checks/urls.py", line
28, in check_resolver
warnings.extend(check_resolver(pattern))
File "/usr/lib/python2.7/site-packages/django/core/checks/urls.py", line
24, in check_resolver
for pattern in resolver.url_patterns:
File "/usr/lib/python2.7/site-packages/django/utils/functional.py", line
35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/lib/python2.7/site-packages/django/urls/resolvers.py", line
322, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf
'<module 'webapp.urls' from
'/home/username/Desktop/prog/django/mysite/webapp/urls.pyc'>' does not
appear to have any patterns in it. If you see valid patterns in the file
then the issue is probably caused by a circular import.
</code></pre>
| -1 | 2016-10-11T05:40:28Z | 39,973,895 | <p>This right here:</p>
<pre><code>'/home/username/Desktop/prog/django/mysite/webapp/urls.pyc'>' does not appear to have any patterns in it.
</code></pre>
<p>Check <code>urls.py</code></p>
<p>I can't tell you exactly what to check without seeing the file, but here is a sample <code>urls.py</code>:</p>
<pre><code>urlpatterns = patterns('',
# Examples:
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^webapp/', include('webapp.urls')),
)
</code></pre>
<p>codes are as follows :
urls.py [/mysite/mysite/urls.py]</p>
<pre><code> from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [url(r'^admin/', admin.site.urls),
url(r'^webapp/', include('webapp.urls'))
]
</code></pre>
<p>settings.py[/mysite/mysite/settings.py]</p>
<pre><code> INSTALLED_APPS = [
'webapp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
</code></pre>
<p>urls.py [/mysite/webapp/urls.py]</p>
<pre><code> from django.conf.urls import url
from. import views
urlpatterns = [
url(r'^$', views.index, name='index')
]
</code></pre>
<p>views.py [/mysite/webapp/views.py]</p>
<pre><code> from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("<h2>Hey!</h2>")
</code></pre>
| 0 | 2016-10-11T09:08:43Z | [
"python",
"django"
] |
How to enable "View State" option for ExecuteScript processor in NiFi UI? | 39,971,249 | <p>I am using NiFi <strong>ExecuteScript</strong> with python. In the python script I add/modify state of the processor</p>
<pre><code>stateManager = context.getStateManager()
stateManager.setState(newmap, Scope.LOCAL)
</code></pre>
<p>Is there anyway I can view/clear the processor state in NiFi web ui? </p>
<p>Some other processors like <strong>TailFile</strong> give you this option via <em>"view state"</em> when you right click on the processor but ExecuteScript right click does not give you this option</p>
| 0 | 2016-10-11T06:01:59Z | 39,977,840 | <p>Most processors that store state have an annotation on them @Stateful which indicates to the framework that they store state, and is used to enabled features such as the "View State". </p>
<p>Since ExecuteScript doesn't store state itself it doesn't currently have this annotation, but since scripts can access the state manager and store state we should add the annotation so that View State works. I created this JIRA:</p>
<p><a href="https://issues.apache.org/jira/browse/NIFI-2885" rel="nofollow">https://issues.apache.org/jira/browse/NIFI-2885</a></p>
| 2 | 2016-10-11T13:00:13Z | [
"python",
"state",
"apache-nifi"
] |
Prompt for Name without any Variables | 39,971,304 | <p>How would go about writing this program without any variables? It's super simple exercise from the book "57 Programming Exercises" but other than using importing sys and using the command line argv I don't see how to go about it. I think the intent is for it not to use sys.argv. Thank you.</p>
<pre><code>inp = raw_input("What is your name? ")
print "Hello,",inp,"nice to meet you!"
</code></pre>
| 0 | 2016-10-11T06:07:27Z | 39,971,333 | <p>This will do the trick:</p>
<pre><code> print "Hello, {} nice to meet you!".format(raw_input("What is your name? "))
</code></pre>
<p><a href="https://docs.python.org/2/library/string.html#format-string-syntax" rel="nofollow">format</a> is just a way of inserting arguments in a string, similar to</p>
<pre><code>print "Hello, " + raw_input("what is your name? ") + " nice to meet you"
</code></pre>
| 5 | 2016-10-11T06:10:01Z | [
"python"
] |
selenium fails to iterate on elements | 39,971,323 | <p>Im trying to translate user comments from tripadvisor.<br>
My code :- </p>
<p>1.]Selects only portuguese comments( from language dropdown), </p>
<p>2.]Then expands each of the comments, </p>
<p>3.]Then saves all these expanded comments in a list</p>
<p>4.]Then translates them into english & prints on screen</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
com_=[] # To save translated comments
expanded_comments=[] # To save expanded comments
driver = webdriver.Chrome("C:\Users\shalini\Downloads\chromedriver_win32\chromedriver.exe")
driver.maximize_window()
def expand_reviews(driver):
# TRYING TO EXPAND REVIEWS (& CLOSE A POPUP)
try:
driver.find_element_by_class_name("moreLink").click()
except:
print "err"
try:
driver.find_element_by_class_name("ui_close_x").click()
except:
print "err"
try:
driver.find_element_by_class_name("moreLink").click()
except:
print "err3"
def save_comments(driver):
expand_reviews(driver)
# SELECTING ALL EXPANDED COMMENTS
expanded_com_elements=driver.find_elements_by_class_name("entry")
time.sleep(3)
for i in expanded_com_elements:
expanded_comments.append(i.text)
# SELECTING ALL GOOGLE-TRANSLATOR links
gt= driver.find_elements(By.CSS_SELECTOR,".googleTranslation>.link")
# NOW PRINTING TRANSLATED COMMENTS
for i in gt:
try:
driver.execute_script("arguments[0].click()",i)
#i.click().perform()
com=driver.find_element_by_class_name("ui_overlay").text
com_.append(com)
time.sleep(5)
driver.find_element_by_class_name("ui_close_x").click().perform()
time.sleep(5)
except Exception as e:
pass
#print e
for i in range(282):
page=i*10
url="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-or"+str(page)+"-TAP-Portugal#REVIEWS"
driver.get(url)
wait = WebDriverWait(driver, 10)
if i==0:
# SELECTING PORTUGUESE COMMENTS ONLY # Run for one time then iterate over pages
try:
langselction = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.sprite-date_picker-triangle")))
langselction.click()
driver.find_element_by_xpath("//div[@class='languageList']//li[normalize-space(.)='Portuguese first']").click()
time.sleep(5)
except Exception as e:
print e
save_comments(driver)
</code></pre>
<p>================ERROR=================</p>
<p>expanded_comments return empty list. Some comments get saved, some get skipped.
First page is saved properly (all comments expanded), but thereafter only first comment gets saved, without being expanded. But translated comments from all pages get saved properly in com_</p>
| 1 | 2016-10-11T06:08:56Z | 39,974,090 | <p>I have changed your code and now it's working.</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome("./chromedriver.exe")
driver.maximize_window()
url="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-TAP-Portugal#REVIEWS"
driver.get(url)
wait = WebDriverWait(driver, 10)
# SELECTING PORTUGUESE COMMENTS ONLY
#show_lan = driver.find_element_by_xpath("//div[@class='languageList']/ul/li[contains(text(),'Portuguese first')]")
try:
langselction = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.sprite-date_picker-triangle")))
langselction.click()
driver.find_element_by_xpath("//div[@class='languageList']//li[normalize-space(.)='Portuguese first']").click()
time.sleep(5)
except Exception as e:
print e
# TRYING TO EXPAND REVIEWS (& CLOSE A POPUP)
try:
driver.find_element_by_class_name("moreLink").click()
except:
print "err"
try:
driver.find_element_by_class_name("ui_close_x").click()
except:
print "err"
try:
driver.find_element_by_class_name("moreLink").click()
except:
print "err3"
# SELECTING ALL EXPANDED COMMENTS
expanded_com_elements=driver.find_elements_by_class_name("entry")
expanded_comments=[]
time.sleep(3)
for i in expanded_com_elements:
expanded_comments.append(i.text)
# SELECTING ALL GOOGLE-TRANSLATOR links
gt= driver.find_elements(By.CSS_SELECTOR,".googleTranslation>.link")
# NOW PRINTING TRANSLATED COMMENTS
for i in gt:
try:
driver.execute_script("arguments[0].click()",i)
#i.click().perform()
print driver.find_element_by_class_name("ui_overlay").text
time.sleep(5)
driver.find_element_by_class_name("ui_close_x").click().perform()
time.sleep(5)
except Exception as e:
pass
#print e
</code></pre>
| 1 | 2016-10-11T09:20:38Z | [
"python",
"selenium",
"web-scraping"
] |
How do I implement the Triplet Loss in Keras? | 39,971,597 | <p>I'm trying to implement Google's Facenet paper:</p>
<p><img src="http://i.stack.imgur.com/RT3TZ.png" alt="enter image description here"></p>
<p>First of all, is it possible to implement this paper using the Sequential API of Keras or should I go for the Graph API? </p>
<p>In either case, could you please tell me how do I pass the custom loss function <code>tripletLoss</code> to the model compile and how do I receive the <code>anchor embedding</code>, <code>positive embedding</code> and the <code>negative embedding</code> as parameters to calculate the loss? </p>
<p>Also, what should be the second parameter Y in model.fit(), I do not have any in this case...</p>
| 1 | 2016-10-11T06:33:36Z | 40,004,986 | <p><a href="https://github.com/fchollet/keras/issues/369" rel="nofollow">This issue</a> explains how to create a custom objective (loss) in Keras:</p>
<pre><code>def dummy_objective(y_true, y_pred):
return 0.5 # your implem of tripletLoss here
model.compile(loss=dummy_objective, optimizer='adadelta')
</code></pre>
<p>Regarding the <code>y</code> parameter of <code>.fit()</code>, since you are the one handling it in the end (the <code>y_true</code> parameter of the objective function is taken from it), I would say you can pass whatever you need that can fit through Keras plumbing. And maybe a dummy vector to pass dimension checks if your really don't need any supervision.</p>
<p>Eventually, as to how to implement this particular paper, looking for <code>triplet</code> or <code>facenet</code> in <a href="https://keras.io/" rel="nofollow">Keras doc</a> didn't return anything. So you'll probably have to either implement it yourself or find someone who has.</p>
| 1 | 2016-10-12T17:39:06Z | [
"python",
"keras"
] |
Lambda function Python3 no change in output | 39,971,604 | <pre><code>def salary_sort(thing):
def importantparts(thing):
for i in range(1, len(thing)):
a=thing[i].split(':')
output = (a[1],a[0],a[8])
sortedlist = sorted(output, key = lambda item: item[2], reverse=True)
print(sortedlist)
return importantparts(thing)
salary_sort(employee_data)
</code></pre>
<p>This function is supposed to sort out a list of names by their salary.
I managed to isolate the first last names and salaries but I can't seem to get it to sort by their salaries </p>
<p>'Thing' aka employee_data</p>
<pre><code>employee_data = ["FName LName Tel Address City State Zip Birthdate Salary",
"Arthur:Putie:923-835-8745:23 Wimp Lane:Kensington:DL:38758:8/31/1969:126000",
"Barbara:Kertz:385-573-8326:832 Ponce Drive:Gary:IN:83756:12/1/1946:268500",
"Betty:Boop:245-836-8357:635 Cutesy Lane:Hollywood:CA:91464:6/23/1923:14500",.... etc.]
</code></pre>
<p>Output</p>
<pre><code>['Putie', 'Arthur', '126000']
['Kertz', 'Barbara', '268500']
['Betty', 'Boop', '14500']
['Hardy', 'Ephram', '56700']
['Fardbarkle', 'Fred', '780900']
['Igor', 'Chevsky', '23400']
['James', 'Ikeda', '45000']
['Cowan', 'Jennifer', '58900']
['Jesse', 'Neal', '500']
['Jon', 'DeLoach', '85100']
['Jose', 'Santiago', '95600']
['Karen', 'Evich', '58200']
['Lesley', 'Kirstin', '52600']
['Gortz', 'Lori', '35200']
['Corder', 'Norma', '245700']
</code></pre>
| 0 | 2016-10-11T06:34:37Z | 39,972,159 | <p>The problem is that you sort <strong>individual</strong> elements (meaning <code>['Putie', 'Arthur', '126000']</code>), based on the salary value, and not the whole array.</p>
<p>Also, since you want to sort the salaries, you have to cast them to <code>int</code>, otherwise alphabetical sort is going to be used.</p>
<p>You can take a look at the following :</p>
<pre><code>def salary_sort(thing):
def importantparts(thing):
data = []
for i in range(1, len(thing)):
a=thing[i].split(':')
output = (a[1],a[0],int(a[8]))
data.append(output)
data.sort(key=lambda item: item[2], reverse=True)
return data
return importantparts(thing)
employee_data = ["FName LName Tel Address City State Zip Birthdate Salary", \
"Arthur:Putie:923-835-8745:23 Wimp Lane:Kensington:DL:38758:8/31/1969:126000", \
"Barbara:Kertz:385-573-8326:832 Ponce Drive:Gary:IN:83756:12/1/1946:268500", \
"Betty:Boop:245-836-8357:635 Cutesy Lane:Hollywood:CA:91464:6/23/1923:14500"]
print(salary_sort(employee_data))
</code></pre>
<p>Which gives, as expected :</p>
<pre><code>[('Kertz', 'Barbara', 268500), ('Putie', 'Arthur', 126000), ('Boop', 'Betty', 14500)]
</code></pre>
<p>What I did there is pushing all the relevant data for the employees into a new array (named <code>data</code>), and then sorted this array using the <code>lambda</code> function.</p>
| 0 | 2016-10-11T07:17:00Z | [
"python",
"sorting",
"lambda"
] |
Lambda function Python3 no change in output | 39,971,604 | <pre><code>def salary_sort(thing):
def importantparts(thing):
for i in range(1, len(thing)):
a=thing[i].split(':')
output = (a[1],a[0],a[8])
sortedlist = sorted(output, key = lambda item: item[2], reverse=True)
print(sortedlist)
return importantparts(thing)
salary_sort(employee_data)
</code></pre>
<p>This function is supposed to sort out a list of names by their salary.
I managed to isolate the first last names and salaries but I can't seem to get it to sort by their salaries </p>
<p>'Thing' aka employee_data</p>
<pre><code>employee_data = ["FName LName Tel Address City State Zip Birthdate Salary",
"Arthur:Putie:923-835-8745:23 Wimp Lane:Kensington:DL:38758:8/31/1969:126000",
"Barbara:Kertz:385-573-8326:832 Ponce Drive:Gary:IN:83756:12/1/1946:268500",
"Betty:Boop:245-836-8357:635 Cutesy Lane:Hollywood:CA:91464:6/23/1923:14500",.... etc.]
</code></pre>
<p>Output</p>
<pre><code>['Putie', 'Arthur', '126000']
['Kertz', 'Barbara', '268500']
['Betty', 'Boop', '14500']
['Hardy', 'Ephram', '56700']
['Fardbarkle', 'Fred', '780900']
['Igor', 'Chevsky', '23400']
['James', 'Ikeda', '45000']
['Cowan', 'Jennifer', '58900']
['Jesse', 'Neal', '500']
['Jon', 'DeLoach', '85100']
['Jose', 'Santiago', '95600']
['Karen', 'Evich', '58200']
['Lesley', 'Kirstin', '52600']
['Gortz', 'Lori', '35200']
['Corder', 'Norma', '245700']
</code></pre>
| 0 | 2016-10-11T06:34:37Z | 39,972,163 | <p>There are a number of issues with your code, but the key one is that you are sorting <em>each row</em> as you create it, rather than the list of lists.</p>
<p>Also:</p>
<ul>
<li><p><code>importantparts()</code> doesn't return anything (so <code>salarysort()</code> returns None). </p></li>
<li><p>You need to cast the <code>Salary</code> field to an <code>int</code> so that it sorts properly by value (they don't all have the same field-width, so an alphanumeric sort will be incorrect).</p></li>
<li><p>Finally, you don't need to use <code>for i in range(1, len(thing)):</code>, you can iterate directly over <code>thing</code>, taking a <a href="http://stackoverflow.com/questions/509211/explain-pythons-slice-notation">slice</a> to remove the first element<sup>1</sup>. </p></li>
</ul>
<p><sup>1</sup><sub>Note that this last is not <em>wrong</em> per se, but iterating directly over an iterable is considered more 'Pythonic'.</sub></p>
<p></p>
<pre><code>def salary_sort(thing):
def importantparts(thing):
unsortedlist = []
for item in thing[1:]:
a=item.split(':')
unsortedlist.append([a[1],a[0],int(a[8])])
print unsortedlist
sortedlist = sorted(unsortedlist, key = lambda item: item[2], reverse=True)
return (sortedlist)
return importantparts(thing)
employee_data = ["FName LName Tel Address City State Zip Birthdate Salary",
"Arthur:Putie:923-835-8745:23 Wimp Lane:Kensington:DL:38758:8/31/1969:126000",
"Barbara:Kertz:385-573-8326:832 Ponce Drive:Gary:IN:83756:12/1/1946:268500",
"Betty:Boop:245-836-8357:635 Cutesy Lane:Hollywood:CA:91464:6/23/1923:14500"]
print salary_sort(employee_data)
</code></pre>
<p>Output:</p>
<pre><code>[['Kertz', 'Barbara', 268500], ['Putie', 'Arthur', 126000], ['Boop', 'Betty', 14500]]
</code></pre>
| 2 | 2016-10-11T07:17:15Z | [
"python",
"sorting",
"lambda"
] |
Lambda function Python3 no change in output | 39,971,604 | <pre><code>def salary_sort(thing):
def importantparts(thing):
for i in range(1, len(thing)):
a=thing[i].split(':')
output = (a[1],a[0],a[8])
sortedlist = sorted(output, key = lambda item: item[2], reverse=True)
print(sortedlist)
return importantparts(thing)
salary_sort(employee_data)
</code></pre>
<p>This function is supposed to sort out a list of names by their salary.
I managed to isolate the first last names and salaries but I can't seem to get it to sort by their salaries </p>
<p>'Thing' aka employee_data</p>
<pre><code>employee_data = ["FName LName Tel Address City State Zip Birthdate Salary",
"Arthur:Putie:923-835-8745:23 Wimp Lane:Kensington:DL:38758:8/31/1969:126000",
"Barbara:Kertz:385-573-8326:832 Ponce Drive:Gary:IN:83756:12/1/1946:268500",
"Betty:Boop:245-836-8357:635 Cutesy Lane:Hollywood:CA:91464:6/23/1923:14500",.... etc.]
</code></pre>
<p>Output</p>
<pre><code>['Putie', 'Arthur', '126000']
['Kertz', 'Barbara', '268500']
['Betty', 'Boop', '14500']
['Hardy', 'Ephram', '56700']
['Fardbarkle', 'Fred', '780900']
['Igor', 'Chevsky', '23400']
['James', 'Ikeda', '45000']
['Cowan', 'Jennifer', '58900']
['Jesse', 'Neal', '500']
['Jon', 'DeLoach', '85100']
['Jose', 'Santiago', '95600']
['Karen', 'Evich', '58200']
['Lesley', 'Kirstin', '52600']
['Gortz', 'Lori', '35200']
['Corder', 'Norma', '245700']
</code></pre>
| 0 | 2016-10-11T06:34:37Z | 39,972,253 | <p>You main problem is that you reset the <code>output</code> sequence with each new <em>line</em> instead of first accumulating the data and then sorting. Another problem is that your external function declared an inner one and called it, but the inner one did not return anything. Finally, if you sort strings without converting them to integers, you will get an alphanumeric sort: ('9', '81', '711', '6') which is probably not what you expect.</p>
<p>By the way, the outer-inner functions pattern is of no use here, and you can use a simple direct function.</p>
<pre><code>def salary_sort(thing):
output = []
for i in range(1, len(thing)):
a=thing[i].split(':')
output.append([a[1],a[0],a[8]])
sortedlist = sorted(output, key = lambda item: int(item[2]), reverse=True)
return sortedlist
</code></pre>
<p>the result is as expected:</p>
<pre><code>[['Kertz', 'Barbara', '268500'], ['Putie', 'Arthur', '126000'], ['Boop', 'Betty', '14500']]
</code></pre>
<hr>
<p>If you prefer numbers for the salaries, you do the conversion one step higher:</p>
<pre><code>def salary_sort(thing):
output = []
for i in range(1, len(thing)):
a=thing[i].split(':')
output.append([a[1],a[0],int(a[8])])
sortedlist = sorted(output, key = lambda item: item[2], reverse=True)
return sortedlist
</code></pre>
<p>and the result is again correct:</p>
<pre><code>[['Kertz', 'Barbara', 268500], ['Putie', 'Arthur', 126000], ['Boop', 'Betty', 14500]]
</code></pre>
| 1 | 2016-10-11T07:24:23Z | [
"python",
"sorting",
"lambda"
] |
How to show yticks on the plot/graph (not on y-axis). Show yticks near points | 39,971,625 | <p>I have a plot with a simple line. For the moment, I set <strong>yticks</strong> as invisible.
<a href="http://i.stack.imgur.com/EaW9w.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/EaW9w.jpg" alt="enter image description here"></a></p>
<p>Here is the code for the graph:</p>
<pre><code>import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 1.5, 2, 2.5, 3]
fig, ax = plt.subplots(figsize=(15,10))
plt.plot(x, y, 'ko-')
plt.xlabel('X', fontsize=15)
plt.ylabel('Y', fontsize=15)
plt.xticks(x, fontsize=13)
plt.yticks(y, visible=False)
plt.margins(0.1, 0.1)
plt.title('Graph', color='black', fontsize=17)
ax.axis('scaled')
ax.grid()
plt.show()
</code></pre>
<hr>
<p>I need to show/print <strong>yticks</strong> right on the graph itself (not on the left side). So, <strong>yticks</strong> are alongside with datapoints.</p>
<p><strong>Desired output:</strong>
<a href="http://i.stack.imgur.com/vvfCm.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/vvfCm.jpg" alt="enter image description here"></a></p>
<hr>
<p>How to do it with <strong>Matplotlib</strong>?</p>
| 2 | 2016-10-11T06:35:49Z | 39,995,065 | <p>You can use <code>plt.text()</code> to annotate text onto an axis. By iterating over your x,y points you can place a label at each marker. For example: </p>
<pre><code>import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 1.5, 2, 2.5, 3]
fig, ax = plt.subplots(figsize=(15,10))
plt.plot(x, y, 'ko-')
plt.xlabel('X', fontsize=15)
plt.ylabel('Y', fontsize=15)
plt.xticks(x, fontsize=13)
plt.yticks(y, visible=False)
offset = 0.05
for xp, yp in zip(x,y):
label = "%s" % yp
plt.text(xp-offset, yp+offset, label, fontsize=12, horizontalalignment='right')
plt.margins(0.1, 0.1)
plt.title('Graph', color='black', fontsize=17)
ax.axis('scaled')
ax.grid()
plt.show()
</code></pre>
<p>Gives the following figure:</p>
<p><a href="https://i.stack.imgur.com/dDP6C.png" rel="nofollow"><img src="https://i.stack.imgur.com/dDP6C.png" alt="enter image description here"></a></p>
| 2 | 2016-10-12T09:25:24Z | [
"python",
"matplotlib",
"linechart"
] |
Import mssql spatial fields into geopandas/shapely geometry | 39,971,629 | <p>I cannot seem to be able to directly import mssql spatial fields into geopandas. I can import normal mssql tables into pandas with Pymssql without problems, but I cannot figure out a way to import the spatial fields into shapely geometry. I know that the OGR driver for mssql should be able to handle it, but I'm not skilled enough in sql to figure this out.
This is more of an issue for lines and polygons as points can be converted to x and y coordinates from the mssql field.
Thanks!</p>
| 0 | 2016-10-11T06:36:05Z | 39,973,045 | <p>I figured it out by properly querying the sql database table and converting the wkt string to shapely geometry via the loads function in shapely.wkt.</p>
<p>I'm no programmer, so bear that in mind with the organization of the function. The function can import mssql tables with or without GIS geometry.</p>
<pre><code>def rd_sql(server, database, table, col_names=None, where_col=None, where_val=None, geo_col=False, epsg=2193, export=False, path='save.csv'):
"""
Function to import data from a MSSQL database. Specific columns can be selected and specific queries within columns can be selected. Requires the pymssql package, which must be separately installed.
Arguments:\n
server -- The server name (str). e.g.: 'SQL2012PROD03'\n
database -- The specific database within the server (str). e.g.: 'LowFlows'\n
table -- The specific table within the database (str). e.g.: 'LowFlowSiteRestrictionDaily'\n
col_names -- The column names that should be retrieved (list). e.g.: ['SiteID', 'BandNo', 'RecordNo']\n
where_col -- The sql statement related to a specific column for selection (must be formated according to the example). e.g.: 'SnapshotType'\n
where_val -- The WHERE query values for the where_col (list). e.g. ['value1', 'value2']\n
geo_col -- Is there a geometry column in the table?.\n
epsg -- The coordinate system (int).\n
export -- Should the data be exported?\n
path -- The path and csv name for the export if 'export' is True (str).
"""
from pymssql import connect
from pandas import read_sql
from shapely.wkt import loads
from geopandas import GeoDataFrame
if col_names is None and where_col is None:
stmt1 = 'SELECT * FROM ' + table
elif where_col is None:
stmt1 = 'SELECT ' + str(col_names).replace('\'', '"')[1:-1] + ' FROM ' + table
else:
stmt1 = 'SELECT ' + str(col_names).replace('\'', '"')[1:-1] + ' FROM ' + table + ' WHERE ' + str([where_col]).replace('\'', '"')[1:-1] + ' IN (' + str(where_val)[1:-1] + ')'
conn = connect(server, database=database)
df = read_sql(stmt1, conn)
## Read in geometry if required
if geo_col:
geo_col_stmt = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=" + "\'" + table + "\'" + " AND DATA_TYPE='geometry'"
geo_col = str(read_sql(geo_col_stmt, conn).iloc[0,0])
if where_col is None:
stmt2 = 'SELECT ' + geo_col + '.STGeometryN(1).ToString()' + ' FROM ' + table
else:
stmt2 = 'SELECT ' + geo_col + '.STGeometryN(1).ToString()' + ' FROM ' + table + ' WHERE ' + str([where_col]).replace('\'', '"')[1:-1] + ' IN (' + str(where_val)[1:-1] + ')'
df2 = read_sql(stmt2, conn)
df2.columns = ['geometry']
geometry = [loads(x) for x in df2.geometry]
df = GeoDataFrame(df, geometry=geometry, crs={'init' :'epsg:' + str(epsg)})
if export:
df.to_csv(path, index=False)
return(df)
conn.close()
</code></pre>
<p>EDIT: Made the function automatically find the geometry field if one exists.</p>
| 0 | 2016-10-11T08:16:33Z | [
"python",
"sql-server",
"shapely",
"geopandas"
] |
Scrapy not able to get image url and also not able to download images | 39,971,674 | <p>I have tried every search result in google and stack overflow solution but i am not able to get the solution.
I am creating a scrapy to extract images please find the code below</p>
<p>My items.py </p>
<pre><code>class MyntraItem(scrapy.Item):
product_urls=scrapy.Field()
files=scrapy.Field()
image_urls=scrapy.Field()
images = scrapy.Field()
</code></pre>
<p>My settings.py</p>
<pre><code>BOT_NAME = 'hello'
SPIDER_MODULES = ['myntra.spiders']
NEWSPIDER_MODULE = 'myntra.spiders'
FILES_STORE = '/home/swapnil/Desktop/AI/myntra/'
ITEM_PIPELINES = {
#'myntra.pipelines.SomePipeline': 300,
'scrapy.pipelines.images.FilesPipeline': 1,
}
</code></pre>
<p>My first.py</p>
<pre><code>class FirstSpider(CrawlSpider):
name = "first"
allowed_domains = ["myntra.com"]
start_urls = [
'http://www.myntra.com/men-sports-tshirts-menu?src=tNav&f=Pattern_article_attr%3Astriped',
]
rules = [Rule(LinkExtractor(restrict_xpaths=['//*[@class="product-link"]']),callback='parse_lnk',follow=True)]
#rules = [Rule(LinkExtractor(allow=['.*']),callback='parse_lnk',follow=True)]
def parse_lnk(self, response):
item=MyntraItem()
item['product_urls']=response.url
item['files']=response.xpath('//*[@class="thumbnails-selected-image"]/@src')
item['image_urls']=item['files']
#print '666666666666666666',item['files']
return item
</code></pre>
<p>Please help: My intention is to download the images.</p>
| 0 | 2016-10-11T06:39:47Z | 39,973,380 | <p>By default, <code>FilesPipeline</code> expects file URLs to be available from the value of <a href="https://docs.scrapy.org/en/latest/topics/media-pipeline.html#usage-example" rel="nofollow">an item's <code>"file_urls"</code> key</a>.</p>
<blockquote>
<p>(...) if a spider returns a dict with the URLs key (<code>"file_urls</code>" or
<code>"image_urls"</code>, for the Files or Images Pipeline respectively), the
pipeline will put the results under respective key (<code>"files"</code> or <code>"images"</code>).</p>
</blockquote>
<p>It seems you are using <code>"product_urls"</code>. To change where the pipeline looks for URLs, you need to set <code>FILES_URLS_FIELD = "product_urls"</code>.</p>
| 0 | 2016-10-11T08:37:28Z | [
"python",
"image",
"scrapy",
"pipeline"
] |
Scrapy not able to get image url and also not able to download images | 39,971,674 | <p>I have tried every search result in google and stack overflow solution but i am not able to get the solution.
I am creating a scrapy to extract images please find the code below</p>
<p>My items.py </p>
<pre><code>class MyntraItem(scrapy.Item):
product_urls=scrapy.Field()
files=scrapy.Field()
image_urls=scrapy.Field()
images = scrapy.Field()
</code></pre>
<p>My settings.py</p>
<pre><code>BOT_NAME = 'hello'
SPIDER_MODULES = ['myntra.spiders']
NEWSPIDER_MODULE = 'myntra.spiders'
FILES_STORE = '/home/swapnil/Desktop/AI/myntra/'
ITEM_PIPELINES = {
#'myntra.pipelines.SomePipeline': 300,
'scrapy.pipelines.images.FilesPipeline': 1,
}
</code></pre>
<p>My first.py</p>
<pre><code>class FirstSpider(CrawlSpider):
name = "first"
allowed_domains = ["myntra.com"]
start_urls = [
'http://www.myntra.com/men-sports-tshirts-menu?src=tNav&f=Pattern_article_attr%3Astriped',
]
rules = [Rule(LinkExtractor(restrict_xpaths=['//*[@class="product-link"]']),callback='parse_lnk',follow=True)]
#rules = [Rule(LinkExtractor(allow=['.*']),callback='parse_lnk',follow=True)]
def parse_lnk(self, response):
item=MyntraItem()
item['product_urls']=response.url
item['files']=response.xpath('//*[@class="thumbnails-selected-image"]/@src')
item['image_urls']=item['files']
#print '666666666666666666',item['files']
return item
</code></pre>
<p>Please help: My intention is to download the images.</p>
| 0 | 2016-10-11T06:39:47Z | 39,985,109 | <p>Use <strong>ImagesPipeline</strong> instead, and extract the images using <strong>regex</strong>.</p>
<p>In My first.py</p>
<pre><code>item['files']= re.findall('front":\{"path":"(.+?)"', response.body)
</code></pre>
<p>In settings.py</p>
<pre><code>IMAGES_STORE = '/home/swapnil/Desktop/AI/myntra/'
ITEM_PIPELINES = {'myntra.pipelines.SomePipeline': 300,
'scrapy.pipelines.images.ImagesPipeline': 1,}
</code></pre>
<p>This would works like a charm.</p>
| 0 | 2016-10-11T19:24:46Z | [
"python",
"image",
"scrapy",
"pipeline"
] |
How to count the number of times a word appears in each row of a csv file, in python | 39,971,779 | <p>I have a csv document in which each row contains a string of words. For each row, I want to know how many times each words appears in that row, how would I go about this?</p>
<p>Thanks</p>
| -3 | 2016-10-11T06:49:12Z | 39,971,953 | <p>Move the row to a list, make it unique and count every object in list,</p>
<p>For converting to list <a href="http://stackoverflow.com/questions/7844118/how-to-convert-comma-delimited-string-to-list-in-python">Check this</a></p>
<p>if result is more than one, print it.</p>
<p>Considered this as list <code>['a','b','a','c']</code></p>
<pre><code>z=['a','b','a','c']
u=set(z)
for i in u:
if z.count(i)>1: print i,z.count(i)
</code></pre>
<p>Output:</p>
<pre><code>`a 2`
</code></pre>
| 0 | 2016-10-11T07:01:59Z | [
"python",
"csv"
] |
How to count the number of times a word appears in each row of a csv file, in python | 39,971,779 | <p>I have a csv document in which each row contains a string of words. For each row, I want to know how many times each words appears in that row, how would I go about this?</p>
<p>Thanks</p>
| -3 | 2016-10-11T06:49:12Z | 39,971,991 | <p>Use <code>collections.Counter</code>:</p>
<pre><code>from collections import Counter
z = ['a', 'b', 'c', 'd', 'a']
u = Counter(z)
print(u['a']) # 2
print(u['b']) # 1
</code></pre>
| 0 | 2016-10-11T07:05:10Z | [
"python",
"csv"
] |
ImportError: No module named cv2. But running apt-get command shows that python-opencv is already installed | 39,971,846 | <p>Even though I tried out the solutions given for the same type of questions concerning the same error, nothing worked. When I try to run the script it gives this import error. But surprisingly when I try </p>
<blockquote>
<p>apt-get install python-opencv </p>
</blockquote>
<p>I get this message:</p>
<blockquote>
<p>python-opencv is already the newest version.</p>
</blockquote>
<p>This is what puzzles me. If it is installed, why can't it be imported?
Thanks in advance.</p>
| 0 | 2016-10-11T06:53:59Z | 39,973,217 | <p>Most likely the library python-opencv is not installed in the default directory. That is why your interpreter cannot find it.</p>
<p>When dealing with python projects it's recommended to use virtualenv. It will allow you to create separate python environments and not mess them up. Then install pip and use it to install python packages rather than apt-get install inside of your virtual environment.</p>
<p>In your case you need to run:</p>
<pre><code>sudo dpkg-query -L python-opencv
</code></pre>
<p>It will output the directories to where the python-opencv library was installed. And the add that path to PYTHONPATH in your .bashrc file (most likely it is .bashrc in Debian):</p>
<pre><code>PYTHONPATH="${PYTHONPATH}:/path/to/the/python/libraries"
export PYTHONPATH
</code></pre>
<p>Then run <code>. .bashrc</code> in your home folder. </p>
<p>But it's not recommended to do that. As I've already said the cleaner way is to use virtualenv and pip. In that case you don't need to mess up with PYTHONPATH.</p>
| 0 | 2016-10-11T08:27:25Z | [
"python",
"opencv",
"importerror"
] |
What are variable annotations in Python 3.6? | 39,971,929 | <p>Python 3.6 is about to be released. <a href="https://www.python.org/dev/peps/pep-0494/">PEP 494 -- Python 3.6 Release Schedule</a> mentions the end of December, so I went through <a href="https://docs.python.org/3.6/whatsnew/3.6.html">What's New in Python 3.6</a> to see they mention the <em>variable annotations</em>:</p>
<blockquote>
<p><a href="https://www.python.org/dev/peps/pep-0484">PEP 484</a> introduced standard for type annotations of function parameters, a.k.a. type hints. This PEP adds syntax to Python for annotating the types of variables including class variables and instance variables:</p>
<pre><code> primes: List[int] = []
captain: str # Note: no initial value!
class Starship:
stats: Dict[str, int] = {}
</code></pre>
<p>Just as for function annotations, the Python interpreter does not attach any particular meaning to variable annotations and only stores them in a special attribute <code>__annotations__</code> of a class or module. In contrast to variable declarations in statically typed languages, the goal of annotation syntax is to provide an easy way to specify structured type metadata for third party tools and libraries via the abstract syntax tree and the <code>__annotations__</code> attribute.</p>
</blockquote>
<p>So from what I read they are part of the type hints coming from Python 3.5, described in <a href="http://stackoverflow.com/q/32557920/1983854">What are Type hints in Python 3.5</a>.</p>
<p>I follow the <code>captain: str</code> and <code>class Starship</code> example, but not sure about the last one: How does <code>primes: List[int] = []</code> explain? Is it defining an empty list that will just allow integers?</p>
| 15 | 2016-10-11T07:00:15Z | 39,972,031 | <p>Everything between <code>:</code> and the <code>=</code> is a type hint, so <code>primes</code> is indeed defined as <code>List[int]</code>, and initially set to an empty list (and <code>stats</code> is an empty dictionary initially, defined as <code>Dict[str, int]</code>).</p>
<p><code>List[int]</code> and <code>Dict[str, int]</code> are not part of the next syntax however, these were already defined in the Python 3.5 typing hints PEP. The 3.6 <a href="https://www.python.org/dev/peps/pep-0526/">PEP 526 â <em>Syntax for Variable Annotations</em></a> proposal <em>only</em> defines the syntax to attach the same hints to variables; before you could only attach type hints to variables with comments (e.g. <code>primes = [] # List[int]</code>).</p>
<p>Both <code>List</code> and <code>Dict</code> are <em>Generic</em> types, indicating that you have a list or dictionary mapping with specific (concrete) contents. </p>
<p>For <code>List</code>, there is only one 'argument' (the elements in the <code>[...]</code> syntax), the type of every element in the list. For <code>Dict</code>, the first argument is the key type, and the second the value type. So <em>all</em> values in the <code>primes</code> list are integers, and <em>all</em> key-value pairs in the <code>stats</code> dictionary are <code>(str, int)</code> pairs, mapping strings to integers.</p>
<p>See the <a href="https://docs.python.org/3/library/typing.html#typing.List"><code>typing.List</code></a> and <a href="https://docs.python.org/3/library/typing.html#typing.Dict"><code>typing.Dict</code></a> definitions, the <a href="https://docs.python.org/3/library/typing.html#generics">section on <em>Generics</em></a>, as well as <a href="https://www.python.org/dev/peps/pep-0483">PEP 483 â <em>The Theory of Type Hints</em></a>.</p>
<p>Like type hints on functions, their use is optional and are also considered <em>annotations</em> (provided there is an object to attach these to, so globals in modules and attributes on classes, but not locals in functions) which you could introspect via the <code>__annotations__</code> attribute. You can attach arbitrary info to these annotations, you are not strictly limited to type hint information.</p>
<p>You may want to read the <a href="https://www.python.org/dev/peps/pep-0526/">full proposal</a>; it contains some additional functionality above and beyond the new syntax; it specifies when such annotations are evaluated, how to introspect them and how to declare something as a class attribute vs. instance attribute, for example.</p>
| 15 | 2016-10-11T07:08:33Z | [
"python",
"python-3.x",
"annotations",
"type-hinting",
"python-3.6"
] |
What are variable annotations in Python 3.6? | 39,971,929 | <p>Python 3.6 is about to be released. <a href="https://www.python.org/dev/peps/pep-0494/">PEP 494 -- Python 3.6 Release Schedule</a> mentions the end of December, so I went through <a href="https://docs.python.org/3.6/whatsnew/3.6.html">What's New in Python 3.6</a> to see they mention the <em>variable annotations</em>:</p>
<blockquote>
<p><a href="https://www.python.org/dev/peps/pep-0484">PEP 484</a> introduced standard for type annotations of function parameters, a.k.a. type hints. This PEP adds syntax to Python for annotating the types of variables including class variables and instance variables:</p>
<pre><code> primes: List[int] = []
captain: str # Note: no initial value!
class Starship:
stats: Dict[str, int] = {}
</code></pre>
<p>Just as for function annotations, the Python interpreter does not attach any particular meaning to variable annotations and only stores them in a special attribute <code>__annotations__</code> of a class or module. In contrast to variable declarations in statically typed languages, the goal of annotation syntax is to provide an easy way to specify structured type metadata for third party tools and libraries via the abstract syntax tree and the <code>__annotations__</code> attribute.</p>
</blockquote>
<p>So from what I read they are part of the type hints coming from Python 3.5, described in <a href="http://stackoverflow.com/q/32557920/1983854">What are Type hints in Python 3.5</a>.</p>
<p>I follow the <code>captain: str</code> and <code>class Starship</code> example, but not sure about the last one: How does <code>primes: List[int] = []</code> explain? Is it defining an empty list that will just allow integers?</p>
| 15 | 2016-10-11T07:00:15Z | 39,973,133 | <p>Indeed, variable annotations are just the next step from <code># type</code> comments as they where defined in <code>PEP 484</code>; the rationale behind this change is highlighted in the <a href="https://www.python.org/dev/peps/pep-0526/#rationale">respective PEP section</a>. So, instead of hinting the type with:</p>
<pre><code>primes = [] # type: List[int]
</code></pre>
<p>New syntax was introduced to allow for directly annotating the type with an assignment of the form:</p>
<pre><code>primes: List[int] = []
</code></pre>
<p>which, as @Martijn pointed out, denotes a list of integers by using types available in <a href="https://docs.python.org/3/library/typing.html"><code>typing</code></a> and initializing it to an empty list.</p>
<hr>
<p>In short, the <a href="https://docs.python.org/3.6/reference/simple_stmts.html#annotated-assignment-statements">new syntax introduced</a> simply allows you to annotate with a type after the colon <code>:</code> character and, optionally allows you to assign a value to it:</p>
<pre><code>annotated_assignment_stmt ::= augtarget ":" expression ["=" expression]
</code></pre>
<hr>
<p>Additional changes were also introduced along with the new syntax; modules and classes now have an <code>__annotations__</code> attribute, as functions have had for some time, in which the type metadata is attached:</p>
<pre><code>from typing import get_type_hints # grabs __annotations__
</code></pre>
<p>Now <code>__main__.__annotations__</code> holds the declared types:</p>
<pre><code>>>> from typing import List, get_type_hints
>>> primes: List[int] = []
>>> captain: str
>>> import __main__
>>> get_type_hints(__main__)
{'primes': typing.List<~T>[int]}
</code></pre>
<p><code>captain</code> won't currently show up through <a href="https://docs.python.org/3.6/library/typing.html#typing.get_type_hints"><code>get_type_hints</code></a> because <code>get_type_hints</code> only returns types that can also be accessed on a module; i.e it needs a value first:</p>
<pre><code>>>> captain = "Picard"
>>> get_type_hints(__main__)
{'primes': typing.List<~T>[int], 'captain': <class 'str'>}
</code></pre>
<p><sub> Using <code>print(__annotations__)</code> will show <code>'captain': <class 'str'></code> but you really shouldn't be accessing <code>__annotations__</code> directly.</sub></p>
<p>Similarly, for classes:</p>
<pre><code>>>> get_type_hints(Starship)
ChainMap({'stats': typing.Dict<~KT, ~VT>[str, int]}, {})
</code></pre>
<p>Where a <code>ChainMap</code> is used to grab the annotations for a given class (located in the first mapping) and all annotations defined in the base classes found in its <code>mro</code> (consequent mappings, <code>{}</code> for object).</p>
<p>Along with the new syntax, a new <a href="https://docs.python.org/3.6/library/typing.html#typing.ClassVar"><code>ClassVar</code></a> type has been added to denote class variables. Yup, <code>stats</code> in your example is actually an <em>instance variable</em>, not a <code>ClassVar</code>.</p>
<hr>
<p>As with type hints from <code>PEP 484</code>, these are completely optional and are of main use for type checking tools (and whatever else you can build based on this information). It is to be provisional when the stable version of Py 3.6 is released so small tweaks might be added in the future.</p>
| 11 | 2016-10-11T08:21:24Z | [
"python",
"python-3.x",
"annotations",
"type-hinting",
"python-3.6"
] |
Subdomain Django Settings Conflict | 39,972,134 | <p>I have a site with a set of sub-domains. When I visit one of those sub-domains including the actual domain, it <strong>sometimes</strong> shows an Internal Server Error on the browser and when I check the apache error.log it tells that it throws an <strong>ImportError</strong> :</p>
<pre><code> [Tue Oct 11 06:47:10.999837 2016] [:error] [pid 13114] [client 0.0.0.0:58735] mod_wsgi (pid=13114): Target WSGI script '/var/www/html/api.ai-labs.co/ai_labs_apps/wsgi.py' cannot be loaded as Python module.
[Tue Oct 11 06:47:11.000377 2016] [:error] [pid 13114] [client 0.0.0.0:58735] mod_wsgi (pid=13114): Exception occurred processing WSGI script '/var/www/html/api.ai-labs.co/ai_labs_apps/wsgi.py'.
[Tue Oct 11 06:47:11.000478 2016] [:error] [pid 13114] [client 0.0.0.0:58735] Traceback (most recent call last):
[Tue Oct 11 06:47:11.000552 2016] [:error] [pid 13114] [client 0.0.0.0:58735] File "/var/www/html/api.ai-labs.co/ai_labs_apps/wsgi.py", line 27, in <module>
[Tue Oct 11 06:47:11.000675 2016] [:error] [pid 13114] [client 0.0.0.0:58735] application = get_wsgi_application()
[Tue Oct 11 06:47:11.000737 2016] [:error] [pid 13114] [client 0.0.0.0:58735] File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application
[Tue Oct 11 06:47:11.000853 2016] [:error] [pid 13114] [client 0.0.0.0:58735] django.setup()
[Tue Oct 11 06:47:11.000913 2016] [:error] [pid 13114] [client 0.0.0.0:58735] File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 17, in setup
[Tue Oct 11 06:47:11.001017 2016] [:error] [pid 13114] [client 0.0.0.0:58735] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
[Tue Oct 11 06:47:11.001076 2016] [:error] [pid 13114] [client 0.0.0.0:58735] File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 55, in __getattr__
[Tue Oct 11 06:47:11.001269 2016] [:error] [pid 13114] [client 0.0.0.0:58735] self._setup(name)
[Tue Oct 11 06:47:11.001330 2016] [:error] [pid 13114] [client 0.0.0.0:58735] File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 43, in _setup
[Tue Oct 11 06:47:11.001395 2016] [:error] [pid 13114] [client 0.0.0.0:58735] self._wrapped = Settings(settings_module)
[Tue Oct 11 06:47:11.001450 2016] [:error] [pid 13114] [client 0.0.0.0:58735] File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 99, in __init__
[Tue Oct 11 06:47:11.001526 2016] [:error] [pid 13114] [client 0.0.0.0:58735] mod = importlib.import_module(self.SETTINGS_MODULE)
[Tue Oct 11 06:47:11.001581 2016] [:error] [pid 13114] [client 0.0.0.0:58735] File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
[Tue Oct 11 06:47:11.001689 2016] [:error] [pid 13114] [client 0.0.0.0:58735] __import__(name)
[Tue Oct 11 06:47:11.001765 2016] [:error] [pid 13114] [client 0.0.0.0:58735] ImportError: No module named project.settings
</code></pre>
<p>I'll just post the files of the two out of five applications because I really can't figure out the error and I'm very bad at deploying to the actual server</p>
<p><strong>1st application: accounts</strong></p>
<p><strong>This is the 1st application's apache2/sites-available/accounts.ai-labs.conf</strong></p>
<pre><code> <VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
ServerName accounts.ai-labs.co
# ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/accounts.ai-labs.co/project
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
<Directory /var/www/html/accounts.ai-labs.co/project>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
Alias /static /var/www/html/accounts.ai-labs.co/project/static
<Directory /var/www/html/accounts.ai-labs.co/project/static>
Require all granted
</Directory>
Alias /static /var/www/html/accounts.ai-labs.co/project/media
<Directory /var/www/html/accounts.ai-labs.co/project/media>
Require all granted
</Directory>
<Directory /var/www/html/accounts.ai-labs.co/project/project>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIScriptAlias / /var/www/html/accounts.ai-labs.co/project/project/wsgi.py
</VirtualHost>
</code></pre>
<p><strong>This is the 1st application's wsgi.py</strong></p>
<pre><code>"""
WSGI config for project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
import sys
import site
site.addsitedir('/var/www/html/accounts.ai-labs.co/lib/python2.7/site-packages')
sys.path.append('/var/www/html/accounts.ai-labs.co/project')
sys.path.append('/var/www/html/accounts.ai-labs.co/project/project')
from django.core.wsgi import get_wsgi_application
from django.conf import settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
activate_env=os.path.expanduser("/var/www/html/accounts.ai-labs.co/bin/activate_this.py")
execfile(activate_env, dict(__file__=activate_env))
application = get_wsgi_application()
</code></pre>
<p><strong>2nd application: blogs</strong></p>
<p><strong>This is the 2nd application's apache2/sites-available/blogs.ai-labs.conf</strong></p>
<pre><code><VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
ServerName blogs.ai-labs.co
# ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/blogs.ai-labs.co
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
<Directory /var/www/html/blogs.ai-labs.co>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
Alias /static /var/www/html/blogs.ai-labs.co/static
<Directory /var/www/html/blogs.ai-labs.co/static>
Require all granted
</Directory>
Alias /static /var/www/html/blogs.ai-labs.co/media
<Directory /var/www/html/blogs.ai-labs.co/media>
Require all granted
</Directory>
<Directory /var/www/html/blogs.ai-labs.co/ai_labs_blogs>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIScriptAlias / /var/www/html/blogs.ai-labs.co/ai_labs_blogs/wsgi.py
</VirtualHost>
</code></pre>
<p><strong>This is the 2nd application's wsgi.py</strong></p>
<pre><code>"""
WSGI config for ai_labs_blogs project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
import sys
import site
site.addsitedir('/var/www/html/.virtualenvs_copy/ai-labs-website-pure-django/local/lib/python2.7/site-packages')
sys.path.append('/var/www/html/blogs.ai-labs.co')
sys.path.append('/var/www/html/blogs.ai-labs.co/ai_labs_blogs')
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ai_labs_blogs.settings")
activate_env=os.path.expanduser("/var/www/html/.virtualenvs_copy/ai-labs-website-pure-django/bin/activate_this.py")
execfile(activate_env, dict(__file__=activate_env))
application = get_wsgi_application()
</code></pre>
<p>How do I resolve this?</p>
| 0 | 2016-10-11T07:15:34Z | 39,975,023 | <p>Don't use:</p>
<pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
</code></pre>
<p>use:</p>
<pre><code>os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings"
</code></pre>
<p>Similarly for the other <code>wsgi.py</code> file.</p>
<p>This is mentioned in the Django documentation for mod_wsgi as a requirement when not using daemon mode. You really should use daemon mode so each application is in separate processes. You can also clean up how virtual environments are used.</p>
<ul>
<li><a href="https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/" rel="nofollow">https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/</a></li>
<li><a href="http://blog.dscpl.com.au/2012/10/why-are-you-using-embedded-mode-of.html" rel="nofollow">http://blog.dscpl.com.au/2012/10/why-are-you-using-embedded-mode-of.html</a></li>
<li><a href="http://blog.dscpl.com.au/2014/09/using-python-virtual-environments-with.html" rel="nofollow">http://blog.dscpl.com.au/2014/09/using-python-virtual-environments-with.html</a></li>
</ul>
| 1 | 2016-10-11T10:12:40Z | [
"python",
"django",
"apache",
"digital-ocean",
"ubuntu-16.04"
] |
How to update pandas when python is installed as part of ArcGIS10.4, or another solution | 39,972,261 | <p>I recently installed ArcGIS10.4 and now when I run python 2.7 programs using Idle (for purposes unrelated to ArcGIS) it uses the version of python attached to ArcGIS.</p>
<p>One of the programs I wrote needs an updated version of the pandas module. When I try to update the pandas module in this verion of python (by opening command prompt as an administrator, moving to C:\Python27\ArcGIS10.4\Scripts and using the command pip install --upgrade pandas) the files download ok but there is an access error message when PIP tries to upgrade. I have tried restarting the computer in case something was open. The error message is quite long and I can't cut and paste from command prompt but it finishes with
" Permission denied: 'C:\Python27\ArcGIS10.4\Lib\site-packages\numpy\core\multiarray.pyd' "</p>
<p>I've tried the command to reinstall pandas completely which also gave an error message. I've tried installing miniconda in the hope that I could get a second version of python working and then use that version instead of the version attached to ArcMap. However I don't know how to direct Idle to choose the newly installed version. </p>
<p>So overall I don't mind having 2 versions of python if someone could tell me how to choose which one runs or if there's some way to update the ArcMap version that would be even better. I don't really want to uninstall ArcMap at the moment.</p>
<p>Any help is appreciated! Thanks!</p>
| 0 | 2016-10-11T07:25:02Z | 39,972,738 | <p>I reinstalled python again directly from python.org and then installed pandas which seems to work. </p>
<p>I guess this might stop the ArcMap version of python working properly but since I'm not using python with ArcMap at the moment it's not a big problem.</p>
| 0 | 2016-10-11T07:57:09Z | [
"python",
"pandas",
"upgrade",
"arcmap"
] |
pydal requires pymongo version >= 3.0, found '2.2.1' | 39,972,326 | <p><strong>Web2py Error:</strong> </p>
<pre><code> <type 'exceptions.RuntimeError'> Failure to connect, tried 5 times:
Traceback (most recent call last): File
"/Applications/web2py.app/Contents/Resources/gluon/packages/dal/pydal/base.py",
line 446, in __init__ File
"/Applications/web2py.app/Contents/Resources/gluon/packages/dal/pydal/adapters/base.py", line 60, in __call__ File
"/Applications/web2py.app/Contents/Resources/gluon/packages/dal/pydal/adapters/mongo.py",
line 91, in __init__ Exception: pydal requires pymongo version >= 3.0, found '2.2.1'
Version web2py⢠Version 2.14.6-stable+timestamp.2016.05.10.00.21.47
</code></pre>
<p><strong>Python:</strong></p>
<pre><code> python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pymongo
>>> pymongo.version
'3.3.0'
>>>
</code></pre>
<p>Environment: OSX
Can someone help in resolving Web2py error?</p>
| 0 | 2016-10-11T07:29:51Z | 39,980,493 | <p>It looks like you are running the OSX binary version of web2py, which comes with its own Python 2 interpreter (currently, web2py runs under Python 2 only), so it will ignore your system's Python installation (and web2py wouldn't run under your Python 3 installation anyway). The web2py binary version does not come with pymongo, so I'm not sure where that pymongo version 2.2.1 has come from, unless you installed it yourself in /web2py.app/Contents/Resources/site-packages.</p>
<p>One option is to install Python 2.7, install pymongo, and then download the source version of web2py instead of the OSX binary.</p>
| 0 | 2016-10-11T15:06:33Z | [
"python",
"web2py",
"pydal"
] |
Extracting DBN last hidden layer, Theano, Python | 39,972,433 | <p>I am new to Theano and I have been searching for this question about 2 months. I am using the code provided in this site: <a href="http://deeplearning.net/tutorial/DBN.html" rel="nofollow">http://deeplearning.net/tutorial/DBN.html</a></p>
<p>I have a 4 layer Deep Belief Network, actually with 2 hidden layers.
As far as I could find out, this code is classifying my data set (I have to provide labels). But I want to "reduce the dimension of my inputs" with this algorithm. So I have to extract the value of the neurons of the last hidden layer. But I can't.</p>
<p>How can I do this?</p>
<p>Thank you in advance</p>
| 0 | 2016-10-11T07:37:39Z | 39,973,007 | <p>DBM is constructed in layer wise of multiple RBM. quick review to the code in the provided link you should look to the appended layer in the DBM and print the output result of this layer when you are providing the input in these following models. </p>
<pre><code> sigmoid_layer = HiddenLayer(rng=numpy_rng,
input=layer_input,
n_in=input_size,
n_out=hidden_layers_sizes[i],
activation=T.nnet.sigmoid)
self.sigmoid_layers.append(sigmoid_layer)
rbm_layer = RBM(numpy_rng=numpy_rng,
theano_rng=theano_rng,
input=layer_input,
n_visible=input_size,
n_hidden=hidden_layers_sizes[i],
W=sigmoid_layer.W,
hbias=sigmoid_layer.b)
self.rbm_layers.append(rbm_layer)
</code></pre>
| 0 | 2016-10-11T08:14:21Z | [
"python",
"theano"
] |
ImportError: No module named 'bs4' in django only | 39,972,580 | <p>The same question has been asked a number of times but I couldn't find the solution.</p>
<p>After I install a package using pip, I am able to import it in python console or python file and it works as expected.
The same package when I try to include in django, it gives <code>import error</code>.
Do I need to modify <code>settings.py</code> file or any requirement that I need to add? I am driving django with the help of virtual env. </p>
<p>Eg:
I am using <code>BeautifulSoup</code> and I am trying to import <code>from bs4 import BeautifulSoup</code> and I am getting error <code>ImportError: No module named 'bs4'</code></p>
<p>This error only comes in django. I am not able to figure out why this is happening.</p>
<p>Screenshot attached for reference.</p>
<p><strong>1. python console - shows no error</strong></p>
<p><a href="http://i.stack.imgur.com/exmvN.png" rel="nofollow"><img src="http://i.stack.imgur.com/exmvN.png" alt="python2 and python3 console"></a></p>
<p><strong>2. django console- import error</strong></p>
<p><a href="http://i.stack.imgur.com/j0IMN.png" rel="nofollow"><img src="http://i.stack.imgur.com/j0IMN.png" alt="django console"></a></p>
<p><em>I am sorry as it is difficult to read the console but any other thing that I can include which will help me make myself more clear will be appreciated.</em> </p>
| -2 | 2016-10-11T07:46:34Z | 39,972,703 | <p>You don't show either the code of your site or the command you ran (and the URL you entered, if any) to trigger this issue. There's almost certainly some difference between the Python environment on the command line and that operating in Django.</p>
<p>Are you using virtual environments? If so, dependencies should be separately added to each environment. Were you operating from a different working directory? Python usually has the current directory somewhere in <code>sys.path</code>, so if you changed directories it's possible you made <code>bs4</code> unavailable that way.</p>
<p>At the interactive Python prompt, try</p>
<pre><code>import bs4
bs4.__file__
</code></pre>
<p>That will tell you where <code>bs4</code> is being imported from, and might therefore give you a clue as to why it's not available to Django.</p>
| 2 | 2016-10-11T07:54:37Z | [
"python",
"django"
] |
ElasticSearch indexing with 450K documents - performance | 39,972,655 | <p>We have ElasticSearch (1.5) on AWS (t2.micro, 2 instances with 10GB SSD storage each) and a MySQL with ~450K fairly big/complex entities. </p>
<p>I'm using python to read from MySql, serialize to JSON and PUT to ElasticSearch. There are 10 threads working simultaneously, each PUTing bulk of 1000 documents at the time.</p>
<p>Total of ~450K (1.3GB) documents, it takes around 20min to process and send to ElasticSearch.</p>
<p>Problem is that only around 85% of them get indexed and rest are lost. When I reduce number of documents to ~100K they all get indexed.</p>
<p>Looking at ElasticSearch AWS monitor I can see CPU getting up to 100% while indexing, but it doesnt give any errors. </p>
<p>What is the best way to find out bottle here? I want it fast but cant afford losing any documents.</p>
<p>EDIT.
I've run it again checking output of /_cat/thread_pool?v every few minutes. Indexed 390805 out of 441400. Out of thread_pool bellow:</p>
<pre><code>host ip bulk.active bulk.queue bulk.rejected index.active index.queue index.rejected search.active search.queue search.rejected
<host> x.x.x.x 1 22 84 0 0 0 0 0 0
<host> x.x.x.x 1 11 84 0 0 0 0 0 0
<host> x.x.x.x 1 29 84 0 0 0 0 0 0
<host> x.x.x.x 1 13 84 0 0 0 0 0 0
<host> x.x.x.x 0 0 84 0 0 0 0 0 0
<host> x.x.x.x 1 17 84 0 0 0 0 0 0
<host> x.x.x.x 0 0 84 0 0 0 0 0 0
</code></pre>
<p>EDIT 2</p>
<pre><code>host ip bulk.active bulk.queue bulk.rejected index.active index.queue index.rejected search.active search.queue search.rejected
<host> x.x.x.x 0 0 84 0 0 0 0 0 0
</code></pre>
<p>EDIT 3 </p>
<pre><code>$ curl https://xxxxx.es.amazonaws.com/_cat/thread_pool?v&h=id,host,ba,bs,bq,bqs,br,ââbl,bc,bmi,bma
[1] 15896
host ip bulk.active bulk.queue bulk.rejected index.active index.queue index.rejected search.active search.queue search.rejected
<host> x.x.x.x 0 0 84 0 0 0 0 0 0
</code></pre>
<p>^^ copy/paste of what I'm getting back</p>
<p>EDIT 4 </p>
<pre><code>$ curl 'https://xxxxx.es.amazonaws.com/_cat/thread_pool?v&h=id,host,ba,bs,bq,bqs,brââ,ââbl,bc,bmi,bma'
<html><body><h1>400 Bad request</h1>
Your browser sent an invalid request.
</body></html>
</code></pre>
<p>still nothing</p>
<p>EDIT 5</p>
<pre><code>id host ba bs bq bqs br bmi bma bl br bc
n6Ad <host> 0 1 0 50 84 1 1 1 84 25821
</code></pre>
<p>some mysterious way it worked when I changed order of params</p>
| 0 | 2016-10-11T07:51:09Z | 40,002,481 | <p>I suspect EC2 is your bottleneck. Based on <a href="http://stackoverflow.com/questions/28984106/whats-is-cpu-credit-balance-in-ec2">the way burstable instances are allocated CPU</a>, a <code>t2.micro</code> accrues 6 cpu credits an hour. </p>
<p>So in your first hour up, your Elasticsearch nodes will be able to run one vCPU at 100% for a <em>maximum of 6 minutes</em> before being "capped" at an unspecified lower resource allocation (assume it is less than the instance quota of 10% of a vCPU).</p>
<p>Elasticsearch is most likely to be CPU-bound during indexing. If the indexing process is sending bulk requests faster than an instance can ingest (due to being CPU-bound... within quota, or outside of quota <em>after those first 6 minutes of bursting</em>), those requests will queue. Once the queue is saturated, Elasticsearch will begin rejecting requests.</p>
<blockquote>
<p>This may help explain why you're able to index 100k documents without issue <em>(under 6min?)</em>, while your full collection (~450k) encounters difficulty.</p>
</blockquote>
<hr>
<p>If your cluster is CPU-bound during indexing, and bulk requests are being rejected, you'll want to either:</p>
<ol>
<li><p>Increase the compute resources available to your cluster nodes during indexing </p>
<p><strong>OR</strong></p></li>
<li><p>Throttle your indexer to keep pace with your cluster ingestion capacity.</p></li>
</ol>
<hr>
<p>You could build an indexer that was more resilient to smaller node-types, by running your <code>thread_pool</code> request to check how many bulk requests were in queue (perhaps as a percentage of the total queue size), before deciding to fire the next bulk indexing request.</p>
| 1 | 2016-10-12T15:25:42Z | [
"python",
"mysql",
"amazon-web-services",
"elasticsearch"
] |
Quick method to make 2 dimensional sparse arrays from a master data array | 39,972,729 | <p>I will simplify my problem with an example of what I would like done (the actual data I am working with is massive).</p>
<p>The solution to my problem would be simple if there was a 3 dimensional sparse array object that could be fed the x,y,z coordinates along with the data to be stored. Note that I will have memory issues if I do not use a sparse array. Lets say I have an array:</p>
<pre><code> import numpy as np
from scipy.sparse import coo_matrix
arr=np.array([1,3,4,5],[0,6,7,8],[1,7,8,7]])
</code></pre>
<p>The first 3 entries are the x,y,z. Ideally I would want a sparse matrix
that would yield B[1,3,4]=5 and B[0,6,7]=8, etc. Right now I am using a dictionary where the x coordinate is the key. y and z will be the sparse array coordinates. So its something like this:</p>
<pre><code> row=arr[:,1]
col=arr[:,2]
data=arr[:,3]
dic={}
### x here goes from only 0 to 1 in this simple example
for x in range(2):
bool=arr[:,0][arr[:,0]==x] ####### this step takes too long
###### now create sparse matrix for all data with
###### x value equal to the iterator
dic[x]=coo_matrix((data[bool], (row[bool],
col[bool])), shape=(1536, 32768)) ### this part ok
</code></pre>
<p>So the bool test that I marked down is the step that is taking up 90 percent of the time. This is due to the fact that my array is massive.
Ideally I want to just index my way into everything all at once. </p>
<p>Solutions?</p>
<p>Thanks!</p>
<p>Thanks! </p>
| 1 | 2016-10-11T07:56:37Z | 39,973,056 | <p>Here's an alternative approach -</p>
<pre><code>out_shp = (10,10) # (1536, 32768) for your actual case
out_dic = {}
for i in np.unique(arr[:,0]):
RCD = arr[arr[:,0] == i,1:]
out_dic[i] = coo_matrix((RCD[:,2],(RCD[:,0],RCD[:,1])), shape=out_shp)
</code></pre>
<p>Sample input, output -</p>
<pre><code>In [87]: arr
Out[87]:
array([[1, 3, 4, 5],
[0, 6, 7, 8],
[1, 7, 8, 7]])
In [88]: out_dic[0].toarray()
Out[88]:
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 8, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
In [89]: out_dic[1].toarray()
Out[89]:
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 5, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 7, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
</code></pre>
<hr>
<p>Here's another approach that sorts the array based on the first column before going into the loop and simply slices inside the loop. This is a meant as an approach with focus on performance as we would be doing less computations inside the loop as that seems to be the bottleneck. So, we would have another implementation like so -</p>
<pre><code>s_arr = arr[arr[:,0].argsort()] # Sorted array
unq,start_idx = np.unique(s_arr[:,0],return_index=1)
stop_idx = np.append(start_idx[1:],arr.shape[0])
out_shp = (10,10) # (1536, 32768) for your actual case
out_dic = {}
for i,u in enumerate(unq):
RCD = s_arr[start_idx[i]:stop_idx[i],1:] # Row-col-data
out_dic[u] = coo_matrix((RCD[:,2],(RCD[:,0],RCD[:,1])), shape=out_shp)
</code></pre>
| 0 | 2016-10-11T08:17:07Z | [
"python",
"numpy",
"indexing",
"sparse-matrix"
] |
Python xlsxwriter: How do I write a formula that references a different sheet | 39,972,739 | <p>I'm trying to add a excel file that includes a formula referencing
a different sheet.</p>
<p>In this example, I try to copy the word "world" from sheet 2 to sheet 1.</p>
<pre><code>import xlsxwriter
workbook = xlsxwriter.Workbook('hello.xlsx')
sheet1 = workbook.add_worksheet(name='Sheet 1')
sheet2 = workbook.add_worksheet(name='Sheet 2')
sheet2.write(2,2,'world')
sheet1.write(2,2,'hello')
sheet1.write_formula('D3', "='Sheet 2'.C3")
workbook.close()
</code></pre>
<p>The resulting xlsx file, when openened, displays the fomula in
lower case. The formula does not work when I press Ctrl+Shift+F9
to recalculate all formulas.</p>
<p>If I type the formula manually, it works.</p>
<p>Is is possible to reference others sheets when creating xlsxwriter excel files?</p>
<p>I'm using Open Office 5 to display the file. </p>
| 1 | 2016-10-11T07:57:14Z | 39,973,378 | <p>The formula needs to be in the US Excel syntax, like the following (note <code>!</code> not <code>.</code>):</p>
<pre><code>sheet1.write_formula('D3', "='Sheet 2'!C3")
</code></pre>
<p>See the <a href="https://xlsxwriter.readthedocs.io/working_with_formulas.html" rel="nofollow">Working with Formulas</a> section of the XlsxWriter docs.</p>
| 1 | 2016-10-11T08:37:23Z | [
"python",
"python-3.x",
"excel-formula",
"openoffice-calc",
"xlsxwriter"
] |
How to average over the output values of a function | 39,972,751 | <p>I am relatively new to python so I apologize for any unconventionality in my code.
I have a function which returns some values. I want to repeat this function n times and get the average over the output values for the n iterations (possibly without defining a new function). How can this be done? For example:</p>
<pre><code>def flip_coin(coins):
pr_head = 1
pr_tail = -1
options = (pr_head, pr_tail)
simulation = [[random.choice(options) for x in range(10)] for y in range(coins)]
rep = [i.count(1) for i in simulation]
m = min(rep)
ind_m = rep.index(m)
c_min = simulation[ind_m]
v_min = c_min.count(1) / 10
return v_min
for i in range(n):
flip_coin(coins)
#take average over(v_min)
</code></pre>
<p>However I cannot access 'v_min' outside of the function scope and when I iterate the function inside the function (with the exact for loop as above) I get the error:</p>
<pre><code>RecursionError: maximum recursion depth exceeded while calling a Python object.
</code></pre>
| -1 | 2016-10-11T07:58:29Z | 39,972,819 | <p>Is that how you want it, you need to assign the return value to a variable to access it later:</p>
<pre><code>for i in range(n):
v_min2 = flip_coin(coins)
print v_min2
</code></pre>
<p>If you want average of everytime you call the function, you can simply do:</p>
<pre><code>average_list = []
for i in range(10):
average_list.append((flip_coin(coins)))
print (sum(average_list)/len(average_list))
</code></pre>
| 1 | 2016-10-11T08:02:15Z | [
"python",
"iteration",
"average"
] |
How to average over the output values of a function | 39,972,751 | <p>I am relatively new to python so I apologize for any unconventionality in my code.
I have a function which returns some values. I want to repeat this function n times and get the average over the output values for the n iterations (possibly without defining a new function). How can this be done? For example:</p>
<pre><code>def flip_coin(coins):
pr_head = 1
pr_tail = -1
options = (pr_head, pr_tail)
simulation = [[random.choice(options) for x in range(10)] for y in range(coins)]
rep = [i.count(1) for i in simulation]
m = min(rep)
ind_m = rep.index(m)
c_min = simulation[ind_m]
v_min = c_min.count(1) / 10
return v_min
for i in range(n):
flip_coin(coins)
#take average over(v_min)
</code></pre>
<p>However I cannot access 'v_min' outside of the function scope and when I iterate the function inside the function (with the exact for loop as above) I get the error:</p>
<pre><code>RecursionError: maximum recursion depth exceeded while calling a Python object.
</code></pre>
| -1 | 2016-10-11T07:58:29Z | 39,973,058 | <p>You are not assigning function call result. First collect all function calls so we can calculate average on them</p>
<pre><code>v_min_list = [flip_coin(coins) for i in range(n)]
</code></pre>
<p>then we can find average with this answer <a href="http://stackoverflow.com/questions/9039961/finding-the-average-of-a-list#9040000">Finding the average of a list</a></p>
<pre><code>averag_v_min = sum(v_min_list) / float(len(v_min_list))
</code></pre>
| 0 | 2016-10-11T08:17:12Z | [
"python",
"iteration",
"average"
] |
Why is my function looping python | 39,972,771 | <p>Weird issue I know that a function is being called twice some how but I dont know where or why its happening.</p>
<p>Heres my code:</p>
<pre><code> 8 def getAccessSecretName():
9 access_key = raw_input("Enter Access Key: ")
10 secret_key = raw_input("Enter Secret Key: ")
11 yourName = raw_input("Enter your name: ")
12 print "Access Key: %s" % access_key
13 print "Secret Key: %s" % secret_key
14 print "Your full name is: %s" % yourName
15 with open (tfVariables,"w") as text_file:
16 text_file.writelines(['access_key = \"'+ access_key +'\"\nsecret_key = \"'+ secre t_key +'\"\n\n\n',
17 'amis = {\n',
18 ' ',
19 'us-west-1 = '+ usWest1ami +'\n',
20 ' ',
21 'us-west-1 = '+ usWest2ami +'\n',
22 ' ',
23 '}'])
24 return access_key, secret_key, yourName
69 def makeMainTF():
70 NameTag,mcGroupTag,mcIPTag = makeNameMCTag()
71 access_key, secret_key, yourName = getAccessSecretName()
72 with open (tfFileName,"w") as text_file:
73 text_file.writelines(['provider \"aws\" {\n',
74 ' ',
75 'access_key = \"${var.access_key}\"\n ',
76 ' ',
77 'secret_key = \"${var.secret_key}\"\n ',
78 ' ',
79 'region = \"${var.access_key}\"\n ',
80 '}\n\n\n',
81 'resource \"aws_instance\" \"example\" {\n',
82 ' ',
83 'ami = \"${lookup(var.amis, var.region) }\"\n',
84 ' ',
85 'instance_type = \"%s\" \n}' % instan ceType,
86 '\n\n\n\n',
87 'tags {\n',
88 ' ',
89 'Name = \"%s\"\n' % NameTag,
90 ' ',
91 'Multicast = \"%s,%s\"\n' % (mcGroupT ag,mcIPTag),
92 ' ',
93 #'Owner = \"%s\"' % " " % yourName,
94 'Owner = \"%s\"' % yourName,
95 '\n}\n\n\n'])
</code></pre>
<p>So here is what I expect to happen. When I run the code it will prompt the user for its access key, secret key and name. Then repeat it to the user once and write the information to a file. What happens when I call on both functions is this:</p>
<pre><code>Enter Access Key: key1
Enter Secret Key: secret1
Enter your name: chowpay
Access Key: key1
Secret Key: secret1
Your full name is: chowpay
newnumber = 68
Name Tag: vlslabs67
Multicast Tag: vlslabmc, 172.16.0.67
Enter Access Key: key2
Enter Secret Key: secret2
Enter your name: chowpay2
Access Key: key2
Secret Key: secret2
Your full name is: chowpay2
</code></pre>
<p>Note that it's prompting the user to enter The keys and their name twice. Which doesnt make sense as this is all I have used to call the function:</p>
<pre><code>getAccessSecretName()
makeMainTF()
</code></pre>
<p>Thanks!</p>
<hr>
<p>I've corrected the code above with the correct function in line 53, it is getAccessSecret<strong>Name</strong>() , not getAccessSecret()</p>
<p>Correction again for adding the wrong function makeTfVars was posted in the question but makeMainTF() was , what was suppose to be in the question.</p>
| -2 | 2016-10-11T07:59:41Z | 39,987,910 | <p>What I thought was a problem in the loop was a issue with how I thought variables in python get passed to other functions.</p>
<p>looks like doing this </p>
<pre><code>71: access_key, secret_key, yourName = getAccessSecretName()
</code></pre>
<p>Doesnt mean make ^ variable values available from the function of getAccessSecretName(). Dumb mistake by me. Instead it means re-run the function to get the values which caused the user to be asked questions again.</p>
<p>The "fix" is adding</p>
<pre><code> 10 def getAccessSecretName():
**11 global access_key, secret_key, yourName**
</code></pre>
<p>and removing </p>
<pre><code> 71: access_key, secret_key, yourName = getAccessSecretName()
</code></pre>
<p>This let me use my variables in other functions. Not sure if this is the right way to do it but it worked for me. Welcome to hear what a better way would be.</p>
<p>Thanks again</p>
| 0 | 2016-10-11T22:45:15Z | [
"python",
"loops"
] |
Python: Compare elements in two list by pair | 39,972,828 | <p>I am so sorry for asking so silly question.
So I have got two lists(columns) for instance:</p>
<pre><code>In:
a= [0.0,1.0,2.0,3.0,4.0]
b= [1.0,2.0,3.0,5.0,6.0]
zp = list(zip(a,b)) #And I zipped it for better view.
for i in zp:
print (i)
Out:
(0.0, 1.0)
(1.0, 2.0)
(2.0, 3.0)
(3.0, 5.0)
(4.0, 6.0)
</code></pre>
<p>I would like compare each i[1] with each i[0] in the next pair(tuple)
For example:</p>
<pre><code>1st pair i[1] = 1.0 compare with i[0] in 2nd
2nd pair i[0] = 1.0 compare with i[0] in 3rd
etc
</code></pre>
<p>I would like find difference in pair. </p>
<pre><code>If i[1] != i[0]
print this value
Answer is 5.0 & 4.0
</code></pre>
<p>Thank you for your attention </p>
| 0 | 2016-10-11T08:02:39Z | 39,972,887 | <p>The initial zip for better view is not completely necessary. </p>
<p>You could simply <code>zip</code> a slice of <code>a</code> starting from index 1 with <code>b</code>, and then compare the items using a <code>for</code> loop:</p>
<pre><code>a = [0.0,1.0,2.0,3.0,4.0]
b = [1.0,2.0,3.0,5.0,6.0]
for i, j in zip(a[1:], b):
if i != j:
print(j, i)
# 5.0, 4.0
</code></pre>
| 4 | 2016-10-11T08:07:10Z | [
"python",
"list",
"compare"
] |
Python: Compare elements in two list by pair | 39,972,828 | <p>I am so sorry for asking so silly question.
So I have got two lists(columns) for instance:</p>
<pre><code>In:
a= [0.0,1.0,2.0,3.0,4.0]
b= [1.0,2.0,3.0,5.0,6.0]
zp = list(zip(a,b)) #And I zipped it for better view.
for i in zp:
print (i)
Out:
(0.0, 1.0)
(1.0, 2.0)
(2.0, 3.0)
(3.0, 5.0)
(4.0, 6.0)
</code></pre>
<p>I would like compare each i[1] with each i[0] in the next pair(tuple)
For example:</p>
<pre><code>1st pair i[1] = 1.0 compare with i[0] in 2nd
2nd pair i[0] = 1.0 compare with i[0] in 3rd
etc
</code></pre>
<p>I would like find difference in pair. </p>
<pre><code>If i[1] != i[0]
print this value
Answer is 5.0 & 4.0
</code></pre>
<p>Thank you for your attention </p>
| 0 | 2016-10-11T08:02:39Z | 39,973,145 | <p>index variant without zip and enumerate</p>
<pre><code>a = [0.0,1.0,2.0,3.0,4.0]
b = [1.0,2.0,3.0,5.0,6.0]
for i in a:
if a.index(i) and i != b[a.index(i)-1]:
print "{0} > {1}".format(i, b[a.index(i)-1])
</code></pre>
| 1 | 2016-10-11T08:21:56Z | [
"python",
"list",
"compare"
] |
Python Pandas: Inconsistent behaviour of boolean indexing on a Series using the len() method | 39,972,874 | <p>I have a Series of strings and I need to apply boolean indexing using <code>len()</code> on it.</p>
<p>In one case it works, in another case it does not:</p>
<p>The working case is a <code>groupby</code> on a dataframe, followed by a <code>unique()</code> on the resulting Series and a <code>apply(str)</code> to change the resulting <code>numpy.ndarray</code> entries into strings:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'A':['a','a','a','a','b','b','b','b'],'B':[1,2,2,3,4,5,4,4]})
dg = df.groupby('A')['B'].unique().apply(str)
db = dg[len(dg) > 2]
</code></pre>
<p>This just works fine and yields the desired result:</p>
<pre><code>>>db
Out[119]: '[1 2 3]'
</code></pre>
<p>The following however throws <code>KeyError: True</code>:</p>
<pre><code>ss = pd.Series(['a','b','cc','dd','eeee','ff','ggg'])
ls = ss[len(ss) > 2]
</code></pre>
<p>Both objects <code>dg</code> and <code>ss</code> are just Series of Strings:</p>
<pre><code>>>type(dg)
Out[113]: pandas.core.series.Series
>>type(ss)
Out[114]: pandas.core.series.Series
>>type(dg['a'])
Out[115]: str
>>type(ss[0])
Out[116]: str
</code></pre>
<p>I'm following the syntax as described in the docs: <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing</a></p>
<p>I can see a potential conflict because <code>len(ss)</code> on its own returns the length of the Series itself and now that exact command is used for boolean indexing <code>ss[len(ss) > 2]</code>, but then I'd expect neither of the two examples to work.</p>
<p>Right now this behaviour seems inconsistent, unless I'm missing something obvious.</p>
| 1 | 2016-10-11T08:06:12Z | 39,972,902 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.len.html" rel="nofollow"><code>str.len</code></a>, because need length of each value of <code>Series</code>:</p>
<pre><code>ss = pd.Series(['a','b','cc','dd','eeee','ff','ggg'])
print (ss.str.len())
0 1
1 1
2 2
3 2
4 4
5 2
6 3
dtype: int64
print (ss.str.len() > 2)
0 False
1 False
2 False
3 False
4 True
5 False
6 True
dtype: bool
ls = ss[ss.str.len() > 2]
print (ls)
4 eeee
6 ggg
dtype: object
</code></pre>
<p>If use <code>len</code>, get length of <code>Series</code>:</p>
<pre><code>print (len(ss))
7
</code></pre>
<p>Another solution is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow"><code>apply</code></a> <code>len</code>:</p>
<pre><code>ss = pd.Series(['a','b','cc','dd','eeee','ff','ggg'])
ls = ss[ss.apply(len) > 2]
print (ls)
4 eeee
6 ggg
dtype: object
</code></pre>
<p>First script is wrong, you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow"><code>apply</code></a> <code>len</code> also:</p>
<pre><code>df = pd.DataFrame({'A':['a','a','a','a','b','b','b','b'],'B':[1,2,2,2,4,5,4,6]})
dg = df.groupby('A')['B'].unique()
print (dg)
A
a [1, 2]
b [4, 5, 6]
Name: B, dtype: object
db = dg[dg.apply(len) > 2]
print (db)
A
b [4, 5, 6]
Name: B, dtype: object
</code></pre>
<p>If cast list to <code>str</code>, you get another <code>len</code> (<code>length</code> of data + length of <code>[]</code> + length of whitespaces):</p>
<pre><code>dg = df.groupby('A')['B'].unique().apply(str)
print (dg)
A
a [1 2]
b [4 5 6]
Name: B, dtype: object
print (dg.apply(len))
A
a 5
b 7
Name: B, dtype: int64
</code></pre>
| 2 | 2016-10-11T08:07:45Z | [
"python",
"python-2.7",
"pandas"
] |
Using Scherrer equation for calculating the grain size | 39,973,073 | <p>I'm trying to calculate the grain size by Scherrer equation but I have stuck in FWHM. </p>
<pre><code>import numpy as np
#import math
k = 0.94
wave_length = 1.5406e-10
data = np.genfromtxt("G3.txt")
indice = np.argmax(data[:,1])
peak = (data[indice, :])
#D = (k*wave_length) / (beta*cos((math.radian(theta))
</code></pre>
<p><a href="http://i.stack.imgur.com/1l5Pq.png" rel="nofollow"><img src="http://i.stack.imgur.com/1l5Pq.png" alt="Corresponding graphs looks likes as in the picture"></a></p>
<p>Information: <a href="https://en.wikipedia.org/wiki/Scherrer_equation" rel="nofollow">Scherrer equation</a>, <a href="https://en.wikipedia.org/wiki/Full_width_at_half_maximum" rel="nofollow">Full width at half maximum</a>, <a href="http://stackoverflow.com/questions/29877427/python-find-fwhm-of-curve">Related question</a></p>
| 0 | 2016-10-11T08:18:07Z | 39,977,103 | <p>Here is a working example, assuming you have a normal distribution. I run this in a Jupyter console, so in case you don't, you have to skip the "magic line" (<code>%matplotlib notebook</code>) and add <code>plt.show()</code> at the very end.</p>
<pre><code>%matplotlib notebook
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
numb = 500 # data size
fwhm_in = 3 # set FWHM for the artificial data
sigma = fwhm_in/2/np.sqrt(2*np.log(2)) # calculate sigma
xval = np.linspace(-10, 10, numb) # calculate x and y values using the formula from Wikipedia (see link in question)
yval = (sigma*np.sqrt(2*np.pi))**(-1)*np.exp(-(xval)**2/(2*sigma**2))+np.random.normal(0, 0.03, numb)
def fitFunc(x, x0, sigm): # this defines the fit-function
return (sigm*np.sqrt(2*np.pi))**(-1)*np.exp(-(x-x0)**2/(2*sigm**2))
guess = (0.5, 2) # tell the code with which values it should start the iteration. Close but not equal to the real values
fitParams, fitCovariance = curve_fit(fitFunc, xval, yval, guess) # do the actual fit
print(fitParams)
print('FWHM_calc = {:.3f}'.format(fwhm_in))
fwhm_fit = 2*fitParams[1]*np.sqrt(2*np.log(2)) # calculate the FWHM from the fitted sigma ( = fitParams[1], since fitParams[0] is the offset x0)
print('FWHM_fit = {:.3f}'.format(fwhm_fit))
plt.plot(xval,yval, 'r.', label='data')
plt.plot(xval, fitFunc(xval, fitParams[0], fitParams[1]), 'k-', label='fit', linewidth = 3)
plt.grid(True)
plt.legend()
ax = plt.gca()
ax.axvline(fwhm_fit/2, color='b')
ax.axvline(-fwhm_fit/2, color='b')
</code></pre>
<p><a href="https://i.stack.imgur.com/hxaB9.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/hxaB9.jpg" alt="Example for the FWHM (blue vertical lines) in a normal distribution."></a></p>
| 3 | 2016-10-11T12:19:21Z | [
"python",
"numpy",
"physics"
] |
Using Scherrer equation for calculating the grain size | 39,973,073 | <p>I'm trying to calculate the grain size by Scherrer equation but I have stuck in FWHM. </p>
<pre><code>import numpy as np
#import math
k = 0.94
wave_length = 1.5406e-10
data = np.genfromtxt("G3.txt")
indice = np.argmax(data[:,1])
peak = (data[indice, :])
#D = (k*wave_length) / (beta*cos((math.radian(theta))
</code></pre>
<p><a href="http://i.stack.imgur.com/1l5Pq.png" rel="nofollow"><img src="http://i.stack.imgur.com/1l5Pq.png" alt="Corresponding graphs looks likes as in the picture"></a></p>
<p>Information: <a href="https://en.wikipedia.org/wiki/Scherrer_equation" rel="nofollow">Scherrer equation</a>, <a href="https://en.wikipedia.org/wiki/Full_width_at_half_maximum" rel="nofollow">Full width at half maximum</a>, <a href="http://stackoverflow.com/questions/29877427/python-find-fwhm-of-curve">Related question</a></p>
| 0 | 2016-10-11T08:18:07Z | 40,049,528 | <p>I'm sorry for sharing this as an answer but comments does not provide me upload a picture to clarify the problem. So I've illustrated the problem with an image below (BTW, I can't edit or delete my comments which I wrote reluctantly).
I got this graph when I run your code
<a href="https://i.stack.imgur.com/wyIVm.png" rel="nofollow"><img src="https://i.stack.imgur.com/wyIVm.png" alt="I got this graph when I run your code"></a></p>
<p><a href="https://i.stack.imgur.com/sp820.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/sp820.jpg" alt="This is the graph what I'm looking for"></a></p>
<p>This graph illustrates what I'm looking for</p>
| 0 | 2016-10-14T18:08:36Z | [
"python",
"numpy",
"physics"
] |
Using Scherrer equation for calculating the grain size | 39,973,073 | <p>I'm trying to calculate the grain size by Scherrer equation but I have stuck in FWHM. </p>
<pre><code>import numpy as np
#import math
k = 0.94
wave_length = 1.5406e-10
data = np.genfromtxt("G3.txt")
indice = np.argmax(data[:,1])
peak = (data[indice, :])
#D = (k*wave_length) / (beta*cos((math.radian(theta))
</code></pre>
<p><a href="http://i.stack.imgur.com/1l5Pq.png" rel="nofollow"><img src="http://i.stack.imgur.com/1l5Pq.png" alt="Corresponding graphs looks likes as in the picture"></a></p>
<p>Information: <a href="https://en.wikipedia.org/wiki/Scherrer_equation" rel="nofollow">Scherrer equation</a>, <a href="https://en.wikipedia.org/wiki/Full_width_at_half_maximum" rel="nofollow">Full width at half maximum</a>, <a href="http://stackoverflow.com/questions/29877427/python-find-fwhm-of-curve">Related question</a></p>
| 0 | 2016-10-11T08:18:07Z | 40,065,417 | <p>I don't know how to solve this problem in python (at least for this moment). So I made it in Matlab. </p>
<pre><code> clear all
clc
A = dlmread('YOUR DATAS'); %Firstly add to path
plot(A(:,1),A(:,2)) %Plotting the graph
hold on
min_peak = input('Just write a value that is higher than minimum peak values: ');
%This value must be between requested peaks and non-requested peaks (you can see this in graph)
[yval, yval_i] = findpeaks(A(:,2),'MinPeakHeight',min_peak); %Finding peaks
scatter(A(yval_i,1), yval); %Showing peaks
Beta = [];
xval = [];
for k = 1:size(yval_i,1) %Finding x values corresponding to y (peak) values
xval1 = A(yval_i(k),1);
xval = [xval xval1];
end
Theta = xval / 2;
for i = 1:size(yval,1) %Finding half of max. peak values
yval_i1 = yval_i(i,1);
while (yval(i,1))/2 < A(yval_i1+1,2)
yval_i1 = yval_i1+1;
end
yval_i2 = yval_i(i,1);
while (yval(i,1))/2 < A(yval_i2-1,2)
yval_i2 = yval_i2-1;
end
plot(A(yval_i2,1)*ones(size(A(:,2))), A(:,2));
plot(A(yval_i1,1)*ones(size(A(:,2))), A(:,2));
% hold on
% scatter(A(yval_i1,1),A(yval_i1,2))
% scatter(A(yval_i2,1),A(yval_i2,2))
B = abs(A(yval_i1,1)-A(yval_i2,1));
Beta = [Beta B];
end
Beta
K = 0.94;
Lambda = 1.5406e-10;
To = [];
for j = 1:size(Beta,2)
To1 = (K*Lambda)/(Beta(j)*cos(Theta(j)));
To = [To To1];
end
To = abs(To)
</code></pre>
| 0 | 2016-10-15T23:53:06Z | [
"python",
"numpy",
"physics"
] |
How to show warning using Python tornado | 39,973,273 | <p>Is there a way to show a warning to the user and just continue with the called function?</p>
<p>All I can find in tornado is the HTTPError. Is there anything like this to show a warning?</p>
<p>Current snippet:</p>
<pre><code>if warning_bool:
warning_text = "Warning! You can still continue though..."
raise HTTPError(status_code=400, reason=warning_text)
put_function()
</code></pre>
<p>This raises an Error and the function is not called.</p>
| 0 | 2016-10-11T08:31:22Z | 39,986,329 | <p>If you want to continue with your processing you will not want to raise an error. That has a number of effects depending on your setup. Typically raising an error will set the status to something other than 200, which probably isn't what you want. It will generally trip whatever exception logging you have (in our case it sends errors to sentry), and it will typically automatically roll back your database transactions.</p>
<p>If you just want to display a warning to a user because they did something "bad" but continue processing you will want another mechanism. I have two different ways I handle this situation depending on the context. Most of the time I display a message automatically on the next page load(after the post that had the warning) by setting a cookie and displaying it. What works for you will be different depending on how your app is set up. If your calls are all ajax calls you can have an object for returning warnings and other messages built into you ajax calls.</p>
<p>The other thing we do is that for some pages that are handling batch commands where there could be many warnings, then we have a special page that loads if there are warnings that knows how to handle a list of warnings.</p>
<p>Here is our code that sets and reads the warning message in Python. This is in our base controller class so that it is available in all controllers. You could also write the read part in javascript:</p>
<pre><code>def flash(self, msg, msg_type="info"):
self.flash_info = (msg, msg_type)
self.set_cookie('flash', base64.b64encode(bytes(json.dumps([msg, msg_type]), 'utf-8')))
def get_flash(self):
msg = None
msg_type = None
if hasattr(self, "flash_info"):
msg, msg_type = self.flash_info
else:
flash_msg = self.get_cookie('flash')
if flash_msg:
msg, msg_type = json.loads(base64.b64decode(flash_msg).decode('utf-8'))
self.clear_cookie('flash')
self.clear_cookie('flash')
return msg, msg_type
</code></pre>
| 1 | 2016-10-11T20:38:39Z | [
"python",
"tornado"
] |
Complicated python regex | 39,973,353 | <p>I have multiple lines like this:</p>
<pre><code>EWSR1{ENST00000397938}:r.1_1364_FLI1{ENST00000429175}:r.1046_3051
EML4{ENST00000318522}:r.1_929_EML4{ENST00000318522}:r.903+188_903+220_ALK{ENST00000389048}:r.4080_6220
FUS{ENST00000254108}:r.1_(608)_FUS{ENST00000254108}:r.(819)_937_DDIT3{ENST00000547303}:r.76_872
TCF3{ENST00000262965}:r.1_1795_ins27_PBX1{ENST00000420696}:r.454_6636
EML4{ENST00000318522}:r.?_ALK{ENST00000389048}:r.?
</code></pre>
<p>I need something like this as output:</p>
<p>For the first one:</p>
<pre><code>EWSR1 ENST00000397938 1 1364
FLI1 ENST00000429175 1046 3051
</code></pre>
<p>For second one:</p>
<pre><code>EML4 ENST00000318522 1 929
EML4 ENST00000318522 903+188 903+220
ALK ENST00000389048 4080 6220
</code></pre>
<p>Third one:</p>
<pre><code>FUS ENST00000254108 1 (608)
FUS ENST00000254108 (819) 937
DDIT3 ENST00000547303 76 872
</code></pre>
<p>4th one:</p>
<pre><code>TCF3 ENST00000262965 1 1795
ins27
PBX1 ENST00000420696 454 6636
</code></pre>
<p>5th one:</p>
<pre><code>EML4 ENST00000318522 ?
ALK ENST00000389048 ?
</code></pre>
<p>I have millions of lines, so i wanted to came up with a regex for this, however i was unable. I created a conditioned regex, but i am sure there is a much more elegant and easier way. Can someone show me a simpler way?</p>
<p>My solution now:</p>
<pre><code>import re
import sys
string = sys.argv[1]
if '+?' in string or '-?' in string or not "?" in string:
for i in re.findall('\w*?\{.*?\}:r\.[\(\)\?\+\-\d]*_[\(\)\?\+\-\d]*', string):
if 'ins' in i:
print(re.findall('ins[A-Za-z0-9]*', i)[0])
i = re.sub('ins[A-Za-z0-9]*', "", i)
print(i.lstrip('_').split('{')[0], re.findall('\{(.*?)\}', i.lstrip('_'))[0], " ".join(i.lstrip('_').split('r.')[-1].split('_')))
else:
for i in re.findall('\w*?\{.*?\}:r\.\?', string):
if 'ins' in i:
print(re.findall('ins[A-Za-z0-9]*', i)[0])
i = re.sub('ins[A-Za-z0-9]*', "", i)
print(i.lstrip('_').split('{')[0], re.findall('\{(.*?)\}', i.lstrip('_'))[0], " ".join(i.lstrip('_').split('r.')[-1].split('_')))
</code></pre>
| 2 | 2016-10-11T08:36:08Z | 39,973,649 | <p>First split on <code>(?<=\d|\)|\?)_(?=[a-z])</code> and you'll end up with the <em>records</em> separated, like this:</p>
<pre><code>EWSR1{ENST00000397938}:r.1_1364
FLI1{ENST00000429175}:r.1046_3051
EML4{ENST00000318522}:r.1_929
EML4{ENST00000318522}:r.903+188_903+220
ALK{ENST00000389048}:r.4080_6220
FUS{ENST00000254108}:r.1_(608)
FUS{ENST00000254108}:r.(819)_937
DDIT3{ENST00000547303}:r.76_872
TCF3{ENST00000262965}:r.1_1795
ins27
PBX1{ENST00000420696}:r.454_6636
EML4{ENST00000318522}:r.?
ALK{ENST00000389048}:r.?
</code></pre>
<p><a href="https://regex101.com/r/cu1WSu/7" rel="nofollow">See it here at regex101</a>.</p>
<p>Then replace the result again by <code>(\{|}:r\.|_)</code> with <code></code>, ending up like <a href="https://regex101.com/r/cu1WSu/9" rel="nofollow">here on regex101</a>.</p>
<p>This will give you</p>
<pre><code>EWSR1 ENST00000397938 1 1364
FLI1 ENST00000429175 1046 3051
EML4 ENST00000318522 1 929
EML4 ENST00000318522 903+188 903+220
ALK ENST00000389048 4080 6220
FUS ENST00000254108 1 (608)
FUS ENST00000254108 (819) 937
DDIT3 ENST00000547303 76 872
TCF3 ENST00000262965 1 1795
ins27
PBX1 ENST00000420696 454 6636
EML4 ENST00000318522 ?
ALK ENST00000389048 ?
</code></pre>
| 3 | 2016-10-11T08:55:33Z | [
"python",
"regex",
"python-3.x"
] |
Complicated python regex | 39,973,353 | <p>I have multiple lines like this:</p>
<pre><code>EWSR1{ENST00000397938}:r.1_1364_FLI1{ENST00000429175}:r.1046_3051
EML4{ENST00000318522}:r.1_929_EML4{ENST00000318522}:r.903+188_903+220_ALK{ENST00000389048}:r.4080_6220
FUS{ENST00000254108}:r.1_(608)_FUS{ENST00000254108}:r.(819)_937_DDIT3{ENST00000547303}:r.76_872
TCF3{ENST00000262965}:r.1_1795_ins27_PBX1{ENST00000420696}:r.454_6636
EML4{ENST00000318522}:r.?_ALK{ENST00000389048}:r.?
</code></pre>
<p>I need something like this as output:</p>
<p>For the first one:</p>
<pre><code>EWSR1 ENST00000397938 1 1364
FLI1 ENST00000429175 1046 3051
</code></pre>
<p>For second one:</p>
<pre><code>EML4 ENST00000318522 1 929
EML4 ENST00000318522 903+188 903+220
ALK ENST00000389048 4080 6220
</code></pre>
<p>Third one:</p>
<pre><code>FUS ENST00000254108 1 (608)
FUS ENST00000254108 (819) 937
DDIT3 ENST00000547303 76 872
</code></pre>
<p>4th one:</p>
<pre><code>TCF3 ENST00000262965 1 1795
ins27
PBX1 ENST00000420696 454 6636
</code></pre>
<p>5th one:</p>
<pre><code>EML4 ENST00000318522 ?
ALK ENST00000389048 ?
</code></pre>
<p>I have millions of lines, so i wanted to came up with a regex for this, however i was unable. I created a conditioned regex, but i am sure there is a much more elegant and easier way. Can someone show me a simpler way?</p>
<p>My solution now:</p>
<pre><code>import re
import sys
string = sys.argv[1]
if '+?' in string or '-?' in string or not "?" in string:
for i in re.findall('\w*?\{.*?\}:r\.[\(\)\?\+\-\d]*_[\(\)\?\+\-\d]*', string):
if 'ins' in i:
print(re.findall('ins[A-Za-z0-9]*', i)[0])
i = re.sub('ins[A-Za-z0-9]*', "", i)
print(i.lstrip('_').split('{')[0], re.findall('\{(.*?)\}', i.lstrip('_'))[0], " ".join(i.lstrip('_').split('r.')[-1].split('_')))
else:
for i in re.findall('\w*?\{.*?\}:r\.\?', string):
if 'ins' in i:
print(re.findall('ins[A-Za-z0-9]*', i)[0])
i = re.sub('ins[A-Za-z0-9]*', "", i)
print(i.lstrip('_').split('{')[0], re.findall('\{(.*?)\}', i.lstrip('_'))[0], " ".join(i.lstrip('_').split('r.')[-1].split('_')))
</code></pre>
| 2 | 2016-10-11T08:36:08Z | 39,974,363 | <p>Here is a one regex solution, that might not be so elegant, but working:</p>
<pre><code>((?<![^_])ins\d+)_|([a-zA-Z]+[0-9]*)\{([^{}]*)\}:r\.([-()?+\d]+)?(?:_([-()?+\d]+))?
</code></pre>
<p>See the <a href="https://regex101.com/r/21roQD/4" rel="nofollow">regex demo</a></p>
<p><em>Details</em>:</p>
<ul>
<li><code>((?<![^_])ins\d+)_</code> - Group 1 capturing <code>ins</code> (not preceded with a char other than <code>_</code>) with one or more digits after and then <code>_</code> </li>
<li><code>|</code> - or</li>
<li><code>([a-zA-Z]+[0-9]*)</code> - 1+ ASCII letters followed with 0+ digits (if they can be intermingled, use <code>\w*</code> instead of <code>[0-9]*</code>)</li>
<li><code>\{([^{}]*)\}</code> - a <code>{...}</code> substring with the contents (that can have no <code>{</code> nor <code>}</code>) captured into Group 2</li>
<li><code>:r\.</code> - literal char sequence <code>:r.</code></li>
<li><code>([-()?+\d]+)?</code> - an optional capturing group (ID 3) matching <code>-</code>, <code>(</code>, <code>)</code>, <code>?</code>, <code>+</code>, or a digit 1 or more times greedily</li>
<li><code>(?:_([-()?+\d]+))?</code> - an optional non-capturing group matching <code>_</code> and capturing into Group 4 the same subpattern as above.</li>
</ul>
<p><a href="https://ideone.com/GUDur7" rel="nofollow">Python demo</a>:</p>
<pre><code>import re
regex = r"((?<![^_])ins\d+)_|([a-zA-Z]+[0-9]*)\{([^{}]*)\}:r\.([-()?+\d]+)?(?:_([-()?+\d]+))?"
test = ["EWSR1{ENST00000397938}:r.1_1364_FLI1{ENST00000429175}:r.1046_3051",
"EML4{ENST00000318522}:r.1_929_EML4{ENST00000318522}:r.903+188_903+220_ALK{ENST00000389048}:r.4080_6220",
"FUS{ENST00000254108}:r.1_(608)_FUS{ENST00000254108}:r.(819)_937_DDIT3{ENST00000547303}:r.76_872",
"TCF3{ENST00000262965}:r.1_1795_ins27_PBX1{ENST00000420696}:r.454_6636",
"EML4{ENST00000318522}:r.?_ALK{ENST00000389048}:r.?"]
res = []
for s in test:
for match in re.finditer(regex, s):
tmp = []
for groupNum in range(0, len(match.groups())):
if match.group(groupNum+1):
tmp.append(match.group(groupNum+1))
res.append(tmp)
print(res)
</code></pre>
<p>Results:</p>
<pre><code>[
['EWSR1', 'ENST00000397938', '1', '1364'],
['FLI1', 'ENST00000429175', '1046', '3051'],
['EML4', 'ENST00000318522', '1', '929'],
['EML4', 'ENST00000318522', '903+188', '903+220'],
['ALK', 'ENST00000389048', '4080', '6220'],
['FUS', 'ENST00000254108', '1', '(608)'],
['FUS', 'ENST00000254108', '(819)', '937'],
['DDIT3', 'ENST00000547303', '76', '872'],
['TCF3', 'ENST00000262965', '1', '1795'],
['ins27'],
['PBX1', 'ENST00000420696', '454', '6636'],
['EML4', 'ENST00000318522', '?'],
['ALK', 'ENST00000389048', '?']
]
</code></pre>
| 3 | 2016-10-11T09:35:24Z | [
"python",
"regex",
"python-3.x"
] |
Complicated python regex | 39,973,353 | <p>I have multiple lines like this:</p>
<pre><code>EWSR1{ENST00000397938}:r.1_1364_FLI1{ENST00000429175}:r.1046_3051
EML4{ENST00000318522}:r.1_929_EML4{ENST00000318522}:r.903+188_903+220_ALK{ENST00000389048}:r.4080_6220
FUS{ENST00000254108}:r.1_(608)_FUS{ENST00000254108}:r.(819)_937_DDIT3{ENST00000547303}:r.76_872
TCF3{ENST00000262965}:r.1_1795_ins27_PBX1{ENST00000420696}:r.454_6636
EML4{ENST00000318522}:r.?_ALK{ENST00000389048}:r.?
</code></pre>
<p>I need something like this as output:</p>
<p>For the first one:</p>
<pre><code>EWSR1 ENST00000397938 1 1364
FLI1 ENST00000429175 1046 3051
</code></pre>
<p>For second one:</p>
<pre><code>EML4 ENST00000318522 1 929
EML4 ENST00000318522 903+188 903+220
ALK ENST00000389048 4080 6220
</code></pre>
<p>Third one:</p>
<pre><code>FUS ENST00000254108 1 (608)
FUS ENST00000254108 (819) 937
DDIT3 ENST00000547303 76 872
</code></pre>
<p>4th one:</p>
<pre><code>TCF3 ENST00000262965 1 1795
ins27
PBX1 ENST00000420696 454 6636
</code></pre>
<p>5th one:</p>
<pre><code>EML4 ENST00000318522 ?
ALK ENST00000389048 ?
</code></pre>
<p>I have millions of lines, so i wanted to came up with a regex for this, however i was unable. I created a conditioned regex, but i am sure there is a much more elegant and easier way. Can someone show me a simpler way?</p>
<p>My solution now:</p>
<pre><code>import re
import sys
string = sys.argv[1]
if '+?' in string or '-?' in string or not "?" in string:
for i in re.findall('\w*?\{.*?\}:r\.[\(\)\?\+\-\d]*_[\(\)\?\+\-\d]*', string):
if 'ins' in i:
print(re.findall('ins[A-Za-z0-9]*', i)[0])
i = re.sub('ins[A-Za-z0-9]*', "", i)
print(i.lstrip('_').split('{')[0], re.findall('\{(.*?)\}', i.lstrip('_'))[0], " ".join(i.lstrip('_').split('r.')[-1].split('_')))
else:
for i in re.findall('\w*?\{.*?\}:r\.\?', string):
if 'ins' in i:
print(re.findall('ins[A-Za-z0-9]*', i)[0])
i = re.sub('ins[A-Za-z0-9]*', "", i)
print(i.lstrip('_').split('{')[0], re.findall('\{(.*?)\}', i.lstrip('_'))[0], " ".join(i.lstrip('_').split('r.')[-1].split('_')))
</code></pre>
| 2 | 2016-10-11T08:36:08Z | 39,989,152 | <p>First split with "_(?=[a-zA-Z]".Then split whith "[}{:._r]"</p>
<pre><code>import re
with open('file.txt') as f:
for l in f:
print "\n".join(map(lambda x:" ".join(re.split(r'[}{:._r]',x)),re.split(r'_(?=[a-zA-Z])',l.strip('\n'))))+'\n'
</code></pre>
| 1 | 2016-10-12T01:27:11Z | [
"python",
"regex",
"python-3.x"
] |
How to pass a list of lists through a for loop in Python? | 39,973,360 | <p>I have a list of lists :</p>
<pre><code>sample = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']]
count = [[4,3],[4,2]]
correctionfactor = [[1.33, 1.5],[1.33,2]]
</code></pre>
<p>I calculate frequency of each character (pi), square it and then sum (and then I calculate het = 1 - sum). </p>
<pre><code>The desired output [[1,2],[1,2]] #NOTE: This is NOT the real values of expected output. I just need the real values to be in this format.
</code></pre>
<p>The problem: I do not how to pass the list of lists(sample, count) in this loop to extract the values needed. I previously passed only a list (eg <code>['TACT','TTTT'..]</code>) using this code. </p>
<ul>
<li>I suspect that I need to add a larger for loop, that indexes over each element in sample (i.e. indexes over <code>sample[0] = ['TTTT', 'CCCZ']</code> and <code>sample[1] = ['ATTA', 'CZZC']</code>. I am not sure how to incorporate that into the code.</li>
</ul>
<p>**
Code</p>
<pre><code>list_of_hets = []
for idx, element in enumerate(sample):
count_dict = {}
square_dict = {}
for base in list(element):
if base in count_dict:
count_dict[base] += 1
else:
count_dict[base] = 1
for allele in count_dict: #Calculate frequency of every character
square_freq = (count_dict[allele] / count[idx])**2 #Square the frequencies
square_dict[allele] = square_freq
pf = 0.0
for i in square_dict:
pf += square_dict[i] # pf --> pi^2 + pj^2...pn^2 #Sum the frequencies
het = 1-pf
list_of_hets.append(het)
print list_of_hets
"Failed" OUTPUT:
line 70, in <module>
square_freq = (count_dict[allele] / count[idx])**2
TypeError: unsupported operand type(s) for /: 'int' and 'list'er
</code></pre>
| 4 | 2016-10-11T08:36:43Z | 39,974,974 | <p>I'm not completely clear on how you want to handle the 'Z' items in your data, but this code replicates the output for the sample data in <a href="https://eval.in/658468" rel="nofollow">https://eval.in/658468</a></p>
<pre><code>from __future__ import division
bases = set('ACGT')
#sample = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']]
sample = [['ATTA', 'TTGA'], ['TTCA', 'TTTA']]
list_of_hets = []
for element in sample:
hets = []
for seq in element:
count_dict = {}
for base in seq:
if base in count_dict:
count_dict[base] += 1
else:
count_dict[base] = 1
print count_dict
#Calculate frequency of every character
count = sum(1 for u in seq if u in bases)
pf = sum((base / count) ** 2 for base in count_dict.values())
hets.append(1 - pf)
list_of_hets.append(hets)
print list_of_hets
</code></pre>
<p><strong>output</strong></p>
<pre><code>{'A': 2, 'T': 2}
{'A': 1, 'T': 2, 'G': 1}
{'A': 1, 'C': 1, 'T': 2}
{'A': 1, 'T': 3}
[[0.5, 0.625], [0.625, 0.375]]
</code></pre>
<p>This code could be simplified further by using a collections.Counter instead of the <code>count_dict</code>.</p>
<p>BTW, if the symbol that's not in 'ACGT' is <em>always</em> 'Z' then we can speed up the <code>count</code> calculation. Get rid of <code>bases = set('ACGT')</code> and change</p>
<pre><code>count = sum(1 for u in seq if u in bases)
</code></pre>
<p>to</p>
<pre><code>count = sum(1 for u in seq if u != 'Z')
</code></pre>
| 3 | 2016-10-11T10:10:30Z | [
"python",
"list",
"for-loop",
"division"
] |
Prime numbers in a given range using Sieve of Eratosthenes | 39,973,477 | <p>I am trying to print prime numbers less than 'n'.The code is below:</p>
<pre><code>def prime_numbers(n):
A=[1 for i in range(n+1)]
for i in range(2,int(sqrt(n))):
if A[i]==1:
for j in range(i*2,n,i):
A[j]=0
for i in range(n):
if A[i]:
print(i)
</code></pre>
<p>Output for</p>
<pre><code>prime_numbers(10)
</code></pre>
<p>is </p>
<pre><code>0
1
2
3
5
7
9
</code></pre>
<p>The program correctly prints for 100. What changes do I need to make?</p>
| 0 | 2016-10-11T08:43:34Z | 39,973,525 | <p>The end point in a <code>range()</code> is not included. Since <code>sqrt(10)</code> is <code>3.1623</code>, your <code>range()</code> loops to 2 and no further, and the multiples of 3 are not removed from your list. Your code works for 100, because it doesn't matter if you test for multiples 10 (those are already covered by 2 and 5).</p>
<p>The same issue applies to your other loops; if you want to include <code>n</code> itself as a candidate prime number you should also include it in the other ranges.</p>
<p>Note that you also want to ignore 0 and 1, those are not primes. You could add <code>A[0] = A[1] = False</code> at the top to make sure your last loop doesn't include those, or start your last loop at 2 rather than 0.</p>
<p>You want to <em>add one</em> to the floored square root to make sure it is tested for:</p>
<pre><code>for i in range(2, int(sqrt(n)) + 1):
</code></pre>
<p>I'd use booleans rather than <code>0</code> and <code>1</code>, by the way, just for clarity (there is not much of a performance or memory footprint difference here):</p>
<pre><code>def prime_numbers(n):
sieve = [True] * (n + 1) # create a list n elements long
for i in range(2, int(sqrt(n)) + 1):
if sieve[i]:
for j in range(i * 2, n + 1, i):
sieve[j] = False
for i in range(2, n + 1):
if sieve[i]:
print(i)
</code></pre>
<p>I used <code>[..] * (n + 1)</code> to create a list of <code>n</code> items (plus 0); this produces a list with <code>n</code> shallow copies of the contents of the left operand. That's faster than a list comprehension, and the shared references are fine since <code>True</code> is a singleton in Python.</p>
<p>Demo:</p>
<pre><code>>>> prime_numbers(31)
2
3
5
7
11
13
17
19
23
29
31
</code></pre>
<p>Note that 31 is included there; your code would have resulted in incorrect output as you'd have left in all the multiples of 5.</p>
| 2 | 2016-10-11T08:46:53Z | [
"python",
"python-3.x",
"primes"
] |
python: how to get list length in list generator expression? | 39,973,542 | <p>Maybe like this (just a pseudocode) </p>
<pre><code>li = [1,2,3,4,5,6]
a = [d for d in li if self.length<3]
print a
[1,2]
</code></pre>
<p>What is a pythonic way to do that thing? </p>
| -1 | 2016-10-11T08:48:53Z | 39,973,729 | <p>You can use <code>itertools.count()</code> to keep track of how many elements you have used:</p>
<pre><code>from itertools import count
li = [1,2,3,4,5,6]
c = count(1) # initialize to 1
a = [d for d in li if next(c) < 3] # everytime you add an element
print (a) # in the comprehension `c` is incremented
</code></pre>
<p>That keeps track of the elements added to the list, hence the length of the list which gives:</p>
<pre><code>[1, 2]
</code></pre>
<p>as expected with length 2.</p>
<p><strong>EDITED:</strong> More easier way, with <code>enumerate</code>:</p>
<pre><code>a = [d for idx, d in enumerate(li) if idx < 2]
</code></pre>
| 3 | 2016-10-11T08:59:35Z | [
"python"
] |
Python IDLE/Terminal return back after error | 39,973,597 | <p>When reading a book or just coding on terminal/IDLE it's common to make typo, forgot brace or comma etc. After I got error and all what I wrote before is lost.
Then I have to write down code again..
Is there any way/option to return back all what write before and just edit mistake and continue to code?</p>
| 1 | 2016-10-11T08:52:02Z | 39,973,715 | <p>In Idle (at least my version, Python 2.7.10 on windows), you can simply copy paste your code. In the python interpreter, you can't afaik, however you can use the up/down arrow keys to recall lines you previously "submitted" (i.e. typed and pressed enter).</p>
| 0 | 2016-10-11T08:58:46Z | [
"python",
"terminal",
"edit",
"python-idle",
"undo"
] |
Python IDLE/Terminal return back after error | 39,973,597 | <p>When reading a book or just coding on terminal/IDLE it's common to make typo, forgot brace or comma etc. After I got error and all what I wrote before is lost.
Then I have to write down code again..
Is there any way/option to return back all what write before and just edit mistake and continue to code?</p>
| 1 | 2016-10-11T08:52:02Z | 39,974,277 | <p>If I understood correctly, IDLE is a GUI (graphical user interface - a visual representation of a program rather just through text) made to have a bit more features for programming in Python. You can use IDLE interactively, like in Terminal (a.k.a command line), or use it to write your script rather than in a separate text editor. Then once you save your script/program you can do neat things like run it directly from IDLE. There's nothing more special about the Terminal, you just have to do some more work. </p>
<p>Furthermore, all the code you have written on your GUI is on the cache memory which is used in system to store information recently accessed by a processor. So, I suggest you write again your code you can't recover them without saving.
To avoid these kind of problems use <strong>Git</strong>! </p>
<p>Git is a version control system that is used for software development and other version control tasks. </p>
| 0 | 2016-10-11T09:31:27Z | [
"python",
"terminal",
"edit",
"python-idle",
"undo"
] |
Python IDLE/Terminal return back after error | 39,973,597 | <p>When reading a book or just coding on terminal/IDLE it's common to make typo, forgot brace or comma etc. After I got error and all what I wrote before is lost.
Then I have to write down code again..
Is there any way/option to return back all what write before and just edit mistake and continue to code?</p>
| 1 | 2016-10-11T08:52:02Z | 39,990,408 | <p>IDLE's Shell window is statement rather that line oriented. One can edit any line of a statement before submitting it for execution. After executing, one may recall any statement by either a) placing the cursor anywhere on the statement and hitting Enter, or b) using the history-next and history-prev actions. On Windows, these are bound, by default, to Alt-p and Alt-p. To check on your installation, Select Options => IDLE preferences on the menu. In the dialog, select the Keys tab. Under Custom Key Bindings, find the 'histor-xyz' actions in the alphabetical list.</p>
<p>For short, one-off scripts, I have a scratch file called tem.py. Since I use it often, it is usually accessible via File => Recent files.</p>
| 0 | 2016-10-12T04:12:57Z | [
"python",
"terminal",
"edit",
"python-idle",
"undo"
] |
Python socket programming and LED interfacing | 39,973,653 | <p>I'm trying to write socket programming in python. Whenever client sends message to server, LED should start blinking.
I'm running server program on Raspberry pi and client on PC.</p>
<p>Here is the code of server which is running on my Pi.</p>
<pre><code>#!/usr/bin/python # This is server.py file
import socket # Import socket module
import time
import RPi.GPIO as GPIO # Import GPIO library
GPIO.setmode(GPIO.BOARD) # Use board pin numbering
GPIO.setup(11, GPIO.OUT) # Setup GPIO Pin 11 to OUT
GPIO.output(11,False) # Init Led off
def led_blink():
while 1:
print "got msg" # Debug msg
GPIO.output(11,True) # Turn on Led
time.sleep(1) # Wait for one second
GPIO.output(11,False) # Turn off Led
time.sleep(1) # Wait for one second
GPIO.cleanup()
s = socket.socket() # Create a socket object
host = "192.168.0.106" # Get local machine name
port = 12345 # Port
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
msg = c.recv(1024)
msg1 = 10
if msg == msg1:
led_blink()
print msg
c.close()
</code></pre>
<p>Here is the code of client which is running on my PC.</p>
<pre><code>#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = "192.168.0.106" # Get local machine name
port = 12345 # port
s.connect((host, port))
s.send('10')
s.close
</code></pre>
<p>I'm able to receive the message from client, But not able to blink the LED.
Sorry I'm new to coding. I've pretty good knowledge in hardware but not in software.
Please help me.</p>
| 2 | 2016-10-11T08:55:40Z | 39,974,480 | <p>Try this on your PC or Raspberry and then edit accordingly:</p>
<pre><code>#!/usr/bin/python # This is server.py file
import socket # Import socket module
def led_blink(msg):
print "got msg", msg # Debug msg
s = socket.socket() # Create a socket object
host = "127.0.0.1" # Get local machine name
port = 12345 # Port
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print "Listening"
c, addr = s.accept() # Establish connection with client.
while True:
msg = c.recv(1024)
print 'Got connection from', addr
if msg == "Exit":
break
led_blink(msg)
c.close()
</code></pre>
<p>and:</p>
<pre><code>#!/usr/bin/python # This is client.py file
import socket, time # Import socket module
s = socket.socket() # Create a socket object
host = "127.0.0.1" # Get local machine name
port = 12345 # port
s.connect((host, port))
x=0
for x in range(10):
s.send('Message_'+str(x))
print x
time.sleep(2)
s.send('Exit')
s.close
</code></pre>
<p>Note that I am using both the server and client on the same machine 127.0.0.1 and removed the GPIO bits as I don't have them available.</p>
| 1 | 2016-10-11T09:42:20Z | [
"python",
"raspberry-pi2"
] |
Python socket programming and LED interfacing | 39,973,653 | <p>I'm trying to write socket programming in python. Whenever client sends message to server, LED should start blinking.
I'm running server program on Raspberry pi and client on PC.</p>
<p>Here is the code of server which is running on my Pi.</p>
<pre><code>#!/usr/bin/python # This is server.py file
import socket # Import socket module
import time
import RPi.GPIO as GPIO # Import GPIO library
GPIO.setmode(GPIO.BOARD) # Use board pin numbering
GPIO.setup(11, GPIO.OUT) # Setup GPIO Pin 11 to OUT
GPIO.output(11,False) # Init Led off
def led_blink():
while 1:
print "got msg" # Debug msg
GPIO.output(11,True) # Turn on Led
time.sleep(1) # Wait for one second
GPIO.output(11,False) # Turn off Led
time.sleep(1) # Wait for one second
GPIO.cleanup()
s = socket.socket() # Create a socket object
host = "192.168.0.106" # Get local machine name
port = 12345 # Port
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
msg = c.recv(1024)
msg1 = 10
if msg == msg1:
led_blink()
print msg
c.close()
</code></pre>
<p>Here is the code of client which is running on my PC.</p>
<pre><code>#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = "192.168.0.106" # Get local machine name
port = 12345 # port
s.connect((host, port))
s.send('10')
s.close
</code></pre>
<p>I'm able to receive the message from client, But not able to blink the LED.
Sorry I'm new to coding. I've pretty good knowledge in hardware but not in software.
Please help me.</p>
| 2 | 2016-10-11T08:55:40Z | 39,974,543 | <p>You are comparing a string <code>"10"</code> with a number <code>10</code>. Change your server code to : </p>
<pre><code>msg1 = "10"
</code></pre>
| 0 | 2016-10-11T09:45:31Z | [
"python",
"raspberry-pi2"
] |
Name Error: name 'QFileDialog' is not defined | 39,973,665 | <p>I am working on coursework for computer science and can't work out why the piece of code isn't working. I am trying to connect a button that I've created in PyQt4 so that when it is pressed it shows a directory dialogue:</p>
<pre><code>self.Browse_Button_1 = QtGui.QToolButton(self.tab)
self.Browse_Button_1.setGeometry(QtCore.QRect(360, 30, 61, 20))
self.Browse_Button_1.setObjectName(_fromUtf8("Browse_Button_1"))
file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
self.Browse_Button_1.clicked.connect(self, file)
</code></pre>
<p>However every time I run the program I just get this error:</p>
<pre><code>Traceback (most recent call last):
File "D:\NEA Project\NEA_UI.py", line 194, in <module>
ui = Ui_Dialog()
File "D:\NEA Project\NEA_UI.py", line 30, in __init__
self.setupUi(self)
File "D:\NEA Project\NEA_UI.py", line 55, in setupUi
file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
NameError: name 'QFileDialog' is not defined
</code></pre>
<p>Any help with the problem would be greatly appreciated.</p>
| 1 | 2016-10-11T08:56:25Z | 39,974,332 | <p><code>QFileDialog</code> is in the <a href="http://doc.qt.io/qt-4.8/qfiledialog.html" rel="nofollow">QtGui module</a>, so you need to append that to beginning of your line, e.g.:</p>
<pre><code>file = str(QtGui.QFileDialog.getExistingDirectory(self, "Select Directory"))
</code></pre>
<p>Alternatively, if you want to use <code>QFileDialog</code> without the <code>QtGui</code> in front, you need to import it from the module (at the top of your file), with: </p>
<pre><code>from PyQt4.QtGui import QFileDialog
</code></pre>
<p>Or for Qt5 (note that in Qt5, <code>QFileDialog</code> moved to the <code>QtWidgets</code> module):</p>
<pre><code>from PyQt5.QtWidgets import QFileDialog
</code></pre>
| 1 | 2016-10-11T09:34:00Z | [
"python",
"pyqt",
"qfiledialog"
] |
How do I run two indefinite loops simultaneously, while also changing variables within them? | 39,973,911 | <p>I'm trying to write a script in Python that records a stream of an IP camera in realtime. It only keeps about a minute worth of recording, constantly overwriting the same files. Whenever an external sensor is triggered I want a variable to be set (event variable) which merges the recording with an extra 30 seconds it records after the sensor is triggered. The combined 90 seconds are then saved as the date and time for later review.</p>
<p>The idea was to have 2 indefinite while loops, the first containing both the real time recording and the event. The second one would constantly read input and activate the 'event' function. Initially I though I could just have a software version of the hardware interrupt I've learned before, though after some research it seems that's only for exceptions. I'm currently using TkInter, simulating the external input with keypresses.</p>
<p>When I tried it out the input wouldn't cause the event to be triggered. So my question is: How do I run the two indefinite loops simultaneously, while also having the input loop change variables in the main loop so that the 'event' can actually occur in real-time? </p>
<p>Since I'm using ffmpeg to record the stream, once the command is called to record it can't be stopped, but I want the event variable to be changed as soon as possible.</p>
<p>I've looked at several similar questions regarding multiple loops, and have tried multiprocessing(though this only seems to be used for performance, which is not that important here), making two separate files(not sure how to have them work together) and lastly, threads. None of these seem to work in my situation as I can't get them running in the way that I want.</p>
<p>Here is my latest attempt, using threads:</p>
<pre><code>i = 0
event = False
aboutToQuit = False
someVar = 'Event Deactivated'
lastVar = False
def process(frame):
print "Thread"
i = 0
frame = frame
frame.bind("<space>", switch)
frame.bind("<Escape>", exit)
frame.pack()
frame.focus_set()
def switch(eventl):
print(['Activating','Deactivating'][event])
event = eventl
event = not(event)
def exit(eventl):
print'Exiting Application'
global aboutToQuit
#aboutToQuit = True
root.destroy()
print("the imported file is", tkinter.__file__)
def GetTime(): #function opens a script which saves the final merged file as date and time.
time = datetime.datetime.now()
subprocess.call("./GetTime.sh", shell = True)
return (time)
def main(root):
global event, aboutToQuit, someVar,lastVar
while (not aboutToQuit):
root.update() # always process new events
if event == False:
someVar = 'Event Deactivated'
subprocess.call(Last30S_Command) #records last 30 seconds overwriting itself.
print "Merge now"
subprocess.call(Merge_Command) #merges last 30 seconds with the old 30 seconds
print "Shift now"
subprocess.call(Shift_Command) #copies the last30s recording to the old 30 seconds, overwriting it.
if lastVar == True: #Triggers only when lastVar state changes
print someVar
lastVar = False
time.sleep(.1)
if event == True:
someVar = 'Event Activated'
print"Record Event"
subprocess.call(EventRecord_Command) #records 30 seconds after event is triggered.
print"EventMerge Now"
subprocess.call(EventMerge_Command) # merges the 1 minute recording of Merge_Command with 30 seconds of EventRecord_Command
if lastVar == False:
print someVar
lastVar = True
time.sleep(.1)
GetTime() #Saves 90 seconds of EventMerge_Command as date and time.
subprocess.call(EventShift_Command) #Copies EventRecord file to the old 30 second recording, overwriting it
if aboutToQuit:
break
if __name__ == "__main__":
root = Tk()
frame = Frame(root, width=100, height=100)
# maintthread = threading.Thread(target=main(root))
# inputthread = threading.Thread(target=process(frame))
# inputthread.daemon = True
# inputthread.start()
# maintthread.daemon = True
# maintthread.start()
# maintthread.join()
Process(target=process(frame)).start()
Process(target=main(root)).start()
print "MainLoop"
</code></pre>
| 1 | 2016-10-11T09:09:35Z | 39,975,189 | <p>Two processes won't share data, so each process will contain a copy of those global variables, which won't work for you.</p>
<p>The best bet is either threading or co-routines(gevent). I"m assuming your logic is -> record 30 seconds, check if event triggered, if so, record another 30 seconds and merge. i.e. I"m assuming you don't need to stop recording as soon as the event is triggered.</p>
| 0 | 2016-10-11T10:22:07Z | [
"python",
"multithreading",
"ffmpeg"
] |
argparse: let the same required argument be positional OR optional | 39,974,093 | <p>I would like to have a required command line argument passed as a positional argument or an optional argument. For example, I would like the same action be performed from any of the following invocations:</p>
<pre><code>prog 10
prog -10
prog -n 10
prog --num 10
</code></pre>
<p>Is this possible with argparse?</p>
| 1 | 2016-10-11T09:20:55Z | 39,982,371 | <p>With a mutually exclusive group I can create a reasonable approximation:</p>
<p>In an interactive session:</p>
<pre><code>In [10]: parser=argparse.ArgumentParser()
In [11]: grp=parser.add_mutually_exclusive_group(required=True)
In [12]: a=grp.add_argument('pos',nargs='?',type=int,default=0)
In [13]: b=grp.add_argument('-n','--num')
</code></pre>
<p><code>grp</code> can contain any number of optionals, and one optional positional. I chose a different <code>type</code> for the positional just a highlight the difference.</p>
<p>Just the positional value:</p>
<pre><code>In [14]: parser.parse_args(['10'])
Out[14]: Namespace(num=None, pos=10)
</code></pre>
<p>Various forms of the optional:</p>
<pre><code>In [16]: parser.parse_args(['-n10'])
Out[16]: Namespace(num='10', pos=0)
In [17]: parser.parse_args(['--num=10'])
Out[17]: Namespace(num='10', pos=0)
In [18]: parser.parse_args(['--num','10'])
Out[18]: Namespace(num='10', pos=0)
</code></pre>
<p>test the group exclusivity</p>
<pre><code>In [25]: parser.parse_args(['--num=20','10'])
usage: ipython3 [-h] [-n NUM] [pos]
ipython3: error: argument pos: not allowed with argument -n/--num
</code></pre>
<p>and group required:</p>
<pre><code>In [26]: parser.parse_args([])
usage: ipython3 [-h] [-n NUM] [pos]
ipython3: error: one of the arguments pos -n/--num is required
</code></pre>
<p>I experimented with giving the positional the same <code>dest</code> as the optional - so both would write to <code>num</code>. But this results in the positional over writing the <code>dest</code> with its default (I can add details if needed)</p>
<pre><code>In [19]: a.dest
Out[19]: 'pos'
In [20]: a.dest='num'
In [21]: parser.parse_args(['--num','10'])
Out[21]: Namespace(num=0)
</code></pre>
<p>Post parsing code will have to handle the <code>args.pos</code> and <code>args.num</code> values in what ever way makes sense.</p>
<p>The <code>'-10</code>' input is impossible to handle. Well, I could define:</p>
<pre><code>parser.add_argument('-1')
</code></pre>
<p>but the result is probably not what you want:</p>
<pre><code>In [31]: parser.parse_args(['--num=20','-12'])
Out[31]: Namespace(1='2', num='20', pos=0)
</code></pre>
<p>Overall this requirement makes things unnecessarily difficult for you the programmer.</p>
| 0 | 2016-10-11T16:41:27Z | [
"python",
"argparse"
] |
Commas in BeautifulSoup csv | 39,974,116 | <p>I'm trying to output some web scraped information to a csv. When I print it to the screen it comes out as I expect but when I output to a csv it has commas between every character. I'm being dumb, but what am I missing?</p>
<p>Here's my relevant python code:</p>
<pre><code>list_of_rows = []
for hotel in hotels:
for row in hotel.findAll('div', attrs={'class': 'listing_title'}):
list_of_rows.append(row.find('a').text.replace('\nspb;', ''))
print(list_of_rows)
outfile = open("./hotels.csv", "wb")
writer = csv.writer(outfile)
writer.writerows(list_of_rows)
outfile.close()
</code></pre>
<p><strong>EDIT: Added example output</strong></p>
<p>When printed, list_of_rows comes out like this:</p>
<blockquote>
<p>[u"130 Queen's Gate", u'Hotel 41', u'Egerton House Hotel', u'The
Milestone Hotel', u'The Beaumont', u'COMO The Halkin', u'Taj 51
Buckingham Gate Suites and Residences', u'The Montague on The
Gardens', u'The Goring', u'Haymarket Hotel', u'Amba Hotel Charing
Cross', u'Rosewood London', u'Covent Garden Hotel', u'The Connaught',
u'The Chesterfield Mayfair', u'The Montcalm London Marble Arch',
u'Corinthia Hotel London', u'The Soho Hotel', u'Four Seasons Hotel
London at Park Lane', u'The Nadler Soho', u'Charlotte Street Hotel',
u'The Ritz London', u'The Nadler Victoria', u'Bulgari Hotel, London',
u"Brown's Hotel", u'The Arch London', u'The Piccadilly London West
End', u'The Stafford London', u'Ham Yard Hotel', u'Sofitel London St
James', u'Staybridge Suites London - Vauxhall']</p>
</blockquote>
<p>But when sent to a csv there is a comma between each letter/space.</p>
| 1 | 2016-10-11T09:22:09Z | 39,974,571 | <p>You should supply the data as a nested list, where each sublist represents a single row. </p>
<pre><code>data_mod = [[item] for item in list_of_rows]
with open("./hotels.csv", "wb") as outfile:
writer = csv.writer(outfile)
for row in data_mod:
writer.writerow(row)
# With writerows() being equivalent to the for loop + writerow()
</code></pre>
| 0 | 2016-10-11T09:46:50Z | [
"python",
"csv",
"beautifulsoup"
] |
py-elasticsearch stop printing errors | 39,974,132 | <p>I am using a py-elasticsearch to query elasticsearch:</p>
<pre><code>try:
res = es.get(index='unique_names', doc_type='name', id=token, ignore=['404'])
except elasticsearch.exceptions.NotFoundError:
continue
</code></pre>
<p>As you can see I use an exception for if the index does not exist, however the errors still get printed to the terminal like this:</p>
<blockquote>
<p>GET /unique_names/name/%E4%BD%8F%E6%B0%91%E3%82%89%E9%81%BF%E9%9B%A3
[status:404 request:0.000s] GET
/unique_names/name/%E6%95%91%E5%8A%A9%E6%9C%AC%E6%A0%BC%E5%8C%96
[status:404 request:0.000s] GET /unique_names/name/%E3%80%81
[status:404 request:0.000s] GET
/unique_names/name/%E5%81%9C%E9%9B%BB%E3%82%82 [status:404
request:0.000s] GET /unique_names/name/%E3%80%82
[status:404 request:0.000s]</p>
</blockquote>
<p>I would like it to not print anything, because my terminal gets flooded. </p>
| 0 | 2016-10-11T09:23:09Z | 39,974,337 | <p>The reason this gets printed out is because of <a href="https://github.com/elastic/elasticsearch-py/blob/d4efb81b0695f3d9f64784a35891b732823a9c32/elasticsearch/connection/base.py#L64-L67" rel="nofollow">these lines</a> in the <code>base.py</code> code.</p>
<p>Basically, you're ignoring 404 status codes, so the request gets logged as if it had succeeded.</p>
<p>If you want to get rid of those lines, you need to increase the logging level to WARN instead of INFO.</p>
| 1 | 2016-10-11T09:34:18Z | [
"python",
"python-3.x",
"elasticsearch",
"pyelasticsearch"
] |
Fetching data from Microsoft Access database using SELECT QUERY WITH WHERE CLAUSE in python | 39,974,214 | <pre><code>from tkinter import *
lg = Tk()
lg.state('zoomed')
def view():
cus = accno.get()
dis = [cus]
print(dis)
import pypyodbc
con=pypyodbc.win_connect_mdb("D:\\customer_details.mdb")
cur = con.cursor()
q = "select * from cus_details where cus_id = '" + cus + "' "
cur.execute(q,dis)
result=cur.fetchall()
Label(lg,text="",font = "Calibri 12 bold",width=2).grid(row=1,column=1)
Label(lg,text="",font = "Calibri 12",width=2).grid(row=2,column=1)
Label(lg,text="",font = "Calibri 12",width=2).grid(row=3,column=1)
Label(lg,text="",font = "Calibri 12",width=2).grid(row=4,column=1)
Label(lg,text="",font = "Calibri 12",width=2).grid(row=5,column=1)
Label(lg,text="",font = "Calibri 12",width=2).grid(row=6,column=1)
Label(lg,text="",font = "Calibri 12",width=2).grid(row=7,column=1)
Label(lg,text="",font = "Calibri 12",width=10).grid(row=8,column=0)
Label(lg,text="",font = "Calibri 12",width=10).grid(row=9,column=1)
Label(lg,text="",font = "Calibri 12",width=10).grid(row=9,column=2)
Label(lg,text="Customer ID",font = "Calibri 12",width=5).grid(row=9,column=3)
Label(lg,text="First Name",font = "Calibri 12",width=20).grid(row=9,column=4)
Label(lg,text="Last Name",font = "Calibri 12",width=15).grid(row=9,column=5)
Label(lg,text="Address",font = "Calibri 12",width=10).grid(row=9,column=6)
Label(lg,text="ID Proof",font = "Calibri 12",width=15).grid(row=9,column=7)
Label(lg,text="A/c No",font = "Calibri 12",width=15).grid(row=9,column=8)
Label(lg,text="A/c Type",font = "Calibri 12",width=15).grid(row=9,column=9)
Label(lg,text="Initial Deposit",font = "Calibri ` ` `12",width=15).grid(row=9,column=10)
r=10
for row in result:
Label(lg,text="",font = "Calibri 12",width=10).grid(row=r,column=0)
Label(lg,text="",font = "Calibri 12",width=10).grid(row=r,column=2)
Label(lg,text=row[0],font = "Calibri 12",width=5).grid(row=r,column=3)
Label(lg,text=row[1],font = "Calibri 12",width=10).grid(row=r,column=4)
Label(lg,text=row[2],font = "Calibri 12",width=20).grid(row=r,column=5)
Label(lg,text=row[3],font = "Calibri 12",width=10).grid(row=r,column=6)
Label(lg,text=row[4],font = "Calibri 12",width=10).grid(row=r,column=7)
Label(lg,text=row[5],font = "Calibri 12",width=10).grid(row=r,column=8)
Label(lg,text=row[6],font = "Calibri 12",width=10).grid(row=r,column=9)
Label(lg,text=row[7],font = "Calibri 12",width=10).grid(row=r,column=10)
r=r+1
con.close()
tit = Label(lg,text="BANK MANAGEMENT SYSTEM",font = "Batang 29 `` bold",fg = "blue")
` ` tit1 = Label(lg,text="Account Detail",font = "Calibri 15 bold")
`` la1 = Label(lg,text="Account No",font = "Calibri 12")
`` accno = Entry(lg,width=35)
`` but = Button(lg,text="Delete",bg = "green",width=11,height=1,fg =
`` "white",font = "Calibri 10 bold")
`` but1 = Button(lg,text="Cancel",bg = "green",width=11,height=1,fg =
`` "white",font = "Calibri 10 bold")
`` but2 = Button(lg,text="Verify",bg = "green",width=11,height=1,fg =
`` "white",font = "Calibri 10 bold",command = view)
`` tit.place(x=600,y=10)
tit1.place(x=600,y=70)
la1.place(x=400,y=150)
accno.place(x=650,y=150)
but2.place(x=870,y=145)
lg.mainloop()
</code></pre>
<p>I get the following error:</p>
<blockquote>
<pre><code> ['1']
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "C:\Python34\pypyodbc-1.3.3\customer_details.py", line 15, in view
cur.execute(q,dis)
File "C:\Python34\pypyodbc-1.3.3\pypyodbc.py", line 1470, in execute
self._BindParams(param_types)
File "C:\Python34\pypyodbc-1.3.3\pypyodbc.py", line 1263, in
_BindParams
raise ProgrammingError('HY000',error_desc)
pypyodbc.ProgrammingError: ('HY000', 'The SQL contains 0 parameter markers, `` but 1 parameters were supplied')
</code></pre>
</blockquote>
<p>I am facing a problem in fetching and displaying the data in a grid.</p>
| 0 | 2016-10-11T09:27:29Z | 39,975,075 | <p>SQL injection is a serious issue and can ultimately destroy your database. The classic to remember is <a href="https://xkcd.com/327/" rel="nofollow">Bobby Tables</a>. For this reason, it's important to build your queries properly to prevent this; that requires some mechanism to "escape" an input so that it cannot be interpreted as a command in itself. </p>
<p><code>q = "select * from cus_details where cus_id = '" + cus + "' "</code><br></p>
<p>This query does not escape anything, since you simply throw the value of <code>cus</code> into your string. <code>cur.execute(q,dis)</code> then fails because there's no marker to explain where the value of <code>dis</code> is supposed to go.</p>
<p>The way to do this is the use placeholders and bindings. In SQLite3 these are <code>?</code> and in other versions of SQL they are <code>%s</code>. I'm not sure which is expected here. EDIT: From Zev Spitz comment, it seems that it's <code>?</code> for placeholder in <a href="https://code.google.com/archive/p/pyodbc/wikis/GettingStarted.wiki" rel="nofollow">this particular case</a> (see <strong>Parameters</strong> section).</p>
<p>Therefore, your query would look something like the following:</p>
<pre><code>q = "SELECT * FROM cus_details WHERE cus_id = ?"
cur.execute(q, (cus,))
# Or
q = "SELECT * FROM cus_details WHERE cus_id = %s"
cur.execute(q, (cus,))
</code></pre>
| 2 | 2016-10-11T10:15:13Z | [
"python",
"ms-access",
"select"
] |
Tornado how to return error exception? | 39,974,225 | <p>I want to run a method I know this method doesn't work and I want to get the error returned by the method. </p>
<p>This is my code : </p>
<pre><code>def is_connect(s):
print("ok connection")
print(s)
ioloop.stop()
try:
current_job_ready = 0
print("ok1")
beanstalk = beanstalkt.Client(host='host', port=port)
print("ok1")
beanstalk.connect(callback=is_connect)
ioloop = tornado.ioloop.IOLoop.instance()
ioloop.start()
print("ok2")
except IOError as e:
print(e)
</code></pre>
<p>And this is the error I have when I run my program with wring port : </p>
<pre><code>WARNING:tornado.general:Connect error on fd 7: ECONNREFUSED
ERROR:tornado.application:Exception in callback <functools.partial object at 0x7f5a0eac6f18>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 604, in _run_callback
ret = callback()
File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 619, in <lambda>
self.add_future(ret, lambda f: f.result())
File "/usr/local/lib/python2.7/dist-packages/tornado/concurrent.py", line 237, in result
raise_exc_info(self._exc_info)
File "/usr/local/lib/python2.7/dist-packages/tornado/gen.py", line 270, in wrapper
result = func(*args, **kwargs)
TypeError: connect() takes exactly 1 argument (2 given)
</code></pre>
<p>I want to have e when I enter a false port or host.
How can I do this?
I tired to add <code>raise IOError("connection error")</code> after <code>beanstalk = beanstalkt.Client(host='host', port=port)</code> But this force the error, and I just want to have error when it exist.</p>
| 1 | 2016-10-11T09:28:00Z | 39,980,565 | <p>Here's where reading the code helps. In beanstalkt 0.6's <code>connect</code>, it creates an IOStream to connect to the server:</p>
<p><a href="https://github.com/nephics/beanstalkt/blob/v0.6.0/beanstalkt/beanstalkt.py#L108" rel="nofollow">https://github.com/nephics/beanstalkt/blob/v0.6.0/beanstalkt/beanstalkt.py#L108</a></p>
<p>It registers your callback to be executed on success, but if the connection fails it'll just call <code>Client._reconnect</code> once per second forever. I think you should open a feature request in their GitHub project asking for an error-notification system for <code>connect</code>. With the current beanstalkt implementation, you just have to decide how long you're willing to wait for success:</p>
<pre><code>import sys
from datetime import timedelta
from tornado.ioloop import IOLoop
def is_connect(s):
print("ok connection")
print(s)
loop.remove_timeout(timeout)
# Do something with Beanstalkd....
def connection_failed():
print(sys.stderr, "Connection failed!")
# Could call IOLoop.stop() or just quit.
sys.exit(1)
loop = IOLoop.current()
timeout = loop.add_timeout(timedelta(seconds=1), connection_failed)
beanstalk.connect(callback=is_connect)
loop.start()
</code></pre>
| 1 | 2016-10-11T15:09:40Z | [
"python",
"exception",
"tornado",
"beanstalk"
] |
How to determine which process is using a port in Linux | 39,974,335 | <p>I'm currently running RethinkDB on its default port, because if I point my browser to <code>localhost:8080</code> I see the RethinkDB web interface:</p>
<p><a href="http://i.stack.imgur.com/vtGXl.png" rel="nofollow"><img src="http://i.stack.imgur.com/vtGXl.png" alt="enter image description here"></a></p>
<p>I'd like to close RethinkDB and re-open it on another port using the <code>--port-offset</code> argument. However, so far I haven't been able to close it from within Python using the <code>conn.close()</code> method.</p>
<p>Instead, I'd like to try a brute-force approach by simply killing the process using that port. I tried to determine which process that is by using <code>netstat</code>, but that doesn't bring up any results:</p>
<pre><code>kurt@kurt-ThinkPad:~$ netstat -a | grep 8080
kurt@kurt-ThinkPad:~$
</code></pre>
<p>How can I kill the RethinkDB process to make the port available again?</p>
| 0 | 2016-10-11T09:34:16Z | 39,974,485 | <pre><code>1. lsof -i:8080
2. kill $(lsof -t -i:8080)
or
2 . kill -9 $(lsof -t -i:8080)
</code></pre>
| 1 | 2016-10-11T09:42:33Z | [
"python",
"linux",
"rethinkdb"
] |
How to determine which process is using a port in Linux | 39,974,335 | <p>I'm currently running RethinkDB on its default port, because if I point my browser to <code>localhost:8080</code> I see the RethinkDB web interface:</p>
<p><a href="http://i.stack.imgur.com/vtGXl.png" rel="nofollow"><img src="http://i.stack.imgur.com/vtGXl.png" alt="enter image description here"></a></p>
<p>I'd like to close RethinkDB and re-open it on another port using the <code>--port-offset</code> argument. However, so far I haven't been able to close it from within Python using the <code>conn.close()</code> method.</p>
<p>Instead, I'd like to try a brute-force approach by simply killing the process using that port. I tried to determine which process that is by using <code>netstat</code>, but that doesn't bring up any results:</p>
<pre><code>kurt@kurt-ThinkPad:~$ netstat -a | grep 8080
kurt@kurt-ThinkPad:~$
</code></pre>
<p>How can I kill the RethinkDB process to make the port available again?</p>
| 0 | 2016-10-11T09:34:16Z | 39,974,560 | <p>Following <a href="http://stackoverflow.com/users/3929826/klaus-d">Klaus D.</a>'s comment, I determined the process using <code>netstat -nlp</code>:</p>
<pre><code>kurt@kurt-ThinkPad:~$ netstat -nlp | grep 8080
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
tcp 0 0 127.0.1.1:8080 0.0.0.0:* LISTEN 2229/rethinkdb
tcp 0 0 127.0.0.1:8080 0.0.0.0:* LISTEN 2229/rethinkdb
tcp6 0 0 ::1:8080 :::* LISTEN 2229/rethinkdb
</code></pre>
<p>The arguments stand for </p>
<ul>
<li><code>numeric</code> (show numerical addresses instead of trying to determine symbolic host, port or usernames)</li>
<li><code>listening</code> (show only listening sockets (these are omitted by default))</li>
<li><code>program</code> (show the PID and name of the program to which each socket belongs)</li>
</ul>
<p>respectively.</p>
| 0 | 2016-10-11T09:46:22Z | [
"python",
"linux",
"rethinkdb"
] |
sympy solve linear equations XOR, NOT | 39,974,427 | <p>I have 60 equations with 70 variables.
all of them are in one list:</p>
<p>(x0,x1,...,x239) are sympy symbols</p>
<pre><code>list_a = [Xor(Not(x40), Not(x86)), Xor(x41, Not(x87)), ...]
</code></pre>
<p>and my question is, if it is possible somehow transform this equations to matrix or solved them.
I think, that it can have more than one solution.</p>
| 1 | 2016-10-11T09:39:16Z | 39,981,657 | <p>A solution to a system of logic expressions is the same as checking SAT for the conjunction (And) of the expressions.</p>
<pre><code>In [3]: list_a = [Xor(Not(x40), Not(x86)), Xor(x41, Not(x87))]
In [4]: list_a
Out[4]: [¬xââ ⻠¬xââ, xââ ⻠¬xââ]
In [5]: satisfiable(And(*list_a))
Out[5]: {x87: False, x40: True, x86: False, x41: False}
</code></pre>
<p>If you want all solutions you can pass <code>all_models=True</code>, although note that in the general case there are exponentially many solutions.</p>
| 0 | 2016-10-11T16:00:25Z | [
"python",
"sympy",
"equation",
"algebra"
] |
Python: get the most maximum values from dictionary | 39,974,474 | <p>I have a dictionary </p>
<pre><code>{u'__': 2, u'\u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0430': 1, u'\u041f\u043e\u0447\u0435\u043c\u0443': 1, u'\u041d\u0430\u043c': 1, u'\u043e\u0434\u0438\u043d': 1, u'\u0441\u043e\u0432\u0435\u0442\u0430\u043c\u0438': 1, u'\u041f\u0440\u043e\u0438\u0437\u043d\u0435\u0441\u0442\u0438': 1, u'\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e,': 1, u'\u0432\u044b\u0445\u043e\u0434\u044f\u0449\u0435\u043c\u0443': 1, u'\u043d\u0430\u0448\u0435\u0439': 2, u'\u0441\u0438\u0441\u0442\u0435\u043c\u0443': 1, u'\u0441\u0431\u043e\u0440\u0430': 1, u'\u0434\u0430\u043b\u044c\u043d\u0435\u0439\u0448\u0435\u043c.': 1, u'[](//www.yandex.ru)': 1, u'\u0412\u0430\u043c': 1, u'\u0430': 102, u'\u0432\u0438\u0440\u0443\u0441\u043e\u0432,': 1, u'\u043e\u0447\u0435\u043d\u044c': 1, u'\u0438': 90, u'\u0440\u0430\u0437.': 1, u'[cureit](http://www.freedrweb.com/?lng=ru)': 1, u'\u043d\u0435': 9, u'\u0438\u043b\u0438': 2, u'\u0441\u043f\u0435\u0446\u0438\u0430\u043b\u044c\u043d\u043e': 1, u'\u043d\u0430': 11, u'\u043d\u043e': 17, u'\u0443\u0441\u0442\u0430\u043d\u043e\u0432\u043b\u0435\u043d\u044b': 1, u'\u041c\u043e\u0436\u0435\u0442': 1, u'\u0432\u0430\u0448': 5, u'\u0445\u043e\u0442\u0438\u0442\u0435': 1, u'[\u0444\u043e\u0440\u043c\u043e\u0439': 1, u'\u0432\u044b': 5, u'\u0446\u0435\u043b\u0435\u0439': 1, u'\u0441\u0438\u043c\u0432\u043e\u043b\u044b': 3, u'\u0415\u0441\u043b\u0438': 2, u'\u0422\u0430\u043a\u0436\u0435': 1, u'\u0432\u043e\u0437\u043d\u0438\u043a\u043b\u0438': 1, u'\u0434\u0430\u043d\u043d\u043e\u0433\u043e': 1, u'**\u0412': 1, u'\u0437\u0430\u043f\u0440\u043e\u0441\u044b),': 1, u'\u041f\u043e\u043c\u043e\u0449\u0438](//help.yandex.ru/common/?id=1111120).': 1, u'\u042f\u043d\u0434\u0435\u043a\u0441\u0443': 1, u'\u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0435': 2, u'\u0432': 69, u'\u0441\u0435\u0440\u0432\u0438\u0441\u043e\u043c': 1, u'\u043f\u043e\u043f\u0440\u043e\u0431\u0443\u0439\u0442\u0435': 1, u'\u0443\u0442\u0438\u043b\u0438\u0442\u043e\u0439': 1, u'\u0430\u0432\u0442\u043e\u043c\u0430\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0435': 4, u'\u0432\u043e\u043f\u0440\u043e\u0441': 1, u'\u0430\u0432\u0442\u043e\u043c\u0430\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0435.': 1, u'\u043f\u043e': 24, u'##': 1, u'\u0434\u043e\u0441\u0442\u0443\u043f': 1, u'\u0443': 37, u'(\u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440,': 1, u'\u0437\u0430\u043f\u043e\u043c\u043d\u0438\u0442\u044c': 1, u'\u2192': 1, u'\u042f\u043d\u0434\u0435\u043a\u0441': 4, u'\u0441\u043b\u0443\u0447\u0430\u0435': 2, u'\u043f\u043e\u0445\u043e\u0436\u0438': 1, u'\u043a\u0430\u043f\u0447\u0435\u0439': 1, u'\xab\u041e\u0442\u043f\u0440\u0430\u0432\u0438\u0442\u044c\xbb.': 1, u'#': 3, u'cookies**.': 1, u'\u0431\u0443\u0434\u0435\u0442': 1, u'\u0427\u0442\u043e\u0431\u044b': 2, u'\u0441\u0432\u044f\u0437\u0438](//feedback2.yandex.ru/captcha/).': 1, u'\u043f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c': 1, u'\u0434\u0440\u0443\u0433\u043e\u043c\u0443': 1, u'\u043f\u0440\u043e\u0431\u043b\u0435\u043c\u044b': 1, u'\u0432\u0430\u043c,': 1, u'\u0441\u043b\u0435\u0432\u0430\u041e\u0442\u043f\u0440\u0430\u0432\u0438\u0442\u044c': 1, u'\u043c\u043e\u0433\u0443\u0442': 1, u'\u0432\u044b\u0445\u043e\u0434\u044f\u0449\u0438\u0445': 1, u'\u0432\u0440\u0435\u043c\u0435\u043d\u043d\u043e': 1, u'\u0441\u043b\u0443\u0436\u0431\u0435': 1, u'ip-\u0430\u0434\u0440\u0435\u0441\u0430,': 1, u'\u043f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430,': 2, u'\u0430\u043d\u0442\u0438\u0432\u0438\u0440\u0443\u0441\u043d\u043e\u0439': 1, u'\u0432\u0430\u043c\u0438': 1, u'\u0435\u0433\u043e': 4, u'\u0437\u0430\u0434\u0430\u0442\u044c': 1, u'\u0442\u0430\u043a': 1, u'\u0440\u0430\u0437': 3, u'\u0441\u0435\u0442\u044c': 1, u'\u0441\u0442\u043e\u0438\u0442': 1, u'cookies,': 1, u'ip-\u0430\u0434\u0440\u0435\u0441\u0430.': 1, u'\u0437\u0430\u0440\u0430\u0436\u0435\u043d': 1, u'\u043d\u0430\u0436\u043c\u0438\u0442\u0435': 1, u'\u0437\u0430\u0431\u043b\u043e\u043a\u0438\u0440\u043e\u0432\u0430\u0442\u044c': 1, u'\u0434\u043b\u044f': 2, u'\u043e\u0439...': 1, u'[\u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0435': 1, u'\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044e,': 1, u'\u0438\u0445.': 1, u'\u044d\u0442\u0438\u0445': 1, u'\u043f\u0440\u043e\u0434\u043e\u043b\u0436\u0438\u0442\u044c': 1, u'\u043e\u0431': 9, u'\u043f\u043e\u0438\u0441\u043a,': 1, u'\u0440\u043e\u0434\u0443': 1, u'\u0434\u043e\u0432\u043e\u043b\u044c\u043d\u043e': 1, u'\u0412': 6, u'\u0441\u043b\u0443\u0447\u0438\u043b\u043e\u0441\u044c?': 1, u'\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u0435\u0439,': 1, u'\u0432\u044b\u043d\u0443\u0436\u0434\u0435\u043d\u044b': 1, u'\u043f\u043e\u043b\u0435': 1, u'\u043f\u043e\u0441\u0442\u0443\u043f\u0438\u0432\u0448\u0438\u0435': 1, u'\u043a\u0430\u0440\u0442\u0438\u043d\u043a\u0438': 1, u'\u043a': 30, u'\u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u0446\u0438\u0440\u043e\u0432\u0430\u0442\u044c': 1, u'\u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044e\u0449\u0435\u0439': 1, u'\u041d\u0435\u0432\u0435\u0440\u043d\u043e,': 1, u'ip.': 1, u'\u0434\u0440\u0443\u0433\u0438\u0445': 1, u'\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0442\u0435\u043b\u044c\u043d\u043e': 1, u'\u043e\u0442\u043a\u043b\u044e\u0447\u0435\u043d\u044b': 1, u'\u0440\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u0430\u043d\u043d\u044b\u043c': 1, u'\u043d\u0430\u043b\u0438\u0447\u0438\u0435': 1, u'\u0432\u0432\u0435\u0434\u0438\u0442\u0435': 1, u'\u0434\u043e\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f,': 1, u'\u043f\u043e\u0441\u043b\u0435': 1, u'\u0432\u0430\u0448\u0435\u0433\u043e': 2, u'\u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e': 1, u'': 1, u'\u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u0430,': 1, u'\u0440\u0435\u043a\u043e\u043c\u0435\u043d\u0434\u0443\u0435\u043c': 2, u'\u0436\u0430\u043b\u044c,': 1, u'\u0432\u0432\u043e\u0434\u0430': 1, u'\u043e\u0442\u043a\u043b\u044e\u0447\u0438\u0442\u044c': 1, u'\u043e\u0442': 9, u'\u0437\u0430\u0434\u0430\u0432\u0430\u0442\u044c': 1, u'\u0447\u0435\u0433\u043e': 1, u'\u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440,': 2, u'\u0437\u0430\u043f\u0440\u043e\u0441\u044b,': 1, u'\u044d\u0442\u043e\u043c': 3, u'\u0437\u043d\u0430\u0435\u0442\u0435': 1, u'\u044d\u0442\u043e\u0439': 1, u'\u0435\u0449\u0451': 1, u'\u0444\u0430\u0439\u043b\u044b': 1, u'\u043a\u043e\u0442\u043e\u0440\u044b\u0435': 1, u'\u0441\u043c\u043e\u0436\u0435\u0442': 1, u'\u0434\u043e\u043b\u0433\u043e.': 1, u'\u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e': 2, u'\u041f\u043e': 3, u'\u0434\u0435\u044f\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u0438': 1, u'\u043e\u0442\u043b\u0438\u0447\u0430\u0442\u044c': 1, u'\u0432\u0430\u0448\u0435\u043c': 2, u'\u043e\u0442\u043f\u0440\u0430\u0432\u043b\u044f\u0442\u044c': 1, u'\u0432\u0432\u0435\u0441\u0442\u0438': 1, u'\u0437\u0430\u043f\u043e\u043c\u043d\u0438\u043c': 1, u'\u0432\u0430\u0441': 4, u'': 1, u'\u0432\u0438\u0440\u0443\u0441\u043d\u043e\u0439': 2, u'\u0412\u043e\u0437\u043c\u043e\u0436\u043d\u043e,': 2, u'\u043f\u043e\u0434\u0434\u0435\u0440\u0436\u043a\u0438,': 1, u'\u0437\u0430\u043f\u0440\u043e\u0441\u044b': 5, u'\u043e\u0431\u0440\u0430\u0442\u043d\u043e\u0439': 1, u'\u0441': 77, u'\u0444\u043e\u0440\u043c\u0443,': 1, u'\u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440': 2, u'\u043f\u043e\u0441\u0442\u0443\u043f\u0430\u044e\u0442': 1, u'\u0432\u0430\u043c': 5, u'\u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u043e\u0439,': 1, u'\u0447\u0442\u043e': 1, u'\u0432\u043e\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c\u0441\u044f': 1, u'\u043f\u043e\u0438\u0441\u043a\u0443.': 2, u'\u0431\u044b\u0442\u044c,': 1, u'\u0441\u043c\u043e\u0436\u0435\u043c': 1, u'\u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435': 1, u'\u0432\u043e\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0439\u0442\u0435\u0441\u044c': 2, u'\xabdr.web\xbb.': 1, u'\u0432\u043a\u043b\u044e\u0447\u0438\u0442\u044c': 1, u'[\u042f\u043d\u0434\u0435\u043a\u0441.xml](//xml.yandex.ru).': 1, u'\u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u0438.': 1, u'\u043f\u0440\u0438\u0447\u0438\u043d\u0435': 1, u'\u0431\u0435\u0441\u043f\u043e\u043a\u043e\u0438\u0442\u044c': 1, u'\u043c\u044b': 3, u'\u043e\u0434\u043d\u043e\u0433\u043e': 1, u'\u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0430\u0442': 1}
</code></pre>
<p>I need to convert it encoding and get dictionary with 10 the biggest values.
I try to use </p>
<p><code>print max(dict.iteritems(), key=operator.itemgetter(10))[0]</code>
But it returns me nothing.
But how convert this string I don't know. I didn't find the way to do it.</p>
| 2 | 2016-10-11T09:42:06Z | 39,974,530 | <p><code>max()</code> can only ever return a single value. Use a Counter:</p>
<pre><code>from collections import Counter
counter = Counter(yourdictionary)
print(counter.most_common(10))
</code></pre>
| 5 | 2016-10-11T09:44:59Z | [
"python",
"dictionary",
"encoding"
] |
Reducing file size of scatter plot | 39,974,576 | <p>I am currently trying to reduce the file size of a scatter plot. My code looks like:</p>
<pre><code>plt.scatter(a1,b1)
plt.savefig('test.ps')
</code></pre>
<p>where a1,b1 are arrays of size 400,000 or so, and it gives a file size of 7.8MB.</p>
<p>I have tried adding </p>
<pre><code>plt.rcParams['path.simplify'] = True
</code></pre>
<p>before this chunk of code, but the file is still 7.8MB. Is this an issue with how it saves as a ".ps" file or another issue?</p>
| 1 | 2016-10-11T09:47:03Z | 39,974,868 | <p>One approach is to use <code>plot</code> instead of <code>scatter</code> (you can still produce scatter plots using <code>plot</code> by using the <code>'o'</code> argument), and use the <code>rasterized</code> keyword argument, like so:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
a1,b1 = np.random.randn(400000,2).T #mock data of similar size to yours
plt.plot(a1,b1,'o',rasterized=True)
plt.savefig("test.ps")
</code></pre>
<p>This should significantly reduce the size of the output file. The text and line art will remain vector, only the points are rasterized, so it is a nice compromise. </p>
<p>Depending on what you're looking to achieve, however, it might be better to histogram your data and plot that instead (e.g. <code>pyplot.hist2d</code> or <code>pyplot.hexbin</code>).</p>
| 1 | 2016-10-11T10:04:34Z | [
"python",
"matplotlib"
] |
Reducing file size of scatter plot | 39,974,576 | <p>I am currently trying to reduce the file size of a scatter plot. My code looks like:</p>
<pre><code>plt.scatter(a1,b1)
plt.savefig('test.ps')
</code></pre>
<p>where a1,b1 are arrays of size 400,000 or so, and it gives a file size of 7.8MB.</p>
<p>I have tried adding </p>
<pre><code>plt.rcParams['path.simplify'] = True
</code></pre>
<p>before this chunk of code, but the file is still 7.8MB. Is this an issue with how it saves as a ".ps" file or another issue?</p>
| 1 | 2016-10-11T09:47:03Z | 39,974,916 | <p>I would think that this is due to the PostScript format, and nothing that can be changed. Let's do the math:</p>
<p>7.8MB is something like 7.8 * 1024 * 1024 = 8,178,892.8. Assuming that you have 400,000 points in your scatter plot, that means that your file would assign something like 20 bytes to each point in your scatterplot if there was nothing else in your file (i.e. no legends, no annotations etc). </p>
<p>Now, I'm not a PostScript expert, but looking at the output <code>test.ps</code>, the command used to draw circles in PostScript looks like this:</p>
<pre><code>[x] [y] o
</code></pre>
<p>where x and y are the coordinates of each point. As these are float values, the information does indeed add up to 15 bytes, which is not too far off my guess above.</p>
<p>So yes, the file size is caused by the nature of the PostScript file, which stores quite a bit of information for each of the 400,000 points in your scatterplot. </p>
<p>You can store the scatterplot as a rasterized image as suggested in @AngusWilliams' answer, and this will result in a smaller file size. However, you will lose the advantage of a vector-based file format: lossless scaling at any resolution. </p>
<p>If you don't need this advantages of vector-based file formats, you may be better off with even another file format like <code>.png</code> which does usually a much better job in compressing the image than PostScript containing rasterized information.</p>
| 0 | 2016-10-11T10:07:13Z | [
"python",
"matplotlib"
] |
Reducing file size of scatter plot | 39,974,576 | <p>I am currently trying to reduce the file size of a scatter plot. My code looks like:</p>
<pre><code>plt.scatter(a1,b1)
plt.savefig('test.ps')
</code></pre>
<p>where a1,b1 are arrays of size 400,000 or so, and it gives a file size of 7.8MB.</p>
<p>I have tried adding </p>
<pre><code>plt.rcParams['path.simplify'] = True
</code></pre>
<p>before this chunk of code, but the file is still 7.8MB. Is this an issue with how it saves as a ".ps" file or another issue?</p>
| 1 | 2016-10-11T09:47:03Z | 39,977,232 | <p>You could consider using e.g. <code>hexbin</code> -- I particularly like this when you have a dense collection of points, since it better indicates where your data is concentrated. For example:</p>
<pre><code>import numpy as np
import matplotlib.pylab as pl
x = np.random.normal(size=40000)
y = np.random.normal(size=40000)
pl.figure()
pl.subplot(121)
pl.scatter(x, y)
pl.xlim(-4,4)
pl.ylim(-4,4)
pl.subplot(122)
pl.hexbin(x, y, gridsize=40)
pl.xlim(-4,4)
pl.ylim(-4,4)
</code></pre>
<p><a href="https://i.stack.imgur.com/3SXJS.png" rel="nofollow"><img src="https://i.stack.imgur.com/3SXJS.png" alt="enter image description here"></a></p>
<p>From the left figure, I would have concluded that the distribution of points between <code>x,y = {-3,3}</code> is roughly equal, which clearly is not the case. </p>
<p>(<a href="http://matplotlib.org/examples/pylab_examples/hexbin_demo.html" rel="nofollow">http://matplotlib.org/examples/pylab_examples/hexbin_demo.html</a>)</p>
| 0 | 2016-10-11T12:26:49Z | [
"python",
"matplotlib"
] |
Search all files in a folder | 39,974,584 | <p>I want to search "word" in many files in a folder. </p>
<p>I have already : </p>
<pre><code>route=os.listdir("/home/new")
for file in route:
</code></pre>
<p>This does not work : </p>
<pre><code> f = open ('' , 'r')
for line in f :
</code></pre>
<p>I tried this :</p>
<pre><code>for file in route:
f = open(file, 'r')
for line in f:
if word in line:
print(file)
break
</code></pre>
<p>but I have an error :</p>
<pre><code>f=open( file ,'r')
IOError: [Errno 2] No such file or directory: file.txt
</code></pre>
<p>When I delete file.txt, next file , I receive the same error.</p>
| -1 | 2016-10-11T09:47:23Z | 39,974,785 | <pre><code>for file in filelist:
f = open(file,"r")
data = f.read()
rows = data.split("\n")
count = 0
full_data = []
for row in rows:
split_row = row.split(",")
full_data.append(split_row)
for each in full_data:
if re.search("word", each) is not None:
count += 1
</code></pre>
<p>Something like this, although your question is not at all specific about whether you want to count, return where word was found, change word to something, etc. so feel free to edit it as you see fit</p>
<p>(This code works for .csv as you can probably tell)</p>
| 0 | 2016-10-11T10:00:25Z | [
"python",
"os.system"
] |
Search all files in a folder | 39,974,584 | <p>I want to search "word" in many files in a folder. </p>
<p>I have already : </p>
<pre><code>route=os.listdir("/home/new")
for file in route:
</code></pre>
<p>This does not work : </p>
<pre><code> f = open ('' , 'r')
for line in f :
</code></pre>
<p>I tried this :</p>
<pre><code>for file in route:
f = open(file, 'r')
for line in f:
if word in line:
print(file)
break
</code></pre>
<p>but I have an error :</p>
<pre><code>f=open( file ,'r')
IOError: [Errno 2] No such file or directory: file.txt
</code></pre>
<p>When I delete file.txt, next file , I receive the same error.</p>
| -1 | 2016-10-11T09:47:23Z | 39,974,869 | <p>You already have it down mostly:</p>
<pre><code>for file in route:
f = open(file, 'r')
for line in f:
if word in line:
print(file)
break
</code></pre>
| -1 | 2016-10-11T10:04:38Z | [
"python",
"os.system"
] |
Search all files in a folder | 39,974,584 | <p>I want to search "word" in many files in a folder. </p>
<p>I have already : </p>
<pre><code>route=os.listdir("/home/new")
for file in route:
</code></pre>
<p>This does not work : </p>
<pre><code> f = open ('' , 'r')
for line in f :
</code></pre>
<p>I tried this :</p>
<pre><code>for file in route:
f = open(file, 'r')
for line in f:
if word in line:
print(file)
break
</code></pre>
<p>but I have an error :</p>
<pre><code>f=open( file ,'r')
IOError: [Errno 2] No such file or directory: file.txt
</code></pre>
<p>When I delete file.txt, next file , I receive the same error.</p>
| -1 | 2016-10-11T09:47:23Z | 40,055,530 | <p><a href="https://docs.python.org/3/library/os.html#os.listdir" rel="nofollow"><code>os.listdir</code> only returns the file names</a>, not the qualified paths. So to make this work, your <code>open</code> needs to be opening the qualified path (constructed with <code>os.path.join("/home/new", file)</code>), not just <code>file</code>.</p>
| 0 | 2016-10-15T05:55:43Z | [
"python",
"os.system"
] |
Search all files in a folder | 39,974,584 | <p>I want to search "word" in many files in a folder. </p>
<p>I have already : </p>
<pre><code>route=os.listdir("/home/new")
for file in route:
</code></pre>
<p>This does not work : </p>
<pre><code> f = open ('' , 'r')
for line in f :
</code></pre>
<p>I tried this :</p>
<pre><code>for file in route:
f = open(file, 'r')
for line in f:
if word in line:
print(file)
break
</code></pre>
<p>but I have an error :</p>
<pre><code>f=open( file ,'r')
IOError: [Errno 2] No such file or directory: file.txt
</code></pre>
<p>When I delete file.txt, next file , I receive the same error.</p>
| -1 | 2016-10-11T09:47:23Z | 40,055,558 | <p>How about something along these lines?</p>
<pre><code>import os
folderpath = "/.../.../foldertosearch"
word = 'giraffe'
for(path, dirs, files) in os.walk(folderpath, topdown=True):
for filename in files:
filepath = os.path.join(path, filename)
with open(filepath, 'r') as currentfile:
for line in currentfile:
if word in line:
print(
'Found the word in ' + filename + ' in line ' +
line
)
</code></pre>
| 0 | 2016-10-15T06:00:09Z | [
"python",
"os.system"
] |
replicate iferror and vlookup in a pandas join | 39,974,673 | <p>I want to join two dataframes:</p>
<pre><code>df1 = pd.DataFrame({'Banner': {0: 'banner1', 1: 'banner2', 2: 'banner3'},
'Campaign': {0: 'campaign1', 1: 'campaign2', 2: '12345'},
'Country ': {0: 'de', 1: 'it', 2: 'de'},
'Date': {0: '1/1/2016', 1: '2/1/2016', 2: '1/1/2016'},
'Value_1': {0: 10, 1: 5, 2: 20}})
df2 = pd.DataFrame({'Banner': {0: 'banner1', 1: 'banner2', 2: 'banner3', 3: 'banner4', 4: 'banner5'},
'Campaign': {0: 'campaign1',1: 'campaign2', 2: 'none',3: 'campaign4',4: 'campaign5'},
'Country ': {0: 'de', 1: 'it', 2: 'de', 3: 'en', 4: 'en'},
'Date': {0: '1/1/2016', 1: '2/1/2016', 2: '1/1/2016', 3: '3/1/2016', 4: '4/1/2016'},
'Value_2': {0: 5, 1: 10, 2: 15, 3: 20, 4: 25},
'id_campaign': {0: 'none', 1: 'none', 2: '12345', 3: 'none', 4: 'none'}})
</code></pre>
<p><strong>edit</strong>:
let's even imagine the option:</p>
<pre><code>df1 = pd.DataFrame({'Banner': {0: 'banner1', 1: 'banner2', 2: 'banner3'},
'Campaign': {0: 'campaign1', 1: 'campaign2', 2: '12345'},
'Date': {0: '1/1/2016', 1: '2/1/2016', 2: '1/1/2016'},
'Value_1': {0: 10, 1: 5, 2: 20}})
</code></pre>
<p>I have to join df2 and df1 on the keys:</p>
<ul>
<li>Date</li>
<li>Campaign</li>
<li>Banner</li>
</ul>
<p>The issue here is that when the match under the key "Campaign" is not found, the key should be switched to field "id_campaign".</p>
<p>I would like to obtain this dataframe:</p>
<pre><code>df_joined = pd.DataFrame({'Banner': {0: 'banner1', 1: 'banner2', 2: 'banner3', 3: 'banner4', 4: 'banner5'},
'Campaign': {0: 'campaign1', 1: 'campaign2', 2: 'none', 3: 'campaign4', 4: 'campaign5'},
'Country ': {0: 'de', 1: 'it', 2: 'de', 3: 'en', 4: 'en'},
'Date': {0: '1/1/2016', 1: '2/1/2016', 2: '1/1/2016', 3: '3/1/2016', 4: '4/1/2016'},
'Value_1': {0: 10, 1: 5, 2: 20, 3: 0, 4: 0},
'Value_2': {0: 5, 1: 10, 2: 15, 3: 20, 4: 25},
'id_campaign': {0: 'none', 1: 'none', 2: '12345', 3: 'none', 4: 'none'}})
</code></pre>
<p>any help is really appreciated.</p>
| 2 | 2016-10-11T09:52:59Z | 39,975,266 | <p>You can use double <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> by 3 and 2 keys and then fill not match values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.combine_first.html" rel="nofollow"><code>combine_first</code></a> from column <code>Value_1</code> of <code>df4</code>:</p>
<pre><code>df3 = pd.merge(df2, df1.drop('Country', axis=1), on=['Date','Campaign','Banner'], how='left')
df4 = pd.merge(df2, df1, on=['Date','Banner'], how='left')
print (df3)
Banner Campaign Country Date Value_2 id_campaign Value_1
0 banner1 campaign1 de 1/1/2016 5 none 10.0
1 banner2 campaign2 it 2/1/2016 10 none 5.0
2 banner3 none de 1/1/2016 15 12345 NaN
3 banner4 campaign4 en 3/1/2016 20 none NaN
4 banner5 campaign5 en 4/1/2016 25 none NaN
print (df4['Value_1'])
0 10.0
1 5.0
2 20.0
3 NaN
4 NaN
Name: Value_1, dtype: float64
df3['Value_1'] = df3['Value_1'].combine_first(df4['Value_1']).fillna(0).astype(int)
print (df3)
Banner Campaign Country Date Value_2 id_campaign Value_1
0 banner1 campaign1 de 1/1/2016 5 none 10
1 banner2 campaign2 it 2/1/2016 10 none 5
2 banner3 none de 1/1/2016 15 12345 20
3 banner4 campaign4 en 3/1/2016 20 none 0
4 banner5 campaign5 en 4/1/2016 25 none 0
</code></pre>
| 0 | 2016-10-11T10:26:31Z | [
"python",
"pandas",
"join",
"merge"
] |
Automatically play video on Mac | 39,974,758 | <p>I've the following code in my webpage (Python/Django framework) to enable a video to play in the background.</p>
<p><strong>HTML</strong></p>
<pre><code><div class="video-container">
<div class="video-container-bg">
<video playsinline autoplay muted loop poster="{{page.image.url}}" id="bgvid">
<source src="{{page.video.url}}" type="video/mp4">
<source src="{{page.mac_video.url}}" type="video/webm">
</video>
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-8">
<div class="animation-element bounce-up">
<h1 class="page-title">{{page.page_title}}</h1>
<p class="strapeline">{{page.strapline}}</p>
<a class="butt" href="#about-us">Learn More</a>
</div>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>video#bgvid {
position: absolute;
top: 50%;
left: 50%;
min-width: 100%;
min-height:100%;
overflow: hidden !important;
z-index: -100;
-ms-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
background: url() no-repeat;
background-size: 100%;
}
.video-container {
min-height: calc(100vh - 75px);
overflow: hidden !important;
position: relative;
}
.video-container-bg {
padding-top: 25vh;
color: #fff;
}
</code></pre>
<p>It works fine on everything except Safari where nothing plays. Why not? Is it something Apple have set to prevent? In fact, when I run Safari on Windows it's telling me it cannot play HTML5 video. Is that right?</p>
| 0 | 2016-10-11T09:58:39Z | 39,995,436 | <p>I've solved this by saving the mp4 files in a lossless state. It now seems to work. I have no idea why</p>
| 0 | 2016-10-12T09:42:58Z | [
"python",
"css",
"django",
"osx",
"html5-video"
] |
Using python's multiprocessing on slurm | 39,974,874 | <p>I am trying to run some parallel code on slurm, where the different processes do not need to communicate. Naively I used python's slurm package. However, it seems that I am only using the cpu's on one node.</p>
<p>For example, if I have 4 nodes with 5 cpu's each, I will only run 5 processes at the same time. How can I tell multiprocessing to run on different nodes?</p>
<p>The python code looks like the following</p>
<pre><code>import multiprocessing
def hello():
print("Hello World")
pool = multiprocessing.Pool()
jobs = []
for j in range(len(10)):
p = multiprocessing.Process(target = run_rel)
jobs.append(p)
p.start()
</code></pre>
<p>The problem is similar to <a href="http://stackoverflow.com/questions/32594734/slurm-multiprocessing-python-job">this one</a>, but there it has not been solved in detail.</p>
| 0 | 2016-10-11T10:04:55Z | 39,975,214 | <p>Your current code will run 10 times on 5 processor, on a SINGLE node where you start it. It has nothing to do with SLURM now. </p>
<p>You will have to <code>SBATCH</code> the script to SLURM.</p>
<p>If you want to run this script on 5 cores with SLURM modify the script like this:</p>
<pre><code>#!/usr/bin/python3
#SBATCH --output=wherever_you_want_to_store_the_output.log
#SBATCH --partition=whatever_the_name_of_your_SLURM_partition_is
#SBATCH -n 5 # 5 cores
import sys
import os
import multiprocessing
# Necessary to add cwd to path when script run
# by SLURM (since it executes a copy)
sys.path.append(os.getcwd())
def hello():
print("Hello World")
pool = multiprocessing.Pool()
jobs = []
for j in range(len(10)):
p = multiprocessing.Process(target = run_rel)
jobs.append(p)
p.start()
</code></pre>
<p>And then execute the script with </p>
<pre><code>sbatch my_python_script.py
</code></pre>
<p>On one of the nodes where SLURM is installed</p>
<p>However this will allocate your job to a SINGLE node as well, so the speed will be the very same as you would just run it on a single node. </p>
<p>I dont know why would you want to run it on different nodes when you have just 5 processes. It will be faster just to run on one node. If you allocate more then 5 cores, in the beginning of the python script, then SLURM will allocate more nodes for you. </p>
| 1 | 2016-10-11T10:23:29Z | [
"python",
"multiprocessing",
"slurm"
] |
python sample large array using smaller array | 39,974,913 | <p>Let's say I have two arrays: SMALL_ARRAY and LARGE_ARRAY
The LARGE_ARRAY contains values that are similar in value (not necessarily the same)
I would like to get a subarray of the LARGE_ARRAY that:</p>
<p>= Has same size as SMALL_ARRAY</p>
<p>= Has similar values (similar distribution) as SMALL_ARRAY</p>
<p>let's assume small = [1,2,3,4] and large = [100,1.8,32,4.1,5,55,34,2.9,1.1,99]</p>
<p>I would like my new array to be [1.1,1.8,2.9,4.1]</p>
<p>so it has same size and similar elements to small</p>
<p>Any assistance please?
Many thanks</p>
| -1 | 2016-10-11T10:06:45Z | 39,975,173 | <p>Based on <a href="http://stackoverflow.com/a/8914682/3627387">http://stackoverflow.com/a/8914682/3627387</a></p>
<pre><code>LARGE_ARRAY = [100,1.8,32,4.1,5,55,34,2.9,1.1,99]
SMALL_ARRAY = [1,2,3,4]
similar = []
for i in SMALL_ARRAY:
diff_list = [(abs(i - x), x) for x in LARGE_ARRAY]
diff_list.sort()
similar.append(diff_list[0][1])
print(similar)
</code></pre>
| 0 | 2016-10-11T10:20:48Z | [
"python",
"arrays"
] |
python sample large array using smaller array | 39,974,913 | <p>Let's say I have two arrays: SMALL_ARRAY and LARGE_ARRAY
The LARGE_ARRAY contains values that are similar in value (not necessarily the same)
I would like to get a subarray of the LARGE_ARRAY that:</p>
<p>= Has same size as SMALL_ARRAY</p>
<p>= Has similar values (similar distribution) as SMALL_ARRAY</p>
<p>let's assume small = [1,2,3,4] and large = [100,1.8,32,4.1,5,55,34,2.9,1.1,99]</p>
<p>I would like my new array to be [1.1,1.8,2.9,4.1]</p>
<p>so it has same size and similar elements to small</p>
<p>Any assistance please?
Many thanks</p>
| -1 | 2016-10-11T10:06:45Z | 39,975,257 | <p><code>numpy.random.choice</code> is your friend if you want to subsample uniformly at random:</p>
<pre><code>import numpy as np
# 'initialise' small so we know its shape
# obviously you can skip that step if you already know the shape
m, n = 5, 10
small = np.zeros((m, n))
# get a sample from a large array
large = np.random.randn(100,1000)
samples = np.random.choice(large.ravel(), size=m*n)
# small
small = samples.reshape(small.shape)
print small
</code></pre>
| 0 | 2016-10-11T10:26:11Z | [
"python",
"arrays"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.