title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
NoReverseMatch at /accounts/login/ form action query?
| 39,439,048 |
<p>Im trying to learn django, but i cant find the answer to this anywhere, or at-least not in simple terms! im trying to implement the included login view in my project and ive tried using the example html that the documentation uses and i get this error.</p>
<pre><code>Template error:
In template
C:\Users\Owner\Documents\django\mysite\templates\registration\login.html, error at line 14
Reverse for 'login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] 4 :
5 : {% if next %}
6 : {% if user.is_authenticated %}
7 : <p>Your account doesn't have access to this page. To proceed,
8 : please login with an account that has access.</p>
9 : {% else %}
10 : <p>Please login to see this page.</p>
11 : {% endif %}
12 : {% endif %}
13 :
14 : <form method="post" action=" {% url 'login' %} ">
15 : {% csrf_token %}
16 : <table>
17 : <tr>
18 : <td>{{ form.username.label_tag }}</td>
19 : <td>{{ form.username }}</td>
20 : </tr>
21 : <tr>
22 : <td>{{ form.password.label_tag }}</td>
23 : <td>{{ form.password }}</td>
24 : </tr>
</code></pre>
<p>what i dont understand is what does " Action="{% url 'login' %}" actually do? i cant find a definitve answer of where it is actully looking for that. this is my blog/views.py file</p>
<pre><code>from django.shortcuts import render
from django.views import generic
from .models import Post
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.http import request, HttpResponse
from django.template import loader
# Create your views here.
class ListViews(generic.ListView):
template_name= 'blog/list.html'
context_object_name= 'latest_blog_posts'
def get_queryset(self):
return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')[:5]
@login_required
def DetailView(request,pk):
model = Post
data_list = Post.objects.get(id=pk)
template = loader.get_template('blog/detail.html')
context = {
'post':data_list,
}
return HttpResponse(template.render(context,request))
#def get_queryset(self):
#return Post.objects.filter(published_date__lte=timezone.now())
</code></pre>
<p>and this is my mysite/urls.py file:</p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^polls/', include('polls.urls', namespace="polls")),
url(r'^blog/', include('blog.urls', namespace="blog")),
url(r'^admin/', admin.site.urls),
url(r'^accounts/login/$', auth_views.login),
]
</code></pre>
<p>and ive already tried accounts/login in the action field of the form and that gives the same error. any ideas will be very much appreciated! thanks!</p>
| -1 |
2016-09-11T17:58:53Z
| 39,439,239 |
<p>Action="{% url 'login' %} : this means when you submit the form it will take you search for the url named 'login' in your urls.py and execute the view. but there isnt anything named login in your urls.py.you can try to edit the last line of urls.py as :
url(r'^accounts/login/$', auth_views.login, name='login'),
or edit template file as:
< form method="post" action="."></p>
| 0 |
2016-09-11T18:19:41Z
|
[
"python",
"django"
] |
How do I get the index of a column by name?
| 39,439,054 |
<p>Given a <code>DataFrame</code></p>
<pre><code>>>> df
x y z
0 1 a 7
1 2 b 5
2 3 c 7
</code></pre>
<p>I would like to find the index of the column by name, e.g., <code>x</code> -> 0, <code>z</code> -> 2, &c.</p>
<p>I can do</p>
<pre><code>>>> list(df.columns).index('y')
1
</code></pre>
<p>but it seems backwards (the <code>pandas.indexes.base.Index</code> class should probably be able to do it without circling back to list).</p>
| 1 |
2016-09-11T17:59:40Z
| 39,439,067 |
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_loc.html" rel="nofollow"><code>Index.get_loc</code></a>:</p>
<pre><code>print (df.columns.get_loc('z'))
2
</code></pre>
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.searchsorted.html" rel="nofollow"><code>Index.searchsorted</code></a>:</p>
<pre><code>print (df.columns.searchsorted('z'))
2
</code></pre>
<p><strong>Timings</strong>:</p>
<pre><code>In [86]: %timeit (df.columns.get_loc('z'))
The slowest run took 13.42 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 1.99 µs per loop
In [87]: %timeit (df.columns.searchsorted('z'))
The slowest run took 10.46 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 4.48 µs per loop
</code></pre>
| 1 |
2016-09-11T18:00:58Z
|
[
"python",
"python-2.7",
"pandas"
] |
Fitting with monte carlo in python
| 39,439,079 |
<p>Hello I use a python package called <code>emcee</code> to fit a function to some data points. The fit looks great, but when I want to plot the value of each parameter at each step I get this: <a href="http://i.stack.imgur.com/t0cpX.png" rel="nofollow"><img src="http://i.stack.imgur.com/t0cpX.png" alt="enter image description here"></a>. In their example (with a different function and data points) they get this: <a href="http://i.stack.imgur.com/qiXaH.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/qiXaH.jpg" alt="enter image description here"></a>. Why is my function converging so fast, and why does it have that weird shape in the beginning. I apply MCMC using likelihood and posterior probability. And even if the fit looks very good, the error on parameters of function are very small (10^10 smaller than the actual value) and I think it is because of the random walks. Any idea how to fix it? Here is their code for fitting: <a href="http://dan.iel.fm/emcee/current/user/line/" rel="nofollow">http://dan.iel.fm/emcee/current/user/line/</a> I used the same code with the obvious modifications for my data points and fitting function.</p>
| 0 |
2016-09-11T18:02:19Z
| 39,725,212 |
<p>I would not say that your function is converging faster than the <code>emcee</code> line-fitting example you're linked to. In the example, the walkers start exploring the most likely values in the parameter space almost immediately, whereas in your case it takes more than 200 iterations to reach the high probability region.</p>
<p>The jump in your trace plots looks like a burn-in. It is a common feature of MCMC sampling algorithms where your walkers are given starting points away from the bulk of the posterior and then must find their way to it. It looks like in your case the likelihood function is fairly smooth so you only need a hundred or so iterations to achieve this, giving your function this "weird shape" you're talking about.</p>
<p>If you can constrain the starting points better, do so; if not, you might consider discarding this initial length before further analysis is made (see <a href="http://stats.stackexchange.com/questions/88819/mcmc-methods-burning-samples">here</a> and <a href="http://stats.stackexchange.com/questions/88256/what-does-sampling-period-mean-in-mcmc/88262#88262">here</a> for discussions on burn in lengths).</p>
<p>As for whether the errors are realistic or not, you need to inspect the resulting posterior models for that, because the ratio of the actual parameter value to its uncertainties does not have a say in this. For example, if we take your linked <a href="http://dan.iel.fm/emcee/current/user/line/" rel="nofollow">example</a> and change the true value of <code>b</code> to 10^10, the resulting errors will be ten magnitudes smaller while remaining perfectly valid.</p>
| 2 |
2016-09-27T12:52:32Z
|
[
"python",
"curve-fitting",
"montecarlo"
] |
Odd behavior when multiplying numpy array by a constant (e.g. 1/100)
| 39,439,279 |
<p>I create the following random array and I multiply it times a constant but get an unexpected result (zeros instead of the answer I expect):</p>
<pre><code>In [4]: A = np.random.rand(1,11)
In [5]: A
Out[5]:
array([[ 0.15138551, 0.41573765, 0.0212214 , 0.44955909, 0.27013062,
0.37835199, 0.89712845, 0.95333785, 0.09920397, 0.2303608 ,
0.11246899]])
In [6]: A*(1/100)
Out[6]: array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
In [7]: A/100
Out[7]:
array([[ 0.00151386, 0.00415738, 0.00021221, 0.00449559, 0.00270131,
0.00378352, 0.00897128, 0.00953338, 0.00099204, 0.00230361,
0.00112469]])
</code></pre>
<p>What is the reason for this? Seems extremely counterintuitive.</p>
| -1 |
2016-09-11T18:24:15Z
| 39,439,298 |
<p>You are using python2 and <code>1/100</code> is integer division, resulting in <code>0</code>.</p>
<p>Use floating points:</p>
<pre><code>A * (1.0/100)
</code></pre>
<p>or use a future import:</p>
<pre><code>from __future__ import division
</code></pre>
<p>to enable floating point division for integers, too.</p>
| 4 |
2016-09-11T18:26:27Z
|
[
"python",
"numpy",
"python-2.x"
] |
What's the most efficient algorithm for topologically sorting a (special case of a) directed acyclic graph?
| 39,439,366 |
<p>I have a data set that is a special case of a directed acyclic graph (DAG). The nodes in my DAG have either 0 or 1 arcs. All arcs are equally weighted (that is, the only information contained in an arc is the node it points at, no "distance" or "cost" or "weight").</p>
<p>My users will input nodes in a semi-random order, with the expectation that the order of arcless nodes be preserved, but all arcs get sorted before the nodes that point at them (so child-first ordering).</p>
<p>Here is a simplified class representing my data:</p>
<pre><code>class Node:
def __init__(self, name, arc=None):
self.name = str(name)
self.arc = str(arc)
</code></pre>
<p>(note that <code>self.arc</code> is a string representation of the pointed-at node and not the object itself)</p>
<p>So, given an input like this:</p>
<pre><code>input = [Node('A'),
Node('B'),
Node('C'),
Node('Z', 'Y'),
Node('X', 'W'),
Node('Y', 'X'),
Node('W')]
</code></pre>
<p>You would get output like this, preferably using the fewest loops and intermediate data structures:</p>
<pre><code>output = [Node('A'),
Node('B'),
Node('C'),
Node('W'),
Node('X', 'W'),
Node('Y', 'X'),
Node('Z', 'Y')]
</code></pre>
| 0 |
2016-09-11T18:33:38Z
| 39,439,453 |
<p>So far this is the best algorithm I've been able to come up with:</p>
<pre><code>def topo_sort(nodes):
objects = {} # maps node names back to node objects
graph = OrderedDict() # maps node names to arc names
output = []
for node in nodes:
objects[node.name] = node
graph[node.name] = node.arc
arcs = graph.values()
# optional
missing = set(arcs) - set(graph) - {None}
if missing:
print('Invalid arcs: {}'.format(', '.join(missing)))
def walk(arc):
"""Recurse down the tree from root to leaf nodes."""
obj = objects.get(arc)
if obj and obj not in output:
follow_the_arcs(graph.get(arc))
output.append(obj)
# Find all root nodes
for node in graph:
if node not in arcs:
walk(node)
return ordered
</code></pre>
<p>What I like about this is that there are only 2 loops (one to build the graph and one to find the roots), and the output is built exclusively with <code>list.append()</code>, no slow <code>list.insert()</code>s. Can anybody think of any improvements to this? Any obvious inefficiencies I've overlooked?</p>
<p>Thanks!</p>
| 0 |
2016-09-11T18:44:58Z
|
[
"python",
"algorithm",
"python-3.x",
"directed-acyclic-graphs",
"topological-sort"
] |
subprocess.Popen executes .sh differently then subprocess.call
| 39,439,385 |
<p>I'm trying to run parsey mcparseface from a subprocess. I get different results when running Popen vs call and I'm wondering why this is.
This works.</p>
<pre><code>process = subprocess.Popen("./syntaxnet/demo.sh", cwd="/home/kahless/models/syntaxnet")
</code></pre>
<p>This does not.</p>
<pre><code>process = subprocess.call("./syntaxnet/demo.sh", cwd="/home/kahless/models/syntaxnet")
</code></pre>
<p>Both execute without python throwing any errors but when running .call parsey does not complete correctly. This also happens when using .wait() or .communicate() with Popen. What I'm trying to do is pause the execution of my code until parsey finishes. Not sure whats going on here.</p>
<p>Edit. When I say that parsey does not complete correctly I mean I am getting a different end result from running the demo.sh file. Here are the different outputs.</p>
<p>When things work correctly</p>
<p>INFO:tensorflow:Processed 10 documents
INFO:tensorflow:Total processed documents: 10
INFO:tensorflow:num correct tokens: 0
INFO:tensorflow:total tokens: 170
INFO:tensorflow:Seconds elapsed in evaluation: 0.18, eval metric: 0.00%
INFO:tensorflow:Processed 10 documents
INFO:tensorflow:Total processed documents: 10
INFO:tensorflow:num correct tokens: 10
INFO:tensorflow:total tokens: 153
INFO:tensorflow:Seconds elapsed in evaluation: 0.86, eval metric: 6.54%</p>
<p>When they do not.</p>
<p>INFO:tensorflow:Total processed documents: 0
INFO:tensorflow:Total processed documents: 0</p>
| 0 |
2016-09-11T18:35:53Z
| 39,439,476 |
<p>Are you sure it ever finishes?</p>
<p>Looks like your code hangs. Perhaps it takes user input?</p>
<p><code>subprocess.call()</code> waits until it finishes so as <code>wait()</code> and <code>communicate()</code></p>
| 0 |
2016-09-11T18:46:58Z
|
[
"python"
] |
Subtract value from netCDF dimension
| 39,439,534 |
<p>How can I use nco tools or any other netcdf toolkit to subtract a specific value from one of the dimensions in a netCDF?</p>
<p>E.g.</p>
<pre><code>ncdump âv time ât file.nc
</code></pre>
<p>gives me:</p>
<pre><code>time = 10, 11, 12, 13 â¦
</code></pre>
<p>How can I subtract 10 from each value in the time dimension so that the end result is:</p>
<pre><code>time = 0, 1, 2, 3 â¦
</code></pre>
| 0 |
2016-09-11T18:54:15Z
| 39,441,641 |
<p>Nothing is more concise than <a href="http://nco.sf.net/nco.html#ncap2" rel="nofollow" title="ncap2">ncap2</a> for this:</p>
<p>ncap2 -s 'time-=10' in.nc out.nc</p>
<p>ncap2 will subtract any value except 13, because that would bring bad luck.</p>
| 2 |
2016-09-11T23:30:59Z
|
[
"python",
"netcdf",
"nco"
] |
Explanation for the second case that made contextlib.nested to be deprecated (Python documentation)
| 39,439,594 |
<p><code>context.nested</code> is deprecated, I'm trying to understand the rationale behind this and after reading the documentation for a quite long time, I couldn't see an example to make the second issue clear: </p>
<blockquote>
<p>Secondly, if the <code>__enter__()</code> method of one of the inner context managers raises an exception that is caught and suppressed by the <code>__exit__()</code> method of one of the outer context managers, this construct will raise <code>RuntimeError</code> rather than skipping the body of the <code>with</code> statement.</p>
</blockquote>
<p>First what is the meaning of inner context managers and outer context managers here? What would this look like in code? </p>
<p><strong>Edit:</strong></p>
<p>From what I understood, I tried to deomonstrate the issue with code: </p>
<pre><code>>>> class A:
... def __enter__(*args):
... print("enter A")
... def __exit__(*args): print("exit A"); return True
...
>>> class B:
... def __enter__(*args): print("B __enter__")
... def __exit__(*args): raise Exception("spam")
...
>>> with nested(A(), B()): pass # A() outer context, B() inner context?
...
enter A
B __enter__
exit A
</code></pre>
<p>But this code doesn't raise <code>RuntimeError</code>?</p>
| 2 |
2016-09-11T19:01:19Z
| 39,440,017 |
<p>In your example, you have the context manager <code>B</code> raising exception in the <code>__exit__</code> method. But the quote describes the inner exception being raised by the <code>__enter__</code> method. I was able to reproduce a <code>RuntimeError</code> by moving the raised exception to the <code>__enter__</code> method.</p>
<p>FWIW, the replacement for <code>contextlib.nested</code> is <a href="https://docs.python.org/3.4/library/contextlib.html#contextlib.ExitStack" rel="nofollow"><code>ExitStack</code></a> in python 3.4+. There is a <a href="http://contextlib2.readthedocs.org/en/latest/" rel="nofollow">backport</a> for python2.</p>
| 1 |
2016-09-11T19:47:58Z
|
[
"python"
] |
Python module installed by issues while importing on Mac OS
| 39,439,622 |
<p>I installed <code>beautifulsoup4</code> module in <code>python2.7</code>, but import is failing.</p>
<p>python module is installed under this directory.</p>
<pre><code>$ls -l /Library/Python/2.7/site-packages
total 1080
-rw-r--r-- 1 root wheel 119 Aug 22 2015 README
drwxr-xr-x 9 root wheel 306 Sep 8 22:17 beautifulsoup4-4.5.1.dist-info
drwxr-xr-x 14 root wheel 476 Sep 8 22:17 bs4
-rw-r--r-- 1 root wheel 30 Sep 8 22:03 easy-install.pth
drwxr-xr-x 34 root wheel 1156 Sep 8 22:16 pip
drwxr-xr-x 10 root wheel 340 Sep 8 22:16 pip-8.1.2.dist-info
-rw-r--r-- 1 root wheel 538338 Sep 8 22:03 setuptools-26.1.1-py2.7.egg
-rw-r--r-- 1 root wheel 30 Sep 8 22:03 setuptools.pth
drwxr-xr-x 6 root wheel 204 Jul 26 21:13 vboxapi
-rw-r--r-- 1 root wheel 241 Jul 26 21:13 vboxapi-1.0-py2.7.egg-info
drwxr-xr-x 32 root wheel 1088 Sep 8 22:16 wheel
drwxr-xr-x 11 root wheel 374 Sep 8 22:16 wheel-0.29.0.dist-info
$
</code></pre>
<p>output of python shell, import fails. I am using python2.7</p>
<pre><code>$ /usr/bin/python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import beautifulsoup4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named beautifulsoup4
>>> exit()
</code></pre>
<p>python <code>sys.path</code> has module location as <code>/Library/Python/2.7/site-packages</code></p>
<pre><code>$ /usr/bin/python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print "\n".join(sys.path)
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC
/Library/Python/2.7/site-packages
/Library/Python/2.7/site-packages/setuptools-26.1.1-py2.7.egg
>>> exit()
$
</code></pre>
<p>please suggest why import of module is failing.</p>
<p>Thanks</p>
| 0 |
2016-09-11T19:03:29Z
| 39,439,662 |
<p>The module is called <code>bs4</code>, not <code>beautifulsoup4</code>, try with:</p>
<pre><code>import bs4
</code></pre>
| 0 |
2016-09-11T19:07:23Z
|
[
"python",
"osx",
"python-2.7"
] |
Python module installed by issues while importing on Mac OS
| 39,439,622 |
<p>I installed <code>beautifulsoup4</code> module in <code>python2.7</code>, but import is failing.</p>
<p>python module is installed under this directory.</p>
<pre><code>$ls -l /Library/Python/2.7/site-packages
total 1080
-rw-r--r-- 1 root wheel 119 Aug 22 2015 README
drwxr-xr-x 9 root wheel 306 Sep 8 22:17 beautifulsoup4-4.5.1.dist-info
drwxr-xr-x 14 root wheel 476 Sep 8 22:17 bs4
-rw-r--r-- 1 root wheel 30 Sep 8 22:03 easy-install.pth
drwxr-xr-x 34 root wheel 1156 Sep 8 22:16 pip
drwxr-xr-x 10 root wheel 340 Sep 8 22:16 pip-8.1.2.dist-info
-rw-r--r-- 1 root wheel 538338 Sep 8 22:03 setuptools-26.1.1-py2.7.egg
-rw-r--r-- 1 root wheel 30 Sep 8 22:03 setuptools.pth
drwxr-xr-x 6 root wheel 204 Jul 26 21:13 vboxapi
-rw-r--r-- 1 root wheel 241 Jul 26 21:13 vboxapi-1.0-py2.7.egg-info
drwxr-xr-x 32 root wheel 1088 Sep 8 22:16 wheel
drwxr-xr-x 11 root wheel 374 Sep 8 22:16 wheel-0.29.0.dist-info
$
</code></pre>
<p>output of python shell, import fails. I am using python2.7</p>
<pre><code>$ /usr/bin/python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import beautifulsoup4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named beautifulsoup4
>>> exit()
</code></pre>
<p>python <code>sys.path</code> has module location as <code>/Library/Python/2.7/site-packages</code></p>
<pre><code>$ /usr/bin/python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print "\n".join(sys.path)
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC
/Library/Python/2.7/site-packages
/Library/Python/2.7/site-packages/setuptools-26.1.1-py2.7.egg
>>> exit()
$
</code></pre>
<p>please suggest why import of module is failing.</p>
<p>Thanks</p>
| 0 |
2016-09-11T19:03:29Z
| 39,439,670 |
<p>Try this:</p>
<pre><code> from bs4 import BeautifulSoup
</code></pre>
| 0 |
2016-09-11T19:08:09Z
|
[
"python",
"osx",
"python-2.7"
] |
python how to know the object attributes(methods) and how to know the hierarchy of the dict
| 39,439,629 |
<p>I am working with the caffe Python wrapper. I have two questions about using Python to access the data details.</p>
<p>I first loaded the caffe net definition by:</p>
<pre><code>net = caffe.Net('deploy_full.prototxt',caffe.TEST)
</code></pre>
<p>I know the net will be a object in Python, and I want to know the attributes within it, so I use the bulit-in dir() methods:</p>
<pre><code>>>> dir(net)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__','__getattribute__', '__hash__', '__init__', '__module__','__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_backward', '_batch', '_blob_loss_weights', '_blob_names', '_blobs', '_forward', '_inputs', '_layer_names', '_outputs', '_set_input_arrays', 'backward', 'blob_loss_weights', 'blobs', 'copy_from', 'forward', 'forward_all', 'forward_backward_all', 'inputs', 'layers', 'outputs', 'params', 'reshape', 'save', 'set_input_arrays', 'share_with']
</code></pre>
<p>Then I used the params attribute to find the keys attribute of net.params:</p>
<pre><code>>>> net.params.keys()
['conv1a', 'bn1a', 'conv1b', 'bn1b', 'conv2a', 'bn2a', 'conv2b', 'bn2b', 'conv3a', 'bn3a', 'conv3b', 'bn3b', 'fc8-conv']
</code></pre>
<p>So the problem is here, I want to know the detail about net.params['bn1a']:</p>
<pre><code>>>> net.params['bn1a']
<caffe._caffe.BlobVec object at 0x7f274b71fbb0>
>>> dir(net.params['bn1a'])
['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__instance_size__', '__iter__', '__len__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'add_blob', 'append', 'extend']
</code></pre>
<p>These outputs are not what I want, after googling somehow, I found want I want to see is achieved by these commands:</p>
<pre><code>>>> net.params['bn1a'][0].data.shape
(1, 16, 1, 1)
>>> net.params['bn1a'][1].data.shape
(1, 16, 1, 1)
</code></pre>
<p>My problem is how could I know there should be [0], [1], and [x], in this dict? Since the net.params.keys() only told me there is key 'bn1a', but didn't tell me [num].</p>
<p>Moreover, if I didn't know there is [num] after ['bn1a'], I have no way to know the attributes of net.params['bn1a'][x], so I can't know the data and shape of these.</p>
<p>I would like to know what is the right way to peel the data/objects without knowledge beforehand.</p>
| 1 |
2016-09-11T19:03:46Z
| 39,439,938 |
<p>Usually in that case I would just go and check <code>BlobVec</code> class source code and find out <code>__iter__</code> method implementation and all other. But in your case it will not so helpful since <code>caffe._caffe.BlobVec</code> is actually points to <a href="https://github.com/BVLC/caffe/blob/master/python/caffe/_caffe.cpp#L241" rel="nofollow">C++ implementation</a> when you can find that it's vector and fugure out about iterating over it etc if you know a thing about C++ and how it binds to Python and other awesome stuff :)</p>
<p>So in your case it's really better to check documentation. There under <a href="http://caffe.berkeleyvision.org/tutorial/interfaces.html" rel="nofollow">Python section</a> you'll find that</p>
<blockquote>
<p>Caffe blobs are exposed as numpy ndarrays for ease-of-use and efficiency.</p>
</blockquote>
<p>Then you should just find docs about numpy arrays and you done.</p>
| 0 |
2016-09-11T19:38:54Z
|
[
"python",
"object"
] |
How to print a file line by line in specific interval continuously using python?
| 39,439,678 |
<p>I have a file with 4 website names as shown below. I want to print each website name one by one continuously, in specific interval.</p>
<p>sample.txt:</p>
<pre><code>facebook.com
gmail.com
test.com
yahoo.com
</code></pre>
<p>I have tried with following code. But its print website names only once. I wanted to website names continuously.</p>
<pre><code>from time import sleep
while True:
with open ("sample.txt", 'r') as test:
while True:
print test.readline()
sleep(3)
pass
</code></pre>
<p>Expected output:</p>
<pre><code>facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
.
.
.
</code></pre>
<p>Can I get help to fix this issue?</p>
<p>Thanks. </p>
| 1 |
2016-09-11T19:08:46Z
| 39,439,698 |
<p>You just need to loop over each line:</p>
<pre><code>for line in test:
print line
</code></pre>
<p>Instead of while True:</p>
<p>Complete:</p>
<pre><code>from time import sleep
with open ("sample.txt", 'r') as test:
for line in test
print line
sleep(3)
</code></pre>
| 1 |
2016-09-11T19:10:41Z
|
[
"python",
"python-2.7"
] |
How to print a file line by line in specific interval continuously using python?
| 39,439,678 |
<p>I have a file with 4 website names as shown below. I want to print each website name one by one continuously, in specific interval.</p>
<p>sample.txt:</p>
<pre><code>facebook.com
gmail.com
test.com
yahoo.com
</code></pre>
<p>I have tried with following code. But its print website names only once. I wanted to website names continuously.</p>
<pre><code>from time import sleep
while True:
with open ("sample.txt", 'r') as test:
while True:
print test.readline()
sleep(3)
pass
</code></pre>
<p>Expected output:</p>
<pre><code>facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
.
.
.
</code></pre>
<p>Can I get help to fix this issue?</p>
<p>Thanks. </p>
| 1 |
2016-09-11T19:08:46Z
| 39,439,712 |
<p>Your file object which returns an <em>iterator</em> got exhausted after the first round of calls to <code>readline()</code>. You should instead read the entire file into a list and iterate over that list successively. </p>
<pre><code>from time import sleep
with open ("sample.txt") as test:
lines = test.readlines() # read all lines into list
while True:
for line in lines:
print line
sleep(3)
</code></pre>
| 1 |
2016-09-11T19:11:55Z
|
[
"python",
"python-2.7"
] |
How to print a file line by line in specific interval continuously using python?
| 39,439,678 |
<p>I have a file with 4 website names as shown below. I want to print each website name one by one continuously, in specific interval.</p>
<p>sample.txt:</p>
<pre><code>facebook.com
gmail.com
test.com
yahoo.com
</code></pre>
<p>I have tried with following code. But its print website names only once. I wanted to website names continuously.</p>
<pre><code>from time import sleep
while True:
with open ("sample.txt", 'r') as test:
while True:
print test.readline()
sleep(3)
pass
</code></pre>
<p>Expected output:</p>
<pre><code>facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
.
.
.
</code></pre>
<p>Can I get help to fix this issue?</p>
<p>Thanks. </p>
| 1 |
2016-09-11T19:08:46Z
| 39,439,730 |
<p>The problem is that, after <code>readline()</code> reaches the end of the file, it will continue to return empty lines. You need something that ends the loop so that you can start over on the beginning of the file:</p>
<pre><code>from time import sleep
while True:
with open ("sample.txt", 'r') as test:
for line in test:
print line.rstrip()
sleep(3)
</code></pre>
<p>If you really want to use <code>readline</code>, then you need to test for the end of file. While <code>readline</code> is reading actual lines, it will always return at least a newline character. If it returns nothing, then it has reached the end of the file. Thus:</p>
<pre><code>from time import sleep
while True:
with open ("sample.txt", 'r') as test:
while True:
line = test.readline()
if not line:
break
print line.rstrip()
sleep(3)
</code></pre>
| 1 |
2016-09-11T19:14:07Z
|
[
"python",
"python-2.7"
] |
How to grab a programs PID using python
| 39,439,687 |
<p>i'm trying to grab openvpn pid then check to see if its running but this code doesnt seem to work. it tells me 'pid' isn't an integer when the output is '432'</p>
<pre><code>import psutil
import time
import os
import subprocess
proc = subprocess.Popen(["pgrep openvpn"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
out = out.strip()
print ("openvpn",out)
pid = out
time.sleep(5)
while True:
if psutil.pid_exists(pid):
print "a process with pid %d exists" % pid
time.sleep(120)
else:
print "a process with pid %d does not exist" % pid
time.sleep(5)
os.system("")
</code></pre>
| 0 |
2016-09-11T19:09:42Z
| 39,439,704 |
<p><code>'432'</code> is not an integer; it's a string that holds digits. Convert it to an integer using <code>int()</code>.</p>
| 1 |
2016-09-11T19:11:21Z
|
[
"python",
"linux",
"psutil"
] |
For loop with increasing variable
| 39,439,724 |
<p>I am writing a for loop to quickly obtain user data for a set. To keep the data useful, each has to have it's own variable it saves to. So far, I have:</p>
<pre><code>hey = ['11', '12', '13', '14']
x = 0
for i in hey:
x += 1
showtimesx = raw_input('NOG >')
print showtimesx
print ""
print "Showtime at 11: " + showtimesx
print "Showtime at 12: " + showtimesx
print "Showtime at 13: " + showtimesx
print "Showtime at 14: " + showtimesx
</code></pre>
<p>The last prints are just to check that the showtimesx have increased in value. However, every time I run it, all of them just end up equaling the last inputted value. </p>
<p>I have attempted to move the x += 1 line, have the x = 0 line inside the loop and a series of other things, but none of them work.</p>
<p>How can I fix that?</p>
| -1 |
2016-09-11T19:13:07Z
| 39,439,753 |
<p>You want to use lists:</p>
<pre><code>hey = ['11', '12', '13', '14']
showtimes = [raw_input('NOG >') for i in hey]
print ""
print "Showtime at 11: " + showtimes[0]
print "Showtime at 12: " + showtimes[1]
print "Showtime at 13: " + showtimes[2]
print "Showtime at 14: " + showtimes[3]
</code></pre>
| 0 |
2016-09-11T19:15:44Z
|
[
"python"
] |
For loop with increasing variable
| 39,439,724 |
<p>I am writing a for loop to quickly obtain user data for a set. To keep the data useful, each has to have it's own variable it saves to. So far, I have:</p>
<pre><code>hey = ['11', '12', '13', '14']
x = 0
for i in hey:
x += 1
showtimesx = raw_input('NOG >')
print showtimesx
print ""
print "Showtime at 11: " + showtimesx
print "Showtime at 12: " + showtimesx
print "Showtime at 13: " + showtimesx
print "Showtime at 14: " + showtimesx
</code></pre>
<p>The last prints are just to check that the showtimesx have increased in value. However, every time I run it, all of them just end up equaling the last inputted value. </p>
<p>I have attempted to move the x += 1 line, have the x = 0 line inside the loop and a series of other things, but none of them work.</p>
<p>How can I fix that?</p>
| -1 |
2016-09-11T19:13:07Z
| 39,439,849 |
<p>The reason is that for each loop that your <code>for</code> does, <code>showtimesx</code> gets overwritten.
This code blow will help:</p>
<pre><code>hey = ['11', '12', '13', '14']
x = 0
showtimesx = []
for n in hey :
for i in n:
x += 1
showtimesx.append(input('NOG >')) #Adds the user's input too end of showtimesx
print (showtimesx) #FYI: input() is equal to raw_input() in python3
break
print ("")
print ("Showtime at 11: " + showtimesx[0])
print ("Showtime at 12: " + showtimesx[1])
print ("Showtime at 13: " + showtimesx[2])
print ("Showtime at 14: " + showtimesx[3])
</code></pre>
| 0 |
2016-09-11T19:27:12Z
|
[
"python"
] |
For loop with increasing variable
| 39,439,724 |
<p>I am writing a for loop to quickly obtain user data for a set. To keep the data useful, each has to have it's own variable it saves to. So far, I have:</p>
<pre><code>hey = ['11', '12', '13', '14']
x = 0
for i in hey:
x += 1
showtimesx = raw_input('NOG >')
print showtimesx
print ""
print "Showtime at 11: " + showtimesx
print "Showtime at 12: " + showtimesx
print "Showtime at 13: " + showtimesx
print "Showtime at 14: " + showtimesx
</code></pre>
<p>The last prints are just to check that the showtimesx have increased in value. However, every time I run it, all of them just end up equaling the last inputted value. </p>
<p>I have attempted to move the x += 1 line, have the x = 0 line inside the loop and a series of other things, but none of them work.</p>
<p>How can I fix that?</p>
| -1 |
2016-09-11T19:13:07Z
| 39,440,751 |
<h1>List Approach</h1>
<p>If you have to iterate through a and perform an operation with each value, try <a href="https://docs.python.org/2.3/whatsnew/section-enumerate.html" rel="nofollow"><code>enumerate()</code>, which will return both the value from your list and its position in the list</a>.<br>
This will also allow you to change the values in your list by index.</p>
<pre><code>mylist = ['11', '12', '13', '14']
for index, value in enumerate(mylist):
if int(value) == 12:
mylist[index] = "fifteen instead"
print mylist # ['11', 'fifteen instead', '13', '14']
</code></pre>
<h1>Dictionary Approach</h1>
<p>In your case, <a href="http://www.tutorialspoint.com/python/python_dictionary.htm" rel="nofollow">consider using a dictionary</a>. This will allow you to more easily save them and query them back later by name ("key") instead of remembering some index like <code>mylist[1]</code> or having to search through it until you find a value.</p>
<pre><code>>>> colors = {"pineapples": "sorry, no pineapples"} # initial key: value pairs
>>> colors["red"] = "#FF0000" # add value
>>> print colors["red"] # retrieve a value by key
#FF0000
</code></pre>
<p>Here's an example as a complete function of your case:</p>
<pre><code>def showtimes(list_of_times, display=True):
dict_of_times = {} # empty dictionary to store your value pairs
print "please enter values for the {} showtimes".format(len(list_of_times))
for value in list_of_times:
dict_of_times[value] = raw_input("NOG > ")
if display: # Let the user decide to display or not
print ""
for time in sorted(dict_of_times.keys()): # dictionaries are unsorted
print "Showtimes at {}: {}".format(time, dict_of_times[time])
return dict_of_times # keep your new dictionary for later
hey = ['11', '12', '13', '14']
showtimes(hey) # pass a list to your function
</code></pre>
| 0 |
2016-09-11T21:19:01Z
|
[
"python"
] |
How to show results from a Biopython Pubmed search in a Gtk.TextView?
| 39,439,729 |
<p>I want to search Pubmed using Biopython (the code is in the Biopython documentation) and display the results (title, authors, source) of each record in a Gtk.TextView. The code works when just printed but when I try to use the TextView, only the first record is shown. If anyone knows why this is the case, I'd appreciate the help.</p>
<p>Here is what I've got so far...</p>
<pre><code>def pbmd_search(self): #searches pubmed database, using Biopython documentation
handle = Entrez.egquery(term=self.entry.get_text())
record = Entrez.read(handle)
for row in record["eGQueryResult"]:
if row["DbName"]=="pubmed":
print(row["Count"])
handle = Entrez.esearch(db="pubmed", term=self.entry.get_text(), retmax=1000)
record = Entrez.read(handle)
idlist = record["IdList"]
handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline", retmode="text")
records = Medline.parse(handle)
records = list(records)
records_str = ""
tv = Gtk.TextView()
for record in records:
records_str +=("title:", record.get("TI", "?"), "authors:", record.get("AU", "?"), "source:", record.get("SO", "?"), (""))
#print(records_str)
tv.get_buffer().set_text(str(records_str))
tv.set_editable(False)
sw = Gtk.ScrolledWindow()
sw.set_size_request(300,200)
sw.add(tv)
w = Gtk.Window() w.add(sw)
w.show_all()
</code></pre>
| 0 |
2016-09-11T19:14:01Z
| 39,561,232 |
<p>As written in my comment: Your <code>for</code> loop produces one long line without linebreaks, and <code>Gtk.TextView</code> does not wrap the line.</p>
<p>From the <a href="http://python-gtk-3-tutorial.readthedocs.io/en/latest/textview.html" rel="nofollow">Python GTK+ 3 tutorial</a>:</p>
<blockquote>
<p>Another default setting of the Gtk.TextView widget is long lines of text will continue horizontally until a break is entered. To wrap the text and prevent it going off the edges of the screen call Gtk.TextView.set_wrap_mode().</p>
</blockquote>
<p>So you should either add linebreaks to your output string or use the <code>Gtk.TextView.set_wrap_mode()</code>.</p>
| 1 |
2016-09-18T18:33:20Z
|
[
"python",
"gtk",
"biopython",
"pubmed"
] |
how to limit input in while loop need serious looking into
| 39,439,813 |
<p>how can i limit the input for srj imbetween 1 and 0 and it just restarts the whole program</p>
<pre><code>def gen0(): # input all the initial data
while True: # this will loop infinitely if needed
try: # this will try to take a float from the user
j=int(input('how many juveniles are there in generation 0? '))
srj=float(input('what is the survival rate of juveniles '))
break # if the user gives a number then break the loop
except ValueError: #if the user does not give a number then the user will be told to retry
print("Sorry, there was an error. Please enter a positive number")
</code></pre>
| -3 |
2016-09-11T19:23:07Z
| 39,439,852 |
<p>put the if statement <code>if srj > 1 or srj < 0:gen0()</code> before the <code>break</code> line<br>
:^)</p>
| -1 |
2016-09-11T19:27:38Z
|
[
"python",
"while-loop"
] |
how to limit input in while loop need serious looking into
| 39,439,813 |
<p>how can i limit the input for srj imbetween 1 and 0 and it just restarts the whole program</p>
<pre><code>def gen0(): # input all the initial data
while True: # this will loop infinitely if needed
try: # this will try to take a float from the user
j=int(input('how many juveniles are there in generation 0? '))
srj=float(input('what is the survival rate of juveniles '))
break # if the user gives a number then break the loop
except ValueError: #if the user does not give a number then the user will be told to retry
print("Sorry, there was an error. Please enter a positive number")
</code></pre>
| -3 |
2016-09-11T19:23:07Z
| 39,439,887 |
<p>Since you are breaking within a <code>try</code>/<code>except</code>, you can simple <code>raise</code> a <code>ValueError</code> if the data is incorrect.</p>
<pre><code>if srj > 1.0 or srj < 0.0:
raise ValueError
</code></pre>
| 0 |
2016-09-11T19:31:59Z
|
[
"python",
"while-loop"
] |
How can I get auto-indentation to work with Python 2.7 on Xcode 7.3?
| 39,439,814 |
<p>I've used <a href="https://vandadnp.wordpress.com/2014/10/20/building-and-running-python-scripts-with-xcode-6-1/" rel="nofollow">this guide</a> to set up Xcode to build Python scripts. When I press return, the cursor always goes back to the beginning of the new line, even though automatic indenting based on syntax is turned on in the preferences menu. It's frustrating to have to press the space key eight times to get two blocks in indenting in every time. Is there something I haven't installed correctly? I have Anaconda installed and as my build tool if that helps. </p>
| 0 |
2016-09-11T19:23:09Z
| 39,439,995 |
<p>I would suggest running Python on something else imho. Something like PyCharm or IPython. The problem with Xcode is that Python is not one of the native languages for it. So Xcode doesn't know the proper formatting for Pythons syntax.
Not to mention that debugging and other features might not work well on Xcode. </p>
| 0 |
2016-09-11T19:45:24Z
|
[
"python",
"xcode",
"python-2.7"
] |
How to immediately re-raise an exception thrown in any of the worker threads?
| 39,439,868 |
<p>I'm using <code>ThreadPoolExecutor</code> and need to abort the whole computation in case any of the worker threads fails.</p>
<p><strong>Example 1.</strong> This prints <em>Success</em> regardless of the error, since <code>ThreadPoolExecutor</code> does not re-raise exceptions automatically.</p>
<pre><code>from concurrent.futures import ThreadPoolExecutor
def task():
raise ValueError
with ThreadPoolExecutor() as executor:
executor.submit(task)
print('Success')
</code></pre>
<p><strong>Example 2.</strong> This correctly crashes the main thread because <code>.result()</code> re-raises exceptions. But it waits for the first task to finish, so the main thread experiences the exception with a delay.</p>
<pre><code>import time
from concurrent.futures import ThreadPoolExecutor
def task(should_raise):
time.sleep(1)
if should_raise:
raise ValueError
with ThreadPoolExecutor() as executor:
executor.submit(task, False).result()
executor.submit(task, True).result()
print('Success')
</code></pre>
<p>How can I notice a worker exception in the main thread (more or less) immediately after it occurred, to handle the failure and abort the remaining workers?</p>
| 0 |
2016-09-11T19:29:23Z
| 39,440,263 |
<p>I think, I'll implement it like that:</p>
<p>I the main process, I create 2 queues:</p>
<ol>
<li>One to report exceptions,</li>
<li>One to notify cancellation.</li>
</ol>
<p>::</p>
<pre><code>import multiprocessing as mp
error_queue = mp.Queue()
cancel_queue = mp.Queue()
</code></pre>
<p>I create each <code>ThreadPoolExecutor</code>, and pass these queues as parameters.</p>
<pre><code>class MyExecutor(concurrent.futures.ThreadPoolExecutor):
def __init__(self, error_queue, cancel_queue):
self.error_queue : error_queue
self.cancel_queue = cancel_queue
</code></pre>
<p>Each <code>ThreadPoolExecutor</code> has a main loop. In this loop, I first scan the <code>cancel_queue</code> to see if a "cancel" message is available.</p>
<p>In the main loop, I also implement an exception manager. And if an erreur occurs, I raise an exception:</p>
<pre><code>self.status = "running"
with True: # <- or something else
if not self.cancel_queue.empty():
self.status = "cancelled"
break
try:
# normal processing
...
except Exception as exc:
# you can log the exception here for debug
self.error_queue.put(exc)
self.status = "error"
break
time.sleep(.1)
</code></pre>
<p>In the main process:</p>
<p>Run all <code>MyExecutor</code> instance.</p>
<p>Scan the error_queue:</p>
<pre><code>while True:
if not error_queue.empty():
cancel_queue.put("cancel")
time.sleep(.1)
</code></pre>
| 0 |
2016-09-11T20:18:13Z
|
[
"python",
"multithreading",
"python-3.x",
"exception",
"threadpoolexecutor"
] |
How to immediately re-raise an exception thrown in any of the worker threads?
| 39,439,868 |
<p>I'm using <code>ThreadPoolExecutor</code> and need to abort the whole computation in case any of the worker threads fails.</p>
<p><strong>Example 1.</strong> This prints <em>Success</em> regardless of the error, since <code>ThreadPoolExecutor</code> does not re-raise exceptions automatically.</p>
<pre><code>from concurrent.futures import ThreadPoolExecutor
def task():
raise ValueError
with ThreadPoolExecutor() as executor:
executor.submit(task)
print('Success')
</code></pre>
<p><strong>Example 2.</strong> This correctly crashes the main thread because <code>.result()</code> re-raises exceptions. But it waits for the first task to finish, so the main thread experiences the exception with a delay.</p>
<pre><code>import time
from concurrent.futures import ThreadPoolExecutor
def task(should_raise):
time.sleep(1)
if should_raise:
raise ValueError
with ThreadPoolExecutor() as executor:
executor.submit(task, False).result()
executor.submit(task, True).result()
print('Success')
</code></pre>
<p>How can I notice a worker exception in the main thread (more or less) immediately after it occurred, to handle the failure and abort the remaining workers?</p>
| 0 |
2016-09-11T19:29:23Z
| 39,440,411 |
<p>First of all, we have to submit the tasks before requesting their results. Otherwise, the threads are not even running in parallel:</p>
<pre><code>futures = []
with ThreadPoolExecutor() as executor:
futures.append(executor.submit(good_task))
futures.append(executor.submit(bad_task))
for future in futures:
future.result()
</code></pre>
<p>Now we can store the exception information in a variable that is available to both the main thread and the worker threads:</p>
<pre><code>exc_info = None
</code></pre>
<p>The main thread cannot really kill its sub processes, so we have the workers check for the exception information to be set and stop:</p>
<pre><code>def good_task():
global exc_info
while not exc_info:
time.sleep(0.1)
def bad_task():
global exc_info
time.sleep(0.2)
try:
raise ValueError()
except Exception:
exc_info = sys.exc_info()
</code></pre>
<p>After all threads terminated, the main thread can check the variable holding the exception information. If it's populated, we re-raise the exception:</p>
<pre><code>if exc_info:
raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
print('Success')
</code></pre>
| 0 |
2016-09-11T20:36:39Z
|
[
"python",
"multithreading",
"python-3.x",
"exception",
"threadpoolexecutor"
] |
How to handle UTF8 string from Pythons imaplib
| 39,439,967 |
<p>Python imaplib sometimes returns strings that looks like this:</p>
<pre><code>=?utf-8?Q?Repertuar_wydarze=C5=84_z_woj._Dolno=C5=9Bl=C4=85skie?=
</code></pre>
<p>What is the name for this notation?</p>
<p>How can I decode (or should I say encode?) it to UTF8?</p>
| 1 |
2016-09-11T19:41:55Z
| 39,440,002 |
<p><strong>In short:</strong></p>
<pre><code>>>> from email.header import decode_header
>>> msg = decode_header('=?utf-8?Q?Repertuar_wydarze=C5=84_z_woj._Dolno=C5=9Bl=C4=85skie?=')[0][0].decode('utf-8')
>>> msg
'Repertuar wydarze\u0144 z woj. Dolno\u015bl\u0105skie'
</code></pre>
<p>My computer doesn't show the polish characters, but they should appear in yours (locales etc.)</p>
<hr>
<p><strong>Explained:</strong></p>
<p>Use the <code>email.header</code> decoder:</p>
<pre><code>>>> from email.header import decode_header
>>> value = decode_header('=?utf-8?Q?Repertuar_wydarze=C5=84_z_woj._Dolno=C5=9Bl=C4=85skie?=')
>>> value
[(b'Repertuar wydarze\xc5\x84 z woj. Dolno\xc5\x9bl\xc4\x85skie', 'utf-8')]
</code></pre>
<p>That will return a list with the decoded header, usually containing one tuple with the decoded message and the encoding detected (sometimes more than one pair).</p>
<pre><code>>>> msg, encoding = decode_header('=?utf-8?Q?Repertuar_wydarze=C5=84_z_woj._Dolno=C5=9Bl=C4=85skie?=')[0]
>>> msg
b'Repertuar wydarze\xc5\x84 z woj. Dolno\xc5\x9bl\xc4\x85skie'
>>> encoding
'utf-8'
</code></pre>
<p>And finally, if you want <code>msg</code> as a normal utf-8 string, use the bytes <code>decode</code> method:</p>
<pre><code>>>> msg = msg.decode('utf-8')
>>> msg
'Repertuar wydarze\u0144 z woj. Dolno\u015bl\u0105skie'
</code></pre>
| 1 |
2016-09-11T19:46:17Z
|
[
"python",
"utf-8",
"imaplib"
] |
joining two pandas dataframes on date and
| 39,440,004 |
<p>I am trying to join two dataframes however after merging the two dataframes i get NaN for all the columns from one of the DataFrames (Master) but the column heading are there. </p>
<p>Below is the structure of each dataframe</p>
<pre><code>b.columns
Index(['Date', 'Ticker', 'Price'], dtype='object')
Master.columns
Index(['Ticker', 'Date', 'Previous Quarter', 'No. Of Shares', 'Action'], dtype='object')
b.dtypes
Date datetime64[ns]
Ticker object
Price float64
dtype: object
Master.dtypes
Ticker object
Date datetime64[ns]
Previous Quarter int64
No. Of Shares int64
Action object
dtype: object
</code></pre>
<p>i have tried:</p>
<pre><code>M1 = pd.merge(left=b,right=Master, how ='left', left_on=['Date', 'Ticker'], right_on=['Date', 'Ticker'])
</code></pre>
| 0 |
2016-09-11T19:46:36Z
| 39,440,466 |
<p>this might be expected behavior.
you have specified <code>how = 'left'</code> which means you are looking for key combinations from your left dataframe only. If there aren't exact(!) key matches in the right dataframe, you are going to get NaN's in the joined table. You can find more info on this argument <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow">here</a>.</p>
<p>I suspect you have no exact matches in your key columns?</p>
<p>Also, if you specify <code>left_on</code> and <code>right_on</code> to be the same, you might as well only specify <code>on</code>.</p>
| 0 |
2016-09-11T20:44:30Z
|
[
"python",
"pandas"
] |
How to allow Flask-Admin to accept JSON for record creation
| 39,440,048 |
<p>I would like to know if it is possible to use <code>Flask-Admin</code> with the python <code>requests</code> library to create new records in the database from a script. An example would be as such:</p>
<pre><code>import requests
new_userdata = {'username': 'testuser', 'confirmed_at': None, 'login_count': 0, 'last_login_at': None, 'active': False, 'password': 'password', 'current_login_ip': None, 'last_login_ip': None, 'current_login_at': None, 'email': 'test@test.com'}
url = "http://localhost:5000/admin/user/new/"
r = requests.post(url, data=new_userdata, headers={"content-type":"application/json")
</code></pre>
<p>I tried this already, and it <em>does</em> successfully create a new <code>user</code> record in the database, but all the fields in the record are <code>null</code>. Is there a configuration setting that needs to be changed to allow this sort of behavior? I wasn't able to find in the <code>Flask-Admin</code> documentation that discussed this kind of usage.</p>
| -1 |
2016-09-11T19:52:31Z
| 39,440,478 |
<p>You're sending form data, but you're also saying that the content type is JSON. If you were actually sending JSON data, you would either need to call <code>json.dumps</code>, or you would pass <code>json=</code> instead of <code>data=</code>. Just remove the header and send form data, as it's obviously sufficient to handle the data you're sending and Flask-Admin recognizes it.</p>
| 0 |
2016-09-11T20:45:30Z
|
[
"python",
"json",
"flask",
"python-requests",
"flask-admin"
] |
How can I make this code not print an entire list and just a single name and time
| 39,440,090 |
<pre><code>from lxml import html
import requests
page = requests.get('http://www.runningzone.com/wp-content/uploads/2016/09/Turtle-Krawl-Overall-Results-2016.html')
tree = html.fromstring(page.content)
x=2
while True:
xpathName = "/html/body/div[2]/table/tbody/tr['x']/td[4]//text()"
xpathTime = "/html/body/div[2]/table/tbody/tr['x']/td[9]//text()"
name = tree.xpath(xpathName)
time = tree.xpath(xpathTime)
print (name), (time)
x += 1
</code></pre>
<p>So I'm trying to make this print both the person name and time using the xpath. For some reason the code prints out an entire list of both the name and time, even though I'm pretty sure the xpath of the Name and Time should print a single name. If I replace the 'x' part with just a single number, it prints just one name. But if I tell the code to print 'x' where it replacesx with a different number each loop, it just prints huge lists.</p>
| 0 |
2016-09-11T19:58:10Z
| 39,440,144 |
<p><code>'x'</code> does not interpolate the <code>x</code> variable into the string. You need to do something like this:</p>
<pre><code>xpathName = "/html/body/div[2]/table/tbody/tr[%d]/td[4]//text()" % (x,)
xpathTime = "/html/body/div[2]/table/tbody/tr[%d]/td[9]//text()" % (x,)
</code></pre>
<p>Also, as @grael mentioned, you need to terminate your loop somewhere.</p>
| 1 |
2016-09-11T20:04:06Z
|
[
"python"
] |
Use a list or array in Python?
| 39,440,132 |
<p>I need to store information for 6 items and their respective length, width and cost values and then work out some values based on user input.</p>
<p>With the help of jcusick, I have now the code below. </p>
<p>I now need help for the items marked in the comments (#).</p>
<p>You do not need to write the complete code - pointing in right direction is perfect. </p>
<p>So far I have:</p>
<pre><code>cost = {}
cost['Themon'] = 450
cost['Larrec'] = 700
cost['Medrec'] = 500
cost['Parallel'] = 825
cost['Suncatch'] = 400
cost['Chantran'] = 975
length = {}
length['Themon'] = 3.2
length['Larrec'] = 3.4
length['Medrec'] = 2.1
length['Parallel'] = 5
length['Suncatch'] = 3
length['Chantran'] = 9
width = {}
width['Themon'] = 2.3
width['Larrec'] = 3
width['Medrec'] = 2
width['Parallel'] = 4
width['Suncatch'] = 3
width['Chantran'] = 6
area = {}
area['Themon'] = 1 # how do i calculate the area (l*w) by referencing the lenght and width dictionary
area['Larrec'] = 1
area['Medrec'] = 1
area['Parallel'] = 1
area['Suncatch'] = 1
area['Chantran'] = 1
#menu
ans=True
while ans:
print("""
Enter 1. to find cheapest garden deck
Enter 2. to display the names of garden decks over a certain lenght
Enter 3. to display the number of garden decks that are available over a certain area
Enter 4. to quit
""")
ans=input("What option would you like? ")
if ans=="1":
print (min(cost, key=cost.get))
elif ans=="2":
input_length = input("\n Please enter minimum deck length between 2 and 15 metres")
print # i need to display names of the decks greater than the user input length
elif ans=="3":
input_area = input("\n Please enter deck area in metres squared between 4 and 80")
print # i need to display the number of garden decks that are greater that the user input area
elif ans=="4":
print("\n Thank you for using Penny's Decking")
else:
print("\n Not a valid choice")
</code></pre>
| 0 |
2016-09-11T20:02:30Z
| 39,440,196 |
<p>I might consider creating a <a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionary</a> for each of the variables your are interested in (length, width, cost). Then you could always query the specific dictionary depending on what the user answers:</p>
<pre><code>cost = {}
cost['Themon'] = 450
cost['Larrec'] = 700
...
print (min(cost, key=cost.get))
# 'Themon'
</code></pre>
| 1 |
2016-09-11T20:11:18Z
|
[
"python",
"python-3.x"
] |
Use a list or array in Python?
| 39,440,132 |
<p>I need to store information for 6 items and their respective length, width and cost values and then work out some values based on user input.</p>
<p>With the help of jcusick, I have now the code below. </p>
<p>I now need help for the items marked in the comments (#).</p>
<p>You do not need to write the complete code - pointing in right direction is perfect. </p>
<p>So far I have:</p>
<pre><code>cost = {}
cost['Themon'] = 450
cost['Larrec'] = 700
cost['Medrec'] = 500
cost['Parallel'] = 825
cost['Suncatch'] = 400
cost['Chantran'] = 975
length = {}
length['Themon'] = 3.2
length['Larrec'] = 3.4
length['Medrec'] = 2.1
length['Parallel'] = 5
length['Suncatch'] = 3
length['Chantran'] = 9
width = {}
width['Themon'] = 2.3
width['Larrec'] = 3
width['Medrec'] = 2
width['Parallel'] = 4
width['Suncatch'] = 3
width['Chantran'] = 6
area = {}
area['Themon'] = 1 # how do i calculate the area (l*w) by referencing the lenght and width dictionary
area['Larrec'] = 1
area['Medrec'] = 1
area['Parallel'] = 1
area['Suncatch'] = 1
area['Chantran'] = 1
#menu
ans=True
while ans:
print("""
Enter 1. to find cheapest garden deck
Enter 2. to display the names of garden decks over a certain lenght
Enter 3. to display the number of garden decks that are available over a certain area
Enter 4. to quit
""")
ans=input("What option would you like? ")
if ans=="1":
print (min(cost, key=cost.get))
elif ans=="2":
input_length = input("\n Please enter minimum deck length between 2 and 15 metres")
print # i need to display names of the decks greater than the user input length
elif ans=="3":
input_area = input("\n Please enter deck area in metres squared between 4 and 80")
print # i need to display the number of garden decks that are greater that the user input area
elif ans=="4":
print("\n Thank you for using Penny's Decking")
else:
print("\n Not a valid choice")
</code></pre>
| 0 |
2016-09-11T20:02:30Z
| 39,440,265 |
<p>I would suggest you look into Pandas and implement this more specifically using DataFrames as they are perfect for what you are doing. Like mentioned by the other guys. Make sure your indentations are formatted correctly. If you don't want to use DataFrames which imho are perfect for what you are doing. I would suggest creating a dictionary of values and referencing them. </p>
| 0 |
2016-09-11T20:18:29Z
|
[
"python",
"python-3.x"
] |
Use a list or array in Python?
| 39,440,132 |
<p>I need to store information for 6 items and their respective length, width and cost values and then work out some values based on user input.</p>
<p>With the help of jcusick, I have now the code below. </p>
<p>I now need help for the items marked in the comments (#).</p>
<p>You do not need to write the complete code - pointing in right direction is perfect. </p>
<p>So far I have:</p>
<pre><code>cost = {}
cost['Themon'] = 450
cost['Larrec'] = 700
cost['Medrec'] = 500
cost['Parallel'] = 825
cost['Suncatch'] = 400
cost['Chantran'] = 975
length = {}
length['Themon'] = 3.2
length['Larrec'] = 3.4
length['Medrec'] = 2.1
length['Parallel'] = 5
length['Suncatch'] = 3
length['Chantran'] = 9
width = {}
width['Themon'] = 2.3
width['Larrec'] = 3
width['Medrec'] = 2
width['Parallel'] = 4
width['Suncatch'] = 3
width['Chantran'] = 6
area = {}
area['Themon'] = 1 # how do i calculate the area (l*w) by referencing the lenght and width dictionary
area['Larrec'] = 1
area['Medrec'] = 1
area['Parallel'] = 1
area['Suncatch'] = 1
area['Chantran'] = 1
#menu
ans=True
while ans:
print("""
Enter 1. to find cheapest garden deck
Enter 2. to display the names of garden decks over a certain lenght
Enter 3. to display the number of garden decks that are available over a certain area
Enter 4. to quit
""")
ans=input("What option would you like? ")
if ans=="1":
print (min(cost, key=cost.get))
elif ans=="2":
input_length = input("\n Please enter minimum deck length between 2 and 15 metres")
print # i need to display names of the decks greater than the user input length
elif ans=="3":
input_area = input("\n Please enter deck area in metres squared between 4 and 80")
print # i need to display the number of garden decks that are greater that the user input area
elif ans=="4":
print("\n Thank you for using Penny's Decking")
else:
print("\n Not a valid choice")
</code></pre>
| 0 |
2016-09-11T20:02:30Z
| 39,440,667 |
<p>I think pandas might be overkill for a small piece of code like this. For your particular example, arrays would be a faster storage method. I would go so far as to say, though, that a list is probably the more pythonic way to handle this particular scale. Your performance won't be terribly affected either way here, and it's slightly more readable now, rather than using an array. </p>
<p>For further reading, sometimes a namedtuple can be helpful in larger scale examples in which you keep, and access, records:
<a href="https://docs.python.org/3/library/collections.html#collections.namedtuple" rel="nofollow">https://docs.python.org/3/library/collections.html#collections.namedtuple</a></p>
| 1 |
2016-09-11T21:07:52Z
|
[
"python",
"python-3.x"
] |
parsing a large json file and retrieving values in python
| 39,440,146 |
<p>I have one large json file of the format - </p>
<pre><code>{
"x": "",
"y": {
"a": {
"-3": {
"id": -2,
"rut": "abc",
},
"-1": {
"id": -1,
"rut": "cdf",
}
}
}
}
</code></pre>
<p>Now I want to retrieve the values of <code>id</code> for all situations.
For this I have the following code -</p>
<pre><code>import json
from pprint import pprint
with open('file.json') as data_file:
data = json.load(data_file)
data['y']['a'].value()['id']
</code></pre>
<p>Since I'm not too familiar with using json in python, I couldn't figure out what I was doing wrong. I used <code>.value()</code> because the values <code>-3</code> and <code>-1</code> could be <b> any number </b> and are not known before hand. The rest of the values are constant. </p>
| 0 |
2016-09-11T20:04:34Z
| 39,440,193 |
<p>import json
from pprint import pprint</p>
<pre><code>with open('file.json') as data_file:
data = json.load(data_file)
pprint([item['id'] for item in data['y']['a'].values()])
</code></pre>
<p>Is it what you are looking for?</p>
| 2 |
2016-09-11T20:10:57Z
|
[
"python",
"json"
] |
parsing a large json file and retrieving values in python
| 39,440,146 |
<p>I have one large json file of the format - </p>
<pre><code>{
"x": "",
"y": {
"a": {
"-3": {
"id": -2,
"rut": "abc",
},
"-1": {
"id": -1,
"rut": "cdf",
}
}
}
}
</code></pre>
<p>Now I want to retrieve the values of <code>id</code> for all situations.
For this I have the following code -</p>
<pre><code>import json
from pprint import pprint
with open('file.json') as data_file:
data = json.load(data_file)
data['y']['a'].value()['id']
</code></pre>
<p>Since I'm not too familiar with using json in python, I couldn't figure out what I was doing wrong. I used <code>.value()</code> because the values <code>-3</code> and <code>-1</code> could be <b> any number </b> and are not known before hand. The rest of the values are constant. </p>
| 0 |
2016-09-11T20:04:34Z
| 39,440,199 |
<p>It is a bit unclear what your problem/error is, but my gess is that you want to simply iterate over all the available values to get your 'id' fields. It would look something like that:</p>
<pre><code>for x in data['y']['a']:
try:
print(x['id'])
except IndexError: #In case 'id' isn't present in that subtree
pass
</code></pre>
| 1 |
2016-09-11T20:11:40Z
|
[
"python",
"json"
] |
parsing a large json file and retrieving values in python
| 39,440,146 |
<p>I have one large json file of the format - </p>
<pre><code>{
"x": "",
"y": {
"a": {
"-3": {
"id": -2,
"rut": "abc",
},
"-1": {
"id": -1,
"rut": "cdf",
}
}
}
}
</code></pre>
<p>Now I want to retrieve the values of <code>id</code> for all situations.
For this I have the following code -</p>
<pre><code>import json
from pprint import pprint
with open('file.json') as data_file:
data = json.load(data_file)
data['y']['a'].value()['id']
</code></pre>
<p>Since I'm not too familiar with using json in python, I couldn't figure out what I was doing wrong. I used <code>.value()</code> because the values <code>-3</code> and <code>-1</code> could be <b> any number </b> and are not known before hand. The rest of the values are constant. </p>
| 0 |
2016-09-11T20:04:34Z
| 39,440,320 |
<p>Did you mean to use values() ?</p>
<p>However, to get the all 'id's:</p>
<pre><code>sub_data = data['y']['a']
for i in sub_data:
print(sub_data['id'])
</code></pre>
| 0 |
2016-09-11T20:26:38Z
|
[
"python",
"json"
] |
Error while saving image using Django Rest Framework with angularjs
| 39,440,153 |
<p>I have two models Blogs, Photo. In Photo model I have fields 'blogs' as foreign key to Blogs model.</p>
<p>models.py:</p>
<pre><code>def content_file_name(instance, filename):
custt=str(datetime.now())
return '/'.join(['content', instance.blogs.slug,custt, filename])
class Photo(models.Model):
blogs = models.ForeignKey(Blogs)
image = models.ImageField(upload_to=content_file_name)
class Blogs(models.Model):
author = models.ForeignKey(CustomUser)
title=models.CharField(max_length=100)
postedin=models.ForeignKey(Posted)
tags= models.ManyToManyField(Tags)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
slug=models.SlugField(max_length=255,unique=True)
def __unicode__(self):
return '{0}'.format(self.title)
</code></pre>
<p>views.py:</p>
<pre><code>class PhotoViewSet(viewsets.ModelViewSet):
queryset=Photo.objects.all()
serializer_class = PhotoSerializer
def perform_create(self,serializer):
serializer.save(blogs=Blogs.objects.latest('id'))
return super(PhotoViewSet,self).perform_create(serializer)
</code></pre>
<p>serializers.py:</p>
<pre><code>class PhotoSerializer(serializers.ModelSerializer):
image = serializers.ImageField(
max_length=None, use_url=True,
)
class Meta:
model = Photo
read_only_fields = ("blogs",)
</code></pre>
<p>js:</p>
<pre><code>function uploadpic(image) {
var fd = new FormData();
fd.append( 'image', image );
return $http.post('/api/v1/uploadpic/',fd, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
});
}
</code></pre>
<p>result:</p>
<p>{image: ["No file was submitted."]}</p>
<p>Also I want to know, is there a better way to get blogs value (Foreign Key) for Photo Model.</p>
| 0 |
2016-09-11T20:05:19Z
| 39,481,410 |
<p>In js:</p>
<pre><code>headers: { 'Content-Type': undefined}
</code></pre>
<p>This solves the problem.</p>
| 0 |
2016-09-14T01:58:20Z
|
[
"python",
"angularjs",
"django",
"django-rest-framework"
] |
Django Form - Passing Values
| 39,440,219 |
<p>I have the following form and can't seem to use the "self.currentSelectedTeam1" as the initial value for team1 as can be seen at the bottom. When I do try this I get the following error:</p>
<pre><code>team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,initial=self.curentSelectedTeam1)
NameError: name 'self' is not defined
</code></pre>
<p>Form:</p>
<pre><code>class SelectTwoTeams(BootstrapForm):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
self.curentSelectedTeam1 = kwargs.pop('curentSelectedTeam1', None)
self.curentSelectedTeam2 = kwargs.pop('curentSelectedTeam2', None)
super(SelectTwoTeams, self).__init__(*args, **kwargs)
queryset = StraightredTeam.objects.filter(currentteam = 1)
self.fields['team1'].queryset = queryset
self.fields['team2'].queryset = queryset
team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,initial=self.curentSelectedTeam1)
team2 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,initial=self.curentSelectedTeam2)
</code></pre>
<p>Many thanks in advance for any help, Alan.</p>
| 0 |
2016-09-11T20:13:50Z
| 39,440,260 |
<p>This doesn't work becasue the fields <code>team1</code> and <code>team2</code> are created before <code>__init__</code> is called because they're instance members.</p>
<p>This means that <code>self.curentSelectedTeam1</code> and <code>self.curentSelectedTeam2</code> aren't available yet and are most likely <code>None</code>.</p>
<p>In order to set initial values on the form, you need to do so when you instantiate the form itself.</p>
<pre><code>team1_pk = 0
team2_pk = 1
form = SelectTwoTeams(initial={'curentSelectedTeam1': team1_pk, 'curentSelectedTeam2': team2_pk})
</code></pre>
<p>You'll need to either remove your current <code>__init__</code> override or call <code>super()</code> to allow the initial values to be passed to the form's default constructor.</p>
| 2 |
2016-09-11T20:18:06Z
|
[
"python",
"django"
] |
Django Form - Passing Values
| 39,440,219 |
<p>I have the following form and can't seem to use the "self.currentSelectedTeam1" as the initial value for team1 as can be seen at the bottom. When I do try this I get the following error:</p>
<pre><code>team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,initial=self.curentSelectedTeam1)
NameError: name 'self' is not defined
</code></pre>
<p>Form:</p>
<pre><code>class SelectTwoTeams(BootstrapForm):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
self.curentSelectedTeam1 = kwargs.pop('curentSelectedTeam1', None)
self.curentSelectedTeam2 = kwargs.pop('curentSelectedTeam2', None)
super(SelectTwoTeams, self).__init__(*args, **kwargs)
queryset = StraightredTeam.objects.filter(currentteam = 1)
self.fields['team1'].queryset = queryset
self.fields['team2'].queryset = queryset
team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,initial=self.curentSelectedTeam1)
team2 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None,initial=self.curentSelectedTeam2)
</code></pre>
<p>Many thanks in advance for any help, Alan.</p>
| 0 |
2016-09-11T20:13:50Z
| 39,440,271 |
<p>The problem is in <code>self</code> keyword in team1 and team2 variables.
The thing is they are on the class-level, and the self is available on the instance level(inside methods, excluding static methods and class methods)</p>
<p>To make it work you need to do the same with <code>self.fields['team1'].queryset</code>:</p>
<pre><code>self.fields['team1'].initial = self.curentSelectedTeam1
</code></pre>
<p>inside <code>__init__</code> method.</p>
| 2 |
2016-09-11T20:19:20Z
|
[
"python",
"django"
] |
How to return a string from pandas.DataFrame.info()
| 39,440,253 |
<p>I would like to display the output from <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.info.html" rel="nofollow"><code>pandas.DataFrame.info()</code></a> on a <code>tkinter</code> text widget so I need a string. However <code>pandas.DataFrame.info()</code> returns <code>NoneType</code> is there anyway I can change this?</p>
<pre><code>import pandas as pd
import numpy as np
data = np.random.rand(10).reshape(5,2)
cols = 'a', 'b'
df = pd.DataFrame(data, columns=cols)
df_info = df.info()
print(df_info)
type(df_info)
</code></pre>
<p>I'd like to do something like:</p>
<pre><code>info_str = ""
df_info = df.info(buf=info_str)
</code></pre>
<p>Is it possible to get <code>pandas</code> to return a string object from <code>DataFrame.info()</code>?</p>
| 2 |
2016-09-11T20:17:36Z
| 39,440,325 |
<p>In the documentation you linked, there's a <code>buf</code> argument:</p>
<blockquote>
<p>buf : writable buffer, defaults to sys.stdout</p>
</blockquote>
<p>So one option would be to pass a StringIO instance:</p>
<pre><code>>>> import io
>>> buf = io.StringIO()
>>> df.info(buf=buf)
>>> s = buf.getvalue()
>>> type(s)
<class 'str'>
>>> print(s)
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 2 columns):
a 5 non-null float64
b 5 non-null float64
dtypes: float64(2)
memory usage: 160.0 bytes
</code></pre>
| 4 |
2016-09-11T20:27:40Z
|
[
"python",
"pandas"
] |
Replacing an item in list with items of another list without using dictionaries
| 39,440,360 |
<p>I am developing a function in python. Here is my content:</p>
<pre><code>list = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']
</code></pre>
<p>So I want that my list becomes like this after replacement</p>
<pre><code>list = ['cow','banana','cream','mango']
</code></pre>
<p>I am using this function:</p>
<pre><code>def replace_item(list, to_replace, replace_with):
for n,i in enumerate(list):
if i== to_replace:
list[n]=replace_with
return list
</code></pre>
<p>It outputs the list like this:</p>
<pre><code>['cow', ['banana', 'cream'], 'mango']
</code></pre>
<p>So how do I modify this function to get the below output?</p>
<pre><code>list = ['cow','banana','cream','mango']
</code></pre>
<p>NOTE: I found an answer here: <a href="http://stackoverflow.com/questions/14962931/replacing-list-item-with-contents-of-another-list">Replacing list item with contents of another list</a>
but I don't want to involve dictionaries in this. I also want to modify my current function only and keep it simple and straight forward.</p>
| 4 |
2016-09-11T20:30:54Z
| 39,440,392 |
<p>First off, never use python built-in names and keywords as your variable names. (change the <code>list</code> to <code>ls</code>)</p>
<p>You don't need loop, find the index then chain the slices:</p>
<pre><code>In [107]: from itertools import chain
In [108]: ls = ['cow','orange','mango']
In [109]: to_replace = 'orange'
In [110]: replace_with = ['banana','cream']
In [112]: idx = ls.index(to_replace)
In [116]: list(chain(ls[:idx], replace_with, ls[idx+1:]))
Out[116]: ['cow', 'banana', 'cream', 'mango']
</code></pre>
<p>In pyhton 3.5+ you can use in-place unpacking:</p>
<pre><code>[*ls[:idx], *replace_with, *ls[idx+1:]]
</code></pre>
| 3 |
2016-09-11T20:34:43Z
|
[
"python",
"list"
] |
Replacing an item in list with items of another list without using dictionaries
| 39,440,360 |
<p>I am developing a function in python. Here is my content:</p>
<pre><code>list = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']
</code></pre>
<p>So I want that my list becomes like this after replacement</p>
<pre><code>list = ['cow','banana','cream','mango']
</code></pre>
<p>I am using this function:</p>
<pre><code>def replace_item(list, to_replace, replace_with):
for n,i in enumerate(list):
if i== to_replace:
list[n]=replace_with
return list
</code></pre>
<p>It outputs the list like this:</p>
<pre><code>['cow', ['banana', 'cream'], 'mango']
</code></pre>
<p>So how do I modify this function to get the below output?</p>
<pre><code>list = ['cow','banana','cream','mango']
</code></pre>
<p>NOTE: I found an answer here: <a href="http://stackoverflow.com/questions/14962931/replacing-list-item-with-contents-of-another-list">Replacing list item with contents of another list</a>
but I don't want to involve dictionaries in this. I also want to modify my current function only and keep it simple and straight forward.</p>
| 4 |
2016-09-11T20:30:54Z
| 39,440,428 |
<pre><code>def replace_item(list, to_replace, replace_with):
index = list.index(to_replace) # the index where should be replaced
list.pop(index) # pop it out
for value_to_add in reversed(replace_with):
list.insert(index, value_to_add) # insert the new value at the right place
return list
</code></pre>
| -1 |
2016-09-11T20:39:01Z
|
[
"python",
"list"
] |
Replacing an item in list with items of another list without using dictionaries
| 39,440,360 |
<p>I am developing a function in python. Here is my content:</p>
<pre><code>list = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']
</code></pre>
<p>So I want that my list becomes like this after replacement</p>
<pre><code>list = ['cow','banana','cream','mango']
</code></pre>
<p>I am using this function:</p>
<pre><code>def replace_item(list, to_replace, replace_with):
for n,i in enumerate(list):
if i== to_replace:
list[n]=replace_with
return list
</code></pre>
<p>It outputs the list like this:</p>
<pre><code>['cow', ['banana', 'cream'], 'mango']
</code></pre>
<p>So how do I modify this function to get the below output?</p>
<pre><code>list = ['cow','banana','cream','mango']
</code></pre>
<p>NOTE: I found an answer here: <a href="http://stackoverflow.com/questions/14962931/replacing-list-item-with-contents-of-another-list">Replacing list item with contents of another list</a>
but I don't want to involve dictionaries in this. I also want to modify my current function only and keep it simple and straight forward.</p>
| 4 |
2016-09-11T20:30:54Z
| 39,440,477 |
<p>This approach is fairly simple and has similar performance to @TadhgMcDonald-Jensen's <code>iter_replace()</code> approach (3.6 µs for me):</p>
<pre><code>lst = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']
def replace_item(lst, to_replace, replace_with):
return sum((replace_with if i==to_replace else [i] for i in lst), [])
print replace_item(lst, to_replace, replace_with)
# ['cow', 'banana', 'cream', 'mango']
</code></pre>
<p>Here's something similar using itertools, but it is slower (5.3 µs):</p>
<pre><code>import itertools
def replace_item(lst, to_replace, replace_with):
return list(itertools.chain.from_iterable(
replace_with if i==to_replace else [i] for i in lst
))
</code></pre>
<p>Or, here's a faster approach using a two-level list comprehension (1.8 µs):</p>
<pre><code>def replace_item(lst, to_replace, replace_with):
return [j for i in lst for j in (replace_with if i==to_replace else [i])]
</code></pre>
<p>Or here's a simple, readable version that is fastest of all (1.2 µs):</p>
<pre><code>def replace_item(lst, to_replace, replace_with):
result = []
for i in lst:
if i == to_replace:
result.extend(replace_with)
else:
result.append(i)
return result
</code></pre>
<p>Unlike some answers here, these will do multiple replacements if there are multiple matching items. They are also more efficient than reversing the list or repeatedly inserting values into an existing list (python rewrites the remainder of the list each time you do that, but this only rewrites the list once).</p>
| 5 |
2016-09-11T20:45:23Z
|
[
"python",
"list"
] |
Replacing an item in list with items of another list without using dictionaries
| 39,440,360 |
<p>I am developing a function in python. Here is my content:</p>
<pre><code>list = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']
</code></pre>
<p>So I want that my list becomes like this after replacement</p>
<pre><code>list = ['cow','banana','cream','mango']
</code></pre>
<p>I am using this function:</p>
<pre><code>def replace_item(list, to_replace, replace_with):
for n,i in enumerate(list):
if i== to_replace:
list[n]=replace_with
return list
</code></pre>
<p>It outputs the list like this:</p>
<pre><code>['cow', ['banana', 'cream'], 'mango']
</code></pre>
<p>So how do I modify this function to get the below output?</p>
<pre><code>list = ['cow','banana','cream','mango']
</code></pre>
<p>NOTE: I found an answer here: <a href="http://stackoverflow.com/questions/14962931/replacing-list-item-with-contents-of-another-list">Replacing list item with contents of another list</a>
but I don't want to involve dictionaries in this. I also want to modify my current function only and keep it simple and straight forward.</p>
| 4 |
2016-09-11T20:30:54Z
| 39,440,524 |
<p>Modifying a list whilst iterating through it is usually problematic because the indices shift around. I recommend to abandon the approach of using a for-loop.</p>
<p>This is one of the few cases where a <code>while</code> loop can be clearer and simpler than a <code>for</code> loop:</p>
<pre><code>>>> list_ = ['cow','orange','mango']
>>> to_replace = 'orange'
>>> replace_with = ['banana','cream']
>>> while True:
... try:
... i = list_.index(to_replace)
... except ValueError:
... break
... else:
... list_[i:i+1] = replace_with
...
>>> list_
['cow', 'banana', 'cream', 'mango']
</code></pre>
| 5 |
2016-09-11T20:51:32Z
|
[
"python",
"list"
] |
Replacing an item in list with items of another list without using dictionaries
| 39,440,360 |
<p>I am developing a function in python. Here is my content:</p>
<pre><code>list = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']
</code></pre>
<p>So I want that my list becomes like this after replacement</p>
<pre><code>list = ['cow','banana','cream','mango']
</code></pre>
<p>I am using this function:</p>
<pre><code>def replace_item(list, to_replace, replace_with):
for n,i in enumerate(list):
if i== to_replace:
list[n]=replace_with
return list
</code></pre>
<p>It outputs the list like this:</p>
<pre><code>['cow', ['banana', 'cream'], 'mango']
</code></pre>
<p>So how do I modify this function to get the below output?</p>
<pre><code>list = ['cow','banana','cream','mango']
</code></pre>
<p>NOTE: I found an answer here: <a href="http://stackoverflow.com/questions/14962931/replacing-list-item-with-contents-of-another-list">Replacing list item with contents of another list</a>
but I don't want to involve dictionaries in this. I also want to modify my current function only and keep it simple and straight forward.</p>
| 4 |
2016-09-11T20:30:54Z
| 39,440,668 |
<p>A simple way of representing a rule like this is with a generator, when the <code>to_replace</code> is seen different items are produced:</p>
<pre><code>def iter_replace(iterable, to_replace, replace_with):
for item in iterable:
if item == to_replace:
yield from replace_with
else:
yield item
</code></pre>
<p>Then you can do <code>list(iter_replace(...))</code> to get the result you want, as long as you don't shadow the name <code>list</code>. </p>
<pre><code>ls = ['cow','orange','mango']
to_replace = 'orange'
replace_with = ['banana','cream']
print(list(iter_replace(ls,to_replace,replace_with)))
# ['cow', 'banana', 'cream', 'mango']
</code></pre>
| 3 |
2016-09-11T21:08:14Z
|
[
"python",
"list"
] |
Process finished with exit code 0
| 39,440,518 |
<p>I have this:</p>
<pre><code>import math
class Point:
def move(self, x, y):
self.x = x
self.y = y
def reset(self):
self.move(0, 0)
def calculate_distance(self, other_point):
return math.sqrt(
(self.x - other_point.x)**2 +(self.y - other_point.y)**2)
# how to use it:
point1 = Point()
point2 = Point()
point1.reset()
point2.move(5,0)
print(point2.calculate_distance(point1))
assert (point2.calculate_distance(point1) == point1.calculate_distance(point2))
point1.move(3,4)
print(point1.calculate_distance(point2))
print(point1.calculate_distance(point1))
</code></pre>
<p>So I expect that it prints like this:</p>
<pre><code>5.0
4.472135955
0.0
</code></pre>
<p>But In pycharm in the console it only prints this:</p>
<pre><code>Process finished with exit code 0
</code></pre>
<p>Where you can see the output?</p>
<p>I also add a attachment for clearness.</p>
<p>Thank you</p>
<p><a href="http://i.stack.imgur.com/QNO7l.png" rel="nofollow"><img src="http://i.stack.imgur.com/QNO7l.png" alt="enter image description here"></a></p>
| 1 |
2016-09-11T20:51:09Z
| 39,440,611 |
<p>There is a window called "python console". The output of your script should be there...</p>
| 0 |
2016-09-11T21:00:36Z
|
[
"python"
] |
Process finished with exit code 0
| 39,440,518 |
<p>I have this:</p>
<pre><code>import math
class Point:
def move(self, x, y):
self.x = x
self.y = y
def reset(self):
self.move(0, 0)
def calculate_distance(self, other_point):
return math.sqrt(
(self.x - other_point.x)**2 +(self.y - other_point.y)**2)
# how to use it:
point1 = Point()
point2 = Point()
point1.reset()
point2.move(5,0)
print(point2.calculate_distance(point1))
assert (point2.calculate_distance(point1) == point1.calculate_distance(point2))
point1.move(3,4)
print(point1.calculate_distance(point2))
print(point1.calculate_distance(point1))
</code></pre>
<p>So I expect that it prints like this:</p>
<pre><code>5.0
4.472135955
0.0
</code></pre>
<p>But In pycharm in the console it only prints this:</p>
<pre><code>Process finished with exit code 0
</code></pre>
<p>Where you can see the output?</p>
<p>I also add a attachment for clearness.</p>
<p>Thank you</p>
<p><a href="http://i.stack.imgur.com/QNO7l.png" rel="nofollow"><img src="http://i.stack.imgur.com/QNO7l.png" alt="enter image description here"></a></p>
| 1 |
2016-09-11T20:51:09Z
| 39,440,635 |
<p>Try this:</p>
<pre><code>import math
class Point:
def move(self, x, y):
self.x = x
self.y = y
def reset(self):
self.move(0, 0)
def calculate_distance(self, other_point):
return math.sqrt((self.x - other_point.x)**2 +(self.y - other_point.y)**2)
# how to use it:
point1 = Point()
point2 = Point()
point1.reset()
point2.move(5,0)
print(point2.calculate_distance(point1))
assert (point2.calculate_distance(point1) == point1.calculate_distance(point2))
point1.move(3,4)
print(point1.calculate_distance(point2))
print(point1.calculate_distance(point1))
</code></pre>
| 2 |
2016-09-11T21:03:46Z
|
[
"python"
] |
Python-flask: How to redirect and then do task?
| 39,440,533 |
<p>Suppose you these functions where a is some function that takes a while to do.</p>
<pre><code>def a():
sleep(5)
return True
@app.route('/')
def b():
a()
return flask.redirect("http://someurl.com")
</code></pre>
<p>How would you get the same functionality but redirect first, then do the function? I'm using Heroku, and I don't want to have to completely restructure my code if I can help it.</p>
| -1 |
2016-09-11T20:52:23Z
| 39,536,565 |
<p>Once you return a method (redirect in this case) it just dies, it can't keep running any code.</p>
<p>The only possible way to do this is to run the long task asynchronously. A very popular framework often used for this purpose is Celery. Check out their <a href="http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html" rel="nofollow">tutorial here</a>. Here's a <a href="http://flask.pocoo.org/docs/0.11/patterns/celery/" rel="nofollow">super quick introduction</a> for using it with flask.</p>
<p>Note that you will need to run a separate service called a message broker for celery tu run. You can find details on it on the tutorial previously linked, but a quick solution and recommendation I can give from personal experience is to setup a Redis server with default configuration and it will just work.</p>
<p>Once you have everything running, you will first define your task with something like this:</p>
<pre><code>@celery.task()
def a():
sleep(5)
return True
</code></pre>
<p>And then you will trigger the task this way:</p>
<pre><code>def b():
a.delay()
return flask.redirect("http://someurl.com")
</code></pre>
<p>Hope that helps get you started with Celery.</p>
| 0 |
2016-09-16T16:51:23Z
|
[
"python",
"asynchronous",
"flask"
] |
Matrix to Vector with python/numpy
| 39,440,633 |
<p>Numpy <code>ravel</code> works well if I need to create a vector by reading by rows or by columns. However, I would like to transform a matrix to a 1d array, by using a method that is often used in image processing. This is an example with initial matrix <code>A</code> and final result <code>B</code>:</p>
<pre><code>A = np.array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
B = np.array([[ 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15])
</code></pre>
<p>Is there an existing function already that could help me with that? If not, can you give me some hints on how to solve this problem? PS. the matrix <code>A</code> is <code>NxN</code>.</p>
| 1 |
2016-09-11T21:03:35Z
| 39,440,945 |
<p>I've been using numpy for several years, and I've never seen such a function.</p>
<p>Here's one way you could do it (not necessarily the most efficient):</p>
<pre><code>In [47]: a
Out[47]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
In [48]: np.concatenate([np.diagonal(a[::-1,:], k)[::(2*(k % 2)-1)] for k in range(1-a.shape[0], a.shape[0])])
Out[48]: array([ 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15])
</code></pre>
<p>Breaking down the one-liner into separate steps:</p>
<p><code>a[::-1, :]</code> reverses the rows:</p>
<pre><code>In [59]: a[::-1, :]
Out[59]:
array([[12, 13, 14, 15],
[ 8, 9, 10, 11],
[ 4, 5, 6, 7],
[ 0, 1, 2, 3]])
</code></pre>
<p>(This could also be written <code>a[::-1]</code> or <code>np.flipud(a)</code>.)</p>
<p><code>np.diagonal(a, k)</code> extracts the <code>k</code>th diagonal, where <code>k=0</code> is the main diagonal. So, for example,</p>
<pre><code>In [65]: np.diagonal(a[::-1, :], -3)
Out[65]: array([0])
In [66]: np.diagonal(a[::-1, :], -2)
Out[66]: array([4, 1])
In [67]: np.diagonal(a[::-1, :], 0)
Out[67]: array([12, 9, 6, 3])
In [68]: np.diagonal(a[::-1, :], 2)
Out[68]: array([14, 11])
</code></pre>
<p>In the list comprehension, <code>k</code> gives the diagonal to be extracted. We want to reverse the elements in every other diagonal. The expression <code>2*(k % 2) - 1</code> gives the values 1, -1, 1, ... as <code>k</code> varies from -3 to 3. Indexing with <code>[::1]</code> leaves the order of the array being indexed unchanged, and indexing with <code>[::-1]</code> reverses the order of the array. So <code>np.diagonal(a[::-1, :], k)[::(2*(k % 2)-1)]</code> gives the <code>k</code>th diagonal, but with every other diagonal reversed:</p>
<pre><code>In [71]: [np.diagonal(a[::-1,:], k)[::(2*(k % 2)-1)] for k in range(1-a.shape[0], a.shape[0])]
Out[71]:
[array([0]),
array([1, 4]),
array([8, 5, 2]),
array([ 3, 6, 9, 12]),
array([13, 10, 7]),
array([11, 14]),
array([15])]
</code></pre>
<p><code>np.concatenate()</code> puts them all into a single array:</p>
<pre><code>In [72]: np.concatenate([np.diagonal(a[::-1,:], k)[::(2*(k % 2)-1)] for k in range(1-a.shape[0], a.shape[0])])
Out[72]: array([ 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15])
</code></pre>
| 3 |
2016-09-11T21:45:46Z
|
[
"python",
"numpy"
] |
Matrix to Vector with python/numpy
| 39,440,633 |
<p>Numpy <code>ravel</code> works well if I need to create a vector by reading by rows or by columns. However, I would like to transform a matrix to a 1d array, by using a method that is often used in image processing. This is an example with initial matrix <code>A</code> and final result <code>B</code>:</p>
<pre><code>A = np.array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
B = np.array([[ 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15])
</code></pre>
<p>Is there an existing function already that could help me with that? If not, can you give me some hints on how to solve this problem? PS. the matrix <code>A</code> is <code>NxN</code>.</p>
| 1 |
2016-09-11T21:03:35Z
| 39,440,952 |
<p>I found discussion of zigzag scan for MATLAB, but not much for <code>numpy</code>. One project appears to use a hardcoded indexing array for 8x8 blocks</p>
<p><a href="https://github.com/lot9s/lfv-compression/blob/master/scripts/our_mpeg/zigzag.py" rel="nofollow">https://github.com/lot9s/lfv-compression/blob/master/scripts/our_mpeg/zigzag.py</a></p>
<pre><code>ZIG = np.array([[0, 1, 5, 6, 14, 15, 27, 28],
[2, 4, 7, 13, 16, 26, 29, 42],
[3, 8, 12, 17, 25, 30, 41, 43],
[9, 11, 18, 24, 31, 40, 44,53],
[10, 19, 23, 32, 39, 45, 52,54],
[20, 22, 33, 38, 46, 51, 55,60],
[21, 34, 37, 47, 50, 56, 59,61],
[35, 36, 48, 49, 57, 58, 62,63]])
</code></pre>
<p>Apparently it's used jpeg and mpeg compression.</p>
| 1 |
2016-09-11T21:46:28Z
|
[
"python",
"numpy"
] |
Where does brew install the Python headers?
| 39,440,709 |
<p>I am trying to compile a simple "Hello, World!" in Cython. In a file I have:</p>
<pre><code>print("Hello, World!")
</code></pre>
<p>I run:</p>
<pre><code>cython hello_world.pyx
</code></pre>
<p>To get the <code>hello_world.c</code> file. I then try:</p>
<pre><code>gcc -c hello_world.c
</code></pre>
<p>Which gives the error:</p>
<pre><code>fatal error: 'Python.h' file not found
</code></pre>
<p>Then I tried <a href="http://stackoverflow.com/a/16454614/667648">this</a>:</p>
<pre><code>gcc -c hello_world.c -framework Python
</code></pre>
<p>Didn't work. I had changed <code>include "Python.h"</code> to <code><Python/Python.h></code> and got a different error:</p>
<pre><code>fatal error: 'longintrepr.h' file not found
</code></pre>
<p>Regardless, I want to use Python3, not the Python Apple ships with, but I am unable to figure out where the Python3 development headers are located.</p>
<p>Ultimately, I want to be able to compile <code>hello_world.c</code> so that it works in a Python3 interpreter.</p>
<p>(I am using brew's python3.5.2_1, if that helps.)</p>
| 2 |
2016-09-11T21:13:03Z
| 39,440,927 |
<p>Going off from @sr3z's comment, doing:</p>
<pre><code>gcc -c random_sum.c -I/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/include/python3.5m
</code></pre>
<p>Creates <code>random_sum.o</code>.</p>
| 0 |
2016-09-11T21:43:33Z
|
[
"python",
"python-3.x",
"homebrew",
"cython"
] |
Python Coursera Assignement
| 39,440,723 |
<p>I am trying to learn Python through a course on Courser, and so far having a feeling I am not going to be able to.</p>
<p>I don't want an answer to the assignment, I want someone to push me in the right direction. Because Im stuck and the online tutors there are not being any help just repeating the obvious that is already stated in the assignment. The assignment is very simple, but I cant understand what I am missing.</p>
<p>Here is the assignment:
<em>Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter the numbers from the book for problem 5.1 and Match the desired output as shown.</em></p>
<p>Here is my code, i tried using the example codes we where show for getting the minimum and maximum, but the problem is in the examples we had they had lists, here I was told I dont need a list. But everytime the value of num changes with ever new input, how can i get the program to choose from certain numbers if they are not storing...or do you think i can enter lists in the raw_input?</p>
<pre><code>while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
largest = None
if largest is None:
largest = num
elif num > largest:
largest = num
smallest = None
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
print "Maximum is", largest
print "Minimum is", smallest
</code></pre>
<p>The numbers from the book are 4, 5, 7 and a word</p>
<p><strong>Thank you everyone for your support,</strong> I understand what I have to do, not sure if I understand how I will get there, but Im going to sit and keep trying. Meanwhile I am getting issues with indentation
let's say I rewrote the code like this and want to add an if statement into the while loop</p>
<pre><code>largest = None
smallest = None
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
</code></pre>
<p>should the if statement start with the same indent as the continue and then the inside of the if indented again?? Because Im getting errors when I do that</p>
| 0 |
2016-09-11T21:15:22Z
| 39,440,780 |
<p>You should check for the largest and smallest numbers inside the loop. First check if its a number - if yes, carry on and see if it is bigger than your current <code>largest</code> variable value (start with 0). If yes, replace it. See, if its smaller than your <code>smallest</code> value (start with the first number that comes in, if you start with 0 or just a random number, you might not get lower that that. If you start with the first number, then it'll definitely be the smallest (after all the loops)), etc, etc. All of that should be done inside the loop and after the loop should be just the printing. And yes, you don't need to use lists.</p>
| 0 |
2016-09-11T21:21:43Z
|
[
"python"
] |
Python Coursera Assignement
| 39,440,723 |
<p>I am trying to learn Python through a course on Courser, and so far having a feeling I am not going to be able to.</p>
<p>I don't want an answer to the assignment, I want someone to push me in the right direction. Because Im stuck and the online tutors there are not being any help just repeating the obvious that is already stated in the assignment. The assignment is very simple, but I cant understand what I am missing.</p>
<p>Here is the assignment:
<em>Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter the numbers from the book for problem 5.1 and Match the desired output as shown.</em></p>
<p>Here is my code, i tried using the example codes we where show for getting the minimum and maximum, but the problem is in the examples we had they had lists, here I was told I dont need a list. But everytime the value of num changes with ever new input, how can i get the program to choose from certain numbers if they are not storing...or do you think i can enter lists in the raw_input?</p>
<pre><code>while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
largest = None
if largest is None:
largest = num
elif num > largest:
largest = num
smallest = None
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
print "Maximum is", largest
print "Minimum is", smallest
</code></pre>
<p>The numbers from the book are 4, 5, 7 and a word</p>
<p><strong>Thank you everyone for your support,</strong> I understand what I have to do, not sure if I understand how I will get there, but Im going to sit and keep trying. Meanwhile I am getting issues with indentation
let's say I rewrote the code like this and want to add an if statement into the while loop</p>
<pre><code>largest = None
smallest = None
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
</code></pre>
<p>should the if statement start with the same indent as the continue and then the inside of the if indented again?? Because Im getting errors when I do that</p>
| 0 |
2016-09-11T21:15:22Z
| 39,440,832 |
<p>You're on the right track with your current implementation, but there is some issues in the order of your operations, and where the operations are taking place. Trace through your program step by step, and try to see why your <code>None</code> assignment may be causing some issues, among other small things. </p>
| 1 |
2016-09-11T21:27:32Z
|
[
"python"
] |
Python Coursera Assignement
| 39,440,723 |
<p>I am trying to learn Python through a course on Courser, and so far having a feeling I am not going to be able to.</p>
<p>I don't want an answer to the assignment, I want someone to push me in the right direction. Because Im stuck and the online tutors there are not being any help just repeating the obvious that is already stated in the assignment. The assignment is very simple, but I cant understand what I am missing.</p>
<p>Here is the assignment:
<em>Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter the numbers from the book for problem 5.1 and Match the desired output as shown.</em></p>
<p>Here is my code, i tried using the example codes we where show for getting the minimum and maximum, but the problem is in the examples we had they had lists, here I was told I dont need a list. But everytime the value of num changes with ever new input, how can i get the program to choose from certain numbers if they are not storing...or do you think i can enter lists in the raw_input?</p>
<pre><code>while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
largest = None
if largest is None:
largest = num
elif num > largest:
largest = num
smallest = None
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
print "Maximum is", largest
print "Minimum is", smallest
</code></pre>
<p>The numbers from the book are 4, 5, 7 and a word</p>
<p><strong>Thank you everyone for your support,</strong> I understand what I have to do, not sure if I understand how I will get there, but Im going to sit and keep trying. Meanwhile I am getting issues with indentation
let's say I rewrote the code like this and want to add an if statement into the while loop</p>
<pre><code>largest = None
smallest = None
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
</code></pre>
<p>should the if statement start with the same indent as the continue and then the inside of the if indented again?? Because Im getting errors when I do that</p>
| 0 |
2016-09-11T21:15:22Z
| 39,440,878 |
<p>Let me give you a hint here, every time your <code>while</code> loop takes in a input, it sets the values of <code>largest</code> and <code>smallest</code> to <code>None</code>. Where should you initialize them?</p>
| 0 |
2016-09-11T21:34:06Z
|
[
"python"
] |
Python Coursera Assignement
| 39,440,723 |
<p>I am trying to learn Python through a course on Courser, and so far having a feeling I am not going to be able to.</p>
<p>I don't want an answer to the assignment, I want someone to push me in the right direction. Because Im stuck and the online tutors there are not being any help just repeating the obvious that is already stated in the assignment. The assignment is very simple, but I cant understand what I am missing.</p>
<p>Here is the assignment:
<em>Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter the numbers from the book for problem 5.1 and Match the desired output as shown.</em></p>
<p>Here is my code, i tried using the example codes we where show for getting the minimum and maximum, but the problem is in the examples we had they had lists, here I was told I dont need a list. But everytime the value of num changes with ever new input, how can i get the program to choose from certain numbers if they are not storing...or do you think i can enter lists in the raw_input?</p>
<pre><code>while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
largest = None
if largest is None:
largest = num
elif num > largest:
largest = num
smallest = None
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
print "Maximum is", largest
print "Minimum is", smallest
</code></pre>
<p>The numbers from the book are 4, 5, 7 and a word</p>
<p><strong>Thank you everyone for your support,</strong> I understand what I have to do, not sure if I understand how I will get there, but Im going to sit and keep trying. Meanwhile I am getting issues with indentation
let's say I rewrote the code like this and want to add an if statement into the while loop</p>
<pre><code>largest = None
smallest = None
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
</code></pre>
<p>should the if statement start with the same indent as the continue and then the inside of the if indented again?? Because Im getting errors when I do that</p>
| 0 |
2016-09-11T21:15:22Z
| 39,440,894 |
<p>You are being asked to keep a running max and running min, the same way you could keep a running total. You just update the running <whatever> inside the loop, then discard the user's most recent input. In the case of running total, the code would look like <code>tot = tot + newinput</code> and you could then discard <code>newinput</code> (or, more likely, reuse it) without recording it in a list or any other data structure.</p>
<p>Not every problem permits a "running" solution. For instance, if you wanted to give the user an undo feature, letting them back out some of the numbers they entered earlier, you would have to keep an exact history of all the numbers. But here, you can get by without keeping that data.</p>
| 1 |
2016-09-11T21:36:06Z
|
[
"python"
] |
Python Coursera Assignement
| 39,440,723 |
<p>I am trying to learn Python through a course on Courser, and so far having a feeling I am not going to be able to.</p>
<p>I don't want an answer to the assignment, I want someone to push me in the right direction. Because Im stuck and the online tutors there are not being any help just repeating the obvious that is already stated in the assignment. The assignment is very simple, but I cant understand what I am missing.</p>
<p>Here is the assignment:
<em>Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter the numbers from the book for problem 5.1 and Match the desired output as shown.</em></p>
<p>Here is my code, i tried using the example codes we where show for getting the minimum and maximum, but the problem is in the examples we had they had lists, here I was told I dont need a list. But everytime the value of num changes with ever new input, how can i get the program to choose from certain numbers if they are not storing...or do you think i can enter lists in the raw_input?</p>
<pre><code>while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
largest = None
if largest is None:
largest = num
elif num > largest:
largest = num
smallest = None
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
print "Maximum is", largest
print "Minimum is", smallest
</code></pre>
<p>The numbers from the book are 4, 5, 7 and a word</p>
<p><strong>Thank you everyone for your support,</strong> I understand what I have to do, not sure if I understand how I will get there, but Im going to sit and keep trying. Meanwhile I am getting issues with indentation
let's say I rewrote the code like this and want to add an if statement into the while loop</p>
<pre><code>largest = None
smallest = None
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
</code></pre>
<p>should the if statement start with the same indent as the continue and then the inside of the if indented again?? Because Im getting errors when I do that</p>
| 0 |
2016-09-11T21:15:22Z
| 39,441,119 |
<p>I sense that your confusion partly stems from how the user is expected to give the input. One could interpret the instructions in two ways.</p>
<ol>
<li><p>The user writes <code>4 5 7 randomword [ENTER]</code></p></li>
<li><p>The user writes <code>4 [ENTER] 5 [ENTER] 7 [ENTER] randomword [ENTER]</code></p></li>
</ol>
<p>If it was the first variant, then you might be expected to process the whole thing as a list and determine its parts</p>
<p>However, the fact that they told you "you will not need lists for this exercise" implies that they expect the second scenario. Which means you should design your <code>while</code> loop such that at each iteration it expects to receive a single input from the user, and do something with it (i.e. check if it's bigger / smaller than the last). Whereas the loop you have now, will simply always keep the last input entered, until "done" is encountered.</p>
<p>Once you're out of the <code>while</code> loop, all you need to do is present the variables that you've so carefully collected and kept updating inside the loop, and that's it.</p>
| 0 |
2016-09-11T22:11:10Z
|
[
"python"
] |
Python Coursera Assignement
| 39,440,723 |
<p>I am trying to learn Python through a course on Courser, and so far having a feeling I am not going to be able to.</p>
<p>I don't want an answer to the assignment, I want someone to push me in the right direction. Because Im stuck and the online tutors there are not being any help just repeating the obvious that is already stated in the assignment. The assignment is very simple, but I cant understand what I am missing.</p>
<p>Here is the assignment:
<em>Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter the numbers from the book for problem 5.1 and Match the desired output as shown.</em></p>
<p>Here is my code, i tried using the example codes we where show for getting the minimum and maximum, but the problem is in the examples we had they had lists, here I was told I dont need a list. But everytime the value of num changes with ever new input, how can i get the program to choose from certain numbers if they are not storing...or do you think i can enter lists in the raw_input?</p>
<pre><code>while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
largest = None
if largest is None:
largest = num
elif num > largest:
largest = num
smallest = None
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
print "Maximum is", largest
print "Minimum is", smallest
</code></pre>
<p>The numbers from the book are 4, 5, 7 and a word</p>
<p><strong>Thank you everyone for your support,</strong> I understand what I have to do, not sure if I understand how I will get there, but Im going to sit and keep trying. Meanwhile I am getting issues with indentation
let's say I rewrote the code like this and want to add an if statement into the while loop</p>
<pre><code>largest = None
smallest = None
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
</code></pre>
<p>should the if statement start with the same indent as the continue and then the inside of the if indented again?? Because Im getting errors when I do that</p>
| 0 |
2016-09-11T21:15:22Z
| 39,458,769 |
<p>I figured it out I think, and the thing that was killing my code was the continue statement if I am not wrong</p>
<p>here is what i got, and please leave comments if I got it wrong</p>
<pre><code>largest = None
smallest = None
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
if largest is None:
largest = num
elif num > largest:
largest = num
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
print "Maximum is", largest
print "Minimum is", smallest
</code></pre>
| 0 |
2016-09-12T21:04:36Z
|
[
"python"
] |
AttributeError: 'NoneType' object has no attribute 'find_all' (Many of the other questions asked weren't applicable)
| 39,440,830 |
<p>I've seen this Error asked on here a few times but the solutions really weren't clear to me. </p>
<p>I am just starting out with BeautifulSoup so this question may be a bit trivial.</p>
<p>I am looking to extract the second table in the following website:</p>
<p><a href="http://www.espnfc.com/player/45843/lionel-messi?season=2015" rel="nofollow">http://www.espnfc.com/player/45843/lionel-messi?season=2015</a></p>
<p>Here is the code I am using to do so:</p>
<pre><code>page = urllib.urlopen('http://www.espnfc.com/player/45843/lionel-messi?season=2015').read()
soup = BeautifulSoup(page, "lxml")
data = []
#find the tables on the webpage
tables = soup.find_all('table')
#extract the table we will be analyzing
store = tables[1]
#extract all of the rows
rows = store.find_all('tr')
for row in rows:
entries = row.tbody.find_all('td')
if entries[6].string is not None:
data.append(entries[6])
</code></pre>
<p>The Attribute Error i'm getting is pointed at <code>entries = row.tbody.find_all('td')</code></p>
<p>Any help would be much appreciated. </p>
| -6 |
2016-09-11T21:27:12Z
| 39,440,925 |
<p>It means you try to call <code>find_all</code> on the value <code>None</code>. That could be <code>row.tbody</code> for example, perhaps because there is no <code><tbody></code> in the actual HTML.</p>
<p>Keep in mind that the <code><tbody></code> element is <em>implied</em>. It'll be visible in your browser's DOM inspector, but that doesn't mean it is actually present in the HTML for BeautifulSoup to parse. Generally, you don't <em>need</em> to reference <code><tbody></code> at all, unless there is also a <code><thead></code> or <code><tfooter></code> or there are multiple <code><tbody></code> elements present.</p>
<p>Just search for the <code><td></code> cells directly:</p>
<pre><code>rows = store.find_all('tr')
for row in rows:
entries = row.find_all('td')
if len(entries) > 6 and entries[6].string is not None:
data.append(entries[6])
</code></pre>
<p>You could simplify this by asking for a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow">CSS selector</a>:</p>
<pre><code>rows = soup.select('table:nth-of-type(2) tr')
data = [cell
for row in rows
for cell in row.select('td:nth-of-type(7)') if cell.string]
</code></pre>
| 1 |
2016-09-11T21:42:55Z
|
[
"python",
"beautifulsoup"
] |
Convert a string of bytes into a python string
| 39,440,917 |
<p>I made an array of bytes like so:</p>
<pre><code>import array
signal = array.array('b', "bird")
print array
array('b', [98, 105, 114, 100])
</code></pre>
<p>I want to convert that back into <code>"bird"</code>.</p>
<p>How would I do that? </p>
| 0 |
2016-09-11T21:41:04Z
| 39,440,946 |
<p>Join the ASCII-to-char array with <code>""</code> to create a string:</p>
<p>Python 2:</p>
<pre><code>import array
signal = array.array('b', "bird")
print("".join(chr(x) for x in signal))
</code></pre>
<p>Python 3 (<code>bytes</code> needs encoding because it's now REAL binary):</p>
<pre><code>import array
signal = array.array('b', bytes("bird","ascii"))
print("".join(chr(x) for x in signal)) # or print("".join(map(chr,signal)))
</code></pre>
| 0 |
2016-09-11T21:45:50Z
|
[
"python",
"arrays",
"byte",
"ascii"
] |
Django - Type Error: expected string or bytes-like object
| 39,440,918 |
<p>I've seen other questions about this error but none of them were able to help so I figured I make on myself. As per the title, I keep getting this type error and I have run out of ideas as to why it is occurring. </p>
<p>I am making an app that involves a Gallery object that adds Photo objects. What I have been specifically working on recently was a zip_upload function in order to add photos from a .zip file. I have tried Photologue but I am deciding to handle everything myself for multiple reasons. Actually, I referred to Photologue a lot when writing it so there any many similarities. Here is my code(left out unimportant details) and traceback:</p>
<p>Models:</p>
<pre><code>from django.utils.timezone import now
class ImageModel(models.Model):
image = models.ImageField('image',max_length=100,upload_to='photos')
class Meta:
abstract = True
class Photo(ImageModel):
title = models.CharField('title',max_length=250,unique=True)
date_added = models.DateTimeField('date added',default=now)
objects = PhotoQuerySet.as_manager()
class Gallery(models.Model):
title = models.CharField('title',max_length=250,unique=True)
photos = models.ManyToManyField(Photo,
related_name='gallery',verbose_name='photos', blank=True)
objects = GalleryQuerySet.as_manager()
</code></pre>
<p>Admin page:</p>
<pre><code>class GalleryAdmin(admin.ModelAdmin):
def get_urls(self):
urls = super(GalleryAdmin, self).get_urls()
add_urls = [
url(r'^upload_zip/$',
self.admin_site.admin_view(self.upload_zip),
name='upload_zip')
]
return add_urls + urls
def upload_zip(self,request):
context = {
'app_label': self.model._meta.app_label,
'opts': self.model._meta,
}
# Handle form request
if request.method == 'POST':
form = UploadZipForm(request.POST, request.FILES)
if form.is_valid():
form.save(request=request)
return HttpResponseRedirect('..')
else:
form = UploadZipForm()
context['form'] = form
context['adminform'] = helpers.AdminForm(form,
list([(None{'fields':form.base_fields})]),{})
return render(
request,'admin/inv_app/gallery/upload_zip.html',context)
</code></pre>
<p>Form:</p>
<pre><code>class UploadZipForm(forms.Form):
zip_file = forms.FileField()
title = forms.CharField(label='Title',required=False)
gallery = forms.ModelChoiceField(Gallery.objects.all(),
label='Gallery',required=False,)
# left out methods that check if zip_file is valid and titles have
# not been used by other Gallery objects
def save(self, request=None, zip_file=None):
if not zip_file:
zip_file = self.cleaned_data['zip_file']
zip = zipfile.ZipFile(zip_file,'r')
count = 1
if self.cleaned_data['gallery']:
logger.debug('Using pre-existing gallery.')
gallery = self.cleaned_data['gallery']
else:
logger.debug(
force_text('Creating new gallery "{0}".')
.format(self.cleaned_data['title']))
gallery = Gallery.objects.create(
title=self.cleaned_data['title'],
slug=slugify(self.cleaned_data['title']),)
found_image = False
for filename in sorted(zip.namelist()):
_, file_extension = os.path.splitext(filename)
file_extension = file_extension.lower()
if not file_extension or file_extension != '.jpg':
continue
# check file is not subfolder
data = zip.read(filename)
# check file is not empty, assign title to photo
contentfile = ContentFile(data)
photo.image.save(filename, contentfile)
# I believe the error is produced here ^
photo.save()
gallery.photos.add(photo)
zip.close()
</code></pre>
<p>Traceback:</p>
<pre><code>File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner
return view(request, *args, **kwargs)
File "/Users/Lucas/Documents/inventory-master/inv_app/admin.py" in upload_zip
form.save(request=request)
File "/Users/Lucas/Documents/inventory-master/inv_app/forms.py" in save
photo.image.save(filename, contentfile)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/fields/files.py" in save
self.instance.save()
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/base.py" in save
force_update=force_update, update_fields=update_fields)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/base.py" in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/base.py" in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/base.py" in _do_insert
using=using, raw=raw)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/query.py" in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in execute_sql
for sql, params in self.as_sql():
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in as_sql
for obj in self.query.objs
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in <listcomp>
for obj in self.query.objs
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in get_db_prep_save
prepared=False)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in get_db_prep_value
value = self.get_prep_value(value)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in get_prep_value
value = super(DateTimeField, self).get_prep_value(value)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in get_prep_value
return self.to_python(value)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/db/models/fields/__init__.py" in to_python
parsed = parse_datetime(value)
File "/Users/Lucas/Documents/python_envs/inventory/lib/python3.5/site-packages/django/utils/dateparse.py" in parse_datetime
match = datetime_re.match(value)
Exception Type: TypeError at /admin/inv_app/gallery/upload_zip/
Exception Value: expected string or bytes-like object
</code></pre>
<p>I am relatively new to web dev so I'm sure I'm missing something minuscule or obvious. Please help! </p>
| 2 |
2016-09-11T21:41:21Z
| 39,494,022 |
<p>Well I was able to solve it on my own!</p>
<p>My problem was the way I was overriding the Photo model's save method:</p>
<pre><code>def save(self, *args, **kwargs):
if self.slug is None:
self.slug = slugify(self.title)
super(Photo, self).save(*args, **kwargs)
</code></pre>
<p>For some reason it was not saving properly so removing it fixed the bug and it works the way it should now. I figured I did not really need to override it so I did not need to replace it! I am realizing I did not post this portion of the model in my original question so that is my mistake for not trying to completely understand the error before posting.</p>
| 0 |
2016-09-14T15:12:53Z
|
[
"python",
"django"
] |
Django self referential m2m field causes causes missing attribtue error
| 39,440,959 |
<p>I get an error if I try to make a self-referential m2m Field. Am I missing something here?</p>
<pre><code>class UserProfile(models.Model):
following = models.ManyToManyField('self', related_name='followers')
</code></pre>
<p>somewhere else in a serializer:</p>
<pre><code>def get_followers(user):
return user.profile.followers
AttributeError: 'UserProfile' object has no attribute 'followers'
</code></pre>
<p>Is there another way I can implement followers? Maybe I should make another model to do this or use a library?</p>
| 1 |
2016-09-11T21:47:35Z
| 39,441,412 |
<p>By default, Django treats all <code>self</code> m2m relations as symmetrical, for example if I am your friend, you are my friend too. When relation is symmetrical, Django won't create reverse relation attribute to your model.</p>
<p>If you want to define non-symmetrical relation, set <code>symmetrical=False</code> attribute on your field, example:</p>
<pre><code> following = models.ManyToManyField('self', related_name='followers', symmetrical=False)
</code></pre>
<p>More on that in <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ManyToManyField.symmetrical" rel="nofollow">Django documentation</a></p>
| 0 |
2016-09-11T22:51:22Z
|
[
"python",
"django",
"django-models",
"many-to-many"
] |
Vertical spacing between xticklabel to the bottom of x-axis
| 39,440,972 |
<p>I am wondering if there could be any way to change the spacing between xticklabel (i.e. $\widetilde{M}) and the bottom of x-axis? In my case the spacing is too small so that the tilde above M (left bar) becomes invisible. BTW I am using pandas' plot function to generate the bar plot.</p>
<p><a href="http://i.stack.imgur.com/JrQhV.png" rel="nofollow"><img src="http://i.stack.imgur.com/JrQhV.png" alt="enter image description here"></a></p>
| 0 |
2016-09-11T21:49:22Z
| 39,441,111 |
<p>Since Pandas uses the Matplotlib library for all the plotting, you can change this setting through rcParams. First import:</p>
<pre><code>from matplotlib import rcParams
</code></pre>
<p>and then (before plotting anything) change the padding above the xticks:</p>
<pre><code>rcParams['xtick.major.pad'] = 20
</code></pre>
| 1 |
2016-09-11T22:10:08Z
|
[
"python",
"pandas",
"numpy",
"matplotlib"
] |
Vertical spacing between xticklabel to the bottom of x-axis
| 39,440,972 |
<p>I am wondering if there could be any way to change the spacing between xticklabel (i.e. $\widetilde{M}) and the bottom of x-axis? In my case the spacing is too small so that the tilde above M (left bar) becomes invisible. BTW I am using pandas' plot function to generate the bar plot.</p>
<p><a href="http://i.stack.imgur.com/JrQhV.png" rel="nofollow"><img src="http://i.stack.imgur.com/JrQhV.png" alt="enter image description here"></a></p>
| 0 |
2016-09-11T21:49:22Z
| 39,441,147 |
<p>Assuming you <code>import matplotlib.pyplot as plt</code> You can manipulate the pyplot object via the tick_params method and <code>pad</code> arg. E.g.:</p>
<pre><code>plt.tick_params(pad=10)
</code></pre>
| 1 |
2016-09-11T22:15:35Z
|
[
"python",
"pandas",
"numpy",
"matplotlib"
] |
Django models: form with infinite group of fields repetition
| 39,440,986 |
<p>I'm studying django these days and I need your help to find a solution to this problem about form construction.</p>
<p>Let's say I have an entity called 'Activity' just made up by:</p>
<pre><code>- title: just a char field
- ActivityYears: a couple of start-end years that can be repeated multiple times
</code></pre>
<p>ActivityYears is made up by:</p>
<pre><code>- start year
- end year
</code></pre>
<p>That's how my database should look like:</p>
<pre><code>activity_table
-ID
-title
activity_years_table
-year start
-year end
-activity ID
</code></pre>
<p>That's how it looks like front-end</p>
<pre><code>Activity title 1
2001 - 2003
2005 - 2006
2007 - 2010
Activity title 2
2011 - 2013
2015 - 2016
and so on
</code></pre>
<p>I'd dare to say that Activity and ActivityYears are models but I cannot connect them in a proper way. When I add an Activity item I should be able to add as many start-end years as I need but how?</p>
<p>Thanx in advance</p>
| 0 |
2016-09-11T21:51:24Z
| 39,441,049 |
<p>You'll likely want to use two separate models with a <code>Foreign Key</code> relationship. For example:</p>
<pre><code>class Activity(Model):
id = AutoField(editable=False, primary_key=True, unique=True)
title = CharField(default="Activity")
class ActivityYear(Model):
id = AutoField(editable=False, primary_key=True, unique=True)
year_start = IntegerField(default=1900)
year_end = IntegerField(default=1999)
activity_id = ForeignKey(Activity)
</code></pre>
<p>With this model design, we can define that each <code>ActivityYear</code> had a member <code>activity_id</code> which points to the <code>id</code> field of a valid <code>Activity</code> row in the database. With this information, you would be able to select <code>ActivityYear</code> objects from the database using the respective <code>Activity</code> object's <code>id</code> member:</p>
<p><code>SELECT * FROM activity_years WHERE activity_id = 1</code></p>
<p>or in Django:</p>
<p><code>activity_years = Activity.objects.filter(activity_id=1)</code></p>
<p>In order to add <code>ActivityYear</code> objects which map to a specific <code>Activity</code> object, you can use the following:</p>
<pre><code>ActivityYear.objects.create({
'year_start': 1990,
'year_end': 1999,
'activity_id': 1,
})
</code></pre>
<p>Let me know if this answers your question.</p>
| 3 |
2016-09-11T22:01:06Z
|
[
"python",
"django"
] |
How to pass a function with a argument in a basic decorator using Python?
| 39,441,031 |
<p>I am reading about decorators and have learned quite a bit from <a href="http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/" rel="nofollow">Simeons blog</a> I had success before when there was no arguments passed in the function like this: decorator(func). I think my issue is decorator(func(args)). I think my issue is func(args) is executing and passing its return value to the decorator instead of the function itself. How can I pass a function & argument in a decorator (example B) and not use the @decorator_name 'decoration' style (example A).</p>
<p>Edit: I would like example B to produce the same result as example A.</p>
<pre><code>user_input = input("Type what you want: ")
def camel_case(func):
def _decorator(arg):
s = ""
words = arg.split()
word_count = len(words)
for i in range(word_count):
if i >0:
s += words[i].title()
else:
s += words[i].lower()
return func(s)
return _decorator
</code></pre>
<p>Example A: This works</p>
<pre><code>@camel_case
def read(text):
print("\n" + text" )
read(user_input)
</code></pre>
<p>Example B: This does not work</p>
<pre><code>def read(text):
print("\n" + text" )
camel_case(read(user_input))
</code></pre>
| 0 |
2016-09-11T21:58:30Z
| 39,441,071 |
<p>Give the function to the decorator as an argument; the decorator returns a new function; then call this returned function with <code>user_input</code> as an argument:</p>
<pre><code>camel_case(read)(user_input)
</code></pre>
| 0 |
2016-09-11T22:03:58Z
|
[
"python",
"python-decorators"
] |
How to pass a function with a argument in a basic decorator using Python?
| 39,441,031 |
<p>I am reading about decorators and have learned quite a bit from <a href="http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/" rel="nofollow">Simeons blog</a> I had success before when there was no arguments passed in the function like this: decorator(func). I think my issue is decorator(func(args)). I think my issue is func(args) is executing and passing its return value to the decorator instead of the function itself. How can I pass a function & argument in a decorator (example B) and not use the @decorator_name 'decoration' style (example A).</p>
<p>Edit: I would like example B to produce the same result as example A.</p>
<pre><code>user_input = input("Type what you want: ")
def camel_case(func):
def _decorator(arg):
s = ""
words = arg.split()
word_count = len(words)
for i in range(word_count):
if i >0:
s += words[i].title()
else:
s += words[i].lower()
return func(s)
return _decorator
</code></pre>
<p>Example A: This works</p>
<pre><code>@camel_case
def read(text):
print("\n" + text" )
read(user_input)
</code></pre>
<p>Example B: This does not work</p>
<pre><code>def read(text):
print("\n" + text" )
camel_case(read(user_input))
</code></pre>
| 0 |
2016-09-11T21:58:30Z
| 39,441,076 |
<p>THe decorator takes a function: <code>camel_case(read)</code>. If you're trying to apply <code>camel_case</code> to the <code>read(user_input)</code> function, try this:</p>
<pre><code>camel_case(read)(user_input)
</code></pre>
<p><code>camel_case(read)</code> returns the decorated function, which you then call with <code>(user_input)</code>.</p>
| 2 |
2016-09-11T22:04:14Z
|
[
"python",
"python-decorators"
] |
Python: writing function mult(a,b) for a*b with only add/sub/neg, recursion error for testing (-a,b)
| 39,441,073 |
<p>I have this so far - but if I test with (-a, b), python gives me a recursion error. Please help, not sure why this isn't working. All other tests work here.</p>
<pre><code>def mult(a, b):
""" mult returns the product of two inputs
inputs: n and m are integers
output: result of multiplying n and m
"""
if b < 0:
return -mult(a,-b)
elif b == 0:
return 0
elif b == 1:
return a
else:
return a + mult(a,b-1)
</code></pre>
<p>Thanks out there. </p>
| -1 |
2016-09-11T22:04:00Z
| 39,441,230 |
<p>Python has a limit to the number of recursions. You may just be hitting into it. See the following answer:</p>
<p><a href="http://stackoverflow.com/questions/3323001/maximum-recursion-depth">Maximum recursion depth?</a></p>
| 1 |
2016-09-11T22:25:11Z
|
[
"python",
"function",
"python-3.x",
"recursion",
"multiplication"
] |
"Compressing" a list of integers
| 39,441,074 |
<p>I have a list of integers as follows:</p>
<pre><code>my_list = [2,2,2,2,3,4,2,2,4,4,3]
</code></pre>
<p>What I want is to have this as a list os strings, indexed and 'compressed', that is, with each element indicated by its position in the list and with each successive duplicate element indicated as a range, like this:</p>
<pre><code>my_new_list = ['0-3,2', '4,3', '5,4', '6-7,2', '8-9,4', '10,3']
</code></pre>
<p>EDIT: The expected output should indicate that list elements 0 to 3 have the number 2, element 3, the number 3, element 5, the number 4, elements 6 and 7, the number 2, elements 8 and 9, number 4, and element 10, number 3. </p>
<p>EDIT 2: The output list need not (indeed cannot) be a list of integers, but a list of strings instead.</p>
<p>I could find many examples of finding (and deleting) duplicated elements from lists, but nothing along the lines of what I need.</p>
<p>Could someone point out a relevant example or suggest an algorithm for solving this?</p>
<p>Thanks in advance!</p>
| 1 |
2016-09-11T22:04:02Z
| 39,441,171 |
<p>First off, your requested results are not valid python. I'm going to assume that the following format would work for you:</p>
<pre><code>my_new_list = [ ((0,3),2), ((4,4),3), ((5,5),4), ((6,7),2), ((8,9),4), ((10,10),3) ]
</code></pre>
<p>Given that, you can first transform <code>my_list</code> into a list of <code>((index,index),value)</code> tuples, then use <code>reduce</code> to gather that into ranges:</p>
<pre><code>my_new_list = reduce(
lambda new_list,item:
new_list[:-1] + [((new_list[-1][0][0],item[0][1]),item[1])]
if len(new_list) > 0 and new_list[-1][1] == item[1]
else new_list + [item]
, [((index,index),value) for (index,value) in enumerate(my_list)]
, []
)
</code></pre>
<p>This does the following:</p>
<ol>
<li><p>transform the list into <code>((index,index),value)</code> tuples:</p>
<pre><code>[((index,index),value) for (index,value) in enumerate(my_list)]
</code></pre></li>
<li><p>use <code>reduce</code> to merge adjacent items with the same value: If the list being built has at least 1 item and the last item in the list has the same value as the item being processed, reduce it to the list minus the last item, plus a new item consisting of the first index from the last list item plus the second index of the current item and the value of the current item. If the list being built is empty or the last item in the list is not the same value as the item being processed, just add the current item to the list.</p></li>
</ol>
<p><em>Edited to use <code>new_list</code> instead of <code>list</code> as my lambda parameter; using <code>list</code> as a parameter or variable name is bad form</em></p>
| 0 |
2016-09-11T22:18:34Z
|
[
"python",
"list"
] |
"Compressing" a list of integers
| 39,441,074 |
<p>I have a list of integers as follows:</p>
<pre><code>my_list = [2,2,2,2,3,4,2,2,4,4,3]
</code></pre>
<p>What I want is to have this as a list os strings, indexed and 'compressed', that is, with each element indicated by its position in the list and with each successive duplicate element indicated as a range, like this:</p>
<pre><code>my_new_list = ['0-3,2', '4,3', '5,4', '6-7,2', '8-9,4', '10,3']
</code></pre>
<p>EDIT: The expected output should indicate that list elements 0 to 3 have the number 2, element 3, the number 3, element 5, the number 4, elements 6 and 7, the number 2, elements 8 and 9, number 4, and element 10, number 3. </p>
<p>EDIT 2: The output list need not (indeed cannot) be a list of integers, but a list of strings instead.</p>
<p>I could find many examples of finding (and deleting) duplicated elements from lists, but nothing along the lines of what I need.</p>
<p>Could someone point out a relevant example or suggest an algorithm for solving this?</p>
<p>Thanks in advance!</p>
| 1 |
2016-09-11T22:04:02Z
| 39,441,321 |
<p>Like most problems involving cascading consecutive duplicates, you can still use <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow">groupby()</a> for this. Just group indices by the value at each index.</p>
<pre><code>values = [2,2,2,2,3,4,2,2,4,4,3]
result = []
for key, group in itertools.groupby(range(len(values)), values.__getitem__):
indices = list(group)
if len(indices) > 1:
result.append('{}-{},{}'.format(indices[0], indices[-1], key))
else:
result.append('{},{}'.format(indices[0], key))
print(result)
</code></pre>
<p>Output:</p>
<pre><code>['0-3,2', '4,3', '5,4', '6-7,2', '8-9,4', '10,3']
</code></pre>
| 3 |
2016-09-11T22:37:45Z
|
[
"python",
"list"
] |
"Compressing" a list of integers
| 39,441,074 |
<p>I have a list of integers as follows:</p>
<pre><code>my_list = [2,2,2,2,3,4,2,2,4,4,3]
</code></pre>
<p>What I want is to have this as a list os strings, indexed and 'compressed', that is, with each element indicated by its position in the list and with each successive duplicate element indicated as a range, like this:</p>
<pre><code>my_new_list = ['0-3,2', '4,3', '5,4', '6-7,2', '8-9,4', '10,3']
</code></pre>
<p>EDIT: The expected output should indicate that list elements 0 to 3 have the number 2, element 3, the number 3, element 5, the number 4, elements 6 and 7, the number 2, elements 8 and 9, number 4, and element 10, number 3. </p>
<p>EDIT 2: The output list need not (indeed cannot) be a list of integers, but a list of strings instead.</p>
<p>I could find many examples of finding (and deleting) duplicated elements from lists, but nothing along the lines of what I need.</p>
<p>Could someone point out a relevant example or suggest an algorithm for solving this?</p>
<p>Thanks in advance!</p>
| 1 |
2016-09-11T22:04:02Z
| 39,441,324 |
<p>You could use enumerate with a generator function</p>
<pre><code>def seq(l):
it = iter(l)
# get first element and set the start index to 0.
start, prev = 0, next(it)
# use enumerate to track the rest of the indexes
for ind, ele in enumerate(it, 1):
# if last seen element is not the same the sequence is over
# if start i == ind - 1 the sequence had just a single element.
if prev != ele:
yield ("{}-{}, {}".format(start, ind - 1, prev)) \
if start != ind - 1 else ("{}, {}".format(start, prev))
start = ind
prev = ele
yield ("{}-{}, {}".format(start-1, ind-1, prev)) \
if start != ind else ("{}, {}".format(start, prev))
</code></pre>
<p>Output:</p>
<pre><code>In [3]: my_list = [2, 2, 2, 2, 3, 4, 2, 2, 4, 4, 3]
In [4]: list(seq(my_list))
Out[4]: ['0-3, 2', '4, 3', '5, 4', '6-7, 2', '8-9, 4', '10, 3']
</code></pre>
<p>I was going to use <em>groupby</em> but will be faster.</p>
<pre><code>In [11]: timeit list(seq(my_list))
100000 loops, best of 3: 4.38 µs per loop
In [12]: timeit itools()
100000 loops, best of 3: 9.23 µs per loop
</code></pre>
| 1 |
2016-09-11T22:37:48Z
|
[
"python",
"list"
] |
"Compressing" a list of integers
| 39,441,074 |
<p>I have a list of integers as follows:</p>
<pre><code>my_list = [2,2,2,2,3,4,2,2,4,4,3]
</code></pre>
<p>What I want is to have this as a list os strings, indexed and 'compressed', that is, with each element indicated by its position in the list and with each successive duplicate element indicated as a range, like this:</p>
<pre><code>my_new_list = ['0-3,2', '4,3', '5,4', '6-7,2', '8-9,4', '10,3']
</code></pre>
<p>EDIT: The expected output should indicate that list elements 0 to 3 have the number 2, element 3, the number 3, element 5, the number 4, elements 6 and 7, the number 2, elements 8 and 9, number 4, and element 10, number 3. </p>
<p>EDIT 2: The output list need not (indeed cannot) be a list of integers, but a list of strings instead.</p>
<p>I could find many examples of finding (and deleting) duplicated elements from lists, but nothing along the lines of what I need.</p>
<p>Could someone point out a relevant example or suggest an algorithm for solving this?</p>
<p>Thanks in advance!</p>
| 1 |
2016-09-11T22:04:02Z
| 39,441,378 |
<p>Here's a generator-based solution similar to Padraic's. However it avoids <code>enumerate()</code>-based index tracking and thus is probably faster for huge lists. I didn't worry about your desired output formatting, either.</p>
<pre><code>def compress_list(ilist):
"""Compresses a list of integers"""
left, right = 0, 0
length = len(ilist)
while right < length:
if ilist[left] == ilist[right]:
right += 1
continue
yield (ilist[left], (left, right-1))
left = right
# at the end of the list, yield the last item
yield (ilist[left], (left, right-1))
</code></pre>
<p>It would be used like this:</p>
<pre><code>my_list = [2,2,2,2,3,4,2,2,4,4,3]
my_compressed_list = [i for i in compress_list(my_list)]
my_compressed_list
</code></pre>
<p>Resulting in output of:</p>
<pre><code>[(2, (0, 3)),
(3, (4, 4)),
(4, (5, 5)),
(2, (6, 7)),
(4, (8, 9)),
(3, (10, 10))]
</code></pre>
| 0 |
2016-09-11T22:45:37Z
|
[
"python",
"list"
] |
"Compressing" a list of integers
| 39,441,074 |
<p>I have a list of integers as follows:</p>
<pre><code>my_list = [2,2,2,2,3,4,2,2,4,4,3]
</code></pre>
<p>What I want is to have this as a list os strings, indexed and 'compressed', that is, with each element indicated by its position in the list and with each successive duplicate element indicated as a range, like this:</p>
<pre><code>my_new_list = ['0-3,2', '4,3', '5,4', '6-7,2', '8-9,4', '10,3']
</code></pre>
<p>EDIT: The expected output should indicate that list elements 0 to 3 have the number 2, element 3, the number 3, element 5, the number 4, elements 6 and 7, the number 2, elements 8 and 9, number 4, and element 10, number 3. </p>
<p>EDIT 2: The output list need not (indeed cannot) be a list of integers, but a list of strings instead.</p>
<p>I could find many examples of finding (and deleting) duplicated elements from lists, but nothing along the lines of what I need.</p>
<p>Could someone point out a relevant example or suggest an algorithm for solving this?</p>
<p>Thanks in advance!</p>
| 1 |
2016-09-11T22:04:02Z
| 39,441,549 |
<p>Here is a lazy version that works on any sequence, and yields slices. Thus it's generic and memory efficient.</p>
<pre><code>def compress(seq):
start_index = 0
previous = None
n = 0
for i, x in enumerate(seq):
if previous and x != previous:
yield previous, slice(start_index, i)
start_index = i
previous = x
n += 1
if previous:
yield previous, slice(start_index, n)
</code></pre>
<p>Usage :</p>
<pre><code>assert list(compress([2, 2, 2, 2, 3, 4, 2, 2, 4, 4, 3])) == [
(2, slice(0, 4)),
(3, slice(4, 5)),
(4, slice(5, 6)),
(2, slice(6, 8)),
(4, slice(8, 10)),
(3, slice(10, 11)),
]
</code></pre>
<p>Why slices? Because it's convenient (can be used as-is for indexing) and the semantics (upper bound not included) are more "standard". Changing that to tuples or string with upper bound is easy btw.</p>
| 1 |
2016-09-11T23:15:35Z
|
[
"python",
"list"
] |
"Compressing" a list of integers
| 39,441,074 |
<p>I have a list of integers as follows:</p>
<pre><code>my_list = [2,2,2,2,3,4,2,2,4,4,3]
</code></pre>
<p>What I want is to have this as a list os strings, indexed and 'compressed', that is, with each element indicated by its position in the list and with each successive duplicate element indicated as a range, like this:</p>
<pre><code>my_new_list = ['0-3,2', '4,3', '5,4', '6-7,2', '8-9,4', '10,3']
</code></pre>
<p>EDIT: The expected output should indicate that list elements 0 to 3 have the number 2, element 3, the number 3, element 5, the number 4, elements 6 and 7, the number 2, elements 8 and 9, number 4, and element 10, number 3. </p>
<p>EDIT 2: The output list need not (indeed cannot) be a list of integers, but a list of strings instead.</p>
<p>I could find many examples of finding (and deleting) duplicated elements from lists, but nothing along the lines of what I need.</p>
<p>Could someone point out a relevant example or suggest an algorithm for solving this?</p>
<p>Thanks in advance!</p>
| 1 |
2016-09-11T22:04:02Z
| 39,442,002 |
<p>Some good answers here, and thought I would offer an alternative. We iterate through the list of numbers and keep an updating <code>current</code> value, associated with a list of indicies for that value <code>current_indicies</code>. We then look-ahead one element to see if the consecutive number <strong>differs</strong> from <code>current</code>, if it does we go ahead and add it as a '<em>compressed number</em>'. </p>
<pre><code>def compress_numbers(l):
result = []
current = None
current_indicies = None
for i, item in enumerate(l):
if current != item:
current = item
current_indicies = [i]
elif current == item:
current_indicies.append(i)
try:
if l[i+1] != current:
result.append(format_entry(current_indicies, current))
except:
result.append(format_entry(current_indicies, current))
return result
# Helper method to format entry in the list.
def format_entry(indicies, value):
i_range = None
if len(indicies) > 1:
i_range = '{}-{}'.format(indicies[0], indicies[-1])
else:
i_range = indicies[0]
return '{},{}'.format(i_range, value)
</code></pre>
<p><strong>Sample Output:</strong></p>
<pre><code>>>> print compress_numbers([2, 2, 2, 2, 3, 4, 2, 2, 4, 4, 3])
['0-3,2', '4,3', '5,4', '6-7,2', '8-9,4', '10,3']
</code></pre>
| 1 |
2016-09-12T00:38:30Z
|
[
"python",
"list"
] |
"Compressing" a list of integers
| 39,441,074 |
<p>I have a list of integers as follows:</p>
<pre><code>my_list = [2,2,2,2,3,4,2,2,4,4,3]
</code></pre>
<p>What I want is to have this as a list os strings, indexed and 'compressed', that is, with each element indicated by its position in the list and with each successive duplicate element indicated as a range, like this:</p>
<pre><code>my_new_list = ['0-3,2', '4,3', '5,4', '6-7,2', '8-9,4', '10,3']
</code></pre>
<p>EDIT: The expected output should indicate that list elements 0 to 3 have the number 2, element 3, the number 3, element 5, the number 4, elements 6 and 7, the number 2, elements 8 and 9, number 4, and element 10, number 3. </p>
<p>EDIT 2: The output list need not (indeed cannot) be a list of integers, but a list of strings instead.</p>
<p>I could find many examples of finding (and deleting) duplicated elements from lists, but nothing along the lines of what I need.</p>
<p>Could someone point out a relevant example or suggest an algorithm for solving this?</p>
<p>Thanks in advance!</p>
| 1 |
2016-09-11T22:04:02Z
| 39,445,885 |
<p>Construct the list with number of consecutive occurences with the item. Then iterate the list and get the list with the range of index of each item.</p>
<pre><code>from itertools import groupby
new_list = []
for k, g in groupby([2,2,2,2,3,4,2,2,4,4,3]):
sum_each = 0
for i in g:
sum_each += 1
##Construct the list with number of consecutive occurences with the item like this `[(4, 2), (1, 3), (1, 4), (2, 2), (2, 4), (1, 3)]`
new_list.append((sum_each, k))
x = 0
for (n, item) in enumerate(new_list):
if item[0] > 1:
new_list[n] = str(x) + '-' + str(x+item[0]-1) + ',' + str(item[1])
else:
new_list[n] = str(x) + ',' + str(item[1])
x += item[0]
print new_list
</code></pre>
| 1 |
2016-09-12T08:09:02Z
|
[
"python",
"list"
] |
How to break a sentence in python depending on fullstop '.'?
| 39,441,157 |
<p>I writing a script in python in which I have the following string:</p>
<pre><code>a = "write This is mango. write This is orange."
</code></pre>
<p>I want to break this string into sentences and then add each sentence as an item of a list so it becomes:</p>
<pre><code>list = ['write This is mango.', 'write This is orange.']
</code></pre>
<p>I have tried using TextBlob but it is not reading it correctly.(Reads the whole string as one sentence).</p>
<p>Is there a simple way of doing it?</p>
| -1 |
2016-09-11T22:16:49Z
| 39,441,188 |
<p>One approach is <a href="https://docs.python.org/2/library/re.html#re.split" rel="nofollow"><code>re.split</code></a> with <em>positive lookbehind</em> assertion:</p>
<pre><code>>>> import re
>>> a = "write This is mango. write This is orange."
>>> re.split(r'(?<=\w\.)\s', a)
['write This is mango.', 'write This is orange.']
</code></pre>
<p>If you want to <em>split</em> on more than one separator, say <code>.</code> and <code>,</code>, then use a character set in the assertion:</p>
<pre><code>>>> a = "write This is mango. write This is orange. This is guava, and not pear."
>>> re.split(r'(?<=\w[,\.])\s', a)
['write This is mango.', 'write This is orange.', 'This is guava,', 'and not pear.']
</code></pre>
<hr>
<p>On a side note, you should not use <code>list</code> as the name of a variable as this will <em>shadow</em> the builtin <code>list</code>.</p>
| 1 |
2016-09-11T22:20:44Z
|
[
"python",
"list"
] |
How to break a sentence in python depending on fullstop '.'?
| 39,441,157 |
<p>I writing a script in python in which I have the following string:</p>
<pre><code>a = "write This is mango. write This is orange."
</code></pre>
<p>I want to break this string into sentences and then add each sentence as an item of a list so it becomes:</p>
<pre><code>list = ['write This is mango.', 'write This is orange.']
</code></pre>
<p>I have tried using TextBlob but it is not reading it correctly.(Reads the whole string as one sentence).</p>
<p>Is there a simple way of doing it?</p>
| -1 |
2016-09-11T22:16:49Z
| 39,441,195 |
<p>you should look in to the NLTK for python.
Here's a sample from NLTK.org</p>
<pre><code>>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']
>>> tagged = nltk.pos_tag(tokens)
>>> tagged[0:6]
[('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'),
('Thursday', 'NNP'), ('morning', 'NN')]
</code></pre>
<p>for your case you can do</p>
<pre><code>import nltk
a = "write This is mango. write This is orange."
tokens = nltk.word_tokenize(a)
</code></pre>
| 1 |
2016-09-11T22:21:32Z
|
[
"python",
"list"
] |
How to break a sentence in python depending on fullstop '.'?
| 39,441,157 |
<p>I writing a script in python in which I have the following string:</p>
<pre><code>a = "write This is mango. write This is orange."
</code></pre>
<p>I want to break this string into sentences and then add each sentence as an item of a list so it becomes:</p>
<pre><code>list = ['write This is mango.', 'write This is orange.']
</code></pre>
<p>I have tried using TextBlob but it is not reading it correctly.(Reads the whole string as one sentence).</p>
<p>Is there a simple way of doing it?</p>
| -1 |
2016-09-11T22:16:49Z
| 39,441,202 |
<p>You know about <code>string.split</code>? It can take a multicharacter split criterion:</p>
<pre><code>>>> "wer. wef. rgo.".split(". ")
['wer', 'wef', 'rgo.']
</code></pre>
<p>But it's not very flexible about things like amount of white space. If you can't control how many spaces come after the full stop, I recommend regular expressions ("import re"). For that matter, you could just split on "." and clean up the white space at the front of each sentence and the empty list that you will get after the last ".".</p>
| 0 |
2016-09-11T22:22:10Z
|
[
"python",
"list"
] |
How to break a sentence in python depending on fullstop '.'?
| 39,441,157 |
<p>I writing a script in python in which I have the following string:</p>
<pre><code>a = "write This is mango. write This is orange."
</code></pre>
<p>I want to break this string into sentences and then add each sentence as an item of a list so it becomes:</p>
<pre><code>list = ['write This is mango.', 'write This is orange.']
</code></pre>
<p>I have tried using TextBlob but it is not reading it correctly.(Reads the whole string as one sentence).</p>
<p>Is there a simple way of doing it?</p>
| -1 |
2016-09-11T22:16:49Z
| 39,441,220 |
<p>This should work. Check out the .split() function here: <a href="http://www.tutorialspoint.com/python/string_split.htm" rel="nofollow">http://www.tutorialspoint.com/python/string_split.htm</a> </p>
<pre><code> a = "write This is mango. write This is orange."
print a.split('.', 1)
</code></pre>
| 0 |
2016-09-11T22:23:41Z
|
[
"python",
"list"
] |
How to break a sentence in python depending on fullstop '.'?
| 39,441,157 |
<p>I writing a script in python in which I have the following string:</p>
<pre><code>a = "write This is mango. write This is orange."
</code></pre>
<p>I want to break this string into sentences and then add each sentence as an item of a list so it becomes:</p>
<pre><code>list = ['write This is mango.', 'write This is orange.']
</code></pre>
<p>I have tried using TextBlob but it is not reading it correctly.(Reads the whole string as one sentence).</p>
<p>Is there a simple way of doing it?</p>
| -1 |
2016-09-11T22:16:49Z
| 39,441,592 |
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><code>a.split()</code></code></pre>
</div>
</div>
</p>
<p>a.split() seems like a simple way of doing it, but you will eventually run into problems. </p>
<p>For example suppose you have</p>
<pre><code>a = 'What is the price of the orange? \
It costs $1.39. \
Thank you! \
See you soon Mr. Meowgi.'
</code></pre>
<p>The a.split('.') would return: </p>
<pre><code>a[0] = 'What is the price of the orange? It costs $1'
a[1] = '39'
a[2] = 'Thank you! See you soon Mr'
a[3] = 'Meowgi'
</code></pre>
<p>I am also not factoring in </p>
<ul>
<li>code snippets
<ul>
<li>e.g. 'The problem occured when I ran ./sen_split function. "a.str(" did not have a closing bracket.'</li>
</ul></li>
<li>Possible Names of Company's
<ul>
<li>e.g. 'I work for the Node.js company'</li>
</ul></li>
<li>etc.</li>
</ul>
<p>This eventually boils down to English syntax. I would recommend looking into nltk module as Mike Tung pointed out.</p>
| 0 |
2016-09-11T23:22:56Z
|
[
"python",
"list"
] |
change list of tuples to 2 lists - Python
| 39,441,191 |
<p>I have a list of tuples (in this case its coordinates for latitude and longitude)</p>
<pre><code>[(51.69768233153901, -5.039923897568534),
(52.14847612092221, 0.33689512047881015),
(52.14847612092221, 0.33689512047881015),
....]
</code></pre>
<p>I am trying to get them into 2 separate lists (one for latitude and one for longitude)</p>
<p>I cannot work out how to loop through to add them to the lists, so far I have: </p>
<pre><code>lat = latlon_df.at[0,'LatLon'][0]
lon = latlon_df.at[0,'LatLon'][1]
</code></pre>
<p>which identifies the first of each. Could someone show me how do create the 2 new lists?</p>
<p>Thanks for your help!</p>
| 1 |
2016-09-11T22:21:03Z
| 39,441,212 |
<p>Try this:</p>
<pre><code>coords = [(51.69768233153901, -5.039923897568534),
(52.14847612092221, 0.33689512047881015),
(52.14847612092221, 0.33689512047881015)]
lat, lon = map(list, zip(*coords))
</code></pre>
<p>Adapted from this answer here <a href="http://stackoverflow.com/questions/19339/a-transpose-unzip-function-in-python-inverse-of-zip">A Transpose/Unzip Function in Python (inverse of zip)</a></p>
| 6 |
2016-09-11T22:23:14Z
|
[
"python",
"tuples",
"ipython"
] |
change list of tuples to 2 lists - Python
| 39,441,191 |
<p>I have a list of tuples (in this case its coordinates for latitude and longitude)</p>
<pre><code>[(51.69768233153901, -5.039923897568534),
(52.14847612092221, 0.33689512047881015),
(52.14847612092221, 0.33689512047881015),
....]
</code></pre>
<p>I am trying to get them into 2 separate lists (one for latitude and one for longitude)</p>
<p>I cannot work out how to loop through to add them to the lists, so far I have: </p>
<pre><code>lat = latlon_df.at[0,'LatLon'][0]
lon = latlon_df.at[0,'LatLon'][1]
</code></pre>
<p>which identifies the first of each. Could someone show me how do create the 2 new lists?</p>
<p>Thanks for your help!</p>
| 1 |
2016-09-11T22:21:03Z
| 39,441,239 |
<p>If I make a list of tuples with a list comprehension like:</p>
<pre><code>In [131]: ll = [(i,j) for i,j in zip(range(10),range(5,15))]
In [132]: ll
Out[132]:
[(0, 5),
(1, 6),
(2, 7),
(3, 8),
(4, 9),
(5, 10),
(6, 11),
(7, 12),
(8, 13),
(9, 14)]
</code></pre>
<p>I can easily split it into 2 list with 2 list comprehensions:</p>
<pre><code>In [133]: [i[0] for i in ll], [i[1] for i in ll]
Out[133]: ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
</code></pre>
<p>Yes, it involves looping over <code>ll</code> twice, but I'd end up looping over it many more times if tried to work out a way of doing it just one loop. Sometimes the simple straightforward approach is better.</p>
<p>Having said that, there is a list version of <code>transpose</code> that does the job</p>
<pre><code>In [134]: list(zip(*ll))
Out[134]: [(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (5, 6, 7, 8, 9, 10, 11, 12, 13, 14)]
</code></pre>
<p>This gives a list of 2 tuples, each with a 'column' of the original. My original constructor can be simplified to</p>
<pre><code>list(zip(range(10),range(5,15)))
</code></pre>
<p>So the <code>list(zip(*...</code> flips the list back and forth.</p>
<p>But: </p>
<pre><code>lat = latlon_df.at[0,'LatLon'][0]
</code></pre>
<p>suggests that the list of tuples might actually be a <code>pandas</code> dataframe. <code>pandas</code> probably has its own tools for indexing in this way. You previously asked about this in dataframe terms</p>
<p><a href="http://stackoverflow.com/questions/39422043/removing-round-brackets-from-a-dataframe-of-lat-lon-pairs">Removing round brackets from a dataframe of lat/lon pairs</a></p>
<p>If the list was really a structured array:</p>
<pre><code>In [143]: arr=np.array(ll, dtype='i,i')
</code></pre>
<p>The print display looks a lot like a list of tuples (though missing some ,)</p>
<pre><code>In [144]: print(arr)
[(0, 5) (1, 6) (2, 7) (3, 8) (4, 9) (5, 10) (6, 11) (7, 12) (8, 13) (9, 14)]
In [145]: arr
Out[145]:
array([(0, 5), (1, 6), (2, 7), (3, 8), (4, 9), (5, 10), (6, 11), (7, 12),
(8, 13), (9, 14)],
dtype=[('f0', '<i4'), ('f1', '<i4')])
</code></pre>
<p>It is easy to select 'fields' by name:</p>
<pre><code>In [146]: arr['f0']
Out[146]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int32)
In [147]: arr['f1']
Out[147]: array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], dtype=int32)
</code></pre>
| 0 |
2016-09-11T22:26:20Z
|
[
"python",
"tuples",
"ipython"
] |
change list of tuples to 2 lists - Python
| 39,441,191 |
<p>I have a list of tuples (in this case its coordinates for latitude and longitude)</p>
<pre><code>[(51.69768233153901, -5.039923897568534),
(52.14847612092221, 0.33689512047881015),
(52.14847612092221, 0.33689512047881015),
....]
</code></pre>
<p>I am trying to get them into 2 separate lists (one for latitude and one for longitude)</p>
<p>I cannot work out how to loop through to add them to the lists, so far I have: </p>
<pre><code>lat = latlon_df.at[0,'LatLon'][0]
lon = latlon_df.at[0,'LatLon'][1]
</code></pre>
<p>which identifies the first of each. Could someone show me how do create the 2 new lists?</p>
<p>Thanks for your help!</p>
| 1 |
2016-09-11T22:21:03Z
| 39,441,266 |
<p>Using list comprehension:</p>
<pre><code>lats, lons = [[coord[index] for coord in coords] for index in (0,1)]
</code></pre>
<p>Note that using list comprehension is over a half order of magnitude faster than the <code>map-list-zip</code> approach for large coordinate lists:</p>
<p><a href="http://i.stack.imgur.com/HjqPA.png" rel="nofollow"><img src="http://i.stack.imgur.com/HjqPA.png" alt="enter image description here"></a></p>
| -1 |
2016-09-11T22:29:51Z
|
[
"python",
"tuples",
"ipython"
] |
Confused about modifying lists using two functions in Python
| 39,441,236 |
<p>I'm currently reading <em>Python Crash Course</em> by Eric Matthes and I'm having an incredibly difficult time understanding chapter 8 which is all about functions. I am stuck on exercise 8-10 which asks me to use a new function to change a list used in the previous exercise.</p>
<p>Here is the exercise:</p>
<pre><code>8-9. Magicians: Make a list of magician's names. Pass the list to a function called show_magicians(), which prints the name of each magician in the list.
8-10. Great Magicians: Start with a copy of your program from exercise 8-9. Write a function make_great() that modifies the list of magicians by adding the phrase the great to each magician's name. Call show_magicians() to see that the list has actually been modified.
</code></pre>
<p><strong>Here is my code for 8-9:</strong></p>
<pre><code>def show_magicians(names):
"""Print each magician name"""
for name in names:
msg = name.title()
print(msg)
magician_names = ['sonic', 'tails', 'knuckles']
show_magicians(magician_names)
</code></pre>
<p>I've seen a very similar topic on this website and so I tried to use the code in the first answer on this page to help me out: <a href="http://stackoverflow.com/questions/39338405/python-crash-course-8-10">Python crash course 8-10</a></p>
<p>However, my code still appears to be incorrect as the compiler prints 'the great' 3 times after each name.</p>
<p><strong>Here is the current code I used for 8-10</strong></p>
<pre><code>def show_magicians(names):
"""Print each magician name"""
for name in names:
msg = name.title()
print(msg)
magician_names = ['sonic', 'tails', 'knuckles']
show_magicians(magician_names)
def make_great(list_magicians):
"""Add 'Great' to each name."""
for magician_name in magician_names:
for i in range(len(list_magicians)):
list_magicians[i] += " the great!"
make_great(magician_names)
show_magicians(magician_names)
</code></pre>
<p>I don't know why but it just seems that I've been struggling through out this entire chapter of functions. Does anyone by any chance have any recommended tutorials to take a look at to help me understand functions better? Thank you for your time.</p>
| 0 |
2016-09-11T22:25:44Z
| 39,441,273 |
<p>Ok, so you have an extra loop on the outside, remove that. The final code:</p>
<pre><code>def show_magicians(names):
"""Print each magician name"""
for name in names:
msg = name.title()
print(msg)
magician_names = ['sonic', 'tails', 'knuckles']
show_magicians(magician_names)
def make_great(list_magicians):
"""Add 'Great' to each name."""
for index, item in enumerate(list_magicians):
list_magicians[index] += " the great!"
make_great(magician_names)
show_magicians(magician_names)
</code></pre>
<p>You were doing a <code>for-in</code> along with a <code>for-in range</code>. That made the code repeat the appending of the string. Let me explain what your previous program did:</p>
<p><strong>Explanation:</strong>
On every iteration, you looped with a <code>for-in</code>, causing it to loop the inner loop 3 times. So, one every iteration of the <em>outer</em> loop, it would repeat the <em>inner</em> loop 3 times, making it append <code>the great</code> 3 times to every name.</p>
<p>Also, as the answerer of the linked question, I'd rather you use <code>enumerate</code> over <code>range(len(list_magicians))</code>.</p>
| 2 |
2016-09-11T22:31:34Z
|
[
"python"
] |
Confused about modifying lists using two functions in Python
| 39,441,236 |
<p>I'm currently reading <em>Python Crash Course</em> by Eric Matthes and I'm having an incredibly difficult time understanding chapter 8 which is all about functions. I am stuck on exercise 8-10 which asks me to use a new function to change a list used in the previous exercise.</p>
<p>Here is the exercise:</p>
<pre><code>8-9. Magicians: Make a list of magician's names. Pass the list to a function called show_magicians(), which prints the name of each magician in the list.
8-10. Great Magicians: Start with a copy of your program from exercise 8-9. Write a function make_great() that modifies the list of magicians by adding the phrase the great to each magician's name. Call show_magicians() to see that the list has actually been modified.
</code></pre>
<p><strong>Here is my code for 8-9:</strong></p>
<pre><code>def show_magicians(names):
"""Print each magician name"""
for name in names:
msg = name.title()
print(msg)
magician_names = ['sonic', 'tails', 'knuckles']
show_magicians(magician_names)
</code></pre>
<p>I've seen a very similar topic on this website and so I tried to use the code in the first answer on this page to help me out: <a href="http://stackoverflow.com/questions/39338405/python-crash-course-8-10">Python crash course 8-10</a></p>
<p>However, my code still appears to be incorrect as the compiler prints 'the great' 3 times after each name.</p>
<p><strong>Here is the current code I used for 8-10</strong></p>
<pre><code>def show_magicians(names):
"""Print each magician name"""
for name in names:
msg = name.title()
print(msg)
magician_names = ['sonic', 'tails', 'knuckles']
show_magicians(magician_names)
def make_great(list_magicians):
"""Add 'Great' to each name."""
for magician_name in magician_names:
for i in range(len(list_magicians)):
list_magicians[i] += " the great!"
make_great(magician_names)
show_magicians(magician_names)
</code></pre>
<p>I don't know why but it just seems that I've been struggling through out this entire chapter of functions. Does anyone by any chance have any recommended tutorials to take a look at to help me understand functions better? Thank you for your time.</p>
| 0 |
2016-09-11T22:25:44Z
| 39,441,294 |
<p>Change the second method to:</p>
<pre><code>def make_great(list_magicians):
"""Add 'Great' to each name."""
i = 0
for magician_name in magician_names:
list_magicians[i] += " the great!"
i += 1
</code></pre>
<p>Currently you are looping twice using two <code>for loops</code> causing it to be added 3 times! </p>
| 1 |
2016-09-11T22:34:27Z
|
[
"python"
] |
Confused about modifying lists using two functions in Python
| 39,441,236 |
<p>I'm currently reading <em>Python Crash Course</em> by Eric Matthes and I'm having an incredibly difficult time understanding chapter 8 which is all about functions. I am stuck on exercise 8-10 which asks me to use a new function to change a list used in the previous exercise.</p>
<p>Here is the exercise:</p>
<pre><code>8-9. Magicians: Make a list of magician's names. Pass the list to a function called show_magicians(), which prints the name of each magician in the list.
8-10. Great Magicians: Start with a copy of your program from exercise 8-9. Write a function make_great() that modifies the list of magicians by adding the phrase the great to each magician's name. Call show_magicians() to see that the list has actually been modified.
</code></pre>
<p><strong>Here is my code for 8-9:</strong></p>
<pre><code>def show_magicians(names):
"""Print each magician name"""
for name in names:
msg = name.title()
print(msg)
magician_names = ['sonic', 'tails', 'knuckles']
show_magicians(magician_names)
</code></pre>
<p>I've seen a very similar topic on this website and so I tried to use the code in the first answer on this page to help me out: <a href="http://stackoverflow.com/questions/39338405/python-crash-course-8-10">Python crash course 8-10</a></p>
<p>However, my code still appears to be incorrect as the compiler prints 'the great' 3 times after each name.</p>
<p><strong>Here is the current code I used for 8-10</strong></p>
<pre><code>def show_magicians(names):
"""Print each magician name"""
for name in names:
msg = name.title()
print(msg)
magician_names = ['sonic', 'tails', 'knuckles']
show_magicians(magician_names)
def make_great(list_magicians):
"""Add 'Great' to each name."""
for magician_name in magician_names:
for i in range(len(list_magicians)):
list_magicians[i] += " the great!"
make_great(magician_names)
show_magicians(magician_names)
</code></pre>
<p>I don't know why but it just seems that I've been struggling through out this entire chapter of functions. Does anyone by any chance have any recommended tutorials to take a look at to help me understand functions better? Thank you for your time.</p>
| 0 |
2016-09-11T22:25:44Z
| 39,441,307 |
<p>Let's look at your <code>make_great</code> function:</p>
<pre><code>def make_great(list_magicians):
"""Add 'Great' to each name."""
for magician_name in magician_names:
for i in range(len(list_magicians)):
list_magicians[i] += " the great!"
</code></pre>
<p>What does this do?</p>
<p><code>for magician_name in magician_names:</code> Loops through <code>magician_names</code>.</p>
<p><code>for i in range(len(list_magicians)):</code> Loops through <code>list_magicians</code> by index.</p>
<p><code>list_magicians[i] += " the great!"</code> Adds <code>the great!</code> to the <code>i</code>th element of <code>list_magicians</code></p>
<p>What line of code isn't necessary?</p>
<p><code>for magician_name in magician_names:</code> Looping through this provides no use. Since its length is 3, that's why you get 3 <code>the great!</code>s added to each element. Remove that line of code and the function should work properly.</p>
| 1 |
2016-09-11T22:36:07Z
|
[
"python"
] |
Confused about modifying lists using two functions in Python
| 39,441,236 |
<p>I'm currently reading <em>Python Crash Course</em> by Eric Matthes and I'm having an incredibly difficult time understanding chapter 8 which is all about functions. I am stuck on exercise 8-10 which asks me to use a new function to change a list used in the previous exercise.</p>
<p>Here is the exercise:</p>
<pre><code>8-9. Magicians: Make a list of magician's names. Pass the list to a function called show_magicians(), which prints the name of each magician in the list.
8-10. Great Magicians: Start with a copy of your program from exercise 8-9. Write a function make_great() that modifies the list of magicians by adding the phrase the great to each magician's name. Call show_magicians() to see that the list has actually been modified.
</code></pre>
<p><strong>Here is my code for 8-9:</strong></p>
<pre><code>def show_magicians(names):
"""Print each magician name"""
for name in names:
msg = name.title()
print(msg)
magician_names = ['sonic', 'tails', 'knuckles']
show_magicians(magician_names)
</code></pre>
<p>I've seen a very similar topic on this website and so I tried to use the code in the first answer on this page to help me out: <a href="http://stackoverflow.com/questions/39338405/python-crash-course-8-10">Python crash course 8-10</a></p>
<p>However, my code still appears to be incorrect as the compiler prints 'the great' 3 times after each name.</p>
<p><strong>Here is the current code I used for 8-10</strong></p>
<pre><code>def show_magicians(names):
"""Print each magician name"""
for name in names:
msg = name.title()
print(msg)
magician_names = ['sonic', 'tails', 'knuckles']
show_magicians(magician_names)
def make_great(list_magicians):
"""Add 'Great' to each name."""
for magician_name in magician_names:
for i in range(len(list_magicians)):
list_magicians[i] += " the great!"
make_great(magician_names)
show_magicians(magician_names)
</code></pre>
<p>I don't know why but it just seems that I've been struggling through out this entire chapter of functions. Does anyone by any chance have any recommended tutorials to take a look at to help me understand functions better? Thank you for your time.</p>
| 0 |
2016-09-11T22:25:44Z
| 39,441,403 |
<p>As another answerer said, your nested loops are doing basically the same thing, but for each time the outer loop runs, the inner loop runs. Both loops are trying to iterate over the list of magicians, one using the name the list goes by outside the function (<code>magician_names</code>) and one using the name the list goes by inside the function (<code>list_magicians</code>). Either way would work, but both is too many. From this point of view, your misunderstanding is not of functions, but of loops.</p>
<p>But the fact that you mention <code>magician_names</code> inside the function at all shows a misconception. It will work, but it's bad form. Usually, the code of a function should refer exclusively to names that are passed to the function via the parameters. So in this case, you should discard the loop over <code>magician_names</code> and keep the loop over <code>list_magician</code>. There are exceptions to the rule, but you should have a definite reason in mind before breaking it. The justification for the rule is encapsulation: you can completely understand the function by reading its parameter list and its code, without having to ask about the role of anything outside the function.</p>
<p>If you accept the idea that functions should operate only on their parameters, then you have to ask, So how does a function affect the outside world? One answer is that the function <code>return</code>s something, and the outside world voluntarily does something with what was returned. Another answer is that the function's parameter happens to point to an object in the outside world, so that changing the object inside the function automatically changes it outside the function. I prefer the first way, but it's probably easier in your case to use the second. So when you pass <code>magician_names</code> into your function, Python renames it to <code>list_magicians</code>; you operate on <code>list_magicians</code> inside the function, so <code>magician_names</code> also changes outside the function; you return from the function, and the <em>name</em> <code>list_magicians</code> goes away, but the <em>changes</em> to <code>magician_names</code> survive.</p>
<p>Here's a last bit of advice, which extends your knowledge to "list comprehensions," a topic you probably haven't learned about yet (but they're perfect for this application): I recommend writing a function to operate on a single piece of data, then calling that function repeatedly, rather than trying to do both the repetition and the single-item data modification in the same function. Like this:</p>
<pre><code>def append_great(magician):
return magician + " the Great"
</code></pre>
<p>With that function available, a list comprehension looks quite nice. It processes a list element by element, according to your instructions. Like this:</p>
<pre><code>>>> magicians = [ "Houdini", "Fubini" ]
>>> [ append_great(m) for m in magicians ]
['Houdini the Great', 'Fubini the Great']
</code></pre>
<p>Note that the list comprehension returned a new list; <code>magicians</code> remains unchanged, unless you change it yourself. Which is how things ought to be. Functions shouldn't reach out and touch the outside world (unless there's a really good reason); instead, the outside world should give some data to the function, receive the result, and use the result as the outside world knows best. That's my advocacy for the return-a-value way of affecting the outside world, but as I said, in this case it's easier to use the pass-a-reference way.</p>
| 1 |
2016-09-11T22:50:03Z
|
[
"python"
] |
Python in-memory database overflow
| 39,441,278 |
<p>I couldn't find an answer online, so here it goes. I'm developing a SAAS that creates a temporary in-memory SQLITE3 database on the cloud for each user. The databases will not be stored, hence they are in-memory:</p>
<pre><code>import sqlite3
conn = sqlite3.connect(':memory:')
</code></pre>
<p>My question is regarding scalability. Worst case scenario there are thousands of users each creating GB sized databases all at the same time. What is the default behavior of SQLITE3 when it runs out of memory? Will it write additional databases to disk? Will it just crash?</p>
<p>I realize this is also a function of how the SAAS SERVER is configured, but my question lies only with the memory issue. </p>
| 0 |
2016-09-11T22:31:44Z
| 39,441,341 |
<p>This <a href="https://www.sqlite.org/inmemorydb.html" rel="nofollow">documentation page</a> reads:</p>
<blockquote>
<p>The sole difference [between a temporary and an in-memory database] is that a ":memory:" database must remain in memory at all times whereas parts of a temporary database might be flushed to disk if database becomes large or if SQLite comes under memory pressure.</p>
</blockquote>
<p>This means that if SQLite runs out of memory then you'll probably hit your operating system's error codes.</p>
<p>The database may be swapped to disk by the OS even if the ram is consumed, though.</p>
<p>I'd advise to use a temporary database instead as described on the same documentation page if you're that worried, so if you run out of ram, SQLite will be able to flush them to disk.</p>
| 2 |
2016-09-11T22:40:57Z
|
[
"python",
"database",
"memory",
"sqlite3"
] |
Python lambda function "translation" causes recursion error
| 39,441,290 |
<p>While attempting to understand python lambda functions, I "translated" this function:</p>
<pre><code>s = lambda y: y ** y; s(3)
</code></pre>
<p>Into this regular, defined function:</p>
<pre><code>def power_of_self(y):
return y ** y
power_of_self(3)
</code></pre>
<p>When I tried running it as a script (<code>python lambda_stuff.py</code>) I had no problem. However, when attempting to run it via the Python shell, this weird thing happened:</p>
<pre><code>>>> def power_of_self(y):
... return y ** y
... power_of_self(3)
File "<stdin>", line 3
power_of_self(3)
^
SyntaxError: invalid syntax
>>> print power_of_self(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in power_of_self
File "<stdin>", line 1, in power_of_self
File "<stdin>", line 1, in power_of_self
File "<stdin>", line 1, in power_of_self
**A FEW HUNDRED MORE OF THESE**
RuntimeError: maximum recursion depth exceeded
</code></pre>
<p>Why did my script execution differ from my shell execution? I wonder if the <code>...</code> had anything to do with it.</p>
| 0 |
2016-09-11T22:33:56Z
| 39,441,309 |
<p>The <code>...</code> means the python shell was waiting for more statements as part of the function. You need a blank line to end the function when entering an indented block from directly into the python shell.</p>
<pre><code>>>> def power_of_self(y):
... return y ** y
...
>>> power_of_self(3)
27
</code></pre>
| 3 |
2016-09-11T22:36:23Z
|
[
"python",
"lambda"
] |
Python lambda function "translation" causes recursion error
| 39,441,290 |
<p>While attempting to understand python lambda functions, I "translated" this function:</p>
<pre><code>s = lambda y: y ** y; s(3)
</code></pre>
<p>Into this regular, defined function:</p>
<pre><code>def power_of_self(y):
return y ** y
power_of_self(3)
</code></pre>
<p>When I tried running it as a script (<code>python lambda_stuff.py</code>) I had no problem. However, when attempting to run it via the Python shell, this weird thing happened:</p>
<pre><code>>>> def power_of_self(y):
... return y ** y
... power_of_self(3)
File "<stdin>", line 3
power_of_self(3)
^
SyntaxError: invalid syntax
>>> print power_of_self(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in power_of_self
File "<stdin>", line 1, in power_of_self
File "<stdin>", line 1, in power_of_self
File "<stdin>", line 1, in power_of_self
**A FEW HUNDRED MORE OF THESE**
RuntimeError: maximum recursion depth exceeded
</code></pre>
<p>Why did my script execution differ from my shell execution? I wonder if the <code>...</code> had anything to do with it.</p>
| 0 |
2016-09-11T22:33:56Z
| 39,441,310 |
<p>Your function is still been defined in the shell. Hit an extra <kbd>Enter</kbd> before calling the function.</p>
| 1 |
2016-09-11T22:36:35Z
|
[
"python",
"lambda"
] |
Python 3 guessing game - int() argument error
| 39,441,314 |
<p>This is the code in its full extent at the moment:</p>
<pre><code>import random
import time
from tkinter import *
from tkinter import ttk
mode_chosen = 0
def update_mode():
global mode_chosen
mode_chosen = entry.get()
mode()
def mode():
if mode_chosen == "1":
new_player()
if mode_chosen == "2":
existing_player()
if mode_chosen == "3":
exit()
def new_player():
global username
entry_entry.pack_forget()
entry1_entry.pack()
choose_button.pack(side="bottom")
screen_var.set(" Make a username or\ntype exit to leave the game")
username = entry1.get()
if username == "exit":
exit()
if username != "":
screen_var.set("""Hello {}, here's how to play my game. I will think of a number between 1 and value depending on the difficulty you will choose, this will also decide how many tries you have to guess my number.""".format(username))
game()
def existing_player():
global username
entry_entry.pack_forget()
entry1_entry.pack()
choose_button.pack(side="bottom")
screen_var.set("Please enter your username or type exit to leave the game")
username = entry1.get()
if username == "exit":
exit()
if username != "":
screen_var.set("\nWelcome back {}.".format(username))
game()
def game():
top = 0
tries = 0
screen_var.set("Pick a level of difficulty (e.g 1, 2, 3) or type exit to leave the game")
entry1_entry.pack_forget()
entry2_entry.pack()
level = ""
level = entry2.get()
if level == "1":
top += 10
tries = 2
screen_var.set("\nWell I am thinking of a number between 1 and {}, you have {} tries to guess my number.\nType exit at anytime to leave the game.".format(top, tries + 1))
elif level == "2":
top += 20
tries = 5
screen_var.set("\nWell I am thinking of a number between 1 and {}, you have {} tries to guess my number.\nType exit at anytime to leave the game.".format(top, tries + 1))
elif level == "3":
top += 30
tries = 8
screen_var.set("\nWell I am thinking of a number between 1 and {}, you have {} tries to guess my number.\nType exit at anytime to leave the game.".format(top, tries + 1))
elif level == "exit":
exit()
number = random.randint(1, top)
guesses_taken = 0
entry2_entry.pack_forget()
entry3_entry.pack()
guess = entry3.get
answer = int(guess)
while guesses_taken <= tries:
screen_var.set("Take a guess: ")
guesses_taken += 1
if answer < 1:
print("Guess a number between 1 and {}.".format(top))
guess_taken -= 1
if answer > top:
print("Guess a number between 1 and {}.".format(top))
guess_taken -= 1
if answer < number:
print("Your guess is too low")
if answer > number:
print("Your guess is too high")
if answer == number:
break
if guess == "exit":
exit()
if answer == number:
print("Good job, {}! You guessed my number in {} guesses!".format(username, guesses_taken))
if answer != number:
print("Nope. The number I was thinking of was: {}.".format(number))
def exit():
root.destroy()
root = Tk()
root.title("Guessing Game")
label1 = Label(root, text="Guessing Game")
label1.pack()
screen_var = StringVar()
screen_var.set("""Choose a mode by entering the number:
1: New Player
2: Existing Player
3: Exit
""")
screen_label = Label(root, textvariable=screen_var, justify="left")
screen_label.pack()
answer_label = ttk.Label(root, text="Answer: ")
answer_label.pack()
entry = StringVar()
entry_entry = ttk.Entry(root, textvariable=entry)
entry_entry.pack()
entry1 = StringVar()
entry1_entry = ttk.Entry(root, textvariable=entry1)
entry2 = StringVar()
entry2_entry = ttk.Entry(root, textvariable=entry2)
entry3 = StringVar()
entry3_entry = ttk.Entry(root, textvariable=entry3)
choose_button = ttk.Button(root, text="Choose", command=update_mode)
choose_button.pack()
root.mainloop()
</code></pre>
<p>At the moment I am running through moving the programme into a python gui, when it comes in this part:</p>
<pre><code>answer = int(guess)
</code></pre>
<p>It gives me the error message of:</p>
<pre><code>Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\lewis\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "C:\Users\lewis\Desktop\GUI test\Gui_Game.py", line 11, in update_mode
mode()
File "C:\Users\lewis\Desktop\GUI test\Gui_Game.py", line 15, in mode
new_player()
File "C:\Users\lewis\Desktop\GUI test\Gui_Game.py", line 33, in new_player
game()
File "C:\Users\lewis\Desktop\GUI test\Gui_Game.py", line 81, in game
answer = int(guess)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'method'
</code></pre>
<p>If anyone can help me find a solution to this error, it would be greatly apprieciated. Thanks. </p>
| 0 |
2016-09-11T22:36:58Z
| 39,442,553 |
<p>Okay, so.</p>
<p>On line 77, you have</p>
<p><code>guess = entry3.get</code></p>
<p>entry3.get is a function. So instead it would be,</p>
<p><code>guess = entry3.get()</code></p>
<p>Sometimes you can use something like <code>print(type(entry3.get))</code> and it'll say</p>
<p><code><class 'method'> <bound method StringVar.get of <tkinter.StringVar object at 0x034A6410>></code></p>
<p>Which tells us it's a function and needs to have <code>()</code> after it.</p>
<p>Thanks,</p>
<p>~Coolq</p>
| 0 |
2016-09-12T02:14:34Z
|
[
"python"
] |
Replace all negative values in a list
| 39,441,323 |
<p>I'm trying to solve this problem on codewars and I'm completely stumped:</p>
<pre><code>y = [-1, -1, 2, 8, -1, 4]
z = [1,3,5]
#to create [1,3,2,8,5,4]
</code></pre>
<p>How would I do this?</p>
<p>I tried to do:</p>
<pre><code>for e in range(len(y)):
try:
if y[e] < 0:
y[e] = z[e]
except:
pass
</code></pre>
<p>But this would only work if the negatives correspond to what is in z.</p>
| 3 |
2016-09-11T22:37:47Z
| 39,441,344 |
<p>You're trying to use the same index for both lists, which doesn't appear to be the correct behaviour from your example. For example, the -1 in <code>y</code> is at index 4, but is replaced by the 5 in <code>z</code> at index 2.</p>
<pre><code>zindex = 0
for yindex in range(len(y)):
if y[yindex] < 0:
y[yindex] = z[zindex]
zindex += 1
</code></pre>
| 0 |
2016-09-11T22:41:12Z
|
[
"python",
"python-3.x"
] |
Replace all negative values in a list
| 39,441,323 |
<p>I'm trying to solve this problem on codewars and I'm completely stumped:</p>
<pre><code>y = [-1, -1, 2, 8, -1, 4]
z = [1,3,5]
#to create [1,3,2,8,5,4]
</code></pre>
<p>How would I do this?</p>
<p>I tried to do:</p>
<pre><code>for e in range(len(y)):
try:
if y[e] < 0:
y[e] = z[e]
except:
pass
</code></pre>
<p>But this would only work if the negatives correspond to what is in z.</p>
| 3 |
2016-09-11T22:37:47Z
| 39,441,354 |
<p>Your code:</p>
<pre><code>for e in range(len(y)):
if y[e] < 0: y[e] = z[e]
</code></pre>
<p>The problem with your code is let's say the 5th element is negative. You are attempting to set the 5th element of <code>y</code> to the 5th element of <code>z</code>. Instead, you should use a counter variable to track which element to substitute.</p>
<pre><code>element_z_index = 0
for e in range(len(y)):
if y[e] < 0:
y[e] = z[element_z_index]
element_z_index += 1
</code></pre>
| 0 |
2016-09-11T22:42:13Z
|
[
"python",
"python-3.x"
] |
Replace all negative values in a list
| 39,441,323 |
<p>I'm trying to solve this problem on codewars and I'm completely stumped:</p>
<pre><code>y = [-1, -1, 2, 8, -1, 4]
z = [1,3,5]
#to create [1,3,2,8,5,4]
</code></pre>
<p>How would I do this?</p>
<p>I tried to do:</p>
<pre><code>for e in range(len(y)):
try:
if y[e] < 0:
y[e] = z[e]
except:
pass
</code></pre>
<p>But this would only work if the negatives correspond to what is in z.</p>
| 3 |
2016-09-11T22:37:47Z
| 39,441,362 |
<p>If you are sure that number of negative numbers is always equal with <code>z</code> you can convert <code>z</code> to an iterable and use a list comprehension for creating your new list:</p>
<pre><code>In [9]: z = iter(z)
In [10]: [next(z) if i < 0 else i for i in y]
Out[10]: [1, 3, 2, 8, 5, 4]
</code></pre>
<p>Note that if the length of <code>z</code> is shorter than number of negative numbers it will raise an <code>StopIteration</code> error.</p>
| 11 |
2016-09-11T22:43:21Z
|
[
"python",
"python-3.x"
] |
Replace all negative values in a list
| 39,441,323 |
<p>I'm trying to solve this problem on codewars and I'm completely stumped:</p>
<pre><code>y = [-1, -1, 2, 8, -1, 4]
z = [1,3,5]
#to create [1,3,2,8,5,4]
</code></pre>
<p>How would I do this?</p>
<p>I tried to do:</p>
<pre><code>for e in range(len(y)):
try:
if y[e] < 0:
y[e] = z[e]
except:
pass
</code></pre>
<p>But this would only work if the negatives correspond to what is in z.</p>
| 3 |
2016-09-11T22:37:47Z
| 39,441,407 |
<p>One-liner. Emulate queue behavior using <code>pop()</code>. (<em>Note this consumes</em> <code>z</code>)</p>
<pre><code>>>> print([num if num > 0 else z.pop(0) for num in y])
[1, 3, 2, 8, 5, 4]
</code></pre>
| 4 |
2016-09-11T22:50:27Z
|
[
"python",
"python-3.x"
] |
Is it possible to use argparse for passing optional arguments without the dash symbol?
| 39,441,329 |
<p>I have a program which can take in a few different arguments, and depending on what the argument is that is passed, that function is called in the python program. I know how to use sys.arv, and I have used argparse before, however I am not sure how to go about accomplishing the following with argparse..</p>
<p>Possible arguments: func1, func2, func3</p>
<p>Program could be executed with either of the following:</p>
<pre><code>python myprogram func1
python myprogram func2
python myprogram func3
</code></pre>
<p>Therefore the arg passed correlates to a function in the program. I do not want to include any dashes in the arguments so nothing like -func1 or -func2...etc. </p>
<p>Thank you!</p>
| 0 |
2016-09-11T22:38:27Z
| 39,441,370 |
<pre><code> parser.add_argument('foo', choices=['func1','func2','func3'])
</code></pre>
<p>will accept one string, and raise an error if that string is not one of the chocies. The results will be a namespace like</p>
<pre><code> Namespace(foo='func1')
</code></pre>
<p>and</p>
<pre><code> print(args.foo)
# 'func1'
</code></pre>
<p>Is that what you want?</p>
<p>The subparsers mechanism does the same thing, but also lets you define added arguents that can differ depending on which subparser is given.</p>
| 1 |
2016-09-11T22:44:26Z
|
[
"python",
"argparse"
] |
How do you schedule cron jobs using APScheduler on Heroku?
| 39,441,337 |
<p>I am trying to use the APScheduler and SendGrid on Heroku to create a cron job for sending an email.</p>
<p>Even though the add_job method call seems to be executing correctly, I am getting the following error.</p>
<p>Below are the logs from heroku</p>
<pre><code>2016-09-11T22:33:37.776867+00:00 heroku[clock.1]: State changed from crashed to starting
2016-09-11T22:33:40.672563+00:00 heroku[clock.1]: Starting process with command `python clock.py`
2016-09-11T22:33:41.353373+00:00 heroku[clock.1]: State changed from starting to up
2016-09-11T22:33:43.527949+00:00 app[clock.1]: created background scheduler
2016-09-11T22:33:43.528848+00:00 app[clock.1]: started background scheduler
2016-09-11T22:33:43.572751+00:00 app[clock.1]: added cron job
2016-09-11T22:33:43.585801+00:00 app[clock.1]: Exception in thread APScheduler (most likely raised during interpreter shutdown):
2016-09-11T22:33:43.585807+00:00 app[clock.1]: Traceback (most recent call last):
2016-09-11T22:33:43.585808+00:00 app[clock.1]: File "/app/.heroku/python/lib/python2.7/threading.py", line 801, in __bootstrap_inner
2016-09-11T22:33:43.585810+00:00 app[clock.1]: File "/app/.heroku/python/lib/python2.7/threading.py", line 754, in run
2016-09-11T22:33:43.585827+00:00 app[clock.1]: File "/app/.heroku/python/lib/python2.7/site-packages/apscheduler/schedulers/blocking.py", line 29, in _main_loop
2016-09-11T22:33:43.585829+00:00 app[clock.1]: File "/app/.heroku/python/lib/python2.7/threading.py", line 614, in wait
2016-09-11T22:33:43.585848+00:00 app[clock.1]: File "/app/.heroku/python/lib/python2.7/threading.py", line 364, in wait
2016-09-11T22:33:43.585851+00:00 app[clock.1]: <type 'exceptions.ValueError'>: list.remove(x): x not in list
2016-09-11T22:33:43.695569+00:00 heroku[clock.1]: Process exited with status 0
2016-09-11T22:33:43.719265+00:00 heroku[clock.1]: State changed from up to crashed
</code></pre>
<p>I am running one clock process, which is in the clock.py file below.</p>
<pre><code>from apscheduler.schedulers.background import BackgroundScheduler
import sendgrid
import os
from sendgrid.helpers.mail import *
def send_email():
try:
sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
print("created send grid api client")
from_email = Email("ohta.g@husky.neu.edu")
print("created from email")
subject = "Weekly update"
to_email = Email("ohta.g@husky.neu.edu")
print("created to email")
content = Content("text/plain", "Hello, Email!")
print("created content")
mail = Mail(from_email, subject, to_email, content)
print("created mail")
response = sg.client.mail.send.post(request_body=mail.get())
except Exception as e:
return e
try:
sched = BackgroundScheduler()
print("created background scheduler")
sched.start()
print("started background scheduler")
sched.add_job(send_email, 'cron', day_of_week=6, hour=22, minute=20)
print("added cron job")
except Exception as e:
print e.message
</code></pre>
<p>Here is my Procfile.</p>
<pre><code>clock: python clock.py
</code></pre>
<p>Here is my requirements.txt file.</p>
<pre><code>APScheduler==3.1.0
sendgrid==3.4.0
</code></pre>
<p>Could someone please tell me what I'm doing wrong?</p>
| 1 |
2016-09-11T22:39:48Z
| 39,454,744 |
<p>You started a background scheduler but then allowed your main thread to exit, which also exits the clock process. This is the entire reason why <code>BlockingScheduler</code> exists. Have you not read Heroku's <a href="https://devcenter.heroku.com/articles/clock-processes-python" rel="nofollow">APScheduler instructions</a>?</p>
| 0 |
2016-09-12T16:22:53Z
|
[
"python",
"heroku",
"cron",
"sendgrid",
"apscheduler"
] |
How to create three separate lists of values from a Python list of dictionaries where each dictionary has three keys
| 39,441,348 |
<p>I am new to Python. My question might come across as simple to experienced developers and coders but I haven't been able to find out an answer to this. </p>
<p>I am retrieving some data through a database query. I have succeeded in organising each row returned by query as a dictionary having three keys and a corresponding value to each key. Essentially, I have organised all rows of data returned by the query into a list of dictionaries.</p>
<p>The list of dictionaries looks somewhat like this:</p>
<pre><code>[
{'Date': date1, 'price': price1, 'itemnumber': number1},
{'Date': date2, 'price': price2, 'itemnumber': number2},
...
]
</code></pre>
<p>How can I convert this list of dictionaries into three separate lists corresponding to each key i.e. Date, Price and itemnumber?</p>
<p>Thank you for your help. </p>
| 2 |
2016-09-11T22:41:27Z
| 39,441,383 |
<pre><code># Defining lists
dates = []
prices = []
item_numbers = []
# Loop through list
for dictionary in your_list:
dates.append(dictionary["Date"]) # Add the date to dates
prices.append(dictionary["price"]) # Add the price to prices
# Add item number to item_numbers
item_numbers.append(dictionary["itemnumber"])
</code></pre>
| 1 |
2016-09-11T22:46:13Z
|
[
"python",
"list",
"dictionary"
] |
How to create three separate lists of values from a Python list of dictionaries where each dictionary has three keys
| 39,441,348 |
<p>I am new to Python. My question might come across as simple to experienced developers and coders but I haven't been able to find out an answer to this. </p>
<p>I am retrieving some data through a database query. I have succeeded in organising each row returned by query as a dictionary having three keys and a corresponding value to each key. Essentially, I have organised all rows of data returned by the query into a list of dictionaries.</p>
<p>The list of dictionaries looks somewhat like this:</p>
<pre><code>[
{'Date': date1, 'price': price1, 'itemnumber': number1},
{'Date': date2, 'price': price2, 'itemnumber': number2},
...
]
</code></pre>
<p>How can I convert this list of dictionaries into three separate lists corresponding to each key i.e. Date, Price and itemnumber?</p>
<p>Thank you for your help. </p>
| 2 |
2016-09-11T22:41:27Z
| 39,441,384 |
<p>You could combine a listcomp and a dictcomp:</p>
<pre><code>In [95]: ds
Out[95]:
[{'Date': 'date1', 'itemnumber': 'number1', 'price': 'price1'},
{'Date': 'date2', 'itemnumber': 'number2', 'price': 'price2'}]
In [96]: {key: [subdict[key] for subdict in ds] for key in ds[0]}
Out[96]:
{'Date': ['date1', 'date2'],
'itemnumber': ['number1', 'number2'],
'price': ['price1', 'price2']}
</code></pre>
<p>Note that we have three separate lists, they're just more conveniently stored as values in a dictionary. This way, if we decide that we want to add an additional trait (say, "purchaser"), we don't need to change any of the logic.</p>
| 3 |
2016-09-11T22:46:14Z
|
[
"python",
"list",
"dictionary"
] |
How to create three separate lists of values from a Python list of dictionaries where each dictionary has three keys
| 39,441,348 |
<p>I am new to Python. My question might come across as simple to experienced developers and coders but I haven't been able to find out an answer to this. </p>
<p>I am retrieving some data through a database query. I have succeeded in organising each row returned by query as a dictionary having three keys and a corresponding value to each key. Essentially, I have organised all rows of data returned by the query into a list of dictionaries.</p>
<p>The list of dictionaries looks somewhat like this:</p>
<pre><code>[
{'Date': date1, 'price': price1, 'itemnumber': number1},
{'Date': date2, 'price': price2, 'itemnumber': number2},
...
]
</code></pre>
<p>How can I convert this list of dictionaries into three separate lists corresponding to each key i.e. Date, Price and itemnumber?</p>
<p>Thank you for your help. </p>
| 2 |
2016-09-11T22:41:27Z
| 39,441,386 |
<pre><code>for (field,values) in [(field,
[result.get(field) for result in results]
) for field in results[0].keys()]:
# this is ugly, but I can't see any other legal way to
# dynamically set variables.
eval "%s=%s" % (field, repr(value))
</code></pre>
<p><em>Edited to not [illegally] modify the <code>locals()</code> dictionary :(</em></p>
| 0 |
2016-09-11T22:46:35Z
|
[
"python",
"list",
"dictionary"
] |
How to create three separate lists of values from a Python list of dictionaries where each dictionary has three keys
| 39,441,348 |
<p>I am new to Python. My question might come across as simple to experienced developers and coders but I haven't been able to find out an answer to this. </p>
<p>I am retrieving some data through a database query. I have succeeded in organising each row returned by query as a dictionary having three keys and a corresponding value to each key. Essentially, I have organised all rows of data returned by the query into a list of dictionaries.</p>
<p>The list of dictionaries looks somewhat like this:</p>
<pre><code>[
{'Date': date1, 'price': price1, 'itemnumber': number1},
{'Date': date2, 'price': price2, 'itemnumber': number2},
...
]
</code></pre>
<p>How can I convert this list of dictionaries into three separate lists corresponding to each key i.e. Date, Price and itemnumber?</p>
<p>Thank you for your help. </p>
| 2 |
2016-09-11T22:41:27Z
| 39,441,390 |
<p>Use <em>list comprehensions</em>:</p>
<pre><code>date = [d['Date'] for d in list_of_dicts]
price = [d['price'] for d in list_of_dicts]
itemnumber = [d['itemnumber'] for d in list_of_dicts]
</code></pre>
<hr>
<p>One could also do this in a less readable one liner:</p>
<pre><code>date, price, itemnumber = zip(*[(d['Date'], d['price'], d['itemnumber']) for d in list_of_dicts])
</code></pre>
<p>Use <code>map(list, ...)</code> to turn the returned tuples into lists in the second case.</p>
| 5 |
2016-09-11T22:47:33Z
|
[
"python",
"list",
"dictionary"
] |
Django custom decorator user_passes_test() can it obtain url parameters?
| 39,441,429 |
<p>Can Django's <code>user_passes_test()</code> access view parameters?</p>
<p>For example I have view that receives an <code>id</code> to retrieve specific record:</p>
<pre><code>def property(request, id):
property = Property.objects.get(id=int(id))
</code></pre>
<p>The record has a field named user_id that contains the id for user that originally created record. I want users to be able to view only their own records otherwise be redirected.</p>
<p>I'd like to use a custom decorator which seems simple and clean.</p>
<p>For custom decorator is there some variation of something like this that will work? </p>
<pre><code>@user_passes_test(request.user.id = Property.objects.get(id=int(id)).id, login_url='/index/')
def property(request, id):
property = Property.objects.get(id=int(id))
</code></pre>
<p>I have tried creating separate <code>test_func</code> named <code>user_is_property_owner</code> to contain logic to compare current user to property record user_id</p>
<pre><code>@user_passes_test(user_is_property_owner(id), login_url='/index/')
def property(request, id):
property = Property.objects.get(id=int(id))
def user_is_property_owner(property_id):
is_owner = False
try:
Property.objects.filter(id=property_id, user_id=user_id).exists()
is_owner = True
except Property.DoesNotExist:
pass
</code></pre>
<p>But having trouble getting current user id and the property id from the request into the <code>user_is_property_owner</code> decorator function.</p>
<hr>
<p>EDIT to add solution I was using. I did test inside each view test was required. It is simple. i thought using a decorator might be prettier and slightly more simple. </p>
<pre><code>def property(request, id):
# get object
property = Property.objects.get(id=int(id))
# test if request user is not user id on property record
if request.user.id != property.user_id:
# user is not same as property user id so redirect to index
return redirect('index')
# rest of the code if request user is user_id on property record
# eg it is ok to let user into view
</code></pre>
| 0 |
2016-09-11T22:55:26Z
| 39,441,690 |
<p>Typically, (using class based views), I'll handle this in the <code>get_queryset</code> method so it would be something like</p>
<pre><code>class PropertyDetail(DetailView):
def get_queryset(self):
return self.request.user.property_set.all()
</code></pre>
<p>and that will give a 404 if the property isn't for the current user. You might prefer to use a project like <a href="https://github.com/django-guardian/django-guardian" rel="nofollow">django-guardian</a> if you end up with more permission relationships than just <code>Property</code>.</p>
<p>If you take a look at <a href="https://github.com/django/django/blob/c1aec0feda73ede09503192a66f973598aef901d/django/contrib/auth/mixins.py" rel="nofollow">UserPassesTestMixin</a> you'll see that it processes the <code>test_func</code> before calling <code>dispatch</code> so you'll have to call <code>self.get_object(request)</code> yourself if you decide to go that route.</p>
| 1 |
2016-09-11T23:40:23Z
|
[
"python",
"django"
] |
Simplejson decoding error only occurs when performing over two iterations
| 39,441,433 |
<p>I'm trying to use the names module along with a wrapper for temp-mail.org (<a href="https://github.com/saippuakauppias/temp-mail" rel="nofollow">https://github.com/saippuakauppias/temp-mail</a>) for part of a project involving creating temporary email addresses. My code is as shown below and works fine unless n is greater than 2. </p>
<pre><code>import names
from random import randint
from tempmail import TempMail
n = input("Please enter number of email addresses: ")
i = 0
while i < n:
first = names.get_first_name()
second = names.get_last_name()
tm = TempMail(login= first + "." + second + str(randint(1,99)))
email = tm.get_email_address()
print email
i = i+1
</code></pre>
<p>If n is greater than two the loop will execute twice then I receive the following error: </p>
<pre><code>>>> runfile('/root/voter.py', wdir='/root')
Please enter number of email addresses: 3
Randell.Elkin17@stexsy.com
Michael.Martinez6@stexsy.com
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 714, in runfile
execfile(filename, namespace)
File "/usr/local/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 81, in execfile
builtins.execfile(filename, *where)
File "/root/voter.py", line 12, in <module>
email = tm.get_email_address()
File "/usr/local/lib/python2.7/dist-packages/tempmail.py", line 66, in get_email_address
available_domains = self.available_domains
File "/usr/local/lib/python2.7/dist-packages/tempmail.py", line 36, in available_domains
domains = req.json()
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 826, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 516, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code></pre>
<p>I know this is a longshot as the tempmail module isn't widely used however I was hoping I've made a simple error elsewhere and someone could help? Thanks</p>
| 1 |
2016-09-11T22:55:59Z
| 39,441,567 |
<p>Okay so I looked over your problem.</p>
<p>The package <a href="https://github.com/saippuakauppias/temp-mail" rel="nofollow">temp-mail</a> seems to make a request to temp-mail.ru <em>each</em> time you call <code>TempMail()</code> to get a list of available domains.</p>
<p>You are encountering the API's <a href="https://en.wikipedia.org/wiki/Rate_limiting" rel="nofollow">rate limiting</a> (in short, you are calling the API too many times in a too short window)</p>
<p>I added some debug to the package to see what was happening. I created a <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a> to test your code. This makes modules that I install (<code>temp-mail</code> and <code>names</code> only local to the project and not globally installed on the system) and looked at the stacktrace. The line that calls the json part is <code>domains = req.json()</code>, located at <code>/home/arch/tmp-tempmail/env/lib/python2.7/site-packages/tempmail.py</code>.</p>
<p>I then edited the file to add some prints (you have to have some notions about the <a href="https://github.com/kennethreitz/requests" rel="nofollow">request</a> module first):</p>
<pre><code>url = 'http://{0}/request/domains/format/json/'.format(
self.api_domain)
req = requests.get(url)
print req
print req.text
domains = req.json()
</code></pre>
<p>The output is:</p>
<pre><code>Please enter number of email addresses: 3
<Response [200]>
["@stexsy.com"]
Larry.Gerald20@stexsy.com
<Response [200]>
["@stexsy.com"]
Darlene.Bullock32@stexsy.com
<Response [429]>
Traceback (most recent call last):
File "main.py", line 29, in <module>
email = tm.get_email_address()
File "/home/arch/tmp-tempmail/env/lib/python2.7/site-packages/tempmail.py", line 68, in get_email_address
available_domains = self.available_domains
File "/home/arch/tmp-tempmail/env/lib/python2.7/site-packages/tempmail.py", line 38, in available_domains
domains = req.json()
File "/home/arch/tmp-tempmail/env/lib/python2.7/site-packages/requests/models.py", line 826, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib64/python2.7/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python2.7/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/python2.7/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code></pre>
<p>You can see that at the response that fails is the third one and it has the HTTP error code 429 which translates to "Too Many Requests".
The JSON parser crashes just because the input is empty.</p>
<p>On the other hand, the API's <a href="https://temp-mail.org/en/api/" rel="nofollow">docs</a> says:</p>
<blockquote>
<p>You can generate absolutely any email address without API notification</p>
</blockquote>
<p>So if you have the domain, you don't need to make a request to the server for receiving mails on the server.</p>
<p>You could also add a delay inside the loop.</p>
<pre><code>import names
from random import randint
from tempmail import TempMail
import time
n = input("Please enter number of email addresses: ")
i = 0
while i < n:
first = names.get_first_name()
second = names.get_last_name()
tm = TempMail(login= first + "." + second + str(randint(1,99)))
email = tm.get_email_address()
print email
time.sleep(1)
i = i+1
</code></pre>
| 0 |
2016-09-11T23:19:15Z
|
[
"python",
"json"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.