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 |
|---|---|---|---|---|---|---|---|---|---|
Iteration number processing large files line by line | 38,556,192 | <p>I have the need to process a large file in Python (about 1GB) line by line.
I use this approach to do it:</p>
<pre><code>with open('file.txt', 'r') as f:
i = 0
for fline in f:
process(fline)
i = i + 1
print i
</code></pre>
<p>the value of <code>i</code> (the number of iteration = the number... | 0 | 2016-07-24T20:00:12Z | 38,557,432 | <p>I can think of two possibilities.</p>
<ol>
<li>You are running 2.x on Windows, the file contains about 3x as many '\r' characters as recognized '\r\n' or '\n' line endings, and EmEditor recognizes '\r' as a line ending, as does Python 3.x. Or something similar is happening with 2.7 on another OS.</li>
</ol>
<p>Ex... | 0 | 2016-07-24T22:25:54Z | [
"python",
"file"
] |
Iteration number processing large files line by line | 38,556,192 | <p>I have the need to process a large file in Python (about 1GB) line by line.
I use this approach to do it:</p>
<pre><code>with open('file.txt', 'r') as f:
i = 0
for fline in f:
process(fline)
i = i + 1
print i
</code></pre>
<p>the value of <code>i</code> (the number of iteration = the number... | 0 | 2016-07-24T20:00:12Z | 38,558,717 | <p>The numbers don't match because the encoding that the <code>open</code> function uses isn't correct for this file, try to use the "ISO-8859-1" encoding.</p>
| 0 | 2016-07-25T01:57:34Z | [
"python",
"file"
] |
How do I mock a class's function's return value? | 38,556,197 | <p>I have a method in Python that looks like this (in <code>comicfile.py</code>):</p>
<pre><code>from zipfile import ZipFile
...
class ComicFile():
...
def page_count(self):
"""Return the number of pages in the file."""
if self.file == None:
raise ComicFile.FileNoneError()
... | 1 | 2016-07-24T20:00:57Z | 38,557,262 | <p><code>ZipFile</code> is instantiated as a <a href="https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/" rel="nofollow">context manager</a>. to <a href="https://docs.python.org/3/library/unittest.mock.html#calling" rel="nofollow">mock</a> it you have to refer to its <code>__enter__</code> method.</p>... | 2 | 2016-07-24T22:01:18Z | [
"python",
"unit-testing"
] |
Different data structures result in huge different size in python | 38,556,213 | <p>I'm trying using Facebook Graph API to get something by python, and there's no problem in my programs.</p>
<p>However, When outputting data to files, I found something strange. I change a structure in output, then my file would be several times bigger.</p>
<p>The original data look like this:</p>
<pre><code>{
"... | -1 | 2016-07-24T20:02:09Z | 38,556,586 | <p>The difference between these two <code>for</code> loops is that in the second one, you're printing out the entire structure each time the <code>for</code> loop body runs.</p>
<p>In the first loop, you are only printing out the current item (well appending it to the output file, but you know that bit already!).</p>
... | 0 | 2016-07-24T20:42:24Z | [
"python",
"python-3.x",
"data-structures"
] |
Automatic 'created by user' field using django-rest-framework? | 38,556,217 | <h3>models.py</h3>
<pre><code>class Nugget(TimeStampedModel):
added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='added_by', blank=True, null=True)
</code></pre>
<h3>serializers.py</h3>
<pre><code>class NuggetSerializer(TaggitSerializer, serializers.ModelSerializer):
... | 0 | 2016-07-24T20:02:36Z | 38,564,949 | <p>Changed <code>added_by</code> in <code>serializers.py</code> (wasn't using a field, and set to read_only) and <code>.save()</code> in <code>views.py</code> to stop overriding the default.</p>
<p><code>CurrentUserDefault()</code> requires <code>request</code> within the <code>context</code> dict. In this case <code>... | 1 | 2016-07-25T10:10:33Z | [
"python",
"django",
"django-models",
"django-rest-framework"
] |
Returning arguments in SWIG/Python | 38,556,223 | <p>According to Swig docs and the marvelous explanation at <a href="http://stackoverflow.com/questions/21373259/swig-in-typemap-works-but-argout-does-not">SWIG in typemap works, but argout does not</a> by @Flexo, the <code>argout</code> typemap turns reference arguments into return values in Python. </p>
<p>I have a s... | 0 | 2016-07-24T20:03:15Z | 38,557,397 | <p>I am a little confused as to what exactly you are asking, but my understanding is:</p>
<ul>
<li>You have an "in" typemap to convert a Python <code>dict</code> to a C++ <code>unordered_map</code> for some function argument.</li>
<li>The function then modifies the <code>unordered_map</code>.</li>
<li>After completion... | 2 | 2016-07-24T22:20:28Z | [
"python",
"swig",
"typemaps"
] |
Returning arguments in SWIG/Python | 38,556,223 | <p>According to Swig docs and the marvelous explanation at <a href="http://stackoverflow.com/questions/21373259/swig-in-typemap-works-but-argout-does-not">SWIG in typemap works, but argout does not</a> by @Flexo, the <code>argout</code> typemap turns reference arguments into return values in Python. </p>
<p>I have a s... | 0 | 2016-07-24T20:03:15Z | 38,578,993 | <p>I am well aware of that the user has already solved his issue, but here goes a solution. Some validation of inputs may be introduced to avoid non-string values of the input dictionary.</p>
<p>Header file</p>
<pre><code>// File: test.h
#pragma once
#include <iostream>
#include <string>
#include <uno... | 0 | 2016-07-25T23:42:22Z | [
"python",
"swig",
"typemaps"
] |
Standard deviation from center of mass along Numpy array axis | 38,556,297 | <p>I am trying to find a well-performing way to calculate the standard deviation from the center of mass/gravity along an axis of a Numpy array.</p>
<p>In formula this is (sorry for the misalignment):</p>
<p><img src="http://latex.codecogs.com/gif.latex?%5Cmu_j&space;=&space;%5Cfrac%7B%5Csum_i%7Bi&space;A_%7Bij%7D%7D... | 1 | 2016-07-24T20:09:56Z | 38,557,752 | <p>You want to take the mean, variance and standard deviation of the vector <code>[1, 2, 3, ..., n]</code> — where <code>n</code> is the dimension of the input matrix <code>A</code> along the axis of interest —, with weights given by the matrix <code>A</code> itself.</p>
<p>For concreteness, say you want t... | 0 | 2016-07-24T23:10:07Z | [
"python",
"python-2.7",
"numpy",
"standard-deviation",
"weighted-average"
] |
Pass multiple variable value into URL in python | 38,556,304 | <p>I have below code to get data using url. I pass ticker value from text file and its successful and its;works (part-1)
but as code per part-2, when I pass multiple value using multiple variable by raw_input(), its give <strong>error "TypeError: not enough arguments for format string"</strong></p>
<p>Part-1</p>
<pre... | -2 | 2016-07-24T20:10:45Z | 38,556,322 | <p>You're not passing those <em>format</em> parameters correctly:</p>
<pre><code>url = "...?s=%s.ns&a=%s&b=%s&c=%s&d=%s&e=%s&f=%s&g=d&ignore=.csv"%(ticker, a, b, c, d, e, f)
# ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
</code></pre>
<p>Whe... | 2 | 2016-07-24T20:12:48Z | [
"python"
] |
Daphne, twisted pip error when installing django channels | 38,556,363 | <p>I have a small problem with <code>pip</code> installing <code>django channels</code>, I noticed this from the <em>github</em> repository </p>
<blockquote>
<p>Note: Recent versions of Channels also need recent versions of Daphne,
asgi_redis and asgiref, so make sure you update all at once</p>
</blockquote>
<p>I... | 1 | 2016-07-24T20:16:15Z | 38,597,359 | <p>Channels is entirely new concept and in beta, In this time recommended way to install channels is <code>pip install -U Channels</code> </p>
<p>Of cource, you can install twisted by visiting in this page <a href="http://twistedmatrix.com/trac/" rel="nofollow">http://twistedmatrix.com/trac/</a> and download the sourc... | 1 | 2016-07-26T18:28:12Z | [
"python",
"django",
"python-3.5",
"django-channels"
] |
Hide or removing a menubar of tkinter in python | 38,556,387 | <p>I can set my menu with the following instruction:</p>
<pre><code>my_tk.config(menu=my_menu_bar)
</code></pre>
<p>But, How do I remove it or hide it completely?</p>
<pre><code>my_tk.config(menu=None)
</code></pre>
<p>doesn't work :-( </p>
| 0 | 2016-07-24T20:18:33Z | 38,557,221 | <p>Is this what you're looking for:</p>
<pre><code>from tkinter import *
root = Tk()
menubar = Menu(root)
root.config(menu=menubar)
submenu = Menu(menubar)
menubar.add_cascade(label="Submenu", menu=submenu)
submenu.add_command(label="Option 1")
submenu.add_command(label="Option 2")
submenu.add_command(label="Option ... | 1 | 2016-07-24T21:56:23Z | [
"python",
"python-3.x",
"tkinter",
"menu"
] |
Hide or removing a menubar of tkinter in python | 38,556,387 | <p>I can set my menu with the following instruction:</p>
<pre><code>my_tk.config(menu=my_menu_bar)
</code></pre>
<p>But, How do I remove it or hide it completely?</p>
<pre><code>my_tk.config(menu=None)
</code></pre>
<p>doesn't work :-( </p>
| 0 | 2016-07-24T20:18:33Z | 38,557,588 | <p>Another way is:</p>
<pre><code>from tkinter import *
root = Tk()
menubar = Menu(root)
root.config(menu=menubar)
submenu = Menu(menubar)
menubar.add_cascade(label="Submenu", menu=submenu)
submenu.add_command(label="Option 1")
submenu.add_command(label="Option 2")
submenu.add_command(label="Option 3")
def remove_f... | 0 | 2016-07-24T22:45:52Z | [
"python",
"python-3.x",
"tkinter",
"menu"
] |
Is there a way to block django views from serving multiple requests concurrently? | 38,556,461 | <p>I have a django app, where I am using one of the views to fetch data from local filesystem and parse it and add it to my database. Now the thing is, I want to restrict this view from serving multiple requests concurrently, I want them to be served sequentially instead. Or just block the new request when one request ... | 1 | 2016-07-24T20:26:59Z | 38,556,568 | <p>You need some kind of mutex. Since your operations involve the filesystem already, perhaps you could use a file as a mutex. For instance, at the start of the operation, check if a specific file exists in a specific place; if it does, return an error, but if not, create it and proceed, deleting it at the end of the o... | 2 | 2016-07-24T20:39:21Z | [
"python",
"django"
] |
Is there a way to block django views from serving multiple requests concurrently? | 38,556,461 | <p>I have a django app, where I am using one of the views to fetch data from local filesystem and parse it and add it to my database. Now the thing is, I want to restrict this view from serving multiple requests concurrently, I want them to be served sequentially instead. Or just block the new request when one request ... | 1 | 2016-07-24T20:26:59Z | 38,557,365 | <p>here is a link to python functions and module that support inter-thread locking:</p>
<p><a href="https://docs.python.org/3/library/asyncio-sync.html" rel="nofollow">https://docs.python.org/3/library/asyncio-sync.html</a></p>
<p>There are some simple examples on the page.</p>
| 1 | 2016-07-24T22:15:15Z | [
"python",
"django"
] |
Combine result of two functions in python | 38,556,474 | <p>The objective I'm trying to reach is to take a string, extract time as hours and minutes and return them as degrees on an analogue clock dial, the only way i could think to do this is to create 2 functions, one to return the hours and another to return the minutes. I've probably gone about this the completely the wr... | 0 | 2016-07-24T20:29:11Z | 38,556,541 | <p>Once you have the times in a list, then you can do the following:</p>
<pre><code>currentTimes = [] # Here's a list of times before the functions manipulate each element.
analogDialTimes = [(clock_degree(time), clock_degree_min(time)) for time in currentTimes]
</code></pre>
<p>This returns a list of tuples, simila... | 1 | 2016-07-24T20:35:46Z | [
"python"
] |
Combine result of two functions in python | 38,556,474 | <p>The objective I'm trying to reach is to take a string, extract time as hours and minutes and return them as degrees on an analogue clock dial, the only way i could think to do this is to create 2 functions, one to return the hours and another to return the minutes. I've probably gone about this the completely the wr... | 0 | 2016-07-24T20:29:11Z | 38,556,561 | <p>I'd rather avoid mixing return types (that's what exceptions are for), and use standard library functions for common operations like parsing time (<a href="https://docs.python.org/2/library/time.html#time.strptime" rel="nofollow" title="time.strptime">time.strptime</a>):</p>
<pre><code>import time
s="15:43"
t=time.... | 0 | 2016-07-24T20:38:56Z | [
"python"
] |
Combine result of two functions in python | 38,556,474 | <p>The objective I'm trying to reach is to take a string, extract time as hours and minutes and return them as degrees on an analogue clock dial, the only way i could think to do this is to create 2 functions, one to return the hours and another to return the minutes. I've probably gone about this the completely the wr... | 0 | 2016-07-24T20:29:11Z | 38,556,596 | <pre><code>def clock_degree(s):
hr, min = s.split(':')
hr = float(hr) + float(min)/60 # convert minutes to hours (ex : 30 min = 0.5h)
hr = hr % 12 # have a time between 0:00 and 12:00
angle = (360 / 12) * hr # calculate the angle (6h => 180°)
print(hr, angle)
return (hr, angle)
clock_de... | 0 | 2016-07-24T20:43:10Z | [
"python"
] |
Combine result of two functions in python | 38,556,474 | <p>The objective I'm trying to reach is to take a string, extract time as hours and minutes and return them as degrees on an analogue clock dial, the only way i could think to do this is to create 2 functions, one to return the hours and another to return the minutes. I've probably gone about this the completely the wr... | 0 | 2016-07-24T20:29:11Z | 38,556,601 | <p>I would prefer something like this that is a bit more terse:</p>
<pre><code>def getDegrees(t):
h, m = [float(n) for n in t.split(":")]
result = []
for n, denominator in (h, 12), (m, 60):
result.append(str((n % denominator) / denominator * 360))
return ",".join(result)
</code></pre>
<p>For b... | 0 | 2016-07-24T20:43:46Z | [
"python"
] |
Matrix using only one column for header and row | 38,556,574 | <p>Let's say I have a list of names like this one in a csv:</p>
<pre><code>Nom;Link;NonLink
Deb;John;
John;Deb;
Martha;Travis;
Travis;Martha;
Allan;;
Lois;;
Jayne;;
Brad;;Abby
Abby;;Brad
</code></pre>
<p>I imported it using numpy:</p>
<pre><code>import numpy as np
file = np.genfromtxt('liste.csv', dtype=None, delimi... | 0 | 2016-07-24T20:40:27Z | 38,556,665 | <p>You can use pandas and create a dataframe using <code>Nom</code> variable.
Something like this:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[0] * len(Nom)] * len(Nom), Nom, Nom)
print(df)
</code></pre>
| 1 | 2016-07-24T20:52:47Z | [
"python",
"numpy",
"pandas"
] |
it is possible to type-hint a compiled regex in python? | 38,556,579 | <p>I would like to use autocompletion for a pre-compiled and stored list of regular expressions, but it doesn't appear that I can import the _sre.SRE_Pattern class, and I can't programmatically feed the obtained type from type() to a comment of the format # type: classname or use it for a return -> classname style hint... | 0 | 2016-07-24T20:41:47Z | 38,935,153 | <p>You should use <a href="https://docs.python.org/3/library/typing.html#typing.re" rel="nofollow"><code>typing.Pattern</code> and <code>typing.Match</code></a> which were specifically added to the typing module to accommodate this use case.</p>
<p>Example:</p>
<pre><code>from typing import Pattern, Match
import re
... | 0 | 2016-08-13T17:12:27Z | [
"python",
"regex",
"type-hinting"
] |
Is there a more efficient way to write this Python code? | 38,556,646 | <p>I am dealing with a preprocessing stage of a data table.
My current code works but I am wondering if there is a more efficient way.</p>
<p>My data table looks like this</p>
<pre><code>object A object B features of A features of B
aaa w 1 0
aaa q ... | 0 | 2016-07-24T20:50:21Z | 38,557,260 | <p>In relational algebra terms, it sounds like you want </p>
<p><code>Ï[features of A, features of B] ((object A) X (object B))</code></p>
<p>i.e. project fields 'features of A', 'features of B' from the cross-product of "object A" and "object B". </p>
<p>This is very natural to express in SQL. </p>
<p>For Python,... | 2 | 2016-07-24T22:01:10Z | [
"python",
"iteration"
] |
Is there a more efficient way to write this Python code? | 38,556,646 | <p>I am dealing with a preprocessing stage of a data table.
My current code works but I am wondering if there is a more efficient way.</p>
<p>My data table looks like this</p>
<pre><code>object A object B features of A features of B
aaa w 1 0
aaa q ... | 0 | 2016-07-24T20:50:21Z | 38,557,349 | <p>Assuming the data actually looks like I think it does, this should do what you want quite efficiently:</p>
<pre><code>import itertools
x = [('aaa', 'aaa', 'bbb', 'ccc'), ('w', 'q', 'x', 'w'), (1, 1, 0, 1), (0, 1, 0, 0)]
a_list = set((x[0][i], x[2][i]) for i in range(len(x[0])))
b_list = set((x[1][i], x[3][i]) for... | 1 | 2016-07-24T22:12:44Z | [
"python",
"iteration"
] |
Why do numpy array arr2d[:, :1] and arr2d[:, 0] produce different results? | 38,556,674 | <p>Say:</p>
<pre><code>arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
</code></pre>
<p><code>arr2d[:, :1]</code> gives me</p>
<pre><code>array([[1],
[4],
[7]])
</code></pre>
<p><code>arr2d[:,0]</code> gives me </p>
<pre><code>array([1, 4, 7])
</code></pre>
<p>I thought they would produce exactl... | 0 | 2016-07-24T20:53:47Z | 38,556,780 | <p>With a list, you have the same behavior you described:</p>
<pre><code>>>> a = [1, 2, 3, 4]
>>> a[0]
1
>>> a[:1]
[1]
</code></pre>
<p>The addition with <code>numpy</code> is the introduction of <code>axis</code> which makes it a little less intuitive.</p>
<p>In the first case, you're <em... | 2 | 2016-07-24T21:05:15Z | [
"python",
"numpy",
"indexing",
"python-2.x"
] |
Why do numpy array arr2d[:, :1] and arr2d[:, 0] produce different results? | 38,556,674 | <p>Say:</p>
<pre><code>arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
</code></pre>
<p><code>arr2d[:, :1]</code> gives me</p>
<pre><code>array([[1],
[4],
[7]])
</code></pre>
<p><code>arr2d[:,0]</code> gives me </p>
<pre><code>array([1, 4, 7])
</code></pre>
<p>I thought they would produce exactl... | 0 | 2016-07-24T20:53:47Z | 38,557,108 | <p>Index <code>':1'</code> implies:</p>
<p>'The <strong>list</strong> of items from <code>index 0</code> to <code>index 0</code>' which is obviously a list of 1 item.</p>
<p>Index <code>'0'</code> implies:</p>
<p>'The item at <code>index 0</code>'.</p>
<p>Extending that to your question should make the results you ... | 1 | 2016-07-24T21:41:52Z | [
"python",
"numpy",
"indexing",
"python-2.x"
] |
Why do numpy array arr2d[:, :1] and arr2d[:, 0] produce different results? | 38,556,674 | <p>Say:</p>
<pre><code>arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
</code></pre>
<p><code>arr2d[:, :1]</code> gives me</p>
<pre><code>array([[1],
[4],
[7]])
</code></pre>
<p><code>arr2d[:,0]</code> gives me </p>
<pre><code>array([1, 4, 7])
</code></pre>
<p>I thought they would produce exactl... | 0 | 2016-07-24T20:53:47Z | 38,557,414 | <p>1)
When you say <code>arr2d[:, 0]</code>, you're saying give me the 0th index of all the rows in arr2d (this is another way of saying give me the 0th column). </p>
<p>2)
When you say <code>arr2d[:, :1]</code>, you're saying give me all the <code>:1</code> index of all the rows in arr2d. Numpy interprets <code>:1</c... | 3 | 2016-07-24T22:23:02Z | [
"python",
"numpy",
"indexing",
"python-2.x"
] |
Django: Linking two tables | 38,556,735 | <p>first of all, I'm aware that this question might've been answered already, but there are two reasons why I'm opening another question: One, obviously, is I'm struggling with the Django syntax. Secondly, and perhaps more importantly, I'm not quite sure whether my database setup makes even sense at this point. So, ple... | 0 | 2016-07-24T21:00:02Z | 38,556,844 | <p>As you note, the <code>proprietary_name</code> field on medwiki is a ForeignKey. You can't return that value directly from the <code>__str__</code> method because that needs to return a string. You need to convert that value into a string before returning it: either use the default string representation of the medse... | 1 | 2016-07-24T21:13:18Z | [
"python",
"sql",
"django",
"database"
] |
Django: Linking two tables | 38,556,735 | <p>first of all, I'm aware that this question might've been answered already, but there are two reasons why I'm opening another question: One, obviously, is I'm struggling with the Django syntax. Secondly, and perhaps more importantly, I'm not quite sure whether my database setup makes even sense at this point. So, ple... | 0 | 2016-07-24T21:00:02Z | 38,556,852 | <p>This would work:</p>
<pre><code>return self.proprietary_name.proprietary_name
</code></pre>
<p>But that doesn't really make sense !</p>
<hr>
<p>The main issue is that you've called the foreign key to <code>medsearch</code>, <code>proprietary_name</code>.</p>
<p>The second issue is just a convention one. In Pyth... | 2 | 2016-07-24T21:14:06Z | [
"python",
"sql",
"django",
"database"
] |
Iterate over variables in spss and get a conditional sum | 38,556,808 | <p>I have the following variables:
<code>attribute1 , value1, attribute2, value2</code>, ...</p>
<p>Each attribute can have a numeric value between 0 and 6.</p>
<p>How can I iterate over the variables and get the sum for each attribute?</p>
<p>Like: get sum of all values where <code>attribute == 0</code>?</p>
| -1 | 2016-07-24T21:08:17Z | 38,556,858 | <p>I don't know the structure of your variable storage, so I'll assume a list of tuples.</p>
<p>Use a list comprehension:</p>
<pre><code>listOfTuples = [(2, 5), (4, 3), (2, 4), (2, 3)] # etc...
someValue = 2 # Your desired value
# Store the VALUE - not the key
sumOfAttrsForAValue = sum([y for x, y in listOfTuples i... | 0 | 2016-07-24T21:14:41Z | [
"python",
"ibm"
] |
Iterating over columns and reassigning values - Pandas/Python | 38,556,822 | <p>Trying to use a for loop to iterate over columns and change Yes and No's to 1 and 0.</p>
<p>For some reason, I am getting an invalid type comparison error when attempting this:</p>
<p>Panda DataFrame has multiple columns, one of them being "Combined"</p>
<pre><code>for col,row in d.iteritems():
d.loc[d[col] =... | 0 | 2016-07-24T21:10:24Z | 38,556,916 | <p>There must be columns which are taking integer values and for those rows its an "invalid comparison". So just check if its an instance of str and you are good to go.</p>
<pre><code>for col,row in d.iteritems():
if isinstance(row[0], str):
d.loc[d[col] == 'No', col] = 0
d.loc[d[col] == 'Yes', col... | 0 | 2016-07-24T21:20:24Z | [
"python",
"pandas",
"dataframe"
] |
Acceptable use of os.open/read/write/close? | 38,556,833 | <p>I intend to frequently read/write small pieces of information from many different files. The following somewhat contrived example shows substantially less time taken when using <code>os</code> operations for acting directly on file descriptors. Am I missing any downside other than the convenience of file objects?</p... | 4 | 2016-07-24T21:11:44Z | 38,558,165 | <p>I'll answer just so this doesn't stay open forever ;-)</p>
<p>There's really little to say: as you already noted, a <code>file</code> object is more convenient. In <em>some</em> cases it's also more functional; for example, it does its own layer of buffering to speed line-oriented text operations (like <code>file... | 1 | 2016-07-25T00:22:24Z | [
"python",
"file"
] |
No twitter Module error [Mac] | 38,556,890 | <p>I have a python script that follows/unfollows and favorites tweets. I keep getting an error:</p>
<pre><code>from twitter import Twitter, OAuth, TwitterHTTPError
ImportError: No module named twitter
</code></pre>
<p>I put in all the oauth info in my script and i continue to get this error. I think im being blocked ... | -3 | 2016-07-24T21:17:09Z | 38,556,998 | <p>First of all: which library do you use? I expect you use tweepy so from a terminal type:</p>
<pre><code>pip install Tweepy
</code></pre>
| 0 | 2016-07-24T21:29:48Z | [
"python",
"osx",
"twitter",
"importerror"
] |
UnicodeEncodeError at /admin/... - Django admin | 38,556,904 | <p>I'm facing an encoding problem in <code>Django-admin</code>. I have a model, which represents a language quiz which consists of questions and answers (both are models) inlined to <code>Quiz</code> model.</p>
<p>I've created a simple <code>csv</code> import. In <code>Quiz</code> model, there is a file field. When ad... | -1 | 2016-07-24T21:19:03Z | 38,556,973 | <p>The following letters are really common in French: 'é', 'è', 'ç', 'à ' and would probably break your code. </p>
<blockquote>
<p>Do you know what should I do?</p>
</blockquote>
<p>Write a test for it reproducing the issue. Once you've written it, you can make experiments a lot faster (use inmemory files); add ... | -3 | 2016-07-24T21:26:45Z | [
"python",
"django",
"encoding",
"django-admin"
] |
UnicodeEncodeError at /admin/... - Django admin | 38,556,904 | <p>I'm facing an encoding problem in <code>Django-admin</code>. I have a model, which represents a language quiz which consists of questions and answers (both are models) inlined to <code>Quiz</code> model.</p>
<p>I've created a simple <code>csv</code> import. In <code>Quiz</code> model, there is a file field. When ad... | -1 | 2016-07-24T21:19:03Z | 38,556,976 | <p>Well, I can't tell where you're receiving the error. Please post a line where you receive the error.</p>
<p>This is a very common error when parsing international text. It's solved with one of the following two methods:</p>
<h3>Encoding with UTF8</h3>
<pre><code>try:
print (myThing)
except UnicodeEncodeError:... | 0 | 2016-07-24T21:26:58Z | [
"python",
"django",
"encoding",
"django-admin"
] |
Python 3 : How to print output to both Console and File | 38,557,096 | <p>So basically I'm still learning Python programming and currently playing around with some code I found on github.</p>
<p>Basically, the code works fine when execute, it print the output to terminal/console. However I would like to save the output to file and therefore followed few tutorials and successfully saved t... | -3 | 2016-07-24T21:40:45Z | 38,560,894 | <p>Instead of setting <code>stdout</code> to be your file, keep it to be the default and use file I/O operations to write to the file while printing.</p>
<pre><code># open the file
f = open('I put my path here to .txt file','a')
for u in convert(args.file,doColor=not args.nocolor, renderIRC=args.irc, cutoff=args.c, si... | 1 | 2016-07-25T06:19:43Z | [
"python",
"windows",
"file",
"python-3.x",
"terminal"
] |
Keras - Objective function for number in range [0-100] | 38,557,107 | <p>Lets say I've ground truth (output) of a number in range [0-100].
Is it possible to learn to predict a number that minimize the delta from the original number (gt) according the input ?</p>
<p>The objective types of Keras are here <a href="http://keras.io/objectives/" rel="nofollow">http://keras.io/objectives/</a><... | 1 | 2016-07-24T21:41:40Z | 38,557,668 | <p>I think your best bet would be to use mean squared error (<code>loss='mse'</code>), which penalizes predictions based on the square of their difference from the ground truth. You would also want to use linear activations (the default) for the last layer. </p>
<p>If you're especially concerned about keeping the pr... | 1 | 2016-07-24T22:57:58Z | [
"python",
"neural-network",
"keras"
] |
Regex match all non letters excluding diacritics (python) | 38,557,116 | <p>I have found this excellent guide: <a href="http://www.regular-expressions.info/unicode.html#category" rel="nofollow">http://www.regular-expressions.info/unicode.html#category</a> that gives some hints on how to match <strong>non</strong> letters with the following regex:</p>
<pre><code>\P{L}
</code></pre>
<p>But ... | 2 | 2016-07-24T21:42:40Z | 38,557,197 | <p>Since you are using Python 2.x, your <code>r'\P{L}'</code> is a byte string, while the input you have is Unicode. You need to make your pattern a Unicode string. See the <a href="https://pypi.python.org/pypi/regex" rel="nofollow">PyPi <code>regex</code> reference</a>:</p>
<blockquote>
<p>If neither the <code>ASCI... | 4 | 2016-07-24T21:52:32Z | [
"python",
"regex",
"python-2.7",
"unicode",
"regex-negation"
] |
is there any way to directly read Pandas dataframe as a file handler? | 38,557,139 | <p>I used pandas to load data from a <code>dataSource.cvs</code> file:</p>
<p><code>DF = pd.read_csv('dataSoruce.csv')</code></p>
<p>In pandas I can clean the data, like filling missing values with 0. </p>
<p>Next I use <code>DF.to_csv('temp.csv', sep=',')</code> to write the <code>DF</code> as a
temporary cvs f... | 0 | 2016-07-24T21:45:14Z | 38,573,144 | <p>suppose <code>DF</code> is a dataframe in pandas, doing the following:</p>
<pre><code> for x in DF.values:
x = tuple(x)
</code></pre>
<p>then <code>x</code> will be <code>(x1, x2, x3...)</code> format. </p>
| 0 | 2016-07-25T16:35:08Z | [
"python",
"pandas",
"dataframe",
"filehandler"
] |
How to automate dictionary creation in Python | 38,557,180 | <p>I am trying to write a python code that solves a Sudoku puzzle. My code starts by making a list of each row/column combination, or the coordinates of each box. Next, I want to find a way to, for each box, reference its location.
This is my current code:</p>
<pre><code>boxes = []
for i in range(1, 10):
for x in ... | 0 | 2016-07-24T21:50:46Z | 38,557,244 | <p>You don't need to create all those dictionaries. You already have your coordinates, just don't lock them up in strings:</p>
<pre><code>boxes = []
for i in range(1, 10):
for x in range(1,10):
boxes.append((i, x))
</code></pre>
<p>would create a list of <code>(row, column)</code> tuples instead, and you ... | 1 | 2016-07-24T21:59:09Z | [
"python",
"dictionary"
] |
How to automate dictionary creation in Python | 38,557,180 | <p>I am trying to write a python code that solves a Sudoku puzzle. My code starts by making a list of each row/column combination, or the coordinates of each box. Next, I want to find a way to, for each box, reference its location.
This is my current code:</p>
<pre><code>boxes = []
for i in range(1, 10):
for x in ... | 0 | 2016-07-24T21:50:46Z | 38,557,598 | <p>While Martijn's answer is probably better from a "what you should do" perspective, for completeness, you could build that structure pretty easily using <a href="http://www.python.org/dev/peps/pep-0274/" rel="nofollow">dictionary comprehension</a>:</p>
<p>The below annotated code will output your desire data structu... | 0 | 2016-07-24T22:48:16Z | [
"python",
"dictionary"
] |
unable to install scrapy-deltafetch | 38,557,241 | <p>I am trying to install scrapy-deltafetch on ubuntu 14 using pip (v8.1.2 on python 2.7). When I run (sudo) pip install scrapy-deltafetch, I get the following error:</p>
<p><strong>Update:</strong></p>
<pre><code>Complete output from command python setup.py egg_info:
Can't find a local Berkeley DB installation.
C... | 0 | 2016-07-24T21:58:39Z | 38,564,458 | <p>scrapy-deltafetch requires <code>bsddb3</code>.</p>
<p><code>bsddb3</code> itself, on Ubuntu Trusty, <a href="http://packages.ubuntu.com/en/trusty/python-bsddb3" rel="nofollow">depends on <code>libdb5.3</code></a>.</p>
<p>You can either install <code>python-bsddb3</code> with <code>apt-get</code>, or only <code>ap... | 1 | 2016-07-25T09:45:45Z | [
"python",
"python-2.7",
"scrapy"
] |
unable to install scrapy-deltafetch | 38,557,241 | <p>I am trying to install scrapy-deltafetch on ubuntu 14 using pip (v8.1.2 on python 2.7). When I run (sudo) pip install scrapy-deltafetch, I get the following error:</p>
<p><strong>Update:</strong></p>
<pre><code>Complete output from command python setup.py egg_info:
Can't find a local Berkeley DB installation.
C... | 0 | 2016-07-24T21:58:39Z | 40,067,356 | <p>Install libbd-dev first,</p>
<pre><code>sudo apt-get install libdb-dev
</code></pre>
<p>then install deltafetch,</p>
<pre><code># for python2
sudo -H pip install scrapy-deltafetch
# for python3
sudo -H pip3 install scrapy-deltafetch
</code></pre>
| 1 | 2016-10-16T06:03:48Z | [
"python",
"python-2.7",
"scrapy"
] |
How can I host my Bitcoin API on the 21 market with a Virtual IP? | 38,557,245 | <p>I'm trying to make my simple Pokemon API available on something other than my localhost. The API has two files, client.py and server.py. I ran the <code>21 market join</code> command and got a virtual IP. (10.244.121.0). </p>
<p>I tried modifying my script so that instead of the client.py requesting "<a href="http:... | 0 | 2016-07-24T21:59:12Z | 38,557,348 | <p>Instead of calling <code>python client.py</code> directly, I can now use <code>21 buy http://10.244.121.0:5000/name?id=1</code> to call my API remotely.</p>
| 1 | 2016-07-24T22:12:28Z | [
"python",
"ubuntu-14.04",
"bitcoin",
"virtual-ip-address"
] |
Tokenization of text file in python 3.5 | 38,557,258 | <p>I'm trying to do tokenization of words in a text file using python 3.5 but have a couple of errors. Here is the code:</p>
<pre><code>import re
f = open('/Users/Half_Pint_Boy/Desktop/sentenses.txt', 'r')
a=0
c=0
for line in f:
b=re.split('[^a-z]', line.lower())
a+=len(filter(None, b))
c = c + 1
d = ... | 0 | 2016-07-24T22:01:00Z | 38,557,288 | <ol>
<li><p>You need an explicit cast to list in Python 3.5 to get the length of your sequence, as <code>filter</code> returns an <em>iterator</em> object and not a list as with Python 2.7:</p>
<pre><code>a += len(list(filter(None, b)))
# ^^
</code></pre></li>
<li><p>The empty spaces where returned from your <... | 1 | 2016-07-24T22:05:36Z | [
"python"
] |
Use variables from one Screen on another in kivy | 38,557,306 | <p>I'm making an app with kivy, and in my kv file I have one screen called MainScreen which has two TextInput boxes. When I press a Button, the screen will change to LoggedInScreen. How do I pass the input from the TextInput boxes on MainScreen, to LoggedInScreen, so I can use them as positional arguments on a function... | 0 | 2016-07-24T22:08:03Z | 38,557,440 | <p>The easiest way would be defining a new method called <code>auth_success</code> in the screen manager, which is in charge of those two screens:</p>
<pre><code>class MyScreenManager(ScreenManager):
...
def auth_success(self, username, password):
self.loggedin.username = username
self.logged... | 0 | 2016-07-24T22:26:57Z | [
"python",
"function",
"class",
"variables",
"kivy"
] |
Regex for this date format? | 38,557,353 | <p>I'm trying to find a regex that will match dates in the following format: <strong>3-Jul-16</strong> or <strong>30-Jun-16</strong></p>
<p>I have tried this regex at first:</p>
<pre><code>/[0-9]{1,}-[a-zA-Z]{3}-[0-9]{1,}/g
</code></pre>
<p>But it matches also dates like <strong>947-UfO-104</strong>, and this is not... | -5 | 2016-07-24T22:13:21Z | 38,557,434 | <p>Split the task into 3 parts. First, a number in the range of 1-31 (<a href="http://www.regular-expressions.info/numericranges.html" rel="nofollow">tutorial</a>), then a list of possible values for the month, and then two numbers.</p>
<pre><code>\b([1-9]|[12][0-9]|3[01])-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|... | 1 | 2016-07-24T22:26:12Z | [
"python",
"regex",
"parsing"
] |
Sum of Two Integers without using "+" operator in python | 38,557,464 | <p>Need some help understanding python solutions of leetcode 371. "Sum of Two Integers". I found <a href="https://discuss.leetcode.com/topic/49900/python-solution/2" rel="nofollow">https://discuss.leetcode.com/topic/49900/python-solution/2</a> is the most voted python solution, but I am having problem understand it.</p... | 1 | 2016-07-24T22:29:36Z | 38,558,504 | <p>Let's disregard the <code>MASK</code>, <code>MAX_INT</code> and <code>MIN_INT</code> for a second.</p>
<p><strong>Why does this black magic bitwise stuff work?</strong></p>
<p>The reason why the calculation works is because <code>(a ^ b)</code> is "summing" the bits of <code>a</code> and <code>b</code>. Recall tha... | 2 | 2016-07-25T01:24:13Z | [
"python"
] |
Cloudant query slow speed using $or or $in | 38,557,485 | <p>I have an index setup for a field "userid". When I try and query with an and $or, I get a bad request. </p>
<pre><code>query = cloudant.query.Query(db,selector={'$or':[{'userid': 35916}, {'userid': 11035}]},fields=['userid'])
</code></pre>
<p>Adding '_id' first works fine but it takes too long to get all docs firs... | 0 | 2016-07-24T22:32:59Z | 38,575,497 | <p>For what it's worth, I created a <code>"type": "json"</code> Cloudant Query index and followed the python-cloudant docs at <a href="http://python-cloudant.readthedocs.io/en/latest/getting_started.html" rel="nofollow">http://python-cloudant.readthedocs.io/en/latest/getting_started.html</a> to write some simple test c... | 1 | 2016-07-25T18:57:09Z | [
"python",
"cloudant"
] |
Unable to install xlrd 1.0.0 wheel | 38,557,513 | <p>I am trying to install the wheel : xlrd-1.0.0-py3-none-any.whl on a 2.7.12 python. windows 7 64 bit and 32 bit cmd.</p>
<pre><code>I get the error msg: xlrd-1.0.0-py3-none-any.whl is not a supported wheel for this platform.
</code></pre>
<p>I downloaded the wheel from <a href="https://pypi.python.org/pypi/xlrd" re... | 0 | 2016-07-24T22:36:03Z | 38,557,596 | <p>Look the error message:</p>
<blockquote>
<p>xlrd-1.0.0-<strong>py3</strong>-none-any.whl is not a supported wheel for this
platform.</p>
</blockquote>
<p>I might be wrong, but py3 is Python 3. So not Python 2.7.
With Python 2.7+, they maybe mean 2.7.xx+, so that's still Python 3.</p>
<p>Try installing it from... | 2 | 2016-07-24T22:47:35Z | [
"python",
"xlrd"
] |
How to get all the unique words in the data frame? | 38,557,617 | <p>I have a dataframe with a list of products and its respective review</p>
<p>+---------+------------------------------------------------+<br>
| product | review |<br>
+---------+------------------------------------------------+<br>
| product_a | It's good for a casual lu... | 0 | 2016-07-24T22:50:59Z | 38,558,245 | <p>Starting with this: </p>
<pre><code>dfx
review
0 United Kingdom
1 The United Kingdom
2 Dublin, Ireland
3 Mardan, Pakistan
</code></pre>
<p>To get all words in the "review" column:</p>
<pre><code> list(dfx['review'].str.split(' ', expand=True).stack().unique())
['United', 'Kingdom'... | 1 | 2016-07-25T00:37:02Z | [
"python",
"pandas",
"dataframe",
"count"
] |
python windows mouse hook crash | 38,557,655 | <p>I'm setting up a mouse hook in python like that:</p>
<pre><code>def listen():
global hook_id
def low_level_handler(aCode, wParam, lParam):
if aCode != win32con.HC_ACTION:
return ctypes.windll.user32.CallNextHookEx(hook_id, aCode, wParam, lParam)
return ctypes.windll.user32.Call... | 0 | 2016-07-24T22:56:34Z | 38,563,501 | <p>It looks like def low_level_handler was going out of scope and being garbage collected (?) / removed from memory. After I moved it out of def listen, it's all working.</p>
| 1 | 2016-07-25T08:59:23Z | [
"python",
"windows",
"hook",
"mouse"
] |
python `getattr` like function that accepts dotted string | 38,557,707 | <p>I would like to implement a function which is similar to <code>getattr</code> but will accept a dotted string and traverse through each attributes.</p>
<pre><code>def getattr_multiple_level(obj, attr_string):
attr_names = attr_string.split('.')
next_level = obj
for attr_name in attr_names:
next_... | 0 | 2016-07-24T23:03:29Z | 38,558,023 | <p>Yes, there is "build-in way". You can use property decorator. <a href="https://docs.python.org/2/library/functions.html#property" rel="nofollow">https://docs.python.org/2/library/functions.html#property</a></p>
<pre><code>class Author(object):
def __init__(self, full_name):
self.full_name = full_name
... | 0 | 2016-07-24T23:56:59Z | [
"python",
"oop",
"object",
"attributes"
] |
MultiIndex / Advanced Indexing where a level is not (!=) a value | 38,557,709 | <p>How do you slice the following df such that the second level != two.</p>
<p>In my real world case my second level are date ranges and I want to be able to select everything except for one date.</p>
<p>From <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html" rel="nofollow">MultiIndex / Advanced Inde... | 1 | 2016-07-24T23:03:47Z | 38,557,948 | <p>Starting with this: </p>
<pre><code> A B C
first second
bar one -0.350640 -1.761671 0.253923
two -0.036557 0.212322 0.537106
baz one -1.597584 -0.301356 -0.634428
two 2.340900 -0.356272 -0.985386
foo one 0.122753... | 2 | 2016-07-24T23:43:03Z | [
"python",
"pandas",
"indexing",
"slice"
] |
how to import python PIL on android and kivy? | 38,557,731 | <p>I want to create an application that takes photos from camera and show thumbnails of them on android. The related part of my code is:</p>
<pre><code>from plyer import camera
from PIL import Image
.
.
.
def take_photo_from_camera(self, x):
filename = str(random.randint(0, 100000000000)) # create random f... | 0 | 2016-07-24T23:06:46Z | 38,597,155 | <p>Use pygame instead of PIL for basic image manipulation processes.
Add pygame to the buildozer requirements list, it works without any problem.</p>
<pre><code>import pygame
picture = pygame.image.load(filepath)
picture = pygame.transform.scale(picture, (100, 100))
pygame.image.save(picture, "scaled_image.png")
</cod... | 0 | 2016-07-26T18:16:27Z | [
"android",
"python",
"python-imaging-library",
"kivy"
] |
How do we call a normal function where a coroutine is expected? | 38,557,768 | <p>Consider a coroutine which calls into another coroutine:</p>
<pre><code>async def foo(bar):
result = await bar()
return result
</code></pre>
<p>This works fine if <code>bar</code> is a coroutine.
What do I need to do (i.e. with what do I need to wrap the call to <code>bar</code>) so that this code does t... | 3 | 2016-07-24T23:12:45Z | 38,563,919 | <p>Simply wrap your synchronous function with <a href="https://docs.python.org/3.4/library/asyncio-task.html#asyncio.coroutine" rel="nofollow">asyncio.coroutine</a> if needed:</p>
<pre><code>if not asyncio.iscoroutinefunction(bar):
bar = asyncio.coroutine(bar)
</code></pre>
<p>Since it is safe to re-wrap a corout... | 2 | 2016-07-25T09:18:02Z | [
"python",
"concurrency",
"python-asyncio"
] |
How to reply to a particular user's most recent tweet using Tweepy? | 38,557,830 | <p>I found this code</p>
<pre><code>toReply = "xxx"
api = tweepy.API(auth)
tweets = api.user_timeline(screen_name = toReply, count=1)
for tweet in tweets:
api.update_status("@" + toReply + " my reply", in_reply_to_status_id = tweet.id)
</code></pre>
<p>But it's not what I'm looking for. It just replies to the la... | 0 | 2016-07-24T23:22:02Z | 38,557,852 | <pre><code>while True:
for tweet in api.user_timeline(...):
</code></pre>
| 1 | 2016-07-24T23:25:52Z | [
"python",
"twitter",
"bots",
"tweepy"
] |
A simple 1-D peak finding program in python | 38,557,849 | <p>A peak finding program in a 1-D python list which returns a peak with its index if for an index 'x' in the list 'arr' if (arr[x] > arr[x+1] and arr[x] > arr[x-1]).
Special case
Case 1 : In case of the first element. Only compare it to the second element. If arr[x] > arr[x+1], peak found.
Case 2 : Last element. Compa... | 1 | 2016-07-24T23:25:10Z | 38,557,877 | <p>Your issue lies in the initialization of your loop</p>
<pre><code>for x in lst:
</code></pre>
<p>With this loop, for your last example, x will be 4, then 3, then 2, then 1.</p>
<p>By the looks of your code, it seems you intended to say:</p>
<pre><code>for x in range(len(lst)):
</code></pre>
<p>This will iterate... | 1 | 2016-07-24T23:29:27Z | [
"python",
"arrays",
"python-2.7",
"python-3.x"
] |
A simple 1-D peak finding program in python | 38,557,849 | <p>A peak finding program in a 1-D python list which returns a peak with its index if for an index 'x' in the list 'arr' if (arr[x] > arr[x+1] and arr[x] > arr[x-1]).
Special case
Case 1 : In case of the first element. Only compare it to the second element. If arr[x] > arr[x+1], peak found.
Case 2 : Last element. Compa... | 1 | 2016-07-24T23:25:10Z | 38,557,885 | <p>x is a list element in your code and you are using it as an index.</p>
<p>you should write:</p>
<pre><code>def find_peak(lst):
for i,x in enumerate(lst):
if i == 0 and x > lst[i+1]:
print "Peak found at index", i
print "Peak :", x
return
elif i == len(lst... | 1 | 2016-07-24T23:31:04Z | [
"python",
"arrays",
"python-2.7",
"python-3.x"
] |
Confusions on /account/ vs /admin/ views (any built in way to create these) | 38,557,850 | <p>I have begun to implement authentication throughout my applications in Django and have done this quite successfully with the Django login_required decorator.</p>
<p>However, I notice that this will always reroute to the deafault login URL: <code>/accounts/...</code> which is non-existent for me. I have been doing a... | 0 | 2016-07-24T23:25:29Z | 38,557,915 | <p>The '/accounts/' is just a url that out of best practices most people when handling authentication. There are no built in templates for accounts. the '/accounts/' is just a default placed. </p>
<p>To change the url to fit your applications url, go to your <em>settings.py</em> file and you can add a <strong>LOGIN_UR... | 1 | 2016-07-24T23:36:51Z | [
"python",
"django",
"authentication",
"django-models",
"django-admin"
] |
Confusions on /account/ vs /admin/ views (any built in way to create these) | 38,557,850 | <p>I have begun to implement authentication throughout my applications in Django and have done this quite successfully with the Django login_required decorator.</p>
<p>However, I notice that this will always reroute to the deafault login URL: <code>/accounts/...</code> which is non-existent for me. I have been doing a... | 0 | 2016-07-24T23:25:29Z | 38,557,924 | <p>If you are not logged in, Django uses the <a href="https://docs.djangoproject.com/en/1.9/ref/settings/#login-url" rel="nofollow"><code>LOGIN_URL</code></a> to decide which url to redirect to. By default, this is set to <code>'/accounts/login/'</code>.</p>
<p>If you use a different login url, then you should update ... | 2 | 2016-07-24T23:38:25Z | [
"python",
"django",
"authentication",
"django-models",
"django-admin"
] |
performance of list.remove(value) in Python 2.7 | 38,557,960 | <p>Suppose a list contains a list of integers, if I call <code>list.remove(100)</code> to remove element with value 100, wondering if it is <code>O(n)</code> or <code>O(logN)</code>? I thought it is <code>O(n)</code>, but not sure if Python 2.7 list has any internal optimizations to improve performance even further. Th... | 0 | 2016-07-24T23:45:43Z | 38,557,982 | <p><a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">Removing an item from a list in Python is O(n)</a>. This is because the underlying space in memory must be "shifted over" now that an element is missing. There are other implementations of lists, such as a linked list, that you could use in Python ... | 1 | 2016-07-24T23:49:19Z | [
"python",
"list",
"python-2.7"
] |
Python files to class | 38,557,972 | <p>Would I be able to convert these files:</p>
<pre><code>### one.py ###
print("one")
### two.py ###
print("two")
</code></pre>
<p>to a Python class so then say I want to import <code>one.py</code>, I would be able to do:</p>
<pre><code>importFile(MyClass.one)
</code></pre>
<p>or something like that?</p>
| -1 | 2016-07-24T23:47:41Z | 38,558,158 | <p>You can do this by putting those statements into a class or a method and them importing the file. This is what <code>one.py</code> would look like if you wanted to make it into a method and then import it:</p>
<h2>one.py</h2>
<pre><code>def print_one():
print("one")
</code></pre>
<h2>Example file with two met... | 0 | 2016-07-25T00:20:46Z | [
"python",
"class",
"oop"
] |
No 'Access-Control-Allow-Origin' header present AngularJS | 38,558,014 | <p>I am trying to build a quick demo site that I do not have control over the server I am trying to connect to. Here is the code that I am using to build it with AngularJS. I am running the file through a simple Python HTTP Server and viewing it at localhost:8000.
var retrieveAppliances = function () {
cons... | 0 | 2016-07-24T23:55:33Z | 38,558,109 | <p>If you're running an Ajax call to a different origin (e.g. different host, port or protocol) and the server at that origin does not have support for cross origin requests, then you cannot fix that from your client. There is nothing you can do from the client.</p>
<p>If the server supported JSONP, you could use tha... | 3 | 2016-07-25T00:12:10Z | [
"javascript",
"python",
"angularjs",
"ajax",
"node.js"
] |
How can I put a Python function to sleep while still calling it (IFTTT) | 38,558,029 | <p>I have a Python function set up to text me if my house gets above 30 degrees Celsius. The script also drives and LCD display that loops through various bits of weather info: house temp, humidity, outdoor conditions, and the times of streetcars.</p>
<p>Because the script is based on a loop, I get a text message ever... | 0 | 2016-07-24T23:59:30Z | 38,558,077 | <p>Instead of trying to stop your loop from continuing, you should record when the last alert was sent and only resend if enough time has elapsed since the last alert.</p>
<p>Whenever a temperature alert gets sent, have it record the <code>datetime</code> to a variable. Each time the function is called, have it compar... | 0 | 2016-07-25T00:06:17Z | [
"python",
"function",
"loops",
"ifttt"
] |
How can I put a Python function to sleep while still calling it (IFTTT) | 38,558,029 | <p>I have a Python function set up to text me if my house gets above 30 degrees Celsius. The script also drives and LCD display that loops through various bits of weather info: house temp, humidity, outdoor conditions, and the times of streetcars.</p>
<p>Because the script is based on a loop, I get a text message ever... | 0 | 2016-07-24T23:59:30Z | 38,558,097 | <p>If I understand correctly, the problem is that you get too many texts. In that case, store some state about the previous events and use that to decide whether or not to send a text.</p>
<p>For example, a simple boolean (True/False) variable can be used as a simple flag. You can still use a loop, but only send an ev... | 0 | 2016-07-25T00:10:11Z | [
"python",
"function",
"loops",
"ifttt"
] |
Create dictionary from a list deleting all spaces | 38,558,068 | <p>sorry for asking but I'm kind of new to these things. I'm doing a splitting words from the text and putting them to dict creating an index for each token:</p>
<pre><code>import re
f = open('/Users/Half_Pint_Boy/Desktop/sentenses.txt', 'r')
a=0
c=0
e=[]
for line in f:
b=re.split('[^a-z]', line.lower())
a... | 0 | 2016-07-25T00:04:49Z | 38,558,095 | <p>How about this?</p>
<pre><code>b = list(filter(None, re.split('[^a-z]', line.lower())))
</code></pre>
<p>As an alternative:</p>
<pre><code>b = re.findall('[a-z]+', line.lower())
</code></pre>
<p>Either way, you can then also remove that <code>filter</code> from the next line:</p>
<pre><code>a += len(b)
</code><... | 2 | 2016-07-25T00:09:32Z | [
"python",
"dictionary"
] |
Create dictionary from a list deleting all spaces | 38,558,068 | <p>sorry for asking but I'm kind of new to these things. I'm doing a splitting words from the text and putting them to dict creating an index for each token:</p>
<pre><code>import re
f = open('/Users/Half_Pint_Boy/Desktop/sentenses.txt', 'r')
a=0
c=0
e=[]
for line in f:
b=re.split('[^a-z]', line.lower())
a... | 0 | 2016-07-25T00:04:49Z | 38,558,113 | <p>Replace:</p>
<pre><code>d = dict(zip(e, range(len(e))))
</code></pre>
<p>With:</p>
<pre><code>d = {word:n for n, word in enumerate(e) if word}
</code></pre>
<p>Alternatively, to avoid the empty entries in the first place, replace:</p>
<pre><code>b=re.split('[^a-z]', line.lower())
</code></pre>
<p>With:</p>
<... | 1 | 2016-07-25T00:13:05Z | [
"python",
"dictionary"
] |
Create dictionary from a list deleting all spaces | 38,558,068 | <p>sorry for asking but I'm kind of new to these things. I'm doing a splitting words from the text and putting them to dict creating an index for each token:</p>
<pre><code>import re
f = open('/Users/Half_Pint_Boy/Desktop/sentenses.txt', 'r')
a=0
c=0
e=[]
for line in f:
b=re.split('[^a-z]', line.lower())
a... | 0 | 2016-07-25T00:04:49Z | 38,558,160 | <p>Your regex looks not a good one. Consider to use:</p>
<pre><code>line = re.sub('[^a-z]*$', '', line.strip())
b = re.split('[^a-z]+', line.lower())
</code></pre>
| 1 | 2016-07-25T00:20:57Z | [
"python",
"dictionary"
] |
Python - Zip code to Barcode | 38,558,076 | <p>The code is supposed to take a 5 digit zip code input and convert it to bar codes as the output. The bar code for each digit is:</p>
<pre><code>{1:'...!!',2:'..!.!',3:'..!!.',4:'.!..!',5:'.!.!.',6:'.!!..',7:'!...!',8:'!..!.',9:'!.!..',0:'!!...'}
</code></pre>
<p>For example, the zip code 95014 is supposed to produ... | -1 | 2016-07-25T00:06:07Z | 38,558,273 | <p>Your code computes <code>rem</code> based on the sum of the digits, but you never use it to add the check-digit bars to the output (<code>answer</code> and <code>final</code>). You need to add code to do that in order to get the right answer. I suspect you're also not computing <code>rem</code> correctly, since you'... | 1 | 2016-07-25T00:41:44Z | [
"python",
"python-2.7"
] |
Python - Zip code to Barcode | 38,558,076 | <p>The code is supposed to take a 5 digit zip code input and convert it to bar codes as the output. The bar code for each digit is:</p>
<pre><code>{1:'...!!',2:'..!.!',3:'..!!.',4:'.!..!',5:'.!.!.',6:'.!!..',7:'!...!',8:'!..!.',9:'!.!..',0:'!!...'}
</code></pre>
<p>For example, the zip code 95014 is supposed to produ... | -1 | 2016-07-25T00:06:07Z | 38,558,456 | <p>Interesting problem. I noticed that you solved the problem as a C-style programmer. I'm guessing your background is in C/C++. I's like to offer a more Pythonic way:</p>
<pre><code>def printBarCode(zip_code):
digit_dict = {1:'...!!',2:'..!.!',3:'..!!.',4:'.!..!',5:'.!.!.',
6:'.!!..',7:'!...!',8... | 0 | 2016-07-25T01:16:09Z | [
"python",
"python-2.7"
] |
How can I convert Python number to 1 byte C type? | 38,558,174 | <p>I'm having some issues with communication between python script (on my laptop) and a C program running on a AVR microcontroller. They are communicating through UART. My issue is right now I have the following set up. </p>
<p>Python sending data:</p>
<pre><code>data = port.write(struct.pack("b", val))
</code></pre>... | 0 | 2016-07-25T00:24:01Z | 38,580,278 | <p>I discovered the problem. The code is correct. I have an issue with my AVR board or my UART module. When I was sending values 0 - 31 the board was receiving 0b11100000 - 0b11111111. For 32 - 63 the board was receiving 0b00100000 - 0b00111111. For 64 - 95 the board was receiving 0b11100000 - ob11111111. For 96 - 100 ... | 0 | 2016-07-26T02:46:43Z | [
"python",
"c",
"ctypes",
"avr"
] |
How can I convert Python number to 1 byte C type? | 38,558,174 | <p>I'm having some issues with communication between python script (on my laptop) and a C program running on a AVR microcontroller. They are communicating through UART. My issue is right now I have the following set up. </p>
<p>Python sending data:</p>
<pre><code>data = port.write(struct.pack("b", val))
</code></pre>... | 0 | 2016-07-25T00:24:01Z | 38,821,422 | <p>Let's have a quick look at the wire form of the transmissions. There's always a start bit 0, then eight data bits with LSB first, then a stop bit 1. From the description, we're getting strange data in 3 bits, correct in 5, so there are 8 patterns to compare. I'll write the wire format right to left here. </p>
<pre>... | 0 | 2016-08-08T04:43:04Z | [
"python",
"c",
"ctypes",
"avr"
] |
How can I convert Python number to 1 byte C type? | 38,558,174 | <p>I'm having some issues with communication between python script (on my laptop) and a C program running on a AVR microcontroller. They are communicating through UART. My issue is right now I have the following set up. </p>
<p>Python sending data:</p>
<pre><code>data = port.write(struct.pack("b", val))
</code></pre>... | 0 | 2016-07-25T00:24:01Z | 38,897,452 | <p>Just to exclude the microcontroller-side software from the "suspects" and concentrate on the communication line - connect Rx/Tx on MCU side and try to send and receive what you have just sent. Campare what you have received against what you have sent. Both sent and received buffers should match. Then we know for sur... | 0 | 2016-08-11T13:14:32Z | [
"python",
"c",
"ctypes",
"avr"
] |
Python 3 (CherryPy) Server Not Working on Other Computer | 38,558,201 | <p>I would like to access my CherryPy site on a different computer, but I have tried the answers form <a href="http://stackoverflow.com/questions/7494171/python-cherrypy-web-app-deployed-locally-but-not-visible-over-intranet">here</a> and <a href="http://stackoverflow.com/questions/115773/how-do-i-configure-the-ip-addr... | 1 | 2016-07-25T00:27:29Z | 38,999,933 | <p>The solution is mentioned in comments below the question so this answer is just for marking this question as answered.</p>
<p>Solution: If you want to see your cherrypy application from another computer, find out an IP address on computer where cherrypy is running, using <code>ifconfig</code> on Unix/Linux or <code... | 0 | 2016-08-17T14:51:14Z | [
"python",
"python-3.x",
"cherrypy"
] |
Quandl download wiki EOD stock prices from python - how to? | 38,558,318 | <ol>
<li>Is there a way to do a partial download on Quandl for the Wiki EOD Stock Prices but for a given day in the past - not the most current date e.g. download for 2016-07-20?</li>
</ol>
<p>Entire database (too large): <a href="https://www.quandl.com/data/WIKI/documentation/bulk-download" rel="nofollow">https://www... | 0 | 2016-07-25T00:50:09Z | 38,581,313 | <ol>
<li><p>It does not seem possible according to Quandl. There is no parameter for the date. Only partial or complete.</p></li>
<li><p>The python code is: </p></li>
</ol>
<p>import quandl
quandl.ApiConfig.api_key = 'XXXXX'
quandl.bulkdownload("WIKI",download_type="partial",filename="./WIKI.zip")</p>
| 0 | 2016-07-26T05:00:03Z | [
"python",
"quandl"
] |
print not working in while loop | 38,558,327 | <p>I want to check a some value using "time". However when I use the time function, the print is not working. The source code is below.</p>
<pre><code>import time
def display():
print "Something..."
while(1):
time.sleep(1)
display()
</code></pre>
<p>My environment is windows 10, mingw, vim, python2.7.</... | -3 | 2016-07-25T00:52:38Z | 38,558,682 | <pre><code>import time
def display(something):
print something
index = 1
while(1):
time.sleep(1)
display(index)
index += 1
</code></pre>
| -1 | 2016-07-25T01:51:55Z | [
"python",
"time",
"while-loop"
] |
Tkinter Text widget : Fetching Cursor Selection | 38,558,405 | <p>I have a text widget, and I have the text </p>
<pre><code>this is some random text
</code></pre>
<p>With the keyboard cursor in the word "<code>random</code>". How can I get the start and end index of the cursor selection.</p>
<p>Thanks in advance!</p>
| -1 | 2016-07-25T01:07:24Z | 38,558,437 | <p>You can get the index of the start of the word by applying the modifier <code>"wordstart"</code> to an index. To get the end of the word, use <code>"wordend"</code>.</p>
<p>For example:</p>
<pre><code>start = text.index("insert wordstart")
end = text.index("insert wordend")
</code></pre>
| 0 | 2016-07-25T01:12:57Z | [
"python",
"text",
"indexing",
"tkinter",
"cursor"
] |
How is it possible to take a slice this way? | 38,558,428 | <p>I'm taking a course in machine learning and there was a recommendation (about making a balancing of classes) to use the following string: </p>
<pre><code>X_train_to_add = X_train[y_train.as_matrix() == 1, :][indices_to_add, :]
</code></pre>
<p>where <code>y_train</code> is a pandas dataframe (which is converted th... | 5 | 2016-07-25T01:11:18Z | 39,405,965 | <p>It might help to break down the statement into its component parts. This statement is equivalent to the following sequence of statements:</p>
<pre><code>y = y_train.as_matrix()
row_mask = y == 1
X_masked = X_train[row_mask,:]
X_train_to_add = X_masked[indices_to_add, :]
</code></pre>
<p>Let's look at a concrete e... | 0 | 2016-09-09T07:21:35Z | [
"python",
"numpy"
] |
Manipulating/Replacing values in dictionaries within lists | 38,558,511 | <p>My data looks similar to the data shown below ('snippet.json'). I want to be able to replace values for example, for id:1, replace employee number to 2455. </p>
<p>Data Snippet:</p>
<blockquote>
<p>{"employees": [{"level1":{"id":1, "firstname": "John", "employee
number": 2343 },{"level1":{"id":2, "firstname": ... | 0 | 2016-07-25T01:24:37Z | 38,559,256 | <p>Since you are importing json, you might want to do something like below,</p>
<pre><code>json_data = json.loads(viewer_string.read())
</code></pre>
<p>you have your data in dict type and you can loop through and replace values as you wish. Make sure the file has valid json</p>
| 0 | 2016-07-25T03:25:12Z | [
"python",
"json",
"list",
"dictionary"
] |
Epoch conversion not working as expected | 38,558,521 | <p>Using the following code I want to convert the input date and time to epoch. The problem is I get an epoch output, but when I test it via conversion online (<a href="http://www.epochconverter.com/" rel="nofollow">http://www.epochconverter.com/</a>), the epoch does not translate to the date and time I input:</p>
<pr... | 0 | 2016-07-25T01:26:31Z | 38,558,696 | <p>What is happening here:</p>
<ul>
<li><code>time.strptime</code> produces a <code>time.struct_time</code> which closely mirrors C's <code>tm</code> struct;</li>
<li>The documentation of <a href="https://docs.python.org/2/library/time.html#time.mktime" rel="nofollow"><code>time.mktime</code></a> is then fairly clear ... | 1 | 2016-07-25T01:53:26Z | [
"python",
"time",
"epoch"
] |
Epoch conversion not working as expected | 38,558,521 | <p>Using the following code I want to convert the input date and time to epoch. The problem is I get an epoch output, but when I test it via conversion online (<a href="http://www.epochconverter.com/" rel="nofollow">http://www.epochconverter.com/</a>), the epoch does not translate to the date and time I input:</p>
<pr... | 0 | 2016-07-25T01:26:31Z | 38,559,042 | <p>(I already upvoted @donkopotamus' answer here: <a href="http://stackoverflow.com/a/38558696/42346">http://stackoverflow.com/a/38558696/42346</a>)</p>
<p>Using this answer: <a href="http://stackoverflow.com/a/19527596/42346">http://stackoverflow.com/a/19527596/42346</a> we can see how you can convert your local time... | 1 | 2016-07-25T02:52:54Z | [
"python",
"time",
"epoch"
] |
Probability grid matplotlib | 38,558,613 | <p>I want to obtain grid with values mapped onto colors. It should be like a probability distribution, where 1.0 corresponds to black and 0.0 to white, grey in between. Reading the answers <a href="http://stackoverflow.com/questions/7229971/2d-grid-data-visualization-in-python">here</a> I try it out for my case:</p>
<... | 1 | 2016-07-25T01:42:44Z | 38,559,184 | <p>Use the <code>vmin</code> and <code>vmax</code> arguments of <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow" rel="nofollow"><code>imshow</code></a>:</p>
<pre><code>img = pyplot.imshow(zvals, interpolation='nearest', cmap=cmap, vmin=0, vmax=1)
</code></pre>
| 3 | 2016-07-25T03:14:44Z | [
"python",
"numpy",
"matplotlib"
] |
BlockingSwitchOutError in debugger after upgrading to PyCharm 2016.2 | 38,558,637 | <p>After upgrading from PyCharm 2016.1.4 to 2016.2, when running the debugger and setting any breakpoint, PyCharm halts in various places where I have no breakpoint set, and logs this to stderr:</p>
<pre><code>Traceback (most recent call last):
File "/usr/local/pycharm/debug-eggs/pycharm-debug.egg/_pydevd_bundle/pyd... | 3 | 2016-07-25T01:46:49Z | 38,579,291 | <p>The solution posted by Elizaveta Shashkova on the PyCharm issue tracker at <a href="https://youtrack.jetbrains.com/issue/PY-20183" rel="nofollow">https://youtrack.jetbrains.com/issue/PY-20183</a> worked for me:</p>
<blockquote>
<p>The new feature has appeared in PyCharm: breakpoint thread suspend policy. You shou... | 2 | 2016-07-26T00:20:46Z | [
"python",
"debugging",
"pycharm"
] |
Generate a pandas dataframe from list of list | 38,558,667 | <p>I am wondering how to generate a pd DataFrame from a list of list which in this form:</p>
<p>Input: </p>
<pre><code>A=[['a','b','c'],['c','d','e'],['f','g','h']]
</code></pre>
<p>Output:(in a dataframe)</p>
<pre><code>No content
0 'a'
0 'b'
0 'c'
1 'c'
1 'd'
1 'e'
2 'f'
2 'g'
2 'h'
</code></pre>
| 1 | 2016-07-25T01:50:18Z | 38,558,738 | <p>You can try this:</p>
<pre><code>import pandas as pd
A1 = pd.DataFrame(A).stack().reset_index().drop('level_1', 1).rename(columns = {'level_0': "No", 0: "content"})
A1
# No content
#0 0 a
#1 0 b
#2 0 c
#3 1 c
#4 1 d
#5 1 e
#6 2 f
#7 2 g
#8 2 ... | 1 | 2016-07-25T02:01:08Z | [
"python",
"list",
"pandas",
"dictionary",
"dataframe"
] |
Generate a pandas dataframe from list of list | 38,558,667 | <p>I am wondering how to generate a pd DataFrame from a list of list which in this form:</p>
<p>Input: </p>
<pre><code>A=[['a','b','c'],['c','d','e'],['f','g','h']]
</code></pre>
<p>Output:(in a dataframe)</p>
<pre><code>No content
0 'a'
0 'b'
0 'c'
1 'c'
1 'd'
1 'e'
2 'f'
2 'g'
2 'h'
</code></pre>
| 1 | 2016-07-25T01:50:18Z | 38,558,759 | <p>You can melt the transpose of the dataframe to produce your desired result.</p>
<pre><code>import pandas as pd
>>> pd.melt(pd.DataFrame(A).T, var_name='No.', value_name='content')
No. content
0 0 a
1 0 b
2 0 c
3 1 c
4 1 d
5 1 e
6 2 f
7 2... | 2 | 2016-07-25T02:06:18Z | [
"python",
"list",
"pandas",
"dictionary",
"dataframe"
] |
Generate a pandas dataframe from list of list | 38,558,667 | <p>I am wondering how to generate a pd DataFrame from a list of list which in this form:</p>
<p>Input: </p>
<pre><code>A=[['a','b','c'],['c','d','e'],['f','g','h']]
</code></pre>
<p>Output:(in a dataframe)</p>
<pre><code>No content
0 'a'
0 'b'
0 'c'
1 'c'
1 'd'
1 'e'
2 'f'
2 'g'
2 'h'
</code></pre>
| 1 | 2016-07-25T01:50:18Z | 38,558,806 | <p>Try this use zip() on your list:</p>
<pre><code>df = pd.melt(pd.DataFrame(zip(*A))).rename(columns= {'variable':'no','value':'content' })
no content
0 0 a
1 0 b
2 0 c
3 1 c
4 1 d
5 1 e
6 2 f
7 2 g
8 2 h
</code></pre>
| 0 | 2016-07-25T02:13:42Z | [
"python",
"list",
"pandas",
"dictionary",
"dataframe"
] |
Tensorflow memory leak with Recurrent Neural Network | 38,558,680 | <p>I'm trying to build a simple Recurrent Neural Network model by using tensorflow on Mac OS X. It is just a toy model and size of input data doesn't exceed 3MB so it should not consume much of memory. However, when I run model, the memory usage significantly increases every training batch and goes above 10GB. It was f... | 0 | 2016-07-25T01:51:40Z | 38,564,534 | <p>I think the problem is that this line</p>
<pre><code>train_step = tf.train.GradientDescentOptimizer(self.learning_rate).minimize(loss)
</code></pre>
<p>occurs in your batch_train function, so on every iteration, a <strong>new</strong> GradientDescentOptimizer is created. Try moving this to your model's init functi... | 0 | 2016-07-25T09:49:34Z | [
"python",
"memory-leaks",
"tensorflow",
"recurrent-neural-network"
] |
Using pytube library to download youtube links from csv | 38,558,744 | <p>I'm trying to use the <a href="https://github.com/nficano/pytube" rel="nofollow">pytube library</a> to download a bunch of links I have on a .csv file.</p>
<p><strong>EDIT:</strong></p>
<p><strong>WORKING CODE</strong>:</p>
<pre><code> import sys
reload(sys)
sys.setdefaultencoding('Cp1252')
import os.path
fro... | 2 | 2016-07-25T02:02:54Z | 38,559,250 | <p>To install it you need to use</p>
<pre><code>pip install pytube
</code></pre>
<p>and then in your code run</p>
<pre><code>from pytube import YouTube
</code></pre>
<p>I haven't seen any code examples of using this with csv though, are you sure it's supported?</p>
<p>You can download via command line directly us... | 3 | 2016-07-25T03:24:18Z | [
"python",
"csv"
] |
Django: Reverse for 'delete' with arguments '(49,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['tidbit/delete_tidbit/'] | 38,558,755 | <p>Can't figure out how to solve this error</p>
<p>Here is the urls.py snippet:</p>
<pre><code>urlpatterns = [
...
url(r'^delete_tidbit/', views.delete_tidbit, name='delete'),
...
]
</code></pre>
<p>The view:</p>
<pre><code>def delete_tidbit(request, pk):
tidbit = Tidbit.objects.get(pk=pk)
tidbi... | 1 | 2016-07-25T02:04:59Z | 38,558,779 | <p>The issue is here:</p>
<pre><code>url(r'^delete_tidbit/', views.delete_tidbit, name='delete'),
</code></pre>
<p>This URL doesn't accept an argument, where as you are trying to give it one.</p>
<p>Try this instead:</p>
<pre><code>url(r'^delete_tidbit/(?P<pk>.*)', views.delete_tidbit, name='delete'),
</code>... | 2 | 2016-07-25T02:09:32Z | [
"python",
"django",
"backend"
] |
Using pandas and EWMA | 38,558,763 | <p>I am accustomed to exponential moving average (EMA) being calculated the <a href="http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averages" rel="nofollow">following</a> way:</p>
<pre><code>SMA: 10 period sum / 10
Multiplier: (2 / (Time periods + 1) ) = (2 / (10 + 1) ) = 0.1818 (... | 0 | 2016-07-25T02:07:21Z | 38,563,432 | <p>I think you were almost on there on your own. </p>
<pre><code>e = f['Adj Close'].ewm(span=10, min_periods=10)
</code></pre>
<p>will generate what you are looking for. You may need to play around with adjust=True and other <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.ewma.html" re... | 0 | 2016-07-25T08:56:13Z | [
"python",
"pandas"
] |
How to call a model method, using the object as parameter in Django? | 38,558,808 | <p>I want to generate a table on my template, showing some data that I get from a method declared on my Task class</p>
<h1>models.py</h1>
<pre><code>class Task(models.Model):
...
def check_if_finished(self):
resp = requests.get(
'http://my.rest.api/tasks/view/{}'.format(self.task_id))
resp_data = resp.js... | 0 | 2016-07-25T02:14:07Z | 38,559,010 | <p>I don't fully understand your question, why can't you just sent in task_id as a parameter?</p>
<pre><code>class Task(models.Model):
...
def check_if_finished(self, task_id):
resp = requests.get(
'http://my.rest.api/tasks/view/{}'.format(task_id))
resp_data = resp.json()
resp_finished = resp_data['t... | 0 | 2016-07-25T02:48:39Z | [
"python",
"django"
] |
How to call a model method, using the object as parameter in Django? | 38,558,808 | <p>I want to generate a table on my template, showing some data that I get from a method declared on my Task class</p>
<h1>models.py</h1>
<pre><code>class Task(models.Model):
...
def check_if_finished(self):
resp = requests.get(
'http://my.rest.api/tasks/view/{}'.format(self.task_id))
resp_data = resp.js... | 0 | 2016-07-25T02:14:07Z | 38,561,263 | <p>When you write a model method you pass on <code>self</code> as parameter, which obviously refers to instance itself. Change your model method to something like this</p>
<pre><code>class Task(models.Model):
fields
def is_finished(self):
return appropriate boolean from here
</code></pre>
<p>Now in yo... | 1 | 2016-07-25T06:45:55Z | [
"python",
"django"
] |
Hashing raw bytes in Python and Java produces different results | 38,558,820 | <p>I'm trying to <strong>replicate the behavior of a Python 2.7 function in Java</strong>, but I'm getting different results when running a (seemingly) identical sequence of bytes through a SHA-256 hash. The bytes are generated by manipulating a very large integer (exactly 2048 bits long) in a specific way (2nd line of... | 0 | 2016-07-25T02:15:36Z | 38,558,996 | <p>In Java, you've got the data in the buffer, but the cursor positions are all wrong. After you've written your data to the ByteBuffer it looks like this, where the <em>x</em>'s represent your data and the <em>0</em>'s are unwritten bytes in the buffer:</p>
<pre><code>xxxxxxxxxxxxxxxxxxxx00000000000000000000000000000... | 2 | 2016-07-25T02:46:33Z | [
"java",
"python",
"bytebuffer",
"hashlib",
"message-digest"
] |
Use list/set comprehension merely as a "for" loop? | 38,558,834 | <p>I am creating a set of NUM_RECORDS tuples in Python. This is my code.</p>
<pre><code>record_key_list = {(choice(tuple(studentID_list)),
choice(tuple(courseID_list)),
randint(2012, 2016),
choice(semesters),
choice(grades)[0])
... | 0 | 2016-07-25T02:17:47Z | 38,839,057 | <p>The first code snippet looks totally fine. If anything, I would extract the record creation to a function for clarity and easier refactoring.</p>
<pre><code>def random_record():
studentID = choice(studentID_list)
courseID = choice(courseID_list)
year = randint(2012, 2016)
semester = choice(semesters... | 1 | 2016-08-08T21:51:05Z | [
"python",
"python-2.7",
"list-comprehension",
"set-comprehension"
] |
Cannot create dictionary with tuples and values? (list indices must be integers, not str) | 38,558,871 | <pre><code>q_values_table = {}
light = ['red', 'green']
v_actions = ['None','forward','left','right']
for i in v_actions:
for j in light:
for k in v_actions:
for l in v_actions:
for m in v_actions:
q_values_table[v_actions[i],light[j],v_actions[k],v_actions[... | 1 | 2016-07-25T02:23:27Z | 38,558,888 | <p>When you iterate a <code>list</code>, you get values, not indices. If you want indices, use <code>range</code>:</p>
<pre><code>for i in range(len(v_actions)):
...
</code></pre>
<p>If you want indices and values, use <code>enumerate</code>:</p>
<pre><code>for i, value in enumerate(v_actions):
...
</code></... | 2 | 2016-07-25T02:28:17Z | [
"python",
"python-2.7"
] |
Cannot create dictionary with tuples and values? (list indices must be integers, not str) | 38,558,871 | <pre><code>q_values_table = {}
light = ['red', 'green']
v_actions = ['None','forward','left','right']
for i in v_actions:
for j in light:
for k in v_actions:
for l in v_actions:
for m in v_actions:
q_values_table[v_actions[i],light[j],v_actions[k],v_actions[... | 1 | 2016-07-25T02:23:27Z | 38,558,890 | <p>just replace the last line with:</p>
<p><code>q_values_table[ i, j, k, l, m ] = None</code></p>
| 1 | 2016-07-25T02:28:53Z | [
"python",
"python-2.7"
] |
Cannot create dictionary with tuples and values? (list indices must be integers, not str) | 38,558,871 | <pre><code>q_values_table = {}
light = ['red', 'green']
v_actions = ['None','forward','left','right']
for i in v_actions:
for j in light:
for k in v_actions:
for l in v_actions:
for m in v_actions:
q_values_table[v_actions[i],light[j],v_actions[k],v_actions[... | 1 | 2016-07-25T02:23:27Z | 38,558,904 | <p>You can also use range(len(lst)) to just iterate over the indices of the list:</p>
<pre><code>q_values_table = {}
light = ['red', 'green']
v_actions = ['None','forward','left','right']
for i in range(len(v_actions)):
for j in range(len(light)):
for k in range(len(v_actions)):
for l in range(... | 0 | 2016-07-25T02:31:00Z | [
"python",
"python-2.7"
] |
Why gevent can speed up requests to download? | 38,558,898 | <p>I think <code>requests.get</code> should be block, so there should be no difference between run and run2.</p>
<pre><code>import sys
import gevent
import requests
from gevent import monkey
monkey.patch_all()
def download():
requests.get('http://www.baidu.com').status_code
def run():
ls = [gevent.spawn(downl... | 0 | 2016-07-25T02:30:12Z | 38,558,952 | <p>From the <a href="http://gevent.org" rel="nofollow">gevent website</a>:</p>
<blockquote>
<p>Fast event loop based on libev (epoll on Linux, kqueue on FreeBSD).</p>
<p>Lightweight execution units based on greenlet.</p>
<p>API that re-uses concepts from the Python standard library (for example there are g... | -1 | 2016-07-25T02:39:00Z | [
"python",
"python-requests",
"gevent"
] |
How to remote access PostgreSQL database and get its dump to local? | 38,558,901 | <p>I need to access the remote database server(linux) and also take its dump to my local(mac). </p>
<pre><code>DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'test-name',
'USER': 'test-user',
'PASSWORD': 'pwd',
'HOST': 'test.amazonaws.com',
}
}
</code></p... | -1 | 2016-07-25T02:30:37Z | 38,559,183 | <p>In local bash, you can connect and dump the remote database with <code>pg_dump</code> command, see <a href="http://stackoverflow.com/questions/1237725/copying-postgresql-database-to-another-server">Copying PostgreSQL database to another server</a></p>
<p>Using Python is similar, except that you need to use <code>ps... | 0 | 2016-07-25T03:14:03Z | [
"python",
"django",
"database",
"postgresql"
] |
How to remove 'u' efficiently in django querySet? | 38,558,902 | <p>I'm making simple django app.
I made database and I want to call it from javascript code.
Everything was fine, but I had some problem with 'u' string..</p>
<p>models.py</p>
<pre><code>class FileDB(models.Model):
fileName = models.CharField(max_length=200)
fileState = models.IntegerField(default=0)
</code></pre... | -2 | 2016-07-25T02:30:38Z | 38,559,287 | <p>You can to use <code>json</code> library.</p>
<pre><code>import json
from .models import FileDB
def get_file_list(request, state):
list = list(FileDB.objects.filter(fileState=state).values())
return HttpsResponse(json.dumps(list))
</code></pre>
<p>This should give you something like this</p>
<pre><code>[... | 3 | 2016-07-25T03:29:39Z | [
"python",
"django"
] |
How to remove 'u' efficiently in django querySet? | 38,558,902 | <p>I'm making simple django app.
I made database and I want to call it from javascript code.
Everything was fine, but I had some problem with 'u' string..</p>
<p>models.py</p>
<pre><code>class FileDB(models.Model):
fileName = models.CharField(max_length=200)
fileState = models.IntegerField(default=0)
</code></pre... | -2 | 2016-07-25T02:30:38Z | 38,559,308 | <p>You can remove the <code>u</code> characters from the keys and values of a dictionary by using a dictionary comprehension and casting the </p>
<pre><code>>>> x = {'fileState': 0, u'id': 1, 'fileName': u'image.jpg'}
>>> {str(k): str(v) for k, v in x.iteritems()}
{'fileState': '0', 'id': '1', 'fileN... | 0 | 2016-07-25T03:32:02Z | [
"python",
"django"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.