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 |
|---|---|---|---|---|---|---|---|---|---|
Formatted string literals in Python 3.6 with tuples | 38,763,895 | <p>With <code>str.format()</code> I can use tuples for accesing arguments:</p>
<pre><code>>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
</code></pre>
<blockquote>
<p>'a, b, c'</p>
</blockquote>
<p>or </p>
<pre><code>>>> t = ('a', 'b', 'c')
>>> '{0}, {1}, {2}'.format(*t)
</code></pre>
<bloc... | 0 | 2016-08-04T09:44:02Z | 38,764,165 | <p>Your first <code>str.format()</code> call is a regular method call with 3 arguments, there is <em>no tuple involved there</em>. Your second call uses the <code>*</code> splat call syntax; the <code>str.format()</code> call receives 3 separate individual arguments, it doesn't care that those came from a tuple.</p>
<... | 1 | 2016-08-04T09:57:44Z | [
"python",
"python-3.x",
"tuples",
"string-formatting",
"python-3.6"
] |
How to save table in python? | 38,763,910 | <p>I am trying to get a table with data saved in svg, pdf or png file. Are there any libraries to do it?</p>
<p>I've tried pygal, but it seems that they provide only charts saving.</p>
<p>Edited: This table is just a couple of arrays with data, and I need to build a nice table from them</p>
| 0 | 2016-08-04T09:44:58Z | 38,764,770 | <p>Use tabulate, the documentation can be found <a href="https://pypi.python.org/pypi/tabulate" rel="nofollow">here</a></p>
| 0 | 2016-08-04T10:25:07Z | [
"python",
"pygal"
] |
Sort a list of lists in python | 38,764,161 | <p>This is how my list look after using some csv parsing:</p>
<pre><code>list=[['1131', '01/06/15', 'PROFI ROM FOOD SRL', '290.7'],
['1131', '', '', ''], ['2024194PJ', '01/08/15',
'SOCIETATEA NATIONALA DE', '2,088.17'], ['2024194PJ', '', 'RADIOCOMUNICATII SA', '']]
</code></pre>
<p>(this is a data s... | -1 | 2016-08-04T09:57:36Z | 38,764,373 | <p>Assuming the list will always follow the schema you provided:</p>
<pre><code>list2 = []
for i in range(len(list)/2):
list2 += [[list[i*2][0],
list[i*2][1],
list[i*2][2] + ' ' + list[i*2+1][2],
list[i*2][3]]]
</code></pre>
<p><strong>Explanation:</strong><br>
We star... | 0 | 2016-08-04T10:07:15Z | [
"python",
"list"
] |
Pandas Divide dataframe by index values | 38,764,425 | <p>I am trying to divide all columns in the dataframe by the index.(1221 rows, 1000 columns)</p>
<pre><code> 5000058004097 5000058022936 5000058036940 5000058036827 \
91.0 3.667246e+10 3.731947e+12 2.792220e+14 2.691262e+13
94.0 9.869027e+10 1.004314e+13 7.514220e+14 7.24252... | 2 | 2016-08-04T10:09:24Z | 38,764,467 | <p>You need to convert the <code>Index</code> object to a <code>Series</code>:</p>
<pre><code>df.div(df.index.to_series(), axis=0)
</code></pre>
<p>Example:</p>
<pre><code>In [118]:
df = pd.DataFrame(np.random.randn(5,3))
df
Out[118]:
0 1 2
0 0.828540 -0.574005 -0.535122
1 -0.126242 2.15... | 1 | 2016-08-04T10:11:41Z | [
"python",
"pandas",
"indexing",
"dataframe"
] |
Pandas Divide dataframe by index values | 38,764,425 | <p>I am trying to divide all columns in the dataframe by the index.(1221 rows, 1000 columns)</p>
<pre><code> 5000058004097 5000058022936 5000058036940 5000058036827 \
91.0 3.667246e+10 3.731947e+12 2.792220e+14 2.691262e+13
94.0 9.869027e+10 1.004314e+13 7.514220e+14 7.24252... | 2 | 2016-08-04T10:09:24Z | 38,764,482 | <p>You need convert index <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.to_series.html" rel="nofollow"><code>to_series</code></a> and then divide by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow"><code>div</code></a>:</p>
<pre><cod... | 1 | 2016-08-04T10:12:09Z | [
"python",
"pandas",
"indexing",
"dataframe"
] |
Pandas Divide dataframe by index values | 38,764,425 | <p>I am trying to divide all columns in the dataframe by the index.(1221 rows, 1000 columns)</p>
<pre><code> 5000058004097 5000058022936 5000058036940 5000058036827 \
91.0 3.667246e+10 3.731947e+12 2.792220e+14 2.691262e+13
94.0 9.869027e+10 1.004314e+13 7.514220e+14 7.24252... | 2 | 2016-08-04T10:09:24Z | 38,764,537 | <p>Another way of doing this is </p>
<pre><code>df.div(df.index.values, axis=0)
</code></pre>
<p>Example:</p>
<pre><code>In [7]: df = pd.DataFrame({'a': range(5), 'b': range(1, 6), 'c': range(2, 7)}).set_index('a')
In [8]: df.divide(df.index.values, axis=0)
Out[8]:
b c
a
0 ... | 1 | 2016-08-04T10:14:32Z | [
"python",
"pandas",
"indexing",
"dataframe"
] |
Initialize multiple lists in python | 38,764,493 | <pre><code>a = 2
b = 3
c = 4
x = y = z = [0 for i in xrange(a*b*c)]
</code></pre>
<p>Is there a way in which x,y,z can be initialized <strong>in one line</strong> (because I don't want to multiply a, b and c for each list initialization), as separate lists of 0s. In the above if x is updated, then y and z are also get... | 0 | 2016-08-04T10:12:35Z | 38,764,558 | <p>Just use another comprehension and unpack it:</p>
<pre><code>x, y, z = [[0 for i in xrange(a*b*c)] for _ in xrange(3)]
</code></pre>
<p>Note that <code>[0 for i in xrange(a*b*c)]</code> is equivalent to the simpler <code>[0] * a*b*c</code>.</p>
| 3 | 2016-08-04T10:15:20Z | [
"python",
"initialization",
"generator-expression"
] |
Initialize multiple lists in python | 38,764,493 | <pre><code>a = 2
b = 3
c = 4
x = y = z = [0 for i in xrange(a*b*c)]
</code></pre>
<p>Is there a way in which x,y,z can be initialized <strong>in one line</strong> (because I don't want to multiply a, b and c for each list initialization), as separate lists of 0s. In the above if x is updated, then y and z are also get... | 0 | 2016-08-04T10:12:35Z | 38,764,707 | <p>Looking at your stated intention rather than at the 'one line' requirement:</p>
<pre><code>a = 2
b = 3
c = 4
x = [0 for i in xrange(a*b*c)]
y = x [:]
z = x [:]
</code></pre>
<p>Not sure the optimizer is clever enough to avoid repeated multiplication at:</p>
<pre><code>x, y, z = [[0 for i in xrange(a*b*c)] for _ i... | 0 | 2016-08-04T10:21:38Z | [
"python",
"initialization",
"generator-expression"
] |
Is there break function in python (for PyCharm or other IDE)? | 38,764,742 | <p>There is <code>__debugbreak</code> function in C++.</p>
<p>I need to use similar function that breaks run-time with resume possibility in my Python code (with PyCharm IDE).</p>
| 1 | 2016-08-04T10:23:35Z | 38,765,075 | <p>There's the pdb (and ipdb) module which provide interactive debuggers.</p>
<p>You can use </p>
<pre><code>import pdb; pdb.set_trace()
</code></pre>
<p>to insert a breakpoint wherever you want.</p>
<p>I'm not sure how these will work with PyCharm (for which you should just be able to click to add a breakpoint any... | 2 | 2016-08-04T10:40:10Z | [
"python",
"debugging",
"pycharm",
"breakpoints",
"break"
] |
Groupby with conditions in pandas | 38,764,766 | <p>I have a <code>pd.DataFrame</code> that looks like this:</p>
<pre><code>In [30]: df
Out[30]:
DATES UID A
0 2014-01-01 1 False
1 2014-01-02 2 False
2 2014-01-03 3 True
3 2014-01-04 4 True
4 2014-01-05 5 False
5 2014-01-06 6 True
6 2014-01-07 1 False
7 2014-01-08 ... | 0 | 2016-08-04T10:25:03Z | 38,764,963 | <p>It looks like need first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html" rel="nofollow"><code>filter</code></a>:</p>
<pr... | 1 | 2016-08-04T10:34:40Z | [
"python",
"pandas"
] |
Python: Writing a script that print filenames of zerolength files and a script that counts all images in a web page | 38,764,891 | <p>I am currently learning Python, and could really use help from experienced coders with help to getting started on solving this assignment: </p>
<ol>
<li><p>Using os.walk, write a script that will print the filenames of zero length files. It should also print the count of zero length files.</p></li>
<li><p>Write a s... | -3 | 2016-08-04T10:31:01Z | 38,767,689 | <p>You can use BeautifulSoup to easily count the number of images on the page. All you would need to do is scrape all of the tags and get the length of that scrape.</p>
<pre><code>import urllib
from bs4 import BeautifulSoup
url = 'whatever the website is'
r = urllib.urlopen(url).read()
soup = BeautifulSoup(r, 'html.... | 0 | 2016-08-04T12:43:53Z | [
"python",
"python-3.x",
"os.walk"
] |
Open all files in a folder starting with a certain letter | 38,764,902 | <p>I would like to open all excel files in a folder that start with a certain string. For example, let's say that I want all files that start with 'hello'. From the following list:
1)hello1.xls
2)hello2.xls
3)other2.xls
4)hello3.xls
5)other3.xls</p>
<p>I would like to open files 1, 2, 4. I would like to open each file... | -3 | 2016-08-04T10:31:40Z | 38,765,002 | <p>Assuming all files are in your current working directory, you can use <code>glob</code> like this:</p>
<pre><code>import glob
file_names = glob.glob("hello*")
for file_name in file_names:
with open(file_name) as f:
for line in f:
# do things
</code></pre>
| 1 | 2016-08-04T10:36:32Z | [
"python",
"pandas"
] |
Python JSON variables not being accepted | 38,764,938 | <p>I'm trying to save the variables from a JSON string to be used as settings for a different function, sadly though, they are not being accepted as good as I wanted. Here's what's cooking;</p>
<p>The JSON string comes through MQTT as so:</p>
<pre><code>def on_message(client, userdata, msg):
data = json.loads... | -1 | 2016-08-04T10:33:27Z | 38,765,260 | <p>Wrap your values with <code>int</code> as these are in <code>unicode</code> format</p>
<pre><code>def on_message(client, userdata, msg):
data = json.loads(msg.payload)
camera = picamera.PiCamera()
camera.resolution = (2592, 1944)
camera.sharpness = int(data['sharpness'])
came... | 0 | 2016-08-04T10:48:17Z | [
"python",
"json"
] |
Makemigrations after splitting models not detecting changes | 38,764,997 | <p>I am developing a django app in virtual environment. Django version 1.9.7.</p>
<p>I splitted the <code>models.py</code> into multiple files and kept them in a folder with <code>__init__.py</code> file. </p>
<pre><code>|-- Models
| |-- __init__.py
| |-- PersonModel.py
| `-- VehicleModel.py
</code></pre>
<p>... | 0 | 2016-08-04T10:36:22Z | 38,766,878 | <p>Just import all models into 'models.py' as the django look up for models in models.py for migrating a schema.</p>
| 0 | 2016-08-04T12:07:08Z | [
"python",
"django"
] |
command line python script run on a file in different directory | 38,765,061 | <p>I have a script.py in /Users/admin/Desktop and I want to run this script on a file that is in /Users/admin//Desktop/folder/file.txt, without changing the present dir. </p>
<p>Question: what is the most efficient way to do that on command-line ? I am using the following commands and results are not as expected. </p>... | 0 | 2016-08-04T10:39:33Z | 38,765,328 | <ol>
<li>Remove the semicolon because that will prematurely terminate the command.</li>
<li>Pass the correct path to the file to your program. You say it is <code>/Users/admin/Desktop/folder/file.txt</code>, however, your command is using <code>/Users/admin/Desktop/file.txt</code> (it's missing <code>folder</code>)</li... | 1 | 2016-08-04T10:51:38Z | [
"python",
"command-line"
] |
List of dictionaries in jinja | 38,765,097 | <p>I want to iterate through a list of dictionaries using jinja.</p>
<p>here is my list :</p>
<pre><code>[{'product': 'EC2', 'cost': 3.5145240400000013}, {'product': 'ElastiCache', 'cost': 1.632000000000001}, {'product': 'Elasticsearch', 'cost': 4.423768260000001}, {'product': 'RDS', 'cost': 1.632000000000001}]
</cod... | -1 | 2016-08-04T10:41:10Z | 38,765,161 | <p>Try This:-</p>
<pre><code>{% for dict_item in products %}
<h1>Product: {{ dict_item['product'] }}</h1>
<h2>Cost: {{ dict_item['cost'] }}</h2>
{% endfor %}
</code></pre>
| 0 | 2016-08-04T10:44:16Z | [
"python",
"dictionary",
"jinja2"
] |
Python: How can I access IDs separated by | (pipe) in an argument | 38,765,150 | <p>I have searched both here and using google. The | (pipe) symbol is the bitwise OR operator, but I can't find anything specific to my problem. Here is an <a href="https://developers.maxon.net/docs/Cinema4DPythonSDK/html/modules/c4d.gui/GeDialog/index.html#GeDialog.AddButton" rel="nofollow">example</a> from the Cinema... | 0 | 2016-08-04T10:43:49Z | 38,765,309 | <p>The key here is to "space out" the values of the flags in such a way that each combination of <code>|</code> with arbitrary number of flags produces a unique value. That way you can tell each flags are meant to be used simply by the value of the argument.</p>
<p>Even though the following article talks about C# you ... | 0 | 2016-08-04T10:50:27Z | [
"python",
"function",
"arguments",
"python-2.x",
"flags"
] |
Python: How can I access IDs separated by | (pipe) in an argument | 38,765,150 | <p>I have searched both here and using google. The | (pipe) symbol is the bitwise OR operator, but I can't find anything specific to my problem. Here is an <a href="https://developers.maxon.net/docs/Cinema4DPythonSDK/html/modules/c4d.gui/GeDialog/index.html#GeDialog.AddButton" rel="nofollow">example</a> from the Cinema... | 0 | 2016-08-04T10:43:49Z | 38,765,508 | <p>Flags like this are sometimes called "bit-masks". If you define them as hexadecimal you will find them much easier to use. </p>
<p>You can use binary <code>&</code> to determine if the flag is set. For example:</p>
<pre><code>ID_OK = 0x01
ID_CANCEL = 0x10
def Func(flags):
print "0x%02x" % (flags)
if... | 0 | 2016-08-04T10:59:50Z | [
"python",
"function",
"arguments",
"python-2.x",
"flags"
] |
UTF -8 issue in Datastxa Cassandra | 38,765,242 | <p>I am using Datastax Cassandra 4.8 version. Using SOlr for Search activity. In my table , I have chinese character as well as English character.
Table retrieval is workign smooth for english character search but once I am trying to search by Chinese character , either it gave me 0 row or give me below error. </p>
<... | 1 | 2016-08-04T10:47:40Z | 38,765,615 | <p>It looks like the author column is configured to use an <code>ascii</code> data type. I'm not familiar with Datastax Cassandra, so I couldn't tell you how to change it, but I think if you change it to datatype <code>varchar</code> it should work.</p>
<p>Sorry for the kinda generic answer, but hope it helps anyway.<... | 0 | 2016-08-04T11:05:02Z | [
"php",
"python",
"solr",
"cassandra",
"datastax"
] |
UTF -8 issue in Datastxa Cassandra | 38,765,242 | <p>I am using Datastax Cassandra 4.8 version. Using SOlr for Search activity. In my table , I have chinese character as well as English character.
Table retrieval is workign smooth for english character search but once I am trying to search by Chinese character , either it gave me 0 row or give me below error. </p>
<... | 1 | 2016-08-04T10:47:40Z | 38,789,546 | <p>It looks like you have run into <a href="https://issues.apache.org/jira/browse/CASSANDRA-10875" rel="nofollow">CASSANDRA-10875</a>. This was fixed in 2.0.13. You don't say which version of 4.8 you are running but I would suggest updating to the latest version of 4.8 where this issue should be fixed.</p>
| 0 | 2016-08-05T12:42:54Z | [
"php",
"python",
"solr",
"cassandra",
"datastax"
] |
pandas Dataframe set value fails | 38,765,480 | <p>I been following the documentation but it keeps on throwing this error</p>
<pre><code>row_names = ["ab_" + str(x) for x in range(4)]
col_names = ["n_" + str(x) for x in range(5)]
df = pd.DataFrame(index=row_names, columns=col_names)
df = df.fillna(0) # with 0s rather than NaNs
# Load the images
print df.loc['ab_3... | 1 | 2016-08-04T10:58:47Z | 38,765,506 | <p>Unlike <code>loc</code>, <code>set_value</code> is a method, so it needs to be called.</p>
<p>But <code>df.set_value(['ab_3','n_1', '1'])</code> won't do what you expect as well.
See the its <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_value.html" rel="nofollow">docs</a>.</p>
| 1 | 2016-08-04T10:59:46Z | [
"python",
"pandas"
] |
pandas Dataframe set value fails | 38,765,480 | <p>I been following the documentation but it keeps on throwing this error</p>
<pre><code>row_names = ["ab_" + str(x) for x in range(4)]
col_names = ["n_" + str(x) for x in range(5)]
df = pd.DataFrame(index=row_names, columns=col_names)
df = df.fillna(0) # with 0s rather than NaNs
# Load the images
print df.loc['ab_3... | 1 | 2016-08-04T10:58:47Z | 38,765,515 | <p>using wrong type of brackets, you want <code>()</code> not <code>[]</code>:</p>
<pre><code>df.set_value('ab_3','n_1', '1')
n_0 n_1 n_2 n_3 n_4
ab_0 0 0 0 0 0
ab_1 0 0 0 0 0
ab_2 0 0 0 0 0
ab_3 0 1 0 0 0
</code></pre>
| 2 | 2016-08-04T11:00:21Z | [
"python",
"pandas"
] |
Boolean Indexing with Pandas isn't working for me | 38,765,585 | <p>I'm getting some strange behaviour in pandas when using Boolean indexing, and I don't understand what's going wrong.</p>
<p>With a DataFrame <code>data</code> that contains a column <code>RSTAR</code> of <code>Float</code> values, among others, I'm getting the following when I try to do boolean indexing:</p>
<pre>... | 2 | 2016-08-04T11:03:41Z | 38,765,620 | <p>I think you can use one line solution with pandas function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.notnull.html" rel="nofollow"><code>notnull</code></a>:</p>
<pre><code>rejection_list = data.ix[(data.RSTAR == 0) | (data.RSTAR.notnull()) , 'NAME'].tolist()
</code></pre>
<p>or:</... | 1 | 2016-08-04T11:05:21Z | [
"python",
"pandas",
"numpy",
"scipy"
] |
Ansible - "NameError: name 'urllib2' is not defined" | 38,765,586 | <p>Getting this below error while trying to run ansible(version >2) with python 3.5.2</p>
<p>I have looked into the github issues terming it as resolved, but can't sort out what needs to be done. <a href="https://github.com/ansible/ansible/issues/16013" rel="nofollow">https://github.com/ansible/ansible/issues/16013</a... | 0 | 2016-08-04T11:03:41Z | 38,765,845 | <p>Urllib2 is specific to Python v2.</p>
<p>Urllib2 documentation at <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">http://docs.python.org/library/urllib2.html</a>:</p>
<blockquote>
<p>The urllib2 module has been split across several modules in Python 3.0
named urllib.request and urllib.erro... | 3 | 2016-08-04T11:15:39Z | [
"python",
"linux",
"ansible"
] |
Ansible - "NameError: name 'urllib2' is not defined" | 38,765,586 | <p>Getting this below error while trying to run ansible(version >2) with python 3.5.2</p>
<p>I have looked into the github issues terming it as resolved, but can't sort out what needs to be done. <a href="https://github.com/ansible/ansible/issues/16013" rel="nofollow">https://github.com/ansible/ansible/issues/16013</a... | 0 | 2016-08-04T11:03:41Z | 38,765,851 | <p>Ansible is currently not able to run with <code>Python3</code>. That is also stated in the linked Github Issue.</p>
| 0 | 2016-08-04T11:15:56Z | [
"python",
"linux",
"ansible"
] |
Ansible - "NameError: name 'urllib2' is not defined" | 38,765,586 | <p>Getting this below error while trying to run ansible(version >2) with python 3.5.2</p>
<p>I have looked into the github issues terming it as resolved, but can't sort out what needs to be done. <a href="https://github.com/ansible/ansible/issues/16013" rel="nofollow">https://github.com/ansible/ansible/issues/16013</a... | 0 | 2016-08-04T11:03:41Z | 38,765,858 | <p>The <a href="https://pypi.python.org/pypi/ansible/2.1.1.0" rel="nofollow">ansible python API</a> does not support Python 3. The PyPI page lists only 2.6 and 2.7 .</p>
| 1 | 2016-08-04T11:16:16Z | [
"python",
"linux",
"ansible"
] |
invalid type, must be a string or Tensor [TensorFlow] | 38,765,676 | <p>I have problem in Machine Learning library from Google - Tensorflow.
When I want to initialize my session, it tells me that must be string or tensor. I don't spot any mistake. </p>
<pre><code>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_... | 0 | 2016-08-04T11:08:09Z | 38,765,816 | <p>I think you just missed a pair of parentheses <code>()</code> after <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/state_ops.html#initialize_all_variables" rel="nofollow"><code>tf.initialize_all_variables</code></a> ;)</p>
<p>As python says, it's in line 13, look after</p>
<blockquote>
<p><co... | 0 | 2016-08-04T11:14:32Z | [
"python",
"initialization",
"syntax-error",
"tensorflow",
"mnist"
] |
How can I save lots of images after resizing them all into another directory in Python(PIL)? | 38,765,757 | <p>Here is my code :</p>
<pre><code># -*- coding: utf-8 -*-
#!/usr/bin/python
import PIL
from PIL import Image
import os,sys
path = "/home/ozer/Desktop/Yedek/Workspace/"
dirs = os.listdir (path)
def resize():
for item in dirs:
if os.path.isfile(path1+item):
img = Image.open(... | 0 | 2016-08-04T11:11:56Z | 38,766,176 | <p>Try</p>
<pre><code>img.save("/home/ozer/Desktop/Scripts/Last/"+item+".jpg","JPEG")
</code></pre>
<p>or, equivalently</p>
<pre><code>img.save("/home/ozer/Desktop/Scripts/Last/{}.jpg".format(item),"JPEG")
</code></pre>
<p>At present you are trying to create a single output file called <code>*.jpg</code> for each i... | 1 | 2016-08-04T11:31:27Z | [
"python",
"python-imaging-library"
] |
Pass multiple arguments to listbox | 38,765,877 | <p>I am trying to pass a label to the callback function of my listbox, but somehow I can't manage to do it.</p>
<p>I already tried with lambdas, but without success.</p>
<p>This is my current code-snippet:</p>
<pre><code>program_list.bind('<<ListboxSelect>>', MainController.select_program)
</code></pre>
... | 0 | 2016-08-04T11:16:52Z | 38,765,965 | <p>You can use lambda like this:</p>
<p><strong>CHANGED</strong></p>
<pre><code>from tkinter import *
root = Tk()
def on_select(event, arg):
lb = event.widget
idx = lb.curselection()
item = lb.get(idx)
print('%s, %s' % (item, arg))
lst = Listbox(root)
for i in range(5):
lst.insert(END, 'item ' ... | 1 | 2016-08-04T11:20:50Z | [
"python",
"python-2.7",
"tkinter",
"listbox"
] |
How to patch globally in pytest? | 38,765,917 | <p>I use pytest quite a bit for my code. Sample code structure looks like this. The entire codebase is <code>python-2.7</code></p>
<pre><code>core/__init__.py
core/utils.py
#feature
core/feature/__init__.py
core/feature/service.py
#tests
core/feature/tests/__init__.py
core/feature/tests/test1.py
core/feature/tests/... | 1 | 2016-08-04T11:18:12Z | 38,782,306 | <p>I added a file called <code>core/feature/conftest.py</code> that looks like this</p>
<pre><code>import logging
import pytest
@pytest.fixture(scope="session", autouse=True)
def default_session_fixture(request):
"""
:type request: _pytest.python.SubRequest
:return:
"""
log.info("Patching core.fe... | 0 | 2016-08-05T06:13:07Z | [
"python",
"tdd",
"py.test",
"python-mock"
] |
Loading numpy arrays into Fortran quickly | 38,765,977 | <p>I am currently working on a Fortran program, which requires a large data file as input. This data file is created using Python, and I am currently saving it in a human readable format using the <code>np.savetxt()</code> function. </p>
<p>However, the size of this file is very large (at least 1.5GB of disk space) an... | 2 | 2016-08-04T11:21:24Z | 38,767,907 | <p>In my day to day work, I run a very large simulation switching between fortran and python for computation and visualization purposes. I would suggest using the netcdf libraries in both of them, netcdf is an excellent format for transferring between the two systems and keeps the file size in check. Some good links ar... | 3 | 2016-08-04T12:53:17Z | [
"python",
"fortran",
"storage",
"loading"
] |
Loading numpy arrays into Fortran quickly | 38,765,977 | <p>I am currently working on a Fortran program, which requires a large data file as input. This data file is created using Python, and I am currently saving it in a human readable format using the <code>np.savetxt()</code> function. </p>
<p>However, the size of this file is very large (at least 1.5GB of disk space) an... | 2 | 2016-08-04T11:21:24Z | 38,777,615 | <p>It depends on your data structures, but if it is just one or a few arrays you don't need any external libraries (I am not impressed with all the hassle of NetCDF).</p>
<pre><code>import numpy as np
a = np.zeros([10,10], order="F")
a.tofile("a.bin")
</code></pre>
<p>and</p>
<pre><code> use iso_fortran_env
real(... | 4 | 2016-08-04T21:23:18Z | [
"python",
"fortran",
"storage",
"loading"
] |
Fit Weibull to distribution with genextreme and weibull_min | 38,765,996 | <p>Using SciPy, I am trying to reproduce the weibull fit from <a href="http://stats.stackexchange.com/questions/132652/how-to-determine-which-distribution-fits-my-data-best">this question</a>. My fit looks good when I use the <code>genextreme</code> function as follows:</p>
<pre><code>import numpy as np
from scipy.sta... | 2 | 2016-08-04T11:21:53Z | 38,766,527 | <p>The parameters returned by <code>weibull_min.fit()</code> are <code>(shape, loc, scale)</code>. <code>loc</code> is the location parameter. (All scipy distributions include a location parameter, even those where a location parameter isn't normally used.) The docstring of <code>weibull_min.fit</code> includes this:... | 1 | 2016-08-04T11:48:31Z | [
"python",
"scipy",
"distribution",
"weibull"
] |
Start Idlex instead of Idle with Launcher Symbol | 38,766,023 | <p>I'm running with Ubuntu 16.04 and Python 2.7.12.
I downloaded and installed Idlex and can start the editor with the extensions, using the terminal in the folder, where the idlex.py file is. </p>
<p>Is it possible, to create a shortcut in the launcher like the standard Idle, such that Idlex is loaded by default?</p>... | 0 | 2016-08-04T11:23:17Z | 38,766,345 | <p>Make it's entry in $PATH veriable than </p>
<p>Go to system settings
click on Details
click on default application
set it here </p>
<p>OR</p>
<p>right click -> Properties
Go to open with tab
set it here or use command </p>
<p>Or </p>
<p>Use Ubuntu Tweak</p>
<pre><code>sudo add-apt-repository ppa:tualatrix/... | 0 | 2016-08-04T11:40:42Z | [
"python",
"ubuntu",
"python-idle"
] |
Having key value separated on python with boto | 38,766,243 | <p>I am trying to get only the value from a dictionary in python>
I followed this <a href="https://www.mkyong.com/python/python-how-to-loop-a-dictionary/" rel="nofollow">link</a> but I have a weird error telling me </p>
<p><code>AttributeError: 'list' object has no attribute 'items'</code></p>
<p>But it is not a list... | 0 | 2016-08-04T11:34:53Z | 38,766,541 | <p>You have the dictionary nested in a list. You have to iterate through the list to access all the <code>attachments</code> to that volume. Your approach only takes the last <code>volume</code> from the previous iteration, you should instead nest the <em>for-loops</em> to view all the volumes: </p>
<pre><code>for vol... | 0 | 2016-08-04T11:49:08Z | [
"python",
"dictionary",
"boto3"
] |
Python binding for MuJoCo physics library using mujoco-py package | 38,766,267 | <p>I want to use MuJoCo (<a href="http://www.mujoco.org/" rel="nofollow">http://www.mujoco.org/</a>), an advanced physics simulator with python bindings (<a href="https://github.com/openai/mujoco-py" rel="nofollow">https://github.com/openai/mujoco-py</a>).</p>
<p>I've got my MuJoCo license file mjkey.text and added th... | 4 | 2016-08-04T11:36:34Z | 38,839,741 | <p>Try editing <code>mjlib.py</code>, replacing <code>"bin/mujoco131.lib"</code> with <code>"bin/mujoco131.dll"</code> in the loader.</p>
<p>I also had to explicitly specify <code>platname = "win"</code> in <code>platname_targdir.py</code></p>
| 1 | 2016-08-08T23:01:31Z | [
"python",
"c++",
"dll",
"physics",
"dllimport"
] |
mayavi in python Anaconda | 38,766,293 | <p>I installed <code>mayavi</code> in Anaconda using the command </p>
<pre><code>conda.exe install mayavi
</code></pre>
<p>in Anaconda command prompt. Now when I close Spyder it doesn't open anymore. How do I fix this? I am using Windows.</p>
| 1 | 2016-08-04T11:37:52Z | 39,778,157 | <p>I want to show my solution for that problem :
My OS = Windows 10 - 64-bit
Python 2.7.12 (Anaconda2 4.2.0 64-bit)
Package Mayavi version 4.4.0</p>
<p>After installation of that package Mayavi (with Anaconda Navigator Beta -> Environments), Spyder couldn't be opened again (as mentioned in your question).
Then I tried... | 1 | 2016-09-29T19:06:46Z | [
"python",
"anaconda",
"spyder",
"mayavi"
] |
Pandas transforming hbar in line | 38,766,333 | <p>I have a pandas hbar plot, but I would like to have a line instead of the bars (just a line going to the top of the bars).</p>
<p>Is that possible? </p>
<p>I have </p>
<pre><code>b3["R2_foret"].plot(legend=False, kind='barh')
</code></pre>
<p>which gives me</p>
<p><a href="http://i.stack.imgur.com/4WdaZ.png... | 0 | 2016-08-04T11:39:45Z | 38,766,500 | <p>do you simply mean</p>
<p><code>b3["R2_foret"].plot()</code> ? </p>
| 0 | 2016-08-04T11:47:26Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
Pandas transforming hbar in line | 38,766,333 | <p>I have a pandas hbar plot, but I would like to have a line instead of the bars (just a line going to the top of the bars).</p>
<p>Is that possible? </p>
<p>I have </p>
<pre><code>b3["R2_foret"].plot(legend=False, kind='barh')
</code></pre>
<p>which gives me</p>
<p><a href="http://i.stack.imgur.com/4WdaZ.png... | 0 | 2016-08-04T11:39:45Z | 38,766,751 | <p>Something close:</p>
<pre><code>b3["R2_foret"].plot(legend=False, drawstyle="steps")
</code></pre>
| 0 | 2016-08-04T11:59:51Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
Pandas transforming hbar in line | 38,766,333 | <p>I have a pandas hbar plot, but I would like to have a line instead of the bars (just a line going to the top of the bars).</p>
<p>Is that possible? </p>
<p>I have </p>
<pre><code>b3["R2_foret"].plot(legend=False, kind='barh')
</code></pre>
<p>which gives me</p>
<p><a href="http://i.stack.imgur.com/4WdaZ.png... | 0 | 2016-08-04T11:39:45Z | 38,767,093 | <p>Assign a new column of <code>y</code> values:</p>
<pre><code>b3['x'] = np.arange(len(b3))
</code></pre>
<p>Then plot <code>y</code> versus <code>R2_foret</code>:</p>
<pre><code> b3.plot(x='R2_foret', y='y', style=['o-'])
</code></pre>
<hr>
<p>For example,</p>
<pre><code>import numpy as np
import pandas as pd
i... | 0 | 2016-08-04T12:16:14Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
How to write Python script like shell script for UNIX? | 38,766,357 | <p>I have many loaded shell scripts in UNIX.
I don't know more about shell scripting. But, I know Python programming.
I have to access multiple server using python.
Anyone guide for this?</p>
| -2 | 2016-08-04T11:41:10Z | 38,768,126 | <p>Assuming you have SSH access to the server and want to remotely write the script:</p>
<ol>
<li>Connect the SSH session</li>
<li>You have to install a text editor. <em>nano</em> is a very simple one. To install it on Debian based systems use <code>sudo apt-get install nano</code></li>
<li>Now create a file using <co... | 0 | 2016-08-04T13:02:36Z | [
"python",
"linux",
"shell",
"unix"
] |
Automatically scan RSS feeds and populate WebContent model | 38,766,502 | <p>I am trying to create a Django server application (currently on local host) that will routinely check given RSS feeds provided by the model <code>Blogger</code> (i.e. once every hour), extract data from then provide data for the model <code>WebContent</code>.</p>
<p>So far I have created a data endpoint at <code>ht... | 0 | 2016-08-04T11:47:27Z | 38,805,055 | <p>There seem to be many problems in your code:</p>
<ol>
<li><p>Within the method <code>generate_web_content</code> you are creating a <code>WebContent</code> object by passing the argument <code>user_profile=self</code> while it should be <code>blogger=self</code>.</p></li>
<li><p>In the method <code>_scan_web_conten... | 0 | 2016-08-06T14:00:01Z | [
"python",
"json",
"django",
"rss"
] |
Synax error on db.close() | 38,766,544 | <p>Im trying to use mysqldb in a python script.</p>
<p>Here is a part of the code from the script</p>
<pre><code>cursor = db.cursor()
sql = """INSERT INTO location(`name`, `lat`, `long`, `guid`, `image`, `date`)VALUES(%(name)s, %(lat)s, %(long)s, %(guid)s, %(image)s, %(date)s)"""
try:
cursor.execute... | 0 | 2016-08-04T11:49:10Z | 38,766,582 | <p>You cannot use <code>try</code> without <code>except</code>.</p>
<p>The proper way to ignore all errors is this:</p>
<pre><code>try:
cursor.execute(sql)
db.commit()
except:
pass
db.close()
</code></pre>
| 2 | 2016-08-04T11:51:02Z | [
"python",
"mysql-python"
] |
Synax error on db.close() | 38,766,544 | <p>Im trying to use mysqldb in a python script.</p>
<p>Here is a part of the code from the script</p>
<pre><code>cursor = db.cursor()
sql = """INSERT INTO location(`name`, `lat`, `long`, `guid`, `image`, `date`)VALUES(%(name)s, %(lat)s, %(long)s, %(guid)s, %(image)s, %(date)s)"""
try:
cursor.execute... | 0 | 2016-08-04T11:49:10Z | 38,766,594 | <p>The error is with the try: - it's looking for an except: prior to the db.close.</p>
| 1 | 2016-08-04T11:51:38Z | [
"python",
"mysql-python"
] |
Synax error on db.close() | 38,766,544 | <p>Im trying to use mysqldb in a python script.</p>
<p>Here is a part of the code from the script</p>
<pre><code>cursor = db.cursor()
sql = """INSERT INTO location(`name`, `lat`, `long`, `guid`, `image`, `date`)VALUES(%(name)s, %(lat)s, %(long)s, %(guid)s, %(image)s, %(date)s)"""
try:
cursor.execute... | 0 | 2016-08-04T11:49:10Z | 38,766,707 | <p>You would make everyone live easier if you posted fully working examples.
I added some dummy code to you post to make it run</p>
<pre><code>class fake:
def commit(self,):pass
def execute(self,sql):pass
def close(self,):pass
db =fake()
cursor=fake()
if 1:
sql = """INSERT INTO location(`name`, `lat... | 0 | 2016-08-04T11:57:59Z | [
"python",
"mysql-python"
] |
Synax error on db.close() | 38,766,544 | <p>Im trying to use mysqldb in a python script.</p>
<p>Here is a part of the code from the script</p>
<pre><code>cursor = db.cursor()
sql = """INSERT INTO location(`name`, `lat`, `long`, `guid`, `image`, `date`)VALUES(%(name)s, %(lat)s, %(long)s, %(guid)s, %(image)s, %(date)s)"""
try:
cursor.execute... | 0 | 2016-08-04T11:49:10Z | 38,767,070 | <p>Ignoring the indentation errors in your code, you need to use either an <code>except</code> clause, a <code>finally</code> clause, or both with your <code>try</code> statement.</p>
<p>With a <code>finally</code> clause you can ensure that the db connection is closed:</p>
<pre><code>try:
cursor.execute(sql)
... | 0 | 2016-08-04T12:15:20Z | [
"python",
"mysql-python"
] |
Using a pattern as a dictionary key | 38,766,593 | <p>I'm trying to perform a set of search and replace in a file at once. For that, I'm using a dictionary where the pattern to search is the key, and the replacement text is the key value. I compile all the substitutions in a single pattern and I do the search-replace using the code below:</p>
<pre><code>re_compiled = ... | 2 | 2016-08-04T11:51:38Z | 38,767,914 | <p>You could try something like:</p>
<pre><code>>>> text = r'start C:\work\l10n\. normal data maxwidth="0" something something ></target> end'
>>> # sub_dict format: {'symbolic_group_name': ['pattern', 'replacement']}
...
>>> sub_dict = {'win_path': [r'C:\\work\\l10n\\.', r'/ae/l10n... | 2 | 2016-08-04T12:53:38Z | [
"python",
"dictionary",
"pattern-matching",
"backslash"
] |
python zip cycle over multiple list | 38,766,596 | <p>Say I have these three lists:</p>
<pre><code>aList = [1,2,3,4,5,6]
bList = ['a','b','c','d']
cList = [1,2]
</code></pre>
<p>and I want to iterate over them using zip.</p>
<p>By using cycle with <code>zip</code> as following:</p>
<pre><code>from itertools import cycle
for a,b,c zip(aList, cycle(bList), cycle(cLis... | 3 | 2016-08-04T11:51:40Z | 38,766,697 | <p>You can use <code>itertools.repeat()</code> to repeat the items of third list based on second list:</p>
<pre><code>>>> from itertools import repeat, chain
>>>
>>> zip(aList,cycle(bList), chain.from_iterable(zip(*repeat(cList, len(bList)))))
[(1, 'a', 1),
(2, 'b', 1),
(3, 'c', 1),
(4, ... | 2 | 2016-08-04T11:57:27Z | [
"python",
"numpy",
"zip",
"cycle",
"itertools"
] |
python zip cycle over multiple list | 38,766,596 | <p>Say I have these three lists:</p>
<pre><code>aList = [1,2,3,4,5,6]
bList = ['a','b','c','d']
cList = [1,2]
</code></pre>
<p>and I want to iterate over them using zip.</p>
<p>By using cycle with <code>zip</code> as following:</p>
<pre><code>from itertools import cycle
for a,b,c zip(aList, cycle(bList), cycle(cLis... | 3 | 2016-08-04T11:51:40Z | 38,766,806 | <p>You can apply <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product</code></a> on <code>c</code> and <code>b</code> and then restore their original order in the <code>print</code> statement:</p>
<pre><code>>>> from itertools import product, cycl... | 2 | 2016-08-04T12:02:46Z | [
"python",
"numpy",
"zip",
"cycle",
"itertools"
] |
python progress bar using tqdm not staying on a single line | 38,766,681 | <p>I am trying to run a script that tries to install modules on a centos7 system via puppet management.
I want to implement a progress bar for the installation that happens along while running the script.
I am using tqdm module to do this.
this is a snap of how i have implemented the module:</p>
<pre><code>from tqdm i... | 2 | 2016-08-04T11:56:54Z | 38,895,115 | <p>For the messages to be printed above the progress bar, you need to signal to tqdm that you are printing messages (else tqdm, nor any other progress bar, can not know that you are outputting messages beside the progress bar).</p>
<p>To do that, you can print your messages using <code>tqdm.write(msg)</code> instead o... | 1 | 2016-08-11T11:28:03Z | [
"python",
"progress-bar",
"tqdm"
] |
python progress bar using tqdm not staying on a single line | 38,766,681 | <p>I am trying to run a script that tries to install modules on a centos7 system via puppet management.
I want to implement a progress bar for the installation that happens along while running the script.
I am using tqdm module to do this.
this is a snap of how i have implemented the module:</p>
<pre><code>from tqdm i... | 2 | 2016-08-04T11:56:54Z | 38,895,337 | <p>Try Using :
Progressbar</p>
<pre><code>import Progressbar
progress = progressbar.ProgressBar()
for i in progress(range(30)):
time.sleep(0.1)
</code></pre>
<p>It will look like this:
43% (13 of 30) |############################ | Elapsed Time: 0:00:01 ETA: 0:00:01</p>
| 1 | 2016-08-11T11:39:25Z | [
"python",
"progress-bar",
"tqdm"
] |
How to create a SQLite3 table with column names from a list? | 38,766,859 | <p>I'm storing patients' daily blood pressure data in an SQLite3 table. Each patient corresponds to a row, each date corresponds to a column. How do I initialize this table with the column names being the dates from a Python Pandas series? Perhaps something like:</p>
<pre><code>DATE_LIST = pandas.date_range(start_date... | 0 | 2016-08-04T12:06:05Z | 38,767,351 | <p>You are breaking the 1NF of databases. Consider restructuring the database to follow the normal form. </p>
<p>In simpler terms, each row should be a patients blood pressure at some date. </p>
<pre><code>patient_id | bloodpressure | date
-----------+---------------+-----------
101 | 120/80 | 2016-08-0... | 0 | 2016-08-04T12:27:24Z | [
"python",
"sqlite3"
] |
How to group data by specific time window, where second time is next day | 38,766,871 | <p>I need to calculate sum of some events between 2015-01-01 and 2015-12-31 made every night between 21:30 and 04:30 next day?</p>
<p>How to made it by using Pandas in a most elegant but possible simple and efficient way?</p>
<p>Example results table should look similar to the following:</p>
<pre><code> ... | 1 | 2016-08-04T12:06:57Z | 38,768,291 | <p>You can use:</p>
<pre><code>df = pd.DataFrame({'a':['2015-04-01 15:00','2015-04-01 23:00','2015-04-01 04:00','2015-04-02 03:00','2015-05-02 16:00','2015-04-03 02:00'],
'b':[2,4,3,1,7,10]})
df['a'] = pd.to_datetime(df.a)
</code></pre>
<pre><code>print (df)
a b
0 2015-04-01... | 1 | 2016-08-04T13:09:54Z | [
"python",
"pandas",
"numpy"
] |
How to solve mysql daily analytics that happens when date changes | 38,766,962 | <p>I have two separate programs; one counts the daily view stats and another calculates earning based on the stats.</p>
<p>Counter runs first and followed by Earning Calculator a few seconds later.</p>
<p>Earning Calculator works by getting stats from counter table using <code>date(created_at) > date(now())</code>... | 0 | 2016-08-04T12:10:39Z | 38,770,424 | <p>You have to put a date on your data and instead of using now() use it.</p>
| 0 | 2016-08-04T14:38:14Z | [
"python",
"mysql",
"analytics"
] |
Python-social-auth returns admin user | 38,766,964 | <p>I am trying to setup python-social-auth to authenticate users from Vk. I have a standard setup as written in docs with normal pipeline. The problem is that when user tries to log in:</p>
<pre><code>'social.pipeline.social_auth.social_user',
</code></pre>
<p>always returns admin user. Basically, any user which trie... | 0 | 2016-08-04T12:10:40Z | 38,769,185 | <p>Ok. I have found the answer. The problem was that I had already social auth association between UID and user which was recorded in DB. After removing the wrong association everything was working like a charm. Thanks to all who tried to help! </p>
| 2 | 2016-08-04T13:46:59Z | [
"python",
"django",
"python-social-auth"
] |
How to write multiple try/excepts efficiently | 38,767,148 | <p>I quote often want to try to convert values to int and if they can't be converted, set them to some default value. For example:</p>
<pre><code>try:
a = int(a)
except:
a = "Blank"
try:
b = int(b)
except:
b = "Blank"
try:
c = int(c)
except:
c = "Blank"
</code></pre>
<p>Can this be written mor... | 0 | 2016-08-04T12:19:21Z | 38,767,233 | <p>I'd simply use a function:</p>
<pre><code>def int_with_default(i):
try:
return int(i)
except ValueError:
return "Blank"
a = int_with_default(a)
b = int_with_default(b)
c = int_with_default(c)
</code></pre>
<p>If necessary, you can always add a second argument that tells what the default va... | 4 | 2016-08-04T12:23:11Z | [
"python"
] |
Python TypeError in Numpy polyfit ufunc did not contain loop with matching signature types | 38,767,154 | <p>This has been asked before so apologies for asking again, I have followed the suggested solutions provided in <a href="http://stackoverflow.com/questions/36637428/typeerror-ufunc-subtract-did-not-contain-a-loop-with-signature-matching-types?noredirect=1&lq=1">these</a> <a href="http://stackoverflow.com/questions... | 0 | 2016-08-04T12:19:36Z | 38,767,755 | <p>I solved this (I hope), I created new lists by iterating through each of the vals range and slopes list, turning each of the objects contained in each into floats. I had done that already inside my for loop so I should have just done that earlier.</p>
| 1 | 2016-08-04T12:46:36Z | [
"python",
"numpy"
] |
add a label to a plot with seaborn | 38,767,241 | <p>I did a plot using seaborn,
Here is my pltt <a href="http://i.stack.imgur.com/2pDID.png" rel="nofollow"><img src="http://i.stack.imgur.com/2pDID.png" alt="enter image description here"></a>
I would like to add a label for each line.
Can you help me please?</p>
<pre><code>import numpy as np
import matplotlib.pylab ... | 2 | 2016-08-04T12:23:23Z | 38,768,867 | <p>You can specify the <code>label</code> names to each subplot axis and use <code>plt.legend</code> to add the appropriate legends to the center right corner. </p>
<pre><code>fig = sns.plt.figure(figsize=(12, 5), dpi=100)
ax1 = fig.add_subplot(111)
x1 = pd.to_datetime(df_no_missing.TIMESTAMP)
y1 = df_no_missing.P_ACT... | 0 | 2016-08-04T13:34:18Z | [
"python",
"seaborn"
] |
Django objects.filter with args in loop | 38,767,242 | <p>I search a way to optimize my Django's research function (in python). At this time I have this :</p>
<pre><code>def search(acronym=None, name=None, reference=None):
queryset = Organization.objects
if acronym:
queryset = queryset.filter(acronym=acronym)
if name:
queryset = queryset.filt... | 0 | 2016-08-04T12:23:23Z | 38,767,396 | <p>Use <code>**kwargs</code> in your function definition and filter out <code>None</code> valued items using a <em>dictionary comprehension</em> before passing and <em>unpacking</em> the named arguments to <code>filter</code>:</p>
<pre><code>def search(**kwargs):
kwargs = {k: v for k, v in kwargs.items() if v}
... | 0 | 2016-08-04T12:29:50Z | [
"python",
"django"
] |
Button to add gui element to exisitng one | 38,767,288 | <p>I have a window with some elements such as Label, ButtonBox etc packed in a group from Pmw module. I want to make such button that when clicked, it will extended the window and add another element (for example another Label) in the bottom OR in existing frame. Problem is that when clicked, nothing happens.</p>
<p>H... | 0 | 2016-08-04T12:25:06Z | 38,767,671 | <pre><code>def orig_button_click(self):
protein_info = tk.Label(self.group.interior(), text='something')
protein_info.pack(padx=2, pady=2, expand='yes', fill='y')
protein_info.bind("<Button-1>",self.Label_Click) #Bind the mouse click event. if you need only click label
def Label_Click(self):
#Do s... | 0 | 2016-08-04T12:42:59Z | [
"python",
"user-interface",
"tkinter",
"widget",
"pmw"
] |
Callback to python function from Tkinter Tcl crashes in windows | 38,767,355 | <p>This is not exactly my application, but very similar. I have created this test code to show the problem. Basically I am trying to call tcl proc from python thread. Tcl proc will callback to python function when result is ready. This result will be posted as an event to wx frame. When I run as pure python code, it wo... | 1 | 2016-08-04T12:27:34Z | 38,767,665 | <p>Each Tcl interpreter object (i.e., the context that knows how to run a Tcl procedure) can only be safely used from the OS thread that creates it. This is because Tcl doesn't use a global interpreter lock like Python, and instead makes extensive use of thread-specific data to reduce the number of locks required inter... | 0 | 2016-08-04T12:42:46Z | [
"python",
"tkinter",
"wxpython",
"tcl"
] |
Django not detecting model classes when folder named as Models | 38,767,383 | <p>I splitted models into multiple files and placed them in a folder. Here is the tree structure. Mind the name of folder. It is 'Models' with capital M.</p>
<pre><code>|-- Models
| |-- __init__.py
| |-- PersonModel.py
| `-- VehicleModel.py
</code></pre>
<p>Content of <code>__init__.py</code> file is -</p>
<pr... | 0 | 2016-08-04T12:29:02Z | 38,767,506 | <p>Django doesn't know or care where your views are. You could put them in a folder called "thesearedefinitelynotviews" and it'll still work, as long as you imported them from there.</p>
<p>Models are different. Django needs to be able to find them on startup, so it can do things like set the relationships up correctl... | 3 | 2016-08-04T12:35:52Z | [
"python",
"django"
] |
Iterating on data in two 3D arrays python | 38,767,421 | <p>I'm trying to perform a number of functions to get some results from a set of satellite imagery (in the example case I am performing similarity functions). I first intended to iterate through all the pixels simultaneously, each containing 4 numbers, then calculating a value for each one based off these too numbers ... | 0 | 2016-08-04T12:31:03Z | 38,767,610 | <p>Before investing anymore effort into programming it this way, take a look into the numpy package. It will be many times faster!</p>
<p>About your code: shouldn't your results array also be multidimensional? So in your inner (per row) loop you should be appending to a row, which you then in you outer loop append to ... | 0 | 2016-08-04T12:40:42Z | [
"python",
"arrays",
"for-loop",
"multidimensional-array",
"append"
] |
Iterating on data in two 3D arrays python | 38,767,421 | <p>I'm trying to perform a number of functions to get some results from a set of satellite imagery (in the example case I am performing similarity functions). I first intended to iterate through all the pixels simultaneously, each containing 4 numbers, then calculating a value for each one based off these too numbers ... | 0 | 2016-08-04T12:31:03Z | 38,767,895 | <p>The best way is to use <code>Numpy</code> for your task. You should think in vectors. And you should write your <code>some_function()</code>to work in a vectorized manner. Here is an example:</p>
<pre><code>array_0 = np.random.rand(1000,1000,4)
array_1 = np.random.rand(1000,1000,4)
results = some_function(array_0.... | 0 | 2016-08-04T12:52:51Z | [
"python",
"arrays",
"for-loop",
"multidimensional-array",
"append"
] |
Scikit-Learn- How to add an 'unclassified' category? | 38,767,481 | <p>I am using Scikit-Learn to classify texts (in my case tweets) using LinearSVC. Is there a way to classify texts as unclassified when they are a poor fit with any of the categories defined in the training set? For example if I have categories for sport, politics and cinema and attempt to predict the classification on... | 1 | 2016-08-04T12:34:32Z | 38,788,040 | <p>In the supervised learning approach as it is, you cannot add extra category.</p>
<p>Therefore I would use some heuristics. Try to predict probability for each category. Then, if all 4 or at least 3 probabilities are approximately equal, you can say that the sample is "unknown".
For this approach LinearSVC or other... | 1 | 2016-08-05T11:22:32Z | [
"python",
"scikit-learn",
"text-classification"
] |
Could not save product object to database | 38,767,499 | <p>I get an error while trying to post store, product, category and merchant data. The error is <strong>ValueError at /api/stores/create/
save() prohibited to prevent data loss due to unsaved related object 'product'.</strong></p>
<p><strong>The code</strong></p>
<pre><code>class Store(models.Model):
merchant = m... | 0 | 2016-08-04T12:35:28Z | 38,767,697 | <p>Use object.save(commit=False) thing.
<a href="https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#the-save-method" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#the-save-method</a> this documentation will help it. </p>
| 0 | 2016-08-04T12:44:24Z | [
"python",
"django",
"python-3.x",
"django-rest-framework",
"django-1.9"
] |
Find out result size of unpacked archive without unpacking it. Or stop unpacking when certain size is exceed | 38,767,584 | <p>I need to validate result size of unpacked archive without unpacking it, so that to prevent huge archives to store on my server.
Or start unpacking and when size is exceeded certain size, then stop unpacking.
I have already tried lib <code>pyunpack</code>, but it allows only unpacking archives.
Need to validate suc... | 0 | 2016-08-04T12:39:28Z | 38,768,586 | <p>I can't give you a native python answer, but, if you need to fall back on <code>os.system</code>, the command-line utilities for handling all four formats have switches which can be used to list the contents of the archive including the size of each file and possibly a total size:</p>
<ul>
<li><code>rar</code>: <co... | 0 | 2016-08-04T13:23:00Z | [
"python",
"linux",
"archive",
"7zip",
"rar"
] |
What exactly happens on the computer when multiple requests came to the webserver serving django or pyramid application? | 38,767,616 | <p>I am having a hard time trying to figure out the big picture of the handling of multiple requests by the <code>uwsgi</code> server with <code>django</code> or <code>pyramid</code> application. </p>
<p><strong>My understanding at the moment is this:</strong>
When multiple <em>http requests</em> are sent to <em>uwsg... | 1 | 2016-08-04T12:40:57Z | 38,767,725 | <p>The power and weakness of webservers is that they are in principle stateless. This enables them to be massively parallel. So indeed for each page request a different thread may be spawned. Wether or not this indeed happens depends on the configuration settings of you webserver. There's also a cost to spawning many t... | 2 | 2016-08-04T12:45:31Z | [
"python",
"django",
"multithreading",
"webserver",
"pyramid"
] |
What exactly happens on the computer when multiple requests came to the webserver serving django or pyramid application? | 38,767,616 | <p>I am having a hard time trying to figure out the big picture of the handling of multiple requests by the <code>uwsgi</code> server with <code>django</code> or <code>pyramid</code> application. </p>
<p><strong>My understanding at the moment is this:</strong>
When multiple <em>http requests</em> are sent to <em>uwsg... | 1 | 2016-08-04T12:40:57Z | 38,782,897 | <p>There's no magic in pyramid or django that gets you past process boundaries. The answers depend entirely on the particular server you've selected and the settings you've selected. For example, uwsgi has the ability to run multiple threads and multiple processes. If uwsig spins up multiple processes then they will ea... | 2 | 2016-08-05T06:50:02Z | [
"python",
"django",
"multithreading",
"webserver",
"pyramid"
] |
How can I pack different lists and dicts into a single JSON object in python | 38,767,681 | <p>I have a set of different lists and dictionaries and variables.
Can I pack them all into one JSON object?
How would you go about it?
Call json.dumps() on each of them and then somehow put them together?</p>
<p>(My purpose behind this is to make the data available to my jacascript programm via npm python shell.)</p... | 0 | 2016-08-04T12:43:32Z | 38,767,890 | <p>Just put all your individual lists and dicts into one big dictionary and <code>json.dumps</code> that dictionary. You could use the variable names as keys, or just put them all one after the other in a list.</p>
<pre><code>>>> a_list = [1,2,3]
>>> a_dict = {"foo": 42, "bar": [4,5,6]}
>>> ... | 0 | 2016-08-04T12:52:35Z | [
"python",
"json",
"list",
"dictionary"
] |
Showing dialog in non-main thread | 38,767,706 | <p>I have a non-GUI program that sometimes needs to display a dialog to user.
The problem is that my program runs in an infinite loop and when I show a dialog in this loop the execution of program halts until the dialog is dismissed and this is not wanted because my program loop is a background service that must be res... | 0 | 2016-08-04T12:44:43Z | 38,769,568 | <p>My suggestion is to make your dialog a separate script, and use the subprocess module to display the dialog in a separate process.</p>
| 1 | 2016-08-04T14:02:49Z | [
"python",
"multithreading",
"tkinter",
"modal-dialog"
] |
Issues with displaying time results in Python | 38,767,768 | <p>I have written a code to take in a running pace value (min/km), convert it to speed (km/hr) and then depending on the slope gradient and whether the direction of travel is up or downhill the lost speed is calculated (km/hr). The new running speed is then displayed along with the new running pace and the time your ro... | -1 | 2016-08-04T12:47:02Z | 38,768,402 | <p>You can do this with the built-in function <a href="https://docs.python.org/2/library/functions.html#divmod" rel="nofollow"><code>divmod</code></a>:</p>
<pre><code># Round the AdjustedPace to seconds
AdjustedPace = round(3600/AdjustedSpeed)
minutes, secon... | 0 | 2016-08-04T13:14:51Z | [
"python",
"python-3.x"
] |
Issues with displaying time results in Python | 38,767,768 | <p>I have written a code to take in a running pace value (min/km), convert it to speed (km/hr) and then depending on the slope gradient and whether the direction of travel is up or downhill the lost speed is calculated (km/hr). The new running speed is then displayed along with the new running pace and the time your ro... | -1 | 2016-08-04T12:47:02Z | 38,768,845 | <p>I would do this with <code>timedelta</code> objects from datetime:</p>
<pre><code>import datetime
inp = raw_input('Enter your pace in minutes per km (min:km):')
mins, kms = inp.split(':')
time = datetime.timedelta(minutes=int(mins))
</code></pre>
<p>If you enter 60 minutes, for example, will give you:</p>
<pre><c... | 0 | 2016-08-04T13:33:42Z | [
"python",
"python-3.x"
] |
Pyplot graphing seperate pie charts | 38,767,813 | <p>I want my program to output separate pie charts but when i run it, they end up on top of each other.
Here is the code I'm running: </p>
<pre><code>plt.pie(sizes, labels=labels, autopct = '%1.1f%%', shadow=True, startangle=90)
plt.axis('equal')
plt.suptitle(title)
plt.show()
</code></pre>
<p>However I call thi... | 0 | 2016-08-04T12:48:49Z | 38,768,032 | <p>Can you use subplots? You can add a subplot to the figure by using fig.add_subplot(y,x,n), with y the total plots in the y direction, x the plots in the x direction and n the current plot.</p>
<p>For example, this code:</p>
<pre><code>import matplotlib.pyplot as plt
fig = plt.figure()
# First plot
fig.add_subplo... | 0 | 2016-08-04T12:58:17Z | [
"python",
"matplotlib",
"pie-chart"
] |
Creating a 2D array based upon a CSV | 38,767,866 | <p>I have a CSV file with millions of lines in the format of the below:</p>
<pre><code>start, finish,count;
101,101,10;
101,103,2;
101,104,8;
102,103,5;
</code></pre>
<p>So we have a start location, an end location and a count of the number of people who make that journey.</p>
<p>What I'd like to do is put this into... | 2 | 2016-08-04T12:51:43Z | 38,768,488 | <p>You said you have millions of lines, so i don't know whether this will be effective or not, but if you don't run into memory issues a pandas dataframe is the way to go:</p>
<pre><code>import pandas as pd
df = pd.read_csv('inputfile.csv')
df = df.groupby(['start','finish']).agg({'count':sum}).reset_index()
# Create... | 0 | 2016-08-04T13:18:43Z | [
"python",
"arrays",
"pandas",
"numpy",
"matrix"
] |
Creating a 2D array based upon a CSV | 38,767,866 | <p>I have a CSV file with millions of lines in the format of the below:</p>
<pre><code>start, finish,count;
101,101,10;
101,103,2;
101,104,8;
102,103,5;
</code></pre>
<p>So we have a start location, an end location and a count of the number of people who make that journey.</p>
<p>What I'd like to do is put this into... | 2 | 2016-08-04T12:51:43Z | 38,768,546 | <p>use <code>set_index</code> and <code>unstack</code></p>
<pre><code>df.set_index(['start', 'finish'])['count'].unstack(0)
</code></pre>
<p><a href="http://i.stack.imgur.com/lCPm4.png" rel="nofollow"><img src="http://i.stack.imgur.com/lCPm4.png" alt="enter image description here"></a></p>
<hr>
<p>To save to csv</p... | 2 | 2016-08-04T13:21:08Z | [
"python",
"arrays",
"pandas",
"numpy",
"matrix"
] |
Creating a 2D array based upon a CSV | 38,767,866 | <p>I have a CSV file with millions of lines in the format of the below:</p>
<pre><code>start, finish,count;
101,101,10;
101,103,2;
101,104,8;
102,103,5;
</code></pre>
<p>So we have a start location, an end location and a count of the number of people who make that journey.</p>
<p>What I'd like to do is put this into... | 2 | 2016-08-04T12:51:43Z | 38,769,482 | <p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a>:</p>
<pre><code>print (df.pivot(index='finish', columns='start', values='count'))
start 101 102
finish
101 10.0 NaN
103 2.0 5.0
104 8... | 0 | 2016-08-04T13:58:48Z | [
"python",
"arrays",
"pandas",
"numpy",
"matrix"
] |
Recursion Error: Maximum Recursion depth exceeded | 38,768,052 | <pre><code>from __future__ import print_function
import os, codecs, nltk.stem
english_stemmer = nltk.stem.SnowballStemmer('english')
for root, dirs, files in os.walk("/Users/Documents/corpus/source-document/test1"):
for file in files:
if file.endswith(".txt"):
posts = codecs.open(os... | 0 | 2016-08-04T12:59:34Z | 38,768,326 | <p>Your error is in <code>analyzer = super(StemmedCountVectorizer, self.build_analyzer())</code> here you are calling the function <code>build_analyzer</code> before the super call, which cause a infinite recursive loop. Change it for <code>analyzer = super(StemmedCountVectorizer, self).build_analyzer()</code></p>
| 1 | 2016-08-04T13:11:12Z | [
"python",
"scikit-learn",
"nltk",
"stemming"
] |
Text after <br> dissapears after replacing br tags | 38,768,201 | <p>I'm scraping some data from websites and have encountered a problem using <code>BeautifulSoup</code> (<code>bs4</code>). I need to get text of some elements, separated by anything (comma, space, etc.) that enables me to split the text in order it appears. </p>
<p><code>text</code> attribute of <code>bs4.element.Tag... | 0 | 2016-08-04T13:05:53Z | 38,768,938 | <p>Well, there probably are many ways to do this, but I wanted a clean solution that will work for real-world, possibly horrible html.</p>
<p>If someone comes looking for solution to similar problem, I stumbled upon one neat method, <code>insert</code>, which is exactly what I was looking for.</p>
<pre><code>from bs4... | 0 | 2016-08-04T13:37:16Z | [
"python",
"beautifulsoup",
"bs4"
] |
Python Tkinter Tabs and Canvas | 38,768,385 | <p>Objective:
I am trying to create a GUI with a portion of the screen having "tabs" (information displayed can be changed based on selected tab), and another portion constantly displaying the same thing.</p>
<pre><code>import ttk
import Tkinter
def demo():
#root = tk.Tk()
schedGraphics = Tkinter
root =... | 1 | 2016-08-04T13:14:03Z | 38,771,025 | <ol>
<li><p>To do this, when gridding your notebook, pass the argument <code>column</code> and choose 0, so that it will be located at the far left, like this:</p>
<p><code>nb.grid(column=0)</code></p></li>
<li><p>That's because you have to chose, for your tkinter app, between <code>.grid()</code> and <code>.pack()</c... | 0 | 2016-08-04T15:04:29Z | [
"python",
"tkinter",
"ttk"
] |
Keeping domain of Email but removing TLD | 38,768,446 | <p>I am using python and I want to be able to keep the domain of the email but remove the 'com', or '.co.uk', or 'us', etc</p>
<p>So basically if I have an email, say random@gmail.com. I want to have only @gmail left in string format, but I want to do this for any email. So random@yahoo.com would leave me with @yahoo,... | 2 | 2016-08-04T13:16:49Z | 38,768,602 | <p>If you do</p>
<pre><code>val = string.split('@')[1].split('.')[0]
</code></pre>
<p>Change 'string' for your email string variable name.</p>
<p>This will take everything after the '@' symbol, then everything up to the first '.'</p>
<p>Using on 'random@gmail.com' gives 'gmail'</p>
<p>If you require the '@' symbol... | 2 | 2016-08-04T13:23:35Z | [
"python",
"pandas",
"string-parsing"
] |
Keeping domain of Email but removing TLD | 38,768,446 | <p>I am using python and I want to be able to keep the domain of the email but remove the 'com', or '.co.uk', or 'us', etc</p>
<p>So basically if I have an email, say random@gmail.com. I want to have only @gmail left in string format, but I want to do this for any email. So random@yahoo.com would leave me with @yahoo,... | 2 | 2016-08-04T13:16:49Z | 38,768,651 | <p>First split on "@", take the part after "@". Then split on "." and take the first part</p>
<pre><code>email = "this.that@gmail.com.x.y"
'@' + email.split("@")[1].split(".")[0]
'@gmail'
</code></pre>
| 2 | 2016-08-04T13:25:39Z | [
"python",
"pandas",
"string-parsing"
] |
Keeping domain of Email but removing TLD | 38,768,446 | <p>I am using python and I want to be able to keep the domain of the email but remove the 'com', or '.co.uk', or 'us', etc</p>
<p>So basically if I have an email, say random@gmail.com. I want to have only @gmail left in string format, but I want to do this for any email. So random@yahoo.com would leave me with @yahoo,... | 2 | 2016-08-04T13:16:49Z | 38,768,691 | <p>With pandas <a href="http://pandas.pydata.org/pandas-docs/stable/text.html" rel="nofollow">functions</a> use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>split</code></a>:</p>
<pre><code>df = pd.DataFrame({'a':['random@yahoo.com','random@aol.uk','... | 1 | 2016-08-04T13:27:09Z | [
"python",
"pandas",
"string-parsing"
] |
Keeping domain of Email but removing TLD | 38,768,446 | <p>I am using python and I want to be able to keep the domain of the email but remove the 'com', or '.co.uk', or 'us', etc</p>
<p>So basically if I have an email, say random@gmail.com. I want to have only @gmail left in string format, but I want to do this for any email. So random@yahoo.com would leave me with @yahoo,... | 2 | 2016-08-04T13:16:49Z | 38,772,107 | <p>For posterity and completeness, this can also be done via index and slice:</p>
<pre><code>email = 'random@aol.co.uk'
at = email.index('@')
dot = email.index('.', at)
domain = email[at:dot]
</code></pre>
<p>Using <code>split()</code>and <code>re</code> seems like overkill when the goal is to extract a single sub-st... | 0 | 2016-08-04T15:55:06Z | [
"python",
"pandas",
"string-parsing"
] |
Python: subset of list as equally distributed as possible? | 38,768,474 | <p>I have a range of possible values, for example:</p>
<pre><code>possible_values = range(100)
</code></pre>
<p>I have a list with unsystematic (but unique) numbers within that range, for example:</p>
<pre><code>somelist = [0, 5, 10, 15, 20, 33, 77, 99]
</code></pre>
<p>I want to create a new list of length < le... | 1 | 2016-08-04T13:18:00Z | 38,768,858 | <p>I think you should check <code>random.sample(population, k)</code> function. It samples the population in k-length list. </p>
| -2 | 2016-08-04T13:34:07Z | [
"python",
"list"
] |
Python: subset of list as equally distributed as possible? | 38,768,474 | <p>I have a range of possible values, for example:</p>
<pre><code>possible_values = range(100)
</code></pre>
<p>I have a list with unsystematic (but unique) numbers within that range, for example:</p>
<pre><code>somelist = [0, 5, 10, 15, 20, 33, 77, 99]
</code></pre>
<p>I want to create a new list of length < le... | 1 | 2016-08-04T13:18:00Z | 38,769,267 | <p>Suppose your range is 0..N-1, and you want a list of K<=N-1 values. Then define an "ideal" list of K values, which would be your desired distribution over this full list (which I am frankly not sure I understand what that would be, but hopefully you do). Finally, take the closest matches to those values from yo... | 1 | 2016-08-04T13:51:02Z | [
"python",
"list"
] |
Python: subset of list as equally distributed as possible? | 38,768,474 | <p>I have a range of possible values, for example:</p>
<pre><code>possible_values = range(100)
</code></pre>
<p>I have a list with unsystematic (but unique) numbers within that range, for example:</p>
<pre><code>somelist = [0, 5, 10, 15, 20, 33, 77, 99]
</code></pre>
<p>I want to create a new list of length < le... | 1 | 2016-08-04T13:18:00Z | 38,769,633 | <p>What about the closest values of your subset to certain list's pivots? ie:</p>
<pre><code>def some_function(somelist, length_list, possible_values):
a = min(possible_values)
b = max(possible_values)
chunk_size = (b-a)/(length_list+1)
new_list = []
for i in range(1,length_list+1):
index ... | 1 | 2016-08-04T14:05:01Z | [
"python",
"list"
] |
How to sync data between a Google Sheet and a Mysql DB? | 38,768,475 | <p>So I have a Google sheet that maintains a lot of data. I also have a MySQL DB with a huge junk of data. There is a vital piece of information in the Sheet that is also present in the DB. Both needs to be in sync. The information always enters the Sheet first. I had a python script with mysql queries to update my dat... | -1 | 2016-08-04T13:18:07Z | 38,782,303 | <p>Connect directly to mySQL. You likely missed reading this part <a href="https://developers.google.com/apps-script/guides/jdbc" rel="nofollow">https://developers.google.com/apps-script/guides/jdbc</a></p>
| 1 | 2016-08-05T06:13:04Z | [
"python",
"mysql",
"google-apps-script",
"google-spreadsheet"
] |
AWS Elastic Beanstalk Environment Variables in Python | 38,768,549 | <p>Recently I have been trying to deploy a django webapp to AWS Elastic Beanstalk and everything has been going fine. However part of my app uses that Twitter API so I need to import my API keys. My understanding is that I should use Configuration > Software Configurations > Environment Properties. I set this up inputt... | 2 | 2016-08-04T13:21:12Z | 38,769,596 | <p>The key you are trying to get doesn't exist among your environment variables. Changing the code to -
<code>os.environ.get('TWITTER_ACCESS_TOKEN')</code> or any other key among your env vars should do the trick.</p>
| 0 | 2016-08-04T14:03:56Z | [
"python",
"django",
"amazon-web-services"
] |
How can I create an abstract syntax tree considering '|'? (Ply / Yacc) | 38,768,585 | <p>Considering the following grammar:</p>
<pre><code>expr : expr '+' term | expr '-' term | term
term : term '*' factor | term '/' factor | factor
factor : '(' expr ')' | identifier | number
</code></pre>
<p>This is my code using ply:</p>
<pre><code>from ply import lex, yacc
tokens = [
"identifier",
"number... | 1 | 2016-08-04T13:22:50Z | 38,768,749 | <p>As far as I can see, in <code>p[0] = ("expr", p[1], p[2])</code>, p<a href="https://github.com/dabeaz/ply/blob/master/example/GardenSnake/GardenSnake.py" rel="nofollow">1</a> would be the left hand expression, p[2] would be the operator, and p[3] (that you aren't using) would be the right hand term. </p>
<p>Just us... | 1 | 2016-08-04T13:29:37Z | [
"python",
"abstract-syntax-tree",
"yacc",
"ply"
] |
Installing a package in Conda environment, but only works in Python not iPython? | 38,768,620 | <p>I am using an Ubuntu docker image. I've installed Anaconda on it with no issues. I'm not trying to install tensorflow, using the directions on the tensorflow website:</p>
<pre><code>conda create --name tensorflow python=3.5
source activate tensorflow
<tensorflow> conda install -c conda-forge tensorflow
</code... | 0 | 2016-08-04T13:24:15Z | 38,771,575 | <p>You have to install IPython in the conda environment</p>
<pre><code>source activate tensorflow
conda install ipython
</code></pre>
| 1 | 2016-08-04T15:29:24Z | [
"python",
"docker",
"path",
"tensorflow",
"anaconda"
] |
How to correctly use fminsearch in Python? | 38,768,635 | <p>I'm trying to translate a part of my matlab code in python. Actually I'm looking for how to translate <code>fminsearch</code> and I found it on this website with this example :</p>
<pre><code>import scipy.optimize
banana = lambda x: 100*(x[1]-x[0]**2)**2+(1-x[0])**2
xopt = scipy.optimize.fmin(func=banana, x0=[-1.2... | 1 | 2016-08-04T13:24:45Z | 38,768,841 | <p>Python told you that because in Python, keyword arguments always follow non keyword (i.e positional) arguments (keyword args have a name assigned to them, as in <code>func</code> in the <code>fmin</code> call). Your function call should look like:</p>
<pre><code>Xu = scipy.optimize.fmin(func=banana, x0=X)
</code></... | 0 | 2016-08-04T13:33:26Z | [
"python",
"matlab",
"python-2.7",
"python-3.x"
] |
Find element with certain text using Selenium with Python | 38,768,687 | <p>Currently, I am using this and it works.</p>
<pre><code>self.browser.find_element_by_xpath('//a/h4[text()="item I want"]').click()
</code></pre>
<p>Is there a better way to select by text? I feel like code readability suffers immensely using xpath.</p>
<p>Simple HTML example that can be any number of elements. Th... | 2 | 2016-08-04T13:27:01Z | 38,769,262 | <p>If you want to improve the code readability, you should see to follow a page object pattern.</p>
<p>A first step would be to define the locator in a variable with an explicit name:</p>
<pre class="lang-py prettyprint-override"><code>from selenium.webdriver.common.by import By
</code></pre>
<pre class="lang-py pre... | 3 | 2016-08-04T13:50:55Z | [
"python",
"django",
"selenium",
"testcase"
] |
Find element with certain text using Selenium with Python | 38,768,687 | <p>Currently, I am using this and it works.</p>
<pre><code>self.browser.find_element_by_xpath('//a/h4[text()="item I want"]').click()
</code></pre>
<p>Is there a better way to select by text? I feel like code readability suffers immensely using xpath.</p>
<p>Simple HTML example that can be any number of elements. Th... | 2 | 2016-08-04T13:27:01Z | 38,769,385 | <p>You can try this one</p>
<pre><code>self.browser.find_element_by_link_text('item I want').click()
</code></pre>
| 0 | 2016-08-04T13:55:10Z | [
"python",
"django",
"selenium",
"testcase"
] |
How to append a "label" to a numpy array | 38,768,688 | <p>I have a numpy array created such as:</p>
<pre><code>x = np.array([[1,2,3,4],[5,6,7,8]])
y = np.asarray([x])
</code></pre>
<p>which prints out </p>
<pre><code> x=[[1 2 3 4]
[5 6 7 8]]
y=[[[1 2 3 4]
[5 6 7 8]]]
</code></pre>
<p>What I would like is an array such as </p>
<pre><code>[0 [[1 2 3 4]
[... | 0 | 2016-08-04T13:27:01Z | 38,768,945 | <p>To do what you're asking, just use the phrase</p>
<pre><code>labeledArray = [0, x]
</code></pre>
<p>This way, you will get a standard array with 0 as the first element and a Numpy array as the second element.</p>
<p>However, in practice, you are probably trying to label for the purpose of later recall. In that ca... | 1 | 2016-08-04T13:37:40Z | [
"python",
"numpy"
] |
How to check if the input for date is correct? | 38,768,730 | <pre><code>def date(date):
DD, MM, YYYY=date.split(' ')
return datetime.date(int(YYYY),int(MM),int(DD))
while True:
end=input('End Date (DD MM YYYY): ')
end=date(end)
if end[0:1].isdigit() and end[3:4].isdigit() and end[6:9].isdigit() and datetime.datetime.strptime(end, '%d/%m/%Y'):
brea... | -2 | 2016-08-04T13:29:00Z | 38,976,636 | <p>Not sure on the purpose of the date function, but one potential way of checking the input is:</p>
<pre><code>import datetime
while True:
end = input('End Date (DD MM YYYY): ')
try:
datetime.datetime.strptime(end,'%d %m %Y')
print("Correct")
#date function?
break
except V... | 0 | 2016-08-16T13:45:27Z | [
"python"
] |
View of a view of a numpy array is a copy? | 38,768,815 | <p>If you change a view of a numpy array, the original array is also altered. This is intended behaviour.</p>
<pre><code>arr = np.array([1,2,3])
mask = np.array([True, False, False])
arr[mask] = 0
arr
# Out: array([0, 2, 3])
</code></pre>
<p>However, if I take a view of such a view, and change that, then the original... | 1 | 2016-08-04T13:32:21Z | 38,768,993 | <p>Selection by <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing-and-indexing" rel="nofollow">basic slicing</a> always returns a view. Selection by <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow">advanced
indexing</a> always... | 3 | 2016-08-04T13:39:31Z | [
"python",
"numpy"
] |
Django Foreign Key not recognising primary key in relation | 38,768,825 | <p>I have two models, <code>Article</code> and <code>ArticlePost</code>. <code>ArticlePost</code> references <code>Article</code> as a foreign key and is in a separate application to <code>Article</code>:</p>
<pre><code>====app1/models.py:======
class Article(models.Model):
name = models.CharField(max_length=200... | 0 | 2016-08-04T13:32:38Z | 38,770,725 | <p>Okay so what you tried to do is absolutely correct. But the problem here is with Django.</p>
<p>When you are setting <code>name</code> as <code>primary_key</code> then according to the official documentation -> <a href="https://docs.djangoproject.com/ja/1.9/ref/models/fields/#django.db.models.Field.unique" rel="nof... | 0 | 2016-08-04T14:51:39Z | [
"python",
"django",
"django-models",
"django-postgresql"
] |
Pass Argument to Python Script in Windows Command Prompt | 38,768,920 | <p>I'm trying to pass an argument to python via windows command prompt, but am encountering the following error: </p>
<p><code>[Errno 22] Invalid argument</code></p>
<p><strong>Command Prompt Code:</strong></p>
<p><code>C:\Python27\python.exe "C:\Users\Apples\Documents\ArcGIS\Grapes\Blueberry_Cobbler\recipe.py C:\Us... | -1 | 2016-08-04T13:36:35Z | 38,768,976 | <p>You are missing both a closing and opening <code>"</code>'s:</p>
<pre><code>C:\Python27\python.exe
"C:\Users\Apples\Documents\ArcGIS\Grapes\Blueberry_Cobbler\recipe.py"
"C:\Users\Apples\Documents\ArcGIS\Grapes\Blueberry_Cobbler\input1.txt"
</code></pre>
| 0 | 2016-08-04T13:38:50Z | [
"python",
"windows",
"parameter-passing",
"command-prompt",
"arcpy"
] |
Animated plot with different color for every data point | 38,768,921 | <p>I want to create an animated plot of a timeserie but I want to be able to color every data point differently. While I am running various analysis tasks on the timeserie data I want to color each data point according to the region that it belongs too.</p>
<p>I followed this <a href="http://matplotlib.org/examples/an... | 1 | 2016-08-04T13:36:40Z | 38,770,550 | <p>You can colour points using <code>scatter</code> and provided you're not planning on plotting too many points, simply adding new points each time with different colours may be the way to go. A minimal example based on decay,</p>
<pre><code>import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import ... | 0 | 2016-08-04T14:43:47Z | [
"python",
"animation",
"matplotlib",
"plot"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.