title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
How to create an adjacency list from an edge list efficiently | 39,562,253 | <p>I have a csv that looks like</p>
<pre><code>id1,id2
a,b
c,d
a,e
c,f
c,g
</code></pre>
<p>I read it in to a dataframe with df = pd.read_csv("file.csv").</p>
<p>I would like to convert it to an adjacency list. That is the output should be</p>
<pre><code>a,b,e
c,d,f,g
</code></pre>
<p>I feel that df.groupby('id1'... | 1 | 2016-09-18T20:16:23Z | 39,610,393 | <p>Something like this:</p>
<pre><code>adj = defaultdict(set)
for line in input:
left, right = line.split(",")
adj[left].add(right)
</code></pre>
<p>Output:</p>
<pre><code>for k,v in adj.items():
print("%s,%s" % (k, ",".join(v)))
</code></pre>
| 0 | 2016-09-21T07:44:09Z | [
"python",
"pandas",
"graph"
] |
My djcelery tasks run locally but not remotely? | 39,562,277 | <p>I have automated tasks working locally but not reomotely in my django app. I was watching a tutorial and the guy said to stop my worker. but before I did that I put my app in maintenance mode, that didn't work. then I ran</p>
<pre><code>heroku ps:restart
</code></pre>
<p>that didn't work, then I ran </p>
<pre><co... | 0 | 2016-09-18T20:18:52Z | 39,563,551 | <p>I read the docs and realized I had to add to my worker procfile</p>
<pre><code>-B
</code></pre>
<p>so it now looks like this</p>
<pre><code>celery -A proj worker -B -l info
</code></pre>
<p>after I made the change I did this</p>
<pre><code>heroku ps:scale worker=0
</code></pre>
<p>then</p>
<pre><code>git add ... | 0 | 2016-09-18T23:21:59Z | [
"python",
"django",
"heroku",
"task",
"crontab"
] |
My djcelery tasks run locally but not remotely? | 39,562,277 | <p>I have automated tasks working locally but not reomotely in my django app. I was watching a tutorial and the guy said to stop my worker. but before I did that I put my app in maintenance mode, that didn't work. then I ran</p>
<pre><code>heroku ps:restart
</code></pre>
<p>that didn't work, then I ran </p>
<pre><co... | 0 | 2016-09-18T20:18:52Z | 39,565,209 | <p>As you've read in the docs, using the <strong>-B</strong> option is not recommended for production use, you'd better run <code>celery-beat</code> as a different process.</p>
<p>So it's best practice to run it in the server like : </p>
<pre><code>celery beat -A messaging_router --loglevel=INFO
</code></pre>
<p>And... | 0 | 2016-09-19T04:06:30Z | [
"python",
"django",
"heroku",
"task",
"crontab"
] |
substract from date tuple | 39,562,373 | <p>I have an index consisting of Date tuples.</p>
<pre><code>2005-02-04 00:00:00 31.81 31.81 31.81 31.81
2005-02-07 00:00:00 31.885 31.885 31.885 31.885
2005-02-08 00:00:00 31.5326 31.5326 31.5326 31.5326
</code></pre>
<p>I would like to... | -2 | 2016-09-18T20:28:35Z | 39,562,559 | <p>Actually I ve found it, you simply need to take the first element off the tuple, and it returns a 'TimeStamp' object: </p>
<pre><code>df.index.min()[0] - dt.timedelta(minutes=5)
</code></pre>
<p>works </p>
| 0 | 2016-09-18T20:49:57Z | [
"python",
"datetime",
"pandas",
"dataframe"
] |
Plot gyrosensor data in csv file in matplotlib | 39,562,374 | <p>I have exported gyro sensor data from my mobile using sensorLog app in csv format. I am trying the plot of three axis data wrt timestamp. Data looks like this </p>
<p>1474145797.91346 -0.055417 -0.465534 -0.284113</p>
<p>1474145797.93344 -0.108296 -0.42116 -0.240057</p>
<p>1474145797.95342 -0.04... | 0 | 2016-09-18T20:28:35Z | 39,563,002 | <p>I believe your Problem is the first line in the CSV-file which is actually the header.</p>
<p>Try passing <em>skiprows=1</em> to loadtxt</p>
| 0 | 2016-09-18T21:48:41Z | [
"python",
"matplotlib"
] |
Printing coeficients of several linear regressions on a single python script | 39,562,376 | <p>I am running this code:</p>
<pre><code>import sklearn
IVS=['CRIM', 'RM', 'PTRATIO']
IVS2=['CRIM','PTRATIO']
model1=lm.fit(bos[IVS],bos.PRICE)
model2=lm.fit(bos[IVS2],bos.PRICE)
print(model1.coef_)
print(model2.coef_)
</code></pre>
<p>When trying to print out the coefficients for both models, I only get the last m... | 0 | 2016-09-18T20:28:54Z | 39,563,819 | <p>You need to create separate instances of your classifier before you call fit:</p>
<pre><code>from sklearn.linear_model import LinearRegression()
model1 = LinearRegression()
model1.fit(bos[IVS],bos.PRICE)
model2 = LinearRegression()
model2.fit(bos[IVS2],bos.PRICE)
</code></pre>
| 0 | 2016-09-19T00:16:10Z | [
"python",
"scikit-learn",
"regression",
"linear",
"coefficients"
] |
MySQL/Python -- committed changes not appearing in loop | 39,562,468 | <p>Using MySQL Connector/Python I have a loop that keeps checking a value for a change every 2 seconds. Without all the meat, here is the loop (the print is there for testing purposes:</p>
<pre><code>try:
while True:
request = database.get_row(table="states", wherecol="state", whereval="request_from_interfa... | 0 | 2016-09-18T20:39:34Z | 39,562,906 | <p>The default <a href="http://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html" rel="nofollow">isolation level</a> of InnoDB is <a href="http://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html#isolevel_repeatable-read" rel="nofollow">REPEATABLE READ</a>. This means that ... | 0 | 2016-09-18T21:33:49Z | [
"python",
"mysql",
"python-3.x",
"mysql-connector-python"
] |
ImportError: No module named bs4 in django | 39,562,519 | <p>I am learning Django and I was working with bs4 in PyCharm on mac. I am using Python3 with Django which also has bs4 installed and it can be seen below.
<a href="http://i.stack.imgur.com/fRQP7.png" rel="nofollow"><img src="http://i.stack.imgur.com/fRQP7.png" alt="enter image description here"></a></p>
<p>But when I... | 0 | 2016-09-18T20:44:57Z | 39,562,552 | <p>You are running the script with Python2.7 (according to the traceback) while having <code>beautifulsoup4</code> package installed in Python3.5 environment.</p>
<p><em>Adjust your run configuration to use Python3.5 to run the script.</em></p>
| 1 | 2016-09-18T20:49:24Z | [
"python",
"django",
"beautifulsoup",
"pycharm",
"bs4"
] |
ImportError: No module named bs4 in django | 39,562,519 | <p>I am learning Django and I was working with bs4 in PyCharm on mac. I am using Python3 with Django which also has bs4 installed and it can be seen below.
<a href="http://i.stack.imgur.com/fRQP7.png" rel="nofollow"><img src="http://i.stack.imgur.com/fRQP7.png" alt="enter image description here"></a></p>
<p>But when I... | 0 | 2016-09-18T20:44:57Z | 39,562,555 | <p>ok first thing, in your python 3 environment you have installed bs4, but in your python 2.7, you probably do not have. As you can see in your attached second screen, django is running on python 2.7.</p>
<p>I recommend using virtual environment, where you can have all of your dependencies personalized for single pro... | 1 | 2016-09-18T20:49:31Z | [
"python",
"django",
"beautifulsoup",
"pycharm",
"bs4"
] |
ImportError: No module named bs4 in django | 39,562,519 | <p>I am learning Django and I was working with bs4 in PyCharm on mac. I am using Python3 with Django which also has bs4 installed and it can be seen below.
<a href="http://i.stack.imgur.com/fRQP7.png" rel="nofollow"><img src="http://i.stack.imgur.com/fRQP7.png" alt="enter image description here"></a></p>
<p>But when I... | 0 | 2016-09-18T20:44:57Z | 39,562,562 | <p>You've installed wrong Beautiful Soup package. The one that you installed is <a href="https://pypi.python.org/pypi/bs4/0.0.1" rel="nofollow">bs4</a></p>
<blockquote>
<p>This is a dummy package managed by the developer of Beautiful Soup to prevent name squatting. The official name of PyPIâs Beautiful Soup Python... | 0 | 2016-09-18T20:50:08Z | [
"python",
"django",
"beautifulsoup",
"pycharm",
"bs4"
] |
How do I resolve this Python inheritance super-child call? | 39,562,574 | <p>If i'm using a super constructor to create a class that is inherited from a parent class, is it possible to use that same call to set an attribute to create a child class?
So in my I am creating an Electric Car. An Electric Car is a child class of a Car.
An Electric Car has an attribute battery which will be initial... | -2 | 2016-09-18T20:52:14Z | 39,562,624 | <p>You don't give battery size here:</p>
<pre><code>my_tesla = ElectricCar('TeslaX', 2016)
</code></pre>
<p>Change it to:</p>
<pre><code>my_tesla = ElectricCar('TeslaX', 2016, 1337) # 1337 is battery size.
</code></pre>
<hr>
<p>If you wish to supply a default, you should also supply it in <code>ElectricCar</code>... | 1 | 2016-09-18T20:58:58Z | [
"python"
] |
Trying to plot Mandelbrot set - no matter what, always get plain black image | 39,562,659 | <p>First, here's the code I have:</p>
<pre><code>from PIL import Image as im
import numpy as np
def mandelbrot_iteration(c):
iters = 0
while abs(c)<2 and iters<200:
c=c**2+c
iters+=1
return iters
HEIGHT = 400
WIDTH = 500
diag = im.new('L',(WIDTH, HEIGHT))
pix = diag.load()
x_pts... | 1 | 2016-09-18T21:03:40Z | 39,562,863 | <p>The immediate problem is your <em>scale</em> is off.</p>
<p>In this line <code>pix[x+2,y+2]=...</code>, with your ranges for <code>x</code> and <code>y</code>, the only pixels that are being drawn are <code>0..4</code>. Since the last few pixels drawn are black, the entire top left 4x4 square is black (and the rest... | 2 | 2016-09-18T21:29:13Z | [
"python",
"python-imaging-library"
] |
I want use different kernels on jupyter, but how can I install different libraries on different kernel? | 39,562,730 | <p>I have two kernels on my jupyter, one is py2.7 and the other is py3.5, but how can I install different libraries like pandas or numpy for py2.7?</p>
| 1 | 2016-09-18T21:12:16Z | 39,562,849 | <p>You ought to use a <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a>: this create a local copy of the Python of your choice. </p>
<p>Then you can use <a href="https://pypi.python.org/pypi/pip" rel="nofollow">pip</a> to install libraries like Pandasâ¦</p>
<p>But, before, install Jupyter... | 1 | 2016-09-18T21:27:53Z | [
"python",
"jupyter"
] |
HTML between extension tags | 39,562,731 | <p>Lets say I have an extension in Jinja. I want the extension to have the form: </p>
<pre><code>{% start %}
<h1>{{ something }}</h1>
<p>{{ something.else }}</p>
{% for content in lst %}
<h3>{{ i.name }}</h3>
{% endfor %}
{% end %}
</code></pre>
<p>In my ext... | 0 | 2016-09-18T21:12:19Z | 39,586,483 | <p>If your desire output is {{something}}, then you can use "raw" block in jinja.</p>
<pre><code>{% raw %}
<h1>{{ something }}</h1>
{% endraw %}
</code></pre>
<p>It will print "{{something}}" (with curly braces).</p>
| 0 | 2016-09-20T05:42:27Z | [
"python",
"flask",
"jinja2"
] |
How to add new blank row in the middle of text in Google Docs when using gspread module for python? | 39,562,807 | <p>I tried to insert a new blank row example after 8 rows with <code>insert_row</code> or <code>append_row</code> or <code>add_row</code>, but they only add a new row in the end of the sheet.</p>
<p>My question is how to correctly insert the row ?</p>
<p>Also, I read <a href="http://gspread.readthedocs.io/en/latest/i... | 0 | 2016-09-18T21:23:19Z | 39,925,772 | <p><a href="http://gspread.readthedocs.io/en/latest/index.html?highlight=row#gspread.Worksheet.insert_row" rel="nofollow">Worksheet.insert_row()</a> is the way to go</p>
<p>Notice that you must supply the index for where the rows will be inserted.</p>
<p>As for how to insert a certain number of rows your best bet is ... | 0 | 2016-10-07T21:03:53Z | [
"python",
"gspread"
] |
How to find max in dataframe with in a certain length in python? | 39,562,824 | <p>Here's my DataFrame:</p>
<pre><code>DATE_TIME
1997-02-25 12:50:00 3238.0
1997-02-25 12:55:00 3237.5
1997-02-25 13:00:00 3237.5
1997-02-25 13:05:00 3237.5
1997-02-25 13:10:00 3239.0
1997-02-25 13:15:00 3242.0
</code></pre>
<p>I'm trying to find a way to find the max for every 2 intervals back and ... | 1 | 2016-09-18T21:24:58Z | 39,562,852 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rolling.html" rel="nofollow">.rolling().max()</a> method:</p>
<pre><code>In [141]: df
Out[141]:
DATE_TIME VAL
0 1997-02-25 12:50:00 3238.0
1 1997-02-25 12:55:00 3237.5
2 1997-02-25 13:00:00 3237.5
3 1997-02-2... | 1 | 2016-09-18T21:28:11Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Pandas groupby where all columns are added to a list prefixed by column name | 39,562,915 | <p>I have a CSV file that looks like this:</p>
<pre><code>id1,feat1,feat2,feat3
a,b,asd,asg
c,d,dg,ag
a,e,sdg,as
c,f,as,sdg
c,g,adg,sd
</code></pre>
<p>I read it in to a dataframe with <code>df = pd.read_csv("file.csv")</code>.</p>
<p>I would like group by <code>id1</code> and combine all the other columns in one l... | 3 | 2016-09-18T21:35:22Z | 39,568,940 | <p>Applying this function will work:</p>
<pre><code>def func(dfg):
dfu = dfg.unstack()
result = dfu.index.get_level_values(0) + '=' + dfu.values
return result.tolist()
df.groupby('id1').apply(func)
</code></pre>
<hr>
<p><strong>Explanation</strong>: let's consider one group, for instance <code>dfg = df[... | 1 | 2016-09-19T08:48:14Z | [
"python",
"pandas"
] |
Pandas groupby where all columns are added to a list prefixed by column name | 39,562,915 | <p>I have a CSV file that looks like this:</p>
<pre><code>id1,feat1,feat2,feat3
a,b,asd,asg
c,d,dg,ag
a,e,sdg,as
c,f,as,sdg
c,g,adg,sd
</code></pre>
<p>I read it in to a dataframe with <code>df = pd.read_csv("file.csv")</code>.</p>
<p>I would like group by <code>id1</code> and combine all the other columns in one l... | 3 | 2016-09-18T21:35:22Z | 39,568,945 | <p>You can use a custom function and <code>apply</code> on the <code>groupby</code> object, the function calls <code>apply</code> again on the Series passed to zip the column names and values into a list, we then perform a list comprehension and return this inside a list as desired:</p>
<pre><code>In [54]:
def foo... | 2 | 2016-09-19T08:48:33Z | [
"python",
"pandas"
] |
how i will remove widget with click button on another class (PyQt) | 39,562,929 | <p>there is an error, how can i provide this?
i want to remove widgets with remove button. is this okay <code>self.removeButton.clicked.connect(self.removing.remove_widget)</code> ? i tried to connect another class with a pushbutton.</p>
<pre><code>from PyQt4 import QtGui, QtCore
import sys
class Main(QtGui... | 0 | 2016-09-18T21:37:51Z | 39,565,252 | <p>You created a new class Test, and connected the new Test then the button del it.</p>
<p>You could try this.</p>
<pre><code>self.kod = []
self.removeButton=QtWidgets.QPushButton("remove widget")
self.removeButton.clicked.connect(self.remove_widget)
...
def addWidget(self):
temp = Test()
self.kod.append(tem... | 0 | 2016-09-19T04:12:48Z | [
"python",
"qt",
"python-3.x",
"pyqt",
"pyqt4"
] |
Error when running TensorFlow image retraining tutorial | 39,562,938 | <p>I have a very basic question about TensorFlow. I'm following the <a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/index.html?index=..%2F..%2Findex#4" rel="nofollow">"TensorFlow for Poets" tutorial</a>, and I'm stuck at the image retraining, when I try to run this command:</p>
<pre><code... | 0 | 2016-09-18T21:40:07Z | 39,563,170 | <p>From the error message, it looks like you have pasted the exact command from your question (and from the original tutorial) into the shell, and the <code>#</code> at the beginning was interpreted as a comment, and it's trying to execute the second line as a command.</p>
<p>If you paste the command <strong>without t... | 2 | 2016-09-18T22:14:25Z | [
"python",
"tensorflow"
] |
predict external dataset with models from random forest | 39,562,939 | <p>I used <code>joblib.dump</code> in python to save models from 5 fold cross validation modelling using random forest. As a result I have 5 models for each dataset saved as: <code>MDL_1.pkl, MDL_2.pkl, MDL_3.pkl, MDL_4.pkl, MDL_5.pkl</code>. Now I want to use these models for prediction of external dataset using <code... | 0 | 2016-09-18T21:40:11Z | 39,563,394 | <p>First of all, you should not save the result of cross validation. Cross validation <strong>is not</strong> a training method, it is <strong>an evaluation scheme</strong>. You should build <strong>a single model</strong> on your whole dataset and use it to predict.</p>
<p>If, for some reason, you can no longer train... | 0 | 2016-09-18T22:54:45Z | [
"python"
] |
`Iterable[(int, int)]` tuple is not allowed in type hints | 39,562,977 | <p>I have this very simple code:</p>
<pre><code>from typing import List, Iterable
Position = (int, int)
IntegerMatrix = List[List[int]]
def locate_zeros(matrix: IntegerMatrix) -> Iterable[Position]:
"""Given an NxM matrix find the positions that contain a zero."""
for row_num, row in enumerate(matrix):
... | 4 | 2016-09-18T21:44:15Z | 39,563,026 | <p>You should use <code>typing.Tuple[int, int]</code> to declare the tuple type <code>Position</code>, not <code>(int, int)</code>.</p>
| 5 | 2016-09-18T21:53:04Z | [
"python",
"python-3.5",
"typing"
] |
Counting values using pandas groupby | 39,563,028 | <p>Here is my data frame</p>
<pre><code>data = {'Date' : ['08/20/10','08/20/10','08/20/10','08/21/10','08/22/10','08/24/10','08/25/10','08/26/10'] , 'Receipt' : [10001,10001,10002,10002,10003,10004,10004,10004],
'Product' : ['xx1','xx2','yy1','fff4','gggg4','fsf4','gggh5','hhhg6']}
dfTest = pd.DataFrame(data)
dfTe... | 2 | 2016-09-18T21:53:21Z | 39,563,053 | <p>try this:</p>
<pre><code>In [191]: dfTest.groupby('Date').Receipt.nunique()
Out[191]:
Date
08/20/10 2
08/21/10 1
08/22/10 1
08/24/10 1
08/25/10 1
08/26/10 1
Name: Receipt, dtype: int64
</code></pre>
<p>or this, depending on your goal:</p>
<pre><code>In [188]: dfTest.groupby(['Date','Receipt']).P... | 2 | 2016-09-18T21:56:38Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Downloading dynamically loaded webpage with python | 39,563,192 | <p>I have this <a href="http://bonusbagging.co.uk/oddsmatching.php#" rel="nofollow">website</a> and I want to download the content of the page.</p>
<p>I tried <strong>selenium</strong>, and button clicking with it, but with no success.</p>
<pre><code>#!/usr/bin/env python
from contextlib import closing
from selenium.... | 1 | 2016-09-18T22:17:47Z | 39,563,753 | <p>I always try to avoid selenium like the plague when scraping; it's very slow and is almost never the best way to go about things. You should dig into the source more before scraping; it was clear on this page that the html was coming in and then a separate call was being made to get the table's data. Why not make th... | 1 | 2016-09-19T00:04:18Z | [
"javascript",
"jquery",
"python",
"html",
"selenium"
] |
Downloading dynamically loaded webpage with python | 39,563,192 | <p>I have this <a href="http://bonusbagging.co.uk/oddsmatching.php#" rel="nofollow">website</a> and I want to download the content of the page.</p>
<p>I tried <strong>selenium</strong>, and button clicking with it, but with no success.</p>
<pre><code>#!/usr/bin/env python
from contextlib import closing
from selenium.... | 1 | 2016-09-18T22:17:47Z | 39,563,813 | <p>Check out the Network tab in Chrome Dev tools. Nab <a href="http://bonusbagging.co.uk/odds-server/getdata_slow.php?draw=1&columns%5B0%5D%5Bdata%5D=rating&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&col... | 0 | 2016-09-19T00:14:57Z | [
"javascript",
"jquery",
"python",
"html",
"selenium"
] |
Unable to delete first row in matrix | 39,563,209 | <p>I am stuck when trying to delete the first row from the <code>log_returns</code> matrix. Essentially, I'd like to get rid of the first row because it has NaN values. I have tried <code>isnan()</code> without joy, and finally landed on the <code>numpy.delete()</code> method which sounds most promising but still doesn... | 1 | 2016-09-18T22:20:20Z | 39,563,261 | <p>Demo:</p>
<pre><code>In [202]: from pandas_datareader import data as web
In [218]: df = web.DataReader('XOM', 'yahoo', start='1/1/2010')['Adj Close']
In [219]: pd.options.display.max_rows = 10
In [220]: df
Out[220]:
Date
2010-01-04 57.203028
2010-01-05 57.426378
2010-01-06 57.922715
2010-01-07 57.740... | 0 | 2016-09-18T22:31:24Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
AI multiple input conversation with if statements in while loop doesn't work? | 39,563,226 | <p>My AI i am making works in a while loop there are if statements for everything i want it to say for example:</p>
<pre><code>`while 1:
lis = ("im bored","game","im board","what do you want to do","what should we do","rage","i","I","smashed","broke","destroyed","cracked","grounded","detention","in trouble","nothin... | -3 | 2016-09-18T22:23:58Z | 39,968,262 | <p>i figured it out you need to put an if statement inside the if statement</p>
<pre><code>if esa in ("im grounded","im in trouble","i have detention","i got detention"):
punish = random.choice(("your always getting in trouble its like second nature for you lol","to bad i guess no fun for a while well its y... | 0 | 2016-10-10T23:28:10Z | [
"python",
"string",
"python-3.x",
"if-statement",
"while-loop"
] |
How to write a dict to a csv | 39,563,314 | <p>I have a CSV file with one column that has a person's first and last name. I am trying to use a CSV to split each name into two columns, first and last. The code below splits all of the first names into one row and all of the last names into one row instead of having a first name into a row and the last name in the ... | 0 | 2016-09-18T22:41:18Z | 39,563,404 | <p>You can use pandas to write your csv (you could actually use pandas for the whole problem), this will automatically transpose you data from a dict of columns to a list of rows:</p>
<pre><code>import pandas as pd
df = pd.DataFrame(newcsvdict)
df.to_csv('new.csv', index=False)
</code></pre>
| 0 | 2016-09-18T22:56:33Z | [
"python"
] |
How to write a dict to a csv | 39,563,314 | <p>I have a CSV file with one column that has a person's first and last name. I am trying to use a CSV to split each name into two columns, first and last. The code below splits all of the first names into one row and all of the last names into one row instead of having a first name into a row and the last name in the ... | 0 | 2016-09-18T22:41:18Z | 39,563,477 | <p>You're creating a single list associated with key. Either use Pandas, as @maxymoo suggested, or write each line separately.</p>
<pre><code>import csv
with open(r'~/Documents/names.csv', 'r') as fh:
reader = csv.reader(fh)
with open(r'~/Documents/output.csv', 'w+') as o:
writer = csv.writer(o)
... | 0 | 2016-09-18T23:08:07Z | [
"python"
] |
How to write a dict to a csv | 39,563,314 | <p>I have a CSV file with one column that has a person's first and last name. I am trying to use a CSV to split each name into two columns, first and last. The code below splits all of the first names into one row and all of the last names into one row instead of having a first name into a row and the last name in the ... | 0 | 2016-09-18T22:41:18Z | 39,563,727 | <p>In this simple case there is little benefit in using a <code>csv.DictWriter</code>, just use <code>csv.writer</code>:</p>
<pre><code>import csv
header = ['first name', 'last name']
with open('fullnames.csv', 'r') as infile, open('new.csv', 'w') as outfile:
writer = csv.writer(outfile)
writer.writerow(heade... | 1 | 2016-09-18T23:58:26Z | [
"python"
] |
How to pull discount rate from if statement | 39,563,430 | <p>I need to calculate the total purchase price of the books. The discount is determined by the amount of books purchased. Those are split within the if statements. How can I have my code fully work? I am currently getting this error message: </p>
<p><a href="http://i.stack.imgur.com/GyRhK.png" rel="nofollow"><img src... | 0 | 2016-09-18T23:00:46Z | 39,563,454 | <p>Your last function is currently written as</p>
<pre><code>def totalPrice(theTotalPrice):
</code></pre>
<p>but your argument should be</p>
<pre><code>def totalPrice(numBooks):
</code></pre>
<p>In fact, you appear to pass the correct argument to this function in <code>main</code>, it is just a mistake in the actua... | 0 | 2016-09-18T23:04:34Z | [
"python",
"if-statement",
"module"
] |
How to pull discount rate from if statement | 39,563,430 | <p>I need to calculate the total purchase price of the books. The discount is determined by the amount of books purchased. Those are split within the if statements. How can I have my code fully work? I am currently getting this error message: </p>
<p><a href="http://i.stack.imgur.com/GyRhK.png" rel="nofollow"><img src... | 0 | 2016-09-18T23:00:46Z | 39,563,535 | <p>Basically, you're not giving your functions all the variables that they need. In <code>eligibleDiscounts</code> you reference a variable <code>totalPrice</code>. Where is that value being defined? Is it meant to be <code>BOOK_PRICE * numBooks</code>?</p>
<p>Similar thing in <code>totalPrice</code>. If you want it t... | 0 | 2016-09-18T23:18:45Z | [
"python",
"if-statement",
"module"
] |
How to pull discount rate from if statement | 39,563,430 | <p>I need to calculate the total purchase price of the books. The discount is determined by the amount of books purchased. Those are split within the if statements. How can I have my code fully work? I am currently getting this error message: </p>
<p><a href="http://i.stack.imgur.com/GyRhK.png" rel="nofollow"><img src... | 0 | 2016-09-18T23:00:46Z | 39,563,975 | <p>Here is the edited code. The first error was that you were returning the values from the functions, but there was no variable being assigned to the return value. Variables created inside a function lives only inside the function. Study the code below and see what changes I made. Ask if you have questions. Also you h... | 1 | 2016-09-19T00:47:54Z | [
"python",
"if-statement",
"module"
] |
Pandas tz_localize: Infer dst when localizing timezone in data with duplicates | 39,563,507 | <p>I want to localize a datetime series with pandas tz_localize. The series crosses a DST date (e.g. 25Oct2015 for Germany CET). I usually do this with</p>
<pre><code>import pandas as pd
T = ['25/10/2015 02:59:00','25/10/2015 02:00:00','25/10/2015 02:01:00']
pd.to_datetime(T).tz_localize('CET',ambiguous='infer')
</cod... | 1 | 2016-09-18T23:12:33Z | 39,570,965 | <p>There were a number of DST related bugs fixed in the latest version, 0.19.0rc1 is out now</p>
<pre><code>In [1]: pd.__version__
Out[1]: u'0.19.0rc1'
In [2]: t = ['25/10/2015 02:59:00', '25/10/2015 02:00:00', '25/10/2015 02:01:00']
In [3]: pd.to_datetime(t).tz_localize('CET',ambiguous='infer')
Out[3]: DatetimeInde... | 0 | 2016-09-19T10:29:46Z | [
"python",
"datetime",
"pandas",
"timezone"
] |
imshow() function displays empty gray image. What do I do? | 39,563,656 | <p>When I try to use <code>cv2.imshow()</code> it gives a shows the image for a second, then makes the window go gray. I can't seem to find anything about it, except that I should use <code>cv2.waitKey(0)</code>, which I am, and also to use <code>cv2.namedWindow()</code>. My code:</p>
<pre><code>import numpy as np
imp... | 0 | 2016-09-18T23:44:46Z | 39,702,260 | <ol>
<li>check your sys.argv[1], try to replace with real path (i.e. "images/1.png")</li>
<li>destroyAllWindows() it is the function (use brackets)</li>
<li>parameter of waitKey (0 in your example) it is delay in ms, 0 means "forever", default value of delay is 0.</li>
<li>in fact you don't need namedWindow and destroy... | 0 | 2016-09-26T11:59:09Z | [
"python",
"opencv"
] |
How does one return a random number from a dictionary every time a key is called? | 39,563,672 | <p>I am trying to create a weapon that provides random damage. I am doing so using an item database in the form</p>
<pre><code>itemsList = {
1: {"name": "Padded Armor", "armor": 1, "value": 5, "class": "Light"},
2: {"name": "Leather Armor", "armor": 2, "value": 10, "class": "Light"},
....
19: {"name": "Dagger", "d... | 2 | 2016-09-18T23:48:32Z | 39,563,714 | <p>You would store a function that generates a random number, not the random number itself, in the dictionary. (By the way, if your dictionary's keys are just sequential integers, consider using a list instead.) </p>
<pre><code>from random import randrange
itemsList = [
{"name": "Padded Armor", "armor": 1, "va... | 3 | 2016-09-18T23:55:40Z | [
"python",
"dictionary",
"random",
"properties",
"python-descriptors"
] |
How does one return a random number from a dictionary every time a key is called? | 39,563,672 | <p>I am trying to create a weapon that provides random damage. I am doing so using an item database in the form</p>
<pre><code>itemsList = {
1: {"name": "Padded Armor", "armor": 1, "value": 5, "class": "Light"},
2: {"name": "Leather Armor", "armor": 2, "value": 10, "class": "Light"},
....
19: {"name": "Dagger", "d... | 2 | 2016-09-18T23:48:32Z | 39,563,871 | <p>I would go to the trouble of making the things in <code>itemsList</code> instances of a class. Although you might think that's overkill, doing it will give you a lot of programming flexibility later. It'll also make a lot of the code easier to write (and read) because you'll be able to refer to things using dot nota... | 3 | 2016-09-19T00:26:50Z | [
"python",
"dictionary",
"random",
"properties",
"python-descriptors"
] |
How does one return a random number from a dictionary every time a key is called? | 39,563,672 | <p>I am trying to create a weapon that provides random damage. I am doing so using an item database in the form</p>
<pre><code>itemsList = {
1: {"name": "Padded Armor", "armor": 1, "value": 5, "class": "Light"},
2: {"name": "Leather Armor", "armor": 2, "value": 10, "class": "Light"},
....
19: {"name": "Dagger", "d... | 2 | 2016-09-18T23:48:32Z | 39,563,986 | <p>You may find it reduces the repetition in your code to store just the damage weighting (still called <code>damage</code> in my code) in your dictionary and have a separate function to calculate the actual damage. e.g.</p>
<pre><code>from random import randint
itemsList = {
1: {"name": "Padded Armor", "armor": 1, ... | 3 | 2016-09-19T00:50:09Z | [
"python",
"dictionary",
"random",
"properties",
"python-descriptors"
] |
Access values for a dictionary within a list in a column of a pandas dataframe | 39,563,719 | <p>I have a column in a pandas dataframe, where each row is a list with a dictionary inside, like this:</p>
<pre><code>urls
---------------------------------------------------------
[{'url': http://t.co, 'expanded_url':http://nytimes.com}]
[{'url': http://t.co, 'expanded_url':http://time.com}]
[]
</code></pre>
<p>So... | 2 | 2016-09-18T23:56:46Z | 39,563,836 | <p>You can try this:</p>
<pre><code>def get_expanded_url(outterlist):
try:
return outterlist[0]['expanded_url']
except IndexError:
return None
df.urls.apply(get_expanded_url)
</code></pre>
<p>The function will try to obtain the url that you want. If it can't, it will return <code>None</code>.... | 1 | 2016-09-19T00:20:48Z | [
"python",
"pandas"
] |
Python: curl -F equivalent with Requests or other | 39,563,786 | <p>I want to reproduce the following curl -F request (<a href="https://developers.facebook.com/docs/messenger-platform/send-api-reference/image-attachment" rel="nofollow">from the Messenger API</a>) to send an image file and parameters to Messenger's Send API:</p>
<pre><code>curl \
-F recipient='{"id":"USER_ID"}' \
-... | 0 | 2016-09-19T00:11:09Z | 39,574,744 | <p>This was the correct format:</p>
<pre><code>imgName = "tmp/graph.png"
files = { "filedata" : ('filename.png', open(imagePath, 'rb'), 'image/png')}
data = {
"recipient":'{"id":"' + id + '"}',
"message":'{"attachment":{"type":"image", "payload":{}}}'
}
r = requests.post('https://graph.facebook.com/v2.... | 1 | 2016-09-19T13:44:28Z | [
"python",
"facebook",
"curl",
"python-requests",
"messenger"
] |
Python: curl -F equivalent with Requests or other | 39,563,786 | <p>I want to reproduce the following curl -F request (<a href="https://developers.facebook.com/docs/messenger-platform/send-api-reference/image-attachment" rel="nofollow">from the Messenger API</a>) to send an image file and parameters to Messenger's Send API:</p>
<pre><code>curl \
-F recipient='{"id":"USER_ID"}' \
-... | 0 | 2016-09-19T00:11:09Z | 39,574,774 | <p>I believe the issue is that you are trying to send formdata inside the requests file kwarg, when it should be in data:</p>
<pre><code>data = {
'recipient': '{"id":"USER_ID"}',
'message': '{"attachment":{"type":"image", "payload":{}}}'
}
files = {
"filedata": open(imagePath, 'rb')
}
r = requests.post('ht... | 1 | 2016-09-19T13:45:54Z | [
"python",
"facebook",
"curl",
"python-requests",
"messenger"
] |
subprocess.CalledProcessError: what *is* the error? | 39,563,802 | <pre><code>import subprocess
cmd = "grep -r * | grep jquery"
print cmd
subprocess.check_output(cmd, shell=True)
</code></pre>
<p><strong>subprocess.CalledProcessError: Command 'grep -r * | grep jquery' returned non-zero exit status 1</strong></p>
<p>I can execute that command in my shell without issues. How can I s... | 1 | 2016-09-19T00:13:39Z | 39,563,839 | <p><a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">Quoting docs</a>:</p>
<blockquote>
<p>If the return code was non-zero it raises a <code>CalledProcessError</code>. The
<code>CalledProcessError</code> object will have the return code in the <code>returncode</code>
attribute and any ou... | 2 | 2016-09-19T00:21:11Z | [
"python",
"subprocess"
] |
subprocess.CalledProcessError: what *is* the error? | 39,563,802 | <pre><code>import subprocess
cmd = "grep -r * | grep jquery"
print cmd
subprocess.check_output(cmd, shell=True)
</code></pre>
<p><strong>subprocess.CalledProcessError: Command 'grep -r * | grep jquery' returned non-zero exit status 1</strong></p>
<p>I can execute that command in my shell without issues. How can I s... | 1 | 2016-09-19T00:13:39Z | 39,563,842 | <p>"non-zero exit status" means that the <em>command you ran</em> indicated a status other than success. For <code>grep</code>, the documentation explicitly indicates that an exit status of 1 indicates no lines were found, whereas an exit status more than 1 indicates that some other error took place.</p>
<p>To quote t... | 3 | 2016-09-19T00:21:14Z | [
"python",
"subprocess"
] |
How to include chromedriver with pyinstaller? | 39,563,851 | <p>I am using pyinstaller to create an executable of my python script.<br>
In the script I'm using these imports:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
etc...
</code></pre>
<p>The problem is, when running <code>pyinstaller myscript.py</code> , it will resu... | 1 | 2016-09-19T00:23:42Z | 39,648,291 | <p>It should be added as a binary file, since it is a binary file...<br>
So a custom spec file needed where the chromedriver's path on the local system and the desired location relative to the dist\myscript should be defined, so it looks something like this:<br></p>
<pre><code>.....
a = Analysis(['myscript.py'],
... | 0 | 2016-09-22T20:26:52Z | [
"python",
"windows",
"selenium",
"selenium-chromedriver",
"pyinstaller"
] |
How to get randomly select n elements from a list using in numpy? | 39,563,859 | <p>I have a list of vectors:</p>
<pre><code>>>> import numpy as np
>>> num_dim, num_data = 10, 5
>>> data = np.random.rand(num_data, num_dim)
>>> data
array([[ 0.0498063 , 0.18659463, 0.30563225, 0.99681495, 0.35692358,
0.47759707, 0.85755606, 0.39373145, 0.54677259,... | -1 | 2016-09-19T00:24:50Z | 39,563,965 | <p>As @ayhan confirmed, it can be done as such:</p>
<pre><code>>>> data[np.random.choice(len(data), size=3, replace=False)]
array([[ 0.80716045, 0.84998745, 0.17893211, 0.36206016, 0.69604008,
0.27249491, 0.92570247, 0.446499 , 0.34424945, 0.08576628],
[ 0.35311449, 0.67901964, 0.71... | 2 | 2016-09-19T00:45:29Z | [
"python",
"numpy",
"random",
"sample",
"choice"
] |
How to use SMTP header and send SendGrid email? | 39,563,869 | <p>I'm working on creating a SendGrid python script that sends emails when executed. I followed the example script <a href="https://github.com/sendgrid/smtpapi-python/blob/master/examples/example.py" rel="nofollow">here</a>, but all this does is generate my custom SMTP API Header. How do I actually send the email? Than... | 0 | 2016-09-19T00:26:23Z | 39,564,053 | <p>That library seems to be for generating SMTP API headers. You would want to use this library for sending emails - <a href="https://github.com/sendgrid/sendgrid-python" rel="nofollow">https://github.com/sendgrid/sendgrid-python</a></p>
<pre><code>import sendgrid
import os
from sendgrid.helpers.mail import *
sg = se... | 0 | 2016-09-19T01:02:01Z | [
"python",
"email",
"smtp",
"sendgrid"
] |
How to read the elements as "columns" from a file? | 39,563,957 | <p>I have the following file that has a number of rows as follows</p>
<pre><code>qt1l 1 A B 90 1 3.00
jqlt1l 2 B Z 20 5 6.00
ahyttl 3 F O 45 33 53.00
kqll 4 L L 70 22 22.00
gqlt1l 5 T U 90 6 77.00
with open('c:/test/file.txt','r') as f:
inp... | -1 | 2016-09-19T00:43:40Z | 39,564,018 | <pre><code>x = 1 # example values
y = 1
z = 1
count = 0
for line in inputfile:
# This splits on whitespace.
# E.g., for the first row:
# columns = ['qt1l', '1', 'A', 'B', '90', '1', '3.00']
columns = line.split()
# Note that indexes into lists are 0-based, so "column 4" is columns[3]
if (colu... | 3 | 2016-09-19T00:55:11Z | [
"python",
"row",
"multiple-columns",
"element"
] |
VENV : Accessing system packages? | 39,564,037 | <p>I want to be able to access a module installed system-wide after the venv was created.
You can see that I can access bcrypt when outside VENV w/o problem, but not inside it
(btw. installation of bcrypt inside VENV fails)</p>
<pre><code># apt-get install python-bcrypt
$ python -c 'import bcrypt'
$ . venv/bin/activ... | 0 | 2016-09-19T00:58:35Z | 39,564,235 | <p>the correct cmd is (venv vs env) :</p>
<pre><code>(venv)$ virtualenv venv --system-site-packages
</code></pre>
| 0 | 2016-09-19T01:35:45Z | [
"python",
"package",
"virtualenv"
] |
django-parsley: uncaught error | 39,564,107 | <p>I am using python 2.7 & django 1.10.</p>
<p>I am also using <a href="https://github.com/agiliq/Django-parsley" rel="nofollow">django-parsley</a> for the client side validation.</p>
<p>On each page I have the following error in the parsley.min.js file:</p>
<pre><code>Uncaught Error: it is not available in the ... | 0 | 2016-09-19T01:15:00Z | 39,564,350 | <p>Check your stack trace. Somehow, <code>setLocale</code> is being called with undefined or empty string as argument, instead of <code>'en'</code> or similar.</p>
| 1 | 2016-09-19T01:56:02Z | [
"javascript",
"python",
"django",
"parsley.js"
] |
Not getting any output in Django for BeautifulSoup | 39,564,141 | <p>I am trying BeautifulSoup4 in Django and I parsed an XML page with it. When I try the parsing the same XML page in a python interpreter in a different way, it works fine. But in Django, I get a page as shown below.</p>
<p><a href="http://i.stack.imgur.com/hPWuk.png" rel="nofollow"><img src="http://i.stack.imgur.com... | 2 | 2016-09-19T01:19:06Z | 39,565,263 | <p>From <a href="https://docs.djangoproject.com/en/1.10/ref/templates/api/#variables-and-lookups" rel="nofollow">documentation</a></p>
<blockquote>
<p>If any part of the variable is callable, the template system will try calling it.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>Occasionally you may want to turn o... | 0 | 2016-09-19T04:14:16Z | [
"python",
"django",
"beautifulsoup",
"render"
] |
Not getting any output in Django for BeautifulSoup | 39,564,141 | <p>I am trying BeautifulSoup4 in Django and I parsed an XML page with it. When I try the parsing the same XML page in a python interpreter in a different way, it works fine. But in Django, I get a page as shown below.</p>
<p><a href="http://i.stack.imgur.com/hPWuk.png" rel="nofollow"><img src="http://i.stack.imgur.com... | 2 | 2016-09-19T01:19:06Z | 39,578,490 | <p>To get text from XML, you need to call get_text() function.</p>
<p>Don't use:</p>
<pre><code>items.title
</code></pre>
<p>Use:</p>
<pre><code>items.title.get_text()
</code></pre>
<p>Also, it's recommended to use <strong>lxml</strong> for parsing. Install lxml python and use:</p>
<pre><code>soup = BeautifulSoup... | 1 | 2016-09-19T17:07:07Z | [
"python",
"django",
"beautifulsoup",
"render"
] |
Using a column of one DataFrame in a function - Python | 39,564,168 | <p>I have a DataFrame which has a column with unique IDs. That same ID is used elsewhere for functions I use. I have no problem using one of the individual IDs in my function, however, I would like to use a subset of those IDs in the function and then append that to a new DataFrame. </p>
<p>This is what my base DataFr... | 0 | 2016-09-19T01:24:01Z | 39,564,578 | <p>Most likely your function takes scalars as input while you pass in a pandas series (i.e., column of a dataframe). Consider a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow">pandas.Series.apply()</a> for element-wise operations. For the other positional argument... | 0 | 2016-09-19T02:30:35Z | [
"python",
"python-2.7"
] |
How to deal with Python long import | 39,564,280 | <p>This is about python long import like this:</p>
<p>from aaa.bbb.ccc.ddd.eee.fff.ggg.hhh.iii.jjj.kkk.lll.mmm.nnn.ooo import xxx</p>
<p>The length between 'from' and 'import' is already above than 80 characters, is there any better pythonic ways to deal with it?</p>
| 0 | 2016-09-19T01:45:39Z | 39,568,827 | <p>You can always wrap lines using the <code>\</code> character at the end of the line.</p>
<pre><code>from a.very.long.and.unconventional.structure.\
and.name import foo
</code></pre>
<p>For multiple statements to import after the <code>from x import</code> statement, you can use parentheses and wrap inside... | 0 | 2016-09-19T08:41:50Z | [
"python",
"python-import"
] |
How to write a fit_transformer with two inputs and include it in a pipeline in python sklearn? | 39,564,355 | <p>Given some fake data:</p>
<pre><code>X = pd.DataFrame( np.random.randint(1,10,28).reshape(14,2) )
y = pd.Series( np.repeat([0,1], [10,4]) ) # imbalanced with more 0s than 1s
</code></pre>
<p>I write a sklearn fit-transformer that under-samples the majority of y to match the length of the minority label. I want to ... | 1 | 2016-09-19T01:56:34Z | 39,564,442 | <p>You're not meant to call the estimator methods on the class directly, you're meant to call it on a class instance; this is because estimators often to have some type of stored state (the model coefficients for example):</p>
<pre><code>u = UnderSampling()
a,b = u.fit(X, y)
a,b = u.fit_transform(X, y)
</code></pre>
| 0 | 2016-09-19T02:09:49Z | [
"python",
"scikit-learn",
"pipeline",
"transformer"
] |
Beautiful Soup has extra </body> before actual end | 39,564,359 | <p>I am trying to scrape poems from PoetryFoundation.org. I have found in one of my test cases that when I pull the html from a specific poem it includes an extra <code></body></code> before the end of the actual poem. I can look at the source code for the poem online and there is no in the middle of the poem (a... | 1 | 2016-09-19T01:57:33Z | 39,564,953 | <p>When I try to get the poem with your url with <code>html.parser</code>,I got the same problem as you.The html was truncated at the <code>in the poem</code> position.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
poem_page = requests.get("https://www.poetryfoundation.org/poems-and-poets/poems/detail/... | 0 | 2016-09-19T03:31:49Z | [
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
Create new column in pandas based on value of another column | 39,564,372 | <p>I have some dataset about genders of various individuals. Say, the dataset looks like this:</p>
<pre><code>Male
Female
Male and Female
Male
Male
Female
Trans
Unknown
Male and Female
</code></pre>
<p>Some identify themselves as Male, some female and some identify themselves as both male and female.</p>
<p>Now, wha... | 1 | 2016-09-19T01:58:44Z | 39,564,558 | <p>Create a mapping function, and use that to map the values.</p>
<pre><code>def map_identity(identity):
if gender.lower() == 'male':
return 1
elif gender.lower() == 'female':
return 2
else:
return 3
df["B"] = df["A"].map(map_identity)
</code></pre>
| 0 | 2016-09-19T02:28:13Z | [
"python",
"pandas"
] |
Create new column in pandas based on value of another column | 39,564,372 | <p>I have some dataset about genders of various individuals. Say, the dataset looks like this:</p>
<pre><code>Male
Female
Male and Female
Male
Male
Female
Trans
Unknown
Male and Female
</code></pre>
<p>Some identify themselves as Male, some female and some identify themselves as both male and female.</p>
<p>Now, wha... | 1 | 2016-09-19T01:58:44Z | 39,566,156 | <p>You can use:</p>
<pre><code>def gender(x):
if "Female" in x and "Male" in x:
return 3
elif "Male" in x:
return 1
elif "Female" in x:
return 2
else: return 4
df["Gender Values"] = df["Gender"].apply(gender)
print (df)
Gender Gender Values
0 Male ... | 1 | 2016-09-19T05:51:13Z | [
"python",
"pandas"
] |
How can I use a 2D array of boolean rows to filter another 2D array? | 39,564,421 | <p>I have some data in a (3, m) array.</p>
<p>I have another array of masks in (n, 3) shape. The rows of this mask are boolean filters that need to be applied on the data array before performing some function. Is there a vectorized way to apply the filter and compute the function?</p>
<p>Here's an example using a l... | 4 | 2016-09-19T02:06:38Z | 39,564,738 | <p>This feels a bit crude and messy, but it does work without a loop.</p>
<p>There are two main tasks:</p>
<ul>
<li>expand <code>data</code> so it can be indexed with <code>masks</code> - from (5,4) to (5,3,4) </li>
<li>apply <code>means</code> to groups of rows; the closest I can find is <code>np.sum.reduceat</code>... | 0 | 2016-09-19T02:59:33Z | [
"python",
"performance",
"numpy",
"vectorization"
] |
How can I use a 2D array of boolean rows to filter another 2D array? | 39,564,421 | <p>I have some data in a (3, m) array.</p>
<p>I have another array of masks in (n, 3) shape. The rows of this mask are boolean filters that need to be applied on the data array before performing some function. Is there a vectorized way to apply the filter and compute the function?</p>
<p>Here's an example using a l... | 4 | 2016-09-19T02:06:38Z | 39,565,286 | <p>So, after playing with it for a while, seems this kind of broadcasting works for mean() as the function specifically:</p>
<pre><code>means = (masks[:, :, np.newaxis] * data).sum(axis=1) / masks.sum(axis=1)[:, np.newaxis]
# means
array([[ 2., 3., 4., 5.],
[ 4., 5., 6., 7.],
[ 6., 7., 8., 9.],... | 0 | 2016-09-19T04:16:58Z | [
"python",
"performance",
"numpy",
"vectorization"
] |
How can I use a 2D array of boolean rows to filter another 2D array? | 39,564,421 | <p>I have some data in a (3, m) array.</p>
<p>I have another array of masks in (n, 3) shape. The rows of this mask are boolean filters that need to be applied on the data array before performing some function. Is there a vectorized way to apply the filter and compute the function?</p>
<p>Here's an example using a l... | 4 | 2016-09-19T02:06:38Z | 39,582,944 | <p>That problem is easily solvable with <code>matrix-multiplication</code> using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html" rel="nofollow"><code>np.dot</code></a> and as such must be really efficient. Here's the implementation -</p>
<pre><code>np.true_divide(masks.dot(data),masks.sum(... | 0 | 2016-09-19T22:17:46Z | [
"python",
"performance",
"numpy",
"vectorization"
] |
Adding a column to a Multiindex Dataframe | 39,564,433 | <blockquote>
<blockquote>
<p>I would like to add a column SUM to the df1 below. It's a Datetime MultiIndex and the new column SUM should return the sum of the price
row.</p>
</blockquote>
</blockquote>
<pre><code>> multex = pd.MultiIndex.from_product([['price',
'weight','quantity','portfolio'] ,df1.ind... | 1 | 2016-09-19T02:08:11Z | 39,565,969 | <p>You can use first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>DataFrame.sort_index</code></a>, because error:</p>
<blockquote>
<p>KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (1)'</p>
<... | 1 | 2016-09-19T05:30:49Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Python's Popen + communicate only returning the first line of stdout | 39,564,455 | <p>I'm trying to use my command-line git client and Python's I/O redirection in order to automate some common operations on a lot of git repos.
(Yes, this is hack-ish. I might go back and use a Python library to do this later, but for now it seems to be working out ok :) )</p>
<p>I'd like to be able to capture the ou... | 1 | 2016-09-19T02:12:03Z | 39,564,562 | <p>Try adding the <code>--progress</code> option to your git command. This forces git to emit the progress status to stderr even when the the git process is not attached to a terminal - which is the case when running git via the <code>subprocess</code> functions.</p>
<pre><code>git_cmd = "git clone --progress git@192.... | 1 | 2016-09-19T02:28:43Z | [
"python",
"git",
"popen",
"communicate"
] |
Python's Popen + communicate only returning the first line of stdout | 39,564,455 | <p>I'm trying to use my command-line git client and Python's I/O redirection in order to automate some common operations on a lot of git repos.
(Yes, this is hack-ish. I might go back and use a Python library to do this later, but for now it seems to be working out ok :) )</p>
<p>I'd like to be able to capture the ou... | 1 | 2016-09-19T02:12:03Z | 39,565,119 | <p>There are two parts of interest here, one being Python-specific and one being Git-specific.</p>
<h3>Python</h3>
<p>When using the <code>subprocess</code> module, you can elect to control up to three I/O channels of the program you run: stdin, stdout, and stderr. This is true for <code>subprocess.call</code> and <... | 1 | 2016-09-19T03:56:36Z | [
"python",
"git",
"popen",
"communicate"
] |
Cleaning string from scraping webpage python | 39,564,456 | <p>I scraped the content of a website via Python and the requests library and I tried to clean out all the html and javascript.</p>
<pre><code>from lxml.html.clean import Cleaner
import lxml.html as html
text = html.document_fromstring(r.text).text_content()
cleaner = Cleaner(kill_tags=['noscript', 'img', 'a', 'h1'], ... | 1 | 2016-09-19T02:12:12Z | 39,564,568 | <p>You need to clean <code><script></code> tags if you want to get rid of javascript. The only thing <code><noscript></code> tags are for is displaying an image or text if the browser has scripts disabled.</p>
<pre><code>cleaner = Cleaner(kill_tags=['script', 'noscript', 'img', 'a', 'h1'], remove_tags=['p'... | 1 | 2016-09-19T02:29:46Z | [
"javascript",
"python"
] |
Cleaning string from scraping webpage python | 39,564,456 | <p>I scraped the content of a website via Python and the requests library and I tried to clean out all the html and javascript.</p>
<pre><code>from lxml.html.clean import Cleaner
import lxml.html as html
text = html.document_fromstring(r.text).text_content()
cleaner = Cleaner(kill_tags=['noscript', 'img', 'a', 'h1'], ... | 1 | 2016-09-19T02:12:12Z | 39,564,596 | <p>My mistake, it was a typo in my code, but thanks for the hint! Correct code:</p>
<pre><code>from lxml.html.clean import Cleaner
import lxml.html as html
text = html.document_fromstring(r.text)
cleaner = Cleaner(kill_tags=['script', 'noscript', 'img', 'a', 'h1'], remove_tags=['p'], style=True)
cleaner(text)
text = t... | 0 | 2016-09-19T02:33:37Z | [
"javascript",
"python"
] |
How do I run an method async inside a class that is being used with asyncio.create_server? | 39,564,565 | <p>I'm using autobahn with asyncio and I'm trying to make a method inside a class that extends WebSocketServerFactory run every x seconds.</p>
<p>This is how the documentation on the autobahn website does it:</p>
<pre><code>from autobahn.asyncio.websocket import WebSocketServerFactory
factory = WebSocketServerFactory... | 0 | 2016-09-19T02:29:21Z | 39,566,070 | <p>Based on your example, the same functionality with asyncio can be done using the asyncio event loop: <a href="https://docs.python.org/3/library/asyncio-eventloop.html#delayed-calls" rel="nofollow">Asyncio delayed calls</a>.</p>
<p>So in your example that would mean something like this:</p>
<pre><code>def tick(self... | 2 | 2016-09-19T05:42:07Z | [
"python",
"python-asyncio",
"autobahn"
] |
PyQt/PySide Get Decimal Place of selected value in QSpinBOX | 39,564,574 | <p>How to query Decimal Place of selected value in QSpinBox(PyQt) ?</p>
<p>Let say QSpinBox contain value 631.1205 and user select 3 then answer should be tens.(i.e 6=Hundreds, 3=Tens, 1=Ones, 1=Tenths, 2=Hundredths, 0=Thousandths, 5=Ten-Thousandths).</p>
| 0 | 2016-09-19T02:30:17Z | 39,584,802 | <p>Let's assume you have two lists that contain the text you want to return (expand beyond thousand*s if appropriate for your use case):
big = ['Ones', 'Tens', Hundreds', 'Thousands']
small = ['Tenths', 'Hundredths', 'Thousandths'] </p>
<p>First you need to get a reference to the <code>QLineEdit</code> in the ... | 0 | 2016-09-20T02:27:00Z | [
"python",
"pyqt",
"pyside"
] |
Beautiful soup: Insert HTML5 Tag between two paragraphs | 39,564,687 | <p>I want to automate the insertion of a html tag between two paragraphs for thousand of similar pages. The snippet is something like this (the new tag must be inserted after the paragraph of header class) :</p>
<pre><code><p align="center"><span class="header">My Title</span></p>
{insert new t... | 0 | 2016-09-19T02:50:37Z | 39,565,038 | <p>Try this:</p>
<pre><code>soup = BeautifulSoup(page, 'html.parser')
p = soup.find('span', {'class': 'header'}).parent
p.insert_after(soup.new_tag('article'))
</code></pre>
<p>A quick look at the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">BeautifulSoup documentation</a> yields lo... | 0 | 2016-09-19T03:44:35Z | [
"python",
"html",
"soap"
] |
Beautiful soup: Insert HTML5 Tag between two paragraphs | 39,564,687 | <p>I want to automate the insertion of a html tag between two paragraphs for thousand of similar pages. The snippet is something like this (the new tag must be inserted after the paragraph of header class) :</p>
<pre><code><p align="center"><span class="header">My Title</span></p>
{insert new t... | 0 | 2016-09-19T02:50:37Z | 39,565,075 | <p>Wow, as the core code is showed by Trombone.I'd like to give a more complete demo.</p>
<pre><code>from bs4 import BeautifulSoup
page = """
<p align="center"><span class="header">My Title1</span></p>
<p align="center">bla-bla-bla</p>
<p align="center"><span class="header"... | 0 | 2016-09-19T03:50:22Z | [
"python",
"html",
"soap"
] |
How to modify .split function to to apply to different alpha numeric inputs? | 39,564,741 | <p>I have the following two types of input:</p>
<pre><code>## Case 1 (a)
# Input #1(a)
>qrst
ABC 10 9 7
>qqqq
ACC 2 5 3
# Case 1 (b) --> Simplified form of Case 1(a)
# Input #1()
>qrst
A 10
>qqqq
A 2
# After reading in the file and making it a list I store the above in l
l = ['ABC 10 9 7', 'ACC 2 5 3'... | 0 | 2016-09-19T03:00:07Z | 39,565,248 | <p>A regex would be a good approach for this, you're looking for a letter <code>([A-Z])</code> followed by an optional space <code>?</code> followed by one or more digits <code>(\d+)</code>:</p>
<pre><code>>>> import re
>>> re.match('([A-Z]) ?(\d+)', 'A10').groups()
('A', '10')
>>> re.match(... | 0 | 2016-09-19T04:12:20Z | [
"python",
"split",
"alphanumeric"
] |
How to modify .split function to to apply to different alpha numeric inputs? | 39,564,741 | <p>I have the following two types of input:</p>
<pre><code>## Case 1 (a)
# Input #1(a)
>qrst
ABC 10 9 7
>qqqq
ACC 2 5 3
# Case 1 (b) --> Simplified form of Case 1(a)
# Input #1()
>qrst
A 10
>qqqq
A 2
# After reading in the file and making it a list I store the above in l
l = ['ABC 10 9 7', 'ACC 2 5 3'... | 0 | 2016-09-19T03:00:07Z | 39,565,997 | <p>would this work:</p>
<pre><code>import re
input_seq = "A10 B 20 C30 D1 Z 67"
input_raw = re.split(r'([A-Z]) *(\d+)' , input_seq)
input_clean = [x for x in input_raw if x and not x.isspace()]
print zip(input_clean[::2], input_clean[1::2])
</code></pre>
<p><em>gives</em>:</p>
<pre><code>[('A', '10'), ('B', '20... | 0 | 2016-09-19T05:34:08Z | [
"python",
"split",
"alphanumeric"
] |
Python 3.5.1, the global variable is not destroyed when delete the module | 39,564,909 | <p>I have a app loading python35.dll. Use python API PyImport_AddModule to run a py file. And use PyDict_DelItemString to delete the module. There is a global vailable in the py file. The global variable is not destroyed when calling PyDict_DelItemString to delete the module. The global variable is destroyed when calli... | 2 | 2016-09-19T03:25:15Z | 39,628,866 | <p>This problem is resolved. Need to call PyGC_Collect after PyDict_DelItemString with Python post 3.4 versions.</p>
<p>For detailed info, please read <a href="http://bugs.python.org/issue28202" rel="nofollow">http://bugs.python.org/issue28202</a>.</p>
| 0 | 2016-09-22T01:28:19Z | [
"python",
"python-3.x",
"pyobject"
] |
MODBUS RTU CRC16 calculation | 39,564,916 | <p>I'm coding a MODBUS CRC16 calculator in C. What I have before is a python that do this, I wanted to convert it to C. I found some codes online but it's not giving me the correct answer.</p>
<p>For my python code, I have this as my CRC16.py</p>
<pre><code>#!/usr/bin/env python
def calc(data):
crc_table=[0x... | 0 | 2016-09-19T03:25:54Z | 39,566,555 | <ul>
<li><p><code>WORD</code> should be <code>unsigned short</code> (2 bytes), not <code>unsigned long</code> (4 or 8 bytes depended on platform)</p>
<pre><code>typedef unsigned short WORD;
</code></pre></li>
<li><p>As @paddy said, loop from 0 to 6 in the for loop:</p>
<pre><code>for (i=0; i<6; i++) {
...
}
</... | 1 | 2016-09-19T06:21:16Z | [
"python",
"c",
"checksum",
"modbus",
"crc16"
] |
Return Pandas DataFrame references/names to a list? | 39,564,956 | <p>I've defined a function that cleans a data frame and returns a new dataframe. I have many data frames that I want to run this function on. I had a list of my DFs, <code>namelist=[a,b,c]</code> and passed them in a loop through my function. I want to return a similar list, <code>cleanDFs=[aClean, bClean, cClean]</cod... | 0 | 2016-09-19T03:32:41Z | 39,565,351 | <p>I'd do</p>
<pre><code>cleadDFs = [dataCleaning(d) for d in catDFs]
</code></pre>
| 0 | 2016-09-19T04:26:10Z | [
"python",
"pandas"
] |
How to install Python 2.7.10 installation without root/sudo permission and internet connection? | 39,564,982 | <p>I have been trying to install Python 2.7.10 along with more than 15 supporting packages in the following environment.</p>
<pre><code>LSB_VERSION=base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
Red Hat Enterprise Linux Server... | 1 | 2016-09-19T03:36:08Z | 39,565,060 | <p>Use <a href="http://conda.pydata.org/miniconda.html" rel="nofollow">miniconda</a> to install a standalone python. Then create environments as needed using the miniconda tool (conda).</p>
<p>See <a href="http://stackoverflow.com/a/19170873/3586654">this answer</a> for example usage. </p>
<p>If you already have a py... | 1 | 2016-09-19T03:47:47Z | [
"python"
] |
URL template tag causing NoReverseMatch when URL name from an include is used | 39,565,046 | <p>With the following definitions:</p>
<p><strong>urls.py</strong></p>
<pre><code>urlpatterns = [
url(r'^admin/', admin.site.urls),
# Homepage
url(r'^$', projects.homepage, name='homepage'),
url(r'^create_new_project/$', projects.create_new_project),
# Project page
url(r'^(?P<project_path... | 0 | 2016-09-19T03:46:09Z | 39,565,129 | <p>Try this:</p>
<pre><code><li><a href="{% url 'projects:project-page' %}">{{ project.name }}</a></li>
</code></pre>
| 0 | 2016-09-19T03:57:20Z | [
"python",
"django",
"django-urls"
] |
URL template tag causing NoReverseMatch when URL name from an include is used | 39,565,046 | <p>With the following definitions:</p>
<p><strong>urls.py</strong></p>
<pre><code>urlpatterns = [
url(r'^admin/', admin.site.urls),
# Homepage
url(r'^$', projects.homepage, name='homepage'),
url(r'^create_new_project/$', projects.create_new_project),
# Project page
url(r'^(?P<project_path... | 0 | 2016-09-19T03:46:09Z | 39,565,284 | <pre><code>url(r'^(?P<project_path>\w+)/', include('projects.urls'))
</code></pre>
<p>if you put this url in main urls.py you need to pass the project path from the Html page other wise it will raise the exception like no reverse match so right way is </p>
<p>Main urls.py</p>
<pre><code>url(r'^$', include('pr... | 0 | 2016-09-19T04:16:49Z | [
"python",
"django",
"django-urls"
] |
Fit regression line to exponential function in python | 39,565,073 | <p>I am trying to learn how to interpret a linear regression model for an exponential function created with Python. I create a model by first transforming the exponential Y data into a straight line by taking the natural log. I then create a linear model and note the slope and intercept. Lastly, I try to compute a s... | 0 | 2016-09-19T03:49:42Z | 39,565,148 | <p>Make sure you've got the latest version of scikit; I got different coeffiecients to you: </p>
<pre><code>Slope:
[ 0.69314718]
Intercept:
4.4408920985e-16
</code></pre>
<p>And you'll need to take the <code>exp</code> of the whole expression, not just the x term:</p>
<pre><code>In [17]: np.exp(0.69314718*1.1 + 4.... | 1 | 2016-09-19T04:00:13Z | [
"python",
"python-3.x",
"numpy",
"machine-learning",
"linear-regression"
] |
Scp with subprocess python with a private key | 39,565,106 | <p>How do i get this scp command converted for python subprocess.</p>
<pre><code> scp -i /home/ramesh7128/Downloads/<private_key>.pem /home/ramesh7128/Downloads/testing_transfer.py <remote_add>:<remote_file_path>
</code></pre>
<p>esp the part to include the private key path is where i am having issu... | 0 | 2016-09-19T03:54:56Z | 39,565,158 | <p>Make sure you're including the user on the remote machine and that you've formatted things correctly:</p>
<pre><code>scp -i /home/ramesh7128/Downloads/<private_key>.pem /home/ramesh7128/Downloads/testing_transfer.py <remote_user>@<remote_add>:<remote_file_path>
scp -i private_key.pem /path/t... | 2 | 2016-09-19T04:00:51Z | [
"python",
"django",
"subprocess",
"scp"
] |
How are conditional statements with multiple conditions evaluated? | 39,565,195 | <p>I'd expect the following two code blocks to be evaluated the same way, but it would seem that is not the case.</p>
<pre><code>if True or False and False:
print('True')
else:
... | 1 | 2016-09-19T04:04:56Z | 39,565,216 | <p>This is because of <a href="https://docs.python.org/2.7/reference/expressions.html#operator-precedence" rel="nofollow">operator precedence</a>. Per the Python 2.x and 3.x docs, the <code>and</code> operator has higher precedence than the <code>or</code> operator. Also, have a look at the boolean truth table:</p>
<p... | 3 | 2016-09-19T04:07:53Z | [
"python"
] |
How are conditional statements with multiple conditions evaluated? | 39,565,195 | <p>I'd expect the following two code blocks to be evaluated the same way, but it would seem that is not the case.</p>
<pre><code>if True or False and False:
print('True')
else:
... | 1 | 2016-09-19T04:04:56Z | 39,565,234 | <p><code>(True or False)</code> evaluates to <code>True</code>. Therefore <code>(True or False) and False</code> evaluates to <code>True and False</code>, which evaluates to <code>False</code>.</p>
<p>This answer explains the rules for boolean evaluation quite well: <a href="http://stackoverflow.com/a/16069560/1470749... | 1 | 2016-09-19T04:09:42Z | [
"python"
] |
How are conditional statements with multiple conditions evaluated? | 39,565,195 | <p>I'd expect the following two code blocks to be evaluated the same way, but it would seem that is not the case.</p>
<pre><code>if True or False and False:
print('True')
else:
... | 1 | 2016-09-19T04:04:56Z | 39,578,170 | <p>Standard Order of operations gives <code>and</code> precedence over <code>or</code>, so the first statement <code>True or False and False</code> is logically equivalent to </p>
<pre><code>True or (False and False)
</code></pre>
<p>This evaluates to <code>True</code>.</p>
<p>The second statement is </p>
<pre><co... | 1 | 2016-09-19T16:47:20Z | [
"python"
] |
How to specialize documenters in sphinx autodoc | 39,565,203 | <p>I am documenting a project with Sphinx I want to create a specialized version of the <code>autoclass::</code> directive that allows me to modify the documentation string for certain classes.</p>
<p>Here is one thing I have tried: searching the sphinx source, I found that the <code>autoclass</code> directive is crea... | 0 | 2016-09-19T04:06:05Z | 39,565,337 | <p>I have found something in <a href="http://www.sphinx-doc.org/en/stable/extdev/markupapi.html#directives" rel="nofollow">Docutils markup API</a></p>
<blockquote>
<p>Directives are handled by classes derived from docutils.parsers.rst.Directive. They have to be registered by an extension using Sphinx.add_directive()... | 0 | 2016-09-19T04:24:19Z | [
"python",
"python-sphinx"
] |
How to specialize documenters in sphinx autodoc | 39,565,203 | <p>I am documenting a project with Sphinx I want to create a specialized version of the <code>autoclass::</code> directive that allows me to modify the documentation string for certain classes.</p>
<p>Here is one thing I have tried: searching the sphinx source, I found that the <code>autoclass</code> directive is crea... | 0 | 2016-09-19T04:06:05Z | 39,574,132 | <p><code>Documenter</code> classes require an existing directive to apply, when appropriate. This can either be a "built in" directive, or it can be a custom directive you create and register. Either way, the directive to use is specified by the <code>directivetype</code> class attribute. You can specify this value exp... | 0 | 2016-09-19T13:14:21Z | [
"python",
"python-sphinx"
] |
pymongo+MongoDB: How to find _id in pymongo? | 39,565,253 | <p>I want to find the <code>_id</code> of a document of a collection <code>(mycol)</code> where <code>"name":"John"</code>. I have inserted the document but want to find the <code>_id</code> of document. Is it possible ? I am trying as </p>
<pre><code>result = db.mycol.find({"_id": {"name": "John"}})
</code></pre>
<... | 2 | 2016-09-19T04:12:53Z | 39,565,444 | <p>Try it like that </p>
<pre><code>result = db.mycol.find({"name": "John"})
for item in result:
print(item['_id'])
</code></pre>
<p>Just have a look at the <a href="http://api.mongodb.com/python/current/tutorial.html#querying-for-more-than-one-document" rel="nofollow">docs</a> to see how to use pymongo</p>
| 0 | 2016-09-19T04:36:20Z | [
"python",
"mongodb",
"mongodb-query",
"pymongo"
] |
pandas dataframe look ahead optimization | 39,565,298 | <p>What's the best way to do this with pandas dataframe? I want to loop through a dataframe, and find the nearest next index that has at least +/-2 value difference. For example: [100, 99, 102, 98, 103, 103] will create a new column with this [2, 2, 3, 0, N/A], 0 means not find.</p>
<p>My solution performance is n * l... | 2 | 2016-09-19T04:18:19Z | 39,620,425 | <p>When all the elements are integers, it is possible to do so in linear time. The following solution is complicated, and of algorithmic interest (if at that) only. Since it uses loops and data structures, any real implementation would need to be in C/C++/Cython (otherwise, the constants would be so high, that a tremen... | 1 | 2016-09-21T15:14:01Z | [
"python",
"algorithm"
] |
Regex: match only outside parenthesis (so that the text isn't split within parenthesis)? | 39,565,349 | <p>I have a target string which looks like this:</p>
<pre><code>"foo (foo, foofoo), bar (foobar), foo, bar (barbar, foo), bar, foo"
</code></pre>
<p>and I want:</p>
<pre><code>["foo (foo, foofoo)", "bar (foobar)", "foo", "bar (barbar, foo)", "bar", "foo"]
</code></pre>
<p>by splitting the target at <code>", "</code... | 1 | 2016-09-19T04:25:36Z | 39,565,427 | <pre><code>,(?![^(]*\))
</code></pre>
<p>You can use this to split.See demo.This holds true as u said there are no nested <code>()</code>.</p>
<p><a href="https://regex101.com/r/wV5bD0/1" rel="nofollow">https://regex101.com/r/wV5bD0/1</a></p>
| 2 | 2016-09-19T04:34:31Z | [
"python",
"regex"
] |
Regex: match only outside parenthesis (so that the text isn't split within parenthesis)? | 39,565,349 | <p>I have a target string which looks like this:</p>
<pre><code>"foo (foo, foofoo), bar (foobar), foo, bar (barbar, foo), bar, foo"
</code></pre>
<p>and I want:</p>
<pre><code>["foo (foo, foofoo)", "bar (foobar)", "foo", "bar (barbar, foo)", "bar", "foo"]
</code></pre>
<p>by splitting the target at <code>", "</code... | 1 | 2016-09-19T04:25:36Z | 39,565,496 | <p>You can use this to extract the matches. Assuming there are no nested <code>()</code></p>
<pre><code>(\w+(?: \([^\)]*\))?)
</code></pre>
<p><a href="https://www.regex101.com/r/gR6jF1/1" rel="nofollow">https://www.regex101.com/r/gR6jF1/1</a></p>
| 1 | 2016-09-19T04:41:37Z | [
"python",
"regex"
] |
call next iteration in list after first comparision loop | 39,565,354 | <p>i have a situation where i have to loop over a list, grab info from a file, write a new file, send an email, and then go back to the list for the next iteration to start the process over again.<br>
i'll try to write it out and then put my code in for you to look at.<br>
the list is a list of ipaddresses and both fil... | 0 | 2016-09-19T04:26:29Z | 39,567,677 | <pre><code> 0 def isp_email_names():
1 with open('Invalid_names_file') as Invalid_names_file:
2 with open('ISP_names_file', 'w') as ISP_names_file:
3 for line in Invalid_names_file:
4 if one_ip_each.ipAddr in line:
</code></pre>
<p>Line 4ï¼ one_ip_each.ipAddr is a list... | 0 | 2016-09-19T07:34:17Z | [
"python",
"python-3.x"
] |
Write a program in Python 3.5 that reads a file, then writes a different file with the same text that was in the first one as well as more? | 39,565,357 | <p>The exact question to this problem is:
*Create a file with a 20 lines of text and name it âlines.txtâ. Write a program to read this a file âlines.txtâ and write the text to a new file, ânumbered_lines.txtâ, that will also have line numbers at the beginning of each line.
Example:
Input file: âlines.txt... | 0 | 2016-09-19T04:26:36Z | 39,565,442 | <p>You have all the right parts, and you're almost there:</p>
<p>When you do</p>
<pre><code>for ln in file_object:
print(ln)
</code></pre>
<p>you've exhausted the contents of that file, and you won't be able to read them again, like you try to do later on.</p>
<p>Also, <code>print</code> does not write to a fil... | 1 | 2016-09-19T04:35:54Z | [
"python",
"file"
] |
Write a program in Python 3.5 that reads a file, then writes a different file with the same text that was in the first one as well as more? | 39,565,357 | <p>The exact question to this problem is:
*Create a file with a 20 lines of text and name it âlines.txtâ. Write a program to read this a file âlines.txtâ and write the text to a new file, ânumbered_lines.txtâ, that will also have line numbers at the beginning of each line.
Example:
Input file: âlines.txt... | 0 | 2016-09-19T04:26:36Z | 39,565,464 | <p>The right way to open a file is using a <code>with</code> statement:</p>
<pre><code>with open("lines.txt",'r') as file_object:
... # do something
</code></pre>
<p>That way, the context manager introduced by <code>with</code> will close your file at the end of "something " or in case of exception.</p>
<p>Of co... | 0 | 2016-09-19T04:38:26Z | [
"python",
"file"
] |
Write a program in Python 3.5 that reads a file, then writes a different file with the same text that was in the first one as well as more? | 39,565,357 | <p>The exact question to this problem is:
*Create a file with a 20 lines of text and name it âlines.txtâ. Write a program to read this a file âlines.txtâ and write the text to a new file, ânumbered_lines.txtâ, that will also have line numbers at the beginning of each line.
Example:
Input file: âlines.txt... | 0 | 2016-09-19T04:26:36Z | 39,565,586 | <ol>
<li><p>In the first loop you're printing the contents of the input file. This means that the file contents have already been consumed when you get to the second loop. (Plus the assignment didn't ask you to print the file contents.)</p></li>
<li><p>In the second loop you're using <code>print()</code> instead of w... | 0 | 2016-09-19T04:51:08Z | [
"python",
"file"
] |
Write a program in Python 3.5 that reads a file, then writes a different file with the same text that was in the first one as well as more? | 39,565,357 | <p>The exact question to this problem is:
*Create a file with a 20 lines of text and name it âlines.txtâ. Write a program to read this a file âlines.txtâ and write the text to a new file, ânumbered_lines.txtâ, that will also have line numbers at the beginning of each line.
Example:
Input file: âlines.txt... | 0 | 2016-09-19T04:26:36Z | 39,565,656 | <p>Good first try, and with that, I can go through your code and explain what you did right (or wrong)</p>
<pre><code>file_object=open("lines.txt",'r')
for ln in file_object:
print(ln)
</code></pre>
<p>This is fine, though generally you want to put a space before and after assignments (you are assigning the resul... | 0 | 2016-09-19T04:59:00Z | [
"python",
"file"
] |
Basic Loop/Python | 39,565,379 | <p>I am supposed to write a program that displays numbers from 100 to 200, ten per line, that are divisible by 5 or 6 but NOT both. This is my code so far. I know it's a basic problem so can you tell me the basic code that I'm missing instead of the "shortcut" steps. Any help is appreciated!</p>
<pre><code> def mai... | -3 | 2016-09-19T04:28:35Z | 39,565,553 | <p>You should init every variable using in the code
While (condition) will break when the condition false. Since your condition depends on num, but num is never changed in your code, infinity loop will happen. You need to add <code>num = num + 1</code> at the end of your loop block.
It's supposed to use if not for for ... | 0 | 2016-09-19T04:47:39Z | [
"python",
"python-3.x"
] |
Basic Loop/Python | 39,565,379 | <p>I am supposed to write a program that displays numbers from 100 to 200, ten per line, that are divisible by 5 or 6 but NOT both. This is my code so far. I know it's a basic problem so can you tell me the basic code that I'm missing instead of the "shortcut" steps. Any help is appreciated!</p>
<pre><code> def mai... | -3 | 2016-09-19T04:28:35Z | 39,565,559 | <p>This is how I would go about it. I would recommend using a for loop over a while loop if you know the range you need. You are less likely to get into an endless loop. The reason for the n variable is since you said you needed 10 numbers per line. The n variable will track how many correct numbers you find so that yo... | 1 | 2016-09-19T04:48:18Z | [
"python",
"python-3.x"
] |
How to get a field value from one model to another model | 39,565,489 | <p>I created a new module which depends on sales. I also created a sales commission tab in sales order. I would like to add <code>amount_total</code> from the <code>sale.order</code> to <code>sales_value</code> in my new model <code>commission.sale</code> but nothing happens.</p>
<p>In commission.py</p>
<pre><code>... | 2 | 2016-09-19T04:41:03Z | 39,826,344 | <pre><code>class salesman_commission(models.Model):
_name = 'salesman_commission'
user = fields.Many2one('res.users',string='User')
sales_order_id = fields.Many2one('sale.order',string='Sale id',ondelete='cascade')
sales_val = fields.Float(compute='_total',string='Sales Value')
percent = fields.Flo... | 0 | 2016-10-03T07:21:30Z | [
"python",
"odoo-8"
] |
error is not displayed in the template | 39,565,560 | <p>I have used <strong>django allauth</strong> for user registration and login. I have used the <code>{{ form.has_errors }}</code> in template to show an error but the error is not displayed in the template. What might be the reason for not showing an error in the template? </p>
<p>The code from allauth <code>login.ht... | 0 | 2016-09-19T04:48:20Z | 39,565,739 | <p>Seems to be a misunderstanding of <a href="https://docs.djangoproject.com/en/1.10/ref/forms/api/#django.forms.Form.has_error" rel="nofollow">has_error</a> </p>
<blockquote>
<p>his method returns a boolean designating whether a field has an error
with a specific error code. If code is None, it will return True i... | 1 | 2016-09-19T05:07:10Z | [
"python",
"django",
"django-templates",
"django-allauth",
"django-1.9"
] |
error is not displayed in the template | 39,565,560 | <p>I have used <strong>django allauth</strong> for user registration and login. I have used the <code>{{ form.has_errors }}</code> in template to show an error but the error is not displayed in the template. What might be the reason for not showing an error in the template? </p>
<p>The code from allauth <code>login.ht... | 0 | 2016-09-19T04:48:20Z | 39,565,751 | <p>Try this one. Errors raised by the form which is not attached to field are stored in non_field_errors</p>
<pre><code> {% if form.non_field_errors %}
<ul class='form-errors'>
{% for error in form.non_field_errors %}
<li>{{ error }}</li>
{% end... | 1 | 2016-09-19T05:09:10Z | [
"python",
"django",
"django-templates",
"django-allauth",
"django-1.9"
] |
Can't deploy to Scrapinghub | 39,565,575 | <p>When I try to deploy using <code>shub deploy</code>, I got this error:</p>
<blockquote>
<p>Removing intermediate container fccf1ec715e6 Step 10 : RUN sudo -u
nobody -E PYTHONUSERBASE=$PYTHONUSERBASE pip install --user
--no-cache-dir -r /app/requirements.txt ---> Running in 729e0d414f46 Double requirement giv... | 0 | 2016-09-19T04:50:03Z | 39,565,576 | <p>From the documentation <a href="http://doc.scrapinghub.com/shub.html" rel="nofollow">here</a></p>
<blockquote>
<p>Note that this requirements file is an extension of the Scrapy Cloud
stack, and therefore should not contain packages that are already part
of the stack, such as scrapy.</p>
</blockquote>
<p>As y... | 0 | 2016-09-19T04:50:03Z | [
"python",
"deployment",
"web-scraping",
"scrapy",
"scrapinghub"
] |
Better edge detection with OpenCV and rounded corner cards | 39,565,584 | <p>I've been using the great tutorials at <a href="http://www.pyimagesearch.com/2014/05/05/building-pokedex-python-opencv-perspective-warping-step-5-6/" rel="nofollow">PyImageSearch.com</a> to get a Pi (v3) to recognise some playing cards. So far it's been working out alright, but the method described in the tutorials ... | 0 | 2016-09-19T04:51:05Z | 39,671,918 | <p>Turns out I just needed to read the <a href="http://docs.opencv.org/trunk/dd/d49/tutorial_py_contour_features.html" rel="nofollow">OpenCV contour docs</a> a bit more. What I was basically looking for was a minimum area box around my contour:</p>
<pre><code>rect = cv2.minAreaRect(cnt) # get a rectangle rotated to ha... | 0 | 2016-09-24T02:30:10Z | [
"python",
"opencv"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.