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 |
|---|---|---|---|---|---|---|---|---|---|
Given an odd length list of values in Python, how can I swap all values other than the final value in the list? | 38,840,017 | <p>In regards to Python 2.7.12 (<em>disclaimer: I understand Python2 is being phased out to Python3, but the course I'm taking started us here, perhaps to understand older code bases</em>):</p>
<p>I have a list of integers whom I'd like to swap each with their neighboring value. So far, this works great for lists that... | 3 | 2016-08-08T23:39:20Z | 38,862,783 | <p>looks like <code>:</code> and <code>::</code> confuse you a little, let me explain it:</p>
<p>Sequences type of object in python such as list, tuple, str, among other provide what is know as a slice, it come in 2 flavors:</p>
<p>Slicing: a[i:j] selects all items with index k such that i <= k < j. When used a... | 1 | 2016-08-10T01:16:59Z | [
"python",
"list"
] |
How to install google-api-python-client via terminal | 38,840,114 | <p>i'n trying to install google-api-python-client package, using terminal and </p>
<pre><code>pip install --upgrade google-api-python-client
</code></pre>
<p>the same result for </p>
<pre><code>sudo -H pip install --upgrade google-api-python-client
</code></pre>
<p>also I found, that someone recommends to use such... | 0 | 2016-08-08T23:55:09Z | 38,840,591 | <p>Install with virtualenv</p>
<pre><code>virtualenv temp
source temp/bin/activate
pip install --upgrade google-api-python-client
</code></pre>
<p>or ignore Six</p>
<pre><code>sudo pip install --upgrade google-api-python-client --ignore-installed six
</code></pre>
| 0 | 2016-08-09T01:14:12Z | [
"python",
"google-api"
] |
Pros and Cons of manually creating an ORM for an existing database? | 38,840,193 | <p>What are the pros and cons of manually creating an ORM for an existing database vs using database reflection?</p>
<p>I'm writing some code using SQLAlchemy to access a pre-existing database. I know I can use <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/automap.html" rel="nofollow"><code>sqlalchemy.e... | 0 | 2016-08-09T00:05:00Z | 38,859,286 | <p>I see a lot of tables that were created with: <code>CREATE TABLE suppliers
AS (SELECT * FROM companies WHERE 1 = 2 );</code>, (a poor man's table copy), which will have no primary keys. If existing tables don't have primary keys, you'll have to constantly catch exceptions and feed <code>Column</code> objects into ... | 0 | 2016-08-09T19:49:58Z | [
"python",
"database",
"orm",
"sqlalchemy"
] |
Cannot drop table in pandas to_sql using SQLAlchemy | 38,840,208 | <p>I'm trying to drop an existing table, do a query and then recreate the table using the pandas to_sql function. This query works in pgadmin, but not here. Any ideas of if this is a pandas bug or if my code is wrong? </p>
<p>Specific error is <code>ValueError: Table 'a' already exists.</code></p>
<pre><code>import p... | 0 | 2016-08-09T00:06:19Z | 38,840,246 | <p>Why are you doing this like that? There is a shorter way: the <code>if_exists</code> kwag in <code>to_sql</code>. Try this:</p>
<pre><code>import pandas.io.sql as psql
from sqlalchemy import create_engine
engine = create_engine(r'postgresql://user@localhost:port/dbname')
c = engine.connect()
conn = c.connection
... | 1 | 2016-08-09T00:13:13Z | [
"python",
"pandas",
"sqlalchemy"
] |
Beautifulsoup how does findAll work | 38,840,221 | <p>I've noticed some weird behavior of <code>findAll</code>'s method:</p>
<pre><code>>>> htmls="<html><body><p class=\"pagination-container\">slytherin</p><p class=\"pagination-container and something\">gryffindor</p></body></html>"
>>> soup=BeautifulSo... | 2 | 2016-08-09T00:08:08Z | 38,840,286 | <p>First of all, <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class" rel="nofollow"><code>class</code></a> is a special <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#multi-valued-attributes" rel="nofollow">multi-valued space-delimited attribute</a> and has a special... | 4 | 2016-08-09T00:20:01Z | [
"python",
"beautifulsoup"
] |
Django PyCrypto - Save Encrypted String to Database Bad Unicode Data | 38,840,305 | <p>I'm working with PyCrypto in Django and I need to encrypt a string using the user's secret key they made themselves. I successfully wrote an encryption method as follows:</p>
<pre><code>from Crypto.Cipher import AES
from Crypto.Random import get_random_string
def encrypt(value, key):
"""
Return an encrypti... | 0 | 2016-08-09T00:23:12Z | 38,840,609 | <p>I guess you're trying to save binary data into <code>CharField</code>s. Either change field types of <code>user.iv</code> and <code>user.secret_value</code> to <code>BinaryField</code>, or encode these values using for example base64 encoder.</p>
| 1 | 2016-08-09T01:16:27Z | [
"python",
"django",
"unicode",
"pycrypto"
] |
Put a 2d Array into a Pandas Series | 38,840,319 | <p>I have a 2D Numpy array that I would like to put in a pandas Series (not a DataFrame):</p>
<pre><code>>>> import pandas as pd
>>> import numpy as np
>>> a = np.zeros((5, 2))
>>> a
array([[ 0., 0.],
[ 0., 0.],
[ 0., 0.],
[ 0., 0.],
[ 0., 0.]])
</co... | 2 | 2016-08-09T00:25:10Z | 38,840,533 | <p>Well, you can use the <code>numpy.ndarray.tolist</code> function, like so:</p>
<pre><code>>>> a = np.zeros((5,2))
>>> a
array([[ 0., 0.],
[ 0., 0.],
[ 0., 0.],
[ 0., 0.],
[ 0., 0.]])
>>> a.tolist()
[[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0... | 1 | 2016-08-09T01:05:25Z | [
"python",
"pandas",
"numpy"
] |
Put a 2d Array into a Pandas Series | 38,840,319 | <p>I have a 2D Numpy array that I would like to put in a pandas Series (not a DataFrame):</p>
<pre><code>>>> import pandas as pd
>>> import numpy as np
>>> a = np.zeros((5, 2))
>>> a
array([[ 0., 0.],
[ 0., 0.],
[ 0., 0.],
[ 0., 0.],
[ 0., 0.]])
</co... | 2 | 2016-08-09T00:25:10Z | 38,842,702 | <pre><code> pd.Series(list(a))
</code></pre>
<p>is consistently slower than </p>
<pre><code>pd.Series(a.tolist())
</code></pre>
<p>tested 20,000,000 -- 500,000 rows </p>
<pre><code>a = np.ones((500000,2))
</code></pre>
<p>showing only 1,000,000 rows:</p>
<pre><code>%timeit pd.Series(list(a))
1 loop, best of 3: 30... | 0 | 2016-08-09T05:27:45Z | [
"python",
"pandas",
"numpy"
] |
pyplot: how to explicitly number an axis in a human-readable way | 38,840,365 | <p>Pyplot has a strange feature where, for large numbers, the axis are scaled by non-base ten numbers, making it nearly impossible to read numeric values:</p>
<pre><code>x = [49856280.352, 49860580.25, 49861011.77, 49861103.034, 49861191.295, 49862295.297, 49862311.928, 49862755.161, 49863005.142, 49863331.328, 498637... | 1 | 2016-08-09T00:32:45Z | 38,840,476 | <p><a href="https://stackoverflow.com/questions/14711655/how-to-prevent-numbers-being-changed-to-exponential-form-in-python-matplotlib-fi">How to prevent numbers being changed to exponential form in Python matplotlib figure</a></p>
<pre><code>ax = plt.gca()
ax.get_xaxis().get_major_formatter().set_useOffset(False)
plt... | 2 | 2016-08-09T00:55:22Z | [
"python",
"matplotlib",
"graph",
"format",
"number-formatting"
] |
No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model | 38,840,366 | <p>I am using CreateView to build a form. The CreateView is called from the DetailView. Once the form is submitted, I want for the validated, submitted data to be returned back to the initial DetailView.</p>
<p>The DetailView calls up the CreateView just fine. The form works as expected until it is submitted. Then, I ... | 0 | 2016-08-09T00:32:57Z | 38,843,216 | <p>The best way to do this is to add a method <code>get_success_url</code> on the create view and use that to redirect back to the detail view. In the create view you have the object after it is saved, like so</p>
<p><code>
class LawyerReviewCreate(CreateView):
def get_success_url(self):
retur... | 0 | 2016-08-09T06:06:39Z | [
"python",
"django",
"forms",
"python-3.x",
"django-class-based-views"
] |
Python 2.7 TypeError: Unsupported operand type(s) for %:'None type' and str | 38,840,398 | <p>I've got an issue where when i try to print 'filename' i get this error</p>
<pre><code>line 101, in purchase_code_fn
print("QR Code Created: %s") %(filename)
TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'
</code></pre>
<p>Below is the offending function.</p>
<pre><code>def purchase_code_fn... | 0 | 2016-08-09T00:39:48Z | 38,840,416 | <p>I think you're trying to run Python 2 code with Python 3. In Python 3, <code>print</code> is a function, but a <em>statement</em> in Python 2.</p>
<p>The <code>print</code> function had already been executed and the formatting did not come a priori as you intended or would have in Python 2. So you are trying to for... | 1 | 2016-08-09T00:43:17Z | [
"python",
"python-3.x",
"typeerror"
] |
Python socket NAT port address | 38,840,434 | <p>I have a client socket behind a NAT and I want to get the local port number used by the process. </p>
<p>To illustrate my question, here's a quick example.</p>
<p>Let's say I create a server using the following code:</p>
<pre><code>welcome_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
welcome_socket.... | 0 | 2016-08-09T00:46:20Z | 38,840,576 | <p>It is likely that the Router is using Port Address Translation (or <a href="https://en.wikipedia.org/wiki/Network_address_translation#MASQUERADING" rel="nofollow">one-to-many NAT</a>). The wiki link further quotes</p>
<blockquote>
<p>PAT attempts to preserve the original source port. If this source port
is alre... | 0 | 2016-08-09T01:12:07Z | [
"python",
"sockets",
"nat"
] |
adding binary numbers without converting to decimal or using built in functions | 38,840,457 | <p>I'm adding two binary numbers inputted as strings and outputting their sum as a string in binary using this <a href="http://www.wikihow.com/Add-Binary-Numbers" rel="nofollow">method</a>.</p>
<p>Any thoughts on getting my code to work?</p>
<pre><code>def add(a,b):
a = list(a)
b = list(b)
equalize(a,b)
... | -1 | 2016-08-09T00:50:14Z | 38,843,223 | <p>Your algorithm is not really simple (I would rewrite it completely; I would also at least give functions and variables more explicit names in order to understand the algorithm again quicker later, like <code>ctr</code> should anyhow explicitely relate to carrying etc.).</p>
<p>Nevertheless, here it is, corrected an... | 0 | 2016-08-09T06:07:03Z | [
"python"
] |
Panda's dataframe split a column into multiple columns | 38,840,460 | <p>I have a pandas dataframe looks like as below:</p>
<pre><code>date | location | occurance <br>
------------------------------------------------------
somedate |united_kingdom_london | 5
somedate |united_state_newyork | 5
</code></pre>
<p>I want it to transform into </p>
<pre><code>date... | 2 | 2016-08-09T00:50:58Z | 38,840,754 | <p>Try this:</p>
<pre><code>temp_location = {}
splits = df['location'].str.split(' ')
temp_location['country'] = splits[0:-1].tolist()
temp_location['city'] = splits[-1].tolist()
location_data = pd.DataFrame(temp_location)
</code></pre>
<p>If you want it back in the original df:</p>
<pre><code>df['country'] = spl... | 0 | 2016-08-09T01:38:40Z | [
"python",
"pandas",
"dataframe"
] |
Panda's dataframe split a column into multiple columns | 38,840,460 | <p>I have a pandas dataframe looks like as below:</p>
<pre><code>date | location | occurance <br>
------------------------------------------------------
somedate |united_kingdom_london | 5
somedate |united_state_newyork | 5
</code></pre>
<p>I want it to transform into </p>
<pre><code>date... | 2 | 2016-08-09T00:50:58Z | 38,840,755 | <p>Consider splitting the column's string value using <a href="https://docs.python.org/3/library/stdtypes.html#str.rfind" rel="nofollow"><code>rfind()</code></a></p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Date': ['somedate', 'somedate'],
'location': ['united_kingdom_london', 'united_sta... | 0 | 2016-08-09T01:38:40Z | [
"python",
"pandas",
"dataframe"
] |
Panda's dataframe split a column into multiple columns | 38,840,460 | <p>I have a pandas dataframe looks like as below:</p>
<pre><code>date | location | occurance <br>
------------------------------------------------------
somedate |united_kingdom_london | 5
somedate |united_state_newyork | 5
</code></pre>
<p>I want it to transform into </p>
<pre><code>date... | 2 | 2016-08-09T00:50:58Z | 38,840,928 | <p>Something like this works</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'Date': ['somedate', 'somedate'],
'location': ['united_kingdom_london', 'united_state_newyork'],
'occurence': [5, 5]})
df.location = df.location.str[::-1].str.replace("_", " ", 1).str[::-1]
newcol... | 0 | 2016-08-09T02:01:21Z | [
"python",
"pandas",
"dataframe"
] |
Panda's dataframe split a column into multiple columns | 38,840,460 | <p>I have a pandas dataframe looks like as below:</p>
<pre><code>date | location | occurance <br>
------------------------------------------------------
somedate |united_kingdom_london | 5
somedate |united_state_newyork | 5
</code></pre>
<p>I want it to transform into </p>
<pre><code>date... | 2 | 2016-08-09T00:50:58Z | 38,841,061 | <p>Starting with this: </p>
<pre><code>df = pd.DataFrame({'Date': ['somedate', 'somedate'],
'location': ['united_kingdom_london', 'united_state_newyork'],
'occurence': [5, 5]})
</code></pre>
<p>Try this: </p>
<pre><code>df['Country'] = df['location'].str.rpartition('_')[0].str.r... | 2 | 2016-08-09T02:19:55Z | [
"python",
"pandas",
"dataframe"
] |
Panda's dataframe split a column into multiple columns | 38,840,460 | <p>I have a pandas dataframe looks like as below:</p>
<pre><code>date | location | occurance <br>
------------------------------------------------------
somedate |united_kingdom_london | 5
somedate |united_state_newyork | 5
</code></pre>
<p>I want it to transform into </p>
<pre><code>date... | 2 | 2016-08-09T00:50:58Z | 38,841,082 | <p>I would use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow">.str.extract()</a> method:</p>
<pre><code>In [107]: df
Out[107]:
Date location occurence
0 somedate united_kingdom_london 5
1 somedate united_state_newyork ... | 0 | 2016-08-09T02:23:11Z | [
"python",
"pandas",
"dataframe"
] |
Panda's dataframe split a column into multiple columns | 38,840,460 | <p>I have a pandas dataframe looks like as below:</p>
<pre><code>date | location | occurance <br>
------------------------------------------------------
somedate |united_kingdom_london | 5
somedate |united_state_newyork | 5
</code></pre>
<p>I want it to transform into </p>
<pre><code>date... | 2 | 2016-08-09T00:50:58Z | 38,842,754 | <p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.rsplit.html" rel="nofollow"><code>str.rsplit</code></a>, which works nice if country has no <code>_</code> (contains only one word):</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'date': {0: 'somedate', 1... | 1 | 2016-08-09T05:31:42Z | [
"python",
"pandas",
"dataframe"
] |
Converting an array of floats to an array of strings in scientific notation | 38,840,465 | <p>I want to convert the array created by numpy.linspace(1,10,1) to an array od strings in a scientific notation. How to do this?</p>
| 0 | 2016-08-09T00:52:04Z | 38,840,536 | <p>You can iterate over the elements of the array, and convert them to strings one by one:</p>
<pre><code>array = numpy.linspace(1, 10, 1)
["%e" % x for x in array]
</code></pre>
<p>Here <code>%e</code> renders the number in scientific notation. You can also use <code>%f</code> for a notation with decimal point, or <... | 0 | 2016-08-09T01:06:02Z | [
"python",
"numpy"
] |
now_time is not getting updated while code is looping | 38,840,492 | <p>i'm trying to do a loop, that keeps checking if time is between 2 times.. so it turns my lights on. but while its looping the current time does not get updated. im trying to create a aquarium controller, that turns 3 sets of lights on a different times. </p>
<p>thanks for your help :)</p>
<pre><code>from dateti... | 1 | 2016-08-09T00:58:00Z | 38,840,525 | <p>You'll need to keep updating <code>now_time</code> in your loop:</p>
<pre><code>while True:
if time (9,30) <= now_time <= time (16,15):
print "yes, within the interval"
now_time = datetime.now().time()
print now_time
time.sleep( 9 )
else:
print "no"
</code></pre... | 0 | 2016-08-09T01:03:12Z | [
"python"
] |
now_time is not getting updated while code is looping | 38,840,492 | <p>i'm trying to do a loop, that keeps checking if time is between 2 times.. so it turns my lights on. but while its looping the current time does not get updated. im trying to create a aquarium controller, that turns 3 sets of lights on a different times. </p>
<p>thanks for your help :)</p>
<pre><code>from dateti... | 1 | 2016-08-09T00:58:00Z | 38,840,600 | <p>If you want to do a loop, you should use one, like while.</p>
<pre><code>from datetime import datetime, time
now = datetime.now()
now_time = now.time()
SleepTimeL = 2
print time(19,30)
print now_time
while True:
if now_time >= time (9,30) and now_time <= time (16,15):
print "yes, within the inter... | 0 | 2016-08-09T01:15:34Z | [
"python"
] |
Can't create link when send email using Lotus Notes in Python | 38,840,590 | <p>I'm sorry for bad grammar before, I have case when send message using lotus notes in Python the link I embed in message is not generated as link (not clickable, and generate like plain text) in doc.Body and link not visible using doc.HTMLBody.</p>
<pre><code>sess=win32com.client.Dispatch("Notes.NotesSession")
db = ... | 0 | 2016-08-09T01:14:10Z | 38,842,680 | <p>Use <a href="http://www.ibm.com/support/knowledgecenter/SSVRGU_9.0.1/com.ibm.designer.domino.main.doc/H_NOTESMIMEENTITY_CLASS_OVERVIEW.html" rel="nofollow">NotesMIMEEntity</a> to <a href="http://www-01.ibm.com/support/docview.wss?uid=swg21098323" rel="nofollow">create a HTML formatted mail</a>.</p>
<p>Your example ... | 1 | 2016-08-09T05:25:43Z | [
"python",
"python-2.7",
"python-3.x",
"lotus-notes"
] |
intersection of np.array and set | 38,840,641 | <p>I would like to intersect an np.array with a set without having to convert the np.array to a list first (slows down the program to an unworkable level).</p>
<p>Here's my current code: (Note that I'm getting this data from b,g,r rawCapture, and selection_data is simply a set from beforehand.)</p>
<pre><code>def Gre... | 0 | 2016-08-09T01:20:24Z | 38,843,039 | <p>First a sample <code>data</code>; I'm guessing it's a nxnx3 array, with dtype <code>uint8</code></p>
<pre><code>In [791]: data=np.random.randint(0,256,(8,8,3),dtype=np.uint8)
</code></pre>
<p><code>reshape</code> method returns a new array with new shape, but doesn't change that in inplace:</p>
<pre><code>In [793... | 0 | 2016-08-09T05:54:52Z | [
"python",
"arrays",
"python-2.7",
"numpy",
"set"
] |
intersection of np.array and set | 38,840,641 | <p>I would like to intersect an np.array with a set without having to convert the np.array to a list first (slows down the program to an unworkable level).</p>
<p>Here's my current code: (Note that I'm getting this data from b,g,r rawCapture, and selection_data is simply a set from beforehand.)</p>
<pre><code>def Gre... | 0 | 2016-08-09T01:20:24Z | 38,844,636 | <p>If I understand your question correctly (and im not 100% sure that i do; but using the same assumptions as hpaulj), your problem can be solved thus using the <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package:</p>
<pre><code>import numpy_indexed as npi
Colour... | 0 | 2016-08-09T07:30:30Z | [
"python",
"arrays",
"python-2.7",
"numpy",
"set"
] |
Problems redirecting to dynamic URLs in Flask with 'action' | 38,840,644 | <p>My app has a text box and a submission button. I am trying to create and redirect to dynamic URLs in my app, that are based off of what is typed in the text box. For example, the user enters in '1234', clicks submit, then is taken to 'website.com/results/1234'. The problem seems to be that the HTML for my button doe... | 1 | 2016-08-09T01:21:15Z | 38,840,719 | <p>Your punctual problem is that /home route function also needs to put the results_page url on the templating context.</p>
<pre><code>results_page = "website.com/results"
return render_template("dashboard.html", results_page=results_page)
</code></pre>
<p>Since the variable is undefined, flask is calling the origina... | 1 | 2016-08-09T01:32:59Z | [
"python",
"html",
"flask",
"jinja2"
] |
Why can functions be pickled, but not modules? | 38,840,728 | <p>I noticed that when my object contains an explicit reference to a module, <code>pickling</code> it will fail because of this.</p>
<p>However, if I stick a reference to a function from that module into my object instead, it can be picked and unpickled successfully.</p>
<p>How come Python can pickle functions, but n... | 0 | 2016-08-09T01:34:21Z | 38,840,848 | <p>Because they didn't code support for it. C level types (and even modules written in Python are implemented with a C level type) require <code>pickle</code> support to be coded explicitly.</p>
<p>It's not very easy to determine what should be pickled if a <code>module</code> is allowed to be pickled; importing the s... | 2 | 2016-08-09T01:49:01Z | [
"python",
"pickle",
"python-2.x",
"python-module"
] |
Average Number of Repeating Patterns with Numpy | 38,840,752 | <p>I have an arbitrary array with only binary values- say:</p>
<pre><code>a = np.array([1,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,0,])
</code></pre>
<p>What would be the most efficient way to count average length of sequences of 1s array? Eg. In this example, it would be (1 + 8 + 2)/3.</p>
| 0 | 2016-08-09T01:38:20Z | 38,840,873 | <p>I'm not sure easiest, but one alternative is</p>
<pre><code>np.mean([len(list(v)) for k,v in itertools.groupby(a) if k])
3.6666666666666665
</code></pre>
<p><strong>Explanation</strong>
<code>groupby</code> groups adjacent equal values together, we filter only ones (<code>if k</code>), the list comprehension <cod... | 1 | 2016-08-09T01:52:57Z | [
"python",
"algorithm",
"numpy"
] |
Average Number of Repeating Patterns with Numpy | 38,840,752 | <p>I have an arbitrary array with only binary values- say:</p>
<pre><code>a = np.array([1,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,0,])
</code></pre>
<p>What would be the most efficient way to count average length of sequences of 1s array? Eg. In this example, it would be (1 + 8 + 2)/3.</p>
| 0 | 2016-08-09T01:38:20Z | 38,841,793 | <p>For an all numpy solution, you can use Alex Martelli's <a href="http://stackoverflow.com/a/1066838/298607">solution</a> like so:</p>
<pre><code>def runs_of_ones_array(bits):
# make sure all runs of ones are well-bounded
bounded = np.hstack(([0], bits, [0]))
# get 1 at run starts and -1 at run ends
d... | 2 | 2016-08-09T03:58:59Z | [
"python",
"algorithm",
"numpy"
] |
Do ABCs enforce method decorators? | 38,840,771 | <p>I'm trying to figure out how to ensure that a method of a class inheriting from an ABC is created using the appropriate decorator. I understand (hopefully) how ABCs work in general.</p>
<pre><code>from abc import ABCMeta, abstractmethod
class MyABC(metaclass=ABCMeta):
@abstractmethod
def my_abstract_method... | 0 | 2016-08-09T01:41:06Z | 38,842,925 | <p>You're correct that ABCs do not enforce that. There isn't a way to enforce something like "has a particular decorator". Decorators are just functions that return objects (e.g., <code>property</code> returns a property object). ABCMeta doesn't do anything to ensure that the defined attributes on the class are anyt... | 1 | 2016-08-09T05:45:50Z | [
"python",
"decorator",
"abc"
] |
catch a 401 Unauthorized http response using jquery ajax | 38,840,823 | <p>How can i access status codes in the "fail" jquery callback function. The jXhr reports a code of 0. The textStatus is "error". When making the request using curl there is a json response body present and the status code is set correctly. See below. </p>
<pre><code>< HTTP/1.1 401 Unauthorized
HTTP/1.1 401 Unautho... | 0 | 2016-08-09T01:46:43Z | 38,841,539 | <p>Even though the preflight OPTIONS call was successful and had all the cross domain related headers set. The subsequent GET call has to have the following header set as well: Access-Control-Allow-Origin</p>
<p>I added it and that fixed the issue. Hopefully this helps someone out there in the future.</p>
| 0 | 2016-08-09T03:25:29Z | [
"jquery",
"python",
"ajax",
"rest",
"bottle"
] |
How do I find largest valid sequence of parentheses and brackets in a string? | 38,840,902 | <p>So I have a script I need to write and one of the largest problems boils down to finding the largest valid subsequence within a string. So I have something like</p>
<pre><code>"()(({}[](][{[()]}]{})))("
</code></pre>
<p>as an input and I would need to return </p>
<pre><code>"[{[()]}]{}"
</code></pre>
<p>as an ... | 4 | 2016-08-09T01:57:04Z | 38,841,489 | <p>If you're talking about arbitrary depth, Franks anser here may apply:
<a href="http://stackoverflow.com/questions/524548/regular-expression-to-detect-semi-colon-terminated-c-for-while-loops/524624#524624">Regular expression to detect semi-colon terminated C++ for & while loops</a></p>
<p>If we are talking finit... | 0 | 2016-08-09T03:19:41Z | [
"python",
"algorithm",
"stack",
"dynamic-programming",
"parentheses"
] |
How do I find largest valid sequence of parentheses and brackets in a string? | 38,840,902 | <p>So I have a script I need to write and one of the largest problems boils down to finding the largest valid subsequence within a string. So I have something like</p>
<pre><code>"()(({}[](][{[()]}]{})))("
</code></pre>
<p>as an input and I would need to return </p>
<pre><code>"[{[()]}]{}"
</code></pre>
<p>as an ... | 4 | 2016-08-09T01:57:04Z | 38,841,577 | <p>This answer uses the following input sequence as an example. The expected output is all of the string except the last <code>(</code>.</p>
<pre><code>Input: ()(({}[]([{[()]}]{})))(
Output: ()(({}[]([{[()]}]{})))
</code></pre>
<p>Step 1 is to find the seeds in the string. A seed is a matched set of symbols: <code>(... | 1 | 2016-08-09T03:30:43Z | [
"python",
"algorithm",
"stack",
"dynamic-programming",
"parentheses"
] |
How do I find largest valid sequence of parentheses and brackets in a string? | 38,840,902 | <p>So I have a script I need to write and one of the largest problems boils down to finding the largest valid subsequence within a string. So I have something like</p>
<pre><code>"()(({}[](][{[()]}]{})))("
</code></pre>
<p>as an input and I would need to return </p>
<pre><code>"[{[()]}]{}"
</code></pre>
<p>as an ... | 4 | 2016-08-09T01:57:04Z | 38,842,144 | <p>This can be solved using dynamic programming. Go through the array recording the longest valid match ending from each index. If you've got the longest match for index i, then it's easy to find the longest match for index i+1: skip backwards the longest match for index i, and then see if the characters surrounding th... | 1 | 2016-08-09T04:34:35Z | [
"python",
"algorithm",
"stack",
"dynamic-programming",
"parentheses"
] |
Can't see infinite loop | 38,840,970 | <p>I am trying to write a webcrawler but I am stuck because I cant see infinite loop somewhere in my code. </p>
<pre><code>class Crawler(object):
def __init__(self, url, query, dir = os.path.dirname(__file__)):
self.start_url = url
self.start_parsed = urllib3.util.parse_url(url)
self.query ... | 2 | 2016-08-09T02:07:56Z | 38,841,037 | <p>Add a <code>visited</code> property inside your crawler.</p>
<pre><code>from collections import defaultdict
class Crawler:
def __init__(self, url, query, dir = os.path.dirname(__file__)):
self.visited = defaultdict(bool)
# Rest of code...
def start(self, depth= 5, url = '/'):
if sel... | 2 | 2016-08-09T02:16:42Z | [
"python",
"beautifulsoup",
"web-crawler",
"urllib3"
] |
Can't see infinite loop | 38,840,970 | <p>I am trying to write a webcrawler but I am stuck because I cant see infinite loop somewhere in my code. </p>
<pre><code>class Crawler(object):
def __init__(self, url, query, dir = os.path.dirname(__file__)):
self.start_url = url
self.start_parsed = urllib3.util.parse_url(url)
self.query ... | 2 | 2016-08-09T02:07:56Z | 38,841,092 | <p>Adapted from Giogian's code:</p>
<pre><code>class Crawler(object):
def __init__(self, url, query, dir=os.path.dirname(__file__)):
self.visited = set()
# Rest of code...
def start(self, depth=5, url='/'):
if url in self.visited:
return True
self.visited.add(url)
<... | 2 | 2016-08-09T02:24:51Z | [
"python",
"beautifulsoup",
"web-crawler",
"urllib3"
] |
Convert "slightly inconsistent" Pandas Column to DateTime | 38,840,996 | <p>I have a column of data from different sources, and hence with slightly inconsistency problem on the time-stamp string:</p>
<pre><code>data_test DataTime
0 2012-10-03 12:14:18.257000000
1 2012-10-01 08:39:54.633000000
2 2012-10-05 07:50:14.203000000
3 2012-10-02 15:02:42.843000000
4 2... | 0 | 2016-08-09T02:11:58Z | 38,841,006 | <p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">to_datetime()</a> method:</p>
<pre><code>In [222]: df
Out[222]:
DataTime
0 2012-10-03 12:14:18.257000000
1 2012-10-01 08:39:54.633000000
2 2012-10-05 07:50:14.203000000
3 20... | 1 | 2016-08-09T02:13:47Z | [
"python",
"datetime",
"pandas"
] |
How to make a field in database in django that only takes few predefined inputs from drop down list | 38,841,118 | <p>I am new to python and django and i had no idea how to shorten my question.
My problem is i am making a model in django. I have made a class user. In that class i have a character type name, integer type id, and a integer type age.
I want a field in which user can only select from a few predefined inputs, like secti... | -1 | 2016-08-09T02:27:14Z | 38,841,216 | <p>You would probably want to use <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#choices" rel="nofollow">Field.choices</a> attribute on your model class. Please visit the link for more in-depth explanation & examples.</p>
<blockquote>
<p><strong>Field.choices</strong></p>
<p>An iterable ... | 1 | 2016-08-09T02:41:39Z | [
"python",
"django"
] |
Feedparser doesn't work, gives AttributeError | 38,841,133 | <p>I have this code:</p>
<pre><code>import jinja2
import webapp2
import os
from google.appengine.ext import db
import feedparser
from xml.dom import minidom
from google.appengine.api import memcache
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.File... | 0 | 2016-08-09T02:30:26Z | 38,841,372 | <p>The GAE app code is not necessarily able to run as a standalone application.</p>
<p>The proper way to execute it locally is through the SDK's local development server, see <a href="https://cloud.google.com/appengine/docs/python/tools/using-local-server" rel="nofollow">Using the Local Development Server</a>. </p>
... | 0 | 2016-08-09T03:01:51Z | [
"python",
"google-app-engine",
"feedparser"
] |
A function takes a string of numbers and inserts a dash before and after each odd digit: The exception: string cannot begin or end with '-' | 38,841,153 | <p>The task: Write a method that takes in a number and returns a string, placing single dash before and after each odd digit. There is one exception: don't start or end the string with a dash.</p>
<p>Here is what I have:</p>
<pre><code>num = "32343"
dash = ""
for digit in num:
if int(num[0]) % 2 != 0:
da... | 0 | 2016-08-09T02:34:03Z | 38,841,389 | <p>The solution is just a series of if - else cases to consider, which is quite self-explanatory:</p>
<pre><code>num = "32343"
string = ""
for i in xrange(0,len(num)):
if i == 0 and i == len(num) - 1 and int(num[i]) % 2 != 0:
string = num[i]
elif i == 0 and int(num[i]) % 2 != 0:
string = num[i]... | 0 | 2016-08-09T03:05:35Z | [
"python"
] |
A function takes a string of numbers and inserts a dash before and after each odd digit: The exception: string cannot begin or end with '-' | 38,841,153 | <p>The task: Write a method that takes in a number and returns a string, placing single dash before and after each odd digit. There is one exception: don't start or end the string with a dash.</p>
<p>Here is what I have:</p>
<pre><code>num = "32343"
dash = ""
for digit in num:
if int(num[0]) % 2 != 0:
da... | 0 | 2016-08-09T02:34:03Z | 38,841,707 | <p>You can approach this in various ways using splicing (the [:] syntax) but my first crack at it would be via a generator. Your use of mod (%) is a great start, but you can avoid several elif using string formatting and implicit else's. </p>
<p>edit: I noticed you should still have a trailing - on the first number an... | 0 | 2016-08-09T03:47:26Z | [
"python"
] |
Python: trailing comma after a catch-all argument | 38,841,183 | <p>
I am baffled by the trailing comma in a function parameter list:</p>
<pre class="lang-py prettyprint-override"><code>def f( *args, ): pass
</code></pre>
<p>earns me a <code>SyntaxError</code> exception. In python 3, even this:</p>
<pre class="lang-py prettyprint-override"><code>def f( *, arg = 1, ): pass
</code>... | 0 | 2016-08-09T02:37:41Z | 38,841,532 | <p>Trailing commas in parameter lists are treated as multiple values separated by commas.</p>
<pre><code>a = (4)
type (a)
>> output: int
a = (4,)
type (a)
>> output: tuple
</code></pre>
<p>So if the parameters of a function have a trailing comma, python thinks that there should be a value but there is... | -2 | 2016-08-09T03:24:33Z | [
"python",
"syntax"
] |
Microseconds lost in datetime | 38,841,192 | <p>I'm trying to get microseconds but the last three digits always are 0, so I suppose I only can get milliseconds.
Is this an OS issue? I'm on Win7x64 with Python 2.7.10.
Am I doing something wrong? How else would I get microseconds?</p>
<pre><code>>>> import datetime
>>> datetime.datetime.now()
dat... | 3 | 2016-08-09T02:38:36Z | 38,841,349 | <p>I believe that's a known limitation of the Python 2.7 implementation under Windows:</p>
<pre class="lang-py prettyprint-override"><code>>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2016, 8, 9, 10, 50, 59, 657000)
>>> datetime.datetime.now()
datetime.datetime(2016, 8, ... | 2 | 2016-08-09T02:58:15Z | [
"python",
"datetime"
] |
Method for calculating irregularly spaced accumulation points | 38,841,263 | <p>I am attempting to do the opposite of <a href="http://stackoverflow.com/questions/6652671/efficient-method-of-calculating-density-of-irregularly-spaced-points">this</a>: Given a 2D image of (continuous) intensities, generate a set of irregularly spaced accumulation points, i.e, points that irregularly cover the 2D m... | 5 | 2016-08-09T02:47:56Z | 38,858,384 | <p>Partition the data using quadtrees (<a href="https://en.wikipedia.org/wiki/Quadtree" rel="nofollow">https://en.wikipedia.org/wiki/Quadtree</a>) into units of equal variance (or maybe also possible to make use of the concentration value?), using a defined threhold, then keep one point per unit (the centroid). There w... | 1 | 2016-08-09T18:54:40Z | [
"python",
"numpy",
"scikit-learn"
] |
invalid literal for int() with base 10: 'n' | 38,841,285 | <p>Error: ValueError at /followed/n/</p>
<p>Actually i don't get why this error appear, i've tried using int() and float() but, anything seems to work</p>
<p><strong>views.py</strong></p>
<pre><code>def followed(request, follow_to):
return render(request, "test.html",{'following':Following.objects.get(follow_to=... | 0 | 2016-08-09T02:50:22Z | 38,841,361 | <p>You have problem with this piece of code in your view.</p>
<pre><code>Following.objects.get(follow_to=follow_to)
</code></pre>
<p>Here the <code>follow_to</code> parameter passed to view is string and from the url mentioned it seems it is <code>'n'</code>. But you are searching for foreign key which will search fo... | 0 | 2016-08-09T03:00:16Z | [
"python",
"django"
] |
invalid literal for int() with base 10: 'n' | 38,841,285 | <p>Error: ValueError at /followed/n/</p>
<p>Actually i don't get why this error appear, i've tried using int() and float() but, anything seems to work</p>
<p><strong>views.py</strong></p>
<pre><code>def followed(request, follow_to):
return render(request, "test.html",{'following':Following.objects.get(follow_to=... | 0 | 2016-08-09T02:50:22Z | 38,847,065 | <p>If the <code>django.contrib.auth.models.User</code> model is used, its <code>pk</code> is an integer. However, the url pattern matches any word character (<code>\w</code>). Thus if only numbers should be allowed, modifying <code>urls.py</code> to only allow integer id matches might be a solution.</p>
<pre><code>url... | 0 | 2016-08-09T09:34:28Z | [
"python",
"django"
] |
How to make a PySide.QtCore.QTimer.singleShot call its timeout method | 38,841,289 | <p>I am working on a complex and poorly commented Qt-based Python application. It employs a PySide.QtCore.QTimer.singleShot(int,slot) timer to delay the execution of a slot within a thread, and I am confused about how this timer works.</p>
<p>Here is a MWE. This example uses the approach of subclassing QThread and rei... | 1 | 2016-08-09T02:50:47Z | 38,841,497 | <p>The default implementaion of <code>QThread.run()</code> calls <code>QThread.exec()</code>, which starts the thread's own event-loop. A <code>QTimer</code> requires a running event-loop, and its <code>timeout()</code> signal will be emitted in the thread it is started in. Your implementation of <code>run()</code> doe... | 1 | 2016-08-09T03:20:20Z | [
"python",
"qt",
"pyside",
"qtimer"
] |
How to make a PySide.QtCore.QTimer.singleShot call its timeout method | 38,841,289 | <p>I am working on a complex and poorly commented Qt-based Python application. It employs a PySide.QtCore.QTimer.singleShot(int,slot) timer to delay the execution of a slot within a thread, and I am confused about how this timer works.</p>
<p>Here is a MWE. This example uses the approach of subclassing QThread and rei... | 1 | 2016-08-09T02:50:47Z | 38,878,224 | <p>As @ekhumoro pointed out, my reimplementation of run() failed to call exec_(). This was the main problem. It took me a minute to find out where to put the exec_() call and how to properly quit() the thread when its work was finished. Here is the code that works.</p>
<p>Class definition, <code>timertester.py</code>:... | 1 | 2016-08-10T15:52:35Z | [
"python",
"qt",
"pyside",
"qtimer"
] |
Pandas Options Broken Again? | 38,841,315 | <p>Running this canonical example:</p>
<pre><code>from pandas.io.data import Options
aapl = Options('aapl', 'yahoo')
data = aapl.get_all_data()
</code></pre>
<p>gives</p>
<pre><code>RemoteDataError: Data not available
</code></pre>
<p>I know this <a href="https://github.com/pydata/pandas/issues/8612" rel="nofollo... | 2 | 2016-08-09T02:54:31Z | 38,841,433 | <p>It's Yahoo - <a href="https://github.com/pydata/pandas-datareader/issues/212" rel="nofollow">they've changed their options site</a>, so old parsers aren't working properly</p>
<p>Suggestion: first of all consider using <code>pandas_datareader</code> instead of deprecated <code>pandas.io.data</code> and monitor <a h... | 3 | 2016-08-09T03:11:15Z | [
"python",
"pandas",
"dataframe"
] |
Get password in Python Programming Language | 38,841,520 | <p>Is there any builtin function that can be used for getting a password in python.
I need answer like this</p>
<p>Input:
Enter a username: abcdefg
Enter a password : ********
If i enter a password abcdefgt. It shows like ********. </p>
| 2 | 2016-08-09T03:23:03Z | 38,841,548 | <h3>Original</h3>
<p>There is a function in the standard library module <a href="https://docs.python.org/3/library/getpass.html#module-getpass" rel="nofollow"><code>getpass</code></a>:</p>
<pre><code>>>> import getpass
>>> getpass.getpass("Enter a password: ")
Enter a password:
'hello'
</code></pre... | 4 | 2016-08-09T03:26:36Z | [
"python"
] |
Get password in Python Programming Language | 38,841,520 | <p>Is there any builtin function that can be used for getting a password in python.
I need answer like this</p>
<p>Input:
Enter a username: abcdefg
Enter a password : ********
If i enter a password abcdefgt. It shows like ********. </p>
| 2 | 2016-08-09T03:23:03Z | 38,841,632 | <p>Use the <code>getpass()</code> function and then print the number of stars equivalent to the number of characters in the password. This is a sample:</p>
<pre><code>import getpass
pswd = getpass.getpass('Password:')
print '*' * len(pswd)
</code></pre>
<p>The drawback is it does not print <code>*****</code> side by ... | 0 | 2016-08-09T03:38:31Z | [
"python"
] |
ISO 8601 Field to Python DateTime Field | 38,841,558 | <p>I am taking in a DateTimeField from an API with the format of "2016-08-09T02:16:15Z". I am using the code below to parse it and turn it to what I thought was a date time field, but am getting an error from one of my class methods to compare the time. Please see the parsing code below:</p>
<pre><code>time= dateutil.... | 0 | 2016-08-09T03:27:46Z | 38,841,923 | <p>This is happening because <code>time</code> in your model is nullable, and is empty (<code>None</code>) for the model instance for which the comparison fails. This raises an exception when you try to compare it with a <code>datetime</code> object.</p>
<p>You need to account for the null possibility in your logic, e... | 0 | 2016-08-09T04:13:12Z | [
"python",
"django",
"api",
"datetime"
] |
Where is the mistake - adjacency list? | 38,841,568 | <p>I'm getting error when try self reference</p>
<pre><code>class Sku(Base, ReprDescrIdMixin):
__tablename__ = 'SC84'
id = Column("ID", String, primary_key=True)
parent_code = Column("PARENTID",String, ForeignKey('sku.id'))
parent = relationship('Sku', foreign_keys='Sku.parent_code')
sqlalchemy.exc.N... | 1 | 2016-08-09T03:29:27Z | 38,842,855 | <p>The self referencing should be with table name (<code>__tablename__</code>) not Object name, following is for ONE-TO-MANY relationship:</p>
<pre><code>class Sku(Base, ReprDescrIdMixin):
__tablename__ = 'SC84'
id = Column("ID", String, primary_key=True)
parent_code = Column("PARENTID",String, ForeignKey(... | 0 | 2016-08-09T05:40:18Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] |
Where is the mistake - adjacency list? | 38,841,568 | <p>I'm getting error when try self reference</p>
<pre><code>class Sku(Base, ReprDescrIdMixin):
__tablename__ = 'SC84'
id = Column("ID", String, primary_key=True)
parent_code = Column("PARENTID",String, ForeignKey('sku.id'))
parent = relationship('Sku', foreign_keys='Sku.parent_code')
sqlalchemy.exc.N... | 1 | 2016-08-09T03:29:27Z | 38,853,993 | <p>try this</p>
<pre><code>class Sku(Base, ReprDescrIdMixin):
__tablename__ = 'SC84'
id = Column("ID", String, primary_key=True)
parent_code = Column("PARENTID",String, ForeignKey(id))
parent = relationship('Sku', foreign_keys=parent_code)
</code></pre>
<p>when using <code>ForeignKey(...)</code> you s... | 1 | 2016-08-09T14:47:33Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] |
Where is the mistake - adjacency list? | 38,841,568 | <p>I'm getting error when try self reference</p>
<pre><code>class Sku(Base, ReprDescrIdMixin):
__tablename__ = 'SC84'
id = Column("ID", String, primary_key=True)
parent_code = Column("PARENTID",String, ForeignKey('sku.id'))
parent = relationship('Sku', foreign_keys='Sku.parent_code')
sqlalchemy.exc.N... | 1 | 2016-08-09T03:29:27Z | 38,872,401 | <pre><code>from sqlalchemy.orm import relationship
class Sku(Base, ReprDescrIdMixin):
__tablename__ = 'SC84'
id = Column("ID", String, primary_key=True)
parent_code = Column("PARENTID",String, ForeignKey('sku.id'))
parent = relationship('Sku', lazy="joined", foreign_keys=[parent_code... | 0 | 2016-08-10T11:38:36Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] |
Spotipy - track names and energy values | 38,841,569 | <pre><code>def lowEnergy():
tids = []
# get songs by recommendation
results = sp.recommendations(seed_artists = [artist['id']])
#retrieve uris for songs
for track in results['tracks']:
tids.append(track['uri'])
#get audio_features
features = sp.audio_features(tids)
#pick ener... | 2 | 2016-08-09T03:29:28Z | 38,841,714 | <p>Not tested, but hope it works.</p>
<pre><code>for i, e in enumerate(energy):
if e < 0.5:
track_name = sp.track(tids[i])['name']
print("{} - {}".format(track_name, e))
</code></pre>
| 0 | 2016-08-09T03:48:49Z | [
"python",
"list",
"spotipy"
] |
Flask app not running | 38,841,582 | <pre><code>from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Index!"
@app.route("/hello")
def hello():
return "Hello World!"
@app.route("/members")
def members():
return "Members"
if __name__ == "__main__":
app.run(debug=True)
</code></pre>
<p>I am trying to run t... | -1 | 2016-08-09T03:31:02Z | 38,841,646 | <p>Make sure Flask is installed in your system you can try something like <code>$ pip freeze | grep flask</code>, if not run<br /></p>
<pre><code>$ pip install Flask
</code></pre>
<p>And when you run your app like <code>$ python <filename>.py</code> you see something like
<br /></p>
<pre><code>* Running on ht... | 0 | 2016-08-09T03:40:23Z | [
"python",
"flask"
] |
Flask app not running | 38,841,582 | <pre><code>from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Index!"
@app.route("/hello")
def hello():
return "Hello World!"
@app.route("/members")
def members():
return "Members"
if __name__ == "__main__":
app.run(debug=True)
</code></pre>
<p>I am trying to run t... | -1 | 2016-08-09T03:31:02Z | 38,849,365 | <p>If you are new to Flask follow these steps and you will be able to view the paths on a browser. First install virtualenv & pip. </p>
<pre><code>sudo apt-get install python-virtualenv
sudo apt-get install python-pip
</code></pre>
<p>Create a directory wher you will store your object. </p>
<pre><code>mkdir yo... | 0 | 2016-08-09T11:23:27Z | [
"python",
"flask"
] |
How do I define a conditional function using sympy? | 38,841,587 | <p>I want to be able to define an expression which takes all the values of variable where it is defined and evaluates the expression as <strong>0</strong> when it is not defined.
Similar to this: - </p>
<pre><code> import numpy as np
import sympy as sp
def expr(k1, k2):
x, y =sp.symbols('x y')
... | 2 | 2016-08-09T03:32:16Z | 38,841,883 | <p>You should define a function inside your function and then return it. Like this:</p>
<pre><code>import numpy as np
import sympy as sp
def expr(k1, k2):
x, y =sp.symbols('x y')
def fn(x, y):
if x==k1:
return 0
else:
return np.divide(1, (x-k1)*(y-k2))
return fn, x,... | 3 | 2016-08-09T04:09:16Z | [
"python",
"numpy",
"sympy"
] |
How do I define a conditional function using sympy? | 38,841,587 | <p>I want to be able to define an expression which takes all the values of variable where it is defined and evaluates the expression as <strong>0</strong> when it is not defined.
Similar to this: - </p>
<pre><code> import numpy as np
import sympy as sp
def expr(k1, k2):
x, y =sp.symbols('x y')
... | 2 | 2016-08-09T03:32:16Z | 38,858,444 | <p>If you want a symbolic function, use <code>Piecewise</code></p>
<pre><code>expr = Piecewise((0, Eq(x, k1)), (1/(x - k1)/(y - k2), True))
</code></pre>
<p>If you later want to evaluate this expression on numeric values, you should convert it to a numeric function with <code>lambdify</code></p>
<pre><code>f = lambd... | 2 | 2016-08-09T18:57:49Z | [
"python",
"numpy",
"sympy"
] |
Get min max from the list inside a list | 38,841,623 | <p>I am new to Python. I am trying to get min and max (output as list) of a list inside a list. But it is not working as expected. Here is what I have so far.</p>
<pre><code>import functools
# Input
raw_data = [
[2, 2, 3, 4, 5, 6, 7],
[0, 2, 3, 4, 5, 6, 17],
[3, 4, 3, 4, 5, 6, 37]
]
min_max_rows = list(m... | 2 | 2016-08-09T03:37:11Z | 38,841,667 | <p>You can flatten your list of list first:</p>
<pre><code>flat = [item for sublist in raw_data for item in sublist]
max_item = max(flat)
min_item = min(flat)
</code></pre>
| 3 | 2016-08-09T03:42:40Z | [
"python",
"python-3.x"
] |
Get min max from the list inside a list | 38,841,623 | <p>I am new to Python. I am trying to get min and max (output as list) of a list inside a list. But it is not working as expected. Here is what I have so far.</p>
<pre><code>import functools
# Input
raw_data = [
[2, 2, 3, 4, 5, 6, 7],
[0, 2, 3, 4, 5, 6, 17],
[3, 4, 3, 4, 5, 6, 37]
]
min_max_rows = list(m... | 2 | 2016-08-09T03:37:11Z | 38,841,680 | <p>Use this </p>
<pre><code>min_val = min(min(raw_data))
max_val = max(max(raw_data))
min_max_list = [min_val,max_val]
</code></pre>
<p>Edit:</p>
<p>There is a problem with this which I apparently overlooked. The <code>min_val</code> contains the minimum value of that row that starts with the smallest value. Likewis... | 2 | 2016-08-09T03:44:13Z | [
"python",
"python-3.x"
] |
Get min max from the list inside a list | 38,841,623 | <p>I am new to Python. I am trying to get min and max (output as list) of a list inside a list. But it is not working as expected. Here is what I have so far.</p>
<pre><code>import functools
# Input
raw_data = [
[2, 2, 3, 4, 5, 6, 7],
[0, 2, 3, 4, 5, 6, 17],
[3, 4, 3, 4, 5, 6, 37]
]
min_max_rows = list(m... | 2 | 2016-08-09T03:37:11Z | 38,841,710 | <p>NumPy approach - it should be much faster on bigger lists:</p>
<pre><code>import numpy as np
In [74]: a = np.asarray(raw_data)
In [75]: a
Out[75]:
array([[ 2, 2, 3, 4, 5, 6, 7],
[ 0, 2, 3, 4, 5, 6, 17],
[ 3, 4, 3, 4, 5, 6, 37]])
In [76]: min_max_list = [a.min(), a.max()]
In [77]: m... | 1 | 2016-08-09T03:48:08Z | [
"python",
"python-3.x"
] |
Get min max from the list inside a list | 38,841,623 | <p>I am new to Python. I am trying to get min and max (output as list) of a list inside a list. But it is not working as expected. Here is what I have so far.</p>
<pre><code>import functools
# Input
raw_data = [
[2, 2, 3, 4, 5, 6, 7],
[0, 2, 3, 4, 5, 6, 17],
[3, 4, 3, 4, 5, 6, 37]
]
min_max_rows = list(m... | 2 | 2016-08-09T03:37:11Z | 38,842,121 | <p>This might be closer to what you want: </p>
<pre><code>result = functools.reduce(lambda a, b: (min(*a, *b), max(*a, *b)), min_max_rows)
</code></pre>
<p>Have the max and min function evaluate explicitly on two arguments which are your tuples from the list. the * is needed to unpack the tuples.</p>
| 0 | 2016-08-09T04:32:29Z | [
"python",
"python-3.x"
] |
Django-medusa can't render wagtail | 38,841,644 | <p>I want render my wagtail site to static site using django-medusa like this documentation <a href="http://docs.wagtail.io/en/v1.1/reference/contrib/staticsitegen.html" rel="nofollow">http://docs.wagtail.io/en/v1.1/reference/contrib/staticsitegen.html</a> . In this step ./manage.py staticsitegen I get an error like th... | 0 | 2016-08-09T03:39:58Z | 38,845,440 | <p>See the latest Wagtail docs - <a href="http://docs.wagtail.io/en/latest/reference/contrib/staticsitegen.html?highlight=medusa" rel="nofollow">http://docs.wagtail.io/en/latest/reference/contrib/staticsitegen.html?highlight=medusa</a></p>
<blockquote>
<p>django-medusa is no longer maintained, and is incompatible wi... | 1 | 2016-08-09T08:15:10Z | [
"python",
"django",
"wagtail"
] |
Matplotlib: How to plot an specfic curve without legend? | 38,841,699 | <p>For example. I have two curves. One is the real curve and the other is just a dashed line to indicate an specific point:</p>
<pre><code>import matplotlib.pyplot as plt
x2=[0,0.5,0.5]
y2=[0.5,0.5,0]
plt.plot(x2,y2,ls='dashed')
x1=[0,1]
y1=[0,1]
plt.plot(x1,y1)
plt.legend(['','y1'])
plt.show()
</code></pre>
<p>I... | 2 | 2016-08-09T03:46:27Z | 38,841,958 | <p>You can use the <code>label</code> keyword and let the <code>legend()</code> function generate the labels automatically.</p>
<pre><code>x2=[0,0.5,0.5]
y2=[0.5,0.5,0]
plt.plot(x2,y2,ls='dashed')
x1=[0,1]
y1=[0,1]
plt.plot(x1,y1, label='y1')
plt.legend()
</code></pre>
<p>Which gives you this result:</p>
<p><a hre... | 3 | 2016-08-09T04:16:53Z | [
"python",
"matplotlib"
] |
Cannot type password. (creating a Django admin superuser) | 38,841,720 | <p>I am doing <code>python manage.py createsuperuser</code> in PowerShell and CMD, and I can type when it prompts me for the Username and Email, but when it gets to Password it just won't let me type. It is not freezing though, because when I press enter it re-prompts me for the password...</p>
<p>Using Django 1.10 an... | -3 | 2016-08-09T03:49:46Z | 38,841,784 | <p>While it does not show you what you are typing, it is still taking the input. So just type in the password both times, press enter and it will work even though it does not show up.</p>
| 1 | 2016-08-09T03:58:25Z | [
"python",
"django",
"django-admin",
"python-3.5"
] |
Python(Numpy)- df apply error - IndexError: tuple index out of range | 38,841,742 | <pre><code>from pandas import DataFrame,Series
import numpy
def avg_bronze_medal():
countries=['Russian Fed','Norway','Canada']
gold=[13,11,10]
silver=[11,5,10]
bronze=[9,10,5]
medal_counts={'country_name':Series(countries),'gold':Series(gold),'silver':Series(silver),'bronze':Series(bronze)}
df... | 0 | 2016-08-09T03:53:03Z | 38,841,824 | <p>To get the mean of all three columns at the same time:</p>
<pre><code>df[['gold', 'bronze', 'silver']].mean(axis=1)
</code></pre>
<p>But it confuses me as to why you would need the average medals awarded in the tournament... But I guess you need it for some reason!</p>
<hr>
<p>Some additional notes the OP should... | 0 | 2016-08-09T04:02:52Z | [
"python",
"pandas",
"numpy",
"data-science"
] |
How do you deal with print() once you done with debugging/coding | 38,841,865 | <p>To python experts:
I put lots of print() to check the value of my variables.
Once I'm done, I need to delete the print(). It quite time-consuming and prompt to human errors.</p>
<p>Would like to learn how do you guys deal with print(). Do you delete it while coding or delete it at the end? Or there is a method to d... | 2 | 2016-08-09T04:07:00Z | 38,841,905 | <p>Use <a href="https://docs.python.org/3/library/logging.html" rel="nofollow">logging</a> instead and here is <a href="http://inventwithpython.com/blog/2012/04/06/stop-using-print-for-debugging-a-5-minute-quickstart-guide-to-pythons-logging-module/" rel="nofollow">why</a>.<br />
logging module comes with many simple &... | 5 | 2016-08-09T04:11:44Z | [
"python"
] |
How do you deal with print() once you done with debugging/coding | 38,841,865 | <p>To python experts:
I put lots of print() to check the value of my variables.
Once I'm done, I need to delete the print(). It quite time-consuming and prompt to human errors.</p>
<p>Would like to learn how do you guys deal with print(). Do you delete it while coding or delete it at the end? Or there is a method to d... | 2 | 2016-08-09T04:07:00Z | 38,842,389 | <p>You can use logging with debug level and once the debugging is completed, change the level to info. So any statements with logger.debug() will not be printed.</p>
| 2 | 2016-08-09T04:59:04Z | [
"python"
] |
How do you deal with print() once you done with debugging/coding | 38,841,865 | <p>To python experts:
I put lots of print() to check the value of my variables.
Once I'm done, I need to delete the print(). It quite time-consuming and prompt to human errors.</p>
<p>Would like to learn how do you guys deal with print(). Do you delete it while coding or delete it at the end? Or there is a method to d... | 2 | 2016-08-09T04:07:00Z | 38,843,280 | <p>What I do is put print statements in with with a special text marker in the string. I usually use <code>print("XXX", thething)</code>. Then I just search for and delete the line with that string. It's also easier to spot in the output. </p>
| 0 | 2016-08-09T06:10:54Z | [
"python"
] |
How to fix pip hanging on uninstalling sqlalchjemy | 38,841,898 | <p>In Python 2.7.11 under Windows I have installed sqlalchemy into a virtual environment. Now, when I try to uninstall it via</p>
<pre><code>pip uninstall sqlalchemy
</code></pre>
<p><code>pip</code> hangs when listing the following lines:</p>
<pre><code>.
.
.
c:\venv\lib\site-packages\sqlalchemy\util\langhelpers.py... | 0 | 2016-08-09T04:11:11Z | 39,139,252 | <p>I was not able to solve <em>why</em> pip hung on uninstall; however through another <a href="http://stackoverflow.com/a/14572899">stackoverflow answer</a> I realised that I can remove the package manually with:</p>
<pre><code>del C:\venv\Lib\site-packages\sqlalchemy
del C:\venv\Lib\site-packages\SQLAlchemy-1.0.14.d... | 0 | 2016-08-25T07:33:14Z | [
"python",
"windows",
"sqlalchemy",
"pip",
"uninstall"
] |
Python sum values of list of dictionaries if two other key value pairs match | 38,841,902 | <p>I have a list of dictionaries of the following form:</p>
<pre><code>lst = [{"Name":'Nick','Hour':0,'Value':2.75},
{"Name":'Sam','Hour':1,'Value':7.0},
{"Name":'Nick','Hour':0,'Value':2.21},
{'Name':'Val',"Hour":1,'Value':10.1},
{'Name':'Nick','Hour':1,'Value':2.1},
{'Name':'Val'... | 3 | 2016-08-09T04:11:28Z | 38,841,988 | <p>consider using pandas module - it's very comfortable for such data sets:</p>
<pre><code>import pandas as pd
In [109]: lst
Out[109]:
[{'Hour': 0, 'Name': 'Nick', 'Value': 2.75},
{'Hour': 1, 'Name': 'Sam', 'Value': 7.0},
{'Hour': 0, 'Name': 'Nick', 'Value': 2.21},
{'Hour': 1, 'Name': 'Val', 'Value': 10.1},
{'Hou... | 4 | 2016-08-09T04:19:07Z | [
"python"
] |
Python sum values of list of dictionaries if two other key value pairs match | 38,841,902 | <p>I have a list of dictionaries of the following form:</p>
<pre><code>lst = [{"Name":'Nick','Hour':0,'Value':2.75},
{"Name":'Sam','Hour':1,'Value':7.0},
{"Name":'Nick','Hour':0,'Value':2.21},
{'Name':'Val',"Hour":1,'Value':10.1},
{'Name':'Nick','Hour':1,'Value':2.1},
{'Name':'Val'... | 3 | 2016-08-09T04:11:28Z | 38,842,296 | <pre><code>[{'Name':name, 'Hour':hour, 'Value': sum(d['Value'] for d in lst if d['Name']==name and d['Hour']==hour)} for hour in hours for name in names]
</code></pre>
<p>if you don't already have all names and hours in lists (or sets) you can get them like so:</p>
<pre><code>names = {d['Name'] for d in lst}
hours= {... | 2 | 2016-08-09T04:49:15Z | [
"python"
] |
Python sum values of list of dictionaries if two other key value pairs match | 38,841,902 | <p>I have a list of dictionaries of the following form:</p>
<pre><code>lst = [{"Name":'Nick','Hour':0,'Value':2.75},
{"Name":'Sam','Hour':1,'Value':7.0},
{"Name":'Nick','Hour':0,'Value':2.21},
{'Name':'Val',"Hour":1,'Value':10.1},
{'Name':'Nick','Hour':1,'Value':2.1},
{'Name':'Val'... | 3 | 2016-08-09T04:11:28Z | 38,842,335 | <p>You can use any (hashable) object as a key for a python dictionary, so just use a tuple containing Name and Hour as the key:</p>
<pre><code>from collections import defaultdict
d = defaultdict(float)
for item in lst:
d[(item['Name'], item['Hour'])] += item['Value']
</code></pre>
| 3 | 2016-08-09T04:53:31Z | [
"python"
] |
Import error while importing nltk (Cannot import bracket_parse) | 38,841,925 | <p>I have installed nltk and nltk-data. Program gives error on
<code>import nltk</code>.</p>
<p>Below is error stack trace:</p>
<pre><code>import nltk
File "/usr/local/lib/python2.7/dist-packages/nltk/__init__.py", line 137, in <module>
from nltk.stem import *
File "/usr/local/lib/python2.7/dist-packages/nltk/s... | 0 | 2016-08-09T04:13:27Z | 38,842,486 | <p>Installed NLTK on Ubuntu 14.04 via following steps:</p>
<ol>
<li>Install Setuptools: <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">http://pypi.python.org/pypi/setuptools</a></li>
<li>Install Pip: run sudo easy_install pip</li>
<li>Install Numpy (optional): run sudo pip install -U numpy</li>
<li>In... | -1 | 2016-08-09T05:08:11Z | [
"python",
"ubuntu",
"nltk"
] |
Import error while importing nltk (Cannot import bracket_parse) | 38,841,925 | <p>I have installed nltk and nltk-data. Program gives error on
<code>import nltk</code>.</p>
<p>Below is error stack trace:</p>
<pre><code>import nltk
File "/usr/local/lib/python2.7/dist-packages/nltk/__init__.py", line 137, in <module>
from nltk.stem import *
File "/usr/local/lib/python2.7/dist-packages/nltk/s... | 0 | 2016-08-09T04:13:27Z | 39,132,270 | <p>Your stack trace shows that the error occurs several levels deep into the first import. So we can rule out the usual culprit, a file named <code>nltk.py</code> in your working directory. I'm guessing something went wrong with your nltk installation-- perhaps it was interrupted and you didn't notice? </p>
<p>Check i... | 0 | 2016-08-24T20:11:29Z | [
"python",
"ubuntu",
"nltk"
] |
Python_LIBRARIES in CMAKE notfound | 38,842,019 | <p>I installed the Qt5 and python to use it for compile Sigil using CMAKE.</p>
<p>First i had problems with the qt5 but i solved setting the CMAKE_PREFIX_PATH.
But the Python seems to have a problem with the pythonlibs and PYTHON_LIBRARIES.</p>
<p>First it reads in black letters:</p>
<pre><code>Looking for python ve... | 2 | 2016-08-09T04:22:50Z | 39,990,694 | <p>I had the same issue and solved it by installing python dependencies as described in <a href="https://github.com/Sigil-Ebook/Sigil/blob/master/docs/Building_on_cutting_edge_Linux.md#python" rel="nofollow">Sigil linux build instructions</a>:
sudo apt-get install python3-dev python3-pip python3-tk python3-lxml python3... | 0 | 2016-10-12T04:46:28Z | [
"python",
"cmake"
] |
How to pass a string that read from keyboard to functions such as isdecimal? | 38,842,022 | <p>I am using Python 2.7.4 here, and I know how to define a string as Unicode, by</p>
<pre><code>a = u"abcd"
</code></pre>
<p>I tried reading a string from keyboard using <strong><code>raw_input()</code></strong>, and I want pass the string that I read to <em><strong>isX()</strong></em> function such as <strong><cod... | 0 | 2016-08-09T04:23:14Z | 38,842,138 | <p>Yes for example i tried below:-</p>
<pre><code>a = 0
try:
a = int(raw_input())
print isX(a)
except:
print "Wrong Input"
</code></pre>
<p>In this case if you pass a string then also it works normally.</p>
| -1 | 2016-08-09T04:34:00Z | [
"python",
"string",
"unicode"
] |
How to pass a string that read from keyboard to functions such as isdecimal? | 38,842,022 | <p>I am using Python 2.7.4 here, and I know how to define a string as Unicode, by</p>
<pre><code>a = u"abcd"
</code></pre>
<p>I tried reading a string from keyboard using <strong><code>raw_input()</code></strong>, and I want pass the string that I read to <em><strong>isX()</strong></em> function such as <strong><cod... | 0 | 2016-08-09T04:23:14Z | 38,842,847 | <p>What you really wanna know how to do, given the way you wrote your question is:
How to convert raw_input()'s output to a unicode object so that you can use .isdecimal() because that is a Unicode object only function.</p>
<p>To answer that question, you can do the below to automatically do that conversion when getti... | 0 | 2016-08-09T05:39:30Z | [
"python",
"string",
"unicode"
] |
How to check the file size limit in django | 38,842,053 | <p>I am creating a method that uploads a file however I want to check the file size since I just want to allow 5mb as the max limit.</p>
<p>I want to make something like this</p>
<pre><code>def handle_uploaded_file(thisFile):
if thisFile > 5mb:
return "This file is more than 5mb"
else:
with o... | 0 | 2016-08-09T04:26:04Z | 38,842,096 | <pre><code># Add to your settings file
CONTENT_TYPES = ['image', 'video']
# 2.5MB - 2621440
# 5MB - 5242880
# 10MB - 10485760
# 20MB - 20971520
# 50MB - 5242880
# 100MB 104857600
# 250MB - 214958080
# 500MB - 429916160
MAX_UPLOAD_SIZE = 5242880
#Add to a form containing a FileField and change the field names according... | 2 | 2016-08-09T04:30:28Z | [
"python",
"django",
"file-upload"
] |
How to check the file size limit in django | 38,842,053 | <p>I am creating a method that uploads a file however I want to check the file size since I just want to allow 5mb as the max limit.</p>
<p>I want to make something like this</p>
<pre><code>def handle_uploaded_file(thisFile):
if thisFile > 5mb:
return "This file is more than 5mb"
else:
with o... | 0 | 2016-08-09T04:26:04Z | 38,842,125 | <p>Use <code>._size</code> file attribute</p>
<pre><code>if thisFile._size > 5242880:
return "This file is more than 5mb"
</code></pre>
<p><code>._size</code> is represented in bytes. <code>5242880 - 5MB</code></p>
<pre><code>def handle_uploaded_file(thisFile):
if thisFile._size > 5242880:
retur... | 1 | 2016-08-09T04:32:41Z | [
"python",
"django",
"file-upload"
] |
How to delete the instance of an object inside a list once a condition is met? | 38,842,116 | <p>I'm writing a text based game as an exercise. I have the GenerateEnemies function which creates some random goblins and places them in the CurrentEnemy list.</p>
<p>Using the Attack function, I can make the hero attack a goblin in the CurrentEnemy list, decreasing its HP.</p>
<p>What I want to happen is that when ... | 1 | 2016-08-09T04:32:20Z | 38,842,326 | <p>Deleting from a list is expensive, use a set() instead. And it has various utility functions to delete the object like s.add() and s.discard().</p>
<p>Now regarding your question: </p>
<p>del(self) only deletes the reference to the local variable self within the class, not the whole object.</p>
<p>And if you wan... | 2 | 2016-08-09T04:51:50Z | [
"python",
"python-3.x",
"oop"
] |
How can i source bashrc before ansible ssh | 38,842,160 | <p>My new ec2 host has default python2.6.
I have script <code>python_27.sh</code> which basically update the PATH with python 27 and export some other stuff like <code>LD_LIBRARY_PATH</code> to enable python 2.7</p>
<p>Then i create virtualenv with that python like <code>/home/ansible/virualenv</code></p>
<p>This i a... | 0 | 2016-08-09T04:35:47Z | 38,844,478 | <p>Instead of <code>~/.bashrc</code> sourcing, you can do the following:</p>
<pre><code>ansible_python_interpreter=env LD_LIBRARY_PATH=/your/path/here /home/ansible/virualenv
</code></pre>
<p>So you will not source <code>~/.bashrc</code> (what generaly speaking is not a good idea),
but set only the variable you need.... | 1 | 2016-08-09T07:20:55Z | [
"python",
"python-2.7",
"ssh",
"ansible"
] |
SQL Query - Filtering out column values with None | 38,842,220 | <p>I have a PSQL database called raw and one of the columns is option, with type VARCHAR. The value is either 'Call', 'Put', or None.</p>
<p>I want to select all rows where the value of the option field is not 'Call' or 'Put', but rather None.</p>
<p>However, when I run this query:</p>
<pre><code>curr.execute('SELEC... | 0 | 2016-08-09T04:41:50Z | 38,842,278 | <pre><code>SELECT * FROM holdings h WHERE option =''
</code></pre>
| 0 | 2016-08-09T04:47:43Z | [
"python",
"sql",
"postgresql",
"psycopg2"
] |
SQL Query - Filtering out column values with None | 38,842,220 | <p>I have a PSQL database called raw and one of the columns is option, with type VARCHAR. The value is either 'Call', 'Put', or None.</p>
<p>I want to select all rows where the value of the option field is not 'Call' or 'Put', but rather None.</p>
<p>However, when I run this query:</p>
<pre><code>curr.execute('SELEC... | 0 | 2016-08-09T04:41:50Z | 38,843,887 | <p>If You want to select rows with <code>null</code> option, You must indicate this by <code>option IS NULL</code>:</p>
<pre><code>SELECT * FROM holdings WHERE option IS NULL
</code></pre>
<p>Instead of <code>option != 'Call' AND option != 'Put'</code> You can use <code>option NOT IN ('Call', 'Put')</code>:</p>
<pre... | 0 | 2016-08-09T06:45:32Z | [
"python",
"sql",
"postgresql",
"psycopg2"
] |
Executing statement inside if block is not printing in python | 38,842,396 | <p>when i executed the below code it is not printing ("yes we can"), its only printing ("all the best").
I am running the code in the visual studio.
Executing statement inside if block is not printing in python.</p>
<p>code:</p>
<pre><code>team = input("your favorite team")
if team == "Ferrari" :
print("yes we c... | -3 | 2016-08-09T04:59:23Z | 38,842,884 | <p>The image you show indicates a leading space before "Ferrari" which you don't have in your prompt. The strings must be identical. When I run your code:</p>
<pre><code>your favorite teamFerrari
yes we can
all the best
</code></pre>
<p>But you show a leading space:</p>
<pre><code>your favorite team Ferrari
all the... | 2 | 2016-08-09T05:42:30Z | [
"python",
"python-2.7",
"python-3.x"
] |
Sum of nested list without using SUM function (exercise) | 38,842,453 | <p>Trying to write a function that take the sum of each list and return individual values in a new single list.
E.g </p>
<pre><code>[[2, 7, 6], [9, 5, 1], [4, 3, 8]]
</code></pre>
<p>becomes </p>
<pre><code>[15, 15, 15]
</code></pre>
<p>What I have so far:<br/></p>
<pre><code>def row_sums(square):
total_lis... | 4 | 2016-08-09T05:04:48Z | 38,842,478 | <p>You need to reset your <code>total</code> counter before starting each inside for.
Also, you don't need to declare it outside, because you will use it only inside.</p>
<pre><code>def row_sums(square):
total_list = []
for i in square:
total = 0
for j in i:
total += j
tota... | 3 | 2016-08-09T05:07:37Z | [
"python",
"python-3.x"
] |
Sum of nested list without using SUM function (exercise) | 38,842,453 | <p>Trying to write a function that take the sum of each list and return individual values in a new single list.
E.g </p>
<pre><code>[[2, 7, 6], [9, 5, 1], [4, 3, 8]]
</code></pre>
<p>becomes </p>
<pre><code>[15, 15, 15]
</code></pre>
<p>What I have so far:<br/></p>
<pre><code>def row_sums(square):
total_lis... | 4 | 2016-08-09T05:04:48Z | 38,842,482 | <p>The error is you do not re-initialize the <code>total</code> variable after each loop. Instead, initialize <code>sum = 0</code> inside he first for-loop like so:</p>
<pre><code>def row_sums(square):
total_list = []
for i in square:
total = 0
for j in i:
total += j
total_... | 3 | 2016-08-09T05:07:56Z | [
"python",
"python-3.x"
] |
Sum of nested list without using SUM function (exercise) | 38,842,453 | <p>Trying to write a function that take the sum of each list and return individual values in a new single list.
E.g </p>
<pre><code>[[2, 7, 6], [9, 5, 1], [4, 3, 8]]
</code></pre>
<p>becomes </p>
<pre><code>[15, 15, 15]
</code></pre>
<p>What I have so far:<br/></p>
<pre><code>def row_sums(square):
total_lis... | 4 | 2016-08-09T05:04:48Z | 38,842,511 | <p>You need to zero your total for each list.</p>
<pre><code>def row_sums(square):
total_list = []
total = 0
for i in square:
for j in i:
total += j
total_list.append(total)
total = 0
return total_list
</code></pre>
| 1 | 2016-08-09T05:10:17Z | [
"python",
"python-3.x"
] |
Sum of nested list without using SUM function (exercise) | 38,842,453 | <p>Trying to write a function that take the sum of each list and return individual values in a new single list.
E.g </p>
<pre><code>[[2, 7, 6], [9, 5, 1], [4, 3, 8]]
</code></pre>
<p>becomes </p>
<pre><code>[15, 15, 15]
</code></pre>
<p>What I have so far:<br/></p>
<pre><code>def row_sums(square):
total_lis... | 4 | 2016-08-09T05:04:48Z | 38,842,634 | <p>Just for fun:</p>
<pre><code>>>> list = [[2, 7, 6], [9, 5, 1], [4, 3, 8]]
>>> import functools
>>> [functools.reduce(lambda x, y: x + y, sublist, 0) for sublist in list]
[15, 15, 15]
</code></pre>
<p>I did't use <code>sum</code> :)</p>
<p>You can read more about <code>functools.reduce<... | 2 | 2016-08-09T05:20:16Z | [
"python",
"python-3.x"
] |
Sum of nested list without using SUM function (exercise) | 38,842,453 | <p>Trying to write a function that take the sum of each list and return individual values in a new single list.
E.g </p>
<pre><code>[[2, 7, 6], [9, 5, 1], [4, 3, 8]]
</code></pre>
<p>becomes </p>
<pre><code>[15, 15, 15]
</code></pre>
<p>What I have so far:<br/></p>
<pre><code>def row_sums(square):
total_lis... | 4 | 2016-08-09T05:04:48Z | 38,843,372 | <p>To be different, flatten the lists and using a generator (assumes sublists are the same length):</p>
<pre><code>def _notsum2(lists):
per_yield = len(lists)
total = 0
for ind, next in enumerate(val for sublist in lists for val in sublist):
if ind % per_yield == 0 and ind:
yield total
... | 0 | 2016-08-09T06:15:56Z | [
"python",
"python-3.x"
] |
Sum of nested list without using SUM function (exercise) | 38,842,453 | <p>Trying to write a function that take the sum of each list and return individual values in a new single list.
E.g </p>
<pre><code>[[2, 7, 6], [9, 5, 1], [4, 3, 8]]
</code></pre>
<p>becomes </p>
<pre><code>[15, 15, 15]
</code></pre>
<p>What I have so far:<br/></p>
<pre><code>def row_sums(square):
total_lis... | 4 | 2016-08-09T05:04:48Z | 38,843,399 | <p>You can also do it using <code>map</code> and list comprehension as:</p>
<pre><code>l=[[2, 7, 6], [9, 5, 1], [4, 3, 8]]
a,b,c=[x for x in l]
map(lambda x,y,z:x+y+z, a,b,c)
</code></pre>
| -1 | 2016-08-09T06:17:31Z | [
"python",
"python-3.x"
] |
Sum of nested list without using SUM function (exercise) | 38,842,453 | <p>Trying to write a function that take the sum of each list and return individual values in a new single list.
E.g </p>
<pre><code>[[2, 7, 6], [9, 5, 1], [4, 3, 8]]
</code></pre>
<p>becomes </p>
<pre><code>[15, 15, 15]
</code></pre>
<p>What I have so far:<br/></p>
<pre><code>def row_sums(square):
total_lis... | 4 | 2016-08-09T05:04:48Z | 38,844,634 | <p><code>[sum(i) for i in zip(*[[2, 7, 6], [9, 5, 1], [4, 3, 8]])]</code></p>
<p>bultin zip func is what you exactly needed</p>
| -2 | 2016-08-09T07:30:27Z | [
"python",
"python-3.x"
] |
Internationalization for datetime | 38,842,666 | <p>I am building a mobile app and would like to follow best practice for datetime. Initially, we launched it in India and made our server, database and app time to IST.</p>
<p>Now we are launching the app to other countries(timezones), how should I store the datetime? Should the server time be set to UTC and app shoul... | 1 | 2016-08-09T05:23:57Z | 38,843,085 | <p>Keep as much in UTC as possible. Do your timezone conversion at your edges (client display and input processing), but keep anything stored server side in UTC.</p>
| 0 | 2016-08-09T05:58:02Z | [
"python",
"postgresql",
"internationalization",
"datetime-format",
"datetimeoffset"
] |
django is not replacing old image | 38,842,678 | <p>I have an Django App which plots the image on browser based on selection made through UI. Whenever there is a change in UI a JavaScript function is called up and which creats a Call to django view.</p>
<p>Whenever I Change the UI from browser a new Image is created by a function in views.py and returned as HTTPResp... | 0 | 2016-08-09T05:25:04Z | 38,845,557 | <p>Got the answer...</p>
<p>in views.py</p>
<pre><code>buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
pilImage = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
pilImage.save(buffer, "PNG")
response = HttpResponse(buffer.getvalue(), content_typ... | 0 | 2016-08-09T08:22:52Z | [
"javascript",
"python",
"django",
"html5",
"django-templates"
] |
Is it possible to retain permissions throughout a request? | 38,842,862 | <p>So I have a model that I'm doing a <code>PATCH</code> to via a view, which under certain circumstances can mutate my object such that the caller is <strong>not</strong> allowed to further mutate it.</p>
<p>My permission class looks something like this:</p>
<pre><code>class MyPermission(BasePermission):
def has... | 0 | 2016-08-09T05:40:43Z | 38,862,375 | <p>So it turns out I was mistaken. Permission checks happen only once and very early during a request.</p>
<p>In my case, the issue was that with the signal handler performing the <code>PATCH</code> request. Unknown to me at the time, there was another signal handler on that model that at some point did <code>instance... | 0 | 2016-08-10T00:19:04Z | [
"python",
"django",
"django-rest-framework"
] |
Slicing or masking? | 38,842,959 | <p>I'm not sure if there's a general answer to my question, but I wonder whether array masking or slicing is "better" to manipulate only parts of an array. With "better" I mean with respect to performance (speed of performing manipulations, memory overhead, i.e. intermediate arrays, etc). Is there any rule of thumb as ... | 0 | 2016-08-09T05:48:47Z | 38,843,940 | <p>These are some results using <code>timeit</code></p>
<pre><code>import numpy as np
x= np.arange(10000)
% timeit x[[np.arange(0,10000,2)]]
#output: 10000 loops, best of 3: 41.4 µs per loop
</code></pre>
<p>Assigning the indexed values to another array</p>
<pre><code>% timeit z = x[[np.arange(0,10000,2)]]
#outpu... | 0 | 2016-08-09T06:49:17Z | [
"python",
"arrays",
"numpy"
] |
Pairing images as np arrays into a specific format | 38,842,975 | <p>So I have 2 images, X and Y, as numpy arrays, each of shape (3, 30, 30): that is, 3 channels (RGB), each of height and width 30 pixels. I'd like to pair them up into a numpy array to get a specific output shape: </p>
<pre><code>my_pair = pair_up_images(X, Y)
my_pair.shape = (2, 3, 30, 30)
</code></pre>
<p>Such tha... | 0 | 2016-08-09T05:50:12Z | 38,843,122 | <p>Simply:</p>
<pre><code>Z = np.array([X, Y])
Z.shape
Out[62]: (2, 3, 30, 30)
</code></pre>
| 1 | 2016-08-09T06:00:16Z | [
"python",
"arrays",
"numpy"
] |
Tar --exclude not working when popen(shell=False) | 38,843,131 | <p>I am trying to execute the following command using Popen.</p>
<pre><code>args = ['/bin/tar', "--exclude='{}'".format('Build.tar.gz'), '-capvf', targetFile, '.' ]
popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
</code></pre>
<p>However the exclude part does only work if I set sh... | 0 | 2016-08-09T06:00:34Z | 38,843,912 | <p>Remove the single quotes from <code>"--exclude='{}'".format(...)</code>, use <code>"--exclude={}".format(...)</code></p>
<p>When you don't use <code>shell=True</code> you don't need to use escapes. The quotes only make sense to the shell, they are removed before the command is executed to create the list of argumen... | 1 | 2016-08-09T06:47:51Z | [
"python",
"python-3.4",
"popen"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.