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 |
|---|---|---|---|---|---|---|---|---|---|
Concepts, use and testing Cloud Datastore in local | 37,745,474 | <p>I'm really confused with the way to try Datastore in local. Please, give me a minute to explain.</p>
<p>I'm developing a app composed to few microservices like a only gae app. In a parte of the app, I use the datastore. So when I run my app, I use the development server and when I save something in the datastore c... | 0 | 2016-06-10T10:05:34Z | 37,921,324 | <p>Finally I think I solved and understood my problem. If I were working with other system that I want connect to Cloud Datastore, I would need use the "emulator". But isn't my case. So, I need use the stubs with unittest because there are not a simple way (I think is imposible) to do this with the dev_server (when he... | 0 | 2016-06-20T11:25:40Z | [
"python",
"unit-testing",
"google-app-engine",
"google-cloud-datastore"
] |
use pytesseract to recognize text from image | 37,745,519 | <p>I need to use pytesseract to extract text from this picture:
<a href="http://i.stack.imgur.com/HWLay.gif" rel="nofollow"><img src="http://i.stack.imgur.com/HWLay.gif" alt="enter image description here"></a></p>
<p>and the code:</p>
<pre><code>from PIL import Image, ImageEnhance, ImageFilter
import pytesseract
path... | 0 | 2016-06-10T10:08:02Z | 37,750,605 | <p>Here is my solution:</p>
<pre><code>import pytesseract
from PIL import Image, ImageEnhance, ImageFilter
im = Img.open("temp.jpg") # the second one
im = im.filter(ImageFilter.MedianFilter())
enhancer = ImageEnhance.Contrast(im)
im = enhancer.enhance(2)
im = im.convert('1')
im.save('temp2.jpg')
text = pytesseract.im... | 0 | 2016-06-10T14:19:54Z | [
"python",
"image",
"ocr",
"pytesser"
] |
Python: How to use output of "listfiles" to delete/ move/ etc. files | 37,745,523 | <p><strong>Background:</strong></p>
<p>My target is to find dublicate files in two differen folders (without subfolders). To do that, I use the following Python script:</p>
<pre><code>###Check ob alle Archive noch vorhanden oder ob Daten bei Check gelöscht wurden
def listfiles(path):
files = []
for dirName, ... | 2 | 2016-06-10T10:08:22Z | 37,745,601 | <p><code>os.walk</code> recursively checks all folders and subfolders starting from the root dir you pass, you want to check <em>two different folders (without subfolders)</em> so just search each folder with <em>glob</em>, if you want to move you can use <a href="https://docs.python.org/2/library/shutil.html#shutil.m... | -1 | 2016-06-10T10:12:41Z | [
"python",
"list",
"directory",
"delete-file",
"os.walk"
] |
executing python script no output | 37,745,547 | <p>I wrote a script and when I run it in the shell, it prints the values, output correct(sudo python /home/pi/map/apps/assistant/IFTTT.py):</p>
<pre><code>def GetCalenderMessages():
print("test")
CalenderMessage = bus_service.receive_queue_message('calendar', peek_lock=True)
if CalenderMessage != None:
... | 0 | 2016-06-10T10:09:53Z | 37,745,767 | <p>1) Instead of using pipes and <code>Popen</code>, just import the script and call <code>GetCalenderMessages</code></p>
<p>2) Do you want it just printed to the console or outputted to the webapp user?</p>
<p>In case the second scenario is the case:</p>
<p>in your <code>route</code> function, you don't seem to <co... | 0 | 2016-06-10T10:20:20Z | [
"python",
"function",
"flask",
"subprocess",
"popen"
] |
How can I extract address from raw text using NLTK in python? | 37,745,801 | <p>I have this text </p>
<blockquote>
<p>'''Hi, Mr. Sam D. Richards lives here, <strong>44 West 22nd Street, New
York, NY 12345</strong>. Can you contact him now? If you need any help, call
me on 12345678'''</p>
</blockquote>
<p>. How the address part can be extracted from the above text using NLTK? I have trie... | 1 | 2016-06-10T10:22:08Z | 37,784,861 | <p>Definitely regular expressions :)</p>
<p>Something like</p>
<pre><code>import re
txt = ...
regexp = "[0-9]{1,3} .+, .+, [A-Z]{2} [0-9]{5}"
address = re.findall(regexp, txt)
# address = ['44 West 22nd Street, New York, NY 12345']
</code></pre>
<p><strong>Explanation:</strong></p>
<p><code>[0-9]{1,3}</code>: 1 t... | 1 | 2016-06-13T08:21:37Z | [
"python",
"nltk",
"stanford-nlp"
] |
cannot concatenate 'str' and 'nonetype' objects in python / sql / flask | 37,745,908 | <p>I need to pass a column name into the SQL Query just once. This code works fine when ordering but when a button is pressed on the page (which inserts content into a table) this error is thrown.</p>
<p>"cannot concatenate 'str' and 'nonetype' objects"</p>
<pre><code> if request.method == "POST":
## DISPLAYIN... | 0 | 2016-06-10T10:26:51Z | 37,746,776 | <p>In the else clause you wrote:</p>
<pre><code> else:
order == ''
break
</code></pre>
<p>Instead of:</p>
<pre><code> else:
order = ''
break
</code></pre>
<p>Also, the <code>while</code> clause is redundant as the code in that block will only run once (because of the <code>brea... | 0 | 2016-06-10T11:11:49Z | [
"python",
"sqlite",
"flask",
"flask-sqlalchemy"
] |
Using plotly without online plotly account | 37,745,917 | <p>Is it possible to use the plotly library to create charts in python without having an online plotly account? I think the code is opensource <a href="https://github.com/plotly/plotly.py" rel="nofollow">https://github.com/plotly/plotly.py</a>. I would like to know whether we can use this without an online account.</p>... | 0 | 2016-06-10T10:27:30Z | 37,746,073 | <p>Yes, it can be done. The only purpose of having a <code>plotly</code> account is to host the graphs in your <code>plotly</code> account. </p>
<p><a href="https://plot.ly/python/offline/" rel="nofollow"><code>Plotly Offline</code></a> allows you to create graphs offline and save them locally. Instead of saving the g... | 1 | 2016-06-10T10:36:12Z | [
"python",
"charts",
"plotly"
] |
how to code vector to matrix hamming distance in Python? | 37,746,027 | <p>I like to develop a query system that finds the most similar items to given one based on a binary signature extracted from the data. I probe for the most efficient way since I have runtime constraints. I tried to use scipy distance but it was too slow. Do you know any other useful library or trick to make it in a fa... | 2 | 2016-06-10T10:33:31Z | 37,746,569 | <p>I would be surprised if there was a significantly faster way than this: Put your data into a pandas DataFrame (<code>M</code>), each vector by columns, and your target vector into a pandas Series (<code>x</code>), </p>
<pre><code>import numpy as np
import pandas as pd
rows = 68
columns=3000
M = pd.DataFrame(np.ra... | 0 | 2016-06-10T11:01:28Z | [
"python",
"matrix",
"information-retrieval",
"hamming-distance"
] |
how to code vector to matrix hamming distance in Python? | 37,746,027 | <p>I like to develop a query system that finds the most similar items to given one based on a binary signature extracted from the data. I probe for the most efficient way since I have runtime constraints. I tried to use scipy distance but it was too slow. Do you know any other useful library or trick to make it in a fa... | 2 | 2016-06-10T10:33:31Z | 37,746,682 | <p>Use <code>cdist</code> from SciPy:</p>
<pre><code>from scipy.spatial.distance import cdist
Y = cdist(XA, XB, 'hamming')
</code></pre>
<blockquote>
<p>Computes the normalized Hamming distance, or the proportion of those vector elements between two n-vectors u and v which disagree. To save memory, the matrix X can... | 0 | 2016-06-10T11:07:02Z | [
"python",
"matrix",
"information-retrieval",
"hamming-distance"
] |
how to code vector to matrix hamming distance in Python? | 37,746,027 | <p>I like to develop a query system that finds the most similar items to given one based on a binary signature extracted from the data. I probe for the most efficient way since I have runtime constraints. I tried to use scipy distance but it was too slow. Do you know any other useful library or trick to make it in a fa... | 2 | 2016-06-10T10:33:31Z | 37,765,932 | <p>Nice problem, I liked the answers of Alex and Piotr. My first naive attempt resulted also in a solution time around 800ms (on my system). My second attempt, using numpy's <code>(un)packbits</code>, resulted in a 4x speed increase.</p>
<pre><code>import numpy as np
LENGTH = 68
K = 1024
DATASIZE = 3000 * K
DATA = np... | 1 | 2016-06-11T16:18:37Z | [
"python",
"matrix",
"information-retrieval",
"hamming-distance"
] |
install python 3 kernel on ipython | 37,746,109 | <p>I know the question has been asked in the past but couldnt find a satisfying solution.</p>
<p>i want to add a python 3 kernel on ipython
here the "official" instructions seems quite straightforward
<a href="https://ipython.readthedocs.io/en/latest/install/kernel_install.html" rel="nofollow">https://ipython.readthed... | 0 | 2016-06-10T10:37:45Z | 37,756,535 | <p>Found the solution:
windows uses the command py -3 instead of python3 that was suggested in the docs posted above;</p>
<p>Sorry if that was abs obvious for all..</p>
| 0 | 2016-06-10T20:17:26Z | [
"python",
"python-3.x",
"install",
"ipython"
] |
django using mptt and polymorphic for model | 37,746,295 | <p>I have a PolymorphicMPTTModel and models are:</p>
<pre><code>class AbstractCategory(PolymorphicMPTTModel):
name = models.CharField(max_length=100)
parent = PolymorphicTreeForeignKey('self', null=True, blank=True,
related_name='sub_categories')
class Category(AbstractCa... | 1 | 2016-06-10T10:46:29Z | 37,792,314 | <p>While I don't quite understand why the <code>category__in</code> filter breaks (it should work!), you can implement this query in a much better way. When you join using the mptt fields, everything happens in a single query instead of a <code>WHERE x IN (SELECT ..)</code> subquery.</p>
<pre><code>class ProductModelQ... | 0 | 2016-06-13T14:26:32Z | [
"python",
"django"
] |
Code changes - Python - Piphone - Raspberry Pi | 37,746,430 | <p>Right now I'm working hard to finish a project named Pihpone; I've been following the adafruit tutorial and I've also bought all the items that were suggested by them</p>
<p>The problem is that..the code was written for 2,8" while I have a 3.5" screen </p>
<p>I've succeeded in making some changes like modifying th... | 1 | 2016-06-10T10:53:10Z | 37,748,145 | <p>The code in <code>piphone.py</code> appears to be using the <a href="http://www.pygame.org/docs/" rel="nofollow">pygame</a> module to do the graphics. The problem is all the <strong>hardcoded</strong> coordinates and sizes for things like the <code>Button</code>s. To fix this, the values must be computed at run-time... | 0 | 2016-06-10T12:19:51Z | [
"python",
"phone"
] |
How to slice pandas DataFrame based on values from another Dataframe without using for-loop? | 37,746,561 | <p>I have a DataFrame <code>df1</code>: </p>
<pre><code>df1.head() =
id type position
dates
2000-01-03 17378 600 400
2000-01-03 4203 600 150
2000-01-03 18321 600 5000
2000-01-03 6158 600 1000
2000-01-03 886 600 10000
2000-01-03 17127 600 800... | 2 | 2016-06-10T11:01:00Z | 37,748,302 | <p>you want something like this:</p>
<pre><code>#Merge the tables together - making sure we keep the index column
mg = df1.reset_index().merge(df2, left_on = 'id', right_on = 'id_x')
#Select only the rows that are within the start and end
mg = mg[(mg['index'] > mg['dt_f']) & (mg['index'] < mg['dt_l'])]
#Fi... | 0 | 2016-06-10T12:27:34Z | [
"python",
"pandas",
"merge",
"vectorization",
"slice"
] |
Tensorflow, multi label accuracy calculation | 37,746,670 | <p>I am working on a multi label problem and i am trying to determine the accuracy of my model.</p>
<p>My model:</p>
<pre class="lang-py prettyprint-override"><code>NUM_CLASSES = 361
x = tf.placeholder(tf.float32, [None, IMAGE_PIXELS])
y_ = tf.placeholder(tf.float32, [None, NUM_CLASSES])
# create the network
pred =... | 2 | 2016-06-10T11:06:38Z | 37,747,871 | <p>I believe the bug in your code is in: <code>correct_prediction = tf.equal( tf.round( pred ), tf.round( y_ ) )</code>.</p>
<p><code>pred</code> should be <strong>unscaled logits</strong> (i.e. without a final sigmoid).</p>
<p>Here you want to compare the output of <code>sigmoid(pred)</code> and <code>y_</code> (bot... | 3 | 2016-06-10T12:05:49Z | [
"python",
"tensorflow"
] |
Authorization issue on bluemix: Python swift client library accessing object storage | 37,746,762 | <p>I am writing a code to access object storage using python swift client library. The intention of the program is to read, write and delete CSV files in object storage using swift client API. May i know what is going wrong. I got this code from a website. Is there any other way to access object storage from python?</p... | 0 | 2016-06-10T11:11:08Z | 39,100,128 | <p>You get multiple choices for the authentication endpoint.
You should specify the <code>auth_version</code> and adjust the <code>authurl</code> accordingly.
Just append '/v3' to <code>authurl</code> and it should work.</p>
<p>Here is a small example using the Insert to code - credentials function.</p>
<pre><code># ... | 1 | 2016-08-23T11:37:36Z | [
"python",
"ibm-bluemix",
"object-storage"
] |
Subtract successive rows in a dataframe grouped by id in pandas(Python) | 37,746,766 | <p>I have the following data frame:</p>
<pre><code>id day total_amount
1 2015-07-09 1000
1 2015-10-22 100
1 2015-11-12 200
1 2015-11-27 2392
1 2015-12-16 123
7 2015-07-09 200
7 2015-07-09 1000
... | 2 | 2016-06-10T11:11:20Z | 37,746,802 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.diff.html" rel="nofollow"><code>DataFrameGroupBy.diff</code></a>:</p>
<pre><code>df['dif'] = df.groupby('id')['day'].diff(-1) * (-1)
print (df)
id day total_amount dif
0 1 2015-07-09 ... | 1 | 2016-06-10T11:13:23Z | [
"python",
"pandas",
"data-manipulation",
"data-cleansing",
"data-science"
] |
Plotting a cumulative graph in Python | 37,746,942 | <p>I'm new to the world of python. I'm trying to create a plot showing accumulated GDD (Growing degree days) vs time for selected cities within a given period of time </p>
<p>I wrote a function to accomplish this, but I can't seem to get it to work right. I keep getting with an empty plot in it. Also a dimension error... | 1 | 2016-06-10T11:19:55Z | 37,747,051 | <p>A simple and fast solution could be to add <code>plt.hold(True)</code> after a plot call.</p>
<p>A more clean solution is to use a figure which can bee seen as window which you draw onto. <a href="http://matplotlib.org/examples/pylab_examples/figlegend_demo.html" rel="nofollow">just like in this example</a></p>
<p... | 0 | 2016-06-10T11:25:41Z | [
"python",
"matplotlib"
] |
Create Numpy array of images | 37,747,021 | <p>I have some (950) 150x150x3 .jpg image files that I want to read into an Numpy array. </p>
<p>Following is my code:</p>
<pre><code>X_data = []
files = glob.glob ("*.jpg")
for myFile in files:
image = cv2.imread (myFile)
X_data.append (image)
print('X_data shape:', np.array(X_data).shape)
</code></pre>
<p... | 2 | 2016-06-10T11:23:26Z | 37,747,559 | <p>I tested your code. It works fine for me with output</p>
<blockquote>
<p>('X_data shape:', (4, 617, 1021, 3))</p>
</blockquote>
<p>however, all images were exactly the same dimension.</p>
<p>When I add another image with different extents I have this output:</p>
<blockquote>
<p>('X_data shape:', (5,))</p>
</... | 2 | 2016-06-10T11:50:28Z | [
"python",
"image",
"opencv",
"numpy",
"image-processing"
] |
Regex on Python 2.7 causing problems on finding text in a string | 37,747,101 | <p>As like as the title i have a little problem with regex... </p>
<p>I have a string called "result" that has got the text: "Name: John Surname: Legend". I have to extract only the Name .
<code>
print re.search('Name: (.+?) Surname: %s' % song, result).group(1)</code></p>
<p>But it doesn't return anything... I have ... | 1 | 2016-06-10T11:28:05Z | 37,747,231 | <pre><code>In [1]: s = "Name: John Surname: Legend"
In [2]: re.search('Name:\s+(.+)\sSurname:\s+(.+)',s).groups()
Out[2]: ('John', 'Legend')
In [3]: re.search('Name:\s+(.+)\sSurname:\s+(.+)',s).group(1)
Out[3]: 'John'
</code></pre>
| 2 | 2016-06-10T11:34:13Z | [
"python",
"regex",
"string",
"text"
] |
Get difference in days between today's date and previous date | 37,747,127 | <p>I'm using the "datetime" module and I'm trying to work out the difference between two dates in <strong>days</strong>. Here's the code that I'm using, with some other code coming before it that gets the object <code>sub.created_utc</code> (a POSIX timestamp, or unix timestap):</p>
<pre><code>import datetime
date = ... | 0 | 2016-06-10T11:29:29Z | 37,747,239 | <p>Once you subtract the dates, you get a <code>datetime.timedelta</code> object, and you can access its properties directly:</p>
<pre><code>import datetime
d1 = datetime.datetime.utcfromtimestamp(sub.created_utc)
print(sub.created_utc)
print(d1)
result = datetime.datetime.utcnow() - d1
print(result.days)
</code></pr... | 3 | 2016-06-10T11:34:22Z | [
"python",
"datetime"
] |
Get difference in days between today's date and previous date | 37,747,127 | <p>I'm using the "datetime" module and I'm trying to work out the difference between two dates in <strong>days</strong>. Here's the code that I'm using, with some other code coming before it that gets the object <code>sub.created_utc</code> (a POSIX timestamp, or unix timestap):</p>
<pre><code>import datetime
date = ... | 0 | 2016-06-10T11:29:29Z | 37,747,269 | <p>the statement</p>
<pre><code>datetime.datetime.now() - date
</code></pre>
<p>yields a <a href="https://docs.python.org/3.5/library/datetime.html#timedelta-objects" rel="nofollow"><code>timedelta</code></a> object. It has attributes like <code>days</code> or <code>seconds</code> etc.</p>
| -1 | 2016-06-10T11:35:39Z | [
"python",
"datetime"
] |
Get difference in days between today's date and previous date | 37,747,127 | <p>I'm using the "datetime" module and I'm trying to work out the difference between two dates in <strong>days</strong>. Here's the code that I'm using, with some other code coming before it that gets the object <code>sub.created_utc</code> (a POSIX timestamp, or unix timestap):</p>
<pre><code>import datetime
date = ... | 0 | 2016-06-10T11:29:29Z | 37,747,289 | <p><strong>ANSWER</strong></p>
<p>The datetime module in Python has got a function called timedelta. Delta in MATHS and in GREEK means difference. For example:</p>
<pre><code>a = 1
b = 2
delta = b-a
</code></pre>
<p>so for answering to your question you have to write:</p>
<pre><code>from datetime import date, timed... | 0 | 2016-06-10T11:36:25Z | [
"python",
"datetime"
] |
Get difference in days between today's date and previous date | 37,747,127 | <p>I'm using the "datetime" module and I'm trying to work out the difference between two dates in <strong>days</strong>. Here's the code that I'm using, with some other code coming before it that gets the object <code>sub.created_utc</code> (a POSIX timestamp, or unix timestap):</p>
<pre><code>import datetime
date = ... | 0 | 2016-06-10T11:29:29Z | 37,751,620 | <p>You don't need to convert it to <code>datetime</code>, you could get the current Unix time using <code>time.time()</code>. It allows to find the time difference in days given a Unix time from the past:</p>
<pre><code>import time
DAY = 86400 # POSIX day - the exact value
days_ago = (time.time() - sub.created_utc) /... | 0 | 2016-06-10T15:09:53Z | [
"python",
"datetime"
] |
F_Regression from sklearn.feature_selection | 37,747,182 | <p>I found the F_regression technique for feature selection in the sklearn feature selection module . I was not able to understand the principle it uses .
The description given was - <br><br>
Univariate linear regression tests.<br>
Quick linear model for testing the effect of a single regressor, sequentially for many ... | 1 | 2016-06-10T11:31:55Z | 38,599,029 | <p>The language in the docs is a little obtuse. I believe 'data' refers to the response. First, the chosen regressor and the response are orthogonalized with respect to the rest of the regressors. This reduces any multicollinearity that may be present. Then, the correlation between the chosen regressor and the respons... | 2 | 2016-07-26T20:10:22Z | [
"python",
"scikit-learn",
"regression",
"feature-selection"
] |
Celery on Apache server throws unexpected IOError | 37,747,312 | <p>I am working on a Django project where users can execute python scripts through a web UI. I'm using <a href="https://github.com/wooey/Wooey" rel="nofollow">Wooey</a> to create the UI. <a href="http://www.celeryproject.org/" rel="nofollow">Celery</a> is used as the task queue (RabbitMQ as broker). The site runs on a ... | 0 | 2016-06-10T11:37:42Z | 37,768,843 | <p>I followed <a href="http://stackoverflow.com/users/3929826/klaus-d">Klaus D.'s</a> suggestion and deleted <code>IOError</code> from line 405 in the Wooey <code>core.py</code> file.</p>
<p>Turns out that the error was indeed caused by a permission issue I thought I'd rectified earlier. Some new files created by Wooe... | 1 | 2016-06-11T21:56:50Z | [
"python",
"linux",
"django",
"apache"
] |
Python pyramid with letter | 37,747,373 | <p>My problem is that I have to make a pyramid of letters in the middle of the screen. The output has to be a pyramid of 15 levels. This assignment has to be done with definition. The output should be like </p>
<pre><code> a
aba
abcba
abcdcba
abcdedcba
... | -4 | 2016-06-10T11:40:51Z | 37,748,963 | <p>Tolen,
you have several minor mistakes and one logical issue in the function </p>
<pre><code>print_y_to_a()
</code></pre>
<p>Be aware that this function produces a string that begins with z, but you want to concatenate your string in reverse direction where your other function print_a_to_y() did stop (+1 position)... | 0 | 2016-06-10T13:01:02Z | [
"python"
] |
How to use python's seaborn to plot CDF? | 37,747,518 | <p>When I use the sns.kdeplot and let culmulative=True, the error is </p>
<blockquote>
<p>Cumulative distributions are currentlyonly implemented in statsmodels.Please install statsmodels.</p>
</blockquote>
<p>Even though I have already installed statsmodels.</p>
| 3 | 2016-06-10T11:48:09Z | 37,750,665 | <p>From <a href="https://github.com/mwaskom/seaborn/blob/master/seaborn/distributions.py" rel="nofollow">the source code</a>, we can see that all Seaborn does is attempt to import </p>
<pre><code>try:
import statsmodels.nonparametric.api as smnp
_has_statsmodels = True
except ImportError:
_has_statsmodels ... | 3 | 2016-06-10T14:22:57Z | [
"python",
"matplotlib",
"seaborn"
] |
Django - Multiple PDFTemplateResponse (wkhtmltopdf) | 37,747,562 | <p>I would like download a number of pdfs which correspond to <code>len(list_element)</code>. I create pdf with one list (I use 2 elements on this list to "write" a pdf) but I can download the first pdf, not others. Thanks for your help. </p>
<pre><code>class CreatePDFCSVView(PDFTemplateView):
"""View to create PDF."... | 0 | 2016-06-10T11:50:35Z | 37,748,773 | <p>In your last while loop you do a <code>return response</code>. This will happen on the first iteration. So you just return one pdf response. The rest is never processed.</p>
<p>But you can't return multiple documents in one response anyway. To do that you could for eg. create a zip file containing multiple files.</... | 0 | 2016-06-10T12:50:58Z | [
"python",
"django",
"python-3.x",
"wkhtmltopdf",
"django-1.9"
] |
True & False in a function def | 37,747,614 | <p>I understand what the function below does, but I don't quite get the significance (or difference) between returning <code>True</code> and <code>False</code>.</p>
<p>Both clauses make the program exit; i.e. upon entering a positive or negative response, the Python prompt is returned, so what actually changes interna... | 4 | 2016-06-10T11:52:35Z | 37,747,765 | <p>Functions rarely get used alone. Returning <code>True</code> or <code>False</code> here is to help the rest of your program determine what to do. For example:</p>
<pre><code>if ask('Do you like cheese?'):
order_cheese() # Some function you've previously defined
</code></pre>
<p>However, if your function is des... | 2 | 2016-06-10T12:01:07Z | [
"python"
] |
True & False in a function def | 37,747,614 | <p>I understand what the function below does, but I don't quite get the significance (or difference) between returning <code>True</code> and <code>False</code>.</p>
<p>Both clauses make the program exit; i.e. upon entering a positive or negative response, the Python prompt is returned, so what actually changes interna... | 4 | 2016-06-10T11:52:35Z | 37,747,794 | <p>Since the user's answer can be one of two sides <code>y or n</code>, <code>yes or no</code>, <code>y or nope</code>, <code>yes or nope</code>, <code>y or no</code> in any order, the function simply maps this list of dichotomies into a simple <code>True</code> or <code>False</code>. So you can use the function as a c... | 1 | 2016-06-10T12:02:25Z | [
"python"
] |
Assist with Python 3, hex, and addition | 37,747,666 | <p>First time python app, so of course it's not been easy ;) In plain English this is what I'm trying to do:</p>
<blockquote>
<p>read a binary file in, if any bytes are 0x00 change them to 0xFF, otherwise add 0x01 to each byte and write to a new file.</p>
</blockquote>
<p>So there it is..my hope is something like<... | 0 | 2016-06-10T11:55:33Z | 37,748,201 | <p>First, you have a bug in the <code>if byte = b'\x00'</code> line, you meant <code>==</code>. This is one of the most dangerous bugs in software development and that's why python doesn't allow assignment inside a condition.
Second, better check for the length of byte because python reads bytes from file as a list of ... | 1 | 2016-06-10T12:22:22Z | [
"python",
"binary",
"hex"
] |
Django - Reorder (update) objects with unique_together = (ForeignKey, IntegerField) | 37,747,687 | <p>I have a model that represents a <code>Session</code> (say a one hour class for kids) that has a number of associated <code>Task</code>s that must follow an order. Easier to understand:</p>
<pre><code>class Task(models.Model):
(...)
order = models.PositiveIntegerField('offset from the beginning of a Session... | 1 | 2016-06-10T11:56:33Z | 37,785,123 | <p>I'll post the code I developed as a solution for my problem; although I am not quite happy (I think there must be somehow a better solution), but just in case it helps someone.</p>
<p>I defined this method for the model <code>Task</code>:</p>
<pre><code>def update_order(self, new_order):
"""
Update the ord... | 0 | 2016-06-13T08:35:35Z | [
"python",
"django",
"orm"
] |
Django - Reorder (update) objects with unique_together = (ForeignKey, IntegerField) | 37,747,687 | <p>I have a model that represents a <code>Session</code> (say a one hour class for kids) that has a number of associated <code>Task</code>s that must follow an order. Easier to understand:</p>
<pre><code>class Task(models.Model):
(...)
order = models.PositiveIntegerField('offset from the beginning of a Session... | 1 | 2016-06-10T11:56:33Z | 37,797,010 | <p>It's usually best to reuse existing solutions:</p>
<p><a href="https://github.com/bfirsh/django-ordered-model" rel="nofollow">https://github.com/bfirsh/django-ordered-model</a></p>
<p>though it still boils down to 2 saves in sequence:</p>
<p><a href="https://github.com/bfirsh/django-ordered-model/blob/master/orde... | 1 | 2016-06-13T18:43:57Z | [
"python",
"django",
"orm"
] |
synergy register hotkey using text config | 37,747,704 | <p>I want to register the hotkey
So, I added key types</p>
<blockquote>
<ol>
<li>key_types.h </li>
</ol>
</blockquote>
<pre><code> static const KeyID kKeyHangul = 0xEF31; /* Zenkaku/Hankaku */ //asmera modify to 0xef31 from 0xef26
</code></pre>
<blockquote>
<ol start="2">
<li>key_types.cpp</li>
... | 0 | 2016-06-10T11:57:27Z | 40,120,813 | <p>This works for me - <kbd>Control</kbd>+<kbd>Alt</kbd>+<kbd>Space</kbd> </p>
<p>Check out this reference for more keys: <a href="https://github.com/symless/synergy/blob/master/src/lib/synergy/key_types.cpp" rel="nofollow">https://github.com/symless/synergy/blob/master/src/lib/synergy/key_types.cpp</a></p>
| 0 | 2016-10-19T01:56:14Z | [
"python",
"c++"
] |
Keras fitting ignoring nan values | 37,747,886 | <p>I am training a neural network to do regression, (1 input and 1 output). Let's <code>x</code> and <code>y</code> be the usual input and output dataset, respectively.</p>
<p>My problem is that the <code>y</code> dataset (not the <code>x</code>) have some values set to nan, so the fitting goes to nan. I wonder if the... | 0 | 2016-06-10T12:06:30Z | 37,749,062 | <p>As said in the comments, simply remove the nan as a preprocessing step:</p>
<pre><code>import numpy as np
x = range(2,8)
y = [4,2,np.nan,7,np.nan,np.nan]
for a,b in zip(x,y):
if str(b) == 'nan':
x.remove(a)
y.remove(b)
print x,y
</code></pre>
<p>produces <code>[2, 3, 5] [4, 2, 7]</code>.</p>... | 2 | 2016-06-10T13:05:12Z | [
"python",
"numpy",
"neural-network",
"keras"
] |
Points should not be connected in plotly line charts if there is a data gap - possible? | 37,747,890 | <p>I am using the plotly library to create charts. I have a weather data which gets updated every one hour for every day. Say due to device fault, the current data did not get updated for a particular day and instead the old data is updated. The plotly by default will just draw a line for points given and make charts. ... | 0 | 2016-06-10T12:06:38Z | 40,096,530 | <p>A hacky way to do it would be to insert a null point when you have a gap. It will create a discontinuity in the line.</p>
<p>However, this means adding points to the graph so if you have a lot of gaps, this may impact the performances.</p>
<p>See this <a href="http://codepen.io/anon/pen/QKkWRz" rel="nofollow">snip... | 0 | 2016-10-17T22:14:50Z | [
"python",
"charts",
"plotly"
] |
python argeparse and input from text and output to text | 37,747,977 | <p>I have found a script on GitHub that I want to edit for my own use. </p>
<p>The original script is <a href="https://github.com/PoorBillionaire/sitereview" rel="nofollow">https://github.com/PoorBillionaire/sitereview</a></p>
<p>The idea I want to implement in my fork is to look up a list of websites in a text file ... | 0 | 2016-06-10T12:11:25Z | 37,748,244 | <p>Try this:</p>
<pre><code>args = p.parse()
input_file, dest_file = args.d, args.o
with f_input, f_dest as open(input_file,'r'), open(dest_file,'w'):
for line in f_input.readline():
f_dest.write(line)
f_dest.flush()
</code></pre>
<p>Please read the docs for <a href="https://docs.python.org/2/library/... | 0 | 2016-06-10T12:24:51Z | [
"python"
] |
Identical tuples give different pickles | 37,748,001 | <p>The situation is pretty strange and I expect that there is something that I don't know about the pickle module.</p>
<p>I have two tuples <code>s1</code> and <code>s2</code>. If I compare them it returns <code>True</code>.</p>
<pre><code>s1 == s2
True
</code></pre>
<p>If I pickle them and compare results, it retur... | 4 | 2016-06-10T12:12:33Z | 37,748,613 | <p>I've tried with marshal module (<a href="https://docs.python.org/2/library/marshal.html#module-marshal" rel="nofollow">https://docs.python.org/2/library/marshal.html#module-marshal</a>), and works. Look the example</p>
<pre><code>import marshal
# code ...
string1 = marshal.dumps(sp1)
</code></pre>
| 0 | 2016-06-10T12:42:54Z | [
"python"
] |
Identical tuples give different pickles | 37,748,001 | <p>The situation is pretty strange and I expect that there is something that I don't know about the pickle module.</p>
<p>I have two tuples <code>s1</code> and <code>s2</code>. If I compare them it returns <code>True</code>.</p>
<pre><code>s1 == s2
True
</code></pre>
<p>If I pickle them and compare results, it retur... | 4 | 2016-06-10T12:12:33Z | 37,748,905 | <p>The problem is that <code>pickle</code> <a href="https://docs.python.org/3/library/pickle.html#comparison-with-marshal" rel="nofollow">preserves identity relationships between subobjects</a> (this is for efficiency and to handle recursive objects):</p>
<pre><code>a1 = "a" * 30
a2 = "a" * 30
s1 = (a1, a2, a1)
s2 = (... | 4 | 2016-06-10T12:58:03Z | [
"python"
] |
update tkinter label with mouse click | 37,748,050 | <p>I am the beginner in Python and am trying to code a tictactoe game with <code>tkinter</code>. My class named <code>Cell</code> extends <code>Tkinter.Label</code>. The <code>Cell</code> class contains data fields <code>emptyLabel</code>, <code>xLabel</code> and <code>oLabel</code>. This is my code so far for class <c... | 1 | 2016-06-10T12:15:15Z | 37,748,785 | <p>You keep reassigning <code>self.cell</code>, and then when that part is done you bind a mouse button to the last cell. Bind the mouse button to each cell within the loop.</p>
<p>The callback function is also hard-coded to only look at <code>self.cell</code>, which you kept reassigning to end up with only the last o... | 2 | 2016-06-10T12:51:47Z | [
"python",
"tkinter"
] |
How to use progressbar module with urlretrieve | 37,748,105 | <p>My <strong>pyhton3</strong> script downloads a number of images over the internet using <strong>urlretrieve</strong>, and I'd like to add a progressbar with a <em>completed percentage</em> and <em>download speed</em> for each download. </p>
<p>The <a href="http://progressbar-2.readthedocs.io/en/latest/" rel="nofoll... | 0 | 2016-06-10T12:17:56Z | 37,748,485 | <p>The hook is defined as:</p>
<p><code>urlretrieve(url[, filename[, reporthook[, data]]])</code>
"The third argument, if present, is a hook function that will be called
once on establishment of the network connection and once after each block
read thereafter. The hook will be passed three arguments; a count of bloc... | 1 | 2016-06-10T12:36:49Z | [
"python",
"python-3.x",
"progress-bar"
] |
Select a valid choice. XXXXXXXX is not one of the available choices | 37,748,121 | <p>i want to send sms to selected user form multiple choices by admin side but, I am unable to get the values from the <code>select_users</code> field after the selection is done by the admin. Please help me to solve this.</p>
<p>here's my code</p>
<p><strong>forms.py</strong></p>
<pre><code>class SendSMSForm(forms.... | 2 | 2016-06-10T12:18:40Z | 37,748,976 | <p>You could try:</p>
<p><code>select_users = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)</code></p>
| 2 | 2016-06-10T13:01:33Z | [
"python",
"django"
] |
Color does not affect Kivy Bubble background | 37,748,345 | <p>The <code>Bubble</code> widget has a <code>background_color</code> property, which represents the RGBA color of the background. It also has a <code>background_image</code> property, which is self-explanatory. But changing the <code>background_color</code> does nothing to how the bubble looks, unlike a <code>Button</... | 0 | 2016-06-10T12:29:52Z | 37,755,870 | <p>Kind of tricky this one! This is the same as tinting, however it works <strong>only</strong> when you set it like this:</p>
<pre><code>background_image = <something> # (1) or
background_image = '' # (2)
# then it'll tint the image(1) or the bubble itself(2)
background_color = (1, 0, 0, 0.5)
</code></... | 0 | 2016-06-10T19:31:11Z | [
"python",
"python-3.x",
"kivy"
] |
Python Illegal instruction on Raspberry Pi Zero | 37,748,358 | <p>When I try to run a python script I get <code>Illegal instruction</code> and that's it, it doesn't give any more details so I have no idea what's going on, is there a way to find out what is causing the <code>Illegal instruction</code> error?
Also, I run the code using <code>sudo</code> I don't get any output, the p... | 0 | 2016-06-10T12:30:19Z | 37,749,956 | <p>Like <a href="http://stackoverflow.com/users/3156750/notlikethat">@Notlikethat</a> said, the <code>Illegal instruction</code> error happens when the code being executed was compiled for a different architecture, Raspberry Pi uses ARM.</p>
<p>That said, I found out that GObject seemed to be causing the problem. Anyw... | 0 | 2016-06-10T13:49:05Z | [
"python",
"raspberry-pi",
"arm"
] |
Where does yum install python on CentOS 6.6? | 37,748,404 | <p>I've installed python27 on my CentOS 6.6 system using this command:</p>
<pre><code>% yum install python27
</code></pre>
<p>The install went successfully but I cannot find the python27 executable. It is not in the following places:</p>
<pre><code>/bin
/usr/bin
/usr/local/bin
</code></pre>
<p>Running the <code>yum... | 0 | 2016-06-10T12:33:09Z | 37,748,635 | <pre><code>rpm -ql <package name>
</code></pre>
<p>will show you all files in your installed rpm.</p>
| 2 | 2016-06-10T12:44:16Z | [
"python",
"centos",
"centos6",
"yum"
] |
Where does yum install python on CentOS 6.6? | 37,748,404 | <p>I've installed python27 on my CentOS 6.6 system using this command:</p>
<pre><code>% yum install python27
</code></pre>
<p>The install went successfully but I cannot find the python27 executable. It is not in the following places:</p>
<pre><code>/bin
/usr/bin
/usr/local/bin
</code></pre>
<p>Running the <code>yum... | 0 | 2016-06-10T12:33:09Z | 37,748,675 | <p>Try:</p>
<pre><code>alternatives --list | grep python
</code></pre>
<p>This lists all packages along with paths, which have multiple installed versions on the system and then greps python in the list.</p>
| 1 | 2016-06-10T12:46:08Z | [
"python",
"centos",
"centos6",
"yum"
] |
Attach the same SQLAlchemy table to two models with different binds | 37,748,717 | <p>I want to add two MySQL databases into my Flask app. Unfortunately, these database are almost identical.
They have same table and column names, but different data.</p>
<p>I am using SQLALCHEMY_BINDS in my <code>config.py</code></p>
<pre><code>SQLALCHEMY_BINDS = {
'old': 'mysql://[OLD_DB_HERE]',
'new': 'my... | 0 | 2016-06-10T12:48:12Z | 37,829,929 | <p>You should use a <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html" rel="nofollow">mixin</a> for this:</p>
<blockquote>
<p>A common need when using <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/api.html#module-sqlalchemy.ext.declarative" rel="nofollow"... | 0 | 2016-06-15T08:24:34Z | [
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] |
How to use method? | 37,748,729 | <p>I have a problem using the </p>
<p>Here is the code.</p>
<pre><code>root.mainloop()
</code></pre>
| 2 | 2016-06-10T12:48:40Z | 37,748,901 | <p>Don't use <code>time.sleep()</code> at all in Tkinter applications. Have the callback schedule a call to itself with <code>after()</code>.</p>
<pre><code>def command_Print(counter=0):
Labelvar.set(counter)
if counter < 10:
root.after(1000, lambda: command_Print(counter+1))
</code></pre>
<p>Also,... | 1 | 2016-06-10T12:57:59Z | [
"python",
"tkinter"
] |
How to use method? | 37,748,729 | <p>I have a problem using the </p>
<p>Here is the code.</p>
<pre><code>root.mainloop()
</code></pre>
| 2 | 2016-06-10T12:48:40Z | 37,751,352 | <p><code>after</code> with a single argument (eg: <code>after(10)</code>) is the same as calling <code>time.sleep</code>, and should generally be avoided. Since it puts your GUI to sleep, your GUI won't be able to respond to <em>any</em> events (including requests by the user or OS to refresh or resize the window)</p>
... | 0 | 2016-06-10T14:56:31Z | [
"python",
"tkinter"
] |
Python - BeautifulSoup - Formatting Data to Write to MySql | 37,748,814 | <p>I am new to Python/Programming and was hoping someone could help me out. I am wondering how I need to format the following in order to write to mySQL. The following code:</p>
<pre><code> from bs4 import BeautifulSoup
import urllib.request
url = "http://www.footballoutsiders.com/stats/qb"
page = urll... | 1 | 2016-06-10T12:53:31Z | 37,749,391 | <p>You need to get the tr tags and then extract the tds:</p>
<pre><code>from bs4 import BeautifulSoup, Tag
import urllib.request
url = "http://www.footballoutsiders.com/stats/qb"
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page.read(),"html.parser")
table = soup.select_one("table.stats")
cols = [td for t... | 0 | 2016-06-10T13:21:25Z | [
"python",
"beautifulsoup"
] |
Python / Django - Local variable designed before assignment | 37,748,828 | <p>I know this topic is talked many times in Stackoverflow but it concerns many different methods and I need help. I'm stuck since four hours ^^'</p>
<p>Here is the message : <strong>local variable 'menuItem' referenced before assignment</strong></p>
<pre><code>def B2BpartnerMenuDetailModify(request, partnerId, menuI... | 0 | 2016-06-10T12:54:06Z | 37,749,374 | <p>I found it !</p>
<p>I just forgot to add another try for this variable, just after the first try.</p>
<pre><code>try:
menuItem = MenuItem.objects.get(id=menuItemId)
except MenuItem.DoesNotExist:
return logoutUser(request)
</code></pre>
| 0 | 2016-06-10T13:20:10Z | [
"python",
"django"
] |
Django AttributeError:'Campaign' object has no attribute 'ads' | 37,748,837 | <p>I am trying to create in a nested serializer in Django Rest Framework but I keep getting this error. I know why it's throwing it but, i thought Django would handle the one-to-many relationship.</p>
<blockquote>
<p>AttributeError at /api/campaigns
Got AttributeError when attempting to get a value for field <code... | 0 | 2016-06-10T12:54:18Z | 37,749,830 | <p>I just fixed this, with a related name in the model</p>
<pre><code>campaign = models.ForeignKey(Campaign, related_name="ads")
</code></pre>
<p>I think it didn't worked last time because the reverse relationship was not working without a related_name.</p>
| 0 | 2016-06-10T13:42:27Z | [
"python",
"angularjs",
"django",
"django-rest-framework"
] |
python matrix average around single point | 37,748,852 | <p>I have a preexisting algorithm that prints out a matrix of integers that represent topography to a particular file. If a single point cannot be averaged the algorithm replaces the integer with a string (let's call it <code>None</code>). </p>
<p>My goal is this.</p>
<p>Anywhere a <code>None</code> is I want to take... | 0 | 2016-06-10T12:55:04Z | 37,749,026 | <pre><code>for i in xrange(len(mat)):
for j in xrange(len(mat[i])):
continue if mat[i][j] is not None;
mat[i][j] = (sum([mat[a][b] if mat[a][b] else 0
for a in xrange(max(0, i-1), min(i+1, len(mat))
for b in xrange(max(0, j-1), min(j+1, len(mat[i])))]) /
... | 0 | 2016-06-10T13:03:37Z | [
"python",
"matrix"
] |
Django REST Framework -- destroy method won't take on URL params? | 37,748,882 | <p>I am designing an API endpoint using Django REST Framework, and would like for it to accept GET and POST methods at the following endpoint:</p>
<pre><code>companies/<company_pk>/membership
</code></pre>
<p>as well as DELETE methods at the following endpoint:</p>
<pre><code>companies/<company_pk>/membe... | 0 | 2016-06-10T12:56:56Z | 37,751,358 | <p>The company membership router generates the following urls:</p>
<pre><code>companies/<company_pk>/membership/ # for handling list requests
companies/<company_pk>/membership/<pk>/ # for handling detail requests
</code></pre>
<p>You can access the <code>membership_pk</code> <strong>using the <code>... | 1 | 2016-06-10T14:57:00Z | [
"python",
"django",
"rest",
"python-3.x",
"django-rest-framework"
] |
Authenticate user with a specific hosted domain (hd) in Flask with Oauth2 | 37,748,993 | <p>Hi this is my current python code for authentification in my web app.</p>
<pre><code>auth_flow = OAuth2WebServerFlow(client_id=AUTH_CLIENT_ID,
client_secret=AUTH_CLIENT_SECRET,
scope=AUTH_PLUS_SCOPE,
redirect_uri=AUTH_CA... | 0 | 2016-06-10T13:02:35Z | 38,088,613 | <p>The hd parameter can be set by appending it to the <code>auth_uri</code> as follows</p>
<pre><code>auth_uri = GOOGLE_AUTH_URI
auth_uri = auth_uri + '?hd=' + 'example.com'
auth_flow = OAuth2WebServerFlow(client_id=AUTH_CLIENT_ID,
client_secret=AUTH_CLIENT_SECRET,
... | 1 | 2016-06-29T00:57:51Z | [
"python",
"flask",
"google-authentication"
] |
Sentences are not getting splitted using CoreNLP Server | 37,749,088 | <p>Having a review text like:</p>
<blockquote>
<p>"<em>The tutu's was for my neice... She LOVED IT!!! It fit well and will fit her for some time with the elastic waist.... great quality and very inexpensive! I would buy her another easily.</em>"</p>
</blockquote>
<p>and sending it to the CoreNLP Server:</p>
<pr... | 0 | 2016-06-10T13:06:07Z | 37,749,952 | <p>Don't know why but the problem appeared to come from <code>tokenize.whitespace</code>. I just commented it out:</p>
<pre><code>properties = {
#"tokenize.whitespace": "true",
"annotators": "tokenize, ssplit, pos, lemma, ner, parse",
"outputFormat": "json"
}
</code></pre>
| 1 | 2016-06-10T13:48:47Z | [
"python",
"stanford-nlp",
"corenlp"
] |
Django: Creating a model for a third party class | 37,749,111 | <p>What is a good way for adding a Django model for an existing third party (non-Django) Python class? I tried multiple inheritance like so:</p>
<pre><code>class ThirdPartyClass(object):
pass
class ModelForThirdPartyClass(models.Model, ThirdPartyClass):
uid = models.ForeignKey(settings.AUTH_USER_MODEL)
</code... | 0 | 2016-06-10T13:07:12Z | 37,753,430 | <p>Ugh, I have been chasing in the wrong direction: The multiple inheritance code above actually works. The error was that I added the following field to ModelForThirdPartyClass:</p>
<pre><code>foo = models.DecimalField(19, 4)
</code></pre>
<p>whereas I should have written</p>
<pre><code>foo = models.DecimalField(ma... | 0 | 2016-06-10T16:50:44Z | [
"python",
"django",
"multiple-inheritance"
] |
Django - 'pop index out of range' error when loop around multiple formset | 37,749,164 | <p>I have three forms that looks like that:</p>
<pre><code>class RoomsForm(forms.Form):
rooms = forms.IntegerField(min_value=1)
class PeopleForm(forms.Form):
adult = forms.IntegerField(min_value=1)
children = forms.IntegerField(required=False)
class ChildrenAgeForm(forms.Form):
children_age = forms.IntegerFiel... | 0 | 2016-06-10T13:09:50Z | 37,749,649 | <p>By using <code>pop</code> you're <em>removing</em> elements from the list:</p>
<pre><code>>>> mylist = [0,1,2,3,4,5,6,7,8,9]
>>> for i in range(0, len(mylist)):
... print(mylist)
... print(mylist.pop(i))
...
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
[1, 2, 3, 4, 5, 6, 7, 8, 9]
2
[1, 3, 4, 5, 6, 7,... | 1 | 2016-06-10T13:34:05Z | [
"python",
"django"
] |
Unexpected order of execution - GUI only updates after download is completed | 37,749,319 | <p>I have developed a GUI with pyside and it is executing a command after a button is pressed. The first command in the function that is called will update the status to "Downloading..." in the text_terminal. The second command will start the actual download (an SQL query which is performed via Pandas and cx_Oracle).</... | 0 | 2016-06-10T13:17:14Z | 37,754,903 | <p>The GUI doesn't update until the redraw events are processed. Those are typically done at the beginning of an event loop. If your application is busy running python code, it won't proceed to the next cycle of the event loop until that code is finished running. The proper way is to push long-running operations int... | 2 | 2016-06-10T18:22:51Z | [
"python",
"qt",
"user-interface",
"pyside"
] |
Callback each time subprocess prints | 37,749,357 | <p>I have an external program I want to call, for example <code>ping -t 8.8.8.8</code>.</p>
<p>And I am a bit confused as to what to do in order to have a callback each time the <code>ping</code> prints an output.</p>
<p>I am looking for a way to call a piece of code with the latest output line each time there is an ... | 0 | 2016-06-10T13:19:21Z | 37,749,358 | <p>This code works, the trick is using <code>process.stdout.readline()</code> since it blocks untill there is a line ready.</p>
<p>Sample code:</p>
<pre><code>cmd = "ping -t www.google.com"
ping = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
try:
while True:
line = str(ping.stdout.readline(), "a... | 0 | 2016-06-10T13:19:21Z | [
"python",
"python-3.x"
] |
Integrate OpenCV webcam into a Kivy user interface | 37,749,378 | <p>My current program is in Python and uses OpenCV. I rely on webcam captures and I am processing every captured frame:</p>
<pre><code>import cv2
# use the webcam
cap = cv2.VideoCapture(0)
while True:
# read a frame from the webcam
ret, img = cap.read()
# transform image
</code></pre>
<p>I would like to ... | 0 | 2016-06-10T13:20:18Z | 37,755,610 | <p><em>Note:</em> I have no clue how OpenCV works, but I found <a href="https://github.com/kivy/kivy/blob/master/kivy/core/camera/camera_opencv.py" rel="nofollow">camera_opencv.py</a>, so this means there is an easy way how to work with it.</p>
<p>As you see in camera example, this is the default way and when you look... | 1 | 2016-06-10T19:10:58Z | [
"python",
"user-interface",
"opencv",
"kivy"
] |
Integrate OpenCV webcam into a Kivy user interface | 37,749,378 | <p>My current program is in Python and uses OpenCV. I rely on webcam captures and I am processing every captured frame:</p>
<pre><code>import cv2
# use the webcam
cap = cv2.VideoCapture(0)
while True:
# read a frame from the webcam
ret, img = cap.read()
# transform image
</code></pre>
<p>I would like to ... | 0 | 2016-06-10T13:20:18Z | 37,823,034 | <p>You may have a look at <a href="http://www.pyimagesearch.com/2016/02/29/saving-key-event-video-clips-with-opencv/" rel="nofollow">http://www.pyimagesearch.com/2016/02/29/saving-key-event-video-clips-with-opencv/</a>. Also have a look at all the other posts from Adrian on his site. Many practical examples.</p>
| 1 | 2016-06-14T22:17:44Z | [
"python",
"user-interface",
"opencv",
"kivy"
] |
TypeError while printing a dictionary using a for-loop | 37,749,393 | <p>This is a (homework) problem that I've been working on for a few hours now. It was all going well until I was asked to print the contents of the dictionary specified in the code below:</p>
<pre><code># Practicing the use of dict in python by writing a simple Finnish-Spanish
# dictionary and a few operations that ca... | 0 | 2016-06-10T13:21:29Z | 37,749,445 | <p><code>sorted</code> returns a list, so <code>jarjestetty_sanakirja</code> is a list, not a dictionary. Lists must be indexed with integers, unlike dicts which can be indexed with anything hashable.</p>
<p>Try indexing the dictionary that gets passed in instead.</p>
<pre><code>jarjestetty_sanakirja = sorted(suomi_e... | 0 | 2016-06-10T13:24:38Z | [
"python",
"python-3.x"
] |
TypeError while printing a dictionary using a for-loop | 37,749,393 | <p>This is a (homework) problem that I've been working on for a few hours now. It was all going well until I was asked to print the contents of the dictionary specified in the code below:</p>
<pre><code># Practicing the use of dict in python by writing a simple Finnish-Spanish
# dictionary and a few operations that ca... | 0 | 2016-06-10T13:21:29Z | 37,750,350 | <p><code>sorted</code> returns a list so you need to access it with an integer unlike a dict that you can access with key-value</p>
| 0 | 2016-06-10T14:06:56Z | [
"python",
"python-3.x"
] |
Python 3: How do I determine the re-occuring sub-string/pattern within a string? | 37,749,395 | <p>I'm working on a CheckIO coding problem that involves decoding a message. I Have to find the key from a given encrypted and decrypted message which I've done; pythonpythonpythonpythonp</p>
<p>However, when I use the same key to try and decrypt a message that is longer than that string it fails as I can only start i... | 0 | 2016-06-10T13:21:42Z | 37,750,391 | <p>For finding the <strong><em>largest substring</em></strong> of a given base string I'd use something like this:</p>
<pre><code>import re
def get_largest_substring(string):
length = 0
x = 0
y = 0
for y in range(len(string)):
for x in range(len(string)):
... | 0 | 2016-06-10T14:09:23Z | [
"python",
"string",
"python-3.x"
] |
XlsxWriter and Python inheritance | 37,749,443 | <p>I just started working with XlsxWriter and I wanted to write my own methods to simplify writing excels, as the data I have has always the same format more or less.</p>
<p>I wanted to do this completely transparent writing a module that inherits <code>XlsxWriter</code> and that for who doesn't need my methods using ... | 4 | 2016-06-10T13:24:27Z | 37,751,111 | <p><code>write_results</code> is a method of <em>worksheet</em>, so you'll have to create a class inherited from <code>Worksheet</code> too. There you'll be able to write your <code>write_results</code>. <em>And</em> you'll have to reimplement the method where the <em>worksheet</em> is created. Looking into code it's <... | 2 | 2016-06-10T14:44:57Z | [
"python",
"inheritance",
"super",
"xlsxwriter"
] |
XlsxWriter and Python inheritance | 37,749,443 | <p>I just started working with XlsxWriter and I wanted to write my own methods to simplify writing excels, as the data I have has always the same format more or less.</p>
<p>I wanted to do this completely transparent writing a module that inherits <code>XlsxWriter</code> and that for who doesn't need my methods using ... | 4 | 2016-06-10T13:24:27Z | 37,753,046 | <p>I took a slightly different approach and it was working well enough to produce xls output in a web app.</p>
<p>Rather than overriding the xlswriter stuff, I just developed a Facade object that was matched what I was trying to do and then would just call on the underlying xlswriter assets to do the work.</p>
<pre><... | 3 | 2016-06-10T16:26:42Z | [
"python",
"inheritance",
"super",
"xlsxwriter"
] |
Proper way to utilize .loc in python's pandas | 37,749,492 | <p>When trying to change a column of numbers from <code>object</code> to <code>float</code> dtypes using pandas dataframes, I receive the following warning:</p>
<pre><code>A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
</code></pre>
<p>Now, t... | 0 | 2016-06-10T13:26:28Z | 37,749,648 | <p>Use the <code>copy</code> method. Instead of:</p>
<pre><code>df2 = df1[df1[some col] == value]
</code></pre>
<p>Just write:</p>
<pre><code>df2 = df1[df1[some col] == value].copy()
</code></pre>
<p>Initially, <code>df2</code> is a slice of <code>df1</code> and not a new dataframe. Which is why, when you try to mo... | 2 | 2016-06-10T13:34:02Z | [
"python",
"pandas",
"dataframe",
"warnings"
] |
Python HTTP request: no adapters found | 37,749,577 | <p>I'm trying to generate an http(s) request via Python Requests however I'm running into a problem:</p>
<pre><code>No connection adapters were found for 'set(['http://www.example.com/target'])'
</code></pre>
<p>I'm attempting to make the connection like so:</p>
<pre><code>url = ['http://www.example.com/target']
hea... | 0 | 2016-06-10T13:30:07Z | 37,749,685 | <p>Use a string, not a set.</p>
<pre><code>url = 'http://www.example.com/target'
</code></pre>
| 1 | 2016-06-10T13:35:27Z | [
"python",
"httprequest",
"python-requests"
] |
Why is my assertion failing when reading a NamedTemporaryFile? | 37,749,641 | <p>I'm writing code that reads a file and creates a dictionary based on the contents of that file. The code is quite straightforward, but I'd like to test the edge cases.</p>
<p>Here's my attempt:</p>
<pre><code>from tempfile import NamedTemporaryFile
from nose.tools import *
def read_file(filename):
with open(f... | -1 | 2016-06-10T13:33:37Z | 37,750,070 | <p>You need to flush the write to ensure the data is written before reading.</p>
<pre><code>def test_read_file():
file_contents = b"""Hello,World"""
with NamedTemporaryFile() as fp:
fp.write(file_contents)
fp.flush()
my_dict = read_file(fp.name)
print(my_dict)
assert my_dict == ... | 2 | 2016-06-10T13:53:30Z | [
"python",
"unit-testing",
"python-3.x",
"nose",
"temporary-files"
] |
Why is my assertion failing when reading a NamedTemporaryFile? | 37,749,641 | <p>I'm writing code that reads a file and creates a dictionary based on the contents of that file. The code is quite straightforward, but I'd like to test the edge cases.</p>
<p>Here's my attempt:</p>
<pre><code>from tempfile import NamedTemporaryFile
from nose.tools import *
def read_file(filename):
with open(f... | -1 | 2016-06-10T13:33:37Z | 37,750,223 | <p>Instead of using a real file, you can use an in-memory file-like object. This requires either mocking <code>open</code>, or changing your API to take a file-like object instead of a file name.</p>
<pre><code>import unittest.mock
import io
def test_read_file():
file_contents = io.BytesIO(b"""Hello,World""")
... | 1 | 2016-06-10T14:02:01Z | [
"python",
"unit-testing",
"python-3.x",
"nose",
"temporary-files"
] |
Fill Pyspark dataframe column null values with average value from same column | 37,749,759 | <p>With a dataframe like this, </p>
<pre><code>rdd_2 = sc.parallelize([(0,10,223,"201601"), (0,10,83,"2016032"),(1,20,None,"201602"),(1,20,3003,"201601"), (1,20,None,"201603"), (2,40, 2321,"201601"), (2,30, 10,"201602"),(2,61, None,"201601")])
df_data = sqlContext.createDataFrame(rdd_2, ["id", "type", "cost", "date"]... | 0 | 2016-06-10T13:38:45Z | 37,751,629 | <p>Well, one way or another you have to:</p>
<ul>
<li>compute statistics</li>
<li>fill the blanks</li>
</ul>
<p>It pretty much limits what you can really improve here not to mention this question would be a better fit for <a href="https://codereview.stackexchange.com/">CodeReview</a>. Still:</p>
<ul>
<li>replace <co... | 1 | 2016-06-10T15:10:11Z | [
"python",
"pyspark"
] |
Python: No value for argument 'filenames' in unbound method call | 37,749,766 | <p>I have a class to wrap around the config stuff of my program.
But when I try to test i in ipython like this:
</p>
<pre><code>c = Config(test.cfg)
</code></pre>
<p>I get the error:</p>
<pre><code>"TypeError: read() missing 1 required positional argument: 'filenames'
"
</code></pre>
<p>But I pylint throws this err... | 0 | 2016-06-10T13:38:54Z | 37,749,979 | <p>You don't instantiate <code>ConfigParser</code> when you assign it to the <code>self.scfgs</code> or <code>self.cfg</code> attributes; so when you then call <code>read</code> on it, you're calling an unbound method via the class, rather than a method on the instance.</p>
<p>It should be:</p>
<pre><code>self.cfg = ... | 2 | 2016-06-10T13:50:01Z | [
"python"
] |
Python: No value for argument 'filenames' in unbound method call | 37,749,766 | <p>I have a class to wrap around the config stuff of my program.
But when I try to test i in ipython like this:
</p>
<pre><code>c = Config(test.cfg)
</code></pre>
<p>I get the error:</p>
<pre><code>"TypeError: read() missing 1 required positional argument: 'filenames'
"
</code></pre>
<p>But I pylint throws this err... | 0 | 2016-06-10T13:38:54Z | 37,750,094 | <p>You are not initializing your <code>ConfigParser</code> correctly on the line before the <code>read</code> -- you are missing the <code>()</code> to actually create an instance.</p>
<p>Try:</p>
<pre><code>if typ is "main":
self.cfg = ConfigParser()
self.cfg.read(cfg)
</code></pre>
| 0 | 2016-06-10T13:54:39Z | [
"python"
] |
How to install Gensim version 0.11.1 on Windows 10 Machine? | 37,749,777 | <p>I have anaconda and Pip installed. I tried doing</p>
<pre><code>conda install -c anaconda gensim-0.11.1
</code></pre>
<p>but it couldn't find the package and the following msg was thrown on the PowerShell.</p>
<pre><code>Using Anaconda Cloud api site https://api.anaconda.org
Fetching package metadata: ......
Solv... | 0 | 2016-06-10T13:39:30Z | 37,893,283 | <p>Any reason you need the <code>0.11.1</code> version? That version hasn't been specifically built as a conda package apparently.</p>
<p>At the moment, <code>conda install gensim</code> will easily give you version <code>0.12.4</code>.</p>
<p>If you really need version <code>0.11.1</code>, first</p>
<pre><code>con... | 1 | 2016-06-18T04:35:57Z | [
"python",
"pip",
"conda",
"gensim"
] |
How to disregard the NaN data point in numpy array and generate the normalized data in Python? | 37,749,900 | <p>Say I have a numpy array that has some float('nan'), I don't want to impute those data now and I want to first normalize those and keep the NaN data at the original space, is there any way I can do that?</p>
<p>Previously I used <code>normalize</code> function in <code>sklearn.Preprocessing</code>, but that functio... | 2 | 2016-06-10T13:46:08Z | 37,750,034 | <p>You can mask your array using the <code>numpy.ma.array</code> function and subsequently apply any <code>numpy</code> operation:</p>
<pre><code>import numpy as np
a = np.random.rand(10) # Generate random data.
a = np.where(a > 0.8, np.nan, a) # Set all data larger than 0.8 to NaN
a = np.ma.array(a, ... | 6 | 2016-06-10T13:52:03Z | [
"python",
"numpy",
"scipy",
"scikit-learn"
] |
How to disregard the NaN data point in numpy array and generate the normalized data in Python? | 37,749,900 | <p>Say I have a numpy array that has some float('nan'), I don't want to impute those data now and I want to first normalize those and keep the NaN data at the original space, is there any way I can do that?</p>
<p>Previously I used <code>normalize</code> function in <code>sklearn.Preprocessing</code>, but that functio... | 2 | 2016-06-10T13:46:08Z | 37,750,497 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.nansum.html" rel="nofollow"><code>numpy.nansum</code></a> to compute the norm and ignore nan:</p>
<pre><code>In [54]: x
Out[54]: array([ 1., 2., nan, 3.])
</code></pre>
<p>Here's the norm with <code>nan</code> ignored:</p>
<pre><... | 0 | 2016-06-10T14:14:33Z | [
"python",
"numpy",
"scipy",
"scikit-learn"
] |
Load a cache file in Maya using Python and create the same render output | 37,750,040 | <p>I try to load a cache file in Maya using a python script. I used the code snipped posted here: <a href="http://stackoverflow.com/questions/20174424/importing-multiple-cache-files-in-maya-using-python?answertab=active#tab-top">importing multiple cache files in Maya using Python</a></p>
<p>My code looks like this:</p... | 0 | 2016-06-10T13:52:19Z | 37,755,674 | <p>Reading the attach cache command, Attaching cache to fluid is different, try :</p>
<pre><code>pm.mel.doImportFluidCacheFile(pathCache, "xmlcache", ['fluid1'], [])
</code></pre>
<p>Hope it will do the trick !</p>
<p>---EDIT---</p>
<p>Note that you could do without pymel formating a string like this : </p>
<pre><... | 1 | 2016-06-10T19:15:32Z | [
"python",
"maya"
] |
Can I query WHERE IN with multiple fields without using extra and raw sql? | 37,750,109 | <p>I am using postgresql backend in my Django application. I am building a queryset for model manager, where I have a filter with multiple Q objects. I've got a list of tuples and I want one of Q objects to be something like this:</p>
<pre><code>WHERE (id, id2) IN (VALUES (1, 1), (2, 1) ...);
</code></pre>
<p>where v... | 0 | 2016-06-10T13:55:09Z | 37,750,488 | <p>You can apply <code>reduce</code> on <code>operator.or_</code> on a <code>Q</code> object holding both ids that takes values from your list of tuples.</p>
<pre><code>import operator
from functools import reduce
from django.db.models import Q
q = reduce(operator.or_, (Q(id=i, id2=j) for i, j in [(1, 1), (2, 1),...... | 0 | 2016-06-10T14:14:21Z | [
"python",
"django",
"postgresql",
"django-queryset",
"django-orm"
] |
Why the execution renders wrong output? | 37,750,334 | <pre><code>def eoo(a):
if a%2 == 0:
print("Entered value is even")
else:
print("Entered value is odd")
b = 5556.4
print(b)
eoo(b)
</code></pre>
<p>The output is</p>
<pre><code>5556.4
Entered value is odd
</code></pre>
<p>Can anyone explain?</p>
| -3 | 2016-06-10T14:06:19Z | 37,750,621 | <p>a%2 will give you the remainder when you divide a by 2. when you divide 5556.4 by 2 your remainder is not 0, it is .4. That is why you are going to your else condition.</p>
| 0 | 2016-06-10T14:20:26Z | [
"python",
"python-3.x"
] |
Why the execution renders wrong output? | 37,750,334 | <pre><code>def eoo(a):
if a%2 == 0:
print("Entered value is even")
else:
print("Entered value is odd")
b = 5556.4
print(b)
eoo(b)
</code></pre>
<p>The output is</p>
<pre><code>5556.4
Entered value is odd
</code></pre>
<p>Can anyone explain?</p>
| -3 | 2016-06-10T14:06:19Z | 37,750,766 | <p>The output is not wrong. <code>5556.4 % 2</code> is not zero, thus you get in the <code>else</code> case:</p>
<pre><code>>>> 5556.4 % 2
0.3999999999996362
</code></pre>
<p>It's your assumption that any number that is not even must be odd that is wrong. In fact, categories such as "even" and "odd" do not m... | 0 | 2016-06-10T14:28:08Z | [
"python",
"python-3.x"
] |
why is my spyder IDE no longer opening | 37,750,357 | <p>I just closed my spyder IDE on win7 64bit 64bit python2.7 after a long session. </p>
<p>during that last session, I had also installed a couple of new libraries via conda install. maybe that threw things off?</p>
<p>now when I try to start spyder again, the spyder splash screen appears briefly but then spyder does... | 0 | 2016-06-10T14:07:22Z | 37,754,202 | <p>try this download setuptools from <a href="https://pypi.python.org/pypi/setuptools" rel="nofollow">here</a> and install.</p>
| 1 | 2016-06-10T17:38:44Z | [
"python",
"anaconda",
"spyder",
"conda"
] |
Django, how to mock annotate? | 37,750,366 | <p>I want to mock annotate, to see if it was called and the correct parameters where passed.</p>
<p>My query:</p>
<pre><code>User.object.filter(pk__in=[1,2,3]).annotate(is_banned=F('profile__is_banned'))
</code></pre>
<p>Test which is working:</p>
<pre><code>@mock.patch('models.User.objects')
def test_method(mock):... | 2 | 2016-06-10T14:07:58Z | 37,751,513 | <p>The annotate is in <code>mock.filter.return_value.annotate</code>.</p>
| 0 | 2016-06-10T15:04:23Z | [
"python",
"django",
"mocking"
] |
Scipy optimization with multiple bounds | 37,750,525 | <p>I'm solving a portfolio optimization problem where I need to allocate weights (capital) in such way that the end portfolio would have the lowest historical volatility possible. Currently I have two constraints on the total sum of weights of each stock and on their squared weights. Bounds for allocation in to each st... | 1 | 2016-06-10T14:15:48Z | 37,800,188 | <p>Modify your optimization function such that there is a high penalty if the weight of any asset goes outside its bound. Using this new function you can try to find the gradient and perform gradient ascent to optimize your return / reward. </p>
| 0 | 2016-06-13T22:33:05Z | [
"python",
"scipy",
"mathematical-optimization",
"finance"
] |
Is there a more efficient way to take the values from one row and apply it to the next 'n' rows in the same column? Pandas | 37,750,660 | <p>Say I have a dataframe. The dataframe has three columns foo1, foo2, fooName, and has 4,000 rows. In every 5th row there is a value in fooName 'blah'. I want to go through the dataframe and say when fooName equals 'blah', then the next 4 values (those that aren't filled with the blah value) of foo1 are set to the val... | 1 | 2016-06-10T14:22:50Z | 37,750,831 | <p>IIUC then the following should work</p>
<pre><code>dataframe.loc[dataframe['fooname'] !='blah', 'foo1'] = np.NaN
dataframe['foo1'] = dataframe['foo1'].ffill()
</code></pre>
<p>So you can replace the rows where the condition is not met with <code>NaN</code> and then call <code>ffill</code> to forward fill the value... | 1 | 2016-06-10T14:32:00Z | [
"python",
"performance",
"pandas"
] |
Convert a string variable to a date in Python 3? | 37,750,668 | <p>Bit of a newbie and I have Google and found no joy with this one. I am trying to create a bit of code that will allow a user to input a date and then tell them how many days it is until then. I have tried to convert the string to date.time using strp but I just get an error message. </p>
<p>I want it to run:
user... | -1 | 2016-06-10T14:23:02Z | 37,752,598 | <p>Is it what you are searching for? You can parse a string to a <code>datetime</code> with <code>strptime</code>, and then compute the number of days to reach it with <code>timedelta</code>.</p>
<pre><code>from datetime import datetime, timedelta
date = input('Enter your date: ')
delta = datetime.strptime(date, '%Y-... | 0 | 2016-06-10T16:01:34Z | [
"python",
"string",
"date",
"python-3.x"
] |
How to assign columns of data to variables | 37,750,728 | <p>I'm writing a general program to read and plot large amounts of data from .txt files. Each file has a different number of columns. I do know that each file has 8 columns that I'm not interested in, so I can figure out the number of relevant columns that way. How can I read the data and sort each relevant column's da... | 3 | 2016-06-10T14:25:46Z | 37,750,834 | <p>Pandas is in fact the right solution here. The issue is that in order to robustly handle something where you aren't certain of the underlying structure there's a lot of edge cases you have to watch out for, and trying to shoe-horn it into the <code>csv</code> module is a recipe for headaches (though it can be done)<... | 6 | 2016-06-10T14:32:19Z | [
"python",
"csv",
"variable-assignment"
] |
How to assign columns of data to variables | 37,750,728 | <p>I'm writing a general program to read and plot large amounts of data from .txt files. Each file has a different number of columns. I do know that each file has 8 columns that I'm not interested in, so I can figure out the number of relevant columns that way. How can I read the data and sort each relevant column's da... | 3 | 2016-06-10T14:25:46Z | 37,750,965 | <p>Well, you can use the csv module provided there is some kind of delimiter within the rows that sets the columns appart.</p>
<pre><code>import csv
file_to_read_from = 'myFile.txt'
#initializing as many lists as the columns you want (not all)
col1, col2, col3 = [], [], []
with open(file_to_read_from, 'r') as file_i... | 1 | 2016-06-10T14:38:05Z | [
"python",
"csv",
"variable-assignment"
] |
tensorflow multiplication across dimension | 37,750,794 | <p>Let tensor <code>T</code> has shape <code>[B, N, N, 6]</code> and I want to multiply matrices <code>[b, N, N, 0:3]</code> by <code>[b, N, N, 5]</code> element-wise for each <code>b in range(B)</code>. Note, that <code>[N, N, 4]</code> should not be changed. What is the best way to do this using tensorflow?</p>
<p>M... | 0 | 2016-06-10T14:29:48Z | 37,751,229 | <p>In TensorFlow, it's not generally possible to build a tensor value by assigning to slices. The programming model tends to be more functional than imperative. One way of implementing your calculation is as follows:</p>
<pre><code>result = tf.concat(3, [tf.mul(T[:, :, :, 0:4], T[:, :, :, 5:6]), T[:, :, :, 4:5]])
</co... | 1 | 2016-06-10T14:50:10Z | [
"python",
"tensorflow"
] |
Twilio Auth windows enviro variables | 37,750,822 | <p>I'm putting together some python code to move and then delete recordings from Twilio. There's plenty of documentation online to help with the script but the documentation says that I need to add the authorization code and token as a windows variable. The documentation shows how to get to the correct location to add... | 2 | 2016-06-10T14:31:35Z | 37,752,019 | <p>Twilio evangelist here.</p>
<p>By default the <code>TwilioRestClient</code> object in the <a href="https://twilio-python.readthedocs.io/en/latest/usage/basics.html" rel="nofollow">Twilio Python helper library</a> looks for environment variables named <code>TWILIO_ACCOUNT_SID</code> and <code>TWILIO_AUTH_TOKEN</code... | 0 | 2016-06-10T15:32:13Z | [
"python",
"windows",
"twilio",
"twilio-api"
] |
Twilio Auth windows enviro variables | 37,750,822 | <p>I'm putting together some python code to move and then delete recordings from Twilio. There's plenty of documentation online to help with the script but the documentation says that I need to add the authorization code and token as a windows variable. The documentation shows how to get to the correct location to add... | 2 | 2016-06-10T14:31:35Z | 37,755,577 | <blockquote>
<p>On my Windows 10 machine - in the new variable window - it asks for
'variable name' and 'variable value'.</p>
</blockquote>
<p>I don't have Windows 10 but I'm showing you on Widnows 7, it's probably the same interface to add system variables.</p>
<p>So you need to set two 'Environment Variables' >... | 1 | 2016-06-10T19:08:36Z | [
"python",
"windows",
"twilio",
"twilio-api"
] |
How can i download a gmail attachment based on subject? ERROR : "No route to host" when connecting to imap.gmail.com | 37,750,823 | <p>This is my first python code, so please excuse me.
This is what i wrote.</p>
<pre><code>import imaplib
import email
import os
import getpass
email = 'br******@******.com'
password = getpass.getpass('Enter your password: ')
mail = 'imap.gmail.com'
flag = '(RFC822)'
svdir = 'c:/Users/'
m = imaplib.IMAP4(mail)
m.log... | 0 | 2016-06-10T14:31:41Z | 38,357,167 | <p>Gmail does not allow connecting on a plain text port. SSL/TLS is required.</p>
<p>You will need:</p>
<pre><code>m = imaplib.IMAP4_SSL("imap.gmail.com", 993)
</code></pre>
| 0 | 2016-07-13T16:32:19Z | [
"python",
"python-2.7",
"python-3.x",
"gmail-imap",
"imaplib"
] |
Python: finding index of all elements of array in another including repeating arrays | 37,750,848 | <p>I have an array A of size 100 which might have repeating elements in it. I have another array B of size 10 which have unique elements in it. All elements of B are present in A and vice versa. I have another array C corresponding to B where each element of C is corresponding to the element in B.</p>
<p>I want to cre... | 0 | 2016-06-10T14:32:51Z | 37,750,993 | <p>No need for <code>numpy</code>. Just <code>zip</code> the <code>B</code> and <code>C</code> arrays to a <code>dict</code> and <code>map</code> the values of <code>A</code>:</p>
<pre><code>>>> btoc = dict(zip(B, C))
>>> A2 = np.array(map(btoc.get, A))
>>> A2
array(['D', 'D', 'A', 'C', 'C',... | 1 | 2016-06-10T14:39:49Z | [
"python",
"numpy"
] |
Python: finding index of all elements of array in another including repeating arrays | 37,750,848 | <p>I have an array A of size 100 which might have repeating elements in it. I have another array B of size 10 which have unique elements in it. All elements of B are present in A and vice versa. I have another array C corresponding to B where each element of C is corresponding to the element in B.</p>
<p>I want to cre... | 0 | 2016-06-10T14:32:51Z | 37,753,646 | <p>Here's a NumPythonic approach using <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>np.searchsorted</code></a> -</p>
<pre><code>sidx = B.argsort()
out = C[sidx[np.searchsorted(B,A,sorter = sidx)]]
</code></pre>
<p>Sample run -</p>
<pre><code>In [17... | 1 | 2016-06-10T17:03:41Z | [
"python",
"numpy"
] |
Python: finding index of all elements of array in another including repeating arrays | 37,750,848 | <p>I have an array A of size 100 which might have repeating elements in it. I have another array B of size 10 which have unique elements in it. All elements of B are present in A and vice versa. I have another array C corresponding to B where each element of C is corresponding to the element in B.</p>
<p>I want to cre... | 0 | 2016-06-10T14:32:51Z | 37,754,197 | <p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) contains functionality to do this in a single call; npi.indices, which is a vectorized equivalent of list.index.</p>
<pre><code>import numpy as np
A = np.array([1,1,4,5,5,6])... | 0 | 2016-06-10T17:38:08Z | [
"python",
"numpy"
] |
PyQt4 QPushButton text and icon alignment | 37,750,887 | <p>I want to create a button with text and icon, for example <strong>Next =></strong>, and I'm using QPushButton.</p>
<p>I tried to do the following:</p>
<pre><code>btn2 = QtGui.QPushButton('Next',self)
btn2.setIcon(QIcon(QPixmap("next.png")))
</code></pre>
<p>but I got:</p>
<p><a href="http://i.stack.imgur.com/wFW... | 1 | 2016-06-10T14:34:03Z | 37,754,484 | <p>You can use <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qwidget.html#setLayoutDirection" rel="nofollow"><code>setLayoutDirection()</code></a></p>
<pre><code>btn2.setLayoutDirection(QtCore.Qt.RightToLeft)
</code></pre>
<p>It can sometimes look a little weird, and you'll have to play with the button size and mar... | 0 | 2016-06-10T17:56:27Z | [
"python",
"python-2.7",
"pyqt4",
"qpushbutton"
] |
Dynamically creating functions and threads in Python | 37,750,917 | <p>I have an array filled with commands and I want to execute all of the commands at the same time.</p>
<p>So far I have:</p>
<pre><code>import threading
...
def MyThread0():
exec commandArray[0]
def MyThread1():
exec commandArray[1]
t1 = threading.Thread(target=MyThread0(), args=[]).start()
t2 = threadin... | 0 | 2016-06-10T14:35:36Z | 37,751,206 | <p>If I understand your problem correctly, it should be like this:</p>
<pre><code>import threading
...
def run_it_boy(index):
exec command_array[index]
for i in range(number_of_commands):
t[i] = threading.Thread(target=run_it_boy, args=(i,))
t[i].start()
</code></pre>
<p>Note that:</p>
<ol>
<li>Pa... | 1 | 2016-06-10T14:49:21Z | [
"python",
"multithreading",
"python-2.7"
] |
Dynamically creating functions and threads in Python | 37,750,917 | <p>I have an array filled with commands and I want to execute all of the commands at the same time.</p>
<p>So far I have:</p>
<pre><code>import threading
...
def MyThread0():
exec commandArray[0]
def MyThread1():
exec commandArray[1]
t1 = threading.Thread(target=MyThread0(), args=[]).start()
t2 = threadin... | 0 | 2016-06-10T14:35:36Z | 37,751,243 | <p>For starters, you don't want the <code>()</code> after the functions' names when creating the threads. That will call the function before the line is evaluated.</p>
<p>Secondly, <code>.start()</code> doesn't return anything, so your assignments to <code>t1</code> and <code>t2</code> are useless.</p>
<p>What you co... | 0 | 2016-06-10T14:50:48Z | [
"python",
"multithreading",
"python-2.7"
] |
Grouping by month-year after using datetime.strptime | 37,751,026 | <p>I'm fairly new at this. I have a csv that has a string date/time column as shown below. I am trying to average flow values based on month-year.</p>
<p>CSV:</p>
<pre><code>X Flow
6/9/16/ 14:00 15000
</code></pre>
<p>Code:</p>
<pre><code>import pandas as pd
from datetime import datetime
#i... | 1 | 2016-06-10T14:41:08Z | 37,751,336 | <p>I think you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a> and set column <code>X</code> to <code>index</code> by parameter <code>'index_col'</code>. Then first convert <code>index</code> to <a href="http://pandas.pydata.org/pandas-do... | 1 | 2016-06-10T14:55:32Z | [
"python",
"csv",
"datetime",
"pandas",
"dataframe"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.