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 |
|---|---|---|---|---|---|---|---|---|---|
Using timer object in python to call a function after certain invertal | 37,765,129 | <p>I have used the following technique to call a function after certain interval. My problem is that it is being called twice at an interval of 5 seconds. That is after every 5 seconds this function is being called twice. How to resolve this? This code is a part of a class.</p>
<pre><code>self.t=Timer(5,self.checkTi... | 0 | 2016-06-11T14:58:53Z | 37,765,858 | <p>This is a timer I wrote a while ago. Try it out with this. For me it works perfectly!</p>
<pre><code>def CountDown(t):
while t:
mins, secs = divmod(t, 60)
#print timeformat
#timeformat = '\r{:02d}:{:02d}'.format(mins, secs)
#sys.stdout.write(timeformat)
#sys.stdout.flush()
time.sleep(1)
... | 0 | 2016-06-11T16:11:38Z | [
"python",
"multithreading"
] |
Present pandas column assignment in one line based on if conditions | 37,765,140 | <p>Continued from <a href="http://stackoverflow.com/questions/37758448/amend-column-values-according-to-timedelta-and-index">separate question</a>, but related code`:</p>
<hr>
<p>I need to change a column of a pandas dataframe, but the solution I found requires a lot of brute force: It lacks versatility by having to ... | 1 | 2016-06-11T15:00:04Z | 37,816,996 | <p>In the line</p>
<p><code>df.loc[idxHS:idxDil0].proc = 'gas soak'</code></p>
<p>you are trying to set values on a slice <code>df.loc[idxHS:idxDil0]</code> of the dataframe <code>df</code>. The problem is that the slice may turn out to be a copy and not a view of <code>df</code>. If you set values on a copy, the ori... | 0 | 2016-06-14T16:02:44Z | [
"python",
"pandas"
] |
Get all tf.Variables related to a specific tensor in TensorFlow | 37,765,153 | <p>I want to create a utility function where I give it a tensor <code>t</code> and a variable name <code>n</code>, and the function returns (it it exists) the <code>variable</code> whos name contains <code>n</code> and is part of the graph of <code>t</code>.</p>
<pre><code>def get_variable(t, n):
#code
return va... | 1 | 2016-06-11T15:01:02Z | 37,765,510 | <p><em>(Warning: I am not going to answer the main question about creating an utility function)</em></p>
<p>The reason the tensors have names like: <code>{name}_{repetition}:0</code> is not because you add again and again these tensors to the <strong>default graph</strong>.</p>
<p>A solution is to always specify the ... | 1 | 2016-06-11T15:37:10Z | [
"python",
"tensorflow"
] |
Darken or lighten a color in matplotlib | 37,765,197 | <p>Say I have a color in Matplotlib. Maybe it's a string (<code>'k'</code>) or an rgb tuple (<code>(0.5, 0.1, 0.8)</code>) or even some hex (<code>#05FA2B</code>). Is there a command / convenience function in Matplotlib that would allow me to darken (or lighten) that color. </p>
<p>I.e. is there <code>matplotlib.py... | 1 | 2016-06-11T15:06:02Z | 37,766,527 | <p>A few months ago I had to solve that problem. The idea was for the user to choose a color (any color) and the software automatically generated a colormap (this was part of a package for scientific purposes).</p>
<p>In any case here is the code that I used to achieve it. You won't need most of what the object does b... | 1 | 2016-06-11T17:18:53Z | [
"python",
"matplotlib",
"colors"
] |
how to fix python iteration for some 2D time dependent diffusion function using implicit schem | 37,765,327 | <p>HI I'm new at this site and I'm looking for an answer for my python code</p>
<p>my code is simply solve groundwater head diffusion (using 2d implicit differentiation). in other words, I'm solving the function as time dependent<br>
with Laplace Equation : d^2h/dx^2+d^2h/dy^2 = ds/dt
where dh is the change of head ov... | 1 | 2016-06-11T15:18:39Z | 37,784,017 | <p>I guess I figured it out what is wrong with my python code</p>
<p>I should let </p>
<pre><code>for k in range(ntm-1):
</code></pre>
<p>instead of </p>
<pre><code> for k in range(1, ntm-1):
</code></pre>
<p>Since python first element in matrix is start with zero , and that where my initial condition head value i... | 0 | 2016-06-13T07:30:47Z | [
"python",
"matlab"
] |
How to structure python project with dot "." or underscore "-" in project/package name? | 37,765,606 | <p><a href="https://www.python.org/dev/peps/pep-0423" rel="nofollow">PEP 423</a> states that project names and package names should be the same and later gives an <a href="https://www.python.org/dev/peps/pep-0423/#use-a-single-name" rel="nofollow">example where the project/package name contains a dot</a>:</p>
<blockqu... | 2 | 2016-06-11T15:46:45Z | 37,771,477 | <p><code>from username import package</code> should work.</p>
<p>Are you sure about your <code>PYTHONPATH</code> ?</p>
<p>You might want to try executing the system commands after <code>PYTHONPATH=.</code> ? This is because you perhaps haven't set <code>PYTHONPATH</code> to include the directory which contains <code>... | 0 | 2016-06-12T06:45:08Z | [
"python",
"packages",
"pep"
] |
How to structure python project with dot "." or underscore "-" in project/package name? | 37,765,606 | <p><a href="https://www.python.org/dev/peps/pep-0423" rel="nofollow">PEP 423</a> states that project names and package names should be the same and later gives an <a href="https://www.python.org/dev/peps/pep-0423/#use-a-single-name" rel="nofollow">example where the project/package name contains a dot</a>:</p>
<blockqu... | 2 | 2016-06-11T15:46:45Z | 37,777,113 | <p><a href="https://www.python.org/dev/peps/pep-0423/#pep-deferral" rel="nofollow">PEP 423 is deferred</a>, so I ended doing to equivalent of <code>pyramid</code> rather than <code>kheops.pyramid</code> via standard python packaging. <a href="https://github.com/pcattori/namespaces" rel="nofollow">Here is the package</a... | 0 | 2016-06-12T17:29:52Z | [
"python",
"packages",
"pep"
] |
int object is not iterable python | 37,765,642 | <p>I am trying to learn python reduce function. </p>
<p>This is some code that does not make sense to me</p>
<pre><code>>>> x = [1,2,3]
>>> reduce(sum, [b for b in x if b > 0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iter... | 0 | 2016-06-11T15:50:26Z | 37,765,688 | <p>In the second case the list you created with list comprehension has only one element, so it is not reduced. This reduction doesn't fail, because there is nothing to be reduced there, so function sum isn't executed and it doesn't fail. The result is the only integer, that has been there before.<br>
The function sum i... | 2 | 2016-06-11T15:55:32Z | [
"python",
"reduce"
] |
int object is not iterable python | 37,765,642 | <p>I am trying to learn python reduce function. </p>
<p>This is some code that does not make sense to me</p>
<pre><code>>>> x = [1,2,3]
>>> reduce(sum, [b for b in x if b > 0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iter... | 0 | 2016-06-11T15:50:26Z | 37,765,834 | <p>From the <a href="https://docs.python.org/2/library/functions.html#reduce" rel="nofollow">docs</a> about <code>reduce</code>:</p>
<blockquote>
<p>Apply function of <strong>two</strong> arguments cumulatively to the items of iterable,
from left to right, so as to reduce the iterable to a single value</p>
</block... | 2 | 2016-06-11T16:09:33Z | [
"python",
"reduce"
] |
int object is not iterable python | 37,765,642 | <p>I am trying to learn python reduce function. </p>
<p>This is some code that does not make sense to me</p>
<pre><code>>>> x = [1,2,3]
>>> reduce(sum, [b for b in x if b > 0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iter... | 0 | 2016-06-11T15:50:26Z | 37,765,848 | <p>The <a href="https://docs.python.org/2/library/functions.html#reduce" rel="nofollow"><code>reduce</code></a> function takes in a function and an iterable.<br>
It then maps each element of that iterable to the function.</p>
<hr>
<p>What your first <code>b > 0</code> function is doing is trying to run <a href="ht... | 1 | 2016-06-11T16:10:53Z | [
"python",
"reduce"
] |
int object is not iterable python | 37,765,642 | <p>I am trying to learn python reduce function. </p>
<p>This is some code that does not make sense to me</p>
<pre><code>>>> x = [1,2,3]
>>> reduce(sum, [b for b in x if b > 0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iter... | 0 | 2016-06-11T15:50:26Z | 37,765,902 | <p>Input in second code snippet is single element list - it's a degenerated case where callable isn't even called.</p>
<p>Consider following example:</p>
<pre><code>def my_sum(*args):
print "my_sum called with", args
return sum(*args)
x = [1, 2, 3]
reduce(my_sum, [b for b in x if b > 2])
# nothing gets p... | 2 | 2016-06-11T16:16:14Z | [
"python",
"reduce"
] |
int object is not iterable python | 37,765,642 | <p>I am trying to learn python reduce function. </p>
<p>This is some code that does not make sense to me</p>
<pre><code>>>> x = [1,2,3]
>>> reduce(sum, [b for b in x if b > 0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iter... | 0 | 2016-06-11T15:50:26Z | 37,765,983 | <p>As Moses points out "sum consumes the iterable in the first iteration"
so let's play with it </p>
<pre><code>>>> sum(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> sum([1,2])
3
>>> sum(x)
6
>>... | 1 | 2016-06-11T16:23:17Z | [
"python",
"reduce"
] |
Invalid literal for float() in Pandas | 37,765,713 | <p>I am working on a dataset with more than 60M rows in Pandas. In one of my numeric columns, I suspect that there is a non-numeric char which gives me the error message "invalid literal for float(): 4010146209+".</p>
<p>I am able to load the column as obj but not as float or int.</p>
<p>I have tried replacing r"\d" ... | 2 | 2016-06-11T15:57:37Z | 37,765,835 | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>.replace()</code></a> with a <a href="https://docs.python.org/2/howto/regex.html" rel="nofollow">regular expression</a> to keep the numeric values rather than converting to <code>np.nan</c... | 0 | 2016-06-11T16:09:49Z | [
"python",
"python-2.7",
"pandas"
] |
Invalid literal for float() in Pandas | 37,765,713 | <p>I am working on a dataset with more than 60M rows in Pandas. In one of my numeric columns, I suspect that there is a non-numeric char which gives me the error message "invalid literal for float(): 4010146209+".</p>
<p>I am able to load the column as obj but not as float or int.</p>
<p>I have tried replacing r"\d" ... | 2 | 2016-06-11T15:57:37Z | 37,766,109 | <p>i would use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_numeric.html" rel="nofollow">to_numeric()</a> function for that</p>
<p>demo</p>
<pre><code>In [583]: a
Out[583]:
0 50.5
1 50.7
2 50.9
3 ... | 0 | 2016-06-11T16:35:01Z | [
"python",
"python-2.7",
"pandas"
] |
Index with an unknown number of indices | 37,765,724 | <p>I have one numpy array with a N dimensions where N can vary:</p>
<pre><code>arr1 = np.array([0,0,1,0])
arr2 = np.array([[0,0],[0,0],[0,1],[0,0]])
</code></pre>
<p>I need to be able to pass an array and tuple/int and get the integer in that location returned:</p>
<pre><code>assert myfunc(arr1, 2) == 1
assert myfun... | 0 | 2016-06-11T15:58:49Z | 37,765,870 | <p>I'm not sure I understood your question correctly; but, you can directly use tuple as an index to retrieve the specific elements.</p>
<p>For instance;</p>
<pre><code>arr1 = np.array([0,0,1,0])
arr2 = np.array([[0,0],[0,0],[0,1],[0,0]])
arr3 = np.array([[[0,0],[0,0],[0,1],[0,0]], [[0,0],[0,0],[0,1],[0,0]]])
assert... | 3 | 2016-06-11T16:13:14Z | [
"python",
"arrays",
"numpy"
] |
move axes text in matplotlib | 37,765,738 | <p>I'm trying to move axes labels in matplotlib. I thought this would work but it doesn't:</p>
<pre><code>import matplotlib.pyplot as plt
plt.figure(0)
xlbl = plt.xlabel("foo")
pos = xlbl.get_position()
pos = (pos[0], pos[1] + 1)
xlbl.set_position(pos)
plt.draw()
</code></pre>
<p>However, this does work (moving in x ... | 1 | 2016-06-11T16:00:08Z | 37,769,185 | <p>Try to use <code>set_label_coords</code>:</p>
<pre><code>import matplotlib.pyplot as plt
plt.figure(0)
xlbl = plt.xlabel("foo")
pos = xlbl.get_position()
pos = (pos[0]+0.3, pos[1]+0.5)
ax = plt.gca()
ax.xaxis.set_label_coords(pos[0], pos[1])
plt.draw()
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/... | 1 | 2016-06-11T22:54:49Z | [
"python",
"matplotlib"
] |
Encoding/Decoding Unicode and Writing CSV | 37,765,754 | <p>I am trying to write words of non-latin based languages to a CSV and cannot get the words to be written in their proper form.</p>
<pre><code>foreign='а Ñакже'
with open('C:\\Users\\Lance\\Desktop\\Programs\\Database Builder\\Russian Test.csv', 'wb') as outfile:
outfile.write((foreign).encode('utf-8'))
</c... | 0 | 2016-06-11T16:01:47Z | 37,767,162 | <p>It writes the file correctly but you are probably displaying the file using an editor or console that is using <code>Windows-1252</code> encoding.</p>
<p>Example from US Windows cmd.exe console:</p>
<pre><code>C:\>type "Russian Test.csv"
â¨â â¤Ã©â¨ââ¨ââ¨â¢â¨â¡
C:\>chcp 1252
Active code page: 12... | 3 | 2016-06-11T18:23:17Z | [
"python",
"csv",
"unicode"
] |
Encoding/Decoding Unicode and Writing CSV | 37,765,754 | <p>I am trying to write words of non-latin based languages to a CSV and cannot get the words to be written in their proper form.</p>
<pre><code>foreign='а Ñакже'
with open('C:\\Users\\Lance\\Desktop\\Programs\\Database Builder\\Russian Test.csv', 'wb') as outfile:
outfile.write((foreign).encode('utf-8'))
</c... | 0 | 2016-06-11T16:01:47Z | 37,772,460 | <p>firstly, writing data into csv file depends on csv library, the correct script should be:</p>
<pre><code>import csv
with open('path/to/test.csv', 'wb') as f:
writer = csv.writer(f)
for line in <your_data>:
writer.writerow(line)
</code></pre>
<p>secondly, as csv library does not support unicode... | -1 | 2016-06-12T09:01:53Z | [
"python",
"csv",
"unicode"
] |
How list indices work in python | 37,765,789 | <p>I'm trying to understand how lists and indices work in python</p>
<p>so I tried this code to print every item in a list and its corresponding index in the list</p>
<pre><code>tokens = ["and", "of", "then", "and", "for", "and"]
for word in tokens:
word_index = tokens.index(word)
print(word_index, word)
</co... | 0 | 2016-06-11T16:05:10Z | 37,765,797 | <blockquote>
<p>My question is why "and" here have the same index of 0 instead of 0, 3, 5?</p>
</blockquote>
<p><strong>Why</strong></p>
<p>It's because <a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow"><code>list.index()</code></a> returns the index of the first occurrence, so since "... | 3 | 2016-06-11T16:06:32Z | [
"python",
"python-3.x"
] |
How list indices work in python | 37,765,789 | <p>I'm trying to understand how lists and indices work in python</p>
<p>so I tried this code to print every item in a list and its corresponding index in the list</p>
<pre><code>tokens = ["and", "of", "then", "and", "for", "and"]
for word in tokens:
word_index = tokens.index(word)
print(word_index, word)
</co... | 0 | 2016-06-11T16:05:10Z | 37,765,803 | <p>Use <code>enumerate</code>. </p>
<pre><code>In [1]: tokens = ["and", "of", "then", "and", "for", "and"]
In [2]: for word_index,word in enumerate(tokens):
....: print (word_index, word)
....:
</code></pre>
<p><strong>Output</strong> </p>
<pre><code>0 and
1 of
2 then
3 and
4 for
5 and
</code></pre>
| 1 | 2016-06-11T16:07:00Z | [
"python",
"python-3.x"
] |
How list indices work in python | 37,765,789 | <p>I'm trying to understand how lists and indices work in python</p>
<p>so I tried this code to print every item in a list and its corresponding index in the list</p>
<pre><code>tokens = ["and", "of", "then", "and", "for", "and"]
for word in tokens:
word_index = tokens.index(word)
print(word_index, word)
</co... | 0 | 2016-06-11T16:05:10Z | 37,765,815 | <p>From the <a href="http://docs.python.org/3/tutorial/datastructures.html" rel="nofollow">Python documentation</a>, <code>index</code> returns the index of the first occurrence of the element in the list:</p>
<blockquote>
<p><code>list.index(x)</code></p>
<p>Return the index in the list of the first item whose... | 0 | 2016-06-11T16:07:48Z | [
"python",
"python-3.x"
] |
Exporting text files to PostgreSQL using Spark - Automation | 37,765,809 | <p>I'm trying export text files to Postgres database using Spark. I am using below piece of code to export individual text files. I have close to 200 text files in the same folder and every text file has same structure. Unfortunately year value is not part of my input file hence I'm hard coding it. </p>
<p>I wish to u... | 3 | 2016-06-11T16:07:31Z | 37,766,155 | <p>Lets assume your data looks like this:</p>
<pre><code>import csv
import tempfile
import os
out = tempfile.mkdtemp()
data = [
("1870", [("Jane Doe", "F", 3)]),
("1890", [("John Doe", "M", 1)]),
]
for year, rows in data:
with open(os.path.join(out, "t-{0}.txt".format(year)), "w") as fw:
csv.wr... | 2 | 2016-06-11T16:39:44Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-sql"
] |
How to implement __delitem__ method? | 37,765,829 | <p>I would like to know the best way to go about fixing the <strong>delitem</strong> method body to improve efficiency, I'm getting an error that won't exit the loop.</p>
<pre><code> def __delitem__(self, idx):
"""Implements `del self[idx]`"""
nidx = self._normalize_idx(idx)
currNode = self.... | 2 | 2016-06-11T16:09:02Z | 37,765,930 | <p>I'd recommend to remove the line</p>
<pre><code>del self[self.length-1]
</code></pre>
<p>You should be able to leave this up to the garbage collector since this element should not be referenced anywhere else, as far as I can tell. It would then get deleted automatically.</p>
<p>Otherwise you'd call <code>__delite... | 1 | 2016-06-11T16:18:31Z | [
"python",
"performance",
"doubly-linked-list"
] |
Send JSON Object through Zmq with C++ Client - Python Server | 37,765,847 | <p>i'm trying to exchange a Json object through a c++ client and a python server using zeromq.</p>
<p>server.py</p>
<pre><code> import zmq
import json
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5555")
while True:
json_str = socket.recv_json()
data_print = json.loads... | 0 | 2016-06-11T16:10:51Z | 37,765,929 | <p>You are trying to convert the json string to a python object twice. Both the following lines return objects, not strings.</p>
<pre><code>json_str = socket.recv_json()
data_print = json.loads(json_str)
</code></pre>
<p>Either receive the data with <code>socket.recv_json()</code> and remove the line after it, or rec... | 0 | 2016-06-11T16:18:25Z | [
"python",
"c++",
"json",
"zeromq"
] |
Cython - how to properly call operator with references | 37,765,864 | <p>I have the following code in my Cython wrapper to a C++ code:</p>
<pre><code># distutils: language = c++
# distutils: sources = symbolic.cpp
from libcpp.vector cimport vector
from libcpp.pair cimport pair
from libcpp.string cimport string
from libcpp cimport bool
cdef extern from "symbolic.h" namespace "metadiff::... | 0 | 2016-06-11T16:12:12Z | 37,819,862 | <p>You have a number of issues:</p>
<ol>
<li><p>You can't return C++ objects directly to Python - you need to return your wrapper type (assign to <code>thisptr</code> of the wrapper)</p></li>
<li><p>You can't guarantee either <code>self</code> or <code>other</code> is of the correct type at the point the function is c... | 1 | 2016-06-14T18:46:46Z | [
"python",
"c++",
"cython"
] |
Django form instance not showing default value when using angularJs | 37,765,904 | <p><strong>In views.py</strong></p>
<pre><code>def demo(request,EID):
instance = Employee.objects.get(EID=EID)
form = Update(instance=instance)
return render(request, 'files/demo.html', {'form': form, })
</code></pre>
<p><strong>In Forms.py</strong></p>
<pre><code>class Update(forms.ModelForm):
Name = form... | 1 | 2016-06-11T16:16:18Z | 37,771,207 | <p>with <code>ng-model</code> you can not set default like this. You need to use <code>ng-init</code>. You can do something like this:</p>
<pre><code>// HTML
<div ng-init=init({{ dict_from_django_view }})>
// your form here
</div>
// in angular controller
$scope.init = function(data){
// set form... | 0 | 2016-06-12T06:04:25Z | [
"javascript",
"python",
"angularjs",
"django"
] |
Adding multiple ndarry using numpy | 37,766,012 | <p>I am quite new to python numpy.</p>
<p>If i do have a list of numpy vectors. What is the best way to ensure computation is fast. </p>
<p>I am currently doing this which i find it to be too slow.</p>
<pre><code>vec = sum(list of numpy vectors) # 4 vectors of 500 dimensions each
</code></pre>
<p>It does take up qu... | 2 | 2016-06-11T16:25:37Z | 37,766,385 | <p>In my opinion this is already the fastest variant. It is pure <code>numpy</code> and as such computed within <code>C</code>-code.</p>
<p>Alternatives could be to compute the sums of each vector individually and then sum the values of the list or to stack all vectors and then sum up. But both are slower: </p>
<p... | 1 | 2016-06-11T17:05:23Z | [
"python",
"numpy",
"vector"
] |
Adding multiple ndarry using numpy | 37,766,012 | <p>I am quite new to python numpy.</p>
<p>If i do have a list of numpy vectors. What is the best way to ensure computation is fast. </p>
<p>I am currently doing this which i find it to be too slow.</p>
<pre><code>vec = sum(list of numpy vectors) # 4 vectors of 500 dimensions each
</code></pre>
<p>It does take up qu... | 2 | 2016-06-11T16:25:37Z | 37,766,390 | <p>Is this what you are trying to do (but with much larger arrays)?</p>
<pre><code>In [193]: sum([np.ones((2,3)),np.arange(6).reshape(2,3)])
Out[193]:
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
</code></pre>
<p><code>500 dimensions each</code> is an unclear description. Do you mean an array with shape <code>(... | 2 | 2016-06-11T17:05:43Z | [
"python",
"numpy",
"vector"
] |
How to create a datetimefiled that keeps the last edited time in django | 37,766,018 | <p>I'm toying around in <code>django</code> trying to understand its philosophy, and I tried to create a last modified entry. I place this in my code:</p>
<pre><code>slide_title = models.CharField(max_length=200)
last_date = models.DateTimeField('last modified',auto_now=True)
def __str__(self):
out = 'title: {}\n ... | 0 | 2016-06-11T16:25:56Z | 37,766,086 | <p>You did an <code>auto_now=True</code>. But that works only when <code>Model.save()</code> method is called. To populate the <code>DateTimeField</code> at the time of creation, you need to add another attribute <code>auto_now_add=True</code>.</p>
<p><a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#d... | 1 | 2016-06-11T16:32:33Z | [
"python",
"django"
] |
Performing calculations on some values in a dictionary based on their keys (Python) | 37,766,020 | <p>Looking to gain some understanding on handling dictionaries efficiently in Python.</p>
<p>I have a dictionary</p>
<pre><code>dict = {'a': 11, 'b': 4, 'c': 7, 'd': 12, 'e': 5}
</code></pre>
<p>and I would like to <strong>perform calculations only on a subset of its values</strong>. Which values to be considered in... | 0 | 2016-06-11T16:26:04Z | 37,766,067 | <p>You can implement the given example with <a href="https://docs.python.org/3.5/library/functions.html#sum" rel="nofollow"><code>sum</code></a> and <a href="https://docs.python.org/3.5/reference/expressions.html#generator-expressions" rel="nofollow">generator expression</a> that returns <code>dict</code> values based ... | 3 | 2016-06-11T16:30:58Z | [
"python",
"python-3.x",
"dictionary"
] |
Adding multiple user inputs to a dictionary and writing them to csv, python tkinter | 37,766,024 | <p>First post on here! I am currently learning python mainly with tkinter to make a GUI that will accept user inputs and save them to a csv.</p>
<p>I have it taking and saving user inputs but i think it would be more benifical to save all the inputs to a dictionary and then call the whole dictionary to be saved to csv... | 0 | 2016-06-11T16:26:31Z | 37,766,153 | <p>You will need separate the submission and write processes into their own functions. I would suggest creating an array that you append dictionaries to. For example</p>
<pre><code>self.data = [
{'name': 'John', 'age':23},
{'name': 'Sally', 'age':26},
]
</code></pre>
<p>Then when it comes time to write your d... | 0 | 2016-06-11T16:39:24Z | [
"python",
"python-3.x",
"csv",
"dictionary",
"tkinter"
] |
"ValueError: labels ['timestamp'] not contained in axis" error | 37,766,030 | <p>I have this code ,i want to remove the column 'timestamp' from the file :<a href="https://www.dropbox.com/s/4cksq4dwgbaqd07/u.data?dl=0" rel="nofollow">u.data</a> but can't.It shows the error<br>
"ValueError: labels ['timestamp'] not contained in axis"
How can i correct it</p>
<pre><code>import numpy as np
import p... | 1 | 2016-06-11T16:27:26Z | 37,766,163 | <blockquote>
<p>"ValueError: labels ['timestamp'] not contained in axis"</p>
</blockquote>
<p>You don't have headers in the file, so the way you loaded it you got a <code>df</code> where the column names are the first rows of the data. You tried to access colunm <code>timestamp</code> which doesn't exist.</p>
<p><s... | 1 | 2016-06-11T16:41:09Z | [
"python",
"pandas",
"machine-learning",
"recommendation-engine",
"data-science"
] |
"ValueError: labels ['timestamp'] not contained in axis" error | 37,766,030 | <p>I have this code ,i want to remove the column 'timestamp' from the file :<a href="https://www.dropbox.com/s/4cksq4dwgbaqd07/u.data?dl=0" rel="nofollow">u.data</a> but can't.It shows the error<br>
"ValueError: labels ['timestamp'] not contained in axis"
How can i correct it</p>
<pre><code>import numpy as np
import p... | 1 | 2016-06-11T16:27:26Z | 37,766,253 | <p>i would do it this way:</p>
<pre><code>data = pd.read_table('u.data', header=None,
names=['userID', 'itemID','rating', 'timestamp'],
usecols=['userID', 'itemID','rating']
)
</code></pre>
<p>Check:</p>
<pre><code>In [589]: data.head()
Out[589]:
userID itemID rating
0 ... | 0 | 2016-06-11T16:50:24Z | [
"python",
"pandas",
"machine-learning",
"recommendation-engine",
"data-science"
] |
"ValueError: labels ['timestamp'] not contained in axis" error | 37,766,030 | <p>I have this code ,i want to remove the column 'timestamp' from the file :<a href="https://www.dropbox.com/s/4cksq4dwgbaqd07/u.data?dl=0" rel="nofollow">u.data</a> but can't.It shows the error<br>
"ValueError: labels ['timestamp'] not contained in axis"
How can i correct it</p>
<pre><code>import numpy as np
import p... | 1 | 2016-06-11T16:27:26Z | 37,766,362 | <p>One of the biggest problem that one faces and that undergoes unnoticed is that in the u.data file while inserting headers the separation should be exactly the same as the separation between a row of data. For example if a tab is used to separate a tuple then you should not use spaces.<br><br> In your u.data file add... | 1 | 2016-06-11T17:03:26Z | [
"python",
"pandas",
"machine-learning",
"recommendation-engine",
"data-science"
] |
3-d Rectangles in Matplotlib | 37,766,034 | <p>I have this dataset</p>
<pre><code>500295 152342 25286
500295 157981 24120.6
500295 163619 15469.8
500295 169258 18071.8
500295 174897 25624.7
500295 180536 30323.5
500295 186174 8828.7
500295 191813 4681.19
500295 197452 7470.08
500295 203090 29070.4
506851 152342 2181.82
506851 157981 1809... | 1 | 2016-06-11T16:27:45Z | 37,766,405 | <p>You can use <a href="http://matplotlib.org/mpl_toolkits/mplot3d/api.html#mpl_toolkits.mplot3d.axes3d.Axes3D.bar3d" rel="nofollow">bar3D</a> for that. Using your provided data:</p>
<pre><code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
xsize = 1000
ysize = 4000
data = ... | 2 | 2016-06-11T17:06:44Z | [
"python",
"matplotlib",
"plot",
"3d"
] |
Openpyxl: can't seem to get the syntax right for what I'm trying to do (read next cell down) | 37,766,047 | <p>Here's the code I have. I'm simply trying to open a spreadsheet (which currently only has information in the first column), and read the first cell, print the information, then later along the lines loop back up to the top and read the next cell down. What am I doing wrong?</p>
<pre><code>import openpyxl
wb = open... | 1 | 2016-06-11T16:29:00Z | 37,766,696 | <p>You could use the <a href="http://openpyxl.readthedocs.io/en/latest/api/openpyxl.cell.interface.html?highlight=offset" rel="nofollow">cell.offset()</a> method.</p>
| 1 | 2016-06-11T17:35:03Z | [
"python",
"excel",
"openpyxl"
] |
Submiting Javascript Form and Scrap with Python | 37,766,107 | <p>I have the following HTML/Javascript code in a website. It basically represents a website with two fields: a) name="N": Field were you mark the "V" letter; b) name="ID" were you input a number with max 8 characters.</p>
<pre><code><tr>
<td>
<form name="form" method="post" action="javascri... | 1 | 2016-06-11T16:34:48Z | 37,766,254 | <p>It is a simple get request, passing two params:</p>
<p><a href="http://i.stack.imgur.com/q4HIf.png" rel="nofollow"><img src="http://i.stack.imgur.com/q4HIf.png" alt="enter image description here"></a></p>
<p>So with requests:</p>
<pre><code>url = "http://www.cne.gob.ve/web/registro_electoral/firmantes.php"
param... | 1 | 2016-06-11T16:50:29Z | [
"javascript",
"python",
"web-scraping",
"urllib"
] |
Spark Matrix multiplication with python | 37,766,213 | <p>I am trying to do matrix multiplication using Apache Spark and Python.</p>
<p>Here is my data</p>
<pre><code>from pyspark.mllib.linalg.distributed import RowMatrix
</code></pre>
<p>My RDD of vectors</p>
<pre><code>rows_1 = sc.parallelize([[1, 2], [4, 5], [7, 8]])
rows_2 = sc.parallelize([[1, 2], [4, 5]])
</code>... | 2 | 2016-06-11T16:46:23Z | 37,766,853 | <p>You cannot. Since <code>RowMatrix</code> has no meaningful row indices it cannot be used for multiplications. Even ignoring that the only distributed matrix <a href="https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.linalg.distributed.BlockMatrix.multiply" rel="nofollow">which supports... | 3 | 2016-06-11T17:51:33Z | [
"python",
"matrix",
"apache-spark",
"multiplication",
"apache-spark-mllib"
] |
Spark Matrix multiplication with python | 37,766,213 | <p>I am trying to do matrix multiplication using Apache Spark and Python.</p>
<p>Here is my data</p>
<pre><code>from pyspark.mllib.linalg.distributed import RowMatrix
</code></pre>
<p>My RDD of vectors</p>
<pre><code>rows_1 = sc.parallelize([[1, 2], [4, 5], [7, 8]])
rows_2 = sc.parallelize([[1, 2], [4, 5]])
</code>... | 2 | 2016-06-11T16:46:23Z | 37,808,956 | <p>I wrote a function to process the matrix multiplication but I'm afraid to have a long processing time. Here is my function: </p>
<pre><code>def matrix_multiply(df1, df2):
nb_row = df1.count()
mat=[]
for i in range(0, nb_row):
row=list(df1.filter(df1['index... | 0 | 2016-06-14T10:05:25Z | [
"python",
"matrix",
"apache-spark",
"multiplication",
"apache-spark-mllib"
] |
Bokeh - adding a tooltip to patches | 37,766,263 | <p>I am new to bokeh, and try to make a simple map.</p>
<p>From this page <a href="http://www.abisen.com/blog/bokeh-maps/" rel="nofollow">http://www.abisen.com/blog/bokeh-maps/</a> it was quite simple to make a map.
But personnalizing it needs deeper understanding of bokeh.
I would like to display the name of each tow... | 0 | 2016-06-11T16:51:36Z | 37,773,272 | <p>I had a wrong data structure in my "data" dict. </p>
<p>I had to create an array of value for each city in the departement, with the same length, and attach it to the departement : </p>
<pre><code>for new_col in ["surf", "pop", "fam", "villes", "dpt", "cp", "perimetre"]:
gliph_.data_source.add(data[dep... | 1 | 2016-06-12T10:37:55Z | [
"python",
"bokeh"
] |
pandas to_datetime parsing wrong year | 37,766,353 | <p>I'm coming across something that is almost certainly a stupid mistake on my part, but I can't seem to figure out what's going on. </p>
<p>Essentially, I have a series of dates as strings in the format <code>"%d-%b-%y"</code>, such as <code>26-Sep-05</code>. When I go to convert them to datetime, the year is sometim... | 0 | 2016-06-11T17:02:37Z | 37,766,686 | <p>That seems to be the behavior of the Python library datetime, I did a test to see where the cutoff is 68 - 69:</p>
<pre><code>datetime.datetime.strptime('31-Dec-68', '%d-%b-%y').date()
>>> datetime.date(2068, 12, 31)
datetime.datetime.strptime('1-Jan-69', '%d-%b-%y').date()
>>> datetime.date(1969... | 2 | 2016-06-11T17:34:09Z | [
"python",
"datetime",
"pandas"
] |
pandas to_datetime parsing wrong year | 37,766,353 | <p>I'm coming across something that is almost certainly a stupid mistake on my part, but I can't seem to figure out what's going on. </p>
<p>Essentially, I have a series of dates as strings in the format <code>"%d-%b-%y"</code>, such as <code>26-Sep-05</code>. When I go to convert them to datetime, the year is sometim... | 0 | 2016-06-11T17:02:37Z | 37,767,723 | <p>from the <a href="https://docs.python.org/3/library/time.html" rel="nofollow">docs</a></p>
<blockquote>
<p><strong>Year 2000 (Y2K) issues:</strong> Python depends on the platformâs C library,
which generally doesnât have year 2000 issues, since all dates and
times are represented internally as seconds sin... | 1 | 2016-06-11T19:26:31Z | [
"python",
"datetime",
"pandas"
] |
Sorting Files and Folders using month | 37,766,392 | <p>I'm looking for a code that moves all the Folders in a directory with the specified year.</p>
<p>For example : I have monthly issues of books of several years in a directory with corresponding month name on them. i.e., "June-2015" folder will contain the June 2015 Issue of the book. All I need is a program that mov... | -1 | 2016-06-11T17:05:54Z | 37,766,597 | <p>Try a package like <a href="https://docs.python.org/2/library/os.html" rel="nofollow"><code>os</code></a> or <a href="https://docs.python.org/2/library/shutil.html" rel="nofollow"><code>shutil</code></a></p>
| 0 | 2016-06-11T17:25:51Z | [
"python",
"automation",
"folder"
] |
fixture 'httpbin' not found | 37,766,474 | <p>I start reading python <code>requests</code> library.<br>
The first thing I do is run pytest locally.</p>
<p>Then I got this error message: </p>
<pre><code> @pytest.fixture
def httpbin(httpbin):
fixture 'httpbin' not found
available fixtures: tmpdir_factory, httpbin_secure, pytestconfig, httpbin, cov, ... | 1 | 2016-06-11T17:13:05Z | 37,778,982 | <p>The <code>httpbin</code> fixture is provided by the <a href="https://pypi.python.org/pypi/pytest-httpbin" rel="nofollow"><code>pytest-httpbin</code></a> package. So you need to make sure that you installed the required <strong>dependencies for running tests / building docs</strong> before running the tests.</p>
<p>... | 1 | 2016-06-12T20:51:40Z | [
"python",
"python-requests",
"py.test"
] |
Python3 Tkinter canvas create_image and create_oval optimization | 37,766,482 | <h1>Background</h1>
<p>I am trying - and succeeding - in creating a simple plot using using the <code>Canvas</code> object within <code>tkinter</code>. I am trying to use as many tools that are installed with Python3 as possible. Matplotlib and others are great, but they are pretty large installs for something that ... | 2 | 2016-06-11T17:13:52Z | 37,766,721 | <p>The canvas has performance problems when many items are created (more specifically, when new object ids are created). Deleting objects doesn't help, the problem is in the ever increasing object ids which are never reused. This problem usually doesn't appear until you have 10's of thousands of items. If you're creati... | 0 | 2016-06-11T17:37:48Z | [
"python",
"plot",
"tkinter",
"tkinter-canvas"
] |
Find number of consecutive elements that are the same before they change | 37,766,515 | <p>So for example if I have the lists</p>
<pre><code>a = [1,1,1,2,2]
b = [1,1,2,2,2]
c = [2,1,1,1,1]
</code></pre>
<p>I would want to get the longest streak of the first element in the list, so for example <code>a</code> would give 3, <code>b</code> would give 2 and <code>c</code> would give 1. I know I could create ... | 4 | 2016-06-11T17:17:31Z | 37,766,550 | <p>You can use groupby and sum how many items are in the first group for each:</p>
<pre><code>a = [1,1,1,2,2]
b = [1,1,2,2,2]
c = [2,1,1,1,1]
from itertools import groupby
for l in [a,b,c]:
print(sum( 1 for _ in next(groupby(l), [[], []],)[1]))
</code></pre>
<p>Or using takewhile:</p>
<pre><code>from itertool... | 3 | 2016-06-11T17:21:12Z | [
"python",
"list"
] |
Find number of consecutive elements that are the same before they change | 37,766,515 | <p>So for example if I have the lists</p>
<pre><code>a = [1,1,1,2,2]
b = [1,1,2,2,2]
c = [2,1,1,1,1]
</code></pre>
<p>I would want to get the longest streak of the first element in the list, so for example <code>a</code> would give 3, <code>b</code> would give 2 and <code>c</code> would give 1. I know I could create ... | 4 | 2016-06-11T17:17:31Z | 37,766,573 | <p>you could do something like this:</p>
<pre><code>numStreak = ([a[0] == n for n in a]+[False]).index(False)
</code></pre>
<p>(this also makes sure that if all elements are like the first element, index does return the correct value)</p>
<p>UPDATE: a more efficient (but less elegant?) version</p>
<pre><code>from i... | 5 | 2016-06-11T17:23:31Z | [
"python",
"list"
] |
Find number of consecutive elements that are the same before they change | 37,766,515 | <p>So for example if I have the lists</p>
<pre><code>a = [1,1,1,2,2]
b = [1,1,2,2,2]
c = [2,1,1,1,1]
</code></pre>
<p>I would want to get the longest streak of the first element in the list, so for example <code>a</code> would give 3, <code>b</code> would give 2 and <code>c</code> would give 1. I know I could create ... | 4 | 2016-06-11T17:17:31Z | 37,766,939 | <p>You could use numpy:</p>
<pre><code>>>> import numpy as np
>>> a = [1,1,1,2,2]
>>> b = [1,1,2,2,2]
>>> c = [2,1,1,1,1]
>>> def runs(data):
... return np.split(data, np.where(np.diff(data) != 0)[0]+1)
...
>>> for e in a,b,c:
... runs(np.array(e))
...
[arr... | 0 | 2016-06-11T18:00:30Z | [
"python",
"list"
] |
Find number of consecutive elements that are the same before they change | 37,766,515 | <p>So for example if I have the lists</p>
<pre><code>a = [1,1,1,2,2]
b = [1,1,2,2,2]
c = [2,1,1,1,1]
</code></pre>
<p>I would want to get the longest streak of the first element in the list, so for example <code>a</code> would give 3, <code>b</code> would give 2 and <code>c</code> would give 1. I know I could create ... | 4 | 2016-06-11T17:17:31Z | 37,767,004 | <p>One liner for the road? Take aim...</p>
<pre><code>a = [5,5,5,5,8]
list(np.ediff1d(a)).count(0)+1
>>> 4
</code></pre>
| 1 | 2016-06-11T18:06:12Z | [
"python",
"list"
] |
passing user data with Python-Flask and mongoDB | 37,766,542 | <p>So basically I have an "/add" route where it is used to manually seed in test user data to mongodb and I want to be able to pass that user's ID to the URL for the route "/agreement" so when the user is on the agreement page, their <code>"_id"</code> will be mapped to that URI and the info they enter on the agreement... | 1 | 2016-06-11T17:20:27Z | 37,766,880 | <p>Try this:</p>
<pre><code>@app.route('/agreement/<user_id>', methods=['GET', 'POST'])
def agreement(user_id):
user = mongo.db.users.find_one({"_id": user_id})
print user
return render_template('agreement.html', user=user)
</code></pre>
<p>URL parameter names in Flask are specified in the <code>rou... | 0 | 2016-06-11T17:54:34Z | [
"python",
"mongodb",
"rest",
"flask"
] |
How is one meant to use the collections.abc classes with multiple inheritance? | 37,766,607 | <p>I'm having an issue where I want to use the mixin methods from <code>collections.abc.MutableSequence</code>, but I also have to inherit from something else.</p>
<pre class="lang-py prettyprint-override"><code>class Thing(urwid.Pile, collections.abc.MutableSequence):
...
</code></pre>
<p>I end up with</p>
<pre... | 0 | 2016-06-11T17:27:07Z | 37,766,651 | <p><code>metaclass=ABCMeta</code> <em>is</em> the problem. <code>MutableSequence</code> is using <code>ABCMeta</code> as its metaclass, <code>Pile</code> is using something else, hence the conflict.</p>
<p>What you can do is inherit from <code>Pile</code> and use <code>MutableSequence.register()</code>, like this:</p>... | 3 | 2016-06-11T17:30:50Z | [
"python",
"python-3.x",
"multiple-inheritance",
"metaclass"
] |
Making python lambda func work inside apply method in Pandas Dataframe | 37,766,700 | <p>I am trying to transform the age columns of a pandas dataframe by applying apply function. how to make below code work or is there a more pythonic way way to do this. </p>
<pre><code>cps=(cps.assign(Age_grp_T=cps['age'].apply(lambda x:{x>=71:'Tradionalists',
... | 1 | 2016-06-11T17:35:31Z | 37,766,808 | <p>i would use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow">cut()</a> function for that:</p>
<pre><code>In [663]: labels=[' ','Millennials','Generation X','Baby Boomers','Tradionalists']
In [664]: a['category'] = pd.cut(a['age'], bins=[1, 16,46,52,71, 200],labels=lab... | 1 | 2016-06-11T17:46:17Z | [
"python",
"pandas",
"dataframe"
] |
Making python lambda func work inside apply method in Pandas Dataframe | 37,766,700 | <p>I am trying to transform the age columns of a pandas dataframe by applying apply function. how to make below code work or is there a more pythonic way way to do this. </p>
<pre><code>cps=(cps.assign(Age_grp_T=cps['age'].apply(lambda x:{x>=71:'Tradionalists',
... | 1 | 2016-06-11T17:35:31Z | 37,767,013 | <p>I have found one more way to do this but thanks MaxU your answers works too</p>
<pre><code>cps=(cps.assign(Age_grp_T=np.where(cps['age']>=71,"Tradionalists",
np.where(np.logical_and(71>cps['age'],cps['age']>=52),"Baby Boomers",
np.where(np.logical_and(52>cps['... | 0 | 2016-06-11T18:07:14Z | [
"python",
"pandas",
"dataframe"
] |
Select certain dates from Pandas dataframe | 37,766,770 | <p>I am learning how to filter dates on a Pandas data frame and need some help with the following please. This is my original data frame (<a href="https://dl.dropboxusercontent.com/u/32282382/ES_800_day_1_min_BarData.txt" rel="nofollow">from this data</a>):</p>
<pre><code>data
Out[120]:
Open High Low Last Vo... | 1 | 2016-06-11T17:43:14Z | 37,767,231 | <p>IIUC, you can do it this way:</p>
<pre><code>x.ix[(x.groupby(pd.Grouper(key='Timestamp', freq='5T'))['Volume'].transform('sum') > 65000)
&
(x.Timestamp.dt.hour==9)
&
(x.Timestamp.dt.minute>=30) & (x.Timestamp.dt.minute<=34)]
</code></pre>
<p>in order to set index back:</p>
... | 1 | 2016-06-11T18:31:43Z | [
"python",
"pandas"
] |
Interruption of a os.rename in python | 37,766,804 | <p>I made a script in python that renames all files and folders(does not <em>recurse</em>) in "." directory: the directory in which file is kept. It happened that I ran the script in a directory which contained no files and only one directory let's say <strong>imp</strong> with path <code>.\imp</code>. While program wa... | 1 | 2016-06-11T17:45:10Z | 37,767,228 | <p>You are using Windows, which means you are (probably) on NTFS. NTFS is a modern, <a href="https://en.wikipedia.org/wiki/Journaling_file_system" rel="nofollow">journaling</a> file system. It should not <em>corrupt</em> or <em>lose</em> any data, though it's possible that only some of the changes that constitute a r... | 2 | 2016-06-11T18:31:24Z | [
"python",
"python-2.7",
"file",
"python-os"
] |
boto3 TypeError: 'NoneType' object is not iterable | 37,766,805 | <p>I'm trying to use boto3 to print the values of an EC2 tag I have called 'Function' but receive a <code>TypeError: 'NoneType' object is not iterable</code> error in line 7 after the code runs through about 20 objects. I've tried to catch this by checking if that value is <code>None</code> but still receive this erro... | 0 | 2016-06-11T17:45:25Z | 37,767,149 | <p>You could try doing this and check:</p>
<pre><code>def tag_to_dict(ec2):
tag_dict = {}
if ec2.tags is None:
return "No Value" ## Replace "No Value" with tag_dict to get an empty dict
for tag in ec2.tags:
tag_dict[tag['Key']] = tag['Value']
return tag_dict
</code></pre>
<p>You ... | 0 | 2016-06-11T18:21:24Z | [
"python",
"amazon-web-services",
"amazon-ec2",
"boto"
] |
Troubleshooting unequal error? | 37,766,849 | <p>I'm creating a LinkedList class to get a better feel for the python language and its doubly linked nodes. My overall task being to not make use of python's built-in list data structure, while also trying to optimize the time efficiency of the code. What would be the best way to go about fixing what I would assume is... | 0 | 2016-06-11T17:51:25Z | 37,767,129 | <blockquote>
<p>I'd get an error saying 1 != 20</p>
</blockquote>
<p>That's a true statement, though, so your problem exists in how you set the data of your list. It wasn't updated, but the Python list was. </p>
<blockquote>
<p>I'm not sure where this 20 value is coming from</p>
</blockquote>
<p>Umm... <code>lst... | 1 | 2016-06-11T18:18:44Z | [
"python",
"performance"
] |
Anaconda on Ubuntu - Error in permission to update using conda command | 37,766,873 | <p>On my laptop on windows 8.1 I have vmware and ubuntu 16.4 installed.</p>
<p>I recently installed Anaconda 2.7 (x64) on it. The directory where anaconda is installed, is:</p>
<pre><code> /home/anaconda2/
</code></pre>
<p>When I tried to use the following command to update packages, I got errors as mentioned below:... | 1 | 2016-06-11T17:53:56Z | 37,766,990 | <p>what about this....</p>
<pre><code> sudo chown -R madhu /home/anaconda2/
</code></pre>
| 2 | 2016-06-11T18:05:06Z | [
"python",
"ubuntu",
"permissions",
"sudo"
] |
Anaconda on Ubuntu - Error in permission to update using conda command | 37,766,873 | <p>On my laptop on windows 8.1 I have vmware and ubuntu 16.4 installed.</p>
<p>I recently installed Anaconda 2.7 (x64) on it. The directory where anaconda is installed, is:</p>
<pre><code> /home/anaconda2/
</code></pre>
<p>When I tried to use the following command to update packages, I got errors as mentioned below:... | 1 | 2016-06-11T17:53:56Z | 39,824,678 | <p>If you are trying it in windows, you can correct this error by giving permission rights to user. For that </p>
<p>1.Go to the Anaconda folder located in your OS Drive in Program Files
2.Then click properties
3.Under the security tab, click edit to change permissions
4.Under that select your user and give full contr... | 1 | 2016-10-03T04:37:37Z | [
"python",
"ubuntu",
"permissions",
"sudo"
] |
How do I switch betwen Python 2 and 3 when using Flycheck with flake8 in Emacs? | 37,766,948 | <blockquote>
<p>How do I switch betwen Python 2 and 3 when using Flycheck with flake8 in Emacs?</p>
</blockquote>
<p>Having installed Flycheck for Emacs, I then install a syntax-checker like <code>flake8</code>.</p>
<p>Installing <code>flake8</code> using <code>pip install flake8</code> makes Flycheck check Python ... | 2 | 2016-06-11T18:01:15Z | 37,792,439 | <p>If you use virtual environments, either using anaconda, miniconda or virtualenv, then I recommend that you use <a href="https://github.com/jorgenschaefer/pyvenv" rel="nofollow">pyvenv.el</a>. It requires a tiny bit of configuration which I may be able to help you out with if you need but it is generally pretty easy ... | 1 | 2016-06-13T14:31:46Z | [
"python",
"emacs",
"flycheck"
] |
Matplotlib: enforce equal size (height) of subplots? | 37,767,026 | <p>I have a figure containing three subplots. The first subplot is an image (<code>imshow</code>), while the other two are distributions (<code>plot</code>).</p>
<p>Here's the code:</p>
<pre><code># collects data
imgdata = ... # img of shape (800, 1600, 3)
x = ... # one 1600-dimensional vector
y ... | 1 | 2016-06-11T18:08:55Z | 37,767,461 | <p>You can do it by specifying it directly in the subplots like this:</p>
<pre><code>from matplotlib import pyplot as plt
from matplotlib import image as mpimg
import numpy as np
imgdata = np.random.rand(200, 400, 3)
x = np.random.normal(loc=100.0, scale=20.0, size=400)
y = np.random.normal(loc=150.0, scale=15.0, siz... | 2 | 2016-06-11T18:57:06Z | [
"python",
"matplotlib",
"resize",
"subplot"
] |
tz_convert in pandas does not work for any city in India | 37,767,030 | <p>the below command seems to work for a other locations in Asia except for any location in India. Is there a bug here or am I missing something?
this works:</p>
<pre><code>pd.to_datetime(pd.datetime.now()).tz_localize('US/Pacific').tz_convert('Asia/Hong_Kong')
pd.to_datetime(pd.datetime.now()).tz_localize('US/Pacific... | 2 | 2016-06-11T18:09:03Z | 37,771,535 | <p>pandas uses the the time zones in the tz database. You can find a list of all available time zone codes for example <a href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones" rel="nofollow">in wikipedia</a>.</p>
<p>For India, you would use <code>Asia/Kolkata</code></p>
<pre><code>pd.to_datetime(pd.date... | 1 | 2016-06-12T06:51:55Z | [
"python",
"datetime",
"pandas"
] |
np.tile to repeat an 1D array | 37,767,110 | <p>I have an ndarray, <code>A</code>,
and I want to multiply this ndarray element wise by another 1D array <code>b</code> where I assume that <code>A.shape[i] = len(b)</code> for some <code>i</code>. I need this generality in my application.</p>
<p>I can do this using <code>np.tile</code> as follows:</p>
<pre><code>... | 1 | 2016-06-11T18:17:13Z | 37,767,508 | <p>For this particular example, the following code would do the trick:</p>
<pre><code>result = A*b[:, np.newaxis]
</code></pre>
<p>For any value of <code>i</code>, try this:</p>
<pre><code>A2, B = np.broadcast_arrays(A, b)
result = A2*B
</code></pre>
| 2 | 2016-06-11T19:01:11Z | [
"python",
"numpy"
] |
If item in list meets condition, remove item and multiple preceding items | 37,767,278 | <p>I am looking for a way to remove every <strong><em>nth</em></strong> item (let's call that item <code>i</code>) in a list, <em>and</em> also <strong><em>x</em></strong> number of items directly preceding <code>i</code> in the list, if <code>i</code> meets a condition.</p>
<p>I have been looking around at list comp... | 0 | 2016-06-11T18:36:47Z | 37,767,378 | <pre><code>>>> myList = ["you", "are", "right", "I", "am", "wrong"]
>>> for i, l in enumerate(myList):
... if l == 'wrong':
... myList = myList[:i-2]
... break
...
>>> myList
['you', 'are', 'right']
</code></pre>
<p>Of course you could make 2 a variable</p>
| 1 | 2016-06-11T18:47:55Z | [
"python",
"list",
"enumerate"
] |
If item in list meets condition, remove item and multiple preceding items | 37,767,278 | <p>I am looking for a way to remove every <strong><em>nth</em></strong> item (let's call that item <code>i</code>) in a list, <em>and</em> also <strong><em>x</em></strong> number of items directly preceding <code>i</code> in the list, if <code>i</code> meets a condition.</p>
<p>I have been looking around at list comp... | 0 | 2016-06-11T18:36:47Z | 37,767,379 | <p>How about, for your example,</p>
<pre><code>new_list = [v for i, v in enumerate(myList)
if myList[3*int(i/3)+2] != 'wrong']
</code></pre>
<p>This works since you want to not-copy the entire group of 3 items that ends with 'wrong'. It would be more complicated if you wanted to delete only part of that g... | 1 | 2016-06-11T18:48:02Z | [
"python",
"list",
"enumerate"
] |
If item in list meets condition, remove item and multiple preceding items | 37,767,278 | <p>I am looking for a way to remove every <strong><em>nth</em></strong> item (let's call that item <code>i</code>) in a list, <em>and</em> also <strong><em>x</em></strong> number of items directly preceding <code>i</code> in the list, if <code>i</code> meets a condition.</p>
<p>I have been looking around at list comp... | 0 | 2016-06-11T18:36:47Z | 37,767,449 | <p>Here a solution with <code>numpy.delete</code>. <code>Numpy.delete</code> remove the elements with using the index. So you can find the corresponding match and delete the preceding ones as much you want. </p>
<pre><code>In [1]: import numpy as np
In [2]: myList = ["you", "are", "right", "I", "am", "wrong"]
In [3]... | 0 | 2016-06-11T18:55:38Z | [
"python",
"list",
"enumerate"
] |
How can I improve this algorithm ? (Image Processing) | 37,767,321 | <p>Ok, so after some hours of documentation on Image Processing topic (I'm a beginner programmer) I decide I want to implement a edge detection function of my own to better understand the mathematics behind it. I was able to do it fortunately, but my algorithm it's just way too slow(O(n^2)). I'll post the code with the... | 0 | 2016-06-11T18:41:27Z | 37,796,272 | <p>I analyzed your code:</p>
<p>you're applying two gradient filters, one for direction <code>x</code>, one for <code>y</code>.</p>
<p>these filters look like:</p>
<pre><code>-1 -2 -1
0 0 0
1 3 0
</code></pre>
<p>and</p>
<pre><code>-1 0 1
-2 0 2
-1 1 0
</code></pre>
<p>I guess these are typos (?) and you ra... | 0 | 2016-06-13T17:58:11Z | [
"python",
"opencv",
"image-processing"
] |
Creating a tripled nested JSON in Python | 37,767,340 | <p>I am trying to create a JSON via first making a python dict that ultimately produces the following structured format:</p>
<pre><code>{"sentences": [{"sentence": "At the end of November 2005 , Hong Kong and America had 132 licensed banks , 41 restricted licensed banks , 35 deposit-taking institutions , and 86 repres... | 0 | 2016-06-11T18:43:06Z | 37,778,878 | <p>It seems like there's somewhat of a mismatch between the ideal output at the beginning of your question, and what the code actually does, in that the code doesn't create the keys <code>sentence</code>, <code>parsedSentence</code> and <code>location-value-pairs</code>.</p>
<p>This may just mean I've misunderstood th... | 1 | 2016-06-12T20:40:44Z | [
"python",
"json"
] |
Cmake - Generate shared library with OpenCV inside | 37,767,352 | <p>I compiled a <code>.so</code> file using the following <code>CmakeList.txt</code>:</p>
<pre><code>cmake_minimum_required(VERSION 3.5.1)
project(phase)
SET(OpenCV_INCLUDE_DIRS "/usr/local/include/opencv")
include_directories(INCLUDE_DIR include ${OpenCV_INCLUDE_DIRS})
set(OpenCV_LIB_DIR "/usr/local/lib")
link_direct... | 0 | 2016-06-11T18:43:56Z | 37,767,442 | <p>I don't find the part in your CMakeLists.txt where you actually call something like <code>target_link_libraries(dct opencv)</code>. I'm not sure whether there's a lookup routine like <code>find_package(opencv REQUIRED)</code> or similar or whether you'd have to build one if you planned to use <code>find_package</cod... | 1 | 2016-06-11T18:54:58Z | [
"python",
"c++",
"opencv",
"cmake",
"shared-libraries"
] |
When using the multiprocessing library, how do I bind resources to specific processes? | 37,767,364 | <p>Say I have 50 processes, and I'm using them to operate on (say) 20000 different input values. (I'm using the pathos library, which I think operates similarly to the multiprocessing library in Python.)</p>
<pre><code>thread_pool = pathos.multiprocessing.ProcessingPool(threads=50)
thread_pool.map(function, inputs)
<... | 0 | 2016-06-11T18:46:09Z | 37,819,993 | <p>I figured out how to do this by using the <code>multiprocess</code> library instead of the <code>pathos</code> library. When creating a pool of processes, you can specify an "initializer function", which runs at the beginning of each process. In this initializer function I created a database engine and declared th... | 0 | 2016-06-14T18:54:45Z | [
"python",
"sqlalchemy",
"multiprocessing",
"pathos"
] |
When using the multiprocessing library, how do I bind resources to specific processes? | 37,767,364 | <p>Say I have 50 processes, and I'm using them to operate on (say) 20000 different input values. (I'm using the pathos library, which I think operates similarly to the multiprocessing library in Python.)</p>
<pre><code>thread_pool = pathos.multiprocessing.ProcessingPool(threads=50)
thread_pool.map(function, inputs)
<... | 0 | 2016-06-11T18:46:09Z | 38,284,989 | <p>I'm the author of both <code>pathos</code> and <code>multiprocess</code>. It turns out that <code>multiprocess</code> is actually what <code>pathos</code> is using, but maybe it's not obvious that is the case. You can do it from <code>pathos</code>:</p>
<pre><code>>>> import pathos
>>> pathos.poo... | 1 | 2016-07-09T18:27:58Z | [
"python",
"sqlalchemy",
"multiprocessing",
"pathos"
] |
Pandas throws weird exception when trying to apply function to duplicate columns | 37,767,392 | <p>Why am I getting the following error message? I am trying to apply a function to a duplicate column. Please don't tell me that the solution is to do something like <code>df["a"] = 2 * df["a"]</code>; this is a dumbed down example of something more complicated I am working on right now.</p>
<pre><code>>>> d... | 0 | 2016-06-11T18:49:20Z | 37,767,780 | <p>IIUC you need change <code>x[0]</code> and <code>x['1']</code> to <code>x.a</code>, because there is no columns <code>0</code> and <code>1</code>:</p>
<pre><code>a = df[["a", "a"]].apply(lambda x: x.a + x.a, axis = 1)
print (a)
a a
0 0 0
1 2 2
2 4 4
</code></pre>
<p>But if duplicity columns have differen... | 2 | 2016-06-11T19:32:47Z | [
"python",
"pandas",
"dataframe",
"duplicity"
] |
ImportError: No module named paths ipython notebook and bokeh using enthought in windows | 37,767,394 | <p>I'm receiving the following error trying to run a plot with bokeh in an Ipython notebook</p>
<pre><code>---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-128-bedfa82edaf4> in <module>()
... | 0 | 2016-06-11T18:49:31Z | 37,775,683 | <p>When you use <code>pip</code> with a package that was already installed with Package Manager (including packages that are bundled with Canopy), you will likely end up with an incompatible mix of files. I suggest that you uninstall Canopy 1.5.2 and install the current version, 1.7.2. Before restarting Canopy, be sure... | 1 | 2016-06-12T15:00:33Z | [
"python",
"ipython",
"enthought",
"bokeh",
"jupyter-notebook"
] |
python package best practice: managing imports | 37,767,502 | <p>Coming from R, I'm trying to wrap my head around the package system in python.</p>
<p><strong>My question (in short) is: what is the best practice for managing external library imports?</strong></p>
<p>Suppose I have a package (call it <code>pointless</code>) with the following directory structure.</p>
<pre><code... | 0 | 2016-06-11T19:00:29Z | 37,767,764 | <p>This is related to this question: <a href="http://stackoverflow.com/questions/19077381/what-happens-when-i-import-module-twice-in-python">what happens when i import module twice in python</a>. Long story short: If you import a module twice, it is loaded only once, so your example is not problematic at all.</p>
| 1 | 2016-06-11T19:31:00Z | [
"python",
"pypi",
"python-packaging"
] |
Timeseries plot with min/max shading using Seaborn | 37,767,719 | <p>I am trying to create a 3-line time series plot based on the following data <a href="http://i.stack.imgur.com/vRP5H.png" rel="nofollow"><img src="http://i.stack.imgur.com/vRP5H.png" alt="Long Dataframe"></a>, in a Week x Overload graph, where each Cluster is a different line.</p>
<p>I have multiple observations for... | 4 | 2016-06-11T19:26:09Z | 37,775,688 | <p>I <strong>really</strong> thought I would be able to do it with <code>seaborn.tsplot</code>. But it does not quite look right. Here is the result I get with seaborn:</p>
<pre><code>cluster_overload = pd.read_csv("TSplot.csv", delim_whitespace=True)
cluster_overload['Unit'] = cluster_overload.groupby(['Cluster','Wee... | 1 | 2016-06-12T15:01:14Z | [
"python",
"pandas",
"seaborn"
] |
Timeseries plot with min/max shading using Seaborn | 37,767,719 | <p>I am trying to create a 3-line time series plot based on the following data <a href="http://i.stack.imgur.com/vRP5H.png" rel="nofollow"><img src="http://i.stack.imgur.com/vRP5H.png" alt="Long Dataframe"></a>, in a Week x Overload graph, where each Cluster is a different line.</p>
<p>I have multiple observations for... | 4 | 2016-06-11T19:26:09Z | 37,776,787 | <p>Based off <a href="http://stackoverflow.com/questions/34293687/standard-deviation-and-errors-bars-in-seaborn-tsplot-function-in-python">this incredible answer</a>, I was able to create a monkey patch to beautifully do what you are looking for.</p>
<pre><code>import pandas as pd
import seaborn as sns
import seab... | 2 | 2016-06-12T16:51:37Z | [
"python",
"pandas",
"seaborn"
] |
Timeseries plot with min/max shading using Seaborn | 37,767,719 | <p>I am trying to create a 3-line time series plot based on the following data <a href="http://i.stack.imgur.com/vRP5H.png" rel="nofollow"><img src="http://i.stack.imgur.com/vRP5H.png" alt="Long Dataframe"></a>, in a Week x Overload graph, where each Cluster is a different line.</p>
<p>I have multiple observations for... | 4 | 2016-06-11T19:26:09Z | 37,776,853 | <p>I finally used the good old <code>plot</code> with a design (subplots) that seems (to me) more readable.</p>
<pre><code>df = pd.read_csv('TSplot.csv', sep='\t', index_col=0)
# Compute the min, mean and max (could also be other values)
grouped = df.groupby(["Cluster", "Week"]).agg({'Overload': ['min', 'mean', 'max']... | 3 | 2016-06-12T16:58:42Z | [
"python",
"pandas",
"seaborn"
] |
Applying Logistic Regression in Coursera ML Course (Week #3) using Python | 37,767,759 | <p>I'm trying to implement an exercise in coursera's ML course (which normally uses matlab and octave) using python (so this isn't cheating). The exercise calls for us to implement logistic regression and use it on a data set.</p>
<p>As a starting point, I first tried to use the implementation in <code>sklearn</code> ... | -1 | 2016-06-11T19:30:44Z | 37,769,063 | <blockquote>
<p>One potential source of error is that I'm misinterpreting the 7 X 4 matrix coefficient matrix stored in trial._coeff</p>
</blockquote>
<p>This matrix is not 7x4, it is 1x28 (check <code>print(trial.coef_.shape)</code>). One coefficient for each of your 28 features (27 returned by constructVariations ... | 3 | 2016-06-11T22:34:39Z | [
"python",
"numpy",
"machine-learning"
] |
Scikit-learn KNN(K Nearest Neighbors ) parallelize using Apache Spark | 37,767,790 | <p>I have been working on machine learning KNN (K Nearest Neighbors) algorithm with Python and Python's Scikit-learn machine learning API.</p>
<p>I have created sample code with toy dataset simply using python and Scikit-learn and my KNN is working fine. But As we know Scikit-learn API is build to work on single machi... | 0 | 2016-06-11T19:33:25Z | 37,768,933 | <p>Well according to discussions <code>https://issues.apache.org/jira/browse/SPARK-2336</code> here MLLib (Machine Learning Library for Apache Spark) does not have an implementation of KNN.
You could try <code>https://github.com/saurfang/spark-knn</code>.</p>
| 0 | 2016-06-11T22:11:59Z | [
"python",
"scala",
"apache-spark",
"machine-learning",
"scikit-learn"
] |
Ansible on Windows 10 - pip install missing pycrypto>=2.6 | 37,767,805 | <p>I've installed ansible on Windows 10 + cygwin using pip. The install finished OK, no error on the output. However, when running <code>ansible</code> from the cygwin prompt after the install I get:</p>
<pre><code>pkg_resources.DistributionNotFound: The 'pycrypto>=2.6' distribution was not found and is required by... | 1 | 2016-06-11T19:35:20Z | 37,955,319 | <p>This was due to wrongly configured paths, with two installs of Python in the system. I have a pure Windows install as well one installed by Cygwin. Correctly pointing the <code>Path</code>, <code>PYTHON</code> and <code>PYTHONPATH</code> variables the Cygwin install fixed the issue.</p>
| 0 | 2016-06-21T22:02:05Z | [
"python",
"pip",
"windows-10",
"ansible"
] |
Is this a good result for normal equations,if not how do I know it's good for data set? | 37,767,857 | <p>I'm trying to learn normal equations for ML but I'm not sure this result are correct.Parameters are so high and I cannot find hypothesis for this parameters, here is what I mean:</p>
<p>Data set:</p>
<pre class="lang-none prettyprint-override"><code>2104,5,1,45,460
1416,3,2,40,232
1534,3,2,30,315
852,2,1,36,178
</... | 0 | 2016-06-11T19:41:06Z | 37,768,990 | <blockquote>
<p>but these numbers are so high. Is this normal?</p>
</blockquote>
<p>Your data is not normalized/scaled, your values are big (~1e2) thus coefficients of regressions are the same.</p>
<blockquote>
<p>I tried to print hypothesis just for my first data set elements (2104,5,1,45,460), but it's giving t... | 0 | 2016-06-11T22:23:03Z | [
"python",
"machine-learning",
"normalization",
"linear-regression"
] |
Saving output of a function as a variable and using it in another function | 37,767,945 | <p>I'm new to programming, so this question might be dumb. </p>
<p>I need to introduce the value of <code>Tr1</code> into the <code>Bzero1</code> function. When I run the module I get the result below: </p>
<p><img src="http://i.stack.imgur.com/vjrKu.png" alt="this result">. </p>
<p>The program is not running the <c... | 1 | 2016-06-11T19:50:37Z | 37,767,990 | <ol>
<li><p>Do not replace <code>Tr1</code> function value, to avoid such replacement change:</p>
<pre><code>Tr1_value = Tr1(T, Tc1)
</code></pre></li>
<li><p>Call <code>Bzero1</code> function with code:</p>
<pre><code>Bzero1(Tr1_value)
</code></pre></li>
<li><p>Modify <code>Tr1</code> to return value:</p>
<pre><cod... | 0 | 2016-06-11T19:55:58Z | [
"python",
"function",
"parameter-passing"
] |
Saving output of a function as a variable and using it in another function | 37,767,945 | <p>I'm new to programming, so this question might be dumb. </p>
<p>I need to introduce the value of <code>Tr1</code> into the <code>Bzero1</code> function. When I run the module I get the result below: </p>
<p><img src="http://i.stack.imgur.com/vjrKu.png" alt="this result">. </p>
<p>The program is not running the <c... | 1 | 2016-06-11T19:50:37Z | 37,768,065 | <p><code>def</code> is only defining a function, not calling it. E.g.</p>
<pre><code>def foo(a):
print a * 2
</code></pre>
<p>means there is now a function <code>foo</code> that takes argument <code>a</code>. The <code>a</code> in <code>foo(a)</code> is the name of the variable <em>inside</em> the function.</p>
... | 0 | 2016-06-11T20:04:40Z | [
"python",
"function",
"parameter-passing"
] |
Parsing html for specific script type | 37,767,947 | <p>In the html code, Vine has <code><script type="application/ld+json"></code> with links to all the videos on the page, how would I got about accessing this JSON?</p>
<pre><code>import requests
from bs4 import BeautifulSoup
url = 'https://vine.co/tags/funny'
source_code = requests.get(url)
plain_text = source_... | 1 | 2016-06-11T19:50:46Z | 37,768,042 | <p>You can use a css selector:</p>
<pre><code>soup.select("script[type=application/ld+json]
</code></pre>
<p>Or find_all setting <code>type="application/ld+json"</code>:</p>
<pre><code>soup.find_all("script",type="application/ld+json")
</code></pre>
<p>Both gives you:</p>
<pre><code>[<script type="application/l... | 2 | 2016-06-11T20:02:39Z | [
"python",
"beautifulsoup",
"html-parsing",
"vine"
] |
400 Bad Request (Flask + html) | 37,767,974 | <p>I keep getting a 400 Bad Request when I try to run my Flask project.</p>
<p>I have to do a project using Flask and HTML, and it was supposed to be a group project, so members would have to learn different parts of it to then gather everything. Sadly, my 'group' didn't do anything at all</p>
<p>Here's my code:</p>
... | -2 | 2016-06-11T19:53:50Z | 37,768,003 | <p>You are trying to access the <code>request.form</code> dictionary, <em>always</em>:</p>
<pre><code>button = request.form["button"]
</code></pre>
<p>This throws a <code>400</code> response error if there is no such value in the form. This is <em>always</em> the case when you have a <code>GET</code> request, <code>r... | 2 | 2016-06-11T19:57:33Z | [
"python",
"html",
"flask"
] |
Enabling context processors in app templates | 37,768,046 | <p>I have a few apps in a Django project with their own templates (i.e. <code>/project/app1/template</code>, <code>/project/app2/template</code> and so on).</p>
<p>However, template context processors (which are defined in the <code>settings.py</code> of the main app/project) are not available in those app templates.<... | 1 | 2016-06-11T20:02:51Z | 37,768,100 | <p>This doesn't have anything at all to do with "app templates"; the behaviour is exactly the same no matter where your templates are located.</p>
<p>You always need a RequestContext if you want context processors to be run; apart from anything else, that's because they are passed the request object, so it needs to be... | 1 | 2016-06-11T20:12:08Z | [
"python",
"django",
"templates"
] |
Generating random value for given cdf | 37,768,058 | <p>Depending on sample of values of random variable I create cumulative density function using kernel density estimation.</p>
<pre><code>cdf = gaussian_kde(sample)
</code></pre>
<p>What I need is to generate sample values of random variable whose density function is equal to constructed cdf. I know about the way of i... | 1 | 2016-06-11T20:03:49Z | 37,768,413 | <p>If you're using a kernel density estimator (KDE) with Gaussian kernels, your density estimate is a Gaussian mixture model. This means that the density function is a weighted sum of 'mixture components', where each mixture component is a Gaussian distribution. In a typical KDE, there's a mixture component centered ov... | 1 | 2016-06-11T20:52:03Z | [
"python",
"random-sample",
"cdf"
] |
how to apply aggregate in pymongo | 37,768,094 | <p>Through the following query in MongoDb , I get all the teams from the entire data.</p>
<pre><code>db.player_level_data.aggregate([{$group : {_id: {team_name : "$team_name"}}}]).toArray()
</code></pre>
<p>I need to import this array of teams in python through pymongo.I tried the following code.</p>
<pre><code>pipe... | 1 | 2016-06-11T20:10:29Z | 37,768,103 | <p>I assume cursor object is <a href="http://anandology.com/python-practice-book/iterators.html" rel="nofollow">generator</a>, so simply convert it to list and print that list:</p>
<pre><code>pprint(list(data))
</code></pre>
<p>Note that data whould be empty after printing. so if you need to continue work on that dat... | 1 | 2016-06-11T20:12:58Z | [
"python",
"mongodb",
"pymongo"
] |
how to apply aggregate in pymongo | 37,768,094 | <p>Through the following query in MongoDb , I get all the teams from the entire data.</p>
<pre><code>db.player_level_data.aggregate([{$group : {_id: {team_name : "$team_name"}}}]).toArray()
</code></pre>
<p>I need to import this array of teams in python through pymongo.I tried the following code.</p>
<pre><code>pipe... | 1 | 2016-06-11T20:10:29Z | 37,768,109 | <p>Of course, this returns a cursor object.</p>
<pre><code>list(cursor)
</code></pre>
<p>should get you a list of the items.</p>
| 1 | 2016-06-11T20:13:44Z | [
"python",
"mongodb",
"pymongo"
] |
Script engine Jython was not found in Mule ESB 3.7.0 application | 37,768,200 | <p>I'm neewbie with Mule ESB.
I'm trying to use a python script block in my mule project, but when I run the project I recive the following errors:</p>
<pre><code>console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.
ERROR 2016-06-11 22:10:32,827 [main] org.mule.module.launcher.application.... | 0 | 2016-06-11T20:24:32Z | 37,822,739 | <p>Jython should be part of your runtime server in Anypoint Studio. Check for it in the Package Explorer and the Mule Server 3.7.0 library icon (books). The enterprise runtime should have it but if you're using the community edition it's not there.</p>
<p>E.g. version 3.7.2 EE contains jython-standalone-2.7.0 but it m... | 0 | 2016-06-14T21:53:43Z | [
"java",
"python",
"mule",
"jython",
"mule-studio"
] |
Scipy function muliple arguments | 37,768,266 | <p>I have this function:</p>
<pre><code>def error(w0, w1):
return sum((data.Height - (w1*data.Weight+w0))**2)
</code></pre>
<p>and next I want to optimize it with<code>res = scipy.optimize.minimize(error, (1, 2), ...</code></p>
<p>When I try to run it, I have error:<code>TypeError: error() takes exactly 2 argume... | 0 | 2016-06-11T20:32:09Z | 37,768,419 | <p>Well if you look at the documentation of this function, it says that </p>
<pre><code>scipy.optimize.minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)[source]
</code></pre>
<p>fun is your function here and args are the argume... | 1 | 2016-06-11T20:52:51Z | [
"python",
"arrays",
"numpy",
"scipy"
] |
Scipy function muliple arguments | 37,768,266 | <p>I have this function:</p>
<pre><code>def error(w0, w1):
return sum((data.Height - (w1*data.Weight+w0))**2)
</code></pre>
<p>and next I want to optimize it with<code>res = scipy.optimize.minimize(error, (1, 2), ...</code></p>
<p>When I try to run it, I have error:<code>TypeError: error() takes exactly 2 argume... | 0 | 2016-06-11T20:32:09Z | 37,768,438 | <pre><code>minimize(fun, x0, args=(), method=None,....):
"""
minimize f(x) subject to
...
where x is a vector of one or more variables.
</code></pre>
<p>So the first argument is your function, <code>error</code>, and the 2nd is <code>x0</code>, in your case a tuple, the initial guess. and the first the code d... | 0 | 2016-06-11T20:56:07Z | [
"python",
"arrays",
"numpy",
"scipy"
] |
How to install googleVis into Anaconda R for windows | 37,768,321 | <p>Anaconda is a scientific python distro that can be augmented by installing a package for using the statistical functions of R</p>
<pre><code>>conda install -c r r-essentials
</code></pre>
<p>However, I also need to use googleVIS, the R interface to Google Charts API.</p>
<p>The recommended solution is this:</p... | 1 | 2016-06-11T20:38:57Z | 37,768,905 | <p>I found a "googleVis" package on CRAN. Try this from R:</p>
<pre><code>install.packages('googleVis')
</code></pre>
<p>Edit: You can install packages directly from within Jupyter Notebook (see the other answer posted here for details) or start R in console mode from within your Anaconda installation (usually C:\An... | -2 | 2016-06-11T22:06:31Z | [
"python",
"package"
] |
How to install googleVis into Anaconda R for windows | 37,768,321 | <p>Anaconda is a scientific python distro that can be augmented by installing a package for using the statistical functions of R</p>
<pre><code>>conda install -c r r-essentials
</code></pre>
<p>However, I also need to use googleVIS, the R interface to Google Charts API.</p>
<p>The recommended solution is this:</p... | 1 | 2016-06-11T20:38:57Z | 37,769,609 | <p>well i fired up jupyter notebook (and of course my anaconda had the r essentials installed). Then i typed into a cell the usual thing I would type in R console: </p>
<pre><code>install.packages('googleVis')
</code></pre>
<p>and it told me to stop trying to use cran without selecting a mirror. so then i did this</p... | 0 | 2016-06-12T00:12:31Z | [
"python",
"package"
] |
Why are modules only working in the shell inmy django app | 37,768,369 | <p>I am importing modules in my django app to use twitter. Modules like twitter, twython, tweepy etc. This is the path showed when I pip uninstall twitter</p>
<pre><code>/Desktop/myheroku/practice/lib/python3.5/site-packages
</code></pre>
<p>but when i look there in the site packages there is no twitter. Where are my... | 0 | 2016-06-11T20:46:41Z | 37,768,723 | <p>@joelgoldstick I am in the environment when I install. I figured it out tho. sorta. I had to hover over it with my mouse and click install twitter. I have never had to do that ever. Glad I learned that, now I know for the future. But I still do not see it in my directories. It must be a pycharm thing</p>
| 0 | 2016-06-11T21:37:46Z | [
"python",
"django",
"shell",
"twitter",
"module"
] |
How do I assign a variable to a price in a while loop in order to get a subtotal? | 37,768,461 | <p>I am working on a project but I can't seem to figure out this whole while loop thing. I am creating a little receipt program and I am able to get user input for the price of their items, however many they want to enter. But I cannot figure out how to tell the program to add all of the items they input to create a su... | 0 | 2016-06-11T20:59:50Z | 37,768,500 | <p>You need to initialize your subtotal to 0 before loop and add the price everytime to subtotal.</p>
<pre><code>import locale
locale.setlocale(locale.LC_ALL, '')
print("Welcome to Publix".center(80))
Subtotal = 0
while(True):
Price = float(input("Price of item: "))
if(Price == -1):
break
Subtot... | 1 | 2016-06-11T21:03:50Z | [
"python",
"string",
"while-loop",
"sum",
"user-input"
] |
How do I assign a variable to a price in a while loop in order to get a subtotal? | 37,768,461 | <p>I am working on a project but I can't seem to figure out this whole while loop thing. I am creating a little receipt program and I am able to get user input for the price of their items, however many they want to enter. But I cannot figure out how to tell the program to add all of the items they input to create a su... | 0 | 2016-06-11T20:59:50Z | 37,768,753 | <p>Use a variable (<code>subtotal</code>) to accumulate the price values. You can add a <a href="https://wiki.python.org/moin/HandlingExceptions" rel="nofollow"><code>try-except-else</code></a> block to prevent wrong user input that cannot be converted to float from breaking your code. With this, your code is a little ... | 0 | 2016-06-11T21:41:33Z | [
"python",
"string",
"while-loop",
"sum",
"user-input"
] |
Convert dataframe to dictionary in Python | 37,768,481 | <p>I have a csv file that I converted into dataframe using Pandas. Here's the dataframe:</p>
<pre><code>Customer ProductID Count
John 1 50
John 2 45
Mary 1 75
Mary 2 10
Mary 5 15
</code></pre>
<p>I need an output in the form of a dictionary that looks like ... | 3 | 2016-06-11T21:02:09Z | 37,768,730 | <p>IIUC you can use:</p>
<pre><code>d = df.groupby('ProductID').apply(lambda x: dict(zip(x.Customer, x.Count)))
.reset_index(name='Count')
.to_dict(orient='records')
print (d)
[{'ProductID': 1, 'Count': {'John': 50, 'Mary': 75}},
{'ProductID': 2, 'Count': {'John': 45, 'Mary': 10}},
{'ProductID': 5, 'C... | 4 | 2016-06-11T21:39:00Z | [
"python",
"dictionary",
"pandas",
"dataframe"
] |
How do we access the latitude and longitude of a location returned by facebook graph API? | 37,768,482 | <p>When we have made this query,</p>
<pre><code>me?fields=location
</code></pre>
<p>the data that is returned is </p>
<pre><code>{
"location": {
"id": "152971558114865",
"name": "Kharagpur"
},
"id": "884016091689459"
}
</code></pre>
<p>My question is how do we get the latitude and longitude of this pl... | 0 | 2016-06-11T21:02:12Z | 37,768,630 | <p>Make another request like</p>
<pre><code>$user_profile = $facebook->api('/' + id,'GET');
</code></pre>
<p>This will return an object having lat/lang</p>
<pre><code>"location": {
"latitude": ... ,
"longitude": ...
},
</code></pre>
<p><strong>EDITED:</strong></p>
<p>javaScript code will be something li... | 1 | 2016-06-11T21:21:47Z | [
"javascript",
"python",
"facebook",
"facebook-graph-api",
"facebook-javascript-sdk"
] |
Handling Modal Dialogs with Selenium in Python | 37,768,502 | <p>I am using Selenium to automate a process and the page I want to interact to opens a modal dialog every time someone access it. I want to be able to interact with the main page properly, so I need a way to close the dialog. However, I've tried some suggestions on handling modal dialogs and they are not working as th... | 0 | 2016-06-11T21:04:03Z | 37,768,657 | <p>With find_element_by_link_text method, you won't find a button, you will find a link element (a). <a href="http://selenium-python.readthedocs.io/locating-elements.html#locating-hyperlinks-by-link-text" rel="nofollow">Reference</a>.</p>
<p>If you want to get that button, you could use:</p>
<pre><code>driver.find_el... | 0 | 2016-06-11T21:26:00Z | [
"python",
"selenium"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.