title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
how to edit entire field values of CSV in Python? | 39,521,744 | <p>I am trying to manipulate CSV data like this</p>
<pre><code>ID,val1,val2,data1,val3,val4
BIGINT,BOOL,INT,VARCHAR,INT,BIGINT
10000,'F',1,'batman',1,0
20000,'T',0,'robin',1,1
30000,'T',1,'joker',0,1
</code></pre>
<p>to</p>
<pre><code>ID,val1,val2,data1,val3,val4
BIGINT,BOOL,BOOL,VARCHAR,BOOL,BIGINT
10000,'F','T','b... | 0 | 2016-09-15T23:24:14Z | 39,521,808 | <p>looks like your indentation is wrong for the write statements. </p>
<pre><code>with open('input.csv', 'rb') as f:
reader1 = csv.reader(f)
reader1.next()
reader1.next()
with open('test.csv', 'wb') as fr:
for row in reader1:
for key in index_list:
if row[key]=='1'... | 0 | 2016-09-15T23:32:17Z | [
"python",
"csv"
] |
how to edit entire field values of CSV in Python? | 39,521,744 | <p>I am trying to manipulate CSV data like this</p>
<pre><code>ID,val1,val2,data1,val3,val4
BIGINT,BOOL,INT,VARCHAR,INT,BIGINT
10000,'F',1,'batman',1,0
20000,'T',0,'robin',1,1
30000,'T',1,'joker',0,1
</code></pre>
<p>to</p>
<pre><code>ID,val1,val2,data1,val3,val4
BIGINT,BOOL,BOOL,VARCHAR,BOOL,BIGINT
10000,'F','T','b... | 0 | 2016-09-15T23:24:14Z | 39,535,445 | <p>You can use <code>pandas</code> and replace all the values as desired. it would look something like:</p>
<pre><code>from StringIO import StringIO
import pandas as pd
TESTDATA = StringIO("""BIGINT,BOOL,INT,VARCHAR,INT
10000,'F',1,'batman',1
20000,'T',0,'robin',1
... | 0 | 2016-09-16T15:44:37Z | [
"python",
"csv"
] |
List converted to Dropdown in Flask/WTForms | 39,521,749 | <p>Basically I have a list in Python and would like to programmatically call on and create a dropdown form from this list using WTForms into an HTML doc. I can't figure out what I am missing here when trying to use the <strong>SelectField</strong> approach in WTForms. The list is within "updatef". </p>
<p>I get the e... | 0 | 2016-09-15T23:24:40Z | 39,522,040 | <p><code>choices</code> has to be a list of 2 value tuples such as <code>[(1,'Daily'),(2,'Weekly')]</code> - your error seems to suggest you might only have a list of values.</p>
| 0 | 2016-09-16T00:04:09Z | [
"python",
"flask",
"jinja2",
"wtforms",
"flask-wtforms"
] |
Creating a dictionary from a dictionary using a tuple Python | 39,521,817 | <p>given a dictionary with N keys and a tuple of K keys, K<=N is there a pythonic way to get a dictionary with only the K keys?</p>
<p>ex. </p>
<pre><code>orig_dict = {'key1':'value1', 'key2':'value2', ..., 'keyN':'valueN'}
tuple = ('key2', 'keyM')
newdict = myFunc(orig_dict, tuple)
print newdict
</code></pre>
... | 1 | 2016-09-15T23:34:31Z | 39,521,846 | <p>You can use a dictionary comprehension:</p>
<pre><code>{k:v for k,v in orig_dict.iteritems() if k in tuple_keys}
</code></pre>
<p>Observe:</p>
<pre><code>>>> orig_dict = {'key1':'value1', 'key2':'value2', 'keyN':'valueN'}
>>> tuple_keys = ('key2', 'keyN')
>>> {k:v for k,v in orig_dict.i... | 2 | 2016-09-15T23:38:04Z | [
"python",
"dictionary",
"tuples"
] |
Creating a dictionary from a dictionary using a tuple Python | 39,521,817 | <p>given a dictionary with N keys and a tuple of K keys, K<=N is there a pythonic way to get a dictionary with only the K keys?</p>
<p>ex. </p>
<pre><code>orig_dict = {'key1':'value1', 'key2':'value2', ..., 'keyN':'valueN'}
tuple = ('key2', 'keyM')
newdict = myFunc(orig_dict, tuple)
print newdict
</code></pre>
... | 1 | 2016-09-15T23:34:31Z | 39,521,865 | <p>Just use a comprehension:</p>
<pre><code>tple = ('key2', 'keyM')
{k: orig_dict[k] for k in tple}
</code></pre>
<p>Or if you prefer functional:</p>
<pre><code>from operator import itemgetter
dict(zip(tple, itemgetter(*tple)(orig_dict)))
</code></pre>
<p>What is more <em>pythonic</em> is debatable, what is defini... | 2 | 2016-09-15T23:40:02Z | [
"python",
"dictionary",
"tuples"
] |
Creating a dictionary from a dictionary using a tuple Python | 39,521,817 | <p>given a dictionary with N keys and a tuple of K keys, K<=N is there a pythonic way to get a dictionary with only the K keys?</p>
<p>ex. </p>
<pre><code>orig_dict = {'key1':'value1', 'key2':'value2', ..., 'keyN':'valueN'}
tuple = ('key2', 'keyM')
newdict = myFunc(orig_dict, tuple)
print newdict
</code></pre>
... | 1 | 2016-09-15T23:34:31Z | 39,521,929 | <p>Use a dictionary comprehension</p>
<pre><code>orig_dict = {'key1':'value1', 'key2':'value2', 'keyN':'valueN'}
keys = ('key2', 'keyM')
>>> {k:orig_dict[k] for k in keys if k in orig_dict}
{'key2': 'value2'}
</code></pre>
<p>This will be more efficient than iterating over the dictionary's keys and checking... | 1 | 2016-09-15T23:49:02Z | [
"python",
"dictionary",
"tuples"
] |
Listing out names of Python dictionary instances | 39,521,869 | <p>I collected public course data from Udemy and put it all in a json file. Each course has an identifier number under which all the data is stored. I can perfectly list out any details I want, except for these identifier numbers.</p>
<p>How can I list out these numbers themselves? Thanks.</p>
<pre><code>{
"15331... | 0 | 2016-09-15T23:40:28Z | 39,521,901 | <p>Parse the json into a python dict, then loop over the keys</p>
<pre><code>parsed = json.loads(input)
for key in parsed.keys():
print(key)
</code></pre>
| 1 | 2016-09-15T23:45:19Z | [
"python",
"json"
] |
Listing out names of Python dictionary instances | 39,521,869 | <p>I collected public course data from Udemy and put it all in a json file. Each course has an identifier number under which all the data is stored. I can perfectly list out any details I want, except for these identifier numbers.</p>
<p>How can I list out these numbers themselves? Thanks.</p>
<pre><code>{
"15331... | 0 | 2016-09-15T23:40:28Z | 39,521,904 | <p>You want the <code>keys</code> of that dictionnary.</p>
<pre><code>import json
with open('course.json') as json_file:
course=json.load(json_file)
print course.keys()
</code></pre>
<p><br>giving :
<code>[u'616990', u'153318']</code></p>
| 4 | 2016-09-15T23:45:38Z | [
"python",
"json"
] |
How do I get a regex pattern type for MyPy | 39,521,895 | <p>If I compile a regex</p>
<pre><code>>>> type(re.compile(""))
<class '_sre.SRE_Pattern'>
</code></pre>
<p>And want to pass that regex to a function and use Mypy to type check</p>
<pre><code>def my_func(compiled_regex: _sre.SRE_Pattern):
</code></pre>
<p>I'm running into this problem</p>
<pre><code... | 0 | 2016-09-15T23:44:22Z | 39,521,927 | <p>Yeah, the types the <code>re</code> module uses aren't actually accessible by name. You'll need to use the <a href="https://docs.python.org/3/library/typing.html#typing.re" rel="nofollow"><code>typing.re</code></a> types for type annotations instead:</p>
<pre><code>import typing
def my_func(compiled_regex: typing.... | 1 | 2016-09-15T23:48:31Z | [
"python",
"mypy"
] |
How do I get a regex pattern type for MyPy | 39,521,895 | <p>If I compile a regex</p>
<pre><code>>>> type(re.compile(""))
<class '_sre.SRE_Pattern'>
</code></pre>
<p>And want to pass that regex to a function and use Mypy to type check</p>
<pre><code>def my_func(compiled_regex: _sre.SRE_Pattern):
</code></pre>
<p>I'm running into this problem</p>
<pre><code... | 0 | 2016-09-15T23:44:22Z | 39,522,012 | <p><code>mypy</code> is very strict in terms of what it can accept, so you can't just generate the types or use import locations that it doesn't know how to support (otherwise it will just complain about library stubs for the syntax to a standard library import it doesn't understand). Full solution:</p>
<pre><code>im... | 2 | 2016-09-16T00:00:55Z | [
"python",
"mypy"
] |
How set permissions for create action in rest_framework | 39,521,924 | <p>I want to set perissions for the create action (post). And I dont know hot to do it.</p>
<p>This is my code:</p>
<p>In permissions.py</p>
<pre><code>class IsAdmin(permissions.BasePermission):
def has_object_permission(self, request, view, category):
if request.user.role == "admin":
return ... | 0 | 2016-09-15T23:48:24Z | 39,521,957 | <p>Just set the <code>permission_classes</code> on the viewset directly:</p>
<pre><code>class CategoryViewSet(viewsets.ModelViewSet):
queryset = Category.objects.all()
serializer_class = CategorySerializer
permission_classes = [IsAccountAdminOrReadOnly]
</code></pre>
| 0 | 2016-09-15T23:53:39Z | [
"python",
"django",
"rest",
"django-rest-framework"
] |
How set permissions for create action in rest_framework | 39,521,924 | <p>I want to set perissions for the create action (post). And I dont know hot to do it.</p>
<p>This is my code:</p>
<p>In permissions.py</p>
<pre><code>class IsAdmin(permissions.BasePermission):
def has_object_permission(self, request, view, category):
if request.user.role == "admin":
return ... | 0 | 2016-09-15T23:48:24Z | 39,522,111 | <p>Already, I have solved it, just i've change in my permissions.py file, the method:</p>
<pre><code> def has_object_permission(self, request, view, category):
if request.user.role == "admin":
return request.user.role == "admin"
return False
</code></pre>
<p>for this method:</p>
<pre><code> def... | 0 | 2016-09-16T00:15:42Z | [
"python",
"django",
"rest",
"django-rest-framework"
] |
Django: How can I get the foreign key's class from a classmethod in the referred-to class? | 39,521,948 | <p>I have the following two Django Classes <code>MyClassA</code> and <code>MyClassB</code> in two separate files. <code>MyClassB</code> has a foreign key reference to an instance of <code>MyClassA</code>. <code>MyClassA</code> cannot import the class <code>MyClassB</code>.</p>
<p>my_class_a/models.py:</p>
<pre><code>... | 1 | 2016-09-15T23:52:10Z | 39,522,809 | <p>You can do it like this.</p>
<pre><code>@classmethod
def my_method_a(cls):
from myclass_b.models import MyClassB
# yes, you can have an import here. and it will not
# lead to a cyclic import error
MyClassB.my_method_b()
</code></pre>
<p>The import failure happens only if you add the import to the ... | 1 | 2016-09-16T02:06:52Z | [
"python",
"django",
"foreign-keys",
"static-methods",
"class-method"
] |
Do generators simply make new objects with __iter__ and next functions? | 39,521,964 | <p>I tried to search for this answer on my own, but there was too much noise.</p>
<p>Are generators in python just a convenience wrapper for the user to make an iterator object?</p>
<p>When you define the generator:</p>
<pre><code>def test():
x = 0
while True:
x += 1
yield x
</code></pre>
<p>is python s... | 1 | 2016-09-15T23:54:37Z | 39,522,038 | <p>No -- Generators also provide other methods (<code>.send</code>, <code>.throw</code>, etc) and can be used for more purposes than simply making iterators (e.g. coroutines).</p>
<p>Indeed, <code>generators</code> are an entirely different beast and a core language feature. It'd be very hard (possibly impossible) to... | 2 | 2016-09-16T00:03:41Z | [
"python"
] |
Do generators simply make new objects with __iter__ and next functions? | 39,521,964 | <p>I tried to search for this answer on my own, but there was too much noise.</p>
<p>Are generators in python just a convenience wrapper for the user to make an iterator object?</p>
<p>When you define the generator:</p>
<pre><code>def test():
x = 0
while True:
x += 1
yield x
</code></pre>
<p>is python s... | 1 | 2016-09-15T23:54:37Z | 39,522,039 | <blockquote>
<p>Are generators in python just a convenience wrapper for the user to make an iterator object?</p>
</blockquote>
<p>No. A <code>generator</code> is a function, where as <code>iterators</code> are class. Hence, generator can not be a object of iterator. But in some way you can say that <em>generator is ... | 1 | 2016-09-16T00:03:53Z | [
"python"
] |
Do generators simply make new objects with __iter__ and next functions? | 39,521,964 | <p>I tried to search for this answer on my own, but there was too much noise.</p>
<p>Are generators in python just a convenience wrapper for the user to make an iterator object?</p>
<p>When you define the generator:</p>
<pre><code>def test():
x = 0
while True:
x += 1
yield x
</code></pre>
<p>is python s... | 1 | 2016-09-15T23:54:37Z | 39,522,076 | <p>Nope. Like so:</p>
<pre><code>>>> def test():
... x = 0
... while True:
... x += 1
... yield x
...
>>> type(test)
<type 'function'>
</code></pre>
<p>So what it returns is a function object. Details from there get hairy; the short course is that the code object belonging ... | 2 | 2016-09-16T00:10:14Z | [
"python"
] |
How do we find validation error of linear regression and elastic-net using Scikit-learn and python? | 39,522,079 | <p>When do we use test set and validation set while calculating errors?
I have linear regression and elastic-net models working. I am new to Machine learning with Scikit-learn and Python.</p>
<p><strong>I am trying to solve this problem.</strong>
<a href="http://i.stack.imgur.com/HsQ0F.png" rel="nofollow">Data Set: U... | -2 | 2016-09-16T00:11:05Z | 39,522,933 | <p>You can use the test set when you build the model by use the method of minimizing the errors.After you build the model, you can calculate the actual error by using the validation set and then use the error to correct the parameter.I hope this can help you.</p>
| 0 | 2016-09-16T02:28:57Z | [
"python",
"machine-learning",
"scikit-learn",
"linear-regression"
] |
Python HackerRank Bonetrousle code times out | 39,522,148 | <p>I have been working on the Bonetrousle problem in hacker rank using python. After many hours the below code passes all the test cases except one where it times out. Any suggestions on how I can make the code quicker would be appreciated. I believe the problem is the code that deals with the remainder, I put comments... | 3 | 2016-09-16T00:22:55Z | 39,534,498 | <p>Replace the code between your comments by:</p>
<pre><code>if rem == 0:
remAdded = True
elif boxArr[-1] + 1 > k:
remAdded = False
elif answer != False:
l = len(boxArr)-1
for r in range(l, l-rem, -1):
boxArr[r] += 1
remAdded = True
</code></pre>
<p>This gets rid of the expensive <code>... | 2 | 2016-09-16T14:55:24Z | [
"python",
"algorithm"
] |
Attribute Error when importing dictionary from module to another | 39,522,169 | <p>So I have 4 different classes which I need to combine into one class at the end in a program called "Main" . However whenever I run the Main program, it keeps throwing up an attribute error when it comes to accessing the <code>emp_det</code> dictionary from the <code>Employee</code> class into the other classes so I... | 0 | 2016-09-16T00:26:36Z | 39,522,190 | <p><code>import Employee</code> will look for a module Employee.py. If there is no file called <code>Employee.py</code> then you won't be able to make that import work.</p>
<p>So in the <code>Monthly-Paid Class</code> file you have to do something like:</p>
<p><code>from path.to.employee_file_name import Employee</co... | 0 | 2016-09-16T00:29:18Z | [
"python",
"dictionary",
"python-module"
] |
Flask errorhandler isn't called for view that returns 404 | 39,522,184 | <p>With the following functions, I'd expect the error handler to get called when the view returns 404. But it does not trigger. Why doesn't a 404 error handler get called when a view returns 404?</p>
<pre><code>@app.errorhandler(404)
def error(e):
return render_template('error.html'), 404
@app.route('/error/')
d... | 1 | 2016-09-16T00:28:32Z | 39,522,393 | <p>You aren't triggering the error. You can use <code>abort</code> for that. </p>
<pre><code>from flask import abort
@app.route('/error/')
def error_test():
abort(404)
</code></pre>
| 1 | 2016-09-16T00:59:08Z | [
"python",
"flask"
] |
Flask errorhandler isn't called for view that returns 404 | 39,522,184 | <p>With the following functions, I'd expect the error handler to get called when the view returns 404. But it does not trigger. Why doesn't a 404 error handler get called when a view returns 404?</p>
<pre><code>@app.errorhandler(404)
def error(e):
return render_template('error.html'), 404
@app.route('/error/')
d... | 1 | 2016-09-16T00:28:32Z | 39,522,427 | <p>Error handlers handle errors. If you just <code>return '',404</code> then your function has finished normally, it just returned an 404 HTTP code. There were no errors, so error handler is not called.</p>
<p>In python we report errors with exceptions. If something goes wrong, you throw it. Flask has special base exc... | 1 | 2016-09-16T01:04:45Z | [
"python",
"flask"
] |
GtkFileChooserDialog with image preview | 39,522,192 | <p>How to create an image preview in a <code>GtkFileChooserDialog</code>?</p>
<p>Here is a simple ChooserDialog:</p>
<pre><code>#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
filechooserdialog = Gtk.FileChooserDialog()
filechooserdialog.set_title("FileChooserDialog")... | 0 | 2016-09-16T00:29:24Z | 39,534,472 | <p>GtkFileChooser provides the <a href="https://developer.gnome.org/gtk3/stable/GtkFileChooser.html#gtk-file-chooser-set-preview-widget" rel="nofollow">set_preview_widget</a> function. You create a GtkImage, set it as the preview widget, and update the image whenever the <code>update-preview</code> signal is emitted:</... | 1 | 2016-09-16T14:54:09Z | [
"python",
"gtk"
] |
Is there any way to use TCP/IP communication between a BBB and PC connected only by USB cable? | 39,522,220 | <p>Is there anyway to use TCP/IP communication between a Beaglebone Black and PC connected only by USB cable?</p>
<p>I'm try to create an oscilloscope using a Beaglebone Black ADC connected to a computer using a USB cable.</p>
<p>I know that when I connect my BBB (Beaglebone Black) I can access it by its ip 192.168.7... | 0 | 2016-09-16T00:33:02Z | 39,522,399 | <p>You can send an outgoing ping so you know that a TCP/IP connection can be established. However that is an <em>outgoing</em> connection and you are wanting to accept and <em>incoming</em> connection.</p>
<p>Check your firewall settings on your development machine, if the incoming connection is denied there you will ... | 0 | 2016-09-16T01:00:10Z | [
"python",
"tcp",
"embedded",
"usb"
] |
find the manhatten sum of a dataframe given two points | 39,522,333 | <p>consider the dataframe <code>df</code></p>
<pre><code>df = pd.DataFrame(np.arange(25).reshape(5, 5), list('abcde'), list('ABCDE'))
df
</code></pre>
<p><a href="http://i.stack.imgur.com/46MJj.png" rel="nofollow"><img src="http://i.stack.imgur.com/46MJj.png" alt="enter image description here"></a></p>
<p>and two po... | 0 | 2016-09-16T00:50:28Z | 39,522,476 | <p>I <em>think</em> you can just sum down the first column and across the row. This will double count the bottom left item so you need to remove that one:</p>
<pre><code>s1 = df.ix['a':'d', 'B'].sum()
s2 = df.ix['d', 'B':'E'].sum()
print s1 + s2 - df.ix['d', 'B']
</code></pre>
<p>Or, if you prefer, you can do:</p>
... | 3 | 2016-09-16T01:12:17Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Converting python2 PIL to python3 code | 39,522,544 | <p>A program I'm trying to convert from python2 to python3 uses <code>PIL</code> the python image library.</p>
<p>I try to download a thumbnail from the web to display within a tkinter style gui. Here is, what I think, the offending line of code:</p>
<pre><code># grab the thumbnail jpg.
req = requests.get(video.thumb... | 0 | 2016-09-16T01:22:18Z | 39,522,571 | <p>In this case you can see that the library you have imported doesn't support Python3. This isn't something you can fix from within your own code.</p>
<p>The lack of Python3 support is because PIL has been discontinued for quite some time now. There is a fork that's actively maintained that I would recommend you use ... | 1 | 2016-09-16T01:26:46Z | [
"python",
"python-3.5"
] |
append adding contents to first list item, not adding new items to list | 39,522,578 | <pre><code>def gen(filename):
result=[]
with open(filename) as sample:
for line in sample.read().splitlines():
for ch in line.split():
result.append(ch)
yield ch
return result
</code></pre>
<p>If i pass in "ABCDEF", i get ["ABCDEF"] back in re... | 0 | 2016-09-16T01:27:34Z | 39,522,613 | <p>I think this is what you want:</p>
<pre><code>def gen(filename):
with open(filename) as sample:
for line in sample.read().splitlines():
for ch in line:
yield ch
# Example usage:
for ch in gen('myfile.txt'):
print("Got character '{}'.".format(ch))
</code></pre>
<p>As you... | 1 | 2016-09-16T01:32:51Z | [
"python"
] |
selenium click() skipping | 39,522,579 | <p>I have been doing some work with selenium lately and I am having an issue with the click() function.</p>
<p>Given the following HTML code:</p>
<pre><code> <div id="sendreply">
<input type="submit" class="button norm-green" value=
"Send Message name="sendmessage"> == $0
</div>
<... | 0 | 2016-09-16T01:27:41Z | 39,522,915 | <p>If you've tried all but nothing get success, try using <code>execute_script()</code> as an alternate solution to perform click and get rid from this issue as below :-</p>
<pre><code>driver.execute_script("arguments[0].click()", driver.find_element_by_name('sendmessage'))
</code></pre>
<p><strong>Warning</strong>:-... | 0 | 2016-09-16T02:26:42Z | [
"python",
"selenium-webdriver"
] |
How To Combine Multiple Rows Into One Based on Shared Value in Pandas | 39,522,589 | <p>I have a dataframe that generically looks like this: </p>
<pre><code>df = pd.DataFrame({'Country': ['USA', 'USA', 'Canada', 'Canada'], 'GDP': [45000, 68000, 34000, 46000], 'Education': [5, 3, 7, 9]})
</code></pre>
<p>Giving: </p>
<pre><code> Country Education GDP
0 USA 5 45000
1 ... | 0 | 2016-09-16T01:29:16Z | 39,522,954 | <p>Original DataFrame:</p>
<pre><code>In [150]: df
Out[150]:
Country Education GDP
0 USA 5 45000
1 USA 3 68000
2 Canada 7 34000
3 Canada 9 46000
</code></pre>
<p>Given that <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">each c... | 1 | 2016-09-16T02:31:23Z | [
"python",
"pandas"
] |
How To Combine Multiple Rows Into One Based on Shared Value in Pandas | 39,522,589 | <p>I have a dataframe that generically looks like this: </p>
<pre><code>df = pd.DataFrame({'Country': ['USA', 'USA', 'Canada', 'Canada'], 'GDP': [45000, 68000, 34000, 46000], 'Education': [5, 3, 7, 9]})
</code></pre>
<p>Giving: </p>
<pre><code> Country Education GDP
0 USA 5 45000
1 ... | 0 | 2016-09-16T01:29:16Z | 39,523,913 | <p>The output that you want generally leads to loss of information.</p>
<pre><code>Country Education Education GDP GDP
USA 5 3 45000 68000
</code></pre>
<p>In the above case you would need to keep track of which GDP column corresponds to which Education column.</p>
<... | 1 | 2016-09-16T04:49:12Z | [
"python",
"pandas"
] |
convert pandas timedelta output from days to quarter | 39,522,594 | <p>here is my input:</p>
<pre><code> import pandas as pd
dt_one = pd.to_datetime('2015/5/25') - pd.tseries.offsets.QuarterEnd()
dt_two = pd.to_datetime('2016/9/15') - pd.tseries.offsets.QuarterEnd()
</code></pre>
<p>here is my output:</p>
<pre><code>(dt_two - dt_one)
Out[75]: Timedelta('457 days 00:00:00')
</code>... | 0 | 2016-09-16T01:30:13Z | 39,522,845 | <p>You can calculate the number of quarters like this:</p>
<pre><code>In [106]: dt_one = pd.to_datetime('2015/5/25') - pd.tseries.offsets.QuarterEnd()
...: dt_two = pd.to_datetime('2016/9/15') - pd.tseries.offsets.QuarterEnd()
...:
In [107]: ((dt_two.year - dt_one.year)*12 + (dt_two.month - dt_one.month))/... | 0 | 2016-09-16T02:14:08Z | [
"python",
"pandas",
"timestamp",
"datetimeindex"
] |
Bokeh - check checkboxes with a button/checkbox callback | 39,522,642 | <p>How can I check checkboxes in a CheckBoxGroup by clicking a button or checking a separate checkbox in bokeh?</p>
<p>I am aware of this solution in javascript <a href="http://stackoverflow.com/questions/5229023/jquery-check-uncheck-all-checkboxes-with-a-button">jquery check uncheck all checkboxes with a button</a></... | 0 | 2016-09-16T01:38:10Z | 39,581,694 | <p>I adapted the answer of Bigreddot to this question: <a href="http://stackoverflow.com/questions/39561553/bokeh-widget-callback-to-select-all-checkboxes/39562653#39562653">Bokeh widget callback to select all checkboxes</a> To have a similar effect from a CustomJS callback.</p>
<p>Assuming a Figure "fig" and a list o... | 0 | 2016-09-19T20:36:40Z | [
"javascript",
"python",
"checkbox",
"bokeh"
] |
Filter rows in a CSV file and then sort them based on a column | 39,522,677 | <p>Trying to parse the data file (below) to find only the rows where the user started before a certain date. then order the values from the words column from these rows in ascending order (by start date)</p>
<pre class="lang-none prettyprint-override"><code>id, name, start_date, role, end_date, words
657, mystical, 13... | 1 | 2016-09-16T01:44:00Z | 39,522,794 | <p>Should be fairly simple. Since you need to type convert and do lookup for your key function, a <code>lambda</code> is simplest:</p>
<pre><code>previous_users.sort(key=lambda row: int(row['start_date']))
</code></pre>
<p>A note: Passing <code>previous_users.keys()</code> to <code>DictWriter</code> as the fieldnames... | 0 | 2016-09-16T02:05:16Z | [
"python",
"csv"
] |
Python real time image classification problems with Neural Networks | 39,522,693 | <p>I'm attempting use caffe and python to do real-time image classification. I'm using OpenCV to stream from my webcam in one process, and in a separate process, using caffe to perform image classification on the frames pulled from the webcam. Then I'm passing the result of the classification back to the main thread to... | 24 | 2016-09-16T01:46:46Z | 39,609,210 | <p>One think might happen in your code, that is it works in gpu mode for the first call and on later calls it calculates the classification under cpu mode as it the default mode. On older version of caffe set gpu mode for once was enough, now newer version it needs to set mode everytime. You can try with following chan... | 0 | 2016-09-21T06:44:37Z | [
"python",
"opencv",
"multiprocessing",
"gpgpu",
"caffe"
] |
Python real time image classification problems with Neural Networks | 39,522,693 | <p>I'm attempting use caffe and python to do real-time image classification. I'm using OpenCV to stream from my webcam in one process, and in a separate process, using caffe to perform image classification on the frames pulled from the webcam. Then I'm passing the result of the classification back to the main thread to... | 24 | 2016-09-16T01:46:46Z | 39,738,897 | <p>Try multi threading approach instead of multiprocessing. Spawning processes is slower than spawning into threads. Once they are running, there is not much difference. In your case I think threading approach will benefit as there are so many frames data involved.</p>
| 0 | 2016-09-28T05:44:07Z | [
"python",
"opencv",
"multiprocessing",
"gpgpu",
"caffe"
] |
Python real time image classification problems with Neural Networks | 39,522,693 | <p>I'm attempting use caffe and python to do real-time image classification. I'm using OpenCV to stream from my webcam in one process, and in a separate process, using caffe to perform image classification on the frames pulled from the webcam. Then I'm passing the result of the classification back to the main thread to... | 24 | 2016-09-16T01:46:46Z | 39,766,758 | <p><strong>Some Explanations and Some Rethinks:</strong></p>
<ol>
<li><p>I ran my code below on a laptop with an <code>Intel Core i5-6300HQ @2.3GHz</code> cpu, <code>8 GB RAM</code> and <code>NVIDIA GeForce GTX 960M</code> gpu(2GB memory), and the result was: </p>
<p>Whether I ran the code with caffe running or not(b... | 2 | 2016-09-29T09:38:35Z | [
"python",
"opencv",
"multiprocessing",
"gpgpu",
"caffe"
] |
How to pass a extra parameter using perform_create of django rest framwork? | 39,522,703 | <p>I am using django rest frameworks generic views. I am trying to insert request user name in the author field of post. </p>
<h1>Serializers</h1>
<pre><code>class PostSerializer(serializers.ModelSerializer):
spoter = serializers.PrimaryKeyRelatedField(
queryset= User.objects.all(),
)
class Meta:... | 0 | 2016-09-16T01:47:45Z | 39,525,112 | <p>Depending on what you want to do, you should:</p>
<ul>
<li>Mark the author field as either <code>read_only=True</code> or <code>required=False</code></li>
<li>Set the author field with <a href="http://www.django-rest-framework.org/api-guide/validators/#createonlydefault" rel="nofollow"><code>CreateOnlyDefault</code... | 0 | 2016-09-16T06:34:12Z | [
"python",
"django",
"python-3.x",
"django-rest-framework",
"django-serializer"
] |
Can't install M2Crypto into Linux mint Rafaela | 39,522,846 | <p>I'm trying to install <code>M2Crypto</code> library with <code>pip</code> inside a <code>virtualenv</code>, but I just can't make it work,</p>
<p>I have done <code>sudo apt-get install python-dev</code> and <code>sudo apt-et install python-m2crypto</code> already, they are in the system</p>
<p>Also tried installin... | 0 | 2016-09-16T02:14:12Z | 39,523,290 | <p>I managed to solve it, it was a version issue, just ran:</p>
<pre><code>pip install M2Crypto==0.24.0
</code></pre>
<p>Thank You</p>
| 0 | 2016-09-16T03:20:49Z | [
"python",
"linux",
"swig",
"m2crypto"
] |
Python Thread getting items from Queue - how do you determine thread has not called task_done()? | 39,522,877 | <pre><code>dispQ = Queue.Queue()
stop_thr_event = threading.Event()
def worker (stop_event):
while not stop_event.wait(0):
try:
job = dispQ.get(timeout=1)
job.do_work() # does some work and may put more jobs in the dispQ
dispQ.task_done()
except Queue.Empty, msg... | 1 | 2016-09-16T02:19:45Z | 39,523,961 | <p>Here is the source for Queue.join, it looks like you can just use <code>queue.unfinished_tasks > 0</code> to check if any tasks are running or in queue. You may want to acquire (then release) the lock to ensure that the queue doesn't change while you're checking its status. (I believe) You don't need to do this i... | 1 | 2016-09-16T04:55:31Z | [
"python",
"multithreading",
"queue"
] |
Best way to filter a django QuerySet based on value without name (rank) | 39,522,924 | <p>So I've build a web app with django, using postgres for the database. Using <code>django.contrib.postgres.search.SearchRank</code>, I search for all recipes in my database with the word 'chocolate', and it gives me back a nice sorted QuerySet.</p>
<pre><code>from django.contrib.postgres.search import SearchVector, ... | 0 | 2016-09-16T02:27:15Z | 39,526,163 | <p>you have an error in your filter, if you would like to use additional conditions to your field, you have to do it be double underscore <code>__</code></p>
<p><code>search_recipes.filter(rank__gt=0)</code></p>
| 1 | 2016-09-16T07:39:18Z | [
"python",
"django",
"postgresql"
] |
Digit Pattern matching | 39,522,926 | <p>I have a list:</p>
<pre><code>a = [1, 2, 4, 5, 8, 2, 4, 2, 4, 6, 7]
</code></pre>
<p>I would like to count how many times <code>2, 4</code> appear together </p>
<pre><code>( 2 at index i and 4 at index i+1).
</code></pre>
<p>How can I do that? </p>
| 1 | 2016-09-16T02:27:43Z | 39,523,004 | <p>In order to do that you'd need to check every pair in your given list to see if the pair contains <code>2</code> and <code>4</code>. In Python, you can create pairs by using the <code>zip</code> built-in function. </p>
<p>In order to create adjacent pairs, we supply the list <code>a</code> as the first argument to ... | 0 | 2016-09-16T02:38:22Z | [
"python",
"python-3.x",
"indexing"
] |
Digit Pattern matching | 39,522,926 | <p>I have a list:</p>
<pre><code>a = [1, 2, 4, 5, 8, 2, 4, 2, 4, 6, 7]
</code></pre>
<p>I would like to count how many times <code>2, 4</code> appear together </p>
<pre><code>( 2 at index i and 4 at index i+1).
</code></pre>
<p>How can I do that? </p>
| 1 | 2016-09-16T02:27:43Z | 39,523,395 | <p>Join the list into a string and search for <code>'24'</code>.</p>
<pre><code>>>> a = [1, 2, 4, 5, 8, 2, 4, 2, 4, 6, 7]
>>> ''.join(map(str, a)).count('24')
3
</code></pre>
| 0 | 2016-09-16T03:35:32Z | [
"python",
"python-3.x",
"indexing"
] |
Parse a Directory of json files with python | 39,522,949 | <p>I have been looking for how to do this but I cannot.
I have a directory of .json files and I am supposed to parse each one.
I know I have to use glob and os.
I feel like the logic behind it is loop over the directory and when reading each file extract the data that is needed, but I cannot find anywhere to help me n... | 0 | 2016-09-16T02:31:09Z | 39,523,013 | <p>Assuming that your JSON files are named with a <code>.json</code> extension and that they are in the same directory that you are running the script from:</p>
<pre><code>import json
from glob import glob
data = []
for file_name in glob('*.json'):
with open(file_name) as f:
data.append(json.load(f))
</co... | 0 | 2016-09-16T02:40:01Z | [
"python",
"json",
"parsing"
] |
List all customers via stripe API | 39,522,963 | <p>I'm trying to get a list of all the customers in my stripe account but am limited by pagination, wanted to know what the most pythonic way to do this.</p>
<pre><code>customers = []
results = stripe.Customer.list(limit=100)
print len(results.data)
for c in results:
customers.append(c)
results = stripe.Customer.l... | 1 | 2016-09-16T02:32:25Z | 39,528,416 | <p>Stripe's Python library has an "auto-pagination" feature:</p>
<pre><code>customers = stripe.Customer.list(limit=100)
for customer in customers.auto_paging_iter():
# Do something with customer
</code></pre>
<p>The <code>auto_paging_iter</code> method will iterate over every customer, firing new requests as need... | 2 | 2016-09-16T09:47:09Z | [
"python",
"stripe-payments"
] |
How to speed up a script to get backups from routers in python | 39,522,975 | <p>I have a script that gets IPs from a text file, and then get a backup or introduces commands to routers or switches(ASR,Nexus,Catalyst,etc). I am using Python version 2.7.12 and telnetlib module.
The problem is that i takes 1 hour for just 200 devices, so it is not very efficient. Maybe running multiple processes i... | -1 | 2016-09-16T02:33:39Z | 39,550,522 | <p>Well after 1 day of struggle, i did it. Netmiko is a great module but only works for ssh and i need it telnet access, so i stuck with this one.
Here is the final code. Hope someone think is usefull. I get the IPs of the devices via a file text that that can have different numbers of columns. </p>
<pre><code>from m... | 0 | 2016-09-17T18:48:46Z | [
"python",
"networking",
"backup",
"cisco"
] |
Receiving TypeError: can only concatenate list (not "NoneType") to list | 39,522,985 | <p>For my computer science class, we are learning recursion and I'm having difficulty understanding it. One part of my assignment is to create an algorithm that returns another list that is identical to L except all elements of e are removed. However, I am currently coming up with a </p>
<blockquote>
<p>TypeError:... | 1 | 2016-09-16T02:35:50Z | 39,523,063 | <p>You are checking for <code>L</code> being an empty list, and you are checking whether the first element of <code>L</code> is not equal to <code>e</code> (and thus part of your result), but as soon as an element is equal to <code>e</code>, your function returns nothing, meaning that it returns a default value of <cod... | 1 | 2016-09-16T02:47:07Z | [
"python",
"functional-programming"
] |
Matplotlib: animation for audio player cursor (sliding vertical line) with blitting looks broken on WxPython | 39,523,011 | <p>I am building up a project that requires an audio player for very specific purposes. I'm currently using WxPython, Matplotlib and PyAudio packages. I'm also using Matplotlib's WXAgg backend (<code>backend_wxagg</code>).</p>
<p>The basic idea is very simple: the <strong>audio data will be plotted on the main window ... | 0 | 2016-09-16T02:39:36Z | 39,650,382 | <p>After more research, I finally found out that the solution was to call the <code>draw()</code> method of canvas object before effectively copying from bbox. Thus, the middle line here is the answer (the other ones serve only as a reference to the correct spot to place the fix):</p>
<pre><code> (...)
self.Lay... | 0 | 2016-09-22T23:33:07Z | [
"python",
"animation",
"matplotlib",
"wxpython",
"blit"
] |
Web-Scraping with Python on Canopy | 39,523,055 | <p>I'm having trouble with this line of code in which I want to print the 4 stock prices for the companies listed. My issue is that, while there are no errors when I run it, the code only prints out empty brackets where the stock prices should go. This is the source of my confusion. </p>
<pre><code>import urllib2
impo... | 2 | 2016-09-16T02:45:59Z | 39,530,003 | <p>Because you don't pass the variable:</p>
<pre><code> url = "http://money.cnn.com/quote/quote.html?symb=' +symbolslist[i] + '"
^^^^^
a string not the list element
</code></pre>
<p>Use <em>str.format</em>:<... | 1 | 2016-09-16T11:07:53Z | [
"python",
"web-scraping",
"canopy"
] |
Django load resources on startup | 39,523,075 | <p>How can I load resources from mysql database when Django starts up and put it in memory (Redis) to use by all the applications. </p>
<p>I have seen this [<a href="https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready]" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/applicatio... | 2 | 2016-09-16T02:48:24Z | 39,523,820 | <p>Since you are only loading into redis rather than creating instances of models that are held in memory and shared by all apps in your website, perhaps the best way is to use a <a class='doc-link' href="http://stackoverflow.com/documentation/django/1661/management-commands/5367/creating-and-running-a-management-comma... | 1 | 2016-09-16T04:37:18Z | [
"python",
"django",
"apache",
"redis"
] |
Pandas relabel rows to recognize unique values within a groupby | 39,523,085 | <p>I have a <code>Pandas DataFrame</code> that describes some version testing and looks like this:</p>
<pre><code>MailingName EmailSubject MailingID
Promo_v1s1 Hello! A8FEFE
Promo_v1s2 Line 2 A8FEFE
Promo_v2s1 Line 2 A8FEFE
Promo_v2s2 Yo! A8FEFE
Promo_v2S3 Hell... | 0 | 2016-09-16T02:50:10Z | 39,523,246 | <pre><code>In [229]: df
Out[229]:
MailingName EmailSubject MailingID
0 Promo_v1s1 Hello! A8FEFE
1 Promo_v1s2 Line 2 A8FEFE
2 Promo_v2s1 Line 2 A8FEFE
3 Promo_v2s2 Yo! A8FEFE
4 Promo_v2S3 Hello! A8FEFE
5 deal_v2s1 Line 2 bbb
6 deal_v2s2 Yo!... | 1 | 2016-09-16T03:15:09Z | [
"python",
"pandas"
] |
Python for Windows hang while calling a function of MinGW-w64 compiled library | 39,523,088 | <p>I'm using ctypes to call a function of a MinGW-w64 compiled library.</p>
<p>C code:</p>
<pre><code>#include <stdio.h>
int hello()
{
printf("Hello world!\n");
return 233;
}
</code></pre>
<p>Python Code:</p>
<pre><code>from ctypes import *
lib = CDLL("a.dll")
hello = lib.hello
hello.restype = c_int
... | 2 | 2016-09-16T02:50:42Z | 39,770,350 | <p>Use 'x86_64-w64-mingw32-gcc' or 'i686-w64-mingw32-gcc' instead of 'gcc' in msys!</p>
<p>The 'gcc' command calls x86_64-pc-msys-gcc.</p>
| 0 | 2016-09-29T12:27:57Z | [
"python",
"c",
"mingw",
"ctypes",
"msys"
] |
What code can I use if I have ten numbers and I want to produce 1000 different randomly shuffled orders of the the ten numbers | 39,523,112 | <p>I can use this to find all of the possible options, however, I want a random sample of 1000 from this set:</p>
<pre><code>items = range(1,11)
//from itertools import permutations
//for p in permutations(items):
print(p)
</code></pre>
| 0 | 2016-09-16T02:54:07Z | 39,523,500 | <p>Here is a suggested solution. Based on your requirements, the list of 10 numbers are already chosen, and you just want to have a list that will have those 10 numbers shuffled in 1000 unique ways. So below, I have a list of 10 numbers. The random.sample(num_list,10), will select those 10 numbers at random, and create... | 0 | 2016-09-16T03:53:40Z | [
"python",
"random",
"permutation",
"shuffle",
"sample"
] |
What code can I use if I have ten numbers and I want to produce 1000 different randomly shuffled orders of the the ten numbers | 39,523,112 | <p>I can use this to find all of the possible options, however, I want a random sample of 1000 from this set:</p>
<pre><code>items = range(1,11)
//from itertools import permutations
//for p in permutations(items):
print(p)
</code></pre>
| 0 | 2016-09-16T02:54:07Z | 39,535,529 | <p>Since <code>set</code> guarantees the uniqueness of its elements, you can generate permutations via <code>random.sample()</code> and attempt adding the result until the size of the set gets up to the desired quantity:</p>
<pre><code>import random
a = range(1,11)
solutions = set()
while len(solutions) < 1000:
... | 0 | 2016-09-16T15:49:29Z | [
"python",
"random",
"permutation",
"shuffle",
"sample"
] |
What code can I use if I have ten numbers and I want to produce 1000 different randomly shuffled orders of the the ten numbers | 39,523,112 | <p>I can use this to find all of the possible options, however, I want a random sample of 1000 from this set:</p>
<pre><code>items = range(1,11)
//from itertools import permutations
//for p in permutations(items):
print(p)
</code></pre>
| 0 | 2016-09-16T02:54:07Z | 39,536,994 | <p>Unfortunately, Python's permutation module only provides a way to iterate through the 3-million-plus permutations, and not a way to pick one arbitrarily by order. You'll need something like this:</p>
<pre><code>def kthperm(S, k):
P = []
while S != []:
f = math.factorial(len(S)-1)
i = int(ma... | 0 | 2016-09-16T17:20:15Z | [
"python",
"random",
"permutation",
"shuffle",
"sample"
] |
How to use python split? | 39,523,115 | <p>I have some data like that:</p>
<p><img src="http://i.stack.imgur.com/6Jgf7.jpg" alt="enter image description here"></p>
<p>I use split function process data into list.I want to make some data mining in this training set,but I don't know how to separate data as futures like this in python:</p>
<p><img src="http:/... | -1 | 2016-09-16T02:54:59Z | 39,545,695 | <p>You said that the documentation says</p>
<pre><code>str.split(str="", num=string.count(str))
</code></pre>
<p>What you're missing is that the the first instance of <code>str</code> in this definition is the delimiter for splitting.</p>
<p>Your error is that in this:</p>
<pre><code> train_set['zi_id'][i].split('... | 0 | 2016-09-17T10:23:29Z | [
"python",
"machine-learning"
] |
How much overhead does python numpy tolist() add? | 39,523,210 | <p>I am using a python program that uses numpy array as standard data type for arrays. For the heavy computation I pass the arrays to a C++ library. In order to do so, I use <a href="https://github.com/pybind/pybind11" rel="nofollow">pybind</a>. However, I am required to use python <code>list</code>. I do the conversio... | 0 | 2016-09-16T03:09:37Z | 39,523,454 | <p>A lot. For simple built-in types, you can use <code>sys.getsizeof</code> on an object to determine the memory overhead associated with that object (for containers, this does not include the values stored in it, only the pointers used to store them).</p>
<p>So for example, a <code>list</code> of 100 smallish <code>i... | 3 | 2016-09-16T03:47:07Z | [
"python",
"c++",
"arrays",
"numpy",
"wrapper"
] |
How much overhead does python numpy tolist() add? | 39,523,210 | <p>I am using a python program that uses numpy array as standard data type for arrays. For the heavy computation I pass the arrays to a C++ library. In order to do so, I use <a href="https://github.com/pybind/pybind11" rel="nofollow">pybind</a>. However, I am required to use python <code>list</code>. I do the conversio... | 0 | 2016-09-16T03:09:37Z | 39,523,462 | <p>Yes it will be new copy. The data layout for an array is very different from that of a list.</p>
<p>An array has attributes like shape and strides, and a 1d data buffer that contains the elements - just a contiguous set of bytes. It's the other attributes and code that treats them as floats, int, strings, 1d, 2d ... | 3 | 2016-09-16T03:47:56Z | [
"python",
"c++",
"arrays",
"numpy",
"wrapper"
] |
Django - ImportError: No module named apps | 39,523,214 | <p>I am trying out the Django tutorial on the djangoproject.com website, but when I reach the part where I do the first "makemigrations polls" I keep getting this error:</p>
<blockquote>
<p>ImportError: No module named apps</p>
</blockquote>
<pre>
Traceback (most recent call last):
File "manage.py", line 22, in
... | 0 | 2016-09-16T03:10:14Z | 39,531,859 | <p>You need to install required packages in your virtualenv to run Django project. First and foremost create virtualenv for your project.</p>
<pre><code>virtualenv env #For python 2.7
virtualenv -p python3 env #For python 3.4
</code></pre>
<p>Actiavte env to install your requirements</p>
<pre><code>source env/bin... | 1 | 2016-09-16T12:44:22Z | [
"python",
"django",
"python-2.7",
"django-models"
] |
Django - ImportError: No module named apps | 39,523,214 | <p>I am trying out the Django tutorial on the djangoproject.com website, but when I reach the part where I do the first "makemigrations polls" I keep getting this error:</p>
<blockquote>
<p>ImportError: No module named apps</p>
</blockquote>
<pre>
Traceback (most recent call last):
File "manage.py", line 22, in
... | 0 | 2016-09-16T03:10:14Z | 39,537,105 | <p>There is an error in the tutorial.</p>
<p>It instructs to add <code>polls.apps.PollsConfig</code> in the <code>INSTALLED_APPS</code> section of the <code>settings.py</code> file. I changed it from <code>polls.apps.PollsConfig</code> to simply <code>polls</code> and that did the trick. I was able to successfully mak... | 0 | 2016-09-16T17:27:12Z | [
"python",
"django",
"python-2.7",
"django-models"
] |
Django - ImportError: No module named apps | 39,523,214 | <p>I am trying out the Django tutorial on the djangoproject.com website, but when I reach the part where I do the first "makemigrations polls" I keep getting this error:</p>
<blockquote>
<p>ImportError: No module named apps</p>
</blockquote>
<pre>
Traceback (most recent call last):
File "manage.py", line 22, in
... | 0 | 2016-09-16T03:10:14Z | 39,537,343 | <p>Your problem is that your Django version does not match the version of the tutorial.</p>
<p>In Django 1.9+, the startapp command automatically creates an app config class, so <a href="https://docs.djangoproject.com/en/1.9/intro/tutorial02/#activating-models" rel="nofollow">the tutorial</a> asks you to add <code>pol... | 0 | 2016-09-16T17:43:37Z | [
"python",
"django",
"python-2.7",
"django-models"
] |
Update AWS Lambda API Key Usage Plans with boto3 | 39,523,225 | <p>I have an API Key associated with a particular usage plan. How do I use <code>boto3</code> to update the usage plan to another usage plan?</p>
<p>I've tried the following methods:</p>
<p><a href="http://boto3.readthedocs.io/en/latest/reference/services/apigateway.html#APIGateway.Client.update_usage_plan" rel="nofo... | 0 | 2016-09-16T03:11:50Z | 39,538,899 | <p>You are looking for <a href="http://boto3.readthedocs.io/en/latest/reference/services/apigateway.html#APIGateway.Client.create_usage_plan_key" rel="nofollow">create_usage_plan_key</a></p>
<p>i.e.</p>
<pre><code>response = client.create_usage_plan_key(
usagePlanId='12345',
keyId='[API_KEY_ID]',
keyType=... | 0 | 2016-09-16T19:32:03Z | [
"python",
"amazon-web-services",
"aws-api-gateway",
"boto3"
] |
BAD REQUEST 400, when trying to access JSON | 39,523,306 | <p>I've been working on a bot for <code>Discord</code> in <code>discord.py</code> (not related) and I'm trying to pull from a server so I can interpret it, however, I'm getting a</p>
<blockquote>
<p>BAD REQUEST 400</p>
</blockquote>
<p>when trying to actually pull from the server. I've tried to add a header to spec... | 0 | 2016-09-16T03:23:16Z | 39,523,536 | <p>I wouldn't use .json() at the end of the request, in case you want to check the status_code for a bad request first.</p>
<pre><code>response = requests.get(url, headers=headers)
if response.status_code == 200:
print response.content
</code></pre>
<p>And if you want to do something with the dict you can use jso... | 2 | 2016-09-16T03:58:07Z | [
"python",
"json",
"python-requests"
] |
User defined aggregation function for spark dataframe (python) | 39,523,317 | <p>I have the below spark dataframe, where id is int and attributes is a list of string</p>
<pre><code>id | attributes
1 | ['a','c', 'd']
2 | ['a', 'e']
1 | ['e', 'f']
1 | ['g']
3 | ['a', 'b']
2 | ['e', 'g']
</code></pre>
<p>I need to perform an aggregation, where the attributes lists for each id are concatenat... | 0 | 2016-09-16T03:24:56Z | 39,523,836 | <p>One way is to create a new frame, using reduceByKey:</p>
<pre><code>>>> df.show()
+---+----------+
| id|attributes|
+---+----------+
| 1| [a, c, d]|
| 2| [a, e]|
| 1| [e, f]|
| 1| [g]|
| 3| [a, b]|
| 2| [e, g]|
+---+----------+
>>> custom_list = df.rdd.reduceByKey(lambda x... | 1 | 2016-09-16T04:39:15Z | [
"python",
"apache-spark",
"spark-dataframe",
"udf"
] |
Flask Security- check what Roles a User has | 39,523,394 | <p>I was looking at the flask-security api and i dont see any function that returns the list of roles a specific User has. Is there anyway to return a list of Roles a user has?</p>
| -1 | 2016-09-16T03:35:22Z | 39,524,988 | <p>If you look at how the <a href="https://github.com/mattupstate/flask-security/blob/develop/flask_security/core.py#L318" rel="nofollow"><code>has_role(...)</code> method</a> has been defined, it simply iterates through <code>self.roles</code>. So the <code>roles</code> attribute in the user is a list of <code>Role</c... | 1 | 2016-09-16T06:25:35Z | [
"python",
"flask",
"flask-sqlalchemy",
"flask-security"
] |
Receiving a KeyError: '0_0' for my python program | 39,523,479 | <p>I'm was working on this question (it's from Leetcode):</p>
<blockquote>
<p>"Given an integer matrix, find the length of the longest increasing
path.</p>
<p>From each cell, you can either move to four directions: left, right, up or down.
You may NOT move diagonally or move outside of the
boundary (i.e.... | 0 | 2016-09-16T03:49:29Z | 39,523,566 | <p>You are trying to access a key (<code>0_0</code>) that doesn't exist yet in the dictionary.</p>
<p>You have to check beforehand if it exists, I'd suggest the <code>in</code> keyword:</p>
<pre><code>key = str(x_coor) + "_" + str(y_coor)
if key in traverse.traveled and traverse.traveled[key]:
# ...
</code></pre>... | 1 | 2016-09-16T04:02:23Z | [
"python",
"algorithm",
"python-2.7",
"data-structures"
] |
jinja2 itterate through list of tuples | 39,523,485 | <p>I have a list of tuples called <em>items</em>:</p>
<pre><code>[ (1,2), (3,4), (5,6), (7,8) ]
</code></pre>
<p>I thought I could iterate though using, but it's not working:</p>
<pre><code># Code
output = template.render( items )
# Tempalte
{% for item in items %}
{{ item[0] }};
{{ item[1] }};
{% endfor %}... | 0 | 2016-09-16T03:50:23Z | 39,523,551 | <p>From the <a href="http://jinja.pocoo.org/docs/dev/api/#jinja2.Template.render" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>render([context])</p>
<p>This method accepts the same arguments as the dict
constructor: A dict, a dict subclass or some keyword arguments. If no
arguments are given the co... | 2 | 2016-09-16T04:00:32Z | [
"python",
"jinja2"
] |
Nginx will not load Flask static files | 39,523,533 | <p>New flask/nginx/uWSGI server. Application loads and functions as expected but non of the html/css templates will load. Using developer tools in Chrome shows the pages are not being returned. </p>
<p>"tail -f /var/log/nginx/error.log" says the file or directory does not exist. But it appears to be the correct path. ... | 0 | 2016-09-16T03:57:25Z | 39,527,071 | <p>In your nginx configuration use an absolute path to your <code>static</code> directory. <code>static</code> should be in the path:</p>
<pre><code>location ^~ /static/ {
root /full/path/to/app/static/;
}
</code></pre>
| 0 | 2016-09-16T08:37:09Z | [
"python",
"nginx",
"flask",
"uwsgi"
] |
Nested for-loop and appending to empty objects | 39,523,665 | <p>I am providing values to a website filter In order to generate different html which l parse. I want to save each page source to a different Python object in order to distinguish the data. I have a list of empty objects which l will append to. parsing page source,and want to save each page source to its own Python ob... | 0 | 2016-09-16T04:17:53Z | 39,524,368 | <p>Your statement</p>
<pre><code>counter=counter+1
</code></pre>
<p>is not within the for loop.</p>
<p>You need to indent it at the same level as the previous line, so that counter is incremented each time around the loop</p>
| 0 | 2016-09-16T05:37:33Z | [
"python",
"nested-loops"
] |
Missing class in beautifulsoup | 39,523,680 | <p>I am attempting to grab a div on the MTA info page. When I grab the html and parse it with BeautifulSoup it seems to be missing some data.</p>
<p>Here is my code so far</p>
<pre><code>from bs4 import BeautifulSoup
import urllib # access the web
# SUBWAY STATUS PROJECT
userURL = "http://www.mta.info" # MTA SITE
h... | 0 | 2016-09-16T04:19:35Z | 39,524,231 | <p>In the subchart variable look for the elements with the class subwayCategory and store the values of the attribute id.
For ex: from this part of the data</p>
<pre><code><div style="float: left; width: 220px; border-bottom: 1px solid #7B7B98; padding: 4px 0;">
<div class="span-11"><img alt="1 2 3 Sub... | 0 | 2016-09-16T05:27:09Z | [
"python",
"html",
"parsing",
"beautifulsoup"
] |
Missing class in beautifulsoup | 39,523,680 | <p>I am attempting to grab a div on the MTA info page. When I grab the html and parse it with BeautifulSoup it seems to be missing some data.</p>
<p>Here is my code so far</p>
<pre><code>from bs4 import BeautifulSoup
import urllib # access the web
# SUBWAY STATUS PROJECT
userURL = "http://www.mta.info" # MTA SITE
h... | 0 | 2016-09-16T04:19:35Z | 39,528,624 | <p>The data is retrieved with an ajax request, you can get the info in <em>json</em> format, the only thing you need to pass it a <em>timestamp</em> which you can get with <em>time.time()</em> then just parse it with the <a href="https://docs.python.org/2/library/json.html" rel="nofollow">json</a> library:</p>
<pre><... | 0 | 2016-09-16T09:57:00Z | [
"python",
"html",
"parsing",
"beautifulsoup"
] |
Python Bisect Search- abs() causing failure | 39,523,798 | <p>So I am attempting to implement a <strong>bisection search algorithm</strong> in Python that returns an "optimal" savings rate.</p>
<p>I've tried creating several different functions, and I don't understand why the program gets caught in an infinite loop. I do know that the abs(current_savings - down_payment) is wh... | 0 | 2016-09-16T04:33:50Z | 39,627,788 | <p>I was confused in the same problem and finally found a solution. Try resetting initial_salary back to annual_salary inside the first while loop within your bisection function, else that would just keep on increasing every time you hit six months on the inner loop. Does that work?</p>
| 0 | 2016-09-21T23:01:49Z | [
"python",
"python-3.x",
"bisection"
] |
Process a list in a Dataframe column | 39,523,900 | <p>I created a DataFrame <code>neighbours</code> using <code>sim_measure_i</code> which is also a DataFrame.</p>
<pre><code>neighbours= sim_measure_i.apply(lambda s: s.nlargest(k).index.tolist(), axis =1)
</code></pre>
<p><code>neighbours</code> looks like this: </p>
<pre><code>1500 [0, 1, 2, 3... | 1 | 2016-09-16T04:47:31Z | 39,524,002 | <p>You can try a nested loop:</p>
<pre><code>for i in range(neighbours.shape[0]): #iterate over each row
for j in range(len(neighbours['neighbours_lists'].iloc[i])): #iterate over each element of the list
a = neighbours['neighbours_lists'].iloc[i][j] #access the element of the list index j in cell location... | 1 | 2016-09-16T05:01:58Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Process a list in a Dataframe column | 39,523,900 | <p>I created a DataFrame <code>neighbours</code> using <code>sim_measure_i</code> which is also a DataFrame.</p>
<pre><code>neighbours= sim_measure_i.apply(lambda s: s.nlargest(k).index.tolist(), axis =1)
</code></pre>
<p><code>neighbours</code> looks like this: </p>
<pre><code>1500 [0, 1, 2, 3... | 1 | 2016-09-16T04:47:31Z | 39,524,060 | <p>Original Data Frame:</p>
<pre><code>In [68]: df
Out[68]:
test_case_id neighbours_lists
0 1500 [0, 1, 2, 3, 4]
1 1501 [0, 1, 2, 3, 4]
2 1502 [0, 1, 2, 3, 4]
3 1503 [7230, 12951, 13783, 8000, 18077]
4 ... | 1 | 2016-09-16T05:08:27Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Process a list in a Dataframe column | 39,523,900 | <p>I created a DataFrame <code>neighbours</code> using <code>sim_measure_i</code> which is also a DataFrame.</p>
<pre><code>neighbours= sim_measure_i.apply(lambda s: s.nlargest(k).index.tolist(), axis =1)
</code></pre>
<p><code>neighbours</code> looks like this: </p>
<pre><code>1500 [0, 1, 2, 3... | 1 | 2016-09-16T04:47:31Z | 39,524,094 | <p>Say you start with <code>neighbors</code> looking like this.</p>
<pre><code>In [87]: neighbors = pd.DataFrame({'neighbors_list': [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]})
In [88]: neighbors
Out[88]:
neighbors_list
0 [0, 1, 2, 3, 4]
1 [0, 1, 2, 3, 4]
</code></pre>
<p>You didn't specify exactly how the other Data... | 1 | 2016-09-16T05:12:33Z | [
"python",
"pandas",
"numpy",
"dataframe"
] |
Odoo v9 - Using Onchange, how do you clear what is already entered in a field? | 39,523,901 | <p>I am extending product.template, and I've added a field called uom_class. When I change this field when editing a product, I'd like to clear what is entered in the Many2One field called "Unit of Measure" (uom_id in product.template). I am doing this because I am also changing the domain for the uom_id, and the exis... | 0 | 2016-09-16T04:47:32Z | 39,524,063 | <p>Well, I figured this one out. </p>
<p>I just declared</p>
<pre><code>uom_id = False
</code></pre>
<p>For some reason, returning the domain works, but not returning the value. Either that, or I just have no idea what I'm doing and I'm returning the value wrong... which is entirely possible.</p>
| 1 | 2016-09-16T05:08:42Z | [
"python",
"model",
"openerp"
] |
i want to compare my sum of Q2 with the sum of all individual account | 39,523,902 | <p>I want my option 3 work out. I want to compare the sum of Apr, May, Jun with the sum of every individual accounts. (sum of column compare to sum of axis) I keep getting the series lengths must match to compare</p>
<pre><code>import pandas as pd
if __name__ == "__main__":
file_name = "sales_rossetti.xlsx" ... | -2 | 2016-09-16T04:47:50Z | 39,531,489 | <p>If you print out the result of <code>df[my_columns].sum()</code> and <code>df[all_columns].sum(axis=1, skipna=None, level=None, numeric_only=True)</code> you would probably be able to debug it for yourself.</p>
<p>My guess is that because you have different values for skipna the first series has dropped some rows s... | 0 | 2016-09-16T12:25:59Z | [
"python",
"pandas"
] |
Is there any issue with this Python script i am using it through sikuli? its not giving me the correct time | 39,523,914 | <p>When I measure the time manually, it is less than the time that I got through this script:</p>
<pre><code>import time import os
def getTimes():
try:
times = []
if(exists("1472205483589.png",60)):
click("1472192774056.png")
wait("1472040968178.png",10)
click("14... | 0 | 2016-09-16T04:49:36Z | 39,540,065 | <p>By using time.time(), you are actually returning a number of seconds--the difference between "the epoch" and now. (The epoch is the same as <code>gmtime(0)</code>). Instead, try using <code>datetime.now()</code> which will give you a datetime object. You can add and subtract datetime objects freely, resulting in a t... | 0 | 2016-09-16T21:05:48Z | [
"python",
"sikuli"
] |
Analyzing a stack sort algorithm's time complexity | 39,523,947 | <p>I've been working through problems in Cracking the Coding Interview to prepare for some interviews. I was able to solve the stack sort problem but I'm having a really hard time figuring out how to reason about the time complexity. My solution was very similar to the one supplied in the book and I have tested it quit... | 0 | 2016-09-16T04:54:23Z | 39,524,066 | <p>This may be an over-simplified approach to algorithm analysis, but whenever I see a nested loop, I think n^2. Three loops nested -- n^3, etc. As a rule of thumb for simple programs, count the nested loops. This is a pretty helpful tutorial: <a href="http://cs.lmu.edu/~ray/notes/alganalysis/" rel="nofollow">http://cs... | 1 | 2016-09-16T05:09:13Z | [
"python",
"algorithm",
"sorting",
"stack",
"big-o"
] |
Analyzing a stack sort algorithm's time complexity | 39,523,947 | <p>I've been working through problems in Cracking the Coding Interview to prepare for some interviews. I was able to solve the stack sort problem but I'm having a really hard time figuring out how to reason about the time complexity. My solution was very similar to the one supplied in the book and I have tested it quit... | 0 | 2016-09-16T04:54:23Z | 39,524,334 | <p>Consider the worst case, in which sorting each and every item in the stack requires completely emptying the temp stack. (This happens when trying to sort a reverse-sorted stack.)</p>
<p>What is the cost of emptying/refilling the temp stack for each item?<br>
How many items are there?</p>
<p>Combining these should ... | 2 | 2016-09-16T05:34:13Z | [
"python",
"algorithm",
"sorting",
"stack",
"big-o"
] |
Why does python's datetime.datetime.strptime('201412', '%Y%m%d') not raise a ValueError? | 39,523,968 | <p>In the format I am given, the date 2014-01-02 would be represented by "20140102". This is correctly parsed with the standard strptime:</p>
<pre><code>>>> datetime.datetime.strptime("20140102", "%Y%m%d")
datetime.datetime(2014, 1, 2, 0, 0)
</code></pre>
<p>In this format, "201412" would <em>not</em> be a ... | 10 | 2016-09-16T04:56:18Z | 39,524,265 | <p>If you look here at how the regex is defined for <code>%m</code> <a href="https://github.com/python/cpython/blob/2d264235f6e066611b412f7c2e1603866e0f7f1b/Lib/_strptime.py#L204">https://github.com/python/cpython/blob/2d264235f6e066611b412f7c2e1603866e0f7f1b/Lib/_strptime.py#L204</a></p>
<p><code>'m': r"(?P<m>1... | 6 | 2016-09-16T05:29:00Z | [
"python",
"datetime",
"strptime"
] |
Why does python's datetime.datetime.strptime('201412', '%Y%m%d') not raise a ValueError? | 39,523,968 | <p>In the format I am given, the date 2014-01-02 would be represented by "20140102". This is correctly parsed with the standard strptime:</p>
<pre><code>>>> datetime.datetime.strptime("20140102", "%Y%m%d")
datetime.datetime(2014, 1, 2, 0, 0)
</code></pre>
<p>In this format, "201412" would <em>not</em> be a ... | 10 | 2016-09-16T04:56:18Z | 39,524,268 | <p>According to the related <a href="https://bugs.python.org/issue22840">issue</a> on the Python tracker, with the example being like such (a bit of a modification to this question, however the concept is the exact same):</p>
<pre><code>>>> datetime.datetime.strptime('20141110', '%Y%m%d').isoformat()
'2014-11... | 5 | 2016-09-16T05:29:15Z | [
"python",
"datetime",
"strptime"
] |
Why does python's datetime.datetime.strptime('201412', '%Y%m%d') not raise a ValueError? | 39,523,968 | <p>In the format I am given, the date 2014-01-02 would be represented by "20140102". This is correctly parsed with the standard strptime:</p>
<pre><code>>>> datetime.datetime.strptime("20140102", "%Y%m%d")
datetime.datetime(2014, 1, 2, 0, 0)
</code></pre>
<p>In this format, "201412" would <em>not</em> be a ... | 10 | 2016-09-16T04:56:18Z | 39,524,276 | <p>This is pretty tricky, but it sounds like <code>strptime</code> just tries to match the string as closely as possible. Python's <code>strptime</code> is the same as C's <code>strptime</code>, and the docs say that padding is optional:</p>
<blockquote>
<p>is the month number [1,12]; leading zeros are permitted but... | 1 | 2016-09-16T05:29:58Z | [
"python",
"datetime",
"strptime"
] |
Requesting and Parsing a JSON with Python | 39,524,008 | <p>I have this code below that I'm working on as part of an AI project. I'm looking to get tags that the user searches and return a url of a post with said tags.</p>
<pre><code>from meya import Component
import requests
import json
API_URL = "https://e621.net/post/index.json?limit=1&tags=rating:s+order:random+{ta... | 0 | 2016-09-16T05:02:37Z | 39,524,111 | <p>Your API returns a dictionary inside a list. Get inside the list first then you can do what you wish with the dictionary.</p>
<pre><code>response = requests.get(API_URL)
foo = json.loads(response.content)
file_url = foo[0].get('file_url')
</code></pre>
<p>If you plan on having multiple dictionaries returned inside... | 1 | 2016-09-16T05:14:22Z | [
"python",
"json",
"parsing"
] |
Requesting and Parsing a JSON with Python | 39,524,008 | <p>I have this code below that I'm working on as part of an AI project. I'm looking to get tags that the user searches and return a url of a post with said tags.</p>
<pre><code>from meya import Component
import requests
import json
API_URL = "https://e621.net/post/index.json?limit=1&tags=rating:s+order:random+{ta... | 0 | 2016-09-16T05:02:37Z | 39,524,131 | <p>I found a temporary workthrough, replacing <code>response.json()['file_url']</code> with <code>response.json()[0]['file_url']</code> works fine in the AI, although it still gives me the error.</p>
| 0 | 2016-09-16T05:16:47Z | [
"python",
"json",
"parsing"
] |
How to obtain a dictionary of the named arguments in a Python function | 39,524,183 | <p>I know it's a common case for people to give a function an arbitrary number of kwargs with <code>**kwargs</code>, and then access them as a dictionary; however, I want to explicitly specify my functions kwargs, but still be able to access them as a dictionary.</p>
<p>This is because I want my function to only recei... | 0 | 2016-09-16T05:22:55Z | 39,524,212 | <p>Simply create a dictionary as normal, retrieving the values of each argument.</p>
<pre><code>def my_func(kwarg1=None, kwarg2=None, kwarg3=None):
kwargs = {'kwarg1':kwarg1, 'kwarg2':kwarg2, 'kwarg3':kwarg3}
for k in kwargs:
# Do my operation
</code></pre>
| 0 | 2016-09-16T05:25:17Z | [
"python",
"dictionary",
"parameters"
] |
How to obtain a dictionary of the named arguments in a Python function | 39,524,183 | <p>I know it's a common case for people to give a function an arbitrary number of kwargs with <code>**kwargs</code>, and then access them as a dictionary; however, I want to explicitly specify my functions kwargs, but still be able to access them as a dictionary.</p>
<p>This is because I want my function to only recei... | 0 | 2016-09-16T05:22:55Z | 39,524,254 | <p>Assuming you have no positional arguments, you could get access to your kwargs via <code>locals</code> if you put it at the top of your function:</p>
<pre><code>def my_func(kwarg1=None, kwarg2=None, kwarg3=None):
# Don't add any more variables before the next line!
kwargs = dict(locals())
for k in kwar... | 1 | 2016-09-16T05:28:25Z | [
"python",
"dictionary",
"parameters"
] |
How to obtain a dictionary of the named arguments in a Python function | 39,524,183 | <p>I know it's a common case for people to give a function an arbitrary number of kwargs with <code>**kwargs</code>, and then access them as a dictionary; however, I want to explicitly specify my functions kwargs, but still be able to access them as a dictionary.</p>
<p>This is because I want my function to only recei... | 0 | 2016-09-16T05:22:55Z | 39,526,190 | <p>This is Python3.3+ code that creates the list of keyword argument names automatically. Just for completness. I would prefer any of the simpler solutions.</p>
<pre><code>import inspect
def my_func(*, kwarg1=None, kwarg2=None, kwarg3=None):
local_vars = locals()
kwargs = {k: local_vars[k] for k in KWARGS_my_... | 1 | 2016-09-16T07:40:51Z | [
"python",
"dictionary",
"parameters"
] |
PYTHON: enter the number of days after today for a future day and display the future day of the week | 39,524,225 | <p>I figured out how to code todays date but i am having trouble finding out how to code the future date, if the future date is larger than the integer 6. In the textbook they entered todays date is 0 so it is Sunday. But for days elapsed since Sunday, they entered 31. The result was "Today is Sunday and the future day... | 0 | 2016-09-16T05:26:40Z | 39,524,261 | <p>Use the modulus operator, <code>%</code>, to divide by 7 and return the remainder of that operation:</p>
<pre><code>>>> 0 % 7
0
>>> 5 % 7
5
>>> 7 % 7
0
>>> 10 % 7
3
</code></pre>
<p>Also, use <code>int()</code> instead of <code>eval()</code> to cast the user's input as an intege... | 0 | 2016-09-16T05:28:41Z | [
"python"
] |
PYTHON: enter the number of days after today for a future day and display the future day of the week | 39,524,225 | <p>I figured out how to code todays date but i am having trouble finding out how to code the future date, if the future date is larger than the integer 6. In the textbook they entered todays date is 0 so it is Sunday. But for days elapsed since Sunday, they entered 31. The result was "Today is Sunday and the future day... | 0 | 2016-09-16T05:26:40Z | 39,524,389 | <p>In addition to Tigerhawk's answer (Would comment but not enough rep :()</p>
<p>You could minimise the code repeition by storing the days in a list and accessing them as such:</p>
<pre><code>days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
todaysDate = int(input("Enter an inter... | 0 | 2016-09-16T05:39:05Z | [
"python"
] |
PYTHON: enter the number of days after today for a future day and display the future day of the week | 39,524,225 | <p>I figured out how to code todays date but i am having trouble finding out how to code the future date, if the future date is larger than the integer 6. In the textbook they entered todays date is 0 so it is Sunday. But for days elapsed since Sunday, they entered 31. The result was "Today is Sunday and the future day... | 0 | 2016-09-16T05:26:40Z | 39,524,525 | <p>here the <code>(daysElapsed+todaysDate) % 7</code> gives you the value of future day</p>
<pre><code>def future(day):
if day == 0:
print("future is Sunday")
elif day == 1:
print("future is Monday")
elif day == 2:
print("future is Tuesday")
elif day == 3:
print("future ... | -1 | 2016-09-16T05:51:05Z | [
"python"
] |
tf.SequenceExample with multidimensional arrays | 39,524,323 | <p>In Tensorflow, I want to save a multidimensional array to a TFRecord. For example:</p>
<pre><code>[[1, 2, 3], [1, 2], [3, 2, 1]]
</code></pre>
<p>As the task I am trying to solve is sequential, I am trying to use Tensorflow's <code>tf.train.SequenceExample()</code> and when writing the data I am successful in writ... | 9 | 2016-09-16T05:33:17Z | 39,681,738 | <p>With the provided code I wasn't able to reproduce your error but making some educated guesses gave the following working code.</p>
<pre><code>import tensorflow as tf
import numpy as np
import tempfile
tmp_filename = 'tf.tmp'
sequences = [[1, 2, 3], [1, 2], [3, 2, 1]]
label_sequences = [[0, 1, 0], [1, 0], [1, 1, 1... | 0 | 2016-09-24T22:59:29Z | [
"python",
"multidimensional-array",
"tensorflow",
"protocol-buffers"
] |
django-mptt show "no such column" | 39,524,365 | <p>I used MPTT to implement a forum which allow posts to latest news.I can't solve this error: "no such column: news_comment.lft"</p>
<p>The app name is news.This is models.py:</p>
<pre><code>from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
class News(models.Model):
....
class Comm... | 0 | 2016-09-16T05:37:20Z | 39,525,827 | <p>MPTT adds fields to models which are using it - it should be enough to run <code>python manage.py makemigrations <your app> && python manage.py migrate</code> as far as i can remember. The <a href="http://django-mptt.github.io/django-mptt/tutorial.html" rel="nofollow">MTPP Tutorial</a> mentions this in... | 0 | 2016-09-16T07:19:48Z | [
"python",
"django",
"django-mptt"
] |
Python how cyclic fetch a pre-fixed number of elements in array | 39,524,440 | <p>I'm trying to make a function that will always return me a pre-fixed number of elements from an array which will be larger than the pre-fixed number:</p>
<pre><code>def getElements(i,arr,size=10):
return cyclic array return
</code></pre>
<p>where <code>i</code> stands for index of array to fetch and <code>arr<... | 5 | 2016-09-16T05:43:47Z | 39,524,550 | <pre><code>def get_elements(i, arr, size=10):
if size - (len(arr) - i) < 0:
return arr[i:size+i]
return arr[i:] + arr[:size - (len(arr) - i)]
</code></pre>
<p>Is that what you want? <strong>Updated to work with lower numbers.</strong></p>
| 2 | 2016-09-16T05:53:42Z | [
"python",
"arrays",
"circular-list"
] |
Python how cyclic fetch a pre-fixed number of elements in array | 39,524,440 | <p>I'm trying to make a function that will always return me a pre-fixed number of elements from an array which will be larger than the pre-fixed number:</p>
<pre><code>def getElements(i,arr,size=10):
return cyclic array return
</code></pre>
<p>where <code>i</code> stands for index of array to fetch and <code>arr<... | 5 | 2016-09-16T05:43:47Z | 39,524,588 | <p>You could return </p>
<pre><code>array[i: i + size] + array[: max(0, i + size - len(array))]
</code></pre>
<p>For example</p>
<pre><code>In [144]: array = list(range(10))
In [145]: array
Out[145]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [146]: i, size = 1, 10
In [147]: array[i: i + size] + array[: max(0, i + size - ... | 3 | 2016-09-16T05:56:42Z | [
"python",
"arrays",
"circular-list"
] |
Python how cyclic fetch a pre-fixed number of elements in array | 39,524,440 | <p>I'm trying to make a function that will always return me a pre-fixed number of elements from an array which will be larger than the pre-fixed number:</p>
<pre><code>def getElements(i,arr,size=10):
return cyclic array return
</code></pre>
<p>where <code>i</code> stands for index of array to fetch and <code>arr<... | 5 | 2016-09-16T05:43:47Z | 39,524,757 | <p>The <a href="https://docs.python.org/3/library/itertools.html#itertools.cycle" rel="nofollow"><code>itertools</code></a>
is a fantastic library with lots of cool things. For this case we can use <code>cycle</code> and <code>islice</code>.</p>
<pre><code>from itertools import cycle, islice
def getElements(i, a, size... | 3 | 2016-09-16T06:09:08Z | [
"python",
"arrays",
"circular-list"
] |
Python how cyclic fetch a pre-fixed number of elements in array | 39,524,440 | <p>I'm trying to make a function that will always return me a pre-fixed number of elements from an array which will be larger than the pre-fixed number:</p>
<pre><code>def getElements(i,arr,size=10):
return cyclic array return
</code></pre>
<p>where <code>i</code> stands for index of array to fetch and <code>arr<... | 5 | 2016-09-16T05:43:47Z | 39,526,491 | <pre><code>a=[1, 2, 3]
def cyclic(a, i):
b=a*2
return b[i:i+len(a)]
print(cyclic(a, 2))
</code></pre>
| 2 | 2016-09-16T08:01:25Z | [
"python",
"arrays",
"circular-list"
] |
How to get rid of row numbers, pd.read_excel? | 39,524,570 | <p>I am a complete beginner with Python. I am working on a assignment and I can't seem to figure out how to get rid of the <em>row numbers</em> from my excel spreadsheet, while using <code>import pandas</code>. </p>
<p>This is what I get when I run the code:</p>
<pre><code>0 $20,000,000 $159,000,000
1 $9,900,0... | 0 | 2016-09-16T05:55:19Z | 39,525,204 | <p>You can try </p>
<pre><code>df = df.set_index('Salary')
</code></pre>
<p>where <code>Salary</code> is the column name you want to be the index.</p>
<p>The row number is called the index.</p>
| 0 | 2016-09-16T06:41:15Z | [
"python",
"excel",
"pandas"
] |
How to get rid of row numbers, pd.read_excel? | 39,524,570 | <p>I am a complete beginner with Python. I am working on a assignment and I can't seem to figure out how to get rid of the <em>row numbers</em> from my excel spreadsheet, while using <code>import pandas</code>. </p>
<p>This is what I get when I run the code:</p>
<pre><code>0 $20,000,000 $159,000,000
1 $9,900,0... | 0 | 2016-09-16T05:55:19Z | 39,526,619 | <p>Internally your dataframe always needs an index. If you get rid of the integer index another column has to be your index and you should only use a data column as your index if you need to for some special purpose.</p>
<p>When you write your dataframe to a file, e.g. with the <code>to_csv()</code> method, you can al... | 1 | 2016-09-16T08:09:15Z | [
"python",
"excel",
"pandas"
] |
How to create an sObject for a sType without using get_unique_sobject method? | 39,524,577 | <p>I wish to create a new sobject for a specific stype.
Currently I am using <code>server.get_unique_sobject( stype, data)</code>, But it assumes that an sobject is already present i.e it creates a new sobject <strong><em>iff</em></strong> there is no combination of sobject with same data <strong>already</strong> exist... | 0 | 2016-09-16T05:55:42Z | 39,710,247 | <p>Found it, the API itself provides a method of inserting a sObject to any sType in the system. It was by using <code>server.insert( sType, data = {})</code> where data is a dictionary of key value pairs.</p>
| 0 | 2016-09-26T18:50:42Z | [
"python",
"tactic"
] |
Write a CSV to store in Google Cloud Storage | 39,524,581 | <p>Background: I'm taking data in my Python/AppEngine project and creating a .tsv file so that I can create charts with d3.js. Right now I'm writing the CSV with each page load; I want to instead store the file once in Google Cloud Storage and read it from there.</p>
<p>How I'm currently writing the file, each time t... | 0 | 2016-09-16T05:56:07Z | 39,525,044 | <p>The problem is that <code>writer.writerow</code> doesn't return anything. The return type will be <code>None</code>, and you are trying to write that into <code>gcs_file</code>.</p>
| 0 | 2016-09-16T06:29:36Z | [
"python",
"csv",
"google-app-engine",
"google-cloud-storage"
] |
Write a CSV to store in Google Cloud Storage | 39,524,581 | <p>Background: I'm taking data in my Python/AppEngine project and creating a .tsv file so that I can create charts with d3.js. Right now I'm writing the CSV with each page load; I want to instead store the file once in Google Cloud Storage and read it from there.</p>
<p>How I'm currently writing the file, each time t... | 0 | 2016-09-16T05:56:07Z | 39,525,052 | <p>You're still attempting to create the writer on a response:</p>
<pre><code>writer = csv.writer(self.response.out, delimiter='\t')
</code></pre>
<p>You need to write to the GCS file. Something like this:</p>
<pre><code> datalist = MyEntity.all()
bucket_name = os.environ.get('BUCKET_NAME', app_identity.get_d... | 1 | 2016-09-16T06:30:00Z | [
"python",
"csv",
"google-app-engine",
"google-cloud-storage"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.