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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
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 are even in the number of integers they contain, however when the list length is odd, it's not so easy to simply swap each value, as the number of integers is uneven.</p>
<p>Giving the following code example, how can I swap all values other than the <em>final</em> value in the list? </p>
<pre><code>arr = [1, 2, 3, 4, 5]
def swapListPairs(arr):
for idx, val in enumerate(arr):
if len(arr) % 2 == 0:
arr[idx], arr[val] = arr[val], arr[idx] # traditional swap using evaluation order
else:
arr[0], arr[1] = arr[1], arr[0] # this line is not the solution but where I know I need some conditions to swap all list values other than len(arr)-1, but am not sure how to do this?
return arr
print swapListPairs(arr)
</code></pre>
<p><strong>Bonus Points to the ultimate Pythonic Master</strong>: How can this code be modified to also swap strings? Right now, I can only use this function using integers and am very curious how I can make this work for both <code>int</code> and <code>str</code> objects?</p>
<p>Thank you so greatly for any insight or suggestions to point me in the right direction! Everyone's help at times here has been invaluable and I thank you for reading and for your help!</p>
| 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 as an expression, a slice is a sequence of the same type. This implies that the index set is renumbered so that it starts at 0.</p>
<p>Extended slicing with a third âstepâ parameter: a[i:j:k] selects all items of a with index x where x = i + n*k, n >= 0 and i <= x < j.</p>
<p>In both cases i, j and/or k can be omitted and in that case suitable values are used instead</p>
<p>Some examples</p>
<pre><code>>>> arr = [10, 20, 30, 40, 50, 60, 70]
>>> arr[:]
[10, 20, 30, 40, 50, 60, 70]
>>> arr[:3]
[10, 20, 30]
>>> arr[1:3]
[20, 30]
>>> arr[1::2]
[20, 40, 60]
>>> arr[::2]
[10, 30, 50, 70]
>>>
</code></pre>
<p>the working of this can also be illustrated with the following function </p>
<pre><code>def the_slice(lista, ini=None, end=None, step=None):
result=[]
if ini is None:
ini = 0
if end is None:
end = len(lista)
if step is None:
step = 1
for index in range(ini,end,step):
result.append( lista[index] )
return result
>>> the_slice(arr,step=2) # arr[::2]
[10, 30, 50, 70]
>>> the_slice(arr,ini=1,step=2) # arr[1::2]
[20, 40, 60]
>>>
</code></pre>
| 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 approach:</p>
<pre><code>sudo chown -R zkid18 /Users/zkid18/Library/Logs/pip
chown: /Users/zkid18/Library/Logs/pip: No such file or directory
</code></pre>
<p>and</p>
<pre><code>sudo chown -R zkid18 /Users/zkid18/Library/Cashes/pip
chown: /Users/zkid18/Library/Cashes/pip: No such file or directory
</code></pre>
<p>Tje same result, when I'm installing via Pycharm
My exception </p>
<p>Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main
status = self.run(options, args)
File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run
prefix=options.prefix_path,
File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 736, in install
requirement.uninstall(auto_confirm=True)
File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 742, in uninstall
paths_to_remove.remove(auto_confirm)
File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
renames(path, new_path)
File "/Library/Python/2.7/site-packages/pip/utils/<strong>init</strong>.py", line 267, in renames
shutil.move(old, new)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
copy2(src, real_dst)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
copystat(src, dst)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-uxDRkx-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'</p>
| 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.ext.automap</code></a> to automagically reflect the schema and create the mappings.</p>
<p>However, I'm wondering if there is any significant benefit of manually creating the mapping classes vs letting the automap do it's magic.</p>
<hr>
<p>If there is significant benefit, can SQLAlchemy auto-generate the python mapping classes like Django's <a href="https://docs.djangoproject.com/en/1.9/ref/django-admin/#django-admin-inspectdb" rel="nofollow"><code>inspectdb</code></a>? That would make creating all of the declarative base mappings much faster, as I'd only have to verify and tweak rather than write from scratch.</p>
<p>Edit:
As @iuridiniz says below, there are a few solutions that mimic Django's <code>inspectdb</code>. See <a href="http://stackoverflow.com/q/1794564/1354930">Is there a Django's inspectdb equivalent for SQLAlchemy?</a>. The answers in that thread are not Python3 compatible, so look into <a href="https://pypi.python.org/pypi/sqlacodegen" rel="nofollow">sqlacodegen</a> or <a href="https://github.com/ksindi/flask-sqlacodegen" rel="nofollow">flask-sqlacodegen</a> if you're looking for something that's actually maintained.</p>
| 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 the mapper. If you've got column objects handy, you're already halfway to writing your own ORM layer. If you just complete the ORM, you won't have to worry about whether tables have primary keys set.</p>
| 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 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
sql = """
drop table a;
select * from some_table limit 1;
"""
df = psql.read_sql(sql, con=conn)
print df.head()
df.to_sql('a', engine)
conn.close()
</code></pre>
| 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
sql = """
select * from some_table limit 1;
"""
df = psql.read_sql(sql, con=conn)
print df.head()
# Notice how below line is different. You forgot the schema argument
df.to_sql('a', con=conn, schema=schema_name, if_exists='replace')
conn.close()
</code></pre>
<p>According to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_sql.html" rel="nofollow">docs</a>: </p>
<blockquote>
<p>replace: If table exists, drop it, recreate it, and insert data.</p>
</blockquote>
<hr>
<p>Ps. Additional tip:</p>
<p>This is better way to handle the connection:</p>
<pre><code>with engine.connect() as conn, conn.begin():
sql = """select * from some_table limit 1"""
df = psql.read_sql(sql, con=conn)
print df.head()
df.to_sql('a', con=conn, schema=schema_name, if_exists='replace')
</code></pre>
<p>Because it ensures that your connection is always closed, even if your program exits with an error. This is important to prevent data corruption. Further, I would just use this:</p>
<pre><code>import pandas as pd
...
pd.read_sql(sql, conn)
</code></pre>
<p>instead of the way you are doing it.</p>
<p>So, if I was in your place writing that code, it would look like this:</p>
<pre><code>import pandas as pd
from sqlalchemy import create_engine
engine = create_engine(r'postgresql://user@localhost:port/dbname')
with engine.connect() as conn, conn.begin():
df = pd.read_sql('select * from some_table limit 1', con=conn)
print df.head()
df.to_sql('a', con=conn, schema=schema_name, if_exists='replace')
</code></pre>
| 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=BeautifulSoup(htmls, "html.parser")
>>> for i in soup.findAll("p",{"class":"pagination-container"}):
print(i.text)
slytherin
gryffindor
>>> for i in soup.findAll("p", {"class":"pag"}):
print(i.text)
>>> for i in soup.findAll("p",{"class":"pagination-container"}):
print(i.text)
slytherin
gryffindor
>>> for i in soup.findAll("p",{"class":"pagination"}):
print(i.text)
>>> len(soup.findAll("p",{"class":"pagination-container"}))
2
>>> len(soup.findAll("p",{"class":"pagination-containe"}))
0
>>> len(soup.findAll("p",{"class":"pagination-contai"}))
0
>>> len(soup.findAll("p",{"class":"pagination-container and something"}))
1
>>> len(soup.findAll("p",{"class":"pagination-conta"}))
0
</code></pre>
<p>So, when we search for <code>pagination-container</code> it returns both the first and the second <code>p</code> tag. It made me think that it looks for a partial equality: something like <code>if passed_string in class_attribute_value:</code>. So I shortened the string in <code>findAll</code> method and it never managed to find anything! </p>
<p>How is that possible?</p>
| 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 handling.</p>
<p>When you write <code>soup.findAll("p", {"class":"pag"})</code>, <code>BeautifulSoup</code> would search for elements having class <code>pag</code>. It would split element class value by space and check if there is <code>pag</code> among the splitted items. If you had an element with <code>class="test pag"</code> or <code>class="pag"</code>, it would be matched.</p>
<p>Note that in case of <code>soup.findAll("p", {"class": "pagination-container and something"})</code>, <code>BeautifulSoup</code> would match an element having the exact <code>class</code> attribute value. There is no splitting involved in this case - it just sees that there is an element where the complete <code>class</code> value equals the desired string.</p>
<p>To have a <em>partial match on one of the classes</em>, you can provide a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-regular-expression" rel="nofollow">regular expression</a> or <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-function" rel="nofollow">a function</a> as a class filter value:</p>
<pre><code>import re
soup.find_all("p", {"class": re.compile(r"pag")}) # contains pag
soup.find_all("p", {"class": re.compile(r"^pag")}) # starts with pag
soup.find_all("p", {"class": lambda class_: class_ and "pag" in class_}) # contains pag
soup.find_all("p", {"class": lambda class_: class_ and class_.startswith("pag")}) # starts with pag
</code></pre>
<hr>
<p>There is much more to say, but you should also know that <code>BeautifulSoup</code> has <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow">CSS selector</a> support (a limited one but covers most of the common use cases). You can write things like:</p>
<pre><code>soup.select("p.pagination-container") # one of the classes is "pagination-container"
soup.select("p[class='pagination-container']") # match the COMPLETE class attribute value
soup.select("p[class^=pag]") # COMPLETE class attribute value starts with pag
</code></pre>
<hr>
<p>Handling <code>class</code> attribute values in <code>BeautifulSoup</code> is a common source of confusion and questions, please see these related topics to gain more understanding:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/34288969/beautifulsoup-returns-empty-list-when-searching-by-compound-class-names">BeautifulSoup returns empty list when searching by compound class names</a> </li>
<li><a href="http://stackoverflow.com/questions/29877663/finding-multiple-attributes-within-the-span-tag-in-python">Finding multiple attributes within the span tag in Python</a></li>
</ul>
| 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 encryption of value under key, as well as IV.
Pads value with extra bytes to make it multiple of 16.
"""
extra = 16 - (len(value) % 16)
data = value + chr(extra) * extra
iv = get_random_bytes(16)
encryption_suite = AES.new(key, AES.MODE_CBC, iv)
cipher_text = encryption_suite.encrypt(data)
return cipher_text, iv
</code></pre>
<p>Why am I not using Django's encryptions? Because there is a client application that is NOT written in Django (and won't ever be) that accepts the encrypted value the user stored previously and decrypts it once the user enters their secret key.</p>
<p>Problem is that I can't seem to save the encrypted value to the database for the User model. For example:</p>
<pre><code>user = User.objects.get(id=user_id)
cipher, iv = encrypt(user_value, user_key)
user.secret_value = cipher
user.iv = iv
user.save()
</code></pre>
<p>This results in this error:</p>
<p><code>Warning: Incorrect string value: '\xE7\xAA\x13\x036\xC8...' for column 'iv' at row 1</code> </p>
<p>(same error for secret_value)</p>
<p>I know this must be something to do with improper encoding. What's the right way to go about fixing this? Should I convert each byte into a string character?</p>
<p>Thanks.</p>
| 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.]])
</code></pre>
<p>But this throws an error:</p>
<pre><code>>>> s = pd.Series(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/miniconda/envs/pyspark/lib/python3.4/site-packages/pandas/core/series.py", line 227, in __init__
raise_cast_failure=True)
File "/miniconda/envs/pyspark/lib/python3.4/site-packages/pandas/core/series.py", line 2920, in _sanitize_array
raise Exception('Data must be 1-dimensional')
Exception: Data must be 1-dimensional
</code></pre>
<p>It is possible with a hack:</p>
<pre><code>>>> s = pd.Series(map(lambda x:[x], a)).apply(lambda x:x[0])
>>> s
0 [0.0, 0.0]
1 [0.0, 0.0]
2 [0.0, 0.0]
3 [0.0, 0.0]
4 [0.0, 0.0]
</code></pre>
<p>Is there a better way?</p>
| 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]]
>>> pd.Series(a.tolist())
0 [0.0, 0.0]
1 [0.0, 0.0]
2 [0.0, 0.0]
3 [0.0, 0.0]
4 [0.0, 0.0]
dtype: object
</code></pre>
<p>EDIT:</p>
<p>A faster way to accomplish a similar result is to simply do <code>pd.Series(list(a))</code>. This will make a Series of numpy arrays instead of Python lists, so should be faster than <code>a.tolist</code> which returns a list of Python lists. </p>
| 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.]])
</code></pre>
<p>But this throws an error:</p>
<pre><code>>>> s = pd.Series(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/miniconda/envs/pyspark/lib/python3.4/site-packages/pandas/core/series.py", line 227, in __init__
raise_cast_failure=True)
File "/miniconda/envs/pyspark/lib/python3.4/site-packages/pandas/core/series.py", line 2920, in _sanitize_array
raise Exception('Data must be 1-dimensional')
Exception: Data must be 1-dimensional
</code></pre>
<p>It is possible with a hack:</p>
<pre><code>>>> s = pd.Series(map(lambda x:[x], a)).apply(lambda x:x[0])
>>> s
0 [0.0, 0.0]
1 [0.0, 0.0]
2 [0.0, 0.0]
3 [0.0, 0.0]
4 [0.0, 0.0]
</code></pre>
<p>Is there a better way?</p>
| 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: 301 ms per loop
%timeit pd.Series(a.tolist())
1 loop, best of 3: 261 ms per loop
</code></pre>
| 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, 49863795.672, 49863892.911, 49864078.203, 49864455.172, 49864628.486, 49865539.345, 49865562.414, 49865652.025, 49865860.79, 49866049.199, 49866559.841, 49866709.259, 49866976.163, 49867118.158, 49867184.515, 49867228.03, 49867703.98, 49868191.475, 49868264.993, 49868402.682, 49868547.472, 49868849.941, 49869167.486, 49869233.011, 49869388.16, 49869462.118, 49869947.616, 49869976.177, 49870146.971, 49870441.068, 49870858.267, 49870898.339, 49870966.598, 49871065.408, 49871113.361, 49871268.792, 49871332.292, 49872008.637, 49872014.321, 49872128.757, 49872276.278, 49872296.18, 49872322.098, 49872366.707, 49872370.336, 49872537.099, 49872909.555, 49872917.363, 49873131.438, 49873230.402, 49873252.129, 49873289.302, 49873382.584, 49873429.968, 49873440.124, 49873444.505, 49873507.617, 49873835.836, 49873905.902, 49873965.72, 49874080.127, 49874101.966, 49874166.944, 49874359.819, 49874388.385, 49874412.152, 49874421.629, 49874584.264, 49874755.328, 49874798.936, 49874833.007, 49875145.279, 49875310.799, 49875391.973, 49875484.389, 49875615.09, 49875616.889, 49875773.568, 49875776.696, 49875892.137, 49875953.749, 49875954.395, 49876161.776, 49876220.899, 49876321.362, 49876380.343, 49876496.107, 49876595.953, 49876644.428, 49876655.041, 49876714.369, 49876770.925, 49876788.46, 49876932.063, 49876952.641, 49877075.874, 49877105.142, 49877220.934, 49877288.062, 49877294.256, 49877308.79, 49877551.764, 49877586.774, 49877620.658, 49877666.194, 49877842.635, 49878091.505, 49878171.278, 49878181.791, 49878229.777, 49878244.476, 49878483.22, 49878541.483, 49878602.181, 49878612.309, 49878615.488, 49878677.558, 49878683.807, 49878703.616, 49878785.269, 49878793.774, 49878922.532, 49878933.228, 49878981.748, 49879041.296, 49879060.17, 49879263.424, 49879355.213, 49879449.193, 49879455.009, 49879471.561, 49879508.752, 49879538.815, 49879597.852, 49879683.744, 49879727.257, 49879751.962, 49879895.858, 49879960.524, 49880178.136, 49880196.753, 49880217.788, 49880336.479, 49880370.356, 49880396.479, 49880422.808, 49880539.652, 49880559.579, 49880624.786, 49880704.456, 49880739.891, 49880836.13, 49880886.385, 49880938.998, 49881169.02, 49881288.366, 49881305.161, 49881426.038, 49881427.956, 49881463.834, 49881617.346, 49881730.679, 49881881.14, 49881894.675, 49881979.949, 49882096.47, 49882112.031, 49882131.716, 49882159.639, 49882190.252, 49882483.949, 49882538.07, 49882583.816, 49882597.938, 49882602.861, 49882611.359, 49882648.24, 49882684.267, 49882706.434, 49882835.084, 49883043.946, 49883084.906, 49883109.752, 49883228.104, 49883288.07, 49883382.503, 49883401.475, 49883491.927, 49883574.922, 49883654.813, 49883702.522, 49883801.5, 49883814.683, 49883826.244, 49883846.713, 49883855.077, 49883978.159, 49884046.234, 49884064.489, 49884112.738, 49884138.818, 49884220.732, 49884251.195, 49884255.97, 49884361.999, 49884397.955, 49884416.274, 49884498.095, 49884516.764, 49884548.794, 49884580.933, 49884597.752, 49884624.897, 49884634.323, 49884670.05, 49884676.813, 49884733.419, 49884751.203, 49884834.288, 49884888.879, 49884902.225, 49885004.171, 49885153.972, 49885157.866, 49885173.615, 49885174.386, 49885219.196, 49885273.781, 49885347.517, 49885364.666, 49885380.826, 49885427.356, 49885509.155, 49885541.137, 49885578.287, 49885595.473, 49885612.014, 49885710.601, 49885740.394, 49885741.348, 49885841.454, 49885952.568, 49885988.633, 49886053.94, 49886058.886, 49886076.628, 49886095.714, 49886147.686, 49886164.4, 49886179.103, 49886201.971, 49886279.139, 49886312.282, 49886312.8, 49886324.598, 49886408.542, 49886481.161, 49886548.747, 49886641.616, 49886642.093, 49886668.221, 49886675.982, 49886725.046, 49886741.706, 49886821.745, 49886833.46, 49886840.54, 49886850.264, 49886873.972, 49887005.587, 49887042.942, 49887073.685, 49887076.296, 49887091.248, 49887105.67, 49887148.602, 49887159.267, 49887271.173, 49887285.866, 49887303.534, 49887369.19, 49887382.49, 49887454.943, 49887479.589, 49887498.203, 49887616.744, 49887721.935, 49887747.864, 49887786.036, 49887803.228, 49887858.683, 49887943.768, 49888058.328, 49888058.963, 49888148.314, 49888200.419, 49888346.257, 49888362.013, 49888366.362, 49888406.004, 49888450.807, 49888497.044, 49888614.062, 49888622.199, 49888628.315, 49888717.575, 49888731.575, 49888736.902, 49888765.916, 49888803.98, 49888875.799, 49888892.348, 49888934.101, 49888967.728, 49888974.393, 49888981.908, 49889075.143, 49889221.983, 49889255.367, 49889277.661, 49889298.851, 49889319.147, 49889320.207, 49889407.915, 49889413.481, 49889429.941, 49889469.243, 49889487.959, 49889532.295, 49889539.477, 49889552.03, 49889572.229, 49889585.375, 49889602.118, 49889668.329, 49889683.014, 49889697.206, 49889772.868, 49889806.44, 49889881.148, 49889916.157, 49889961.726, 49889989.911, 49889997.299, 49890021.069, 49890092.985, 49890123.557, 49890137.558, 49890249.033, 49890337.341, 49890363.69, 49890412.835, 49890438.527, 49890455.844, 49890457.272, 49890540.923, 49890552.792, 49890571.653, 49890656.799, 49890657.446, 49890771.402, 49890893.014, 49890940.859, 49891117.607, 49891188.608, 49891197.473, 49891204.319, 49891260.746, 49891286.509, 49891329.619, 49891369.244, 49891373.448, 49891400.609, 49891594.308, 49891664.373, 49891769.784, 49891812.789, 49891878.95, 49891889.874, 49891924.49, 49891962.647, 49891972.677, 49892086.585, 49892096.15, 49892131.411, 49892145.241, 49892147.07, 49892186.586, 49892221.814, 49892257.429, 49892295.906, 49892366.592, 49892414.483, 49892486.488, 49892505.361, 49892571.789, 49892614.344, 49892775.098, 49892807.812, 49892832.242, 49892837.597, 49892858.141, 49892894.853, 49892896.347, 49893017.939, 49893029.177, 49893118.449, 49893168.059, 49893232.781, 49893235.78, 49893287.331, 49893326.778, 49893406.653, 49893471.93, 49893495.472, 49893510.31, 49893593.136, 49893668.36, 49893690.138, 49893717.478, 49893841.341, 49893849.407, 49893918.451, 49893929.304, 49893965.073, 49893995.907, 49894105.083, 49894113.528, 49894207.766, 49894220.283, 49894229.309, 49894287.256, 49894296.334, 49894321.153, 49894394.072, 49894410.075, 49894426.245, 49894429.549, 49894486.508, 49894569.593, 49894596.175, 49894646.893, 49894684.32, 49894706.127, 49894730.259, 49894814.007, 49894846.182, 49894921.957, 49895075.836, 49895134.196, 49895411.552, 49895467.919, 49895581.219, 49895643.126, 49895681.785, 49895715.833, 49895717.103, 49895732.304, 49895747.613, 49895775.574, 49895797.26, 49895801.342, 49895905.897, 49895914.703, 49895933.794, 49895949.521, 49895999.669, 49896017.596, 49896189.338, 49896213.562, 49896231.62, 49896310.695, 49896462.188, 49896483.7, 49896508.985, 49896602.682, 49896631.951, 49896719.268, 49896806.399, 49896806.913, 49896872.332, 49897018.727, 49897124.196, 49897134.793, 49897213.913, 49897270.838, 49897284.028, 49897315.792, 49897330.168]
plt.hist(x)
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/5mP7i.png" rel="nofollow"><img src="http://i.stack.imgur.com/5mP7i.png" alt="enter image description here"></a></p>
<p>In my example, the axis should be scaled by 1e7 or 1e8, or displayed as rgular numbers--not 4.986e7. Why would anyone want this setting? How can I make the x axis numbers human-readable?</p>
| 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.draw()
</code></pre>
| 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 get this error: <strong>No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.</strong></p>
<p>I tried using <a href="http://stackoverflow.com/questions/33585579/django-redirect-to-previous-url-after-createview">this solution</a>, but it kicks out the same error. I tried passing the data and redirecting through the URL that calls the CreateView. I still get the same error.</p>
<p>Can someone please tell me how to redirect the CreateView back to the original DetailView (and passing back the validated data?</p>
<p>models.py</p>
<pre><code>class Lawyer(models.Model):
name = models.CharField(max_length=100, default='')
practice_area = models.CharField(max_length=100, default='')
address = models.CharField(max_length=255, default='')
city = models.CharField(max_length=50, default='')
state = models.CharField(max_length=2, default='')
zipcode = models.CharField(max_length=10, default='')
telephone = models.CharField(max_length=15, default='')
years_practice = models.IntegerField(default=10)
objects = models.Manager()
lawyer_slug = models.SlugField(default='')
def get_absolute_url(self):
return reverse('lawyer_detail', kwargs={'lawyer_slug': self.lawyer_slug})
def __str__(self):
return self.name
class Review(models.Model):
RATING_CHOICES = (
(0, '0'),
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
(5, '5'),
)
lawyer = models.ForeignKey(Lawyer, null=True)
review_created = models.DateTimeField('Date of Review', auto_now_add=True)
reviewer_name = models.CharField(max_length=55, default='')
reviewer_city = models.CharField(max_length=55, default='')
reviewer_state = models.CharField(max_length=2, default='')
email = models.EmailField(default='')
rating = models.IntegerField(default=1, choices=RATING_CHOICES)
review_comment = models.TextField(default='')
review_slug = models.SlugField(default='')
def get_absolute_url(self):
return reverse('lawyer_createreview', kwargs={'review_slug': self.review_slug})
def __str__(self):
return self.review_slug
</code></pre>
<p>views.py</p>
<pre><code>class LawyerDetail(DetailView):
model = Lawyer
template = 'lawyer_detail.html'
context_object_name = 'lawyer'
def get_object(self):
lawyer_slug = Lawyer.objects.get(
lawyer_slug=self.kwargs.get('lawyer_slug')
)
return lawyer_slug
def get_context_data(self, **kwargs):
context = super(LawyerDetail, self).get_context_data(**kwargs)
context['lawyer_reviews'] = self.object.review_set.all()
return context
class LawyerReviewCreate(CreateView):
model = Review
form_class = ReviewForm
def get_form_kwargs(self, **kwargs):
kwargs = super(LawyerReviewCreate, self).get_form_kwargs()
redirect = self.request.GET.get('next')
if redirect:
if 'initial' in kwargs.keys():
kwargs['initial'].update({'next': redirect})
else:
kwargs['initial'] = {'next': redirect}
return kwargs
def form_invalid(self, form):
import pdb;pdb.set_trace() # debug example
return super(LawyerReviewCreate, self).form_invalid(form)
def form_valid(self, form):
redirect = form.cleaned_data.get('next')
if redirect:
self.success_url = redirect
return super(LawyerReviewCreate, self).form_valid(form)
</code></pre>
<p>urls.py</p>
<pre><code>url(r'^lawyers/(?P<lawyer_slug>[\w-]+)/$', LawyerDetail.as_view(), name='lawyer_detail'),
url(r'^lawyers/(?P<lawyer_slug>[\w-]+)/createreview/$', LawyerReviewCreate.as_view(), name='lawyer_createreview'),
</code></pre>
<p>template.html (calls CreateView and part that displays the returned data)</p>
<pre><code><div class="review_buttom_wrapper">
<a href="{% url 'lawyer_createreview' lawyer.lawyer_slug %}?next={% url 'lawyer_detail' lawyer.lawyer_slug %}">
<button class="review_button">
<strong>Review</strong> {{ lawyer.name }}
</button>
</a>
</div>
{% for review in lawyer_reviews %}
<div style="padding-left: 15px; padding-right: 15px; overflow:auto;">
<div class="review-masthead">
<div class="medium-3 columns">
<p class="posttime">{{ review.review_created|timesince }} ago </p>
<p class="review-title">{{ review.user_name }} <span class="location">{{ review.lawyer.city }}, {{ review.lawyer.state }}</span></p>
</div>
<div class="medium-7 columns">
<p>{{ review.review_comment }}</p>
</div>
<div class="medium-2 columns">
<div class="user_rating">
Rating
</div>
<div class="rating_number">
{{ review.rating }}
</div>
</div>
</div>
{% endfor %}
</code></pre>
<p>forms.py</p>
<pre><code>RATING_CHOICES = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
(5, '5'),
)
class ReviewForm(forms.ModelForm):
reviewer_name = forms.CharField(widget = forms.TextInput(attrs={'class': 'review_input_box', 'placeholder': 'Your name'}))
reviewer_city = forms.CharField(widget = forms.TextInput(attrs={'class': 'review_input_box', 'placeholder': 'Your city'}))
reviewer_state = forms.CharField(widget = forms.TextInput(attrs={'class': 'review_input_box', 'placeholder': 'Your state'}))
rating = forms.ChoiceField(choices = RATING_CHOICES, label="", initial='', widget = forms.Select(attrs={'class': 'review_selector'}), required=True)
email = forms.EmailField(widget = forms.TextInput(attrs={'class': 'review_input_box', 'placeholder': 'your-email@email.com'}))
review_comment = forms.CharField(widget = forms.Textarea(attrs={'class': 'review_input_box', 'placeholder': 'What would you like to say?'}))
class Meta:
model = Review
fields = ['reviewer_name', 'reviewer_city', 'reviewer_state', 'rating', 'email', 'review_comment']
Traceback:
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/views/generic/edit.py" in get_success_url
190. url = self.object.get_absolute_url()
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/ralph/fathers/models.py" in get_absolute_url
142. return reverse('lawyer_createreview', kwargs={'lawyer_slug': self.lawyer_slug})
During handling of the above exception ('Review' object has no attribute 'lawyer_slug'), another exception occurred:
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/views/generic/base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/views/generic/edit.py" in post
256. return super(BaseCreateView, self).post(request, *args, **kwargs)
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/views/generic/edit.py" in post
222. return self.form_valid(form)
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/ralph/fathers/views.py" in form_valid
165. return super(LawyerReviewCreate, self).form_valid(form)
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/views/generic/edit.py" in form_valid
202. return super(ModelFormMixin, self).form_valid(form)
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/views/generic/edit.py" in form_valid
108. return HttpResponseRedirect(self.get_success_url())
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/views/generic/edit.py" in get_success_url
193. "No URL to redirect to. Either provide a url or define"
Exception Type: ImproperlyConfigured at /xxxxxxx/xxxxxxx/xxxxxxx-xxxxxx/createreview/
Exception Value: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.
</code></pre>
<p>Traceback after changing get_absolute_url on Review model</p>
<pre><code>Traceback:
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/contrib/admin/sites.py" in wrapper
265. return self.admin_view(view, cacheable)(*args, **kwargs)
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner
244. return view(request, *args, **kwargs)
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/contrib/contenttypes/views.py" in shortcut
31. absurl = get_absolute_url()
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/xxxxx/xxxxxxx/models.py" in get_absolute_url
142. return reverse('lawyer_createreview', kwargs={'review_slug': self.review_slug})
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/core/urlresolvers.py" in reverse
600. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/xxxx/xxxxxxxxxx/xxxx/xxxxxxxxxxxx/lib/python3.5/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix
508. (lookup_view_s, args, kwargs, len(patterns), patterns))
Exception Type: NoReverseMatch at /admin/r/14/1/
Exception Value: Reverse for 'lawyer_createreview' with arguments '()' and keyword arguments '{'review_slug': 'michael-ferrin'}' not found. 1 pattern(s) tried: ['fathers/lawyers/(?P<lawyer_slug>[\\w-]+)/createreview/$']
</code></pre>
| 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):
return reverse('lawyer_detail', kwargs={'lawyer_slug': self.object.lawyer_slug})
</code></p>
<p>This will then automatically send the user back to the detail view if the form is valid.</p>
<p>Also, make sure your kwargs is using the correct key, it would appear that you are using review_slug in some cases and lawyer_slug in other cases</p>
| 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():
count=+1
name = raw_input("Name: ")
email_prompt = raw_input("Please enter your email address: ")
userid = uuid.uuid4()
filename = (str(email_prompt)+str(count))
print("QR Code Created: %s") %(filename)
qr_code_fn(email_prompt, userid)
</code></pre>
<p>A pointer in the right direction would be fantastic. </p>
<p>Cheers!</p>
| 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 format the <code>None</code> returned by <code>print</code>, which is clearly not going to work. </p>
<p>You should remove the closing parenthesis trailing the string:</p>
<pre><code>print("QR Code Created: %s" % filename)
</code></pre>
| 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.bind(("", 1500))
welcome_socket.listen(5)
</code></pre>
<p>I then listen for incoming connections:</p>
<pre><code>(client_socket, address) = self.welcome_socket.accept()
</code></pre>
<p>I connect from a client (behind a NAT) using the following code:</p>
<pre><code>sock = socket.create_connection(("server_address", 1500))
</code></pre>
<p>Here is where I'm a little confused. </p>
<p>The address I get on the server side has the public address of the WiFi network the client is connected to (which I expect) and some port number, which based on my understanding of NATs, should be different from the actual port number used by the client and is used for address translation. </p>
<p>However, if I used the getsockname() function on the client, I get the same port number as the one given by the server. </p>
<p>Returning to the example in code.</p>
<p>On the server:</p>
<pre><code>client_socket.getpeername()
>>> ('WiFi_address', 4551)
</code></pre>
<p>On the client:</p>
<pre><code>sock.getsockname()
>>> ('local_address', 4551)
</code></pre>
<p>So, both port numbers are the same, even though the client is behind a NAT. How is this the case? Am I misunderstanding how the NAT works? Or is there another command to get the physical address that the client socket is bound to?</p>
<p>Any insight would be appreciated. </p>
| 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 already used, PAT assigns the first available port number starting
from the beginning of the appropriate port group 0-511, 512-1023, or
1024-65535. When there are no more ports available and there is more
than one external IP address configured, PAT moves to the next IP
address to try to allocate the original source port again. This
process continues until it runs out of available ports and external IP
addresses.</p>
</blockquote>
<p>And that should be the reason why you are seeing port 4551 on the server.</p>
<p>(<a href="http://blog.boson.com/bid/53313/NAT-and-PAT-What-s-the-Difference" rel="nofollow">This link</a> should also help to clarify the difference between NAT and PAT)</p>
| 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)
sum_check(a,b,ctr)
out = " ".join(str(x) for x in sum_check(a,b,ctr))
out.replace(" ","")
print(out)
def equalize(a,b):
if len(a) > len(b):
for i in range(0, len(a)-len(b)):
b.insert(0,'0')
elif len(a) < len(b):
for i in range(0, len(b)-len(a)):
a.insert(0,'0')
def sum_check(a,b):
out = []
ctr = 0
def sum(a, b):
if ctr > 0:
if a[-1] + b[-1] == 2:
out.append('1')
elif a[-1] + b[-1] == 0:
out.append('1')
ctr -= 1
else: # a[-1] + b[-1] = 1
out.append('0')
ctr -= 1
else: # ctr = 0
if a[-1] + b[-1] == 2:
out.append('1')
ctr += 1
elif a[-1] + b[-1] == 0:
out.append('0')
else: # a[-1] + b[-1] = 1
out.append('1')
for i in range(len(a)):
if i == 0:
sum(a,b)
else:
new_a = a[:-1]
new_b = b[:-1]
sum(new_a, new_b)
return out
</code></pre>
| -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 and working. I have inserted some comments at places where I changed things (either errors in the algorithm, or python programming errors).</p>
<p>I have put <code>def sum(...)</code> outside <code>sum_check</code>, it's clearer this way.</p>
<p>Though you should know that <code>sum</code> is a <a href="https://docs.python.org/3.4/library/functions.html#sum" rel="nofollow">python builtin</a>, so you should find another name, to avoid losing the builtin in your namespace (but I guess your algorithm is only for training purpose, since you could replace all this by an operation on binary numbers directly:</p>
<pre><code>$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = int('10110', 2)
>>> b = int('1011100', 2)
>>> bin(a + b)
'0b1110010'
>>>
</code></pre>
<p>).</p>
<p>Also, I have left some debugging <code>print</code> statements, to help to see what happens. Plus an example to check all cases were gone through.</p>
<p>Last note: it first crashed because you used <code>ctr</code> before you had defined it. This was the first thing to correct.</p>
<pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def equalize(a, b):
if len(a) > len(b):
for i in range(0, len(a) - len(b)):
b.insert(0, 0)
elif len(a) < len(b):
for i in range(0, len(b) - len(a)):
a.insert(0, 0)
return a, b
def sum(a, b, ctr):
out = ''
print('\n'.join(['-------', 'Working on:', str(a), str(b)]))
if ctr > 0:
if a[-1] + b[-1] == 2:
out = '1'
print('Case 1')
elif a[-1] + b[-1] == 0:
out = '1'
ctr -= 1
print('Case 2')
else: # a[-1] + b[-1] = 1
out = '0'
print('Case 3')
# ctr -= 1 (wrong)
else: # ctr = 0
if a[-1] + b[-1] == 2:
out = '0' # '1' was wrong
ctr += 1
print('Case 4')
elif a[-1] + b[-1] == 0:
out = '0'
print('Case 5')
else: # a[-1] + b[-1] = 1
out = '1'
print('Case 6')
print('Sum will return: ' + str(out)
+ ' and carry: ' + str(ctr) + '\n-------')
return out, ctr
def sum_check(a, b):
ctr = 0
out = []
n = len(a)
for i in range(n):
if i != 0:
# You were always giving the same a and b to feed sum().
# In order to change them, as it's not advised to iterate over a
# changing list (maybe not even possible), I stored the desired
# length in a number n. Then, I assign new values to a and b.
a = a[:-1]
b = b[:-1]
new_out, ctr = sum(a, b, ctr)
out.append(new_out)
print('Current out: ' + str(out) + ' and carry: ' + str(ctr))
return out
def add(a, b):
a = [int(x) for x in a]
b = [int(x) for x in b]
# You need to return the new contents of a and b, otherwise you'll keep
# them as they were before the call to equalize()
a, b = equalize(a, b)
print('\n'.join(['Equalized: ', str(a), str(b)]))
# On next line, [::-1] reverses the result (your algorithm returns a
# result to be read from right to left)
print('Result: ' + ''.join(sum_check(a, b)[::-1]))
add('10110', '1011100')
</code></pre>
<p>Output:</p>
<pre><code>Equalized:
[0, 0, 1, 0, 1, 1, 0]
[1, 0, 1, 1, 1, 0, 0]
-------
Working on:
[0, 0, 1, 0, 1, 1, 0]
[1, 0, 1, 1, 1, 0, 0]
Case 5
Sum will return: 0 and carry: 0
-------
Current out: ['0'] and carry: 0
-------
Working on:
[0, 0, 1, 0, 1, 1]
[1, 0, 1, 1, 1, 0]
Case 6
Sum will return: 1 and carry: 0
-------
Current out: ['0', '1'] and carry: 0
-------
Working on:
[0, 0, 1, 0, 1]
[1, 0, 1, 1, 1]
Case 4
Sum will return: 0 and carry: 1
-------
Current out: ['0', '1', '0'] and carry: 1
-------
Working on:
[0, 0, 1, 0]
[1, 0, 1, 1]
Case 3
Sum will return: 0 and carry: 1
-------
Current out: ['0', '1', '0', '0'] and carry: 1
-------
Working on:
[0, 0, 1]
[1, 0, 1]
Case 1
Sum will return: 1 and carry: 1
-------
Current out: ['0', '1', '0', '0', '1'] and carry: 1
-------
Working on:
[0, 0]
[1, 0]
Case 2
Sum will return: 1 and carry: 0
-------
Current out: ['0', '1', '0', '0', '1', '1'] and carry: 0
-------
Working on:
[0]
[1]
Case 6
Sum will return: 1 and carry: 0
-------
Current out: ['0', '1', '0', '0', '1', '1', '1'] and carry: 0
Result: 1110010
</code></pre>
| 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 | country | city | occurance <br>
---------------------------------------------------
somedate | united kingdom | london | 5
---------------------------------------------------
somedate | united state | newyork | 5
</code></pre>
<p>I am new to Python and after some research I have written following code, but seems to unable to extract country and city:</p>
<pre><code>df.location= df.location.replace({'-': ' '}, regex=True)
df.location= df.location.replace({'_': ' '}, regex=True)
temp_location = df['location'].str.split(' ').tolist()
location_data = pd.DataFrame(temp_location, columns=['country', 'city'])
</code></pre>
<p>I appreciate your response.</p>
| 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'] = splits[0:-1].tolist()
df['city'] = splits[-1].tolist()
</code></pre>
| 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 | country | city | occurance <br>
---------------------------------------------------
somedate | united kingdom | london | 5
---------------------------------------------------
somedate | united state | newyork | 5
</code></pre>
<p>I am new to Python and after some research I have written following code, but seems to unable to extract country and city:</p>
<pre><code>df.location= df.location.replace({'-': ' '}, regex=True)
df.location= df.location.replace({'_': ' '}, regex=True)
temp_location = df['location'].str.split(' ').tolist()
location_data = pd.DataFrame(temp_location, columns=['country', 'city'])
</code></pre>
<p>I appreciate your response.</p>
| 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_state_newyork'],
'occurence': [5, 5]})
df['country'] = df['location'].apply(lambda x: x[0:x.rfind('_')])
df['city'] = df['location'].apply(lambda x: x[x.rfind('_')+1:])
df = df[['Date', 'country', 'city', 'occurence']]
print(df)
# Date country city occurence
# 0 somedate united_kingdom london 5
# 1 somedate united_state newyork 5
</code></pre>
| 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 | country | city | occurance <br>
---------------------------------------------------
somedate | united kingdom | london | 5
---------------------------------------------------
somedate | united state | newyork | 5
</code></pre>
<p>I am new to Python and after some research I have written following code, but seems to unable to extract country and city:</p>
<pre><code>df.location= df.location.replace({'-': ' '}, regex=True)
df.location= df.location.replace({'_': ' '}, regex=True)
temp_location = df['location'].str.split(' ').tolist()
location_data = pd.DataFrame(temp_location, columns=['country', 'city'])
</code></pre>
<p>I appreciate your response.</p>
| 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]
newcols = df.location.str.split(" ")
newcols = pd.DataFrame(df.location.str.split(" ").tolist(),
columns=["country", "city"])
newcols.country = newcols.country.str.replace("_", " ")
df = pd.concat([df, newcols], axis=1)
df.drop("location", axis=1, inplace=True)
print(df)
Date occurence country city
0 somedate 5 united kingdom london
1 somedate 5 united state newyork
</code></pre>
<p>You could use regex in the replace for a more complicated pattern but if it's just the word after the last <code>_</code> I find it easier to just reverse the str twice as a hack rather than fiddling around with regular expressions</p>
| 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 | country | city | occurance <br>
---------------------------------------------------
somedate | united kingdom | london | 5
---------------------------------------------------
somedate | united state | newyork | 5
</code></pre>
<p>I am new to Python and after some research I have written following code, but seems to unable to extract country and city:</p>
<pre><code>df.location= df.location.replace({'-': ' '}, regex=True)
df.location= df.location.replace({'_': ' '}, regex=True)
temp_location = df['location'].str.split(' ').tolist()
location_data = pd.DataFrame(temp_location, columns=['country', 'city'])
</code></pre>
<p>I appreciate your response.</p>
| 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.replace("_", " ")
df['City'] = df['location'].str.rpartition('_')[2]
df[['Date','Country', 'City', 'occurence']]
Date Country City occurence
0 somedate united kingdom london 5
1 somedate united state newyork 5
</code></pre>
<p>Borrowing idea from @MaxU</p>
<pre><code>df[['Country'," " , 'City']] = (df.location.str.replace('_',' ').str.rpartition(' ', expand= True ))
df[['Date','Country', 'City','occurence' ]]
Date Country City occurence
0 somedate united kingdom london 5
1 somedate united state newyork 5
</code></pre>
| 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 | country | city | occurance <br>
---------------------------------------------------
somedate | united kingdom | london | 5
---------------------------------------------------
somedate | united state | newyork | 5
</code></pre>
<p>I am new to Python and after some research I have written following code, but seems to unable to extract country and city:</p>
<pre><code>df.location= df.location.replace({'-': ' '}, regex=True)
df.location= df.location.replace({'_': ' '}, regex=True)
temp_location = df['location'].str.split(' ').tolist()
location_data = pd.DataFrame(temp_location, columns=['country', 'city'])
</code></pre>
<p>I appreciate your response.</p>
| 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 5
2 somedate germany_munich 5
In [108]: df[['country','city']] = (df.location.str.replace('_',' ')
.....: .str.extract(r'(.*)\s+([^\s]*)', expand=True))
In [109]: df
Out[109]:
Date location occurence country city
0 somedate united_kingdom_london 5 united kingdom london
1 somedate united_state_newyork 5 united state newyork
2 somedate germany_munich 5 germany munich
In [110]: df = df.drop('location', 1)
In [111]: df
Out[111]:
Date occurence country city
0 somedate 5 united kingdom london
1 somedate 5 united state newyork
2 somedate 5 germany munich
</code></pre>
<p>PS please be aware that it's not possible to parse properly (to distinguish) between rows containing two-words country + one-word city and rows containing one-word country + two-words city (unless you have a full list of countries so you check it against this list)...</p>
| 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 | country | city | occurance <br>
---------------------------------------------------
somedate | united kingdom | london | 5
---------------------------------------------------
somedate | united state | newyork | 5
</code></pre>
<p>I am new to Python and after some research I have written following code, but seems to unable to extract country and city:</p>
<pre><code>df.location= df.location.replace({'-': ' '}, regex=True)
df.location= df.location.replace({'_': ' '}, regex=True)
temp_location = df['location'].str.split(' ').tolist()
location_data = pd.DataFrame(temp_location, columns=['country', 'city'])
</code></pre>
<p>I appreciate your response.</p>
| 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: 'somedate', 2: 'somedate'},
'location': {0: 'slovakia_bratislava',
1: 'united_kingdom_london',
2: 'united_state_newyork'},
'occurance <br>': {0: 5, 1: 5, 2: 5}})
print (df)
date location occurance <br>
0 somedate slovakia_bratislava 5
1 somedate united_kingdom_london 5
2 somedate united_state_newyork 5
df[['country','city']] = df.location.str.replace('_', ' ').str.rsplit(n=1, expand=True)
#change ordering of columns, remove location column
cols = df.columns.tolist()
df = df[cols[:1] + cols[3:5] + cols[2:3]]
print (df)
date country city occurance <br>
0 somedate slovakia bratislava 5
1 somedate united kingdom london 5
2 somedate united state newyork 5
</code></pre>
| 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 <code>%g</code> for auto-choice between different representations.</p>
| 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 datetime import datetime, time
now = datetime.now()
now_time = now.time()
SleepTimeL = 2
if now_time >= time (9,30) and now_time <= time (16,15):
print "yes, within the interval"
print now_time
time.sleep( 9 )
else:
print "no"
</code></pre>
| 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>
<p>You can replace the conditions with a <a href="https://docs.python.org/2/reference/expressions.html#not-in" rel="nofollow"><em>chained comparison</em></a>, which is more readable.</p>
<p>You can also set the comparison as the condition on the <code>while</code>, in which case the loop only runs in the specified duration and needs to be restarted for the cycle of the duration:</p>
<pre><code>while time (9,30) <= now_time <= time (16,15):
print "yes, within the interval"
now_time = datetime.now().time()
print now_time
time.sleep( 9 )
</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 datetime import datetime, time
now = datetime.now()
now_time = now.time()
SleepTimeL = 2
if now_time >= time (9,30) and now_time <= time (16,15):
print "yes, within the interval"
print now_time
time.sleep( 9 )
else:
print "no"
</code></pre>
| 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 interval"
print now_time
time.sleep( 9 )
else: print "no"
</code></pre>
<p>If you want to make an aquarium controller you should check the lights state in every iteration:</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):
if isLightOff: lightOn
time.sleep( 9 )
else: if isLightOn: lightOff
</code></pre>
| 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 = sess.getdatabase('','')
db.openmail
agent=db.getAgent("DeleteOldDocs")
doc=db.createdocument
doc.SendTo = recipients
doc.Subject = subject
doc.Body = "Test link http://www.thislink.com"
doc.HTMLBody = "<a href='http://www.thislink.com'>Link</a>"
doc.send(0)
</code></pre>
<p>how it possible to send a clickable link in an email message ?</p>
<p>and this is for example:</p>
<p><a href="http://i.stack.imgur.com/9sEXe.png" rel="nofollow">This email send by program, and as You can see the link is not clickable and must be copy first then paste to the browser. This is not convenient for the client</a></p>
| 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 would look like this then:</p>
<pre><code>sess=win32com.client.Dispatch("Notes.NotesSession")
db = sess.getdatabase('','')
stream = sess.CreateStream
sess.ConvertMIME = False
doc = db.CreateDocument
doc.Form = "Memo"
body = doc.CreateMIMEEntity()
header = body.CreateHeader("Subject")
header.SetHeaderVal(subject)
header = body.CreateHeader("To")
header.SetHeaderVal(recipients)
stream.writetext("<html><body>")
stream.writetext("Test link http://www.thislink.com <a href='http://www.thislink.com'>Link</a>")
stream.writetext("</body></html>")
body.SetContentFromText(stream, "text/HTML;charset=UTF-8", 1728)
doc.Send(0)
sess.ConvertMIME = True
</code></pre>
| 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 GreenCalculations(data):
data.reshape(1,-1,3)
data={tuple(item) for item in data[0]}
ColourCount=selection_data & set(data)
Return ColourCount
</code></pre>
<p>Now my current issue I think is that I'm only comparing the first top part of the picture, due to data[0]. Is it possible to loop through all the rows?</p>
<p>Note: tolist() takes lots of time.</p>
| 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]: data.reshape(1,-1,3)
</code></pre>
<p><code>data.shape=(1,-1,3)</code> would do that inplace. But why the initial <code>1</code>? </p>
<p>Instead:</p>
<pre><code>In [795]: aset={tuple(item) for item in data.reshape(-1,3)}
In [796]: aset
Out[796]:
{(3, 92, 60),
(5, 211, 227),
(6, 185, 183),
(9, 37, 0),
....
In [797]: len(aset)
Out[797]: 64
</code></pre>
<p>In my case a set of 64 unique items - not surprising given how I generated the values</p>
<p>Your do-nothing <code>data.reshape</code> line and <code>{tuple(item) for item in data[0]}</code> accounts for why it seem to be working on just the 1st row of the picture.</p>
<p>I'm guessing <code>selection_data</code> is similar 3 item tuples, such as:</p>
<pre><code>In [801]: selection_data = {tuple(data[1,3,:]), (1,2,3), tuple(data[5,5,:])}
In [802]: selection_data
Out[802]: {(1, 2, 3), (49, 132, 26), (76, 131, 16)}
In [803]: selection_data&aset
Out[803]: {(49, 132, 26), (76, 131, 16)}
</code></pre>
<p>You don't say where you attempt to use <code>tolist</code>, but I'm guessing in generating the set of tuples.</p>
<p>But curiously, <code>tolist</code> speeds up the conversion:</p>
<pre><code>In [808]: timeit {tuple(item) for item in data.reshape(-1,3).tolist()}
10000 loops, best of 3: 57.7 µs per loop
In [809]: timeit {tuple(item) for item in data.reshape(-1,3)}
1000 loops, best of 3: 239 µs per loop
In [815]: timeit data.reshape(-1,3).tolist()
100000 loops, best of 3: 19.8 µs per loop
In [817]: timeit {tuple(item.tolist()) for item in data.reshape(-1,3)}
10000 loops, best of 3: 100 µs per loop
</code></pre>
<p>So for doing this sort of list and set operation, we might as well jump to the list format right away.</p>
<p><code>numpy</code> has some set functions, for example <code>np.in1d</code>. That only operations on 1d arrays, but as has been demonstrated in some <code>unique row</code> questions, we can get around that by viewing the 2d array as a structured array. I had to fiddle around to get this far:</p>
<pre><code>In [880]: dt=np.dtype('uint8,uint8,uint8')
In [881]: data1=data.reshape(-1,3).view(dt).ravel()
In [882]: data1
Out[882]:
array([(41, 145, 254), (138, 144, 7), (192, 241, 203), (42, 177, 215),
(78, 132, 87), (221, 176, 87), (107, 171, 147), (231, 13, 53),
...
dtype=[('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1')])
</code></pre>
<p>Construct a selection with the same structured array nature:</p>
<pre><code>In [883]: selection=[data[1,3,:],[1,2,3],data[5,5,:]]
In [885]: selection=np.array(selection,np.uint8).view(dt)
In [886]: selection
Out[886]:
array([[(49, 132, 26)],
[(1, 2, 3)],
[(76, 131, 16)]],
dtype=[('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1')])
</code></pre>
<p>So the items in <code>selection</code> that are also found in <code>data1</code> are:</p>
<pre><code>In [888]: np.in1d(selection,data1)
Out[888]: array([ True, False, True], dtype=bool)
</code></pre>
<p>and the items in <code>data1</code> that are in selection are:</p>
<pre><code>In [890]: np.where(np.in1d(data1,selection))
Out[890]: (array([11, 45], dtype=int32),)
</code></pre>
<p>or in the unraveled shape</p>
<pre><code>In [891]: np.where(np.in1d(data1,selection).reshape(8,8))
Out[891]: (array([1, 5], dtype=int32), array([3, 5], dtype=int32))
</code></pre>
<p>the same (1,3) and (5,5) items I used to generate <code>selection</code>.</p>
<p>The <code>in1d</code> timings are competitive:</p>
<pre><code>In [892]: %%timeit
...: data1=data.reshape(-1,3).view(dt).ravel()
...: np.in1d(data1,selection)
...:
10000 loops, best of 3: 65.7 µs per loop
In [894]: timeit selection_data&{tuple(item) for item in data.reshape(-1,3).tolist()}
10000 loops, best of 3: 91.5 µs per loop
</code></pre>
| 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 GreenCalculations(data):
data.reshape(1,-1,3)
data={tuple(item) for item in data[0]}
ColourCount=selection_data & set(data)
Return ColourCount
</code></pre>
<p>Now my current issue I think is that I'm only comparing the first top part of the picture, due to data[0]. Is it possible to loop through all the rows?</p>
<p>Note: tolist() takes lots of time.</p>
| 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
ColourCount = npi.intersection(data.reshape(-1, 3), np.asarray(selection_data))
</code></pre>
<p>That is, it treats both the reshaped array as well as the set as sequences of length-3 ndarrays, of which it finds the intersection in a vectorized manner.</p>
| 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 doesn't want to redirect the user to the new, dynamic URL. I am passing this to the HTML with Jinja. </p>
<p>Here is what I have.</p>
<p>The user starts on the home page, that is defined like this</p>
<pre><code>@app.route("/home/", methods=["GET", "POST"])
def start():
return render_template("dashboard.html")
</code></pre>
<p>Dashboard.html has a text box and submission button (below). As you can see, the <code>action</code> of this button is to redirect to <code>{{ results_page }}</code>, where "results_page" comes from my Python function <code>load_results</code> (also below) and is passed to the HTML with <code>render_template</code>. </p>
<pre><code><div>
<form action="{{ results_page }}" class="form-inline" method="post">
<div class="form-group">
<label for="PubmedID">Pubmed ID(s)</label>
<input type="text" class="form-control" id="PubmedID" placeholder="18952863, 18269575" name="pmid" value="{{request.form.pmid}}">
</div>
<button type="submit" id= "myButton" class="btn btn-default" data-toggle="modal" data-target="#myModal">Submit</button>
</form>
</div>
</code></pre>
<p>The results page of my app uses the user input to look up some information and display it. </p>
<pre><code>@app.route('/results/<query>', methods=["GET", "POST"])
def load_results(query):
form = pmidForm(secret_key='super secret key')
try:
if request.method == 'POST':
query = form.pmid.data #This is the user input
results_page = "website.com/results/"+query
return(query)
#do lots of stuff using the query
return render_template('results.html', form=form, results_page = results_page)
except Exception as e:
return(str(e))
</code></pre>
<p>If I run my app like this, the home page is fine, but when I click "Submit", the app doesn't take in the user input or do anything with it. Simply the <code>home</code> page refreshes. </p>
<p>I am new to web development, but since this code works fine if I hardcode the button to <code>action = "website.com/results"</code> in the HTML, AND do without the <code><query></code> in <code>/results/<query></code> for the results page, I think that only a few adjustments should be needed to make my app dynamically redirect to and load pages correctly. Right now, I'm not sure what I'm missing. Please let me know where I'm going stray. </p>
<p>EDIT - </p>
<p>Now I have implemented a <code>handle_form</code> function that redirects to my dynamic URL. This function properly redirects but then I get a 404 error.</p>
<pre><code>@app.route('/form/', methods=["POST"]) #handles form submission
def handle_form():
form = pmidForm(secret_key='super secret key')
if request.method == "POST":
query = request.form['pmid']
return redirect('/results/'+query)
</code></pre>
<p>I have also edited my form in the HTML <code>action</code> to go to <code>/form/</code></p>
<pre><code><form action="website.com/form/" class="form-inline" method="post">
<div class="form-group">
<label for="PubmedID">Pubmed ID(s)</label>
<input type="text" class="form-control" id="PubmedID" placeholder="18952863, 18269575" name="pmid" value="{{request.form.pmid}}">
</div>
<button type="submit" id= "myButton" class="btn btn-default" data-toggle="modal" data-target="#myModal">Submit</button>
</form>
</code></pre>
<p>With this, my site will properly redirect to <code>/results/<query></code>/ (e.g. /results/1234) but I get a 404 error. Here is how I have changed my <code>load_results</code></p>
<pre><code>@app.route('/results/<query>', methods=["GET"])
def load_results(query):
form = pmidForm(secret_key='super secret key')
try:
if request.method == 'GET':
query = form.pmid.data #THIS IS THE USER INPUT FROM THE FORM #referencing 'class pmidForm'
return query
.
.
#do stuff
</code></pre>
<p>I think I am very close but need to figure out why I am getting a 404 error. My guess is that I am using "GET" incorrectly. My form in the HTML uses <code>method="post"</code>. Since this does not match with "GET", is there no way for my <code>load_results(query)</code> function to retrieve the contents of the form?</p>
<p>EDIT 2 - </p>
<p>Changed <code>handle_form</code> to redirect with <code>url_for</code>:</p>
<pre><code>@app.route('/form/', methods=["POST"]) #handles form submission
def handle_form():
form = pmidForm(secret_key='super secret key')
if request.method == "POST":
query = request.form['pmid']
return redirect(url_for('.load_results', query=query))
</code></pre>
<p>And changed <code>load_results</code> to not return "query"</p>
<pre><code>@app.route('/results/<query>', methods=["GET"])
def load_results(query):
form = pmidForm(secret_key='super secret key')
try:
if request.method == 'GET':
query = form.pmid.data # This shouldn't work??
.
.
# do stuff with the variable "query"
</code></pre>
<p>With this, it's still returning the 404 Error as before. Should I not be using <code>if request.method == GET</code> ? </p>
<p>Edit 3 - </p>
<p>Even a very simplified <code>load_results</code> will give me the 404 error, so I'm not sure what's up.</p>
<pre><code>@app.route('/results/<query>', methods=["GET", "POST"])
def load_results(query):
q = query
return render_template('test.html', q=q)
</code></pre>
<p>EDIT - 3</p>
<p>It seems that the accepted solution IS the correct solution to this problem, however there is an issue with uwsgi in my server that is re-directing it to the wrong location :( </p>
| 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 original endpoint on the form submission.</p>
<p>Your larger problem is that your appraoch isn't going to get you a dynamic results url that looks like /results/1234. </p>
<p>Typical approaches are to redirect on the server side when you handle the post request; or to use JavaScript in the client to get the form data and change the browser location to /results/1234.</p>
<p>A simplified version of how to handle this with a server side redirect might look something like this. One route that handles the form submission and another that displays results. You simply redirect from one to the other to get the nice url.</p>
<pre><code>@app.route('/form', methods=["POST"])
def handle_form():
query = form.pmid.data #This is the user input
return redirect(url_for('.load_results', query=query))
@app.route('/results/<query>') *removed the method spec to handle the redirect?
def load_results(query):
.
.
# do something with query
</code></pre>
| 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 not modules? </p>
| 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 same name on the other side would seem simple, but if you're actually trying to pickle the module itself, the worry would be that you want to pickle module state as well. It's even more confusing if the module is a C extension module, where module state may not even be exposed to Python itself, only used internally at the C layer.</p>
<p>Given that usually you want specific things from a module, not the whole module (which is usually not referenced as state, just imported at the top level), the benefits of supporting pickling for modules are limited, and the semantics are unclear, they haven't bothered to implement it.</p>
| 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 <code>[...]</code> creates the list of the lengths of sub sequences of ones, i.e. <code>[1,8,2]</code>, and <code>mean</code> computes the average value.</p>
| 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
difs = np.diff(bounded)
run_starts, = np.where(difs > 0)
run_ends, = np.where(difs < 0)
return run_ends - run_starts
>>> a=np.array([1,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,1,1,0,])
>>> b=runs_of_ones_array(a)
>>> float(sum(b))/len(b)
3.66666666667
</code></pre>
| 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(self):
pass
class MyClass(MyABC):
pass
MyClass()
</code></pre>
<p>This gives "TypeError: Can't instantiate abstract class MyClass with abstract methods my_abstract_method". Great, makes sense. Just create a method with that name.</p>
<pre><code>class MyClass(MyABC):
def my_abstract_method(self):
pass
MyClass()
</code></pre>
<p>Boom. You're done. But what about this case?</p>
<pre><code>from abc import ABCMeta, abstractmethod
class MyABC(metaclass=ABCMeta):
@property
@abstractmethod
def my_attribute(self):
pass
class MyClass(MyABC):
def my_attribute(self):
pass
MyClass()
</code></pre>
<p>The MyClass() call works even though my_attribute is not a property. I guess in the end all ABCs do is ensure that a method with a given name exists. Thats it. If you want more from it, you have to look at MyABC's source code and read the documentation. The decorators and comments there will inform you of how you need to construct your sub-class.</p>
<p>Do I have it right or am I missing something here?</p>
| 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 anything in particular; it just makes sure they are there. This "works" without errors:</p>
<pre><code>class MyABC(metaclass=ABCMeta):
@abstractmethod
def my_abstract_method(self):
pass
class MyClass(MyABC):
my_abstract_method = 2
MyClass()
</code></pre>
<p>That is, ABCMeta doesn't even ensure that the abstract method as provided on the subclass is a method at all. There just has to be an attribute of some kind with that name,</p>
<p>You could certainly write your own metaclass that does more sophisticated checking to ensure that certain attributes have certain kinds of values, but that's beyond the scope of ABCMeta.</p>
| 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 Unauthorized
< Server: nginx/1.10.0 (Ubuntu)
Server: nginx/1.10.0 (Ubuntu)
< Date: Tue, 09 Aug 2016 01:39:03 GMT
Date: Tue, 09 Aug 2016 01:39:03 GMT
< Content-Type: application/json
Content-Type: application/json
< Content-Length: 42
Content-Length: 42
< Connection: keep-alive
Connection: keep-alive
<
* Connection #0 to host api.somedomain.com left intact
{"status": "error", "msg": "unauthorized"}
</code></pre>
<p>Am i missing something here. This is not a jsonp request. The server sets the:
Access-Control-Allow-Origin appropriately during the preflight OPTIONS request before this GET request in question. The parent domain is the same, only the subdomains are different.</p>
<p>The backend is using python 3 with Bottle </p>
<p>The statusCode with the 401 callback does not get triggered and the error callback gets triggered but the status code is set to 0, also the complete callback reports status code of 0. The other questions do not solve my issue.</p>
| 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 output. </p>
<p>I have tried using a stack like structure like you would do if it was just parentheses but haven't been able to figure out something that works. I'd prefer a solution in python but any guidance anyone can offer will help regardless of language. The efficiency should ideally be better than n^2 since I can think of an O(n^2) solution using this <a href="http://stackoverflow.com/questions/2509358/how-to-find-validity-of-a-string-of-parentheses-curly-brackets-and-square-brack">How to find validity of a string of parentheses, curly brackets and square brackets?</a> and just trying it on different substrings</p>
| 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 finite depth, Regex could be your friend (you may want to check performance)</p>
<p>it seems that you're looking for:</p>
<ul>
<li>literal square-bracket</li>
<li>a bunch of chars that aren't end bracket</li>
<li>close bracket</li>
<li>open brace</li>
<li>all chars up to the last close brace </li>
<li>close brace</li>
</ul>
<p>so, language-agnostic something like:</p>
<pre><code>\[[^]]*\{.*\}
</code></pre>
<p>this could be used with re.compile with Python, but really it could be any language. Since .* (any char) and [^]] (not-end square brace) are assumed, you can use w+ or d+ for word/digit or other Regex short-hand to refine the solution and speed things up. </p>
| 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 output. </p>
<p>I have tried using a stack like structure like you would do if it was just parentheses but haven't been able to figure out something that works. I'd prefer a solution in python but any guidance anyone can offer will help regardless of language. The efficiency should ideally be better than n^2 since I can think of an O(n^2) solution using this <a href="http://stackoverflow.com/questions/2509358/how-to-find-validity-of-a-string-of-parentheses-curly-brackets-and-square-brack">How to find validity of a string of parentheses, curly brackets and square brackets?</a> and just trying it on different substrings</p>
| 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>()</code>, <code>[]</code>, or <code>{}</code>. I've given each seed a numerical value to assist the reader in visualizing the seeds.</p>
<pre><code>()(({}[]([{[()]}]{})))(
11 2233 44 55
</code></pre>
<p>Step 2 is to <strong>expand</strong> the seeds into sequences. A sequences is a nested set of symbols: e.g. <code>[{[()]}]</code>. So starting from a seed, work outwards, verifying that the enclosing symbols are matched. The search ends at a mismatch, or at the beginning or end of the string. In the example, only seed 4 is enclosing by matching symbols, so only seed 4 is expanded.</p>
<pre><code>()(({}[]([{[()]}]{})))(
11 2233 4444444455
</code></pre>
<p>Step 3 is to <strong>combine</strong> adjacent sequences. Note that there can be two or more adjacent sequences, but in the example there are two adjacent sequences in two places</p>
<pre><code>()(({}[]([{[()]}]{})))(
11 2222 4444444444
</code></pre>
<p>Repeat step 2, treating the combined sequences as seeds. In this example, sequence 4 is enclosed by matching parentheses, so sequence 4 is expanded.</p>
<pre><code>()(({}[]([{[()]}]{})))(
11 2222444444444444
</code></pre>
<p>Repeat step 3, combine sequences</p>
<pre><code>()(({}[]([{[()]}]{})))(
11 2222222222222222
</code></pre>
<p>Repeat step 2, expand</p>
<pre><code>()(({}[]([{[()]}]{})))(
1122222222222222222222
</code></pre>
<p>And combine one more time</p>
<pre><code>()(({}[]([{[()]}]{})))(
1111111111111111111111
</code></pre>
<p>The algorithm ends when there's nothing left to expand, or combine. The longest sequence is the answer.</p>
<hr>
<p>Implementation notes:</p>
<p>I think that you can achieve <code>O(n)</code> by expanding/merging one sequence at a time. I would keep the list of sequences in a doubly-linked list (so removal is an <code>O(1)</code> operation). Each sequence would be represented by a <code>start</code> index, and an <code>end</code> index. </p>
<p>Expanding a sequence involves checking the symbols at <code>array[start-1]</code> and <code>array[end+1]</code>, and then updating the <code>start</code>/<code>end</code> indexes as appropriate. </p>
<p>Merging involves checking the next and previous sequences in the linked list. If the sequences can be merged, then one sequence is updated to cover the full range, and the other is deleted. </p>
<p>Once an sequence is expanded/merged as much as possible, move to the next sequence in the list. As this new sequence is expanded/merged, it may eventually work its way back to the previous sequence. Hence, after initially creating a doubly-linked list of seeds, one pass through the linked list should be sufficient to expand/merge all of the sequences. Then a second pass through whatever remains of the linked list is needed to find the longest sequence.</p>
| 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 output. </p>
<p>I have tried using a stack like structure like you would do if it was just parentheses but haven't been able to figure out something that works. I'd prefer a solution in python but any guidance anyone can offer will help regardless of language. The efficiency should ideally be better than n^2 since I can think of an O(n^2) solution using this <a href="http://stackoverflow.com/questions/2509358/how-to-find-validity-of-a-string-of-parentheses-curly-brackets-and-square-brack">How to find validity of a string of parentheses, curly brackets and square brackets?</a> and just trying it on different substrings</p>
| 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 that are matching open/close brackets. Then add the longest match to the left of that too, if any.</p>
<p>Here's some Python code that computes this:</p>
<pre><code>def longest_valid(s):
match = [0] * (len(s) + 1)
for i in xrange(1, len(s)):
if s[i] in '({[':
continue
open = '({['[')}]'.index(s[i])]
start = i - 1 - match[i - 1]
if start < 0: continue
if s[start] != open: continue
match[i] = i - start + 1 + match[start - 1]
best = max(match)
end = match.index(best)
return s[end + 1 - best:end + 1]
print longest_valid("()(({}[](][{[()]}]{})))(")
print longest_valid("()(({}[]([{[()]}]{})))(")
print longest_valid("{}[()()()()()()()]")
</code></pre>
<p>It's O(n) in time and space.</p>
| 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 = re.compile(query, re.IGNORECASE)
self.dir = dir
self.__horizon = set()
self.log = []
self.__horizon.add(url)
self.log.append(url)
print("initializing crawler....")
print(locals())
def start(self, depth= 5, url = '/'):
print(url, depth)
self.log.append(url)
if depth > 0:
pool = urllib3.PoolManager()
data = pool.request("GET", self.start_url if url == '/' else url).data.decode('utf-8')
valid_list = []
self.add_horizon(parser_soup.get_links(data), valid_list)
if re.search(self.query, parser_soup.get_text(data)):
self.output(data)
for u in valid_list:
self.start(depth = (depth-1), url = u)
def output(self, data):
with open(os.path.join(self.dir, get_top_domain(self.start_parsed.host) + '.' + str(time.time()) + '.html'), 'w+') as f:
f.write(data)
def add_horizon(self, url_list, valid_list = []):
for url in url_list:
if get_top_domain(url) == get_top_domain(self.start_parsed.host) \
and (not str(url) in self.log or not str(url) in self.__horizon):
valid_list.append(str(url))
self.__horizon.update(valid_list)
</code></pre>
<p>It runs forever. How should I ensure that I eliminate duplicate links?</p>
| 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 self.visited[url]:
return True
self.visited[url] = True
# Rest of code...
</code></pre>
<p>To be honest though, I can't see the infinite loop either. It would help if you posted some output.</p>
<p>EDIT: Note that in above answer I wrote that using a <code>defaultdict</code> is the wrong solution. I meant to say that using a <em>list</em> is the wrong solution!</p>
<p>EDIT 2: @Jona Christopher Sahnwald made a point more valid than mine (see his comment under the OP's question). It might be more productive to add a <code>max_visit</code> and <code>current_visit</code> property in your class (set to like 1000 or so). Start with <code>current_visit</code> at 0, and every time you visit a site, increment <code>current_visit</code>. When <code>current_visit</code> is greater than <code>max_visit</code>, abort the crawl. Note that instead of using recursion to recurse over visited web sites, it might be better to implement some kind of stack so you can pause/resume the crawl rather than aborting. Like so:</p>
<pre><code>from collections import defaultdict
class Crawler:
def __init__(self, url, query, dir = os.path.dirname(__file__)):
self.visited = defaultdict(bool)
self.current_visit = 0
self.max_visit = 1000
self.to_visit = []
# Rest of code...
def start(self, depth=5, url = '/'):
self.to_visit.append((url, 1))
while len(self.to_visit) > 0:
url, current_depth = self.to_visit.pop()
if current_depth > depth:
continue
elif visited[url]:
continue
elif self.current_visited > self.max_visited:
break
self.current_visited += 1
visited[url] = True
# Code that does something for each page (like download it, etc)
# Code that finds links on page...
for link in links_on_page:
self.to_visit.append((link, current_depth + 1))
</code></pre>
<p>That way, you can pause the crawl once <code>current_visit</code> exceeds <code>max_visit</code>, allowing you to crawl in batches of <code>max_visit</code>.</p>
| 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 = re.compile(query, re.IGNORECASE)
self.dir = dir
self.__horizon = set()
self.log = []
self.__horizon.add(url)
self.log.append(url)
print("initializing crawler....")
print(locals())
def start(self, depth= 5, url = '/'):
print(url, depth)
self.log.append(url)
if depth > 0:
pool = urllib3.PoolManager()
data = pool.request("GET", self.start_url if url == '/' else url).data.decode('utf-8')
valid_list = []
self.add_horizon(parser_soup.get_links(data), valid_list)
if re.search(self.query, parser_soup.get_text(data)):
self.output(data)
for u in valid_list:
self.start(depth = (depth-1), url = u)
def output(self, data):
with open(os.path.join(self.dir, get_top_domain(self.start_parsed.host) + '.' + str(time.time()) + '.html'), 'w+') as f:
f.write(data)
def add_horizon(self, url_list, valid_list = []):
for url in url_list:
if get_top_domain(url) == get_top_domain(self.start_parsed.host) \
and (not str(url) in self.log or not str(url) in self.__horizon):
valid_list.append(str(url))
self.__horizon.update(valid_list)
</code></pre>
<p>It runs forever. How should I ensure that I eliminate duplicate links?</p>
| 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)
</code></pre>
<p><code>defaultdict</code> is a dictionary that has a default which is used if the index doesn't exist. This however, is the wrong solution. A set would be more memory efficient and elegant, as shown in my code.</p>
<p>A set uses O(1) time - just as fast as @Giorgian's answer.</p>
<p>Use <code>Ctrl-C</code> to interrupt your program when it's in an infinite loop. This will print a Traceback showing the command that was being executed when the program was interrupted. Do this a few times and you should get a good idea of where it happens. Alternatively, use a debugger and pause when it's in the infinite loop and use the "step" feature to run to the next line of execution so you can follow the program's execution. PyCharm is a great editor that includes a debugger. It has good autocompletion and is just good all-around. It's free, check it out.</p>
| 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 2012-10-02 09:02:13
5 2012-10-02 09:02:13
6 2012-10-09 11:00:36
7 2012-10-09 11:00:36
</code></pre>
<p>Some 'Second's are integer and some are float numbers, so both following methods would fail:</p>
<pre class="lang-python prettyprint-override"><code>import datetime as dt
#Method 1: consider the float
data_test['DataTime'] = data_test['DataTime'].apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f'))
#Method 2: ignore the float
data_test['DataTime'] = data_test['DataTime'].apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%d %H:%M:%S'))
</code></pre>
<p>Is there any simple methods I could convert this column into DateTime?</p>
| 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 2012-10-02 15:02:42.843000000
4 2012-10-02 09:02:13
5 2012-10-02 09:02:13
6 2012-10-09 11:00:36
7 2012-10-09 11:00:36
In [223]: df.dtypes
Out[223]:
DataTime object
dtype: object
In [224]: df.DataTime = pd.to_datetime(df.DataTime)
In [225]: df
Out[225]:
DataTime
0 2012-10-03 12:14:18.257
1 2012-10-01 08:39:54.633
2 2012-10-05 07:50:14.203
3 2012-10-02 15:02:42.843
4 2012-10-02 09:02:13.000
5 2012-10-02 09:02:13.000
6 2012-10-09 11:00:36.000
7 2012-10-09 11:00:36.000
In [226]: df.dtypes
Out[226]:
DataTime datetime64[ns]
dtype: object
</code></pre>
| 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 section A, B or C. Because then I can easily use form class to render a form to a HTML page without any coding. I know I can use a charfield to save A, B or C but is there a way to do what I want ? </p>
| -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 (e.g., a list or tuple) consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for this field. If this is given, the default form widget will be a select box with these choices instead of the standard text field.</p>
</blockquote>
<p>So you could use it like this in your model class:</p>
<pre><code>class myClass(models.Model):
AVAILABLE_CHOICES = (
('a', 'Section A'),
('b', 'Section B'),
('c', 'Section C'),
)
section = models.CharField(max_length=10, choices=AVAILABLE_CHOICES, default='a')
...
</code></pre>
<blockquote>
<p>The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name.</p>
</blockquote>
| 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.FileSystemLoader(template_dir), autoescape = True)
class News(db.Model):
title = db.StringProperty(required=True)
description = db.StringProperty(required=True)
url = db.StringProperty(required=True)
imageurl = db.StringProperty(required=True)
feeds = [ 'https://news.google.co.in/news/section?cf=all&pz=1&ned=in&topic=e&ict=ln&output=rss' # Entertainment
'https://news.google.co.in/news/section?cf=all&pz=1&ned=in&topic=snc&ict=ln&output=rss' # Science
'https://news.google.co.in/news/section?cf=all&pz=1&ned=in&topic=s&ict=ln&output=rss' # Sports
'https://news.google.co.in/news/section?cf=all&pz=1&ned=in&topic=b&ict=ln&output=rss' # Business
'https://news.google.co.in/news/section?cf=all&pz=1&ned=in&topic=tc&ict=ln&output=rss' # Technology
]
def render_str(template, **params):
t = jinja_env.get_template(template)
return t.render(params)
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.write(feedparser.__file__)
self.response.write(render_str('mainpage.html'))
class Entertainment(webapp2.RequestHandler):
def get(self):
rssfeed = feedparser.parse(feeds[0])
self.response.write(rsfeed.entries[0].title)
self.response.write(rsfeed.entries[0].link)
self.response.write(rsfeed.entries[0].published)
self.response.write(rsfeed.entries[0].description)
app = webapp2.WSGIApplication([('/', MainPage),
('/entertainment', Entertainment)
], debug = True)
</code></pre>
<p><code>mainpage.html</code> has nothing except five <code><p></p></code> tags with one of them hyperlinked to <code>/entertainment</code>.</p>
<p>When I run it and click on the hyperlinked paragraph, I get this</p>
<p><code>AttributeError: 'module' object has no attribute 'parse'</code></p>
<p>I've followed <a href="http://stackoverflow.com/questions/11171073/feedparser-py-in-root-directory-but-still-not-working-on-dev-server">this question</a>, which is why I printed out the filepath in the <code>get</code> of <code>MainPage</code>. </p>
<p>My folder structure is :</p>
<ul>
<li><p>templates</p>
<ul>
<li>mainpage.html</li>
</ul></li>
<li><p>app.yaml</p></li>
<li><p>feedparser.py</p></li>
<li><p>newsapp.py</p></li>
<li><p>newsapp.pyc</p></li>
</ul>
<p>When I ran it the first time, feedparser pointed to <code>C:\Users\IBM_ADMIN\Downloads\7c\News Aggregator GAE\feedparser.pyc</code>. That was wrong, so I deleted the <code>.pyc</code> file, and then it pointed to <code>C:\Users\IBM_ADMIN\Downloads\7c\News Aggregator GAE\feedparser.py</code>. But it still gave the same error and the <code>.pyc</code> file got generated again. I know it gets generated because I'm compiling the feedparser file, but why does the feedparser module point to that location? And how can I get around that error?</p>
| 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>
<p>The local development server will properly set the execution environment to not accidentally reach modules outside your application. It should address your import issue.</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:
dash = digit + "-"
else:
dash += digit
if int(digit) % 2 != 0:
dash += "-" + digit + "-"
else:
dash += digit
if int(num[-1]) % 2 != 0:
dash += "-" + digit
else:
dash += digit
print(dash)
</code></pre>
<p>It is printing "3--3--3"</p>
<p>If someone could tell me where I'm going wrong, it would be much appreciated!</p>
| 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] + "-"
elif i == len(num) - 1 and int(num[i]) % 2 != 0:
string = string + "-" + num[i]
elif int(num[i]) % 2 !=0:
string = string + "-" + num[i] + "-"
elif int(num[i]) % 2 == 0:
string = string + num[i]
print string
</code></pre>
| 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:
dash = digit + "-"
else:
dash += digit
if int(digit) % 2 != 0:
dash += "-" + digit + "-"
else:
dash += digit
if int(num[-1]) % 2 != 0:
dash += "-" + digit
else:
dash += digit
print(dash)
</code></pre>
<p>It is printing "3--3--3"</p>
<p>If someone could tell me where I'm going wrong, it would be much appreciated!</p>
| 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 and a preceding - on the end number as per example. Using splicing, I remove these in the revision and no longer yield 0th and last elements unaltered:</p>
<pre><code>def dash(num):
""" add surrounding -'s to any digit in num which is odd """
for n in num:
if int(n) % 2 != 0:
n = "-%s-" % n
yield n
def remove_bookends(_str):
""" if - is at the start or end of _str, remove it """
if _str[0] is "-":
_str = _str[1:]
if _str[-1] is "-":
_str = _str[:-1]
return _str
if __name__ == '__main__':
num = "32343"
_str = "".join([n for n in dash(num)])
_str = remove_bookends(_str)
print _str
</code></pre>
| 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></pre>
<p>raises a syntax error exception. Both point to the closed parenthesis.</p>
<p>Removing the trailing comma, everything is quiet.
I am scratching my head on <a href="https://docs.python.org/3/reference/compound_stmts.html#function-definitions" rel="nofollow">https://docs.python.org/3/reference/compound_stmts.html#function-definitions</a> but it is somehow beyond me (and possibly also wrong... at least, in my browser's rendering I can't pair the last closing parenthesis in the <code>parameter_list</code> definition).
Am I doing something wrong?
I am the</p>
<pre class="lang-py prettyprint-override"><code>def f(*,
a: "doc A" = 1,
b: "doc B" = 2,
c: "doc C" = 3,
d: "doc D" = 4,
# ... and maybe more,
)
</code></pre>
<p>type of person, and this issue kind-of annoys me (maybe that is the wrong part, and I should become the <code>, a: "doc A" = 1</code> type of person - but it looks weird to me).</p>
<p>Using python as distributed in Gentoo ebuilds dev-lang/python 2.7.12 and 3.5.2 (from <a href="http://www.python.org" rel="nofollow">http://www.python.org</a>).</p>
| 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 isn't, so it raises a syntax error.</p>
<p>Trailing commas in lists, on the other hand, are fine. </p>
<pre><code>list1 = [ 0, 1, 2, 3, ]
>> totally fine
</code></pre>
| -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()
datetime.datetime(2016, 8, 9, 4, 33, 28, 504000)
</code></pre>
<p>This is not a duplicate of</p>
<p><a href="https://stackoverflow.com/questions/6677332/using-f-with-strftime-in-python-to-get-microseconds">Using %f with strftime() in Python to get microseconds</a></p>
<p>as this approach gives me the same zeroes at the end.</p>
| 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, 9, 10, 51, 1, 561000)
>>> datetime.datetime.now()
datetime.datetime(2016, 8, 9, 10, 51, 2, 314000)
>>> datetime.datetime.now()
datetime.datetime(2016, 8, 9, 10, 51, 2, 906000)
>>> datetime.datetime.now()
datetime.datetime(2016, 8, 9, 10, 51, 9, 277000)
</code></pre>
<p>See, for example, <a href="http://www.expobrain.net/2013/07/12/timestamp-and-microseconds-on-windows-platforms/" rel="nofollow">here</a> and <a href="http://stackoverflow.com/questions/16507924/bad-microsecond-resolution-in-python">here</a>.</p>
<p>In the Python 2.7 source code, the function <code>Modules/datetimemodule.c/datetime_now()</code> eventually calls <code>Modules/timemodule.c/floattime()</code>, which has the following comment:</p>
<pre class="lang-c prettyprint-override"><code>/* There are three ways to get the time:
(1) gettimeofday() -- resolution in microseconds
(2) ftime() -- resolution in milliseconds
(3) time() -- resolution in seconds
In all cases the return value is a float in seconds.
Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
fail, so we fall back on ftime() or time().
Note: clock resolution does not imply clock accuracy! */
</code></pre>
<p>So the Windows platform is obviously using <code>ftime()</code> to get the current time and, as per <a href="https://msdn.microsoft.com/en-us/library/z54t9z5f.aspx" rel="nofollow">the MSDN page for <code>_ftime()</code></a> (which it no doubt ends up in), no microseconds are available. Therefore Python 2.7 just gives you the milliseconds and leaves the microseconds as zero:</p>
<pre><code>return (double)t.time + (double)t.millitm * (double)0.001;
</code></pre>
<p>Python 3.5 appears to have a full microsecond resolution so you may want to consider switching to that (as if the large number of <em>other</em> improvements weren't enough).</p>
| 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 map, being closer to each other at the areas of high intensities (<strong>but without overlap!</strong>).</p>
<p>My first try was "weighted" k-means. As I didn't find a working implementation of weighted k-means, the way I introduce the weights consists of repeating the points with high intensities. Here is my code:</p>
<pre><code>import numpy as np
from sklearn.cluster import KMeans
def accumulation_points_finder(x, y, data, n_points, method, cut_value):
#computing the rms
rms = estimate_rms(data)
#structuring the data
X,Y = np.meshgrid(x, y, sparse=False)
if cut_value > 0.:
mask = data > cut_value
#applying the mask
X = X[mask]; Y = Y[mask]; data = data[mask]
_data = np.array([X, Y, data])
else:
X = X.ravel(); Y = Y.ravel(); data = data.ravel()
_data = np.array([X, Y, data])
if method=='weighted_kmeans':
res = []
for i in range(len(data)):
w = int(ceil(data[i]/rms))
res.extend([[X[i],Y[i]]]*w)
res = np.asarray(res)
#kmeans object instantiation
kmeans = KMeans(init='k-means++', n_clusters=n_points, n_init=25, n_jobs=2)
#performing kmeans clustering
kmeans.fit(res)
#returning just (x,y) positions
return kmeans.cluster_centers_
</code></pre>
<p>Here are two different results: 1) Making use of all the data pixels. 2) Making use of only pixels above some threshold (RMS).</p>
<p><a href="http://i.stack.imgur.com/YBMnw.png" rel="nofollow"><img src="http://i.stack.imgur.com/YBMnw.png" alt="Without threshold"></a></p>
<p><a href="http://i.stack.imgur.com/6FVLsl.png" rel="nofollow"><img src="http://i.stack.imgur.com/6FVLsl.png" alt="With threshold"></a></p>
<p>As you can see the points seems to be more regularly spaced than concentrated at areas of high intensities. </p>
<p>So my <strong>question</strong> is if there exist a (deterministic if possible) better method for computing such accumulation points. </p>
| 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 will be more subdivisions in areas with rapidly changing values, fewer in the background areas.</p>
| 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=follow_to),
'selfieList':Selfie.objects.filter(selfie_user=follow_to),})
</code></pre>
<p><strong>template</strong></p>
<pre><code>{% for f in following %}
<a href="{% url 'followed' f.follow_to %}">{{f.follow_to}}</a> <br>
{% endfor %}
</code></pre>
<p><strong>urls.py</strong></p>
<pre><code>url(r'^followed/(?P<follow_to>[-\w]+)/$', followed, name='followed'),
</code></pre>
<p><strong>models.py</strong></p>
<pre><code>class Following(models.Model):
follow_from = models.ForeignKey("auth.User",related_name='from_person')
follow_to = models.ForeignKey("auth.User", related_name='to_person')
date_follow = models.DateTimeField(auto_now=True)
def __unicode__(self):
return unicode(self.follow_from)
def __str__(self):
</code></pre>
| 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 for <code>id</code> of an object. <code>id</code> is integer. </p>
<p>So in the query its trying to convert <code>'n'</code> into <code>int</code> to search appropriate object. But the conversion fails.</p>
<p>You need to either check for that and/or use <code>id</code> related regex in url for <code>follow_to</code> parameter.</p>
| 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=follow_to),
'selfieList':Selfie.objects.filter(selfie_user=follow_to),})
</code></pre>
<p><strong>template</strong></p>
<pre><code>{% for f in following %}
<a href="{% url 'followed' f.follow_to %}">{{f.follow_to}}</a> <br>
{% endfor %}
</code></pre>
<p><strong>urls.py</strong></p>
<pre><code>url(r'^followed/(?P<follow_to>[-\w]+)/$', followed, name='followed'),
</code></pre>
<p><strong>models.py</strong></p>
<pre><code>class Following(models.Model):
follow_from = models.ForeignKey("auth.User",related_name='from_person')
follow_to = models.ForeignKey("auth.User", related_name='to_person')
date_follow = models.DateTimeField(auto_now=True)
def __unicode__(self):
return unicode(self.follow_from)
def __str__(self):
</code></pre>
| 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(r'^followed/(?P<follow_to>\d+)/$', followed, name='followed'),
</code></pre>
| 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 reimplementing run(). I put the following in a file called timertester.py:</p>
<pre><code>import PySide
import time
class SubClassThread(PySide.QtCore.QThread):
def run(self):
print('called SubClassThread.run()')
self.delayed_print()
def delayed_print(self):
print('called SubClassThread.delayed_print()')
PySide.QtCore.QTimer.singleShot(1000, self.print_things)
time.sleep(2)
print('end of delayed_print()')
def print_things(self):
print('called print_things')
</code></pre>
<p>The code I am using to test this (call it <code>test.py</code>):</p>
<pre><code>import sys
import time
import PySide
from timertester import SubClassThread
print('Test: QThread subclassing')
app = PySide.QtCore.QCoreApplication([])
sct = SubClassThread()
sct.finished.connect(app.exit)
sct.start()
sys.exit(app.exec_())
</code></pre>
<p>The output of <code>python test.py</code>:</p>
<pre><code>Test: QThread subclassing
called SubClassThread.run()
called SubClassThread.delayed_print()
end of delayed_print()
</code></pre>
<p>The curious part is that the callable passed to QTimer.singleShot never seems to get called (there is no <code>called print_things()</code> in the output!) I would greatly appreciate any clarity that you can shed on this. I feel that I am missing some simple ingredient of the Qt framework. Please bear with me- I did spend some hours searching for answers to this.</p>
| 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> does not start an event-loop, so the timer will do nothing.</p>
| 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 reimplementing run(). I put the following in a file called timertester.py:</p>
<pre><code>import PySide
import time
class SubClassThread(PySide.QtCore.QThread):
def run(self):
print('called SubClassThread.run()')
self.delayed_print()
def delayed_print(self):
print('called SubClassThread.delayed_print()')
PySide.QtCore.QTimer.singleShot(1000, self.print_things)
time.sleep(2)
print('end of delayed_print()')
def print_things(self):
print('called print_things')
</code></pre>
<p>The code I am using to test this (call it <code>test.py</code>):</p>
<pre><code>import sys
import time
import PySide
from timertester import SubClassThread
print('Test: QThread subclassing')
app = PySide.QtCore.QCoreApplication([])
sct = SubClassThread()
sct.finished.connect(app.exit)
sct.start()
sys.exit(app.exec_())
</code></pre>
<p>The output of <code>python test.py</code>:</p>
<pre><code>Test: QThread subclassing
called SubClassThread.run()
called SubClassThread.delayed_print()
end of delayed_print()
</code></pre>
<p>The curious part is that the callable passed to QTimer.singleShot never seems to get called (there is no <code>called print_things()</code> in the output!) I would greatly appreciate any clarity that you can shed on this. I feel that I am missing some simple ingredient of the Qt framework. Please bear with me- I did spend some hours searching for answers to this.</p>
| 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>:</p>
<pre><code>import PySide
class SubClassThread(PySide.QtCore.QThread):
def __init__(self,parent=None):
print('called SubClassThread.__init__()')
super(SubClassThread,self).__init__(parent)
def run(self):
print('called SubClassThread.run()')
self.delayed_print()
self.exec_()
def delayed_print(self):
print('called SubClassThread.delayed_print()')
PySide.QtCore.QTimer.singleShot(1000, self.print_things)
print('end of delayed_print()')
def print_things(self):
print('called print_things')
self.quit()
</code></pre>
<p>Application, <code>test.py</code>:</p>
<pre><code>import sys
import PySide
from timertester import SubClassThread
print('Test: QThread subclassing')
# instantiate a QApplication
app = PySide.QtCore.QCoreApplication([])
# instantiate a thread
sct = SubClassThread()
# when the thread finishes, make sure the app quits too
sct.finished.connect(app.quit)
# start the thread
# it will do nothing until the app's event loop starts
sct.start()
# app.exec_() starts the app's event loop.
# app will then wait for signals from QObjects.
status=app.exec_()
# print status code and exit gracefully
print('app finished with exit code {}'.format(status))
sys.exit(status)
</code></pre>
<p>And, finally, the output of <code>python test.py</code>:</p>
<pre><code>Test: QThread subclassing
called SubClassThread.__init__()
called SubClassThread.run()
called SubClassThread.delayed_print()
end of delayed_print()
called print_things
app finished with exit code 0
</code></pre>
<p>What I learned about QTimers: the call to delayed_print() finishes while the timer is still running, and by putting quit() in the method called by the timer, the app does not exit until after that method has been called.</p>
<p>If there are any further comments on this code, or on the aspects of Qt relating to this simple app, please do post! I have had some trouble finding accessible PyQt/PySide information for beginners.</p>
| 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="nofollow">used to be an issue</a> in v0.14 or so, but it was <a href="http://stackoverflow.com/questions/26879082/my-code-using-pandas-options-did-work-now-throws-an-error">supposedly fixed</a> with v0.15. I'm on 0.18.1</p>
| 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 href="https://github.com/pydata/pandas-datareader/issues/212" rel="nofollow">this issue</a> so you'll know when this issue is fixed </p>
| 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>
<p>This function does not echo any characters as you type.</p>
<h3>Addendum</h3>
<p>If you absolutely <strong>must</strong> have <code>*</code> echoed while the password is typed, and you are on Windows, then you can do so by butchering the existing <code>getpass.win_getpass</code> to add it. Here is an example (untested):</p>
<pre><code>def starred_win_getpass(prompt='Password: ', stream=None):
import sys, getpass
if sys.stdin is not sys.__stdin__:
return getpass.fallback_getpass(prompt, stream)
# print the prompt
import msvcrt
for c in prompt:
msvcrt.putwch(c)
# read the input
pw = ""
while 1:
c = msvcrt.getwch()
if c == '\r' or c == '\n':
break
if c == '\003':
raise KeyboardInterrupt
if c == '\b':
pw = pw[:-1]
# PATCH: echo the backspace
msvcrt.putwch(c)
else:
pw = pw + c
# PATCH: echo a '*'
msvcrt.putwch('*')
msvcrt.putwch('\r')
msvcrt.putwch('\n')
return pw
</code></pre>
<p>Similarly, on unix, a solution would be to butcher the existing <code>getpass.unix_getpass</code> in a similar fashion (replacing the <code>readline</code> in <code>_raw_input</code> with an appropriate <code>read(1)</code> loop).</p>
| 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 side.</p>
| 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.parser.parse(x['MatchTime']) #MatchTime is the ISO 8601 field
</code></pre>
<p>The time seems to be pulling correctly, but when I add it to my Game model, pasted below, <strong>my is_live</strong> method is giving me an error</p>
<p>Game model:</p>
<pre><code>class Game(models.Model):
time = models.DateTimeField(null=True, blank=True)
livePick = models.BooleanField(default=True)
def is_live(self):
now = timezone.now()
now.astimezone(timezone.utc).replace(tzinfo=None)
if now < self.time:
return True
else:
return False
</code></pre>
<p>This is the error I am getting when I run the script to add in the Game with the time</p>
<pre><code>line 34, in is_live
if now < self.time:
TypeError: unorderable types: datetime.datetime() < NoneType()
</code></pre>
<p>Update:
Time is added to the Game model with the following</p>
<pre><code>g = Game.objects.create(team1=team1, team2=team2)
g.time = time
g.save()
</code></pre>
<p>Any help is greatly appreciated. Thank you!</p>
| 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.g.,:</p>
<pre><code>if self.time is not None and now < self.time:
return True
else:
return False
</code></pre>
| 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.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Sku.parent - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
</code></pre>
<p>Wherefore? this is work <a href="http://docs.sqlalchemy.org/en/latest/orm/self_referential.html" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/self_referential.html</a></p>
| 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('SC84.id'))
# -----------------------------------------------> ^^^^ __tablename__ here
children = relationship('Sku')
</code></pre>
<p>For MANY-TO-ONE relationship:</p>
<pre><code>class Sku(Base, ReprDescrIdMixin):
__tablename__ = 'SC84'
id = Column("ID", String, primary_key=True)
parent_code = Column("PARENTID",String, ForeignKey('SC84.id'))
parent = relationship('Sku', remote_side=['id'])
</code></pre>
| 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.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Sku.parent - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
</code></pre>
<p>Wherefore? this is work <a href="http://docs.sqlalchemy.org/en/latest/orm/self_referential.html" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/self_referential.html</a></p>
| 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 should pass the reference key, there's two ways to do this</p>
<ol>
<li>By passing a string with table name and key concatenated with <code>.</code> like <code>ForeignKey("table_name.key")</code> </li>
<li>By passing a Column object like <code>ForeignKey(key)</code> </li>
</ol>
<p>You can only use the method 2 if the <code>key</code> was already defined, in other words, if the <code>ForeignKey(key)</code> comes after <code>key = Column(...)</code></p>
<p>In my example, I'm using the method 2, I prefer this way in order to code be analyzed by my IDE.</p>
<p>See this <a href="http://docs.sqlalchemy.org/en/latest/core/constraints.html#sqlalchemy.schema.ForeignKey.params.column" rel="nofollow">link</a></p>
| 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.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Sku.parent - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.
</code></pre>
<p>Wherefore? this is work <a href="http://docs.sqlalchemy.org/en/latest/orm/self_referential.html" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/self_referential.html</a></p>
| 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])
</code></pre>
| 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 energies
energy = [x['energy'] for x in features]
#here I filter out low energy values
low_energy = [x for x in energy if x < 0.5]
#get track names
track_names = [sp.track(uri)['name'] for uri in tids]
</code></pre>
<p>Now I would like to <strong>filter out track names by energy values below 0.5</strong>, like so:</p>
<p><code>track name1 - 0.49
track name2 - 0.34</code></p>
<p>and so on.</p>
<p>but I'm struggling here...how do I achieve this? thanks</p>
| 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 the above example program, I am not sure how to check the output in browser.
I tried the links - <a href="http://127.0.0.1:5000/hello" rel="nofollow">http://127.0.0.1:5000/hello</a> , <a href="http://127.0.0.1:5000/members" rel="nofollow">http://127.0.0.1:5000/members</a> nothing come up.
Help me if I am missing anything ?</p>
| -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 http://localhost:5000/
</code></pre>
| 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 the above example program, I am not sure how to check the output in browser.
I tried the links - <a href="http://127.0.0.1:5000/hello" rel="nofollow">http://127.0.0.1:5000/hello</a> , <a href="http://127.0.0.1:5000/members" rel="nofollow">http://127.0.0.1:5000/members</a> nothing come up.
Help me if I am missing anything ?</p>
| -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 yourflaskapp
cd yourflaskapp
</code></pre>
<p>Create your virtual environment where you will install flask. </p>
<pre><code>virtualenv yourvirtualenv
</code></pre>
<p>After succesfully creating your virtual environment, activate it using the following command. To deactivate type and run <code>deactivate</code>. </p>
<pre><code>source yourvirtualenv/bin/activate
</code></pre>
<p>Now install flask in your virtual environment. </p>
<pre><code>pip install flask
</code></pre>
<p>Create file app.py below then run <code>python app.py</code>.</p>
<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>
| 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')
if x == k1 :
fn = 0
else:
fn = np.divide(1,(x-k1)*(y-k2))
return fn, x, y
f,x, y = expr(1,2)
print(f)
fx = f.subs({x:1,y:4})
print(fx)
</code></pre>
<p>So how is the equality or conditionality going to be checked once the function has been defined?</p>
<p>fn = 1/ (x-1)(y-2); How to set it as 0 for x=1 or y=2?</p>
| 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, y
f, x, y = expr(1, 2)
print(f(x, y))
print(f(1, 4))
</code></pre>
<p><strong>EDIT:</strong> </p>
<p>Here is one way to use <code>sp.lambdify</code> as asked in the comments:</p>
<pre><code>x_dot = 1 / ((x - 1) * (y - 2))
f = lambda a, b : 0 if a==1 or b==2 else sp.lambdify((x,y), xdot, "numpy")(a,b)
</code></pre>
<p>Another option is to use <code>sp.subs</code></p>
<pre><code>f = lambda a, b: 0 if a==1 or b==2 else float(x_dot.subs({x:a, y:b}))
</code></pre>
| 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')
if x == k1 :
fn = 0
else:
fn = np.divide(1,(x-k1)*(y-k2))
return fn, x, y
f,x, y = expr(1,2)
print(f)
fx = f.subs({x:1,y:4})
print(fx)
</code></pre>
<p>So how is the equality or conditionality going to be checked once the function has been defined?</p>
<p>fn = 1/ (x-1)(y-2); How to set it as 0 for x=1 or y=2?</p>
| 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 = lambdify((x, y, k1, k2), expr, 'numpy')
</code></pre>
<p>I do not recommend trying to mix NumPy and SymPy functions, as that generally won't work. NumPy functions don't know how to work with SymPy expressions and SymPy functions don't know how to work with NumPy arrays. The better way is to create the symbolic expression with SymPy, manipulate it however you need, then use <code>lambdify</code> to convert it to a NumPy function. </p>
| 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(map(lambda x: (min(x), max(x)), raw_data))
result = functools.reduce(lambda x, y: (min(x), max(y)), min_max_rows)
print(result) # Prints (2,37) instead of (0,37)
</code></pre>
| 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(map(lambda x: (min(x), max(x)), raw_data))
result = functools.reduce(lambda x, y: (min(x), max(y)), min_max_rows)
print(result) # Prints (2,37) instead of (0,37)
</code></pre>
| 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. Likewise for <code>max_val</code> so instead, I propose a different solution</p>
<pre><code>temp1 = []
temp2 = []
for x in raw_data:
temp1.append(min(x))
temp2.append(max(x))
min_max_list = [min(temp1),max(temp2)]
</code></pre>
| 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(map(lambda x: (min(x), max(x)), raw_data))
result = functools.reduce(lambda x, y: (min(x), max(y)), min_max_rows)
print(result) # Prints (2,37) instead of (0,37)
</code></pre>
| 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]: min_max_list
Out[77]: [0, 37]
</code></pre>
| 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(map(lambda x: (min(x), max(x)), raw_data))
result = functools.reduce(lambda x, y: (min(x), max(y)), min_max_rows)
print(result) # Prints (2,37) instead of (0,37)
</code></pre>
| 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 this :</p>
<pre><code> Traceback (most recent call last):
File "./manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/ifanramza/Desktop/CMS/.env/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/home/ifanramza/Desktop/CMS/.env/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/ifanramza/Desktop/CMS/.env/lib/python2.7/site-packages/django/core/management/__init__.py", line 195, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/home/ifanramza/Desktop/CMS/.env/lib/python2.7/site-packages/django/core/management/__init__.py", line 39, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/ifanramza/Desktop/CMS/.env/lib/python2.7/site-packages/django_medusa/management/commands/staticsitegen.py", line 2, in <module>
from django_medusa.renderers import StaticSiteRenderer
File "/home/ifanramza/Desktop/CMS/.env/lib/python2.7/site-packages/django_medusa/renderers/__init__.py", line 2, in <module>
from django.utils import importlib
ImportError: cannot import name importlib
</code></pre>
<p>But i have importlib module in installed apps. Is something wrong with my configuration? Thanks</p>
| 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 with Django 1.8 and above; the information below is retained for historical reference only. An alternative module based on the django-bakery package is available as a third-party contribution: <a href="https://github.com/mhnbcu/wagtailbakery" rel="nofollow">https://github.com/mhnbcu/wagtailbakery</a></p>
</blockquote>
| 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 don't want to show the first legend (I know that in this case I can just change the plot order to solve this problem)</p>
<p><a href="http://i.stack.imgur.com/nDqR0.png" rel="nofollow"><img src="http://i.stack.imgur.com/nDqR0.png" alt="enter image description here"></a></p>
| 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 href="http://i.stack.imgur.com/DHYV8.png" rel="nofollow"><img src="http://i.stack.imgur.com/DHYV8.png" alt="enter image description here"></a></p>
| 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 and Windows 10.</p>
| -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=DataFrame(medal_counts)
print df
print df['gold'].apply(numpy.mean, axis=1)
</code></pre>
<p>Last line is giving error as "IndexError: tuple index out of range". I need to use apply function in data frame and it should get average of columns gold,bronze and silver. In above example, I used only gold column. Please help me in fixing the error.</p>
| 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 be aware of:</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>.apply</code></a> is a method that works on rows or columns (default). If you call <code>df.apply(func)</code> the function, <code>func</code> will be applied to all columns, one column at a time. <code>df.apply(func, axis=1)</code> will apply <code>func</code> to all rows, one at a time. In case of <code>pd.Series</code> since there is only one column, <code>.apply</code> always works on rows. <code>.apply</code> is useful if you have a <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#flexible-apply" rel="nofollow">complex custom function</a> that you need to apply to either rows or columns. Some statistical measures, such as sum, mean, standard deviation, are <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#cython-optimized-aggregation-functions" rel="nofollow">common</a> and have vectorized functions of their own. Therefore one can directly call them, like in the answer above.</p>
<p>Please read the docs linked in the above paragraph for further information.</p>
| 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 delete it automatically or you don't use print()to check the variable value?</p>
| 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 & handy log methods like <code>debug, info, warning, error, critical</code><br>
ex:-
<code>logging.debug(<debug stuff>)</code><br />
<strong>EDIT</strong>
I am not sure I understood correctly about your need to disable logging once you are done, but if you want to do away with console logging you can try</p>
<pre><code>#logger = logging.getLogger() # this gets the root logger
logger = logging.getLogger('my-logger')
logger.propagate = False
# now if you use logger it will not log to console.
</code></pre>
<p><strong>EDIT</strong><br>
I think you want to remove all your print()/loggging statements from your code once you make sure everything is working fine!!!!<br />
Try using a regx to comment out all print statements</p>
<pre><code>find . -name '<filename>.py' -exec sed -ri "s/(^\s*)(print.*$)/#\1\2/g" {} \;
</code></pre>
| 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 delete it automatically or you don't use print()to check the variable value?</p>
| 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 delete it automatically or you don't use print()to check the variable value?</p>
| 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
c:\venv\lib\site-packages\sqlalchemy\util\langhelpers.pyc
c:\venv\lib\site-packages\sqlalchemy\util\queue.py
c:\venv\lib\site-packages\sqlalchemy\util\queue.pyc
c:\venv\lib\site-packages\sqlalchemy\util\topological.py
c:\venv\lib\site-packages\sqlalchemy\util\topological.pyc
</code></pre>
<p>This happens repeatedly, when I cancel the uninstall command and issue it again, even after system restart.</p>
<p>What can I do to make <code>pip</code> continue?</p>
| 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.dist-info
</code></pre>
<p>I checked for mentions of sqlalchemy in any *.pth file too, but there were no occurrences.</p>
<p>In any case, <code>pip freeze</code> revealed that the package was properly gone.</p>
| 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',"Hour":1,'Value':11},]
</code></pre>
<p>I want to be able to sum all values for a name for a particular hour, e.g. if <code>Name == Nick and Hour == 0</code>, I want value to give me the sum of all values meeting the condition. <code>2.75 + 2.21</code>, according to the piece above. </p>
<p>I have already tried the following but it doesn't help me out with both conditions. </p>
<pre><code>finalList = collections.defaultdict(float)
for info in lst:
finalList[info['Name']] += info['Value']
finalList = [{'Name': c, 'Value': finalList[c]} for c in finalList]
</code></pre>
<p>This sums up all the values for a particular <code>Name</code>, not checking if the <code>Hour</code> was the same. How can I incorporate that condition into my code as well? </p>
<p>My expected output : </p>
<pre><code>finalList = [{"Name":'Nick','Hour':0,'Value':4.96},
{"Name":'Sam','Hour':1,'Value':7.0},
{'Name':'Val',"Hour":1,'Value':21.1},
{'Name':'Nick','Hour':1,'Value':2.1}...]
</code></pre>
| 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},
{'Hour': 1, 'Name': 'Nick', 'Value': 2.1}]
In [110]: df = pd.DataFrame(lst)
In [111]: df
Out[111]:
Hour Name Value
0 0 Nick 2.75
1 1 Sam 7.00
2 0 Nick 2.21
3 1 Val 10.10
4 1 Nick 2.10
In [123]: df.groupby(['Name','Hour']).sum().reset_index()
Out[123]:
Name Hour Value
0 Nick 0 4.96
1 Nick 1 2.10
2 Sam 1 7.00
3 Val 1 10.10
</code></pre>
<p>export it to CSV:</p>
<pre><code>df.groupby(['Name','Hour']).sum().reset_index().to_csv('/path/to/file.csv', index=False)
</code></pre>
<p>result:</p>
<pre><code>Name,Hour,Value
Nick,0,4.96
Nick,1,2.1
Sam,1,7.0
Val,1,10.1
</code></pre>
<p>if you want to have it as a dictionary:</p>
<pre><code>In [125]: df.groupby(['Name','Hour']).sum().reset_index().to_dict('r')
Out[125]:
[{'Hour': 0, 'Name': 'Nick', 'Value': 4.96},
{'Hour': 1, 'Name': 'Nick', 'Value': 2.1},
{'Hour': 1, 'Name': 'Sam', 'Value': 7.0},
{'Hour': 1, 'Name': 'Val', 'Value': 10.1}]
</code></pre>
<p>you can do many fancy things using pandas:</p>
<pre><code>In [112]: df.ix[(df.Name == 'Nick') & (df.Hour == 0), 'Value'].sum()
Out[112]: 4.96
In [121]: df.groupby('Name')['Value'].agg(['sum','mean'])
Out[121]:
sum mean
Name
Nick 7.06 2.353333
Sam 7.00 7.000000
Val 10.10 10.100000
</code></pre>
| 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',"Hour":1,'Value':11},]
</code></pre>
<p>I want to be able to sum all values for a name for a particular hour, e.g. if <code>Name == Nick and Hour == 0</code>, I want value to give me the sum of all values meeting the condition. <code>2.75 + 2.21</code>, according to the piece above. </p>
<p>I have already tried the following but it doesn't help me out with both conditions. </p>
<pre><code>finalList = collections.defaultdict(float)
for info in lst:
finalList[info['Name']] += info['Value']
finalList = [{'Name': c, 'Value': finalList[c]} for c in finalList]
</code></pre>
<p>This sums up all the values for a particular <code>Name</code>, not checking if the <code>Hour</code> was the same. How can I incorporate that condition into my code as well? </p>
<p>My expected output : </p>
<pre><code>finalList = [{"Name":'Nick','Hour':0,'Value':4.96},
{"Name":'Sam','Hour':1,'Value':7.0},
{'Name':'Val',"Hour":1,'Value':21.1},
{'Name':'Nick','Hour':1,'Value':2.1}...]
</code></pre>
| 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= {d['Hour'] for d in lst}
</code></pre>
| 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',"Hour":1,'Value':11},]
</code></pre>
<p>I want to be able to sum all values for a name for a particular hour, e.g. if <code>Name == Nick and Hour == 0</code>, I want value to give me the sum of all values meeting the condition. <code>2.75 + 2.21</code>, according to the piece above. </p>
<p>I have already tried the following but it doesn't help me out with both conditions. </p>
<pre><code>finalList = collections.defaultdict(float)
for info in lst:
finalList[info['Name']] += info['Value']
finalList = [{'Name': c, 'Value': finalList[c]} for c in finalList]
</code></pre>
<p>This sums up all the values for a particular <code>Name</code>, not checking if the <code>Hour</code> was the same. How can I incorporate that condition into my code as well? </p>
<p>My expected output : </p>
<pre><code>finalList = [{"Name":'Nick','Hour':0,'Value':4.96},
{"Name":'Sam','Hour':1,'Value':7.0},
{'Name':'Val',"Hour":1,'Value':21.1},
{'Name':'Nick','Hour':1,'Value':2.1}...]
</code></pre>
| 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/stem/__init__.py", line 29, in <module>
from nltk.stem.snowball import SnowballStemmer
File "/usr/local/lib/python2.7/dist-packages/nltk/stem/snowball.py", line 24, in <module>
from nltk.corpus import stopwords
File "/usr/local/lib/python2.7/dist-packages/nltk/corpus/__init__.py", line 66, in <module>
from nltk.corpus.reader import *
File "/usr/local/lib/python2.7/dist-packages/nltk/corpus/reader/__init__.py", line 109, in <module>
from nltk.corpus.reader import bracket_parse
ImportError: cannot import name bracket_parse
</code></pre>
<p>Thanks in advance</p>
| 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>Install NLTK: run sudo pip install -U nltk</li>
<li>Test installation: run python then type import nltk</li>
</ol>
<p>Hope it helps</p>
| -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/stem/__init__.py", line 29, in <module>
from nltk.stem.snowball import SnowballStemmer
File "/usr/local/lib/python2.7/dist-packages/nltk/stem/snowball.py", line 24, in <module>
from nltk.corpus import stopwords
File "/usr/local/lib/python2.7/dist-packages/nltk/corpus/__init__.py", line 66, in <module>
from nltk.corpus.reader import *
File "/usr/local/lib/python2.7/dist-packages/nltk/corpus/reader/__init__.py", line 109, in <module>
from nltk.corpus.reader import bracket_parse
ImportError: cannot import name bracket_parse
</code></pre>
<p>Thanks in advance</p>
| 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 if the file <code>/usr/local/lib/python2.7/dist-packages/nltk/corpus/reader/bracket_parse.py</code> exists. I think there's any way to get the exact error trace you report if the file is present. If it's absent, I recommend zapping and reinstalling the <code>nltk</code> from scratch. (<code>nltk_data</code> can stay, and is easier to update from inside the system anyway if something is wrong.) </p>
| 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 version '3.4' by checking executables: python;python3;python3.4.
Found executable C:/Users/usuario pc/AppData/Local/Programs/Python/Python35-32/python.exe with UNsuitable version 3.5.2
Looking for python version '3.5' by checking executables: python;python3;python3.5.
Found executable C:/Users/usuario pc/AppData/Local/Programs/Python/Python35-32/python.exe with suitable version 3.5.2
Could NOT find PythonLibs (missing: PYTHON_LIBRARIES) (found suitable version "3.5.2", minimum required is "3.4")
</code></pre>
<p>And at the end in red letters it says:</p>
<pre><code>CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
Please set them or make sure they are set and tested correctly in the CMake files:
PYTHON_LIBRARY (ADVANCED)
linked by target "Sigil" in directory D:/Archivos de Programa/Sigil-0.9.6/src
</code></pre>
<p>Do I have to reinstall python? (which i did and reinitiate the PC). Do i have to change any line?</p>
<p>Thanks.</p>
| 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-six</p>
| 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><code>isdecimal()</code></strong>, <strong><code>isalnum()</code></strong> etc. But when I do that, I gets error message like this.</p>
<blockquote>
<p>âAttributeError: 'str' object has no attribute 'isdecimal'</p>
</blockquote>
<p>Is there anyway that I can use, so that I can read string, and pass these strings to these functions such as isdecimal?</p>
<p>I can explain an example case to you.</p>
<pre><code>a = raw_input()
</code></pre>
<p>I inputs <strong>'two'</strong> to the variable <strong>a</strong>. And then,</p>
<pre><code>print(a.isdecimal())
</code></pre>
<p>I want to print <strong><code>False</code></strong> instead of printing the given error message.</p>
| 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><code>isdecimal()</code></strong>, <strong><code>isalnum()</code></strong> etc. But when I do that, I gets error message like this.</p>
<blockquote>
<p>âAttributeError: 'str' object has no attribute 'isdecimal'</p>
</blockquote>
<p>Is there anyway that I can use, so that I can read string, and pass these strings to these functions such as isdecimal?</p>
<p>I can explain an example case to you.</p>
<pre><code>a = raw_input()
</code></pre>
<p>I inputs <strong>'two'</strong> to the variable <strong>a</strong>. And then,</p>
<pre><code>print(a.isdecimal())
</code></pre>
<p>I want to print <strong><code>False</code></strong> instead of printing the given error message.</p>
| 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 getting the input:</p>
<pre><code>text= raw_input().decode(sys.stdin.encoding or locale.getpreferredencoding(True))
</code></pre>
<p>The whole code would look like this:</p>
<pre><code>import sys, locale
text= raw_input().decode(sys.stdin.encoding or locale.getpreferredencoding(True))
print(text.isdecimal())
</code></pre>
<p>By the way, you have .isdigit() for non Unicode (aka normal strings).
To avoid all this hassle with string to Unicode conversion I'd advise you to move to python 3 if you have no strong need to stay with 2.7.*</p>
| 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 open('some/file/' + str(thisFile), 'wb+') as destination:
for chunk in thisFile.chunks():
destination.write(chunk)
return "File has successfully been uploaded"
</code></pre>
| 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 accordingly.
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
def clean_content(self):
content = self.cleaned_data['content']
content_type = content.content_type.split('/')[0]
if content_type in settings.CONTENT_TYPES:
if content._size > settings.MAX_UPLOAD_SIZE:
raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(content._size)))
else:
raise forms.ValidationError(_('File type is not supported'))
return content
</code></pre>
<p>Credit goes to <a href="https://www.djangosnippets.org/snippets/1303/" rel="nofollow">django snippet</a></p>
| 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 open('some/file/' + str(thisFile), 'wb+') as destination:
for chunk in thisFile.chunks():
destination.write(chunk)
return "File has successfully been uploaded"
</code></pre>
| 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:
return "This file is more than 5mb"
else:
with open('some/file/' + str(thisFile), 'wb+') as destination:
for chunk in thisFile.chunks():
destination.write(chunk)
return "File has successfully been uploaded"
</code></pre>
| 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 an enemy's health reaches below 0, it dies. I put in the exception "if self.HP < 0: del(self)" but that doesn't work.</p>
<p>What is the proper syntax to achieve the intended behavior? Also, if the object is deleted, what would happen to the things inside CurrentEnemy? Would everything shift or would there be nothing in the index the object was once in?</p>
<pre><code>import random
CurrentEnemy = []
class Monster(object):
def __init__(self, Name, HP, Damage):
self.Name = Name
self.HP = HP
self.Damage = Damage
**if self.HP < 0:
del(self)**
class Hero(object):
def __init__(self, Name, HP, Damage):
self.Name = Name
self.HP = HP
self.Damage = Damage
def GenerateEnemies():
NumberEnemies = random.randint(0,5)
del CurrentEnemy[:]
i=0
while i < (NumberEnemies+1):
TempMonster = Monster("Goblin", random.randint(15,20), random.randint(1,3))
CurrentEnemy.append(TempMonster)
i = i + 1
i=0
while i in range(0, len(CurrentEnemy)):
print("Goblin " + str(i) + " HP: " + str(CurrentEnemy[i].HP))
print("Goblin " + str(i) + " Damage: " + str(CurrentEnemy[i].Damage))
i = i + 1
def GenerateHero(HeroName, HeroHP, HeroDamage):
return Hero(HeroName, HeroHP, HeroDamage)
MyHero = GenerateHero("Bob", 100, 10)
def Attack(Attacker, Defender):
Defender.HP = Defender.HP - Attacker.Damage
</code></pre>
| 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 want to delete the object, you have to delete it from the list container in which you have stored it. </p>
| 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 am using in hosts like</p>
<pre><code>ansible_python_interpreter=/home/ansible/virualenv
</code></pre>
<p>The error i get is</p>
<pre><code> libpython2.7.so.1.0: cannot open shared object file: No such file or
</code></pre>
<p>directory</p>
<p>I think that is because when ansible ssh into it it does not source python 2.7 sh file which enables the new library config.</p>
<p>Is there any way ansbile can source that first thing before ssh</p>
| 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.</p>
| 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('SELECT * FROM holdings h WHERE option != \'Call\' AND option != \'Put\';')
</code></pre>
<p>nothing gets returned</p>
<p>If I run :</p>
<pre><code>curr.execute('SELECT * FROM holdings h WHERE option != \'Call\';')
</code></pre>
<p>I only get those rows with option value = 'Put'</p>
<p>How can I get the rows with None for option, without just doing a set difference. Ideally I want to be able to just select those rows that aren't 'Call' and 'Put' without calling difference from the all the rows and those that have 'Call' and 'Put'</p>
<p>Thank you for any help!</p>
| 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('SELECT * FROM holdings h WHERE option != \'Call\' AND option != \'Put\';')
</code></pre>
<p>nothing gets returned</p>
<p>If I run :</p>
<pre><code>curr.execute('SELECT * FROM holdings h WHERE option != \'Call\';')
</code></pre>
<p>I only get those rows with option value = 'Put'</p>
<p>How can I get the rows with None for option, without just doing a set difference. Ideally I want to be able to just select those rows that aren't 'Call' and 'Put' without calling difference from the all the rows and those that have 'Call' and 'Put'</p>
<p>Thank you for any help!</p>
| 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><code>SELECT * FROM holdings WHERE option NOT IN ('Call', 'Put')
</code></pre>
<p>And join this together with <code>OR</code>:</p>
<pre><code>SELECT * FROM holdings WHERE option NOT IN ('Call', 'Put') OR option IS NULL
</code></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 can")
print("all the best")
</code></pre>
<p><a href="http://i.stack.imgur.com/DwO6r.png" rel="nofollow">enter image description here</a></p>
<p>may anyone please help me.</p>
| -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 best
</code></pre>
<p>You can fix this in a number of ways. First choose a better prompt. Second, strip leading and trailing whitespace:</p>
<pre><code>team = input("Your favorite team: ").strip()
</code></pre>
| 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_list = []
total = 0
for i in square:
for j in i:
total += j
total_list.append(total)
return total_list
</code></pre>
<p>But this just accumulates each list onto each other resulting in:</p>
<pre><code>[15, 30, 45]
</code></pre>
<p>I'm not sure how to keep the sums for each list separate here. The SUM function is not allowed here as it's an exercise on nested loops.</p>
<p>Thanks.</p>
| 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
total_list.append(total)
return total_list
</code></pre>
| 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_list = []
total = 0
for i in square:
for j in i:
total += j
total_list.append(total)
return total_list
</code></pre>
<p>But this just accumulates each list onto each other resulting in:</p>
<pre><code>[15, 30, 45]
</code></pre>
<p>I'm not sure how to keep the sums for each list separate here. The SUM function is not allowed here as it's an exercise on nested loops.</p>
<p>Thanks.</p>
| 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_list.append(total)
return total_list
</code></pre>
| 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_list = []
total = 0
for i in square:
for j in i:
total += j
total_list.append(total)
return total_list
</code></pre>
<p>But this just accumulates each list onto each other resulting in:</p>
<pre><code>[15, 30, 45]
</code></pre>
<p>I'm not sure how to keep the sums for each list separate here. The SUM function is not allowed here as it's an exercise on nested loops.</p>
<p>Thanks.</p>
| 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_list = []
total = 0
for i in square:
for j in i:
total += j
total_list.append(total)
return total_list
</code></pre>
<p>But this just accumulates each list onto each other resulting in:</p>
<pre><code>[15, 30, 45]
</code></pre>
<p>I'm not sure how to keep the sums for each list separate here. The SUM function is not allowed here as it's an exercise on nested loops.</p>
<p>Thanks.</p>
| 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</code> <a href="https://docs.python.org/3/library/functools.html#functools.reduce" rel="nofollow">here</a>.</p>
<p>Edit: As Sevanteri pointed out in the comment, you can also use <code>[functools.reduce(int.__add__, sublist, 0) for sublist in list]
</code>(if you really want to drive your teacher mad!)</p>
| 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_list = []
total = 0
for i in square:
for j in i:
total += j
total_list.append(total)
return total_list
</code></pre>
<p>But this just accumulates each list onto each other resulting in:</p>
<pre><code>[15, 30, 45]
</code></pre>
<p>I'm not sure how to keep the sums for each list separate here. The SUM function is not allowed here as it's an exercise on nested loops.</p>
<p>Thanks.</p>
| 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
total = 0
total += next
yield total
if __name__ == '__main__':
li = [[2, 7, 6], [9, 5, 1], [4, 3, 8]]
print [g for g in _notsum2(li)]
</code></pre>
| 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_list = []
total = 0
for i in square:
for j in i:
total += j
total_list.append(total)
return total_list
</code></pre>
<p>But this just accumulates each list onto each other resulting in:</p>
<pre><code>[15, 30, 45]
</code></pre>
<p>I'm not sure how to keep the sums for each list separate here. The SUM function is not allowed here as it's an exercise on nested loops.</p>
<p>Thanks.</p>
| 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_list = []
total = 0
for i in square:
for j in i:
total += j
total_list.append(total)
return total_list
</code></pre>
<p>But this just accumulates each list onto each other resulting in:</p>
<pre><code>[15, 30, 45]
</code></pre>
<p>I'm not sure how to keep the sums for each list separate here. The SUM function is not allowed here as it's an exercise on nested loops.</p>
<p>Thanks.</p>
| 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 should display time-based on user's timezone?</p>
<p>What's the best practice to follow in terms of storing date time and exchanging date time format between client and server? Should the client send date time in UTC to the server or in it's own timezone along with locale?</p>
| 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 HTTPResponse to Javascript which eventually Plots the image on browser. </p>
<p>Problem here is that Old image doesn't get removed and a new Image is plotted on browser which looks like images below</p>
<p>This is when a page is loaded for the first time
<a href="http://i.stack.imgur.com/LSj1J.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/LSj1J.jpg" alt="enter image description here"></a></p>
<p>When UI is changed to PCA
<a href="http://i.stack.imgur.com/aelt9.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/aelt9.jpg" alt="enter image description here"></a></p>
<p>When I again selected Kmeans, It is still showing the Previous graph
<a href="http://i.stack.imgur.com/UTdVu.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/UTdVu.jpg" alt="enter image description here"></a></p>
<p>I have checked that all calcualtions are being made in views.py and values are returned to templates.</p>
<pre><code>views.py
class PlotTool(View):
@staticmethod
def kmeansPlot(request):
[X,labels] = cluster_kmeans(request.GET.get('value'))
color = ["g", "r", 'purple','olive','teal','orchid','darkorange']
size = [90] * len(X)
for i in xrange(len(X)):
plt.scatter(X[i][0], X[i][1], c=color[labels[i]],s=size[i])
#To Show Centroids on Plot
plt.title('Kmeans')
plt.grid(True)
# Store image in a string buffer
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_type="image/png")
return response
@staticmethod
def PCAPlot(request):
score,coeff,labels = pcaAnalysis()
xs = score[:,0]
ys = score[:,1]
n=coeff.shape[0]
scalex = 1.0/(xs.max()- xs.min())
scaley = 1.0/(ys.max()- ys.min())
plt.scatter(xs*scalex,ys*scaley)
for i in range(n):
plt.arrow(0, 0, coeff[i,0], coeff[i,1],color='r',alpha=0.5)
if labels is None:
plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color='g', ha='center', va='center')
else:
plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color='g', ha='center', va='center')
plt.title('PCA')
plt.xlim(-1,1)
plt.ylim(-1,1)
plt.xlabel("PC{}".format(1))
plt.ylabel("PC{}".format(2))
plt.grid()
# Store image in a string buffer
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_type="image/png")
return response
</code></pre>
<p>Python 2.7.10, Django 1.9
Any Help is Appreciated...Thanks</p>
<p>EDIT: Full Java Script Code</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><body>
<div class="container">
<div class="col-left">
<form action='#' method="get">
<div>
<label>No of Cluster</label>
</div>
<input id="slider1" type="range" class="myinput" value="3" min="2" max="10" step="1" onchange="callFun(dropdown1.value,this.value)" />
<div class="count"><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span style="border:none">10</span></div>
</form>
</div>
<div class="col-right">
<label>Select Clustering Method</label>
<select name="test" id="dropdown1" onchange="callFun(this.value,slider1.value)">
<option value="Kmeans Clustering" selected>Kmeans Clustering</option>
<option value="Birch Clustering">Birch Clustering</option>
<option value="PCA Plot">PCA Plot</option>
</select>
</div>
<div style="width:100%; float:left;margin-top:30px;">
<img id="im" src='{% url "kmeans_graph" %}' align="left" height="400" width="400" >
<p id="demo">3</p>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/1.0.0/fetch.min.js"></script>
<script>
function callFun(value1,value2) {
if (value1 == 'Kmeans Clustering'){
var img_src = '{% url "kmeans_graph" %}'
document.getElementById("im").setAttribute("src",img_src + '?value=' + value2);
document.getElementById("demo").innerHTML =value2
}
else if(value1 == 'Birch Clustering'){
var img_src = '{% url "birch_graph" %}'
document.getElementById("im").setAttribute("src",img_src + '?value=' + value2);
document.getElementById("demo").innerHTML =value2
}
else{
var img_src = '{% url "pca_graph" %}'
document.getElementById("im").setAttribute("src",img_src + '?value=' + Math.random());
document.getElementById("demo").innerHTML ='pca_graph'
}
}
</script>
</body>
</html></code></pre>
</div>
</div>
</p>
| 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_type="image/png")
return response
</code></pre>
<p>In the above code <code>pylab.get_current_fig_manager().canvas</code> get the current fig manager which is same everytime that is why it was plotting over old image instead of creating new image. So i changed the code as</p>
<pre><code>fig = Figure()
ax = fig.add_subplot(111)
#change all plt instances with ax
canvas=FigureCanvas(fig)
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
</code></pre>
<p>This has worked for me</p>
| 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_object_permission(self, request, view, obj):
if request.user.has_perm("can_change_when_not_done") and obj.status != "done":
return True
return super(MyPermission, self).has_object_permission(request, view_obj)
</code></pre>
<p>This works as expected.</p>
<p>However, it seems that when I patch the object to be "done" (e.g. <code>{'status': 'done'}</code> in the payload), it passes through a serializer on the way back which does another permission check, which results in a 403, since the object is now "done". I would like to still get a 200 and a serialized view of what the object looks like now from that request. <em>Future</em> mutating requests should result in a 403.</p>
<p>Setting the object to be read-only under "safe" methods (e.g. <code>GET</code>) does <strong>not</strong> help, since the original request is still a <code>PATCH</code>.</p>
<p>Is there an easy way to achieve what I want, or am I approaching this wrong?</p>
| 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.save()</code>. This caused my signal handler to run twice, which on the second request obviously resulted in a 403.</p>
<p>After combining the signal handlers (no reason for both to exist), everything works flawlessly. Hope this can help someone in the future!</p>
| 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 to which one to use?</p>
| 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)]]
#output: 10000 loops, best of 3: 41.9 µs per loop
</code></pre>
<p>or, assigning values to the indexed array</p>
<pre><code>% timeit x[[np.arange(0,10000,2)]] = 1
#output: 1000 loops, best of 3: 151 µs per loop
</code></pre>
<p>Now let's try the same using masking:</p>
<pre><code>x = np.ma.array(np.arange(10000))
% timeit x.mask = [1 if i%2==0 else 0 for i in np.arange(10000)]
#output: 100 loops, best of 3: 11.6 ms per loop
</code></pre>
<p>If you already have values to mask stored</p>
<pre><code>maskValues = [1 if i%2==0 else 0 for i in np.arange(10000)]
% timeit x.mask = maskValues
# output: 1000 loops, best of 3: 712 µs per loop
</code></pre>
<p>So indexing in numpy proved to be simpler and faster for this example</p>
| 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 that I can get the original images by slicing:</p>
<pre><code>my_pair[0] == X
my_pair[1] == Y
</code></pre>
<p>After a few attempts, I keep getting either:</p>
<blockquote>
<ul>
<li>my_pair.shape = (2,) #By converting the images into lists and adding them.</li>
</ul>
</blockquote>
<p>This works as well, but the next step in the pipeline just requires a shape (2, 3, 30, 30)</p>
<blockquote>
<ul>
<li><p>my_pair.shape = (6, 30, 30) # using np.vstack</p></li>
<li><p>my_pair.shape = (3, 60, 30) # using np.hstack</p></li>
</ul>
</blockquote>
<p>Thanks!</p>
| 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 shell=True IE running the above command does not exclude the file 'Build.tar.gz'.
Why is that?
Is there a way to make this work without setting the shell=True ?</p>
<p>regards</p>
| 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 arguments. If you use quotes in an argument list for <code>Popen</code> they are passed as literal qoute characters, so in your case you would exclude <code>'Build.tar.gz'</code> including quotes.</p>
| 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.