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
No JSON object could be decoded, JvectorMap Converter
38,929,030
<p>Scenario is,</p> <p>Im new to python and trying to generate jvectorMap using <code>Converter.py</code> plugin provided by <code>jVectorMap</code>,</p> <p>I have installed OSGEO4W (Desktop INSTALL) on Windows 7 64bit. Python 2.7,GDAL 2.1.0 and Shapely is also installed under OSGEO4W.</p> <p>I download shapefile</p> <pre><code>ne_10m_admin_1_states_provinces.shp </code></pre> <p>I placed this shape file in converter.py directory, then I opened OSGEO4W shell and navigates to converter.py directory and run following command to generate Russia map for learning conversion of maps.</p> <pre><code>python converter.py ne_10m_admin_1_states_provinces.shp test-map.js --width 400 --where "ISO_3166_2 = 'RU-' and code_hasc!='' --country_name_index 12 --country_code_index 18 --minimal_area 4000000 --buffer_distance -0.5 --simplify_tolerance 10000 --longitude0 54.8270 --name russia </code></pre> <p>I have taken this command from this post How to generate a new map for jvectormap jquery plugin? but I faced error JSON object Decode, have a look on below image <a href="http://i.stack.imgur.com/Gx63H.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/Gx63H.jpg" alt="enter image description here"></a></p> <p>Help me to solve my problem ,As I have stated im new to python and jvector Maps</p>
0
2016-08-13T03:56:34Z
38,929,056
<p>I suspect the issue is that the passed in arguments cannot be converted to JSON by the script due to a missing double quote at the end of your <code>--where</code>. It should probably be:</p> <pre><code>--where "ISO_3166_2 = 'RU-' and code_hasc!=''" </code></pre> <p><strong>EDIT</strong>:</p> <p>Turns out it's a larger issue. If you look at the source code for <a href="https://github.com/bjornd/jvectormap/blob/master/converter/converter.py" rel="nofollow">converter.py</a>, you'll find this:</p> <pre><code>args = {} if len(sys.argv) &gt; 1: paramsJson = open(sys.argv[1], 'r').read() else: paramsJson = sys.stdin.read() paramsJson = json.loads(paramsJson) </code></pre> <p>So, it looks like this script cannot be called this way. It's either expecting a file with this JSON in it, or for the params to be passed through stdin. The <a href="http://jvectormap.com/documentation/gis-converter/" rel="nofollow">documentation</a> seems to agree with this.</p>
0
2016-08-13T04:02:55Z
[ "python", "json", "windows", "shapefile", "jvectormap" ]
Splitting a dictionary's multiple values from one key
38,929,119
<p>I have the dictionary:</p> <pre><code>dict1 = {'A': {'val1': '5', 'val2': '1'}, 'B': {'val1': '10', 'val2': '10'}, 'C': {'val1': '15', 'val3': '100'} </code></pre> <p>Here, I have one key, with two values. I can obtain the key by using:</p> <pre><code>letters = dict1.keys() </code></pre> <p>which returns:</p> <pre><code> ['A', 'B', 'C'] </code></pre> <p>I am use to working with arrays and being able to "slice" them. How can I break this dictionary in a similar way as the key for the values?</p> <pre><code> val1_and_val2 = dict1.values() </code></pre> <p>returns:</p> <pre><code> [{'val1': '5', 'val2': '1'}, {'val1': '10', 'val2': '10'}, {'val1': '15', 'val2': '100'}] </code></pre> <p>How can I get:</p> <pre><code> number1 = [5, 10, 15] number2 = [1, 10, 100] </code></pre>
0
2016-08-13T04:14:44Z
38,929,182
<p>If I understand you correctly then:</p> <pre><code>number1 = [val["val1"] for val in dict1.values()] </code></pre> <p>If you prefer, this will accomplish the same thing with lambdas.</p> <pre><code>number1 = map(lambda value: value["val1"], dict1.values()) </code></pre> <p>Note how you really need to take the dict1[key]["val1"] to get an individual value.</p>
1
2016-08-13T04:26:59Z
[ "python", "python-2.7", "dictionary" ]
modifying argument value within function
38,929,137
<p>I am trying to figure out a way to modify the order of a list of tuples within a function without returning the list.</p> <p>For example:</p> <pre><code>L = [(2,4),(8,5),(1,3),(9,4)] def sort_ratios(L): L = sorted(L, key=lambda x: float(x[0])/float(x[1])) return L </code></pre> <p>Thus, calling sort_ratios() outputs:</p> <pre><code>&gt;&gt;&gt;sort_ratios(L) [(1,3),(2,4),(8,5),(9,4)] </code></pre> <p>But <code>L</code> would still be <code>[(2,4),(8,5),(1,3),(9,4)]</code> Instead, I would like to simply modify the value of L without returning anything so that <code>sort_ratios()</code> operates as follows:</p> <pre><code>&gt;&gt;&gt;sort_ratios(L) &gt;&gt;&gt;L [(1,3),(2,4),(8,5),(9,4)] </code></pre> <p>It seems trivial, but I just can't seem to get the function to operate this way.</p>
0
2016-08-13T04:18:10Z
38,929,170
<p>Try <code>L.sort(key=lambda x: float(x[0])/float(x[1]))</code> for an in-place sort.</p>
4
2016-08-13T04:25:28Z
[ "python" ]
"RuntimeError: working outside of application context" for config module
38,929,153
<p>I have a config.py module that I call from my main file, it has a variety of app.configs for jinja2filters and some other plugins I'm using:</p> <p>excerpt of config.py:</p> <pre><code>from flask import current_app as app #imports go here def function1: print("hello") app.config['PROPERTY_1'] = 'configgoeshere' #jinja2 functions and configs would go here like app.jinja_env.filters['datetime'] = datetimeformat </code></pre> <p>calling from index.py:</p> <pre><code>from flask import Flask, flash, render_template, jsonify, request, json, request, redirect, url_for, Response, send_from_directory app = Flask(__name__) app.config['DEBUG'] = False app.config.from_object('config') #config file ############################################################################################################################ # MAIN ROUTES ############################################################################################################################ # The route for the homepage @app.route('/') def index(): </code></pre> <p>returns the error:</p> <pre><code>RuntimeError: working outside of application context </code></pre> <p><strong>Update</strong> I'm trying to pass the application context along now, here is index.py:</p> <pre><code>from flask import Flask, flash, render_template, jsonify, request, json, request, redirect, url_for, Response, send_from_directory import time, datetime, os, urllib, urllib2, urlparse, requests, json, string from urllib2 import Request, urlopen, URLError, HTTPError, urlparse app = Flask(__name__) app.config['DEBUG'] = False app.config.from_object('config') ############################################################################################################################ # MAIN ROUTES ############################################################################################################################ # The route for the homepage @app.route('/') def index(): </code></pre> <p>Here's the updated excerpt config.py:</p> <pre><code>from index import app #imports go here def function1: print("hello") app.config['PROPERTY_1'] = 'configgoeshere' #jinja2 functions and configs would go here like app.jinja_env.filters['datetime'] = datetimeformat </code></pre> <p>The error returned is:</p> <pre><code>$ python index.py Traceback (most recent call last): File "index.py", line 8, in &lt;module&gt; app.config.from_object('config') File "C:\Python27\lib\site-packages\flask\config.py", line 162, in from_object obj = import_string(obj) File "C:\Python27\lib\site-packages\werkzeug\utils.py", line 418, in import_string __import__(import_name) File "C:\Users\****\Desktop\*****\config.py", line 1, in &lt;module&gt; from index import app File "C:\Users\***\Desktop\*****\index.py", line 17, in &lt;module&gt; @app.route('/') File "C:\Python27\lib\site-packages\werkzeug\local.py", line 343, in __getattr__ return getattr(self._get_current_object(), name) File "C:\Python27\lib\site-packages\werkzeug\local.py", line 302, in _get_current_object return self.__local() File "C:\Python27\lib\site-packages\flask\globals.py", line 34, in _find_app raise RuntimeError('working outside of application context') RuntimeError: working outside of application context </code></pre> <p>Note - there is no code on line 162 inside of config.py like the error suggests</p>
0
2016-08-13T04:22:46Z
38,929,258
<p>Check out Flask's explanation of <a href="http://flask.pocoo.org/docs/0.10/appcontext/#creating-an-application-context" rel="nofollow">Application Contexts</a>.</p> <p>In your <code>config.py</code> file, the <code>from flask import current_app as app</code> makes it so that the call to <code>app.config['PROPERTY_1'] = 'configgoeshere'</code> actually tries to set the config on <code>current_app</code>, though there's no application context by default until a request comes in (hence the error). Since that call is not within a function, it is executed immediately before anything else (like a request) can happen.</p> <p>I would suggest doing the config on the <code>app</code> instance in index instead of on <code>current_app</code>.</p>
0
2016-08-13T04:41:13Z
[ "python", "flask", "jinja2" ]
pandas DataFrame columns named True and False work just fine
38,929,267
<p>The sample code:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(5,2), columns=[True, False]) # All of the following works fine. Just like you would expect # them to, if the columns had any other (string) name. # (Because True == True, True == False and False == False are # valid comparisons -- they have to be.) df.loc[:, True] df.loc[:, False] df.loc[:, [col for col in df.columns if col]] df.loc[:, :] # However, the below line, only returns column `True`. But if # the names were strings, it would return both columns. df.loc[:, [True, False]] </code></pre> <p>What <a href="http://www.mememaker.net/static/images/memes/2707704.jpg" rel="nofollow">witchcraft</a> makes this possible? I thought some check for keys will fail. But they didn't and I had to ask because they didn't.</p> <p>So rephrasing my question: How does pandas (Python, for that matter) decide between Boolean and non-Boolean (for lack of better expression) indexing? How does it avoid confusion? And what prevents misbehavior? Had the first line (<code>df = pd.DataFrame(np.random.rand(5,2), columns=[True, False])</code>) returned a single column (<code>True</code>) I would have been less surprised.</p>
2
2016-08-13T04:42:26Z
38,929,383
<p>There is no witchcraft. As far as I know, columns can be labeled by any hashable type. Given that booleans are instances of ints, is it really any more strange than: </p> <pre><code>In [7]: df1 = pd.DataFrame(np.random.rand(5,2), columns=[0, 1]) In [8]: df1 Out[8]: 0 1 0 0.706135 0.307180 1 0.713418 0.006204 2 0.308810 0.688868 3 0.582871 0.738771 4 0.418600 0.948231 </code></pre> <p>However, since <code>.loc</code> lets you select by label, there is one way where boolean labels will be ambiguous. Consider what I can do with my <code>int</code> labelled columns:</p> <pre><code>In [10]: df1.loc[:, [1, 0]] Out[10]: 1 0 0 0.307180 0.706135 1 0.006204 0.713418 2 0.688868 0.308810 3 0.738771 0.582871 4 0.948231 0.418600 </code></pre> <p>However, if I try to do the same thing with the boolean labelled columns:</p> <pre><code>In [11]: df Out[11]: True False 0 0.487752 0.545283 1 0.921928 0.715808 2 0.618667 0.946385 3 0.975142 0.078050 4 0.994348 0.468887 In [12]: df.loc[:, [False, True]] Out[12]: False 0 0.545283 1 0.715808 2 0.946385 3 0.078050 4 0.468887 </code></pre> <p>Whoops! now it is reverting to boolean indexing behavior. Still, you can always use <code>.iloc</code>:</p> <pre><code>In [13]: df.iloc[:, [1, 0]] Out[13]: False True 0 0.545283 0.487752 1 0.715808 0.921928 2 0.946385 0.618667 3 0.078050 0.975142 4 0.468887 0.994348 </code></pre> <h2>Edit to address OP edit </h2> <p>Notice, however, that <code>df = pd.DataFrame(np.random.rand(5,2), columns=[True, False])</code> is works fine because it isn't an indexing or selection operation, it is creating a DataFrame. Finally, notice that:</p> <pre><code>In [17]: df.loc[:, [False]] Out[17]: Empty DataFrame Columns: [] Index: [0, 1, 2, 3, 4] </code></pre> <p>Also uses boolean indexing on the columns, as expected. So, it reverts to boolean indexing as far as I can tell.</p> <h1>Edit by asker</h1> <p>Do also see <a href="http://stackoverflow.com/a/38930045/3765319">this answer</a> to the question to get the other part of the story.</p>
2
2016-08-13T05:01:04Z
[ "python", "pandas" ]
pandas DataFrame columns named True and False work just fine
38,929,267
<p>The sample code:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(5,2), columns=[True, False]) # All of the following works fine. Just like you would expect # them to, if the columns had any other (string) name. # (Because True == True, True == False and False == False are # valid comparisons -- they have to be.) df.loc[:, True] df.loc[:, False] df.loc[:, [col for col in df.columns if col]] df.loc[:, :] # However, the below line, only returns column `True`. But if # the names were strings, it would return both columns. df.loc[:, [True, False]] </code></pre> <p>What <a href="http://www.mememaker.net/static/images/memes/2707704.jpg" rel="nofollow">witchcraft</a> makes this possible? I thought some check for keys will fail. But they didn't and I had to ask because they didn't.</p> <p>So rephrasing my question: How does pandas (Python, for that matter) decide between Boolean and non-Boolean (for lack of better expression) indexing? How does it avoid confusion? And what prevents misbehavior? Had the first line (<code>df = pd.DataFrame(np.random.rand(5,2), columns=[True, False])</code>) returned a single column (<code>True</code>) I would have been less surprised.</p>
2
2016-08-13T04:42:26Z
38,930,045
<p>There is no witchcraft!</p> <p>The cool thing about <code>loc</code> is that you can pass boolean masks along side label indexing. The developers decided that if <code>loc</code> sees an array like structure of boolean values... then its going to be a mask.</p> <pre><code>df[False] 0 0.385615 1 0.212807 2 0.312314 3 0.826243 4 0.431003 dtype: float64 </code></pre> <hr> <pre><code>df.loc[:, False] 0 0.385615 1 0.212807 2 0.312314 3 0.826243 4 0.431003 dtype: float64 </code></pre> <hr> <pre><code># Looks like a mask df.loc[:, [False]] Empty DataFrame Columns: [] Index: [0, 1, 2, 3, 4] </code></pre> <p>Here's an idea. Don't play with bizarre edge cases and expect everything to be perfect. Just use normal column labels. I also wouldn't try to fly a helicopter in a vacuum and ask why it didn't fly.</p>
1
2016-08-13T06:50:19Z
[ "python", "pandas" ]
pytesser giving import error
38,929,372
<p>I am trying to implement OCR in python. When I run the following code:</p> <pre><code>from PIL import Image from pytesser import * image_file = 'menu.jpg' im = Image.open(image_file) text = image_to_string(im) text = image_file_to_string(image_file) text = image_file_to_string(image_file, graceful_errors=True) print "=====output=======\n" print text </code></pre> <p>I get the following error:</p> <pre><code>Traceback (most recent call last): File "C:/Python27/ocr.py", line 2, in &lt;module&gt; from pytesser import * File "C:/Python27\pytesser.py", line 6, in &lt;module&gt; ImportError: No module named Image </code></pre> <p>I have a folder name <code>pytesser</code> in my <code>C:\Python27\Lib\site-packages</code> directory and also one named <code>PIL</code> in the same directory which is from the installation of PILLOW.</p> <p>Edit: I tried the solution at <a href="http://stackoverflow.com/questions/26505958/why-cant-python-import-image-from-pil">Why can&#39;t Python import Image from PIL?</a>. But it doesn't seem to help</p>
1
2016-08-13T04:59:19Z
38,929,467
<p>As per the traceback, error is not from <code>pytesser</code> in <code>c:\Python27\Lib\Site-Packages</code>, it is coming from <code>C:\Python27\pytesser.py line 6</code></p> <p>Can you share the code at C:\Python27\pytesser.py line 6? or debug it by looking at code at <code>C:\Python27\pytesser.py line 6</code></p> <p>If you want your ocr.py to use pytesser at C:\Python27\Lib\site-packages (if it exists), please remove pytesser.py from the directory of ocr.py</p> <p>If it is coded by you, ideally it should be <code>from PIL import Image</code>, not <code>import Image</code></p>
0
2016-08-13T05:15:21Z
[ "python", "python-2.7" ]
How to pass a username from a Django login form?
38,929,433
<p>This will be an easy question for someone out there. I searched around quite a bit and if there's a thread that addresses this perfectly, please direct me and close this out. I'm building a very simple web form within our organization's website using Django. </p> <p>In forms.py I've got a class for the login page:</p> <pre><code>class userLogin(forms.Form): user = forms.CharField(label = 'Username ', max_length = 25) pwd = forms.CharField(label = 'Password ', widget = forms.PasswordInput) def clean(self): cleaned_data = super(userLogin, self).clean() user = cleaned_data.get("user") pwd = cleaned_data.get("pwd") if not fs.authenticateUser(user, pwd): raise forms.ValidationError("Invalid password!") </code></pre> <p>I have to authenticate against our website's API, which is what the fs.authenticate bit is about; it just returns True or False. In views.py I do this:</p> <pre><code> if request.method == 'POST': user_form = userLogin(data = request.POST) if user_form.is_valid(): return redirect('PickupAuthorization/main') else: pass </code></pre> <p>The authentication and redirection to the main page works splendidly, and the login form throws an invalid password message as expected when the credential is incorrect. What I want to know is how to make "user" available to views.py. If I try to reference user_form.user in the view, Python tells me that user is not an attribute of userLogin!</p> <p>I haven't done much with OOP, so I'm imagining that this has a simple answer, but I can't freakin' find it. Thanks!</p> <p>EDIT: I have had to shelve this project for the moment in favor of more pressing matters, but I will update it when I have a solution that works properly.</p>
0
2016-08-13T05:11:16Z
38,930,075
<p>You need to use <code>authenticate</code> method provided by <code>Django</code> in order to get the user. The <code>authenticate</code> method returns a user if it finds one. <br> To <code>authenticate</code> a given <code>username</code> and <code>password</code>, use <code>authenticate()</code>. It takes two keyword arguments, <code>username</code> and <code>password</code>, and it returns a <code>User object</code> if the <code>password</code> is valid for the given <code>username</code>. If the <code>password</code> is invalid, <code>authenticate()</code> returns <code>None</code>:</p> <p>Generally the flow using <code>authenticate</code> goes like this:</p> <p><strong>forms.py</strong></p> <pre><code>class userLogin(forms.Form): user = forms.CharField(label = 'Username ', max_length = 25) pwd = forms.CharField(label = 'Password ', widget = forms.PasswordInput) def __init__(self, *args, **kwargs): self.user_cache = None # You need to make the user as None initially super(LoginForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(userLogin, self).clean() user = cleaned_data.get("user") pwd = cleaned_data.get("pwd") # Now you get the user self.user_cache = authenticate(username=user, password=pwd) # Do other stuff return self.cleaned_data # Function to return user in views def get_user(self): return self.user_cache </code></pre> <p><strong>Views.py</strong></p> <pre><code>if request.method == 'POST': user_form = userLogin(data = request.POST) # You can now get user using the get_user method user = user_form.get_user() # Do other stuff </code></pre> <p>Another thing I'd like to add is if your user has already logged in you can simply do <code>request.user.username</code> in your <code>views.py</code> to get the current user.</p>
0
2016-08-13T06:53:31Z
[ "python", "django", "django-forms" ]
How can I insert the Python timestamp time.strftime into a pathname for the filename output?
38,929,493
<p>Goal is to put a date-timestamp as the filename for output of photos of a Python script.</p> <pre><code>timestr=time.strftime("%Y%m%d-%H%M%S") </code></pre> <p>gives me exactly what I want for print (timestr) but I cannot figure out how to insert this string for the file name into what I am given by:</p> <pre><code>camera.capture('/path/to/save/file.jpg') </code></pre>
0
2016-08-13T05:19:56Z
38,929,615
<p>you are halfway done, now just try to change the file name that you are saving </p> <pre><code>dir_path='path/to/save/' timestr=time.strftime("%Y%m%d-%H%M%S") file_name=timestr + '.jpg' #file name path=dir_path+file_name #abs path of file camera.capture(path) </code></pre>
0
2016-08-13T05:38:40Z
[ "python" ]
How can I insert the Python timestamp time.strftime into a pathname for the filename output?
38,929,493
<p>Goal is to put a date-timestamp as the filename for output of photos of a Python script.</p> <pre><code>timestr=time.strftime("%Y%m%d-%H%M%S") </code></pre> <p>gives me exactly what I want for print (timestr) but I cannot figure out how to insert this string for the file name into what I am given by:</p> <pre><code>camera.capture('/path/to/save/file.jpg') </code></pre>
0
2016-08-13T05:19:56Z
38,932,335
<p>Here's a proper solution:</p> <pre><code>import time import os timestr, file_path = time.strftime("%Y%m%d-%H%M%S"), '/path/to/save/file.jpg' filename, file_extension = os.path.splitext(file_path) output = "{0}_{1}{2}".format(filename, timestr, file_extension) print timestr, filename, output </code></pre> <p>output variable will have the desired result</p>
0
2016-08-13T11:41:28Z
[ "python" ]
Numpy: Reshape array along a specified axis
38,929,531
<p>I have the following array:</p> <pre><code>x = np.arange(24).reshape((2,3,2,2)) array([[[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[ 8, 9], [10, 11]]], [[[12, 13], [14, 15]], [[16, 17], [18, 19]], [[20, 21], [22, 23]]]]) </code></pre> <p>I would like to reshape it to a (3,4,2) array like below:</p> <pre><code>array([[[ 0, 1], [ 2, 3], [12, 13], [14, 15]], [[ 4, 5], [ 6, 7], [16, 17], [18, 19]], [[ 8, 9], [10, 11], [20, 21], [22, 23]]]) </code></pre> <p>I've tried to use reshape but it gave me the following which is not what I want.</p> <pre><code>array([[[ 0, 1], [ 2, 3], [ 4, 5], [ 6, 7]], [[ 8, 9], [10, 11], [12, 13], [14, 15]], [[16, 17], [18, 19], [20, 21], [22, 23]]]) </code></pre> <p>Can someone please help?</p>
1
2016-08-13T05:28:56Z
38,929,595
<pre><code>x = np.arange(24).reshape((2,3,2,2)) y = np.dstack(zip(x))[0] print y </code></pre> <p>result:</p> <pre><code>[[[ 0 1] [ 2 3] [12 13] [14 15]] [[ 4 5] [ 6 7] [16 17] [18 19]] [[ 8 9] [10 11] [20 21] [22 23]]] </code></pre>
1
2016-08-13T05:36:11Z
[ "python", "arrays", "numpy" ]
Numpy: Reshape array along a specified axis
38,929,531
<p>I have the following array:</p> <pre><code>x = np.arange(24).reshape((2,3,2,2)) array([[[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[ 8, 9], [10, 11]]], [[[12, 13], [14, 15]], [[16, 17], [18, 19]], [[20, 21], [22, 23]]]]) </code></pre> <p>I would like to reshape it to a (3,4,2) array like below:</p> <pre><code>array([[[ 0, 1], [ 2, 3], [12, 13], [14, 15]], [[ 4, 5], [ 6, 7], [16, 17], [18, 19]], [[ 8, 9], [10, 11], [20, 21], [22, 23]]]) </code></pre> <p>I've tried to use reshape but it gave me the following which is not what I want.</p> <pre><code>array([[[ 0, 1], [ 2, 3], [ 4, 5], [ 6, 7]], [[ 8, 9], [10, 11], [12, 13], [14, 15]], [[16, 17], [18, 19], [20, 21], [22, 23]]]) </code></pre> <p>Can someone please help?</p>
1
2016-08-13T05:28:56Z
38,929,684
<p>Use <code>transpose</code> and then <code>reshape</code> like so -</p> <pre><code>shp = x.shape out = x.transpose(1,0,2,3).reshape(shp[1],-1,shp[-1]) </code></pre>
1
2016-08-13T05:50:46Z
[ "python", "arrays", "numpy" ]
Get value from variable instead of command line in argparse
38,929,563
<p>I am using pynetdicom script to fetch the data from the dcm4chee. to run the script I need to pass the arguments from the command line. But I already have that value in some variable or in other object and I need to use from there but I am not getting how can I pass that value to the parser or Is it possible to do without parsing.</p> <p>Please help me to know how can I pass the value using some variables instead of passing through the command line.</p> <p><strong>Script :</strong></p> <pre><code> #!/usr/bin/python """ For help on usage, python qrscu.py -h """ import argparse from netdicom.applicationentity import AE from netdicom.SOPclass import * from dicom.dataset import Dataset, FileDataset from dicom.UID import ExplicitVRLittleEndian, ImplicitVRLittleEndian, ExplicitVRBigEndian import netdicom import tempfile # parse commandline parser = argparse.ArgumentParser(description='storage SCU example') print "parser", parser parser.add_argument('remotehost') parser.add_argument('remoteport', type=int) parser.add_argument('searchstring') parser.add_argument('-p', help='local server port', type=int, default=9999) parser.add_argument('-aet', help='calling AE title', default='PYNETDICOM') parser.add_argument('-aec', help='called AE title', default='REMOTESCU') parser.add_argument('-implicit', action='store_true', help='negociate implicit transfer syntax only', default=False) parser.add_argument('-explicit', action='store_true', help='negociate explicit transfer syntax only', default=False) args = parser.parse_args() print "args :::: ", type(args), args if args.implicit: ts = [ImplicitVRLittleEndian] elif args.explicit: ts = [ExplicitVRLittleEndian] else: ts = [ ExplicitVRLittleEndian, ImplicitVRLittleEndian, ExplicitVRBigEndian ] # call back def OnAssociateResponse(association): print "Association response received" def OnAssociateRequest(association): print "Association resquested" return True def OnReceiveStore(SOPClass, DS): print "Received C-STORE", DS.PatientName try: # do something with dataset. For instance, store it. file_meta = Dataset() file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.2' file_meta.MediaStorageSOPInstanceUID = "1.2.3" # !! Need valid UID here file_meta.ImplementationClassUID = "1.2.3.4" # !!! Need valid UIDs here filename = '%s/%s.dcm' % (tempfile.gettempdir(), DS.SOPInstanceUID) ds = FileDataset(filename, {}, file_meta=file_meta, preamble="\0" * 128) ds.update(DS) ds.save_as(filename) print "File %s written" % filename except: pass # must return appropriate status return SOPClass.Success # create application entity with Find and Move SOP classes as SCU and # Storage SOP class as SCP MyAE = AE(args.aet, args.p, [PatientRootFindSOPClass, PatientRootMoveSOPClass, VerificationSOPClass], [StorageSOPClass], ts) MyAE.OnAssociateResponse = OnAssociateResponse MyAE.OnAssociateRequest = OnAssociateRequest MyAE.OnReceiveStore = OnReceiveStore MyAE.start() # remote application entity RemoteAE = dict(Address=args.remotehost, Port=args.remoteport, AET=args.aec) # create association with remote AE print "Request association" assoc = MyAE.RequestAssociation(RemoteAE) # perform a DICOM ECHO print "DICOM Echo ... ", if assoc: st = assoc.VerificationSOPClass.SCU(1) print 'done with status "%s"' % st print "DICOM FindSCU ... ", print "\n\n----------------------------------------------------------------------\n\n" d = Dataset() d.StudyDate = args.searchstring d.QueryRetrieveLevel = "STUDY" d.PatientID = "*" study = [x[1] for x in assoc.PatientRootFindSOPClass.SCU(d, 1)][:-1] print 'done with status "%s"' % st print "\n\n\n Cont...", study print "\n\n----------------------------------------------------------------------\n\n" # loop on patients for pp in study: print "\n\n----------------------Pateint Detals------------------------------------------------\n\n" print "%s - %s" % (pp.StudyDate, pp.PatientID) # find studies d = Dataset() d.PatientID = pp.PatientID d.QueryRetrieveLevel = "STUDY" d.PatientName = "" d.StudyInstanceUID = "" d.StudyDate = "" d.StudyTime = "" d.StudyID = "" d.ModalitiesInStudy = "" d.StudyDescription = "" studies = [x[1] for x in assoc.PatientRootFindSOPClass.SCU(d, 1)][:-1] # loop on studies for st in studies: print "\n study :: ", studies print "\n\n---------------------------Study---------------------------\n\n" print " %s - %s %s" % (st.StudyDescription, st.StudyDate, st.StudyTime) d = Dataset() d.QueryRetrieveLevel = "SERIES" d.StudyInstanceUID = st.StudyInstanceUID d.SeriesInstanceUID = "" d.InstanceNumber = "" d.Modality = "" d.SeriesNumber = "" d.SeriesDescription = "" d.AccessionNumber = "" d.SeriesDate = "" d.SeriesTime = "" d.SeriesID = "" d.NumberOfSeriesRelatedInstances = "" series = [x[1] for x in assoc.PatientRootFindSOPClass.SCU(d, 1)][:-1] # print series uid and number of instances if series: for se in series: print "\n\n---------------------------Series---------------------------\n\n" print "\n\n\n series", se print " %15s - %10s - %35s - %5s" % (se.SeriesNumber, se.Modality, se.SeriesDescription, se.NumberOfSeriesRelatedInstances) print "Release association" assoc.Release(0) # done MyAE.Quit() else: print "Failed to create Association." # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: </code></pre>
0
2016-08-13T05:32:36Z
38,929,965
<p>Put everything inside functions and call them wherever you like:</p> <pre><code>#!/usr/bin/python """ For help on usage, python qrscu.py -h """ import os import argparse from netdicom.applicationentity import AE from netdicom.SOPclass import * from dicom.dataset import Dataset, FileDataset from dicom.UID import ExplicitVRLittleEndian, ImplicitVRLittleEndian, ExplicitVRBigEndian import netdicom import tempfile # call back def OnAssociateResponse(association): print "Association response received" def OnAssociateRequest(association): print "Association resquested" return True def OnReceiveStore(SOPClass, DS): print "Received C-STORE", DS.PatientName try: # do something with dataset. For instance, store it. file_meta = Dataset() file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.2' file_meta.MediaStorageSOPInstanceUID = "1.2.3" # !! Need valid UID here file_meta.ImplementationClassUID = "1.2.3.4" # !!! Need valid UIDs here filename = os.path.join(tempfile.gettempdir(), DS.SOPInstanceUID + '%s.dcm') ds = FileDataset(filename, {}, file_meta=file_meta, preamble="\0" * 128) ds.update(DS) ds.save_as(filename) print "File %s written" % filename except Exception as e: print "Some exception occured", e # must return appropriate status return SOPClass.Success def print_data(remotehost, remoteport, searchstring, local_port=9999, calling_title='PYNETDICOM', called_title='REMOTESCU', ts=(ExplicitVRLittleEndian, ImplicitVRLittleEndian, ExplicitVRBigEndian)): # create application entity with Find and Move SOP classes as SCU and # Storage SOP class as SCP MyAE = AE(calling_title, local_port, [PatientRootFindSOPClass, PatientRootMoveSOPClass, VerificationSOPClass], [StorageSOPClass], ts) MyAE.OnAssociateResponse = OnAssociateResponse MyAE.OnAssociateRequest = OnAssociateRequest MyAE.OnReceiveStore = OnReceiveStore MyAE.start() # remote application entity RemoteAE = dict(Address=remotehost, Port=remoteport, AET=called_title) # create association with remote AE print "Request association" assoc = MyAE.RequestAssociation(RemoteAE) # perform a DICOM ECHO print "DICOM Echo ... ", if not assoc: print "Failed to create Association." return st = assoc.VerificationSOPClass.SCU(1) print 'done with status "%s"' % st print "DICOM FindSCU ... ", print "\n\n----------------------------------------------------------------------\n\n" d = Dataset() d.StudyDate = searchstring d.QueryRetrieveLevel = "STUDY" d.PatientID = "*" study = [x[1] for x in assoc.PatientRootFindSOPClass.SCU(d, 1)][:-1] print 'done with status "%s"' % st print "\n\n\n Cont...", study print "\n\n----------------------------------------------------------------------\n\n" # loop on patients for pp in study: print "\n\n----------------------Pateint Detals------------------------------------------------\n\n" print "%s - %s" % (pp.StudyDate, pp.PatientID) # find studies d = Dataset() d.PatientID = pp.PatientID d.QueryRetrieveLevel = "STUDY" d.PatientName = "" d.StudyInstanceUID = "" d.StudyDate = "" d.StudyTime = "" d.StudyID = "" d.ModalitiesInStudy = "" d.StudyDescription = "" studies = [x[1] for x in assoc.PatientRootFindSOPClass.SCU(d, 1)][:-1] # loop on studies for st in studies: print "\n study :: ", studies print "\n\n---------------------------Study---------------------------\n\n" print " %s - %s %s" % (st.StudyDescription, st.StudyDate, st.StudyTime) d = Dataset() d.QueryRetrieveLevel = "SERIES" d.StudyInstanceUID = st.StudyInstanceUID d.SeriesInstanceUID = "" d.InstanceNumber = "" d.Modality = "" d.SeriesNumber = "" d.SeriesDescription = "" d.AccessionNumber = "" d.SeriesDate = "" d.SeriesTime = "" d.SeriesID = "" d.NumberOfSeriesRelatedInstances = "" series = [x[1] for x in assoc.PatientRootFindSOPClass.SCU(d, 1)][:-1] # print series uid and number of instances for se in series: print "\n\n---------------------------Series---------------------------\n\n" print "\n\n\n series", se print " %15s - %10s - %35s - %5s" % (se.SeriesNumber, se.Modality, se.SeriesDescription, se.NumberOfSeriesRelatedInstances) print "Release association" assoc.Release(0) # done MyAE.Quit() def parse_commandline(): # parse commandline parser = argparse.ArgumentParser(description='storage SCU example') print "parser", parser parser.add_argument('remotehost') parser.add_argument('remoteport', type=int) parser.add_argument('searchstring') parser.add_argument('-p', help='local server port', type=int, default=9999) parser.add_argument('-aet', help='calling AE title', default='PYNETDICOM') parser.add_argument('-aec', help='called AE title', default='REMOTESCU') parser.add_argument('-implicit', action='store_true', help='negociate implicit transfer syntax only', default=False) parser.add_argument('-explicit', action='store_true', help='negociate explicit transfer syntax only', default=False) args = parser.parse_args() print "args :::: ", type(args), args if args.implicit: ts = [ImplicitVRLittleEndian] elif args.explicit: ts = [ExplicitVRLittleEndian] else: ts = [ ExplicitVRLittleEndian, ImplicitVRLittleEndian, ExplicitVRBigEndian ] return args, ts if __name__ == '__main__': args, ts = parse_commandline() print_data(args.remotehost, args.remoteport, args.searchstring, args.p, args.aet, args.aec, ts) </code></pre> <p>and use it like:</p> <pre><code>import your_module your_module.print_data(remotehost, remoteport, searchstring) </code></pre>
1
2016-08-13T06:37:28Z
[ "python", "python-2.7", "arguments", "argparse" ]
Get value from variable instead of command line in argparse
38,929,563
<p>I am using pynetdicom script to fetch the data from the dcm4chee. to run the script I need to pass the arguments from the command line. But I already have that value in some variable or in other object and I need to use from there but I am not getting how can I pass that value to the parser or Is it possible to do without parsing.</p> <p>Please help me to know how can I pass the value using some variables instead of passing through the command line.</p> <p><strong>Script :</strong></p> <pre><code> #!/usr/bin/python """ For help on usage, python qrscu.py -h """ import argparse from netdicom.applicationentity import AE from netdicom.SOPclass import * from dicom.dataset import Dataset, FileDataset from dicom.UID import ExplicitVRLittleEndian, ImplicitVRLittleEndian, ExplicitVRBigEndian import netdicom import tempfile # parse commandline parser = argparse.ArgumentParser(description='storage SCU example') print "parser", parser parser.add_argument('remotehost') parser.add_argument('remoteport', type=int) parser.add_argument('searchstring') parser.add_argument('-p', help='local server port', type=int, default=9999) parser.add_argument('-aet', help='calling AE title', default='PYNETDICOM') parser.add_argument('-aec', help='called AE title', default='REMOTESCU') parser.add_argument('-implicit', action='store_true', help='negociate implicit transfer syntax only', default=False) parser.add_argument('-explicit', action='store_true', help='negociate explicit transfer syntax only', default=False) args = parser.parse_args() print "args :::: ", type(args), args if args.implicit: ts = [ImplicitVRLittleEndian] elif args.explicit: ts = [ExplicitVRLittleEndian] else: ts = [ ExplicitVRLittleEndian, ImplicitVRLittleEndian, ExplicitVRBigEndian ] # call back def OnAssociateResponse(association): print "Association response received" def OnAssociateRequest(association): print "Association resquested" return True def OnReceiveStore(SOPClass, DS): print "Received C-STORE", DS.PatientName try: # do something with dataset. For instance, store it. file_meta = Dataset() file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.2' file_meta.MediaStorageSOPInstanceUID = "1.2.3" # !! Need valid UID here file_meta.ImplementationClassUID = "1.2.3.4" # !!! Need valid UIDs here filename = '%s/%s.dcm' % (tempfile.gettempdir(), DS.SOPInstanceUID) ds = FileDataset(filename, {}, file_meta=file_meta, preamble="\0" * 128) ds.update(DS) ds.save_as(filename) print "File %s written" % filename except: pass # must return appropriate status return SOPClass.Success # create application entity with Find and Move SOP classes as SCU and # Storage SOP class as SCP MyAE = AE(args.aet, args.p, [PatientRootFindSOPClass, PatientRootMoveSOPClass, VerificationSOPClass], [StorageSOPClass], ts) MyAE.OnAssociateResponse = OnAssociateResponse MyAE.OnAssociateRequest = OnAssociateRequest MyAE.OnReceiveStore = OnReceiveStore MyAE.start() # remote application entity RemoteAE = dict(Address=args.remotehost, Port=args.remoteport, AET=args.aec) # create association with remote AE print "Request association" assoc = MyAE.RequestAssociation(RemoteAE) # perform a DICOM ECHO print "DICOM Echo ... ", if assoc: st = assoc.VerificationSOPClass.SCU(1) print 'done with status "%s"' % st print "DICOM FindSCU ... ", print "\n\n----------------------------------------------------------------------\n\n" d = Dataset() d.StudyDate = args.searchstring d.QueryRetrieveLevel = "STUDY" d.PatientID = "*" study = [x[1] for x in assoc.PatientRootFindSOPClass.SCU(d, 1)][:-1] print 'done with status "%s"' % st print "\n\n\n Cont...", study print "\n\n----------------------------------------------------------------------\n\n" # loop on patients for pp in study: print "\n\n----------------------Pateint Detals------------------------------------------------\n\n" print "%s - %s" % (pp.StudyDate, pp.PatientID) # find studies d = Dataset() d.PatientID = pp.PatientID d.QueryRetrieveLevel = "STUDY" d.PatientName = "" d.StudyInstanceUID = "" d.StudyDate = "" d.StudyTime = "" d.StudyID = "" d.ModalitiesInStudy = "" d.StudyDescription = "" studies = [x[1] for x in assoc.PatientRootFindSOPClass.SCU(d, 1)][:-1] # loop on studies for st in studies: print "\n study :: ", studies print "\n\n---------------------------Study---------------------------\n\n" print " %s - %s %s" % (st.StudyDescription, st.StudyDate, st.StudyTime) d = Dataset() d.QueryRetrieveLevel = "SERIES" d.StudyInstanceUID = st.StudyInstanceUID d.SeriesInstanceUID = "" d.InstanceNumber = "" d.Modality = "" d.SeriesNumber = "" d.SeriesDescription = "" d.AccessionNumber = "" d.SeriesDate = "" d.SeriesTime = "" d.SeriesID = "" d.NumberOfSeriesRelatedInstances = "" series = [x[1] for x in assoc.PatientRootFindSOPClass.SCU(d, 1)][:-1] # print series uid and number of instances if series: for se in series: print "\n\n---------------------------Series---------------------------\n\n" print "\n\n\n series", se print " %15s - %10s - %35s - %5s" % (se.SeriesNumber, se.Modality, se.SeriesDescription, se.NumberOfSeriesRelatedInstances) print "Release association" assoc.Release(0) # done MyAE.Quit() else: print "Failed to create Association." # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: </code></pre>
0
2016-08-13T05:32:36Z
38,930,285
<p>You can incorporate and use the script above in your own code by using the pyhton module <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">subprocess</a>. It will let you run the script with arguments that you define depending on your variables or objects.</p> <p>Example: Let say that you have some variables your_arg_1...your_arg_n that can be consumed by grscu.py. Then you can pass these variables to the script with</p> <pre><code> import subprocess r = subprocess.check_call(['grscu.py', your_arg_1, your_arg_2, ..., your_arg_n]) </code></pre> <p>The "args = parser.parse_args()" in the script will grab the variables and pass them to the MyAE object. For more information about argparse, see <a href="https://docs.python.org/2/howto/argparse.html" rel="nofollow">link</a>.</p>
0
2016-08-13T07:20:19Z
[ "python", "python-2.7", "arguments", "argparse" ]
sending more than1000 requests per second in python
38,929,590
<p>I am trying to send requests concurrently to a server and then record the average latency using this code:</p> <pre><code>import Queue import time import threading import urllib2 data = "{"image_1":"abc/xyz.jpg"}" headers = {.....} def get_url(q, url): num = 1 sum = 0 while num &lt;= 200: start = time.time() req = urllib2.Request(url, data, headers) response = urllib2.urlopen(req) end = time.time() print end - start num = num + 1 q.put(response.read()) sum = sum + (end - start) print sum theurls = ["http://example.com/example"] q = Queue.Queue() for u in theurls: t = threading.Thread(target = get_url, args = (q, u)) t.daemon = True t.start() while True: s = q.get() print s </code></pre> <p>This code is working just fine, but now I intend to send more than 1000 requests per second. I came across <a href="http://stackoverflow.com/a/32029760/5080347">this answer</a> but I am not sure how do I use <code>grequests</code> for my case. Some insights will be very helpful.</p> <p>Thanks</p>
0
2016-08-13T05:35:08Z
39,109,582
<p>With qrequests you do not need to implement threading or queues. Grequests handles that all for you. Just do a normal request but use grequests instead like shown in the example.</p>
0
2016-08-23T19:51:23Z
[ "python", "python-multithreading", "grequests" ]
Python - List of Assignments
38,929,641
<p>Is there a way to have</p> <pre><code>statements = [statement1, statement2, statement3, ...] </code></pre> <p>in Python?</p> <p>I want to be able to do:</p> <pre><code>run statements[i] </code></pre> <p>or:</p> <p><code>f = statements[j]</code> (where f is a function)</p> <p>P.S. I want to have a list of assignment statements (lambda would not work) and I rather not create functions. For example:</p> <pre><code>switch = [output = input, output = 2 * input, output = input ** 2] </code></pre> <p>Is there any other way than defining a function for each entry?</p> <p>Thank you everyone who answered my question.</p>
1
2016-08-13T05:44:02Z
38,929,678
<p>This is a perfectly fine usage in python as in python function is first class</p> <p>You can use </p> <pre><code>def add(a,b): return a+b def sub(a,b): return a-b; funcs = [add,sub] for func in funcs: print func[10,15] </code></pre> <p>Or you may use lamdas instead of defining the functions in advance</p> <pre><code>funcs = [lambda x: x * a for a in [range(10)]] #following gives so multiplication table of 4 for func in funcs: print func(4) </code></pre>
0
2016-08-13T05:49:56Z
[ "python" ]
Python - List of Assignments
38,929,641
<p>Is there a way to have</p> <pre><code>statements = [statement1, statement2, statement3, ...] </code></pre> <p>in Python?</p> <p>I want to be able to do:</p> <pre><code>run statements[i] </code></pre> <p>or:</p> <p><code>f = statements[j]</code> (where f is a function)</p> <p>P.S. I want to have a list of assignment statements (lambda would not work) and I rather not create functions. For example:</p> <pre><code>switch = [output = input, output = 2 * input, output = input ** 2] </code></pre> <p>Is there any other way than defining a function for each entry?</p> <p>Thank you everyone who answered my question.</p>
1
2016-08-13T05:44:02Z
38,929,680
<p>This is perfectly fine:</p> <pre><code>def addbla(item): return item + ' bla' items = ['Trump', 'Donald', 'tax declaration'] new_items = [addbla(item) for item in items] print(new_items) </code></pre> <p>It adds a <em>political statement</em> to every item in <code>items</code> :)</p>
0
2016-08-13T05:50:21Z
[ "python" ]
Python - List of Assignments
38,929,641
<p>Is there a way to have</p> <pre><code>statements = [statement1, statement2, statement3, ...] </code></pre> <p>in Python?</p> <p>I want to be able to do:</p> <pre><code>run statements[i] </code></pre> <p>or:</p> <p><code>f = statements[j]</code> (where f is a function)</p> <p>P.S. I want to have a list of assignment statements (lambda would not work) and I rather not create functions. For example:</p> <pre><code>switch = [output = input, output = 2 * input, output = input ** 2] </code></pre> <p>Is there any other way than defining a function for each entry?</p> <p>Thank you everyone who answered my question.</p>
1
2016-08-13T05:44:02Z
38,929,682
<p>If you want to run a block of statements, use a function.</p> <pre><code>def run_statements(): func() for i in range(3): if i &gt; 1: break extra_func() run_statements() </code></pre> <p>If you want to choose specific statements from a list, wrap each one in a function:</p> <pre><code>def looper(): for i in range(3): if i&gt;1: break def func(): print('hello') statements = [looper, func] statements[-1]() </code></pre> <p>If your statements are simply function calls, you can put them directly into a list without creating wrapper functions.</p>
0
2016-08-13T05:50:35Z
[ "python" ]
Python - List of Assignments
38,929,641
<p>Is there a way to have</p> <pre><code>statements = [statement1, statement2, statement3, ...] </code></pre> <p>in Python?</p> <p>I want to be able to do:</p> <pre><code>run statements[i] </code></pre> <p>or:</p> <p><code>f = statements[j]</code> (where f is a function)</p> <p>P.S. I want to have a list of assignment statements (lambda would not work) and I rather not create functions. For example:</p> <pre><code>switch = [output = input, output = 2 * input, output = input ** 2] </code></pre> <p>Is there any other way than defining a function for each entry?</p> <p>Thank you everyone who answered my question.</p>
1
2016-08-13T05:44:02Z
38,929,738
<p>Yes. Functions are <em>first-class-citizens</em> in python: i.e. you could pass them as parameters or even store them in an array. </p> <p>It is not uncommon to have a list of functions: You could build a simple registry in python like this:</p> <pre><code>#!/usr/bin/env python processing_pipeline = [] def step(function): processing_pipeline.append(function); return function @step def step_1(data): print("processing step1") @step def step_2(data): print("processing step2") @step def step_3(data): print("processing step3") def main(): data = {} for process in processing_pipeline: process(data) if __name__ == '__main__': main() </code></pre> <p>Here the <code>processing_pipeline</code> is just a list with functions. <code>step</code> is a so called <em>decorator</em>-function, which works like a closure. The python interpreter adds while parsing the file every decorated <code>@step</code> to the pipeline.</p> <p>And you are able to access the function with an iterator, or via <code>processing_pipeline[i]</code>: try adding <code>processing_pipeline[2](data)</code>.</p>
4
2016-08-13T05:58:27Z
[ "python" ]
Python - List of Assignments
38,929,641
<p>Is there a way to have</p> <pre><code>statements = [statement1, statement2, statement3, ...] </code></pre> <p>in Python?</p> <p>I want to be able to do:</p> <pre><code>run statements[i] </code></pre> <p>or:</p> <p><code>f = statements[j]</code> (where f is a function)</p> <p>P.S. I want to have a list of assignment statements (lambda would not work) and I rather not create functions. For example:</p> <pre><code>switch = [output = input, output = 2 * input, output = input ** 2] </code></pre> <p>Is there any other way than defining a function for each entry?</p> <p>Thank you everyone who answered my question.</p>
1
2016-08-13T05:44:02Z
38,929,739
<p>You can do:</p> <pre><code>funcs = [min, max, sum] f = funcs[0] funcs[1](1,2,3) # out 3 funcs[2]([1,2,3]) # out 6 </code></pre>
0
2016-08-13T05:58:52Z
[ "python" ]
Python - List of Assignments
38,929,641
<p>Is there a way to have</p> <pre><code>statements = [statement1, statement2, statement3, ...] </code></pre> <p>in Python?</p> <p>I want to be able to do:</p> <pre><code>run statements[i] </code></pre> <p>or:</p> <p><code>f = statements[j]</code> (where f is a function)</p> <p>P.S. I want to have a list of assignment statements (lambda would not work) and I rather not create functions. For example:</p> <pre><code>switch = [output = input, output = 2 * input, output = input ** 2] </code></pre> <p>Is there any other way than defining a function for each entry?</p> <p>Thank you everyone who answered my question.</p>
1
2016-08-13T05:44:02Z
38,930,766
<blockquote> <p>I want to be able to do: <code>run statements[i]</code></p> </blockquote> <p>well, you can do that by <strong>exec</strong>:</p> <pre><code>statements = ["result=max(1,2)","print(result)"] for idx in range(len(statements)): exec(statements[idx]) print(result) </code></pre> <p>Hope it helps!</p>
0
2016-08-13T08:23:06Z
[ "python" ]
Python - List of Assignments
38,929,641
<p>Is there a way to have</p> <pre><code>statements = [statement1, statement2, statement3, ...] </code></pre> <p>in Python?</p> <p>I want to be able to do:</p> <pre><code>run statements[i] </code></pre> <p>or:</p> <p><code>f = statements[j]</code> (where f is a function)</p> <p>P.S. I want to have a list of assignment statements (lambda would not work) and I rather not create functions. For example:</p> <pre><code>switch = [output = input, output = 2 * input, output = input ** 2] </code></pre> <p>Is there any other way than defining a function for each entry?</p> <p>Thank you everyone who answered my question.</p>
1
2016-08-13T05:44:02Z
39,116,194
<p>Since we've had every other way, I thought I'd toss this out:</p> <pre><code>def a(input): return pow(input, 3) def b(input): return abs(input) def c(input): return "I have {0} chickens".format(str(input)) #make an array of functions foo = [a,b,c] #make a list comprehension of the list of functions dop = [x(3) for x in foo] print dop </code></pre>
0
2016-08-24T06:46:31Z
[ "python" ]
django-mongodb-engine can't update an object
38,929,708
<p>I am writing a Django-based back end using django-mongodb-engine for an android app and I'm trying to get data from a PUT request to update a record in my database. I'm getting a username and filtering the database for the user object with that name (successfully), but the save function doesn't seem to be saving the changes. I can tell the changes aren't being saved because when I go onto mLab's online database management tool the changes aren't there. </p> <p>Here's the code:</p> <pre><code>existing_user = User.objects.filter(userName = user_name) if existing_user == None: response_string += "&lt;error&gt;User not identified: &lt;/error&gt;" elif (existing_user[0].password != user_pwd): response_string += "&lt;error&gt;Password error.&lt;/error&gt;" #if we have a validated user, then manipulate user data else: existing_user[0].star_list.append(new_star) existing_user[0].save() </code></pre> <p>I'm not getting any error messages, but the data remains the same. The star_list remains empty after the above. In fact, as a test I even tried replacing the else clause above with:</p> <pre><code>else: existing_user[0].userName = "Barney" existing_user[0].save() </code></pre> <p>And following this call, the existing_user[0].userName is still it's original value ("Fred", rather than "Barney")!</p>
0
2016-08-13T05:53:57Z
38,938,428
<p>Found an answer to this question. I'm not sure why it wasn't working as posted, but there were problems trying to access the object through the list... in other words the following didn't work:</p> <pre><code>existing_user[0].userName = "Barney" existing_user[0].save() </code></pre> <p>But this did:</p> <pre><code>found_user = existing_user[0] found_user.userName = "Barney" found_user.save() </code></pre> <p>Based on my understanding of Python lists, either one should be the same... but maybe some python genius out there can explain why they aren't? </p>
0
2016-08-14T01:31:33Z
[ "python", "django", "mongodb" ]
Pandas: Rolling sum with multiple indexes (i.e. panel data)
38,929,737
<p>I have a dataframe with multiple index and would like to create a rolling sum of some data, but for each id in the index.</p> <p>For instance, let us say I have two indexes (<em>Firm</em> and <em>Year</em>) and I have some data with name <em>zdata</em>. The working example is the following:</p> <pre><code>import pandas as pd # generating data firms = ['firm1']*5+['firm2']*5 years = [2000+i for i in range(5)]*2 zdata = [1 for i in range(10)] # Creating the dataframe mydf = pd.DataFrame({'firms':firms,'year':years,'zdata':zdata}) # Setting the two indexes mydf.set_index(['firms','year'],inplace=True) print(mydf) zdata firms year firm1 2000 1 2001 1 2002 1 2003 1 2004 1 firm2 2000 1 2001 1 2002 1 2003 1 2004 1 </code></pre> <p>And now, I would like to have a rolling sum that starts over for each firm. However, if I type</p> <pre><code>new_rolling_df=mydf.rolling(window=2).sum() print(new_rolling_df) zdata firms year firm1 2000 NaN 2001 2.0 2002 2.0 2003 2.0 2004 2.0 firm2 2000 2.0 2001 2.0 2002 2.0 2003 2.0 2004 2.0 </code></pre> <p>It doesn't take into account the multiple index and just make a normal rolling sum. Anyone has an idea how I should do (especially since I have even more indexes than 2 (firm, worker, country, year)</p> <p>Thanks,</p> <p>Adrien</p>
2
2016-08-13T05:58:25Z
38,929,931
<p><strong><em>Option 1</em></strong></p> <pre><code>mydf.unstack(0).rolling(2).sum().stack().swaplevel(0, 1).sort_index() </code></pre> <p><a href="http://i.stack.imgur.com/9yYCq.png" rel="nofollow"><img src="http://i.stack.imgur.com/9yYCq.png" alt="enter image description here"></a></p> <p><strong><em>Option 2</em></strong></p> <pre><code>mydf.groupby(level=0, group_keys=False).rolling(2).sum() </code></pre> <p><a href="http://i.stack.imgur.com/bD9mO.png" rel="nofollow"><img src="http://i.stack.imgur.com/bD9mO.png" alt="enter image description here"></a></p>
1
2016-08-13T06:32:26Z
[ "python", "pandas", "panel", "multi-index", "rolling-sum" ]
Send multiple Web requests
38,929,778
<p>Im trying to send API requests at specific rate (Example using QPS value), I'm using the following code to launch my requests (stored in web_requests list).</p> <p>If I set QPS=10, delay will be 0.1s or 100 ms. I use time.sleep(0.1) and send a request, but this code is waiting for remote end HTTP response which is around 30 ms, so I end up having 0.3 seconds of extra delay total. How can I send X web requests per seconds without waiting for the response?</p> <pre><code>@gen.coroutine def send_requests(campaign_instance): ... http_client = httpclient.AsyncHTTPClient() while True: try: web_request = web_requests.pop() time.sleep(delay) headers = {'Content-Type': 'application/json'} request = httpclient.HTTPRequest(auth_username=settings.api_account, auth_password=settings.api_password, url=settings.api_web_request, body=json.dumps(web_request), headers=headers, request_timeout=5, method="POST") yield http_client.fetch(request, callback=partial(handle_response, web_request["to"])) gen_log.info("start_campaign() Requests in Queue: {}".format(len(web_requests))) except httpclient.HTTPError, exception: gen_log.info.exception("start_campaign() ".format(exception)) api_errors += 1 if handle_api_errors(api_errors): break except IndexError: gen_log.info.info('start_campaign() Campaign web requests completed. API Errors: {}'.format(api_errors)) break def start(): ioloop.IOLoop.current().run_sync(lambda: send_requests(campaign_instance)) log.info('process_campaign() Campaign completed') campaign_instance.terminate() </code></pre>
0
2016-08-13T06:07:56Z
38,933,772
<p>Simply do not "yield" the future returned by "fetch". Then your coroutine will continue looping immediately, and the callback is executed when the fetch completes in the background.</p> <p>Also, never ever ever call "sleep" in a Tornado application:</p> <p><a href="http://www.tornadoweb.org/en/stable/faq.html#why-isn-t-this-example-with-time-sleep-running-in-parallel" rel="nofollow">http://www.tornadoweb.org/en/stable/faq.html#why-isn-t-this-example-with-time-sleep-running-in-parallel</a></p> <p>If you do, all processing stops and your "fetch" is hung until the sleep completes. Instead:</p> <pre><code>yield gen.sleep(delay) </code></pre>
1
2016-08-13T14:35:49Z
[ "python", "multithreading", "web-services", "tornado" ]
sending a function instance over API (django)
38,929,855
<p>maybe a stupid question :) I have two Django apps, I need one of them to use the functions of the other one without importing them. as if I am requesting them using API, is there a way I can get an instance of a function and use it, I don't want to do the following:</p> <pre><code>response = requests.get('HTTP://URL/example/', data) data = response.json() </code></pre> <p>I want instead to do something like this</p> <pre><code>function = requests.get('HTTP://URL/example/') </code></pre> <p>and execute the function as follows</p> <pre><code>data = function() </code></pre> <p>thanks</p>
0
2016-08-13T06:21:53Z
38,931,071
<p>You can use <code>marshal</code> module to serialize function code, add it as a request content and deserialize in the other app.</p> <pre><code>In [13]: def foo(a, b): print a + b ....: In [14]: import marshal In [15]: a = marshal.dumps(foo.func_code) In [16]: a Out[16]: 'c\x02\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00C\x00\x00\x00s\r\x00\x00\x00|\x00\x00|\x01\x00\x17GHd\x00\x00S(\x01\x00\x00\x00N(\x00\x00\x00\x00(\x02\x00\x00\x00t\x01\x00\x00\x00at\x01\x00\x00\x00b(\x00\x00\x00\x00(\x00\x00\x00\x00s\x1f\x00\x00\x00&lt;ipython-input-13-a0f238eac2f8&gt;t\x03\x00\x00\x00foo\x01\x00\x00\x00s\x02\x00\x00\x00\x00\x01' </code></pre> <p>Another interpreter:</p> <pre><code>In [13]: import marshal, types In [14]: a = marshal.loads('c\x02\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00C\x00\x00\x00s\r\x00\x00\x00|\x00\x00|\x01\x00\x17GHd\x00\x00S(\x01\x00\x00\x00N(\x00\x00\x00\x00(\x02\x00\x00\x00t\x01\x00\x00\x00at\x01\x00\x00\x00b(\x00\x00\x00\x00(\x00\x00\x00\x00s\x1e\x00\x00\x00&lt;ipython-input-1-a0f238eac2f8&gt;t\x03\x00\x00\x00foo\x01\x00\x00\x00s\x02\x00\x00\x00\x00\x01') In [15]: types.FunctionType(a, globals(), 'foo')(1, 2) 3 </code></pre> <p>However you need to ensure that no one will send you malicious code before executing it. Also please note that you will not have access to any global variables which where defined in original module of the function.</p> <p>Generally I would not recommend this approach. Better to just use RestAPI to get results you want instead of passing functions around.</p>
0
2016-08-13T09:01:17Z
[ "python", "function", "instance", "django-apps" ]
Django Error : 'WSGIRequest' object has no attribute 'user'
38,930,157
<p><br> I'm practicing django.<br> Before I met this error message that is</p> <blockquote> <p>'WSGIRequest' object has no attribute 'user'</p> </blockquote> <p>, I restart project and it was disappeared.<br> Today, I met this error message again. I want to fix.<br> It's OK when I open </p> <blockquote> <p>localhost:8000</p> </blockquote> <p>but when i try to open </p> <blockquote> <p>local host:8000/admin/</p> </blockquote> <p>error is occured.</p> <p>I searched this error message at google and stackoverflow.<br> I reordered my MIDDLEWARE in settings.py. It doesn't work.<br> Please help me.<br></p> <p>error message</p> <pre><code>AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user' Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 1.9.8 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'user' Exception Location: c:\todocal\myvenv\lib\site-packages\django\contrib\admin\sites.py in has_permission, line 173 Python Executable: c:\todocal\myvenv\Scripts\python.exe Python Version: 3.4.3 Python Path: ['c:\\todocal', 'C:\\Python34\\Lib', 'C:\\WINDOWS\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34', 'c:\\todocal\\myvenv', 'c:\\todocal\\myvenv\\lib\\site-packages'] Server time: Sat, 13 Aug 2016 15:31:02 +0900 </code></pre> <p>It's trace back</p> <pre><code> Environment: Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 1.9.8 Python Version: 3.4.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todocal_web'] Installed Middleware: ['django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware'] Traceback: File "c:\todocal\myvenv\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "c:\todocal\myvenv\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "c:\todocal\myvenv\lib\site-packages\django\contrib\admin\sites.py" in wrapper 265. return self.admin_view(view, cacheable)(*args, **kwargs) File "c:\todocal\myvenv\lib\site-packages\django\utils\decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "c:\todocal\myvenv\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "c:\todocal\myvenv\lib\site-packages\django\contrib\admin\sites.py" in inner 233. if not self.has_permission(request): File "c:\todocal\myvenv\lib\site-packages\django\contrib\admin\sites.py" in has_permission 173. return request.user.is_active and request.user.is_staff Exception Type: AttributeError at /admin/ Exception Value: 'WSGIRequest' object has no attribute 'user' </code></pre> <p>It's settings.py</p> <pre><code> """ Django settings for todocal project. Generated by 'django-admin startproject' using Django 1.10. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'uij5f=ewy^jv$-=lzt!p%+lq2qv179$a6_lr=$774)@+$=a5(y' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todocal_web', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'todocal.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'todocal.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Seoul' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') </code></pre>
0
2016-08-13T07:02:58Z
38,930,587
<p>Change in settings.py <code>MIDDLEWARE</code> to <code>MIDDLEWARE_CLASSES</code>.</p>
2
2016-08-13T07:59:43Z
[ "python", "django" ]
Django Error : 'WSGIRequest' object has no attribute 'user'
38,930,157
<p><br> I'm practicing django.<br> Before I met this error message that is</p> <blockquote> <p>'WSGIRequest' object has no attribute 'user'</p> </blockquote> <p>, I restart project and it was disappeared.<br> Today, I met this error message again. I want to fix.<br> It's OK when I open </p> <blockquote> <p>localhost:8000</p> </blockquote> <p>but when i try to open </p> <blockquote> <p>local host:8000/admin/</p> </blockquote> <p>error is occured.</p> <p>I searched this error message at google and stackoverflow.<br> I reordered my MIDDLEWARE in settings.py. It doesn't work.<br> Please help me.<br></p> <p>error message</p> <pre><code>AttributeError at /admin/ 'WSGIRequest' object has no attribute 'user' Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 1.9.8 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'user' Exception Location: c:\todocal\myvenv\lib\site-packages\django\contrib\admin\sites.py in has_permission, line 173 Python Executable: c:\todocal\myvenv\Scripts\python.exe Python Version: 3.4.3 Python Path: ['c:\\todocal', 'C:\\Python34\\Lib', 'C:\\WINDOWS\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34', 'c:\\todocal\\myvenv', 'c:\\todocal\\myvenv\\lib\\site-packages'] Server time: Sat, 13 Aug 2016 15:31:02 +0900 </code></pre> <p>It's trace back</p> <pre><code> Environment: Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 1.9.8 Python Version: 3.4.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todocal_web'] Installed Middleware: ['django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware'] Traceback: File "c:\todocal\myvenv\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "c:\todocal\myvenv\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "c:\todocal\myvenv\lib\site-packages\django\contrib\admin\sites.py" in wrapper 265. return self.admin_view(view, cacheable)(*args, **kwargs) File "c:\todocal\myvenv\lib\site-packages\django\utils\decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "c:\todocal\myvenv\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "c:\todocal\myvenv\lib\site-packages\django\contrib\admin\sites.py" in inner 233. if not self.has_permission(request): File "c:\todocal\myvenv\lib\site-packages\django\contrib\admin\sites.py" in has_permission 173. return request.user.is_active and request.user.is_staff Exception Type: AttributeError at /admin/ Exception Value: 'WSGIRequest' object has no attribute 'user' </code></pre> <p>It's settings.py</p> <pre><code> """ Django settings for todocal project. Generated by 'django-admin startproject' using Django 1.10. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'uij5f=ewy^jv$-=lzt!p%+lq2qv179$a6_lr=$774)@+$=a5(y' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todocal_web', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'todocal.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'todocal.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Seoul' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') </code></pre>
0
2016-08-13T07:02:58Z
38,930,620
<p><code>request.user</code> is added by <a href="https://docs.djangoproject.com/en/1.10/ref/middleware/#django.contrib.auth.middleware.AuthenticationMiddleware" rel="nofollow"><code>AuthenticationMiddleware</code></a>. As you can easily see from the error message, you don't have that loaded.</p> <p>As noted by @Sergey Gornostaev, your settings are wrong. If you want to provide a list of middleware classes, use <code>MIDDLEWARE_CLASSES</code> instead of just <code>MIDDLEWARE</code>.</p>
2
2016-08-13T08:03:30Z
[ "python", "django" ]
Python 2.7, finding length of numpy.ndarray
38,930,191
<p>So with my code, I'm analyzing the total number of pixels that are within the threshold of my values. However, it's very slow, and it all comes down to one line of code, basically bottle-necking the entire program. This code is simple, in that it splits the array up into the values so I can count the length, however, it brings the frames per second down from 30 to about 4.</p> <pre><code>import cv2 import numpy as np import time from picamera.array import PiRGBArray from picamera import PiCamera import RPi.GPIO as GPIO from PIL import Image camera = PiCamera() camera.resolution = (320,240) rawCapture= PiRGBArray(camera) for frame in camera.capture_continuous(rawCapture, format='bgr', use_video_port=True): data= frame.array lower=np.array([100, %0, 50], dtype='uint8') upper= np.array([250, 150, 150], dtype="uint8") thresh= cv2.inRange(data, lower, upper) data={tuple(item) for item in thresh} # this is the problem line. len(data) rawCapture.truncate(0) FPS=FPS+1 New_time=time.time()-start if New_time&gt; 10: print FPS/10, 'fps' New_time=0 start=time.time() FPS=0 </code></pre> <p>I feel like half the problem is that it is a loop (python hates loops), but I don't really know how to alter arrays. What's the 'pythonic' way of achieving this?</p>
2
2016-08-13T07:07:07Z
38,930,476
<blockquote> <p>I don't want the size of the picture itself, nor how many total pixels. Just the pixels that are within the threshold.</p> </blockquote> <p><code>cv2.inRange</code> already does that, so the <em>set comprehension</em> will not be required:</p> <blockquote> <p>After calling <code>cv2.inRange</code>, a binary mask is returned, where white pixels (255) represent pixels that fall into the upper and lower limit range and black pixels (0) do not.</p> </blockquote> <p>From the binary mask, the <em>in-range</em> values can be counted with:</p> <pre><code>thresh = cv2.inRange(data, lower, upper) within_threshold = (thresh == 255).sum() </code></pre> <p>To get the pixels themselves, you can index the original <code>data</code> on the <em>in-range</em> binary mask:</p> <pre><code>data = data[thresh == 255] </code></pre>
1
2016-08-13T07:44:57Z
[ "python", "arrays", "python-2.7", "opencv", "numpy" ]
Error: Unexpected eof while parsing?
38,930,206
<p>Im writing my first code and can't figure out what this error means and what i should fix, Please help. Error: Unexpected eof while parsing</p> <pre><code>import math def circumference(r): return 2 * math.pi * r def area(r) : return math.pi * radius**2 * r fName = input("Please enter your first name: ") lName = input("Please enter your last name: ") radius = float(input( fName + " " + lName + " , please enter your radius: ")) print("Hello %s %s Your circumference is %s and your area is %s " % (fName, lName, circumference(radius), area(radius)) </code></pre>
-1
2016-08-13T07:09:14Z
38,931,148
<p>You need to close every parenthesis you open. The line of code that is probably causing the error is this:</p> <pre><code>print("Hello %s %s Your circumference is %s and your area is %s " % (fName, lName, circumference(radius), area(radius)) </code></pre> <p>You're missing a ")" at the end.</p>
0
2016-08-13T09:10:31Z
[ "python", "python-3.x" ]
Update creates a new entity instead of updating the current one on Google's Datastore
38,930,291
<p>Working on an app in python deployed over the google app engine.</p> <p>Here is the code i used to do the update.</p> <pre><code>key = ndb.Key('User', uid) user = key.get() if not user: logging.info("Creating new user...") user = M.User(id=uid) user.remind = tmp user.put() </code></pre> <p>Instead of updating the old entity, a new entity is created with the key as a in the name field. As seen below Name/ID classNo created first_name groupid last_name remind updated username </p> <p>id=133877436 0 2016-08-13 (15:16:04.890) HKT JIACHENNN null true 2016-08-13 (15:19:49.055) HKT</p> <p>name=133877436 -1 2016-08-13 (15:19:52.590) HKT null null null true 2016-08-13 (15:19:52.590) HKT null</p> <p>Appreciate any help!</p> <p>UPDATE/SOLVED</p> <p>solved it by using the int(uid) when fetching the entity. It was creating a mew entity because the two keys was different. One was 133877436 and was was enclosed in quotes '133877436' hence name was called. </p> <p>Hope this helps someone else</p>
0
2016-08-13T07:21:29Z
39,000,551
<p>if you want to update an entity you ought to retrieve this entity by his id, then you can change the old value. For exemple:</p> <pre><code>entity_to_edit = Entity.get_by_id(this_entit_id) entity_to_edit.some_attribute = "new_variable" entity_to_edit.put() </code></pre>
0
2016-08-17T15:18:54Z
[ "python", "google-app-engine", "app-engine-ndb", "google-cloud-datastore" ]
MrJob on Hadoop can't import libraries
38,930,398
<p>I am using CDH 5.7.2 and MrJob to submit a MapReduce job</p> <p>When I try in <strong>localmode, everything works fine</strong>, but when i use <code>-r hadoop</code> It gives me following error:</p> <pre><code> Task Id : attempt_1471071791922_0005_m_000001_2, Status : FAILED Error: java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 1 at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:325) at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:538) at org.apache.hadoop.streaming.PipeMapper.close(PipeMapper.java:130) at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:61) at org.apache.hadoop.streaming.PipeMapRunner.run(PipeMapRunner.java:34) at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:453) at org.apache.hadoop.mapred.MapTask.run(MapTask.java:343) at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:164) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:415) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1693) at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158) </code></pre> <p>I figured out that <strong>problem occurs</strong> when I try to import library:</p> <pre><code>import geopy from geopy.distance import great_circle </code></pre> <p>This is how I execute my script:</p> <pre><code>python test2.py -r hadoop hdfs:///user/dataset/test_data --hadoop-streaming-jar /opt/cloudera/parcels/CDH/lib/hadoop-mapreduce/hadoop-streaming.jar </code></pre> <p>P.S. MrJob cant fine hadoop-streaming-jar , so I specify it manually</p> <p>How can I execute MapReduce jon on Hadoop <strong>with library import</strong> ?</p>
0
2016-08-13T07:35:20Z
39,011,937
<p>Found answer by myself.</p> <p>What I have to do - is to install this library on <strong>all of my nodes</strong> (not just on master)</p>
0
2016-08-18T07:09:05Z
[ "python", "hadoop", "mapreduce", "cloudera-cdh", "mrjob" ]
page not found django.views.static.serve
38,930,474
<p>first post so be gentle.</p> <p>I am trying to display a static image in django. I can upload the image to my media directory but when I try to display it I get a nothing. If I copy the url to the browser I get ...</p> <p>Page not found (404) Request Method: GET Request URL: <a href="http://127.0.0.1:8000/media/Will_and_Matt.jpg" rel="nofollow">http://127.0.0.1:8000/media/Will_and_Matt.jpg</a> Raised by: django.views.static.serve</p> <p>detail.py</p> <pre><code>... &lt;img src="{{ student.photo.url }}" class="img-responsive"&gt; ... </code></pre> <p>model.py</p> <pre><code>class Student(models.Model): photo = models.FileField( blank=True, null=True) </code></pre> <p>project urls.py</p> <pre><code>from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^opencmis/', include('opencmis.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_URL) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_URL) </code></pre> <p>settings.py</p> <pre><code>STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' </code></pre> <p>My update form works as it created the media folder and places images in it.</p> <p>The URL pattern seems to match /media as it doesn't give an error there it just doesn't display the image.</p> <p>Any ideas?</p>
1
2016-08-13T07:44:36Z
38,954,912
<p>document_root=settings.STATIC_URL should be document_root=settings.STATIC_ROOT and similar for MEDIA_ROOT. You want the filesystem path in there, not the URL. – dhke</p>
0
2016-08-15T12:16:27Z
[ "python", "django", "filefield" ]
Webpack setup, webpack doesn't resolve(pack into bundle) css files
38,930,589
<p>I have problem inserting css inside my react code. Problem is that webpack not resolving css files. I did everything according to docs, and no luck. Also could be issue that i'm using django 1.9 for this</p> <p>File structure:</p> <pre><code>webpack.config.js static ├── bundles │   └── reqct-25186f952a42614d1bdc.js ├── css │   ├── tabs.css │   └── testings.css └── js ├── env_tab.js ├── envs.jsx └── index.jsx </code></pre> <p>Here is my webpack config:</p> <pre class="lang-js prettyprint-override"><code>var path = require("path"); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); var ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports = { entry: { reqct: './static/js' }, output: { path: path.resolve('./static/bundles/'), filename: "[name]-[hash].js" }, plugins: [ new BundleTracker({ filename: './webpack-stats.json' }), new ExtractTextPlugin({ filename: "[name].css", allChunks: true }) ], module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel' }, { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") } ] }, resolve: { modulesDirectories: ['node_modules'], extensions: ['', '.js', '.jsx', '.css'] } }; </code></pre> <p>Dependencies installed:</p> <pre><code>"babel-core": "^6.13.2", "babel-loader": "^6.2.4", "babel-preset-es2015": "^6.13.2", "babel-preset-react": "^6.11.1", "css-loader": "^0.23.1", "extract-text-webpack-plugin": "^1.0.1", "jquery": "^3.1.0", "react": "^15.3.0", "react-dom": "^15.3.0", "style-loader": "^0.13.1", "webpack": "^1.13.1", "webpack-bundle-tracker": "0.0.93" </code></pre> <p>Error msg:</p> <pre><code>ERROR in ./static/js/envs.jsx Module not found: Error: Cannot resolve 'file' or 'directory' ./testings.css in /Users/ievgeniivdovenko/workspace/personal/tool/static/js resolve file /Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css doesn't exist /Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css.js doesn't exist /Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css.jsx doesn't exist /Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css.css doesn't exist resolve directory /Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css doesn't exist (directory default file) /Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css/package.json doesn't exist (directory description file) [/Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css] [/Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css.js] [/Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css.jsx] [/Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css.css] @ ./static/js/envs.jsx 6:14-43 </code></pre> <p>I tried to add one more entry point:</p> <pre><code>css: './static/css' </code></pre> <p>and now errors are:</p> <pre><code>ERROR in Entry module not found: Error: Cannot resolve directory './static/css' in /Users/ievgeniivdovenko/workspace/personal/tool resolve directory ./static/css in /Users/ievgeniivdovenko/workspace/personal/tool /Users/ievgeniivdovenko/workspace/personal/tool/static/css/package.json doesn't exist (directory description file) directory default file index resolve file index in /Users/ievgeniivdovenko/workspace/personal/tool/static/css /Users/ievgeniivdovenko/workspace/personal/tool/static/css/index doesn't exist /Users/ievgeniivdovenko/workspace/personal/tool/static/css/index.js doesn't exist /Users/ievgeniivdovenko/workspace/personal/tool/static/css/index.jsx doesn't exist /Users/ievgeniivdovenko/workspace/personal/tool/static/css/index.css doesn't exist ERROR in ./static/js/envs.jsx Module not found: Error: Cannot resolve 'file' or 'directory' ./testings.css in /Users/ievgeniivdovenko/workspace/personal/tool/static/js resolve file /Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css doesn't exist /Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css.js doesn't exist /Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css.jsx doesn't exist /Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css.css doesn't exist resolve directory /Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css doesn't exist (directory default file) /Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css/package.json doesn't exist (directory description file) [/Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css] [/Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css.js] [/Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css.jsx] [/Users/ievgeniivdovenko/workspace/personal/tool/static/js/testings.css.css] @ ./static/js/envs.jsx 6:14-43 </code></pre>
0
2016-08-13T08:00:07Z
38,930,741
<p>From the error messages, it looks like you're trying to include <code>./testings.css</code> in the file <code>static/js/envs.jsx</code>, so Webpack is (understandably) trying to find that CSS file in <code>static/js</code>:</p> <blockquote> <p>.../<strong>static/js/testings.css</strong> doesn't exist</p> </blockquote> <p>Try including <code>../css/testings.css</code> instead.</p>
0
2016-08-13T08:19:40Z
[ "python", "django", "reactjs", "webpack", "css-loader" ]
flask and flask_login - organizing code
38,930,604
<p>I am currently coding up a simple web application using flask and flask_login, and got stuck due to a code organisation problem.</p> <pre><code>import flask import flask_login app = flask.Flask(__name__) login_manager = flask_login.LoginManager() login_manager.init_app(app) </code></pre> <p>The above works. The problem arises because I want to separate authentication related code from the main flask application code. In other words, I want <code>my_auth.py</code> that imports <code>flask_login</code> and initializes the <code>login_manager</code>, and I want <code>main.py</code> to <code>import my_auth</code>, and NOT have to import <code>flask_login</code>.</p> <p>The problem is that <code>login_manager.init_app(app)</code> requires the main flask <code>app</code> to be passed in, and this clear separation seems difficult. Thus my questions are:</p> <ol> <li>Is what I am asking for even possible? If so, how?</li> <li>If what I am asking for is not possible, what is currently accepted as the best practice in organising such code?</li> </ol>
1
2016-08-13T08:01:39Z
38,930,826
<p>You can do something like the following, if <code>main.py</code> and <code>my_auth.py</code> reside on same directory:</p> <p><code>my_auth.py</code>:</p> <pre><code>import flask_login login_manager = flask_login.LoginManager() </code></pre> <p><code>main.py</code>:</p> <pre><code>from flask import Flask from my_auth import login_manager app = Flask(__name__) login_manager.init_app(app) </code></pre>
1
2016-08-13T08:31:16Z
[ "python", "flask", "flask-login" ]
Can't see the where "expected an indented block" should be
38,930,627
<p>I know it's an indent issue but I can't see the indent problem with this. I've added added and removed indents. move it all over, moved it all back. I've got square eyes on this one :)</p> <blockquote> <p>File "", line 7 def <strong>init</strong>(self, start_time, time_limit=60):</p> </blockquote> <p>IndentationError: expected an indented block</p> <pre><code>#Listener Class Override class listener(StreamListener): def __init__(self, start_time, time_limit=60): self.time = start_time self.limit = time_limit self.tweet_data = [] def on_data(self, data): saveFile = io.open('raw_tweets.json', 'a', encoding='utf-8') while (time.time() - self.time) &lt; self.limit: try: self.tweet_data.append(data) return True except BaseException, e: print 'failed ondata,', str(e) time.sleep(5) pass saveFile = io.open('raw_tweets.json', 'w', encoding='utf-8') saveFile.write(u'[\n') saveFile.write(','.join(self.tweet_data)) saveFile.write(u'\n]') saveFile.close() exit() def on_error(self, status): print statuses </code></pre>
0
2016-08-13T08:04:24Z
38,930,684
<p>You must be mixing tabs and spaces for indentation.</p> <p>Check this: <a href="https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces" rel="nofollow">https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces</a></p> <blockquote> <p>A text editor which automatically formats code will guide your code from getting into such issues. [eg -Sublime Text editor (where you can make the following change: View -> Indentation -> Convert Indentation to Spaces) with Python Flake8 Lint]</p> </blockquote>
1
2016-08-13T08:12:46Z
[ "python", "python-2.7" ]
Interpreting a bytearray as array of longs in Python 2.7
38,930,639
<p>In Python 3 it is possible to interpret the underlying memory as array of bytes or ints or longs via <code>memoryview.cast()</code>:</p> <pre><code>[] b=bytearray(2*8) [] b bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') [] m=memoryview(b).cast('L') #reinterpret as an array of unsigned longs [] m[1]=2**64-1 [] b bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff') </code></pre> <p>As it can be seen, we can access the <code>bytearray</code> <code>b</code> as if it where an array of unsigned longs (which are 8 byte long on my machine) with help of the <code>memoryview</code> <code>m</code>.</p> <p>However, in Python 2.7 the <code>memoryview</code> <a href="https://docs.python.org/2.7/c-api/buffer.html#memoryview-objects" rel="nofollow">lacks</a> the method <code>cast</code>. </p> <p>Thus my question: Is there a possibility to reinterpret a <code>bytearray</code> as an array of longs in Python 2.7?</p> <p>It is important to do it without copying/allocating more memory.</p> <p>Time needed for reading a long value via <code>T[i]</code> on my machine (Python 3.4):</p> <pre class="lang-none prettyprint-override"><code>python list: 40ns (fastest but needs 24 bytes per element) python array: 120ns (has to create python int-object) memoryview of bytearray 120ns (the same as array.array) Jean-François's solution: 6630ns (ca. 50 times slower) Ross's solution: 120ns </code></pre>
4
2016-08-13T08:06:51Z
38,930,889
<p>Not really a reinterpretation since it creates a copy. In that case, you would have to </p> <ul> <li>convert <code>bytearray</code> to list of longs</li> <li>work with the list of longs</li> <li>convert back to <code>bytearray</code> when you're done</li> </ul> <p>(a bit like working with <code>str</code> characters when converting them to list of characters, modifying them, then joining them back to a string)</p> <pre><code>import struct b=bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff') larray=[] for i in range(0,len(b),8): larray.append(struct.unpack('@q',b[i:i+8])[0]) print(larray) larray[1]=1000 b = bytearray() for l in larray: b += struct.pack('@q',l) print(b) </code></pre> <p>Method which does not involve copy (only works for long ints):</p> <pre><code>def set_long(array,index,value): index *= 8 if sys.byteorder=="little": shift=0 for i in range(index,index+8): array[i] = (value&gt;&gt;shift) &amp; 0xFF shift += 8 else: # sys.byteorder=="big" shift = 56 for i in range(index+8,index,-1): array[i] = (value&lt;&lt;shift) &amp; 0xFF shift -= 8 def get_long(array,index): index *= 8 value = 0 if sys.byteorder=="little": shift=0 for i in range(index,index+8): c = (array[i]&lt;&lt;shift) value += c shift += 8 else: # sys.byteorder=="big" shift = 56 for i in range(index+8,index,-1): value += (array[i]&gt;&gt;shift) shift -= 8 return value b=bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff') print(get_long(b,1)==2**64-1) set_long(b,1,2001) print(b) print(get_long(b,1)) </code></pre> <p>output:</p> <pre><code>bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\xe8\x03\x00\x00\x00\x00\x00\x00') True bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\xd1\x07\x00\x00\x00\x00\x00\x00') 2001 </code></pre>
1
2016-08-13T08:39:24Z
[ "python", "python-2.7", "bytearray" ]
Interpreting a bytearray as array of longs in Python 2.7
38,930,639
<p>In Python 3 it is possible to interpret the underlying memory as array of bytes or ints or longs via <code>memoryview.cast()</code>:</p> <pre><code>[] b=bytearray(2*8) [] b bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') [] m=memoryview(b).cast('L') #reinterpret as an array of unsigned longs [] m[1]=2**64-1 [] b bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff') </code></pre> <p>As it can be seen, we can access the <code>bytearray</code> <code>b</code> as if it where an array of unsigned longs (which are 8 byte long on my machine) with help of the <code>memoryview</code> <code>m</code>.</p> <p>However, in Python 2.7 the <code>memoryview</code> <a href="https://docs.python.org/2.7/c-api/buffer.html#memoryview-objects" rel="nofollow">lacks</a> the method <code>cast</code>. </p> <p>Thus my question: Is there a possibility to reinterpret a <code>bytearray</code> as an array of longs in Python 2.7?</p> <p>It is important to do it without copying/allocating more memory.</p> <p>Time needed for reading a long value via <code>T[i]</code> on my machine (Python 3.4):</p> <pre class="lang-none prettyprint-override"><code>python list: 40ns (fastest but needs 24 bytes per element) python array: 120ns (has to create python int-object) memoryview of bytearray 120ns (the same as array.array) Jean-François's solution: 6630ns (ca. 50 times slower) Ross's solution: 120ns </code></pre>
4
2016-08-13T08:06:51Z
38,938,610
<p>You can use ctypes and its <a href="https://docs.python.org/2/library/ctypes.html#ctypes._CData.from_buffer" rel="nofollow"><code>from_buffer</code></a> method to create a ctypes array of unsigned longs that shares its memory with the <code>bytearray</code> object.</p> <p>For example:</p> <pre><code>import ctypes ba = bytearray(b'\x00' * 16) a = (ctypes.c_ulong * (len(ba) / 8)).from_buffer(ba) a[1] = -1 print repr(ba) </code></pre>
1
2016-08-14T02:24:07Z
[ "python", "python-2.7", "bytearray" ]
Heroku Web Server Won't Start Locally
38,930,678
<p>I am having problems starting heroku web server localy. Here is the error message I am constantlly getting:</p> <pre><code>PS C:\Users\Dragan\heroku_workspace\python-getting-started&gt; heroku local [OKAY] Loaded ENV .env File as KEY=VALUE Format 10:01:32 web.1 | Traceback (most recent call last): 10:01:32 web.1 | File "c:\users\dragan\anaconda3\lib\runpy.py", line 170, in _run_module_as_main 10:01:32 web.1 | "__main__", mod_spec) 10:01:32 web.1 | File "c:\users\usr1\anaconda3\lib\runpy.py", line 85, in _run_code 10:01:32 web.1 | exec(code, run_globals) 10:01:32 web.1 | File C:\Users\Dragan\Anaconda3\Scripts\gunicorn.exe\__main__.py", line 5, in &lt;module&gt; 10:01:32 web.1 | File "c:\users\dragan\anaconda3\lib\site-packages\gunicorn\app\wsgiapp.py", line 10, in &lt;module&gt; 10:01:32 web.1 | from gunicorn.app.base import Application 10:01:32 web.1 | File "c:\users\dragan\anaconda3\lib\site-packages\gunicorn\app\base.py", line 12, in &lt;module&gt; 10:01:32 web.1 | from gunicorn import util 10:01:32 web.1 | File "c:\users\dragan\anaconda3\lib\site-packages\gunicorn\util.py", line 9, in &lt;module&gt; 10:01:32 web.1 | import fcntl 10:01:32 web.1 | ImportError: No module named 'fcntl' [DONE] Killing all processes with signal null 10:01:33 web.1 Exited with exit code 1 </code></pre> <p>I am following every step described in this tutorial <a href="https://devcenter.heroku.com/articles/getting-started-with-python#run-the-app-locally" rel="nofollow">LINK</a> I installed the virtual environment inside the project 'python-getting-started'. I am trying to start the local web server from the project's root directory.</p> <p>Can anybody help me resolve this issue?</p> <p>UPDATE_1: I have installed Heroku Toolbelt for Windows, and I have installed Anaconda for Python.</p>
1
2016-08-13T08:12:15Z
38,944,880
<p>You are trying to deploy a Python web application to Heroku using the <a href="http://gunicorn.org/" rel="nofollow">gunicorn</a> web server. This works great on Heroku, but CANNOT WORK on Windows because gunicorn only runs on *nix based operating systems.</p> <p>What you can do instead of running <code>heroku local</code> is run your web server WITHOUT gunicorn locally. Simply say something like <code>$ python myapp.py</code> or whatever your main python web server file is. That will start your server locally using Python ONLY, and not gunicorn.</p>
1
2016-08-14T17:43:12Z
[ "python", "heroku" ]
Django simple queryset in form field
38,930,901
<p>I couldn't find any solution in previous answers so i'm here asking how to register the result of a form field made by a queryset. Maybe i'm doing wrong something simple here how ever my model are:</p> <pre><code>@python_2_unicode_compatible class Choice(models.Model): choice_text = models.CharField(max_length=100) def __str__(self): return self.choice_text @python_2_unicode_compatible class Contatto(models.Model): contatto_choice = models.ForeignKey(Choice, on_delete=models.PROTECT) phone_number = models.CharField(max_length=12) email = models.CharField(max_length=100) text = models.CharField(max_length=250) def __str__(self): return self.email class ContactForm(ModelForm): class Meta: model = Contatto fields = ['contatto_choice', 'phone_number','email','text'] </code></pre> <p>My forms.py is:</p> <pre><code>class ContactForm(forms.Form): contatto_choice = forms.ModelChoiceField(queryset=Choice.objects.all()) phone_number = forms.CharField(max_length=12) email = forms.CharField(max_length=100) text = forms.CharField(widget=forms.Textarea, max_length=500) </code></pre> <p>and my views is:</p> <pre><code>def contatti(request): if request.method=="POST": form = ContactForm(request.POST) if form.is_valid(): contatto = Contatto() contatto.phone_number = form.cleaned_data['phone_number'] contatto.email = form.cleaned_data['email'] contatto.text = form.cleaned_data['text'] contatto.contatto_choice = form.cleaned_data['contatto_choice'] contatto.save() recipients = ['cercaservizi@gmail.com'] send_mail("Contatto Cercaservizi", contatto.phone_number+' '+contatto.email+' '+contatto.text,contatto.email, recipients) return HttpResponseRedirect('/') else: form = ContactForm() return render(request, 'form.html', {'form': form}) </code></pre> <p>The view of the submitted form complains about the fact that a contatto_choice should be an instance of a choice i cannot find any tutorial about how to solve this. If you could help it would be appreciated. </p>
0
2016-08-13T08:40:22Z
38,932,232
<p>Edit Your ContactForm</p> <pre><code>class ContactForm(ModelForm): contatto_choice = forms.ModelChoiceField(queryset=Choice.objects.all()) class Meta: model = Contatto fields = ['contatto_choice', 'phone_number','email','text'] </code></pre> <p>and you will not need other form </p>
1
2016-08-13T11:28:45Z
[ "python", "django", "forms" ]
How to order the files the way it is selecting in pyqt?
38,930,908
<p>i have code which can select multiple files and print their names. But i found that they are not in order in which i am selecting them. say for example if i have file name as <strong>file1,file2,file3</strong>and if i first select <strong>file2</strong> then <strong>file3</strong> then <strong>file1</strong> while printing it is showing <strong>file1,file2,file3</strong> in this order. the code i have written is like this</p> <pre><code> global desktop1 global filesnames1 file_name = QtGui.QFileDialog() file = file_name.getOpenFileNames(self, "Select the file to add", desktop1, "source File (*.MOV;*.MP4)") filesnames1=list(file) for i in filesnames1: print i </code></pre> <p>please help how to achieve what i want.</p>
-1
2016-08-13T08:41:22Z
38,931,140
<p>I don't think there is a method for that but you can write a function to get the selection and compare it to the previous one and connect that function to the activation of your QFileDialog :</p> <pre><code>global desktop1 global previous_selection global filesnames1 QtGui.QFileDialog.currentChanged(get_selection) file_name = QtGui.QFileDialog() def get_selection(previous_selection): file = file_name.getOpenFileNames(self, "Select the file to add", desktop1, "source File (*.MOV;*.MP4)") selected_files=list(file) if len(selected_files) &gt; 1: current_file = selected_files-filenames1 filenames1.append(current_file) else: filenames1=list() filenames1.append(selected_files[0]) </code></pre> <p>I didn't try that code, but I think something like that would do the trick.</p>
0
2016-08-13T09:09:24Z
[ "python", "pyqt" ]
How to order the files the way it is selecting in pyqt?
38,930,908
<p>i have code which can select multiple files and print their names. But i found that they are not in order in which i am selecting them. say for example if i have file name as <strong>file1,file2,file3</strong>and if i first select <strong>file2</strong> then <strong>file3</strong> then <strong>file1</strong> while printing it is showing <strong>file1,file2,file3</strong> in this order. the code i have written is like this</p> <pre><code> global desktop1 global filesnames1 file_name = QtGui.QFileDialog() file = file_name.getOpenFileNames(self, "Select the file to add", desktop1, "source File (*.MOV;*.MP4)") filesnames1=list(file) for i in filesnames1: print i </code></pre> <p>please help how to achieve what i want.</p>
-1
2016-08-13T08:41:22Z
38,934,440
<p>By default, the <a href="http://doc.qt.io/qt-4.8/qfiledialog.html#static-public-members" rel="nofollow">static functions</a> (like <code>getOpenFileNames</code>) will open a <em>native</em> file-dialog whenever possible. For native file-dialogs, Qt has no control over the order of the returned files, so there's nothing you can do to change it.</p> <p>However, it seems that the <em>built-in</em> Qt file-dialog <strong>does</strong> return the files in the order they were selected. So if you don't need a native file-dialog, you can simply do this:</p> <pre><code>files = QFileDialog.getOpenFileNames( self, "Select the file to add", desktop1, "source File (*.mov *.mp4)", options=QFileDialog.DontUseNativeDialog ) </code></pre>
1
2016-08-13T15:51:52Z
[ "python", "pyqt" ]
How do I make one data frame to keep the same rows as another one?
38,930,932
<p>I have one data frame (df) x,</p> <pre><code> A B O 2 3 1 4 4 3 2 1 </code></pre> <p>You may notice that the number 2 row is missing. That is because i have used x.dropna() and therefore the no.2 row is dropped as it is NAN.</p> <p>Now I have another df y:</p> <pre><code> C D O 1 2 1 4 3 2 3 5 3 1 4 </code></pre> <p>I want y to keep the same rows as x. That is, I want the no.2 of y to be removed.</p> <p>I used following codes:</p> <pre><code>temp=x.join(y) x=temp.ix[:,0:2] y=temp.ix[:,2:4] </code></pre> <p>This would work. but I suppose there might be more direct way to do it?</p> <p>Thank you very much.</p>
2
2016-08-13T08:44:33Z
38,930,967
<p>Use loc:</p> <pre><code>y.loc[x.index] Out: C D O 1 2 1 4 3 3 1 4 </code></pre> <p>You can assign it back to y: <code>y = y.loc[x.index]</code></p>
1
2016-08-13T08:49:17Z
[ "python", "pandas", "dataframe" ]
How do I make one data frame to keep the same rows as another one?
38,930,932
<p>I have one data frame (df) x,</p> <pre><code> A B O 2 3 1 4 4 3 2 1 </code></pre> <p>You may notice that the number 2 row is missing. That is because i have used x.dropna() and therefore the no.2 row is dropped as it is NAN.</p> <p>Now I have another df y:</p> <pre><code> C D O 1 2 1 4 3 2 3 5 3 1 4 </code></pre> <p>I want y to keep the same rows as x. That is, I want the no.2 of y to be removed.</p> <p>I used following codes:</p> <pre><code>temp=x.join(y) x=temp.ix[:,0:2] y=temp.ix[:,2:4] </code></pre> <p>This would work. but I suppose there might be more direct way to do it?</p> <p>Thank you very much.</p>
2
2016-08-13T08:44:33Z
38,931,445
<p>You can also use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.isin.html" rel="nofollow"><code>index.isin</code></a> to check if each index value of <code>y</code> is found in index value of <code>x</code>.</p> <pre><code>In [3]: y = y[y.index.isin(x.index)] In [4]: y Out[4]: C D O 1 2 1 4 3 3 1 4 </code></pre>
1
2016-08-13T09:48:09Z
[ "python", "pandas", "dataframe" ]
Run and log the output of 'ping' in a loop in a Python script
38,930,950
<p>i wrote a simple agaent in python that all it dose is just cheacks for the internet connection. When he finds out that ther is no connection he writes a log file to a text the hour and date and then just exit the program.</p> <p>I want it to keep testing if there is a connection even if there is not how can i do this ? without the program exit</p> <p>this is the code:</p> <pre><code>import os import time def Main(): ping =os.system('ping -n 1 -l 1000 8.8.8.8 ') while ping ==0: time.sleep(4) ping = os.system('ping -n 1 -l 1000 8.8.8.8 ') if ping ==1: print 'no connection' CT =time.strftime("%H:%M:%S %d/%m/%y") alert=' No Connection' f = open('logfile.txt','a+') f.write('\n'+CT) f.write(alert) f.close() if __name__ == "__main__": Main() </code></pre> <p>Thanx a lot.</p>
-1
2016-08-13T08:46:59Z
38,931,004
<p>Wrap the <code>Main</code> call in an <em>infinite loop</em>?</p> <pre><code>if __name__ == "__main__": while True: Main() time.sleep(1) # optional, as Main already contains a sleep time </code></pre>
1
2016-08-13T08:53:41Z
[ "python", "while-loop", "io" ]
Run and log the output of 'ping' in a loop in a Python script
38,930,950
<p>i wrote a simple agaent in python that all it dose is just cheacks for the internet connection. When he finds out that ther is no connection he writes a log file to a text the hour and date and then just exit the program.</p> <p>I want it to keep testing if there is a connection even if there is not how can i do this ? without the program exit</p> <p>this is the code:</p> <pre><code>import os import time def Main(): ping =os.system('ping -n 1 -l 1000 8.8.8.8 ') while ping ==0: time.sleep(4) ping = os.system('ping -n 1 -l 1000 8.8.8.8 ') if ping ==1: print 'no connection' CT =time.strftime("%H:%M:%S %d/%m/%y") alert=' No Connection' f = open('logfile.txt','a+') f.write('\n'+CT) f.write(alert) f.close() if __name__ == "__main__": Main() </code></pre> <p>Thanx a lot.</p>
-1
2016-08-13T08:46:59Z
38,931,252
<p>If I understand yous correctly this will do its job:</p> <pre><code>import os import time def Main(): while True: ping = os.system('ping -n 1 -l 1000 8.8.8.8 ') if ping: print 'no connection' CT =time.strftime("%H:%M:%S %d/%m/%y") alert=' No Connection' with open('logfile.txt','a+') as f: f.write('\n'+CT) f.write(alert) time.sleep(4) if __name__ == "__main__": Main() </code></pre>
0
2016-08-13T09:25:03Z
[ "python", "while-loop", "io" ]
Run and log the output of 'ping' in a loop in a Python script
38,930,950
<p>i wrote a simple agaent in python that all it dose is just cheacks for the internet connection. When he finds out that ther is no connection he writes a log file to a text the hour and date and then just exit the program.</p> <p>I want it to keep testing if there is a connection even if there is not how can i do this ? without the program exit</p> <p>this is the code:</p> <pre><code>import os import time def Main(): ping =os.system('ping -n 1 -l 1000 8.8.8.8 ') while ping ==0: time.sleep(4) ping = os.system('ping -n 1 -l 1000 8.8.8.8 ') if ping ==1: print 'no connection' CT =time.strftime("%H:%M:%S %d/%m/%y") alert=' No Connection' f = open('logfile.txt','a+') f.write('\n'+CT) f.write(alert) f.close() if __name__ == "__main__": Main() </code></pre> <p>Thanx a lot.</p>
-1
2016-08-13T08:46:59Z
38,931,579
<p>This code should set you on your way. Just substitute the host with that of your choosing in the call to the <code>LogPing</code> object.</p> <p>Check out the comments inline and please ask me if you have any questions.</p> <pre><code>from datetime import datetime import os import shlex import subprocess from time import sleep class LogPing: def __init__(self, host, count=1, timeout_seconds=10, logfile="ping_log.txt"): self.host = host self.count = count self.timeout_seconds = timeout_seconds self.logfile = logfile self.output_blackhole = open(os.devnull, 'wb') def _command(self): command_string = "ping -c {count} -t {timeout} {host}".format( count=self.count, timeout=self.timeout_seconds, host=self.host ) try: # we don't actually care about the output, just the return code, # so trash the output. result == 0 on success result = subprocess.check_call( shlex.split(command_string), stdout=self.output_blackhole, stderr=subprocess.STDOUT ) except subprocess.CalledProcessError: # if here, that means that the host couldn't be reached for some reason. result = -1 return result def run(self): ping_command_result = self._command() if ping_command_result == 0: status = "OK" else: status = "NOK" # The time won't be exact, but close enough message = "{status} : {time} : {host}\n".format( status=status, time=datetime.utcnow().strftime("%Y-%m-%d_%T"), host=self.host ) # open file in a context manager for writing, creating if not exists # using a+ so that we append to the end of the last line. with open(self.logfile, 'a+') as f: f.write(message) if __name__ == "__main__": while True: ping_instance = LogPing("example.org").run() sleep(4) </code></pre>
1
2016-08-13T10:04:35Z
[ "python", "while-loop", "io" ]
Can you get and put into a Queue at the same time?
38,930,971
<p>I currently have a program that starts a thread with a FIFO queue. The queue is constantly putting data into the queue, and there is a method to get the items from the queue. The method acquires a lock and releases it once it grabs the items. </p> <p>My question is, will I face into any problems in the future putting and getting from the queue simultaneously? Would I need to add a lock when putting data into the queue?</p> <p>Thanks.</p>
0
2016-08-13T08:49:53Z
38,932,248
<p>The <code>Queue</code> type has blocking calls to <code>get()</code> and <code>put()</code> by default. So when you make a <code>get()</code> call, it will block the call and wait for an item to be put in the queue. </p> <p>The <code>put()</code> call will also by default block if the queue is full and wait for a slot to be free before it can put the item. </p> <p>This default behaviour might be altered by using <code>block=False</code> or passing a positive integer to <code>timeout</code>. If you disable blocking or set a timeout, the call will try to execute normally and if it fails (within the timeout), it will raise certain exceptions. </p> <p>Disabling blocking will fail instantly where as setting a timeout value would fail after those seconds. </p> <p>Since the default nature of the calls are blocking, you should not run into any issues. Even if you disable blocking, still there will be exceptions which you can handle and properly control the flow of the program. So there should not be an issue from simultaneously accessing the queue as it is "synchronized". </p>
1
2016-08-13T11:30:50Z
[ "python", "multithreading", "queue", "locking" ]
flask and flask_login - avoid importing flask_login from main code
38,930,978
<p>I am currently coding up a simple web application using flask and flask_login. This is <code>main.py</code>:</p> <pre><code>import flask import flask_login app = flask.Flask(__name__) login_manager = flask_login.LoginManager() login_manager.init_app(app) @app.route('/') @flask_login.login_required def index(): return "Hello World!" </code></pre> <p>The above code works. The problem arises because I want to separate authentication related code from the main flask application code. In other words, I want <code>my_auth.py</code> that imports <code>flask_login</code>, and I want <code>main.py</code> to <code>import my_auth</code>, and NOT have to import <code>flask_login</code>.</p> <p>The problem is with the <code>@flask_login.login_required</code> decorator. If I do not import <code>flask_login</code> from <code>main.py</code>, is it still possible to somehow "wrap" the main <code>index()</code> function with <code>login_required</code>?</p> <p>(I've actually asked a wrong question before, which may still be relevant: <a href="http://stackoverflow.com/questions/38930604/flask-and-flask-login-organizing-code">flask and flask_login - organizing code</a>)</p>
0
2016-08-13T08:50:51Z
38,931,555
<p>create a file <code>my_auth.py</code></p> <pre><code># my_auth.py import flask_login login_manager = flask_login.LoginManager() # create an alias of login_required decorator login_required = flask_login.login_required </code></pre> <p>and in file <code>main.py</code></p> <pre><code># main.py import flask from my_auth import ( login_manager, login_required ) app = flask.Flask(__name__) login_manager.init_app(app) @app.route('/') @login_required def index(): return "Hello World!" </code></pre> <p>Maybe this is what you want to achieve.</p>
3
2016-08-13T10:02:10Z
[ "python", "flask", "flask-login" ]
flask and flask_login - avoid importing flask_login from main code
38,930,978
<p>I am currently coding up a simple web application using flask and flask_login. This is <code>main.py</code>:</p> <pre><code>import flask import flask_login app = flask.Flask(__name__) login_manager = flask_login.LoginManager() login_manager.init_app(app) @app.route('/') @flask_login.login_required def index(): return "Hello World!" </code></pre> <p>The above code works. The problem arises because I want to separate authentication related code from the main flask application code. In other words, I want <code>my_auth.py</code> that imports <code>flask_login</code>, and I want <code>main.py</code> to <code>import my_auth</code>, and NOT have to import <code>flask_login</code>.</p> <p>The problem is with the <code>@flask_login.login_required</code> decorator. If I do not import <code>flask_login</code> from <code>main.py</code>, is it still possible to somehow "wrap" the main <code>index()</code> function with <code>login_required</code>?</p> <p>(I've actually asked a wrong question before, which may still be relevant: <a href="http://stackoverflow.com/questions/38930604/flask-and-flask-login-organizing-code">flask and flask_login - organizing code</a>)</p>
0
2016-08-13T08:50:51Z
38,931,700
<p>I can confirm that Akshay's answer works.</p> <p>While waiting for an answer, however, I've also found a workaround(?) that does not rely on using the decorator:</p> <p>In <code>main.py</code>:</p> <pre><code>@SVS.route("/") def index(): if not my_auth.is_authenticated(): return flask.redirect(flask.url_for('login')) return "Hello World!" </code></pre> <p>In <code>my_auth.py</code>:</p> <pre><code>def is_authenticated(): return flask_login.current_user.is_authenticated </code></pre>
1
2016-08-13T10:19:50Z
[ "python", "flask", "flask-login" ]
OneClassSVM scikit learn
38,931,023
<p>I have two data sets, trainig and test. They have labels "1" and "0". I need to evaluate these data sets using "oneClassSVM" Algorithm with "rbf" kernel in scikit learn. I loaded training data set, but I have no idea how to evaluate that with test data set. Below is my code,</p> <pre><code>from sklearn import svm import numpy as np input_file_data = "/home/anuradha/TrainData.csv" dataset = np.loadtxt(input_file_iris, delimiter=",") X = dataset[:,0:4] y = dataset[:,4] estimator= svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.1) </code></pre> <p>Please some one can help me to solve this problem ?</p>
1
2016-08-13T08:55:34Z
38,931,229
<p>It's as simple as adding the following two lines of code at the end of your script:</p> <pre><code>estimator.fit(X_train) y_pred_test = estimator.predict(X_test) </code></pre> <p>The first line tells svn which training data to use and the second one makes prediction on the test set (be sure to load both datasets and to change variable names accordingly).</p> <p><a href="http://scikit-learn.org/stable/auto_examples/svm/plot_oneclass.html" rel="nofollow">Here</a> there is a complete example on how to use <code>OneClassSVM</code> and <a href="http://scikit-learn.org/stable/modules/generated/sklearn.svm.OneClassSVM.html" rel="nofollow">here</a> the class reference.</p>
2
2016-08-13T09:21:06Z
[ "python", "machine-learning", "scikit-learn", "svm" ]
TypeError: string indices must be integer
38,931,066
<p>I tried to get data from <code>JSON</code>. But instead data i get <code>TypeError</code>:</p> <pre><code>'TypeError: string indices must be integers' </code></pre> <p>Here ist my code:</p> <pre><code>api.authenticate(LOGIN, CONN) profil = api.get_profile("abc") data = json.dumps(profil, indent=4) print(data["login"]) </code></pre> <p>JSON file:</p> <pre><code>{ "public_email": "", "violation_url": null, "is_blocked": false, "links_published": 0, "login": "abc", "links_added": 1, "gg": "", "signup_date": "2014-10-26 21:15:41", } </code></pre> <p>I've looking for solution (google, SO) but I cannot find or not working for me.</p>
0
2016-08-13T09:00:31Z
38,931,241
<p>There is an extra <code>,</code> in your json file at the end. Delete this:</p> <pre><code>{ "public_email": "", "violation_url": null, "is_blocked": false, "links_published": 0, "login": "abc", "links_added": 1, "gg": "", "signup_date": "2014-10-26 21:15:41" } </code></pre> <p>Then <code>load</code> the json file (not <code>dump</code>):</p> <pre><code>with open('abc.json') as data_file: data = json.load(data_file) print(data["login"]) </code></pre>
-1
2016-08-13T09:22:36Z
[ "python", "json", "python-3.x" ]
theano.function - how does it work?
38,931,112
<p>I've read the official documenation and read the comments here <a href="https://github.com/Theano/theano/blob/ddfd7d239a1e656cee850cdbc548da63f349c37d/theano/compile/function.py#L74-L324" rel="nofollow">https://github.com/Theano/theano/blob/ddfd7d239a1e656cee850cdbc548da63f349c37d/theano/compile/function.py#L74-L324</a>, and one man told me that it tells Theano to compile the symbolic computation graph into an actual program that you can run.</p> <p>However, I still cannot figure out how does it know, for example in this code:</p> <pre><code>self.update_fun = theano.function( inputs=[self.input_mat, self.output_mat], outputs=self.cost, updates=updates, allow_input_downcast=True) </code></pre> <p>how to compute all that, if it has no body? I mean all those things are computed in some code above these pasted lines, but... is theano.function actually looking to source code to find out how to compute those things? I'm just guessing and would really like to know how it works.</p> <p>Maybe the problem I have in the explanation that "<em>it tells Theano to compile the symbolic computation graph into an actual program</em>" is that I have no clue what symbolic computation graph is, so that would be another question very related to the previous.</p> <p>Explanation would be appreciated.</p>
1
2016-08-13T09:06:08Z
38,931,455
<p>I'm no expert but here's my take at explaining it:</p> <p>Yes the 'body' is defined in the code above. But <code>theano</code> doesn't 'interpret' that code directly like the python interpreter would. The code in question is just creating <code>theano</code> objects that will allow <code>theano</code> to compile the desired function. Let's take a simple example: how you would create a function <code>f(x) = 2x + x**3</code>.</p> <p>You first create a symbolic input variable <code>x</code>. Then you define the 'body' of the function by building the symbolic expression of <code>f(x)</code>:</p> <pre><code>y = 2 * x + x**3 # defines a new symbolic variable which depends on x </code></pre> <p>This <code>y</code> object is equivalent to a graph representing the formula. Something like <code>Plus(Times(2,x), Power(x,3))</code>. You finally call <code>theano.function</code> with <code>input=x</code> and <code>output=y</code>. Then <code>theano</code> does its magic and compiles the actual function <code>f(x) = y = 2 * x + x**3</code> from the information (the graph) 'contained' in <code>y</code>.</p> <p>Does it make things clearer?</p>
1
2016-08-13T09:48:49Z
[ "python", "function", "theano" ]
pygame-How to darken screen
38,931,142
<p>I want to darken current screen a bit before poping up a new surface. I know there is no function in pygame to do this and that I will have to process the image to darken it. But as long as I know the only way to get current displaying surface in pygame is by saving it to disk as a file which slows down the game. Is there any other way to do this with pygame? Like saving the image to a value in memory so that I can process it without saving it somewhere.</p> <p>Thanks in advance,</p> <p>Stam</p>
1
2016-08-13T09:09:37Z
38,931,184
<p>You don't need to save anything to a file. When you read an image to a file, it is a <code>Surface</code> object. You them blit this object to the screen. But these <code>Surface</code> objects have the same methods and properties than the object working as the screen - (which is also a Surface): you can draw primitives, and blit other images to them - all in memory.</p> <p>So, once you read your image, just make a copy of it, draw a filled rectangle with a solid transparent color on it to darken it, and then blit it to the screen. Repeat the process increasing the transparency level and pasting it on the screen again if you want a fade in effect.</p> <pre><code>import pygame screen = pygame.display.set_mode((640,480)) img = pygame.image.load("MYIMAGE.PNG") for opacity in range(255, 0, -15): work_img = img.copy() pygame.draw.rect(work_img, (255,0, 0, opacity), (0,0, 640,480)) screen.blit(work_img, (0,0)) pygame.display.flip() pygame.time.delay(100) </code></pre>
2
2016-08-13T09:15:20Z
[ "python", "python-3.x", "pygame" ]
Avoiding duplicates and assigning value to each singleton in a for loop
38,931,196
<p>I am attempting to deal with the duplication and the failure of assigning value to each singleton in a for loop.</p> <p>First, I create edges from one node to nodes which it connects to:</p> <pre><code>ti = "D" #node from lst = ["A", "B", "C"] #nodes to packaged = [(ti, l) for l in lst] # a list of edges (from - to) l_lst = len(lst) ## length of lst, *i.e.* degree of ti weight = 1 / float(l_lst) # edge weight, normalized by length of lst for pair in packaged: print (packged, weight) </code></pre> <p>This gives me</p> <pre><code>([('D', 'A'), ('D', 'B'), ('D', 'C')], 0.3333333333333333) ([('D', 'A'), ('D', 'B'), ('D', 'C')], 0.3333333333333333) ([('D', 'A'), ('D', 'B'), ('D', 'C')], 0.3333333333333333) </code></pre> <p>However, what I would like to achieve is:</p> <pre><code>('D', 'A'), 0.3333333333333333 ('D', 'B'), 0.3333333333333333 ('D', 'C'), 0.3333333333333333 </code></pre> <p>How to avoid duplicates and assign weight to each pair of nodes (edge)?</p> <p>Thank you!!</p>
0
2016-08-13T09:16:37Z
38,931,220
<p>What you need is this:</p> <pre><code>ti = "D" #node from lst = ["A", "B", "C"] #nodes to packaged = [(ti, l) for l in lst] # a list of edges (from - to) l_lst = len(lst) ## length of lst, *i.e.* degree of ti weight = 1 / float(l_lst) # edge weight, normalized by length of lst for pair in packaged: print (pair, weight) </code></pre> <p>In for loop use <code>pair</code> instead of <code>packaged</code></p>
3
2016-08-13T09:19:54Z
[ "python", "loops" ]
Avoiding duplicates and assigning value to each singleton in a for loop
38,931,196
<p>I am attempting to deal with the duplication and the failure of assigning value to each singleton in a for loop.</p> <p>First, I create edges from one node to nodes which it connects to:</p> <pre><code>ti = "D" #node from lst = ["A", "B", "C"] #nodes to packaged = [(ti, l) for l in lst] # a list of edges (from - to) l_lst = len(lst) ## length of lst, *i.e.* degree of ti weight = 1 / float(l_lst) # edge weight, normalized by length of lst for pair in packaged: print (packged, weight) </code></pre> <p>This gives me</p> <pre><code>([('D', 'A'), ('D', 'B'), ('D', 'C')], 0.3333333333333333) ([('D', 'A'), ('D', 'B'), ('D', 'C')], 0.3333333333333333) ([('D', 'A'), ('D', 'B'), ('D', 'C')], 0.3333333333333333) </code></pre> <p>However, what I would like to achieve is:</p> <pre><code>('D', 'A'), 0.3333333333333333 ('D', 'B'), 0.3333333333333333 ('D', 'C'), 0.3333333333333333 </code></pre> <p>How to avoid duplicates and assign weight to each pair of nodes (edge)?</p> <p>Thank you!!</p>
0
2016-08-13T09:16:37Z
38,931,235
<p>A simple fix:</p> <pre><code>for pair in packaged: print (pair, weight) </code></pre>
3
2016-08-13T09:21:51Z
[ "python", "loops" ]
OrientDB: How can I create a property unique using SQL?
38,931,334
<p>I have a little question for you, I don't know how create a property UNIQUE. I know the SQL command for create a property, but don't know how do this UNIQUE.</p> <p>And I can't use the app studio of OrientDB (would be most easy for me but...)</p> <p>This is the command that I know:</p> <pre><code>"CREATE PROPERTY user.name STRING" </code></pre> <p>Thanks in advance.</p>
0
2016-08-13T09:34:48Z
38,931,388
<p>You can create index on this particular property.</p> <pre><code>CREATE INDEX user.name UNIQUE </code></pre> <p>Take a look here: <a href="http://orientdb.com/docs/2.1/Console-Command-Create-Index.html" rel="nofollow">Console - CREATE INDEX</a></p>
2
2016-08-13T09:42:48Z
[ "python", "orientdb" ]
How to execute one python file with the arguments from another python file without passing arguments on command/terminal line?
38,931,450
<p>I have a default code in Python that has the argument parser and have to pass those argument by myself in command line,but i dont want to pass the arguments myself rather execute that file from another python file with the arguments written in that file or i dont want to write those arguments myself on command lines.</p> <p>My argument parsing code is as follows:</p> <pre><code>if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-i', type=str, nargs='+', help="Enter the filenames with extention of an Image") arg=parser.parse_args() if not len(sys.argv) &gt; 1: parser.print_help() exit() </code></pre> <p>my function is </p> <pre><code>def Predict_Emotion(filename): print "Opening image...." try: img=io.imread(filename) cvimg=cv2.imread(filename) except: print "Exception: File Not found." return </code></pre> <p>And my execution line is as</p> <pre><code>for filename in arg.i: Predict_Emotion(filename) </code></pre> <p>Any help would be appreciated.</p>
-4
2016-08-13T09:48:24Z
38,931,618
<p>Here is how you do it. You need to slightly modify the above code to form the following</p> <pre><code>import sys, argparse def run_function (lista): parser = argparse.ArgumentParser() parser.add_argument('-i', type=str, nargs='+', help="Enter the filenames with extention of an Image") arg=parser.parse_args(lista) if (len(sys.argv) &lt;= 1): parser.print_help() exit() if __name__ == "__main__": run_function (sys.argv) </code></pre> <p>Reference used: <a href="https://docs.python.org/2/library/argparse.html" rel="nofollow">https://docs.python.org/2/library/argparse.html</a></p> <p>That will now allow you to give it your own list from another file. To call it from the other file, you need to do the following</p> <pre><code>#These below two lines are not necessary if stating python in directory the script is in, or if it is already in your Python Path import sys sys.path.insert(0, "path to directory script is in") #Below lines are now necessary import your_script #NOTE this is the name of your file without the .py extention on the end list_of_files = ["file1", "file2"] your_script.run_function(list_of_files) </code></pre> <p>I think that is everything you asked!</p>
0
2016-08-13T10:08:28Z
[ "python", "opencv" ]
Invalid \escape in json.loads(), python 2.7
38,931,535
<p>I am having a list of jsons in a text file as </p> <pre><code>[{"key1": "value1", "key2": "value2"},{},{}] </code></pre> <p>Now I am trying to read the file and converting it into list of dicts so that I can iterate and use those key-value pairs using code - </p> <pre><code>with open('./file.txt') as f: listOfDict= json.load(f) </code></pre> <p>I am getting error - </p> <pre><code>ValueError: Invalid \escape: line 1 column 2005707 (char 2005706) </code></pre> <p>I think that might be because some of the values are like - For eg. {"key1":"ENERGIZER\xc2"}</p> <p><strong>I forgot to use text.encode("utf-8") while writing to this file.</strong> Instead I used str(text) while writing to the file.</p> <p>Is this is the reason for this error and how can I resolve this issue. </p>
0
2016-08-13T09:59:00Z
38,931,895
<p>Ok, you'll have to do a little string manipulation to unescape and decode.</p> <p>It depends on whether your data contains escaped Unicodes or escaped 8bit characterset, like <code>latin1</code> or <code>cp1252</code>. You'll have to experiment to see what works for your data.</p> <p>If it's escaped Unicode you can simply do:</p> <pre><code>import io with io.open('./file.txt', 'r', encoding='unicode_escape') as f: listOfDict= json.load(f) </code></pre> <p>If escaped 8bit 'latin1', you'll need to do:</p> <pre><code>with open('./file.txt', 'r') as f: # read, convert escape to byte, convert bytes as 'latin1' decoded_json = f.read().decode('string_escape').decode('latin1') listOfDict = json.loads(decoded_json) # Note the "s". </code></pre>
0
2016-08-13T10:47:38Z
[ "python", "json", "io", "character-encoding" ]
How can I increment the value of a variable within dictionary comprehension
38,931,552
<pre><code>start = 0 limit = 100 count = 10 total_count = 1000 pages = {} for i in range(1, count+1): pages[i] = start start += limit print pages {1: 0, 2: 100, 3: 200, 4: 300, 5: 400, 6: 500, 7: 600, 8: 700, 9: 800, 10: 900} </code></pre> <p>How can I achieve the same result using dictionary comprehension? I can't seem to be able to increment the value of variable 'start' after each iteration with dict comprehension.</p> <p>Is it possible to achieve the same result comprehension?</p>
0
2016-08-13T10:02:09Z
38,931,612
<pre><code>start = 0 limit = 100 count = 10 pages2 = {(i + 1): start + i * limit for i in range(count)} print pages2 </code></pre>
1
2016-08-13T10:07:48Z
[ "python", "dictionary-comprehension" ]
How can I increment the value of a variable within dictionary comprehension
38,931,552
<pre><code>start = 0 limit = 100 count = 10 total_count = 1000 pages = {} for i in range(1, count+1): pages[i] = start start += limit print pages {1: 0, 2: 100, 3: 200, 4: 300, 5: 400, 6: 500, 7: 600, 8: 700, 9: 800, 10: 900} </code></pre> <p>How can I achieve the same result using dictionary comprehension? I can't seem to be able to increment the value of variable 'start' after each iteration with dict comprehension.</p> <p>Is it possible to achieve the same result comprehension?</p>
0
2016-08-13T10:02:09Z
38,931,615
<p>Use mathematics:</p> <pre><code>pages = {(i+1): 100 * i for i in range(count)} </code></pre> <p>Since <code>start</code> starts at zero and keeps adding <code>100</code>, we can use multiplication to find where it should be at each point. If <code>start</code> and <code>limit</code> aren't always going to be what they are here, you can still do this:</p> <pre><code>pages = {(i+1): start + (limit * i) for i in range(count)} </code></pre>
2
2016-08-13T10:07:56Z
[ "python", "dictionary-comprehension" ]
weird behaviour of globals() and locals() in python
38,931,598
<p>I create a simple code. For example </p> <pre><code>x = 50 def func(x): x = 2 print 'Changed local x to', x func(x) </code></pre> <p>Then I type globals() and expect to see the list of global variables Instead I get a weird output like this below. Why? I use python 2.7, in jupyter. Everything else works fine. And this behaviour of globals() always happens . Same with locals(). </p> <pre><code>{'In': ['', u"x = 50\n\ndef func(x):\n print 'x is', x\n x = 2\n print 'Changed local x to', x\n\nfunc(x)\nprint 'x is still', x", u'globals()', u"x = 50\n\n def func(x):\n x = 2\n print 'Changed local x to', x\n\n func(x)", u"x = 50\n\ndef func(x):\n x = 2\n print 'Changed local x to', x\n\nfunc(x)", u'globals()'], 'Out': {2: {...}}, '_': {...}, '_2': {...}, '__': '', '___': '', '__builtin__': &lt;module '__builtin__' (built-in)&gt;, '__builtins__': &lt;module '__builtin__' (built-in)&gt;, '__doc__': 'Automatically created module for IPython interactive environment', '__name__': '__main__', '_dh': [u'C:\\Users\\user'], '_i': u" x = 50\n\n def func(x):\n x = 2\n print 'Changed local x to', x\n\n func(x)", '_i1': u"x = 50\n\ndef func(x):\n print 'x is', x\n x = 2\n print 'Changed local x to', x\n\nfunc(x)\nprint 'x is still', x", '_i2': u'globals()', '_i3': u" x = 50\n\n def func(x):\n x = 2\n print 'Changed local x to', x\n\n func(x)", '_i4': u" x = 50\n\n def func(x):\n x = 2\n print 'Changed local x to', x\n\n func(x)", '_i5': u'globals()', '_ih': ['', u"x = 50\n\ndef func(x):\n print 'x is', x\n x = 2\n print 'Changed local x to', x\n\nfunc(x)\nprint 'x is still', x", u'globals()', u"x = 50\n\n def func(x):\n x = 2\n print 'Changed local x to', x\n\n func(x)", u"x = 50\n\ndef func(x):\n x = 2\n print 'Changed local x to', x\n\nfunc(x)", u'globals()'], '_ii': u" x = 50\n\n def func(x):\n x = 2\n print 'Changed local x to', x\n\n func(x)", '_iii': u'globals()', '_oh': {2: {...}}, '_sh': &lt;module 'IPython.core.shadowns' from 'C:\Users\user\Anaconda2\lib\site-packages\IPython\core\shadowns.pyc'&gt;, 'exit': &lt;IPython.core.autocall.ZMQExitAutocall at 0x27d0a90&gt;, 'func': &lt;function __main__.func&gt;, 'get_ipython': &lt;bound method ZMQInteractiveShell.get_ipython of &lt;ipykernel.zmqshell.ZMQInteractiveShell object at 0x0272F9D0&gt;&gt;, 'quit': &lt;IPython.core.autocall.ZMQExitAutocall at 0x27d0a90&gt;, 'x': 50} </code></pre>
0
2016-08-13T10:06:17Z
38,931,692
<p>What you're seeing is indeed the global variables defined in your interpreter session. There are a few more of them than you expected! That's because the interactive interpreter uses some variables for its own purposes, such as keeping track of past inputs and outputs.</p> <p>Some of the globals you're seeing (like <code>__builtins__</code> and <code>exit</code>) are a documented part of the Python language. Others are implementation details specific to your particular interpreter or shell environment, and may or may not be documented anywhere.</p> <p>As for <code>locals</code>, it's only useful inside a function. At the top level of a module, it will return exactly the same dictionary as <code>globals</code> (including all the interactive crud if you're running it interactively).</p>
2
2016-08-13T10:18:25Z
[ "python", "python-2.7", "ipython", "jupyter", "jupyter-notebook" ]
How to access dictionary-type items in a list (python or maybe javascript)
38,931,966
<p>I have some data stored in 'nutrients' JSONField in a django 'Food' model.</p> <p>some sample datastructure at the bottom.</p> <p>The data is Food.nutrients, but I don't know how/ best way access a particular item in the nutrients list - which is structured like [{dict type item},{dict type item},...]. </p> <p>Each item is a dictionary with a 'name' key and 'nutrient_id' key, which I <em>feel</em> could help me pick out the item that I want. And then from the item dictionary I want to get the value for key 'value' (I didn't name the key 'value').</p> <pre><code> [{u'dp': 1, u'group': u'Minerals', u'measures': [], u'name': u'Manganese, Mn', u'nutrient_id': 315, u'se': u'', u'sourcecode': [1], u'unit': u'mg', u'value': 0.094}, {u'dp': 1, u'group': u'Minerals', u'measures': [], u'name': u'Selenium, Se', u'nutrient_id': 317, u'se': u'', u'sourcecode': [1], u'unit': u'\xb5g', u'value': 0.4}, {u'dp': 1, u'group': u'Vitamins', u'measures': [], u'name': u'Vitamin C, total ascorbic acid', u'nutrient_id': 401, u'se': u'', u'sourcecode': [1], u'unit': u'mg', u'value': 4.0}] </code></pre>
0
2016-08-13T10:57:13Z
38,932,026
<p>Let's suppose, you have the list of dictionaries in <code>nutrients</code>. Now you can filter the list to find the items matching a particular key with a specific value. For example, to find the dictionary with <code>name</code> having "Manganese, Mn", you can do: </p> <pre><code>matches = filter(lambda n: n.get('name') == 'Manganese, Mn', nutrients) </code></pre> <p>Now the <code>matches</code> list should contain the nutrients which contain "Manganese, Mn" in the <code>name</code> key. </p> <p>You can access the first nutrient using index - <code>matches[0]</code>. Now you can access other keys too, like <code>matches[0].get('value')</code></p>
3
2016-08-13T11:05:54Z
[ "python", "json", "list", "dictionary" ]
cannot import name DurationField
38,931,987
<p>I am trying to run an application that uses django rest framework.However am getting the import error "cannot import name DurationField".How do i resolve this error ?</p> <p>Error message <a href="http://i.stack.imgur.com/EiRl1.png" rel="nofollow">enter image description here</a></p> <p>Views.py</p> <pre><code>from django.shortcuts import render from django.contrib.auth.models import User from django.http import Http404 from restapp.serializers import UserSerializer from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status class UserList(APIView): #List all user,create new one def get(self,request,format=None): users = User.objects.all() serializer = UserSerializer(users,many=True) return Response(serializer.data) def post(self,request,format=None): serializer= UserSerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) def delete(self,request,pk, format=None): user = self.get_object(pk) user.delete() return Response(status=status.HTTP_204_NO_CONTENT) class UserDetail(APIView): #Retrive update,or delete a user instance def get_object(self,pk): try: return User.objects.get(pk=pk) except user.DoesNotExist: raise 404 def get(self,request,pk,format=None): user = self.get_object(pk) user = UserSerializer(user) return Response(user.data) def put(self,request,pk,format=None): user = self.get_object(pk) serializer=UserSerializer(user,data = request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) def delete(self,request,pk,format=None): user = self.get_object(pk) user.delete() return Response(status=status.HTTP_204_NO_CONTENT) </code></pre> <p>serializers.py</p> <pre><code>from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','username','firstname','last_name','email') </code></pre> <p>It points to this file serializers.py,line 18 as source of error.</p> <p><a href="http://i.stack.imgur.com/Bhy3X.png" rel="nofollow">enter image description here</a></p>
0
2016-08-13T10:59:47Z
38,932,278
<p>From the screenshot, I can see you're using Django 1.7. </p> <p>The <code>DurationField</code> that is being imported by DRF was introduced in Django 1.8. </p> <p>So you have to upgrade your Django to get this version of DRF to work. </p>
2
2016-08-13T11:34:29Z
[ "python", "django", "django-rest-framework" ]
is there a way to execute a python program using c#?
38,932,127
<p>I want to call my python program and get it executed automatically as it gets called, using c#. I have done uptill opening the program but how to run it and the get the output. It is my final year project kindly help me out.Here is my code:</p> <pre><code>Process p = new Process(); ProcessStartInfo pi = new ProcessStartInfo(); pi.UseShellExecute = true; pi.FileName = @"python.exe"; p.StartInfo = pi; try { p.StandardOutput.ReadToEnd(); } catch (Exception Ex) { } </code></pre>
0
2016-08-13T11:18:23Z
38,944,660
<p>The following code execute python script that call modules and return result</p> <pre><code>class Program { static void Main(string[] args) { RunPython(); Console.ReadKey(); } static void RunPython() { var args = "test.py"; //main python script ProcessStartInfo start = new ProcessStartInfo(); //path to Python program start.FileName = @"F:\Python\Python35-32\python.exe"; start.Arguments = string.Format("{0} ", args); //very important to use modules and other scripts called by main script start.WorkingDirectory = @"f:\labs"; start.UseShellExecute = false; start.RedirectStandardOutput = true; using (Process process = Process.Start(start)) { using (StreamReader reader = process.StandardOutput) { string result = reader.ReadToEnd(); Console.Write(result); } } } } </code></pre> <p>test scripts:</p> <p>test.py</p> <pre><code>import fibo print ( "Hello, world!") fibo.fib(1000) </code></pre> <p>module: fibo.py</p> <pre><code>def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b &lt; n: print (b), a, b = b, a+b </code></pre>
0
2016-08-14T17:19:06Z
[ "c#", "python", "using", "execute" ]
mnlogit regression, singular matrix error
38,932,129
<p>My regression model using statsmodels in python works with 48,065 lines of data, but while adding new data I have tracked down one line of code that produces a singular matrix error. Answers to similar questions seem to suggest missing data but I have checked and there is nothing visibibly irregular from the error prone row of code causing me major issues. Does anyone know if this is an error in my code or knows a solution to fix it as I'm out of ideas.</p> <p>Data2.csv - <a href="http://www.sharecsv.com/s/8ff31545056b8864f2ad26ef2fe38a09/Data2.csv" rel="nofollow">http://www.sharecsv.com/s/8ff31545056b8864f2ad26ef2fe38a09/Data2.csv</a></p> <pre><code>import pandas as pd import statsmodels.formula.api as smf data = pd.read_csv("Data2.csv") formula = 'is_success ~ goal_angle + goal_distance + np_distance + fp_distance + is_fast_attack + is_header + prev_tb + is_rebound + is_penalty + prev_cross + is_tb2 + is_own_goal + is_cutback + asst_dist' model = smf.mnlogit(formula, data=data, missing='drop').fit() </code></pre> <p>CSV Line producing error: <code>0,0,0,0,0,0,0,1,22.94476,16.877204,13.484806,20.924627,0,0,11.765203</code></p> <p>Error with Problematic line within the model:</p> <pre><code>runfile('C:/Users/User1/Desktop/Model Check.py', wdir='C:/Users/User1/Desktop') Optimization terminated successfully. Current function value: 0.264334 Iterations 20 Traceback (most recent call last): File "&lt;ipython-input-76-eace3b458e24&gt;", line 1, in &lt;module&gt; runfile('C:/Users/User1/Desktop/xG_xA Model Check.py', wdir='C:/Users/User1/Desktop') File "C:\Users\User1\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile execfile(filename, namespace) File "C:\Users\User1\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc) File "C:/Users/User1/Desktop/xG_xA Model Check.py", line 6, in &lt;module&gt; model = smf.mnlogit(formula, data=data, missing='drop').fit() File "C:\Users\User1\Anaconda2\lib\site-packages\statsmodels\discrete\discrete_model.py", line 587, in fit disp=disp, callback=callback, **kwargs) File "C:\Users\User1\Anaconda2\lib\site-packages\statsmodels\base\model.py", line 434, in fit Hinv = np.linalg.inv(-retvals['Hessian']) / nobs File "C:\Users\User1\Anaconda2\lib\site-packages\numpy\linalg\linalg.py", line 526, in inv ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj) File "C:\Users\User1\Anaconda2\lib\site-packages\numpy\linalg\linalg.py", line 90, in _raise_linalgerror_singular raise LinAlgError("Singular matrix") LinAlgError: Singular matrix </code></pre>
0
2016-08-13T11:18:51Z
38,933,654
<p>As far as I can see:</p> <p>The problem is the variable <code>is_own_goal</code> because all observation where this is 1 also have the dependent variable <code>is_success</code> equal to 1. That means there is no variation in the outcome because <code>is_own_goal</code> already specifies that it is a success. </p> <p>As a consequence, we cannot estimate a coefficient for is_own_goal, the coefficient is not identified by the data. The variance of the coefficient would be infinite and inverting the Hessian to get the covariance of the parameter estimates fails because the Hessian is singular. Given floating point precision, with some computational noise the hessian might be invertible and the Singular Matrix exception would not show up. Which, I guess, is the reason that it works with some but not all observations.</p> <p>BTW: If the dependent variable, endog, is binary, then Logit is more appropriate, even though MNLogit has it as a special case.</p> <p>BTW: Penalized estimation would be another way to force an estimate even in singular cases, although the coefficient would still not be identified by the data and be just a consequence of the penalization.</p> <p>In this example, </p> <p><code>mod = smf.logit(formula, data=data, missing='drop').fit_regularized()</code></p> <p>works for me. This is L1 penalization. In statsmodels 0.8, there is also elastic net penalization for GLM which has Binomial (i.e. Logit) as a family.</p>
0
2016-08-13T14:22:42Z
[ "python", "regression", "statsmodels" ]
How improve this django view code?
38,932,266
<p>What do you think about this code part? How bad it is? It's normal practise to write code like this? How I can improve this code and make it shorter, more readable and ofcourse improver performance?</p> <p>I think this code isn't very good, especially to understand it and maintain it.</p> <pre><code>def car_list(request): if request.GET.get('city'): city = request.GET.get('city').split(",")[0] elif 'city' in request.COOKIES: city = request.COOKIES['city'].split(",")[0] else: city = '' not_older_than = request.GET.getlist('not_older_than') transmission_type = request.GET.getlist('transmission_type') travel_abroad = request.GET.get('travel_abroad') insurance = request.GET.get('insurance') fuel_type = request.GET.getlist('fuel_type') body_type = request.GET.getlist('body_type') doors = request.GET.getlist('doors') deposit_exists = request.GET.get('deposit_exists') delivery_same_city = request.GET.get('delivery_same_city') day_run_limit_exists = request.GET.get('day_run_limit_exists') seats = request.GET.getlist('seats') if request.user.is_authenticated(): favorite = CarFavorite.objects.filter(user=request.user) else: favorite = [] favorite_user_cars = [] for fav in favorite: favorite_user_cars.append(fav.car.id) q = Q() if city: q &amp;= Q(city__city=city) if not_older_than: qx = Q() for yr in not_older_than: print yr year = str(yr) print year if year == '5': qx |= Q(years__gt=int(date.today().year-5)) print 'yeah yeah 5', int(date.today().year-5) if year == '10': qx |= Q(years__gt=date.today().year-10, years__lt=date.today().year-5) print 'yeah yeah yeah 10' if year == '15': qx |= Q(years__gt=date.today().year-15, years__lt=date.today().year-10) if year == '16': qx |= Q(years__lte=date.today().year-15) q &amp;=qx # q &amp;= Q(city=city) if travel_abroad: if travel_abroad == u'True': q &amp;= Q(travel_abroad=True) if insurance: q &amp;= Q(insurance=insurance) if transmission_type: qx = Q() for transmission in transmission_type: qx |= Q(transmission_type=transmission) q &amp;= qx if fuel_type: qx = Q() for fuel in fuel_type: qx |= Q(fuel_type=fuel) q &amp;= qx if body_type: qx = Q() for body in body_type: qx |= Q(body_type=body) q &amp;= qx if doors: qx = Q() for door in doors: qx |= Q(doors=door) q &amp;= qx if deposit_exists: qx = Q() if str(deposit_exists) == 'False': qx &amp;= Q(deposit_exists=False) q &amp;= qx if delivery_same_city: if delivery_same_city==u'True': q &amp;= Q(do_you_deliver=True) if day_run_limit_exists: if day_run_limit_exists == u'True': q &amp;= Q(day_run_limit_exists=False) if seats: qx = Q() for seat in seats: seat = str(seat) if seat == '2': qx |= Q(seats=2) if seat == '4': qx |= Q(seats__gte=4, seats__lte=5) if seat == '6': qx |= Q(seats__gte=6) q &amp;= qx if 'filter' in request.GET: cars = models.CarForRent.objects.filter(q) elif 'body_type' in request.GET: body_type = request.GET.get('body_type') cars = models.CarForRent.objects.filter(body_type=body_type) else: cars = models.CarForRent.objects.filter(q) car_ratings={} rent_prices={} if 'end_date' in request.COOKIES: total_rent_days = datetime.strptime(request.COOKIES['end_date'], '%Y-%m-%d') - \ datetime.strptime(request.COOKIES['start_date'],'%Y-%m-%d') if total_rent_days.days == 0: total_rent_days = 1 else: total_rent_days = total_rent_days.days else: total_rent_days = 1 for car in cars: car_rent_prices = models.CarRentPrice.objects.filter(car=car) if car_rent_prices: if car_rent_prices.last().end &gt; total_rent_days: for price in car_rent_prices: if price.start &lt;= total_rent_days &lt;= price.end: rent_prices[car.id] = total_rent_days * price.price else: rent_prices[car.id] = total_rent_days * car_rent_prices.last().price ratings = UserRating.objects.filter(rating_for=car) if len(ratings) &gt; 0: service_rating = 0 car_rating = 0 how_real_rating = 0 for rating in ratings: service_rating += rating.service car_rating += rating.car how_real_rating += rating.how_real total_rating = round(((service_rating/len(ratings)) + (car_rating/len(ratings)) + \ (how_real_rating/len(ratings)))/3.0,1) car_ratings[car.id] = total_rating else: car_ratings[car.id] = 0 sorted_by_price = sorted(rent_prices.items(), key=operator.itemgetter(1)) sorted_by_rating = sorted(car_ratings.items(), key=operator.itemgetter(1), reverse=True) if 'sort_by' in request.GET: if request.GET.get('sort_by') == 'price': cars = [] for car_id in sorted_by_price: cars.append(models.CarForRent.objects.get(id=car_id[0])) elif request.GET.get('sort_by') == 'rating': cars = [] for car_id in sorted_by_rating: cars_filter = models.CarForRent.objects.filter(id=car_id[0]) for car in cars_filter: cars.append(car) else: cars = [] for car_id in sorted_by_price: cars.append(models.CarForRent.objects.get(id=car_id[0])) elif 'sort_param' in request.COOKIES: if request.COOKIES['sort_param'] == 'price': cars = [] for car_id in sorted_by_price: cars.append(models.CarForRent.objects.get(id=car_id[0])) elif request.COOKIES['sort_param'] == 'rating': cars = [] for car_id in sorted_by_rating: cars_filter = models.CarForRent.objects.filter(id=car_id[0]) for car in cars_filter: cars.append(car) else: cars = [] for car_id in sorted_by_price: # print car_id[0] cars.append(models.CarForRent.objects.get(id=car_id[0])) else: cars = [] for car_id in sorted_by_price: cars.append(models.CarForRent.objects.get(id=car_id[0])) paginator = Paginator(cars, 10) page = request.GET.get('page') try: cars = paginator.page(page) except PageNotAnInteger: cars = paginator.page(1) except EmptyPage: cars = paginator.page(paginator.num_pages) return render(request, 'cars.html', {'city': city, 'cars': cars, 'favorite_user_cars': favorite_user_cars, 'car_ratings': car_ratings, 'rent_prices': rent_prices, 'rent_days': total_rent_days}) </code></pre>
1
2016-08-13T11:32:46Z
38,932,462
<p>I would start with this small refactoring</p> <p>from </p> <pre><code>if request.user.is_authenticated(): favorite = CarFavorite.objects.filter(user=request.user) else: favorite = [] favorite_user_cars = [] for fav in favorite: favorite_user_cars.append(fav.car.id) </code></pre> <p>to --></p> <pre><code># utils.py def _get_favorite_car_ids(user): return list(CarFavorite.objects.filter(user=user).values_list('car_id', flat=True)) if user.is_authenticated() else [] # views.py favorite_car_ids = _get_favorite_car_ids(request.user) </code></pre>
2
2016-08-13T11:56:04Z
[ "python", "django", "django-views" ]
How to pip install for certain version of python
38,932,377
<p>I need to install <code>requests</code> for python3</p> <pre><code>pip install requests </code></pre> <p>installs it for python2.7.</p> <p>How to do this without <code>virtualenv</code> ?</p>
-4
2016-08-13T11:45:57Z
38,932,589
<p>Sorry for the rate of -2 in your problem, and I don't think I can understand your question well, either. I will try too help.</p> <p>Now you have python 2.7 and python3, when your virtualenv is not activate, 'pip' is for python2.x and 'pip3' is for python3.x</p> <p>there is no necessary to think about Why pip is for python2.7</p> <p>you can choose python3 when you create a virtualenv environment folder: </p> <p>$ virtualenv --python=python3 aaa</p> <p>$ cd aaa</p> <p>$ . bin/activate</p> <p>now 'pip install' is for python3.x</p>
0
2016-08-13T12:11:06Z
[ "python", "python-3.x", "pip", "virtualenv" ]
How to pip install for certain version of python
38,932,377
<p>I need to install <code>requests</code> for python3</p> <pre><code>pip install requests </code></pre> <p>installs it for python2.7.</p> <p>How to do this without <code>virtualenv</code> ?</p>
-4
2016-08-13T11:45:57Z
38,937,196
<p>I tried <code>pip install lxml</code> and succeed, not sure the situation you encountered.</p> <p><code>pip</code> command uses the "default" Python version in your system, you HAVE to check the output of <code>pip --version</code> to figure out which version it belongs to.</p> <p>"<code>pip</code> is for Python2" is not always correct, at least on my machine.</p> <p>If you want to install packages without virtualenv, you have to install them globally, <code>sudo pip install requests</code> does that.</p> <p>But think twice and try more a little bit before you do, we usually not install python packages globally.</p>
0
2016-08-13T21:33:45Z
[ "python", "python-3.x", "pip", "virtualenv" ]
How to pip install for certain version of python
38,932,377
<p>I need to install <code>requests</code> for python3</p> <pre><code>pip install requests </code></pre> <p>installs it for python2.7.</p> <p>How to do this without <code>virtualenv</code> ?</p>
-4
2016-08-13T11:45:57Z
38,943,277
<p>To resolve conflicting installation sites always follow the following steps:</p> <ol> <li><p>To install for python3 use: <code>python3 -m pip install requests</code></p></li> <li><p>For python2 use: <code>python2 -m pip install [any_module]</code></p></li> </ol> <p>This will prevent any conflicts, which I hope is what you are asking.</p>
2
2016-08-14T14:40:37Z
[ "python", "python-3.x", "pip", "virtualenv" ]
Using except to mean "and if that doesn't work"
38,932,530
<p>I fully get the general principle of not catching all exception, as explained in this question, for instance (<a href="http://stackoverflow.com/questions/21553327/why-is-except-pass-a-bad-programming-practice">Why is &quot;except: pass&quot; a bad programming practice?</a>). Yet I have found myself writing this sequence to get the source of a file like object:</p> <pre><code> try: self.doc.source = source.geturl() except: try: self.doc.source = pathlib.Path(os.path.abspath(source.name)).as_uri() except: self.doc.source = None </code></pre> <p>Clearly with some spelunking I could figure out which specific errors to catch with a reasonable degree of confidence. But at is explained in this question (<a href="http://stackoverflow.com/questions/1591319/python-how-can-i-know-which-exceptions-might-be-thrown-from-a-method-call">Python: How can I know which exceptions might be thrown from a method call</a>) you can't ever be quite certain.</p> <p>So is there a better way to do what I am doing here, which is essentially to say: try this and if it doesn't work try this and if that doesn't work do this. Since this is all about setting a single variable, and there is a fallback of setting it to None, it is not obvious to me wherein the peril lies in this construct. </p>
1
2016-08-13T12:03:07Z
38,932,719
<p>Maybe it'd be better to put it into a dedicated function ?</p> <pre><code>def func(source): try: return source.geturl() except Exception: try: return pathlib.Path(os.path.abspath(source.name)).as_uri() except Exception: pass </code></pre> <h2>Notes on swallowing exceptions</h2> <p>Ignoring any kind of exception is not the best pattern : it'd be better to know what call can raise what kind of exception.</p> <p>Even if <code>except ...: pass</code> is bad, that's already what you were doing in your example, and here it's clear that we try another way if it fails.</p> <p>The bad programming practice is basing the error handling on the ability to catch any kind of error. In itself, <code>except: pass</code> is better than <code>except: &lt;lots_of_things_that_wont_raise_again&gt;</code>. </p> <p>However, the first answer in the post you referred to says something very sensible : <code>pass</code> semantically indicates that you won't do <strong>ANYTHING</strong> with the exception, and as you do not store in a variable, it also shows that you'll never be able to access it again (well you could, but still..). As /u/Aprillion/, you'll want to at least log these errors, because otherwise, you <strong>may be swallowing very useful debugging information</strong>, which could make your life (or others) much more difficult at some point.</p> <p>For example, what happens if there's a bug hidden in <code>geturl</code>, that makes it raises exception in normal cases ? It may stay hidden for long, because this exception will be swallowed and never shown anywhere. Good luck to the debugger to find it !</p> <h2>Ways to improve this</h2> <ul> <li>replace <code>except Exception</code> with the exceptions that could be raised</li> <li>check before an attempt if it is going to fail, so that you don't have to catch an exception</li> </ul> <p>Additionally, you probably want to use a logger to save/show these exceptions somewhere, at least in DEBUG mode.</p> <blockquote> <p>Clearly with some spelunking I could figure out which specific errors to catch with a reasonable degree of confidence. But at is explained in this question (Python: How can I know which exceptions might be thrown from a method call) you can't ever be quite certain.</p> </blockquote> <p>Why would that change anything ? If <code>geturl</code> returns specific exception types, you'd only catch these, and you'd want other unexpected errors to bubble up to the interpreter.</p> <p>The big problem with the givn approach is that if <code>geturl</code> is undefined, or not callable, or take more arguments, this error would not make the interpreter crash, even though it is a clear programming error. That's because <code>except:</code> or <code>except Exception:</code> will catch a lof of Python errors, should it be <code>AttributeError</code>, <code>NameError</code>, <code>ImportError</code> or even <code>SyntaxError</code>.</p> <p>To conclude, I really think you'd prefer to replace <code>Exception</code> with the list of exceptions you can catch (and at least send the exceptions to a logger). Note that you can write it as such :</p> <pre><code> try: return source.geturl() except (ExceptionA, ExceptionB, ExceptionC): pass </code></pre>
1
2016-08-13T12:27:18Z
[ "python", "exception" ]
Cannot fully utilise all cpu using multiprocessing.pool.ThreadPool Module
38,932,541
<p>I have a 32 core machine , using multiprocessing.pool.ThreadPool library to generate ThreadPool of Size 32. I have given the sample snippet in my case 2 D Array is huge. </p> <pre><code>from multiprocessing.pool import ThreadPool as Pool import time def f(x): return x[1] if __name__ == '__main__': pool = Pool(32) # start 4 worker processes startTime=time.time() twoDimensionalArraay=[[1,2],[2,3],[3,4],[4,5]] d=pool.map(f,twoDimensionalArraay) print time.time()-startTime </code></pre> <p>After running the process i ran the top command . and saw that out of 32 only one core is busy rest are IDLE</p> <pre><code>Cpu(s): 2.3%us, 1.3%sy, 0.0%ni, 96.4%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 132158392k total, 98751480k used, 33406912k free, 230528k buffers Swap: 2097148k total, 0k used, 2097148k free, 17625092k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 8062 centos 20 0 80.7g 75g 10m S 194.1 59.8 34:49.95 python </code></pre> <p>Can anyone tell me how to fully utilise this cpu so that all the processors are busy </p>
0
2016-08-13T12:04:17Z
38,999,404
<p>I believe the issue is because you're using <code>multiprocessing.pool.ThreadPool</code> as the <code>Pool</code>, not <code>multiprocessing.Pool</code>. The former creates thread-based dummy Process objects that wrap a Python thread, so using it doesn't create separate processes like the latter does.</p> <p>Try using <code>from multiprocessing import Pool</code> instead.</p>
0
2016-08-17T14:25:49Z
[ "python", "multithreading", "threadpool", "python-multithreading", "python-multiprocessing" ]
Multithreading in Scrapy using proxies
38,932,556
<p>I want to crawl about 4 million pages using scrapy. I am using <a href="http://stormproxies.com/" rel="nofollow">storm proxies</a>. Lets say Number of threads allowed on my account is 20. I want to ask - </p> <p>Is multithreading means CONCURRENT_REQUESTS_PER_DOMAIN , in scrapy.</p> <p>or there is an any other way to do that.</p> <p>How can I effectively use those 20 threads</p> <p>NOTE - In case I am not clear with my question , please leave a comment, and I will try to elaborate according to that.</p>
1
2016-08-13T12:06:47Z
38,943,547
<p>Straight out of the docs:</p> <blockquote> <p><code>CONCURRENT_REQUESTS</code>- The maximum number of concurrent (ie. simultaneous) requests that will be performed by the Scrapy downloader.</p> <p><code>CONCURRENT_REQUESTS_PER_DOMAIN</code> - The maximum number of concurrent (ie. simultaneous) requests that will be performed to any single domain.</p> <p><code>CONCURRENT_REQUESTS_PER_IP</code> - The maximum number of concurrent (ie. simultaneous) requests that will be performed to any single IP. If non-zero, the CONCURRENT_REQUESTS_PER_DOMAIN setting is ignored, and this one is used instead. In other words, concurrency limits will be applied per IP, not per domain.</p> </blockquote> <p>Answering your question directly</p> <p>I suspect that that service only let's you scrape up to 20 threads overall, meaning it doesn't care what you are requesting so you should use <code>CONCURRENT_REQUESTS</code> set to 20 maximum (default is 16).</p> <p>Each request is "kind of a thread". It's built on top of <a href="https://twistedmatrix.com/trac/wiki/Documentation" rel="nofollow">Twisted</a>. In the eyes of the proxy service you are using, there's no way to tell the difference so every request will be a proxy thread!</p>
1
2016-08-14T15:11:36Z
[ "python", "multithreading", "web-scraping", "scrapy" ]
Unsure how to run Celery under windows for periodic tasks
38,932,602
<p>I am having difficulty understanding how to run Celery after setting up some scheduled tasks. </p> <p>Firstly, my project directory is structured as follows:</p> <p><a href="http://i.stack.imgur.com/AwGsB.png" rel="nofollow"><img src="http://i.stack.imgur.com/AwGsB.png" alt="enter image description here"></a></p> <p><strong><code>blogpodapi\api\__init__.py</code></strong> contains</p> <pre><code>from tasks import app import celeryconfig </code></pre> <p><strong><code>blogpodapi\api\celeryconfig.py</code></strong> contains</p> <pre><code>from datetime import timedelta # Celery settings CELERY_BROKER_URL = 'redis://localhost:6379/0' BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/1' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' CELERY_IMPORTS = ("api.tasks",) CELERYBEAT_SCHEDULE = { 'write-test': { 'task': 'api.tasks.addrandom', 'schedule': timedelta(seconds=2), 'args': (16000, 42) }, } </code></pre> <p><strong><code>blogpodapi\api\tasks.py</code></strong> contains</p> <pre><code>from __future__ import absolute_import import random from celery import Celery app = Celery('blogpodapi') @app.task def add(x, y): r = x + y print "task arguments: {x}, {y}".format(x=x, y=y) print "task result: {r}".format(r=r) return r @app.task def addrandom(x, *args): # *args are not used, just there to be interchangable with add(x, y) y = random.randint(1,100) print "passing to add(x, y)" return add(x, y) </code></pre> <p><strong><code>blogpodapi\blogpodapi\__init__.py</code></strong> contains</p> <pre><code>from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app # noqa </code></pre> <p><strong><code>blogpodapi\blogpodapi\settings.py</code></strong> contains</p> <pre><code>... # Celery settings CELERY_BROKER_URL = 'redis://localhost:6379/0' BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/1' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' CELERY_IMPORTS = ("api.tasks",) ... </code></pre> <p>I run <code>celery -A blogpodapi worker --loglevel=info</code> in command prompt and get the following:</p> <pre><code>D:\blogpodapi&gt;celery -A blogpodapi worker --loglevel=info -------------- celery@JM v3.1.23 (Cipater) ---- **** ----- --- * *** * -- Windows-8-6.2.9200 -- * - **** --- - ** ---------- [config] - ** ---------- .&gt; app: blogpodapi:0x348a940 - ** ---------- .&gt; transport: redis://localhost:6379/0 - ** ---------- .&gt; results: redis://localhost:6379/1 - *** --- * --- .&gt; concurrency: 2 (prefork) -- ******* ---- --- ***** ----- [queues] -------------- .&gt; celery exchange=celery(direct) key=celery [tasks] . api.tasks.add . api.tasks.addrandom . blogpodapi.celery.debug_task [2016-08-13 13:01:51,108: INFO/MainProcess] Connected to redis://localhost:6379/0 [2016-08-13 13:01:52,122: INFO/MainProcess] mingle: searching for neighbors [2016-08-13 13:01:55,138: INFO/MainProcess] mingle: all alone c:\python27\lib\site-packages\celery\fixups\django.py:265: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! warnings.warn('Using settings.DEBUG leads to a memory leak, never ' [2016-08-13 13:02:00,157: WARNING/MainProcess] c:\python27\lib\site-packages\celery\fixups\django.py:265: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! warnings.warn('Using settings.DEBUG leads to a memory leak, never ' [2016-08-13 13:02:27,790: WARNING/MainProcess] celery@JM ready. </code></pre> <p>I then run <code>celery -A blogpodapi beat</code> in command prompt and get the following:</p> <pre><code>D:\blogpodapi&gt;celery -A blogpodapi beat celery beat v3.1.23 (Cipater) is starting. __ - ... __ - _ Configuration -&gt; . broker -&gt; redis://localhost:6379/0 . loader -&gt; celery.loaders.app.AppLoader . scheduler -&gt; celery.beat.PersistentScheduler . db -&gt; celerybeat-schedule . logfile -&gt; [stderr]@%INFO . maxinterval -&gt; now (0s) [2016-08-13 13:02:51,937: INFO/MainProcess] beat: Starting... </code></pre> <p>For some reason, I can't seem to view my periodic tasks being logged. Is there anything I am doing wrong?</p> <p><strong>UPDATE: here is my celery.py...</strong></p> <pre><code>from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blogpodapi.settings') from django.conf import settings # noqa app = Celery('blogpodapi') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) </code></pre>
0
2016-08-13T12:12:06Z
39,025,232
<p>You need to run celery beat with the celery settings file, rather than</p> <pre><code>celery -A blogpodapi.celery beat --loglevel=INFO </code></pre>
1
2016-08-18T18:33:22Z
[ "python", "django", "windows", "celery", "django-celery" ]
LoginRequiredMixin and get_queryset with django-tables2
38,932,651
<p>I already had a working table built on Django's generic ListView class. But I was missing the ability to sort and I therefore took a look at generating a new table using django-tables2. It was very easy to set up, but I don't know how to implement two important features from my old ListView class; 1) page is only visible to logged in users and 2) filter objects based on user.</p> <p>Here is my old class in <code>views.py</code>:</p> <pre><code>class CarList(LoginRequiredMixin, ListView): model = Car paginate_by = 20 def get_queryset(self): qs = super().get_queryset() return qs if self.request.user.is_staff else qs.filter(bureau=self.request.user.bureau, active = 1) </code></pre> <p>Here is the new django-tables2 function in <code>views.py</code>:</p> <pre><code>def car(request): table = CarTable(Car.objects.all()) RequestConfig(request, paginate={'per_page': 25}).configure(table) return render(request, 'car.html', {'table': table}) </code></pre> <p>and the new <code>tables.py</code>:</p> <pre><code>import django_tables2 as tables from app.models import Feriehus from django.contrib.auth.mixins import LoginRequiredMixin class CarTable(tables.Table): class Meta: model = Car attrs = {'class': 'paleblue'} fields = ('car_id', 'type', 'price', 'year',) </code></pre> <p>How do I implement LoginRequiredMixin (so that the list page is only visible to logged in users) and my old get_queryset (so that user only see the cars they are supposed to see) with django-tables2? Can anyone help. Thank you very much for any assistance!</p>
0
2016-08-13T12:18:09Z
39,006,148
<p>For managing permission to view page you can still use <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#django.contrib.auth.decorators.login_required" rel="nofollow" title="login_required">login_required</a> decorator for your function-based views.</p> <pre><code>from django.contrib.auth.decorators import login_required @login_required def car(request): table = CarTable(Car.objects.all()) RequestConfig(request, paginate={'per_page': 25}).configure(table) return render(request, 'car.html', {'table': table}) </code></pre> <p>And you should put correct filtered queryset when initializing CarTable.</p>
1
2016-08-17T20:57:15Z
[ "python", "django", "python-3.x", "django-views", "django-tables2" ]
send a list of string elements in Django
38,932,686
<p>I am new to Django. This is my Tag model</p> <pre><code>class Tag(models.Model): name=models.CharField(max_length=255) post=models.ManyToManyField('Post') </code></pre> <p>I send a list of all tags name to a template. I want to use it in a javascript code. The problem is that, the list looks like this in javascript</p> <pre><code> [u&amp;#39;c++&amp;#39;, u&amp;#39;c#&amp;#39;, u&amp;#39;php&amp;#39;, u&amp;#39;python&amp;#39;, u&amp;#39;django&amp;#39;] </code></pre> <p>It should be as this </p> <blockquote> <p>['c++', 'c#', 'php', 'python', 'django']</p> </blockquote> <p>I think it's some thing about unicode, but I do not know how to handel it. any help please? </p> <p>excuse my bad english</p>
0
2016-08-13T12:22:35Z
38,932,884
<p>Can you tell me whether the mistake is when you render the first time the view, or is an ajax call?, I think you are doing ajax call, then can you debug the django process, and write here what are the datas that you recover of your database, please?.</p> <p>In addition, can you put the json serializer that you are using please?</p> <p>If you try the next code, you can see the problem is not unicode:</p> <pre><code> import json json.dumps([unicode(i) for i in range(10)]) result: '["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]' </code></pre> <p>try send the above data, and tell us the result please. Thanks!</p>
1
2016-08-13T12:47:01Z
[ "javascript", "python", "django", "unicode" ]
send a list of string elements in Django
38,932,686
<p>I am new to Django. This is my Tag model</p> <pre><code>class Tag(models.Model): name=models.CharField(max_length=255) post=models.ManyToManyField('Post') </code></pre> <p>I send a list of all tags name to a template. I want to use it in a javascript code. The problem is that, the list looks like this in javascript</p> <pre><code> [u&amp;#39;c++&amp;#39;, u&amp;#39;c#&amp;#39;, u&amp;#39;php&amp;#39;, u&amp;#39;python&amp;#39;, u&amp;#39;django&amp;#39;] </code></pre> <p>It should be as this </p> <blockquote> <p>['c++', 'c#', 'php', 'python', 'django']</p> </blockquote> <p>I think it's some thing about unicode, but I do not know how to handel it. any help please? </p> <p>excuse my bad english</p>
0
2016-08-13T12:22:35Z
38,932,941
<p>Use "|safe"</p> <p>something like this in your template.</p> <pre><code>{{ variable_name | safe }} </code></pre>
0
2016-08-13T12:55:19Z
[ "javascript", "python", "django", "unicode" ]
Number of occurence of a name in list
38,932,703
<p>Here is my homework:</p> <blockquote> <p>Write a function, number of occurrences(string, name) which returns the number of occurrences of name in the string of names string.</p> <p>For example, number of occurrences('Alojz, Samo, Peter, Alojz, Franci','Alojz') should return 2.</p> </blockquote> <p>Here is my solution:</p> <pre><code>def number_of_occurence(string,name): m = 0 l = string.split(',') for i in l: if i == name: m+=1 return m </code></pre> <p>This gives wrong answer because it doesn't check every element of a list. Can someone please help to find mistake?</p>
-2
2016-08-13T12:24:56Z
38,932,728
<p>you can use collections.Counter</p> <pre><code>from collections import Counter l = (word.strip() for word in string.split(',')) c = Counter(l) return c[name] </code></pre> <p>edited</p> <p>OR</p> <p>You can use regex:</p> <pre><code>def count_naem(string, name): return len(re.findall("{},".format(name), string+",")) </code></pre>
1
2016-08-13T12:29:09Z
[ "python", "string", "list", "split" ]
Number of occurence of a name in list
38,932,703
<p>Here is my homework:</p> <blockquote> <p>Write a function, number of occurrences(string, name) which returns the number of occurrences of name in the string of names string.</p> <p>For example, number of occurrences('Alojz, Samo, Peter, Alojz, Franci','Alojz') should return 2.</p> </blockquote> <p>Here is my solution:</p> <pre><code>def number_of_occurence(string,name): m = 0 l = string.split(',') for i in l: if i == name: m+=1 return m </code></pre> <p>This gives wrong answer because it doesn't check every element of a list. Can someone please help to find mistake?</p>
-2
2016-08-13T12:24:56Z
38,932,771
<p>If you change your input string to <code>('Alojz,Samo,Peter,Alojz,Franci' , 'Alojz')</code> from <code>('Alojz, Samo, Peter, Alojz, Franci' , 'Alojz')</code>, it would work.</p> <p>You need to remove extra spaces from input string.</p> <p>OR</p> <p>Replace white space from string.</p> <pre><code> def number_of_occurrences(string,name): m = 0 string = string.replace(" ", "") l = string.split(',') for i in l: if i == name: m+=1 return m </code></pre>
0
2016-08-13T12:33:00Z
[ "python", "string", "list", "split" ]
Number of occurence of a name in list
38,932,703
<p>Here is my homework:</p> <blockquote> <p>Write a function, number of occurrences(string, name) which returns the number of occurrences of name in the string of names string.</p> <p>For example, number of occurrences('Alojz, Samo, Peter, Alojz, Franci','Alojz') should return 2.</p> </blockquote> <p>Here is my solution:</p> <pre><code>def number_of_occurence(string,name): m = 0 l = string.split(',') for i in l: if i == name: m+=1 return m </code></pre> <p>This gives wrong answer because it doesn't check every element of a list. Can someone please help to find mistake?</p>
-2
2016-08-13T12:24:56Z
38,932,831
<p>you can just trim out whitespaces after splitting the string.</p> <p>use <code>strip()</code> to strip <code>whitespaces</code> from both sides. you can have <code>whitespaces</code> in both sides.</p> <p>this may help you:</p> <pre><code>def number_of_occurence(string,name): m = 0 l = string.split(',') for i in l: if i.strip() == name: m+=1 return m </code></pre> <p>If you have <code>tabs \t</code> ,<code>newline \n</code> or <code>escape sequence \r</code> in your string, then you can use <code>strip(' \t\n\r)</code> instead of <code>strip()</code>.</p>
0
2016-08-13T12:40:54Z
[ "python", "string", "list", "split" ]
why do these python code examples all call the constructor twice?
38,932,722
<p>I am new to Python, and have been reading some API examples of python scientific libraries. </p> <p>in one library, scikit-learn, the code examples always call the constructor once without arguments, and then later again with all the arguments.</p> <p>Here is an example (see the last line, and the third before last line (clf = linear_....), taken from the documentation of <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDRegressor.html#sklearn.linear_model.SGDRegressor" rel="nofollow"><code>sklearn.linear_model.SGDRegressor</code></a>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from sklearn import linear_model &gt;&gt;&gt; n_samples, n_features = 10, 5 &gt;&gt;&gt; np.random.seed(0) &gt;&gt;&gt; y = np.random.randn(n_samples) &gt;&gt;&gt; X = np.random.randn(n_samples, n_features) &gt;&gt;&gt; clf = linear_model.SGDRegressor() &gt;&gt;&gt; clf.fit(X, y) ... SGDRegressor(alpha=0.0001, average=False, epsilon=0.1, eta0=0.01, fit_intercept=True, l1_ratio=0.15, learning_rate='invscaling', loss='squared_loss', n_iter=5, penalty='l2', power_t=0.25, random_state=None, shuffle=True, verbose=0, warm_start=False) </code></pre> <p>I think I might misunderstand something about Python, because <strong>I don't see why the constructor is called twice?</strong> Is there a reason for this, or is it just a weird way to show all the possible parameters of the constructor?</p>
2
2016-08-13T12:27:32Z
38,932,860
<p>What you are reading is a <a href="https://docs.python.org/3.5/library/doctest.html" rel="nofollow">doctest</a>, a test embedded in a documentation string.</p> <p>Doctests use lines prefixed by <code>&gt;&gt;&gt;</code> to indicate runnable examples, while their output is shown unprefixed.</p> <p>The test runner will match the output of the example with the output written in the documentation test.</p> <p>We can see that by running the example in an IPython interpreter :</p> <pre><code>In [18]: import numpy as np In [19]: np.random.seed(0) In [20]: y = np.random.randn(n_samples) In [21]: X = np.random.randn(n_samples, n_features) In [22]: clf = linear_model.SGDRegressor() In [23]: clf.fit(X, y) Out[23]: SGDRegressor(alpha=0.0001, average=False, epsilon=0.1, eta0=0.01, fit_intercept=True, l1_ratio=0.15, learning_rate='invscaling', loss='squared_loss', n_iter=5, penalty='l2', power_t=0.25, random_state=None, shuffle=True, verbose=0, warm_start=False) </code></pre> <p><strong>TLDR</strong>; The 2nd constructor you see is not in the code, and is just a representation of the output of the <code>fit</code> method.</p>
3
2016-08-13T12:43:55Z
[ "python" ]
Python: Is there a way to execute an or statement before !=
38,932,775
<p>I'm trying to run the following code:</p> <pre><code>while check == False: op = input('Do you want to add, subtract, multiply or divide?') if op != ((('add' or 'subtract') or 'multiply') or 'divide'): print('Please enter a valid operation') else: check = True </code></pre> <p>However, only 'add' is seen as a valid input. Is there a way to execute this code without using nested if statements so that all 4 options are valid?</p>
-1
2016-08-13T12:33:20Z
38,932,808
<p>You have to make each comparison individually, so <code>op != 'add' and op != 'subtract'...</code>.</p>
1
2016-08-13T12:37:58Z
[ "python", "python-3.x", "operand" ]
Python: Is there a way to execute an or statement before !=
38,932,775
<p>I'm trying to run the following code:</p> <pre><code>while check == False: op = input('Do you want to add, subtract, multiply or divide?') if op != ((('add' or 'subtract') or 'multiply') or 'divide'): print('Please enter a valid operation') else: check = True </code></pre> <p>However, only 'add' is seen as a valid input. Is there a way to execute this code without using nested if statements so that all 4 options are valid?</p>
-1
2016-08-13T12:33:20Z
38,932,816
<p>You can do it using the <code>not in</code> operator:</p> <pre><code>if op not in ['add', 'substract', 'multiply', 'divide']: print('Please enter a valid operation') </code></pre> <p><code>in</code> checks for an item in a <em>container</em>, <code>not in</code> just does the opposite.</p> <hr> <p>Or additionally, as @Chris_Rands suggests, replace the list by a set for efficiency:</p> <pre><code>if op not in {'add', 'substract', 'multiply', 'divide'}: print('Please enter a valid operation') </code></pre>
4
2016-08-13T12:39:03Z
[ "python", "python-3.x", "operand" ]
Python: Is there a way to execute an or statement before !=
38,932,775
<p>I'm trying to run the following code:</p> <pre><code>while check == False: op = input('Do you want to add, subtract, multiply or divide?') if op != ((('add' or 'subtract') or 'multiply') or 'divide'): print('Please enter a valid operation') else: check = True </code></pre> <p>However, only 'add' is seen as a valid input. Is there a way to execute this code without using nested if statements so that all 4 options are valid?</p>
-1
2016-08-13T12:33:20Z
38,932,840
<p><code>or</code> operator <em>is</em> executed before <code>!=</code>. What you doing wrong is that you are working with wrong operands:</p> <pre><code>'add' or 'substract' &gt;&gt;&gt; 'add' </code></pre> <p>This means that in the end it will be:</p> <pre><code>if 'op' != 'add': </code></pre> <p>That is exactly what you get. What you need to do is to compare op to each operation you allow:</p> <pre><code>if (op != 'add') and (op != 'substract'): </code></pre> <p>or with python-fu </p> <pre><code>validOperations = ['add, 'substract'] if op not in validOperations: </code></pre>
0
2016-08-13T12:41:48Z
[ "python", "python-3.x", "operand" ]
Python: Is there a way to execute an or statement before !=
38,932,775
<p>I'm trying to run the following code:</p> <pre><code>while check == False: op = input('Do you want to add, subtract, multiply or divide?') if op != ((('add' or 'subtract') or 'multiply') or 'divide'): print('Please enter a valid operation') else: check = True </code></pre> <p>However, only 'add' is seen as a valid input. Is there a way to execute this code without using nested if statements so that all 4 options are valid?</p>
-1
2016-08-13T12:33:20Z
38,932,850
<p>You can use <code>in</code> and a list.</p> <pre><code>while check == False: op = input('Do you want to add, subtract, multiply or divide?') if op not in ['add', 'subtract', 'multiply', 'divide']: print('Please enter a valid operation') else: check = True </code></pre>
0
2016-08-13T12:43:04Z
[ "python", "python-3.x", "operand" ]
Python: Is there a way to execute an or statement before !=
38,932,775
<p>I'm trying to run the following code:</p> <pre><code>while check == False: op = input('Do you want to add, subtract, multiply or divide?') if op != ((('add' or 'subtract') or 'multiply') or 'divide'): print('Please enter a valid operation') else: check = True </code></pre> <p>However, only 'add' is seen as a valid input. Is there a way to execute this code without using nested if statements so that all 4 options are valid?</p>
-1
2016-08-13T12:33:20Z
38,932,867
<p>If you're keen on an answer similar to your code, this works:</p> <pre><code>check = False while check == False: op = raw_input('add/subtract/multiply/divide ? : ') if op != 'add' and op != 'subtract' and op != 'multiply' and op != 'divide': print 'What? Choose wisely.' else: print 'Well chosen.' check = True </code></pre>
0
2016-08-13T12:44:40Z
[ "python", "python-3.x", "operand" ]
Unable to install pyzmail - "Command "python setup.py egg_info" failed with error code 1"
38,932,818
<p>I am trying to install pyzmail for Python 3.4. I am using Visual Studio Community Edition (Windows) but have also tried to install using the command line and get the following dump:</p> <pre><code> ----- Installing 'pyzmail' ----- Collecting pyzmail Using cached pyzmail-1.0.3.tar.gz Collecting distribute (from pyzmail) Using cached distribute-0.7.3.zip Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info\distribute.egg-info writing requirements to pip-egg-info\distribute.egg-info\requires.txt writing top-level names to pip-egg-info\distribute.egg-info\top_level.txt writing dependency_links to pip-egg-info\distribute.egg-info\dependency_links.txt writing pip-egg-info\distribute.egg-info\PKG-INFO Traceback (most recent call last): File "C:\Users\user\AppData\Local\Temp\pip-build-v5zvr2p3\distribute\pkg_resources.py", line 2680, in _dep_map return self.__dep_map File "C:\Users\user\AppData\Local\Temp\pip-build-v5zvr2p3\distribute\pkg_resources.py", line 2525, in __getattr__ raise AttributeError(attr) AttributeError: _DistInfoDistribution__dep_map During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\user\AppData\Local\Temp\pip-build-v5zvr2p3\distribute\setup.py", line 58, in &lt;module&gt; setuptools.setup(**setup_params) File "C:\Python34\lib\distutils\core.py", line 148, in setup dist.run_commands() File "C:\Python34\lib\distutils\dist.py", line 955, in run_commands self.run_command(cmd) File "C:\Python34\lib\distutils\dist.py", line 974, in run_command cmd_obj.run() File "C:\Users\user\AppData\Local\Temp\pip-build-v5zvr2p3\distribute\setuptools\command\egg_info.py", line 177, in run writer = ep.load(installer=installer) File "C:\Users\user\AppData\Local\Temp\pip-build-v5zvr2p3\distribute\pkg_resources.py", line 2241, in load if require: self.require(env, installer) File "C:\Users\user\AppData\Local\Temp\pip-build-v5zvr2p3\distribute\pkg_resources.py", line 2254, in require working_set.resolve(self.dist.requires(self.extras),env,installer))) File "C:\Users\user\AppData\Local\Temp\pip-build-v5zvr2p3\distribute\pkg_resources.py", line 2471, in requires dm = self._dep_map File "C:\Users\user\AppData\Local\Temp\pip-build-v5zvr2p3\distribute\pkg_resources.py", line 2682, in _dep_map self.__dep_map = self._compute_dependencies() File "C:\Users\user\AppData\Local\Temp\pip-build-v5zvr2p3\distribute\pkg_resources.py", line 2699, in _compute_dependencies from _markerlib import compile as compile_marker ImportError: No module named '_markerlib' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\user\AppData\Local\Temp\pip-build-v5zvr2p3\distribute\ ----- Failed to install 'pyzmail' ----- </code></pre> <p>After Googling, I checked I had the ez_setup and setuptools modules installed, which I do. Any help would be much appreciated!</p>
0
2016-08-13T12:39:31Z
38,932,976
<p>I've been able to reproduce your problem, and you're right, using <code>pip install pyzmail</code> wont' be good (pyzmail's installer is buggy) so i've tried this instead:</p> <pre><code>easy_install pyzmail </code></pre> <p>And it succeed, then I could just import pyzmail without any problem.</p>
0
2016-08-13T12:59:08Z
[ "python", "visual-studio", "python-3.x" ]
Django installation picking up wrong path names for migrate after project was copied
38,932,939
<p>I have tried to create a new Django project on my Mac by making a copy of an existing working Django project.</p> <p>I have tried to remove references to the old project paths from the new project but when doing a migrate or createsuperuser I get an error:</p> <pre><code>psycopg2.OperationalError: invalid connection option "init_command" </code></pre> <p>Both projects use a virtual environment called myvenv. The original project used the MySQL database. The new one uses Postgresql which has been installed in the virtual environment.</p> <p>The trace history for the error shows that some of the paths show the correct path name of <code>yhistory-server</code> and some show the path name for the old project from which the new project was copied: <code>veeuserver</code>. I have been through all my code but cannot see where it is picking up the veeuserver path name from.</p> <pre><code>Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py", line 41, in &lt;module&gt; run_module(manage_file, None, '__main__', True) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/runpy.py", line 182, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Users/billnoble/Documents/YHistory-Server/manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 52, in execute return super(Command, self).execute(*args, **options) File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 86, in handle default_username = get_default_username() File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/contrib/auth/management/__init__.py", line 189, in get_default_username auth_app.User._default_manager.get(username=default_username) File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/db/models/manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/db/models/query.py", line 381, in get num = len(clone) File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/db/models/query.py", line 240, in __len__ self._fetch_all() File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/db/models/query.py", line 1074, in _fetch_all self._result_cache = list(self.iterator()) File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/db/models/query.py", line 52, in __iter__ results = compiler.execute_sql() File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 846, in execute_sql cursor = self.connection.cursor() File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/db/backends/base/base.py", line 231, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/db/backends/base/base.py", line 204, in _cursor self.ensure_connection() File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/db/backends/base/base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/django/db/backends/postgresql/base.py", line 175, in get_new_connection connection = Database.connect(**conn_params) File "/Users/billnoble/Documents/VeeUServer/myvenv/lib/python3.4/site-packages/psycopg2/__init__.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) django.db.utils.OperationalError: invalid connection option "init_command" </code></pre>
0
2016-08-13T12:55:11Z
38,935,435
<p>It's still trying to use a postgres database. You should update the <code>DATABASES</code> setting to use django's mysql backend, and you may need to remove all of your migrations as well. After you've removed the migrations and change the <code>DATABASES</code> settings, you should be able to <code>python manage.py migrate</code> and <code>python manage.py makemigrations</code> then finally <code>createsupersuser</code>.</p>
0
2016-08-13T17:49:08Z
[ "python", "django", "postgresql" ]
remove() pop () and del() function
38,932,943
<pre><code>&gt;&gt;&gt; b=[0, 2, 5, 1, 5, 0, 2, 3, 5, 1] &gt;&gt;&gt; c=[0, 2, 5, 1, 5, 0, 2, 3, 5, 1] &gt;&gt;&gt; d=[0, 2, 5, 1, 5, 0, 2, 3, 5, 1] &gt;&gt;&gt; for i in c: print('i:',i) del c[c.index(i)] print(c) i: 0 [2, 5, 1, 5, 0, 2, 3, 5, 1] i: 5 [2, 1, 5, 0, 2, 3, 5, 1] i: 5 [2, 1, 0, 2, 3, 5, 1] i: 2 [1, 0, 2, 3, 5, 1] i: 5 [1, 0, 2, 3, 1] </code></pre> <p>Why the i is disorder and why can't remove all the elements of list ? I try the " d.remove(i) " and " b.pop(b.index(i)) ", I get same result.</p>
0
2016-08-13T12:56:06Z
38,933,100
<p>Whenever you iterate over an object using <code>for</code>, a separate <em>iterator</em> object is created. This object keeps track of which object the <code>for</code> loop's body should use next, and when to stop. When you <code>for</code>-loop over a list, Python creates a list iterator object.</p> <p>But whenever the list is changed, the list iterator doesn't notice. The list doesn't notify it, it's too expensive for the list iterator to check <em>if</em> the list has changed, and even if it would know that the list changed, it has no way of knowing <em>how</em> it changed.</p> <p>How the list iterator deals with the case where the list changes "underneath its feet" is (seemingly) not officially documented, so you can't depend on it. <strong>You should not change the list as you iterate over it</strong>.</p>
3
2016-08-13T13:15:13Z
[ "python" ]
Python 2.7 built from Source on AIX5.3 does not execute for libpython2.7.so
38,933,007
<p>This is on AIX 5.3.</p> <p>When i run Python that I built from source, I get the following error (<strong>This is despite the library being present in the path and that path being present in the LD_LIBRARY_PATH variable.</strong>).</p> <pre><code>a776q /app/appadm/.Mim&gt;python2.7/bin/python exec(): 0509-036 Cannot load program python2.7/bin/python because of the following errors: 0509-150 Dependent module libpython2.7.so could not be loaded. 0509-022 Cannot load module libpython2.7.so. 0509-026 System error: A file or directory in the path name does not exist. a776q /app/appadm/.Mim&gt;export LD_LIBRARY_PATH=/app/appadm/.Mim/python2.7/lib/:$LD_LIBRARY_PATH a776q /app/appadm/.Mim&gt;python2.7/bin/python exec(): 0509-036 Cannot load program python2.7/bin/python because of the following errors: 0509-150 Dependent module libpython2.7.so could not be loaded. 0509-022 Cannot load module libpython2.7.so. 0509-026 System error: A file or directory in the path name does not exist. a776q /app/appadm/.Mim&gt;ls -ltr /app/appadm/.Mim/python2.7/lib/ total 5192 -r-xr-xr-x 1 appadm appadm 2637588 13 ago 07:50 libpython2.7.so drwxr-sr-x 28 appadm appadm 14336 13 ago 07:59 python2.7 drwxr-sr-x 2 appadm appadm 512 13 ago 07:59 pkgconfig a776q /app/appadm/.Mim&gt;ldd python2.7/bin/python python2.7/bin/python needs: /usr/lib/libc.a(shr.o) /usr/lib/libpthreads.a(shr_comm.o) /usr/lib/libpthreads.a(shr_xpg5.o) Cannot find /unix /usr/lib/libcrypt.a(shr.o) </code></pre> <p>I built the python from source using the following</p> <pre><code>export PATH=/usr/bin:/usr/vac/bin export CC=/usr/vac/bin/xlc_r ./configure --with-gcc="xlc_r" --disable-ipv6 AR="ar" --prefix=/app/appadm/.Mim/python2.7 --enable-shared make make install </code></pre> <p>Please guide </p>
0
2016-08-13T13:03:01Z
39,337,361
<p>In the end the issue was that I was setting <strong>LD_LIBRARY_PATH</strong> when i should instead be setting <strong>LIBPATH</strong> on AIX.</p>
0
2016-09-05T20:34:03Z
[ "python", "python-2.7", "aix" ]
What's the proper way to scrape asynchronously and store my results using django celery and redis and store my?
38,933,035
<p>I have been trying to understand what my problem is when I try to scrape using a function I created in my django app. The function goes to a website gathers data and stores it in my database. At first I tried using rq and redis for a while but I kept getting an error message. So someone thought I should try and use celery,and I did. But I see now that rq nor celery is the problem. For I am getting the same error message as I was before. I tired importing it, but still got the error message, and then I thought well maybe If I have the actual function in my tasks.py file that it would make a difference but it didn't. Heres my function I tried to use in my tasks.py</p> <pre><code>import requests from bs4 import BeautifulSoup from src.blog.models import Post import random import re from django.contrib.auth.models import User import os @app.tasks def p_panties(): def swappo(): user_one = ' "Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0" ' user_two = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)" ' user_thr = ' "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko" ' user_for = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:10.0) Gecko/20100101 Firefox/10.0" ' agent_list = [user_one, user_two, user_thr, user_for] a = random.choice(agent_list) return a headers = { "user-agent": swappo(), "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3", "accept-encoding": "gzip,deflate,sdch", "accept-language": "en-US,en;q=0.8", } pan_url = 'http://www.example.org' shtml = requests.get(pan_url, headers=headers) soup = BeautifulSoup(shtml.text, 'html5lib') video_row = soup.find_all('div', {'class': 'post-start'}) name = 'pan videos' if os.getenv('_system_name') == 'OSX': author = User.objects.get(id=2) else: author = User.objects.get(id=3) def youtube_link(url): youtube_page = requests.get(url, headers=headers) soupdata = BeautifulSoup(youtube_page.text, 'html5lib') video_row = soupdata.find_all('p')[0] entries = [{'text': div, } for div in video_row] tubby = str(entries[0]['text']) urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', tubby) cleaned_url = urls[0].replace('?&amp;amp;autoplay=1', '') return cleaned_url def yt_id(code): the_id = code youtube_id = the_id.replace('https://www.youtube.com/embed/', '') return youtube_id def strip_hd(hd, move): str = hd new_hd = str.replace(move, '') return new_hd entries = [{'href': div.a.get('href'), 'text': strip_hd(strip_hd(div.h2.text, '– Official video HD'), '– Oficial video HD').lstrip(), 'embed': youtube_link(div.a.get('href')), #embed 'comments': strip_hd(strip_hd(div.h2.text, '– Official video HD'), '– Oficial video HD').lstrip(), 'src': 'https://i.ytimg.com/vi/' + yt_id(youtube_link(div.a.get('href'))) + '/maxresdefault.jpg', #image 'name': name, 'url': div.a.get('href'), 'author': author, 'video': True } for div in video_row][:13] for entry in entries: post = Post() post.title = entry['text'] title = post.title if not Post.objects.filter(title=title): post.title = entry['text'] post.name = entry['name'] post.url = entry['url'] post.body = entry['comments'] post.image_url = entry['src'] post.video_path = entry['embed'] post.author = entry['author'] post.video = entry['video'] post.status = 'draft' post.save() post.tags.add("video", "Musica") return entries </code></pre> <p>and In the python shell if I run</p> <pre><code>from tasks import * </code></pre> <p>I get </p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/ray/Desktop/myheroku/practice/tasks.py", line 5, in &lt;module&gt; from src.blog.models import Post File "/Users/ray/Desktop/myheroku/practice/src/blog/models.py", line 3, in &lt;module&gt; from taggit.managers import TaggableManager File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/taggit/managers.py", line 7, in &lt;module&gt; from django.contrib.contenttypes.models import ContentType File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/contrib/contenttypes/models.py", line 159, in &lt;module&gt; class ContentType(models.Model): File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/contrib/contenttypes/models.py", line 160, in ContentType app_label = models.CharField(max_length=100) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 1072, in __init__ super(CharField, self).__init__(*args, **kwargs) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 166, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. </code></pre> <p>which is the exact same traceback I got using rq and redis. I found that If I modify the imports like this</p> <pre><code>import requests from bs4 import BeautifulSoup # from src.blog.models import Post import random import re # from django.contrib.auth.models import User import os </code></pre> <p>and modify my function like this</p> <pre><code>@app.task def p_panties(): def swappo(): user_one = ' "Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0" ' user_two = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)" ' user_thr = ' "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko" ' user_for = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:10.0) Gecko/20100101 Firefox/10.0" ' agent_list = [user_one, user_two, user_thr, user_for] a = random.choice(agent_list) return a headers = { "user-agent": swappo(), "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3", "accept-encoding": "gzip,deflate,sdch", "accept-language": "en-US,en;q=0.8", } pan_url = 'http://www.example.org' shtml = requests.get(pan_url, headers=headers) soup = BeautifulSoup(shtml.text, 'html5lib') video_row = soup.find_all('div', {'class': 'post-start'}) name = 'pan videos' # if os.getenv('_system_name') == 'OSX': # author = User.objects.get(id=2) # else: # author = User.objects.get(id=3) def youtube_link(url): youtube_page = requests.get(url, headers=headers) soupdata = BeautifulSoup(youtube_page.text, 'html5lib') video_row = soupdata.find_all('p')[0] entries = [{'text': div, } for div in video_row] tubby = str(entries[0]['text']) urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', tubby) cleaned_url = urls[0].replace('?&amp;amp;autoplay=1', '') return cleaned_url def yt_id(code): the_id = code youtube_id = the_id.replace('https://www.youtube.com/embed/', '') return youtube_id def strip_hd(hd, move): str = hd new_hd = str.replace(move, '') return new_hd entries = [{'href': div.a.get('href'), 'text': strip_hd(strip_hd(div.h2.text, '– Official video HD'), '– Oficial video HD').lstrip(), 'embed': youtube_link(div.a.get('href')), #embed 'comments': strip_hd(strip_hd(div.h2.text, '– Official video HD'), '– Oficial video HD').lstrip(), 'src': 'https://i.ytimg.com/vi/' + yt_id(youtube_link(div.a.get('href'))) + '/maxresdefault.jpg', #image 'name': name, 'url': div.a.get('href'), # 'author': author, 'video': True } for div in video_row][:13] # # for entry in entries: # post = Post() # post.title = entry['text'] # title = post.title # if not Post.objects.filter(title=title): # post.title = entry['text'] # post.name = entry['name'] # post.url = entry['url'] # post.body = entry['comments'] # post.image_url = entry['src'] # post.video_path = entry['embed'] # post.author = entry['author'] # post.video = entry['video'] # post.status = 'draft' # post.save() # post.tags.add("video", "Musica") return entries </code></pre> <p>It works, as this is my output</p> <pre><code>[2016-08-13 08:31:17,222: INFO/MainProcess] Received task: tasks.p_panties[e196c6bf-2b87-4bb2-ae11-452e3c41434f] [2016-08-13 08:31:17,238: INFO/Worker-4] Starting new HTTP connection (1): www.example.org [2016-08-13 08:31:17,582: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:18,314: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:18,870: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:19,476: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:20,089: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:20,711: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:21,218: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:21,727: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:22,372: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:22,785: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:23,375: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:23,983: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:24,396: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:25,003: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:25,621: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:26,029: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:26,446: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:27,261: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:27,671: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:28,082: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:28,694: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:29,311: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:29,922: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:30,535: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:31,154: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:31,765: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:32,387: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:32,992: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:33,611: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:34,030: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:34,635: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:35,041: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:35,659: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:36,278: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:36,886: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:37,496: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:37,913: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:38,564: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:39,143: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:39,754: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:40,409: INFO/Worker-4] Starting new HTTP connection (1): example.org [2016-08-13 08:31:40,992: INFO/MainProcess] Task tasks.p_panties[e196c6bf-2b87-4bb2-ae11-452e3c41434f] succeeded in 23.767645187006565s: [{'src': 'https://i.ytimg.com/vi/3bU-AtShW7Y/maxresdefault.jpg', 'name': 'pan videos', 'url':... </code></pre> <p>It seems some type of authorization is needed to interact with my Post model. I just don't know how. I have been scouring the net for examples on how to scrape and save data into the database. oddly I have come across none. Any advice tips doc's i could read would be a great help.</p> <h1>EDIT</h1> <p>My File structure</p> <pre><code>environ\ |-src\ |-blog\ |-migrations\ |-static\ |-templates\ |-templatetags\ |-__init__.py |-admin.py |-forms.py |-models |-tasks |-urls |-views </code></pre>
4
2016-08-13T13:06:57Z
39,438,939
<h3>You need to setup Django</h3> <p>You seem to be trying to run your task in <strong>Python shell</strong>, it's more likely since your code works when you comment out the <em>Django model</em> part.</p> <p>So the problem is, when running pure <em>python shell</em>, <strong>Django needs to be setup</strong>, in order to run fine. When you run it through <em>manage.py shell</em>, manage.py takes care or setting it up for you, but doing it via a python script, needs manual setup. It's the reason for the missing <em>DJANGO_SETTINGS_MODULE</em> error.</p> <p>You also seem to have used your defined models, to be able to import them into your python script, <strong>you need to add the path to the root folder of your project to the current python path</strong>.</p> <p>Finally, you need to tell django where your <strong>settings file</strong> is (<em>before</em> setting up your django), in your manage.py file, you should have something like this :</p> <pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") </code></pre> <p>Go make it a constant, name it <em>DEFAULT_SETTINGS_MODULE</em>, so you now have:</p> <pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", DEFAULT_SETTINGS_MODULE) </code></pre> <p>Now you need to import the constant into your script and tell django (By setting an env var) where it should look for the settings file. </p> <p>So in all:</p> <pre><code>import sys, os sys.path.insert(0, "/path/to/parent/of/src") # /home/projects/my-crawler from manage import DEFAULT_SETTINGS_MODULE os.environ.setdefault("DJANGO_SETTINGS_MODULE", DEFAULT_SETTINGS_MODULE) import django django.setup() ... The rest of your script ... </code></pre> <p>This way you're setup up just fine. But if you want to run a <em>celery task</em>, you should be using the <code>.delay()</code> or <code>.apply_async()</code>, to be sure the code runs in the background.</p> <p>My own advice is to run python shell using <strong>python manage.py shell</strong>, this case django takes care of everything for you. You just need to import your task and run it.</p> <p>Also about the storage of the results of your scraping task, you can do it both in the database, or in redis, or wherever(a file, another web server ... etc, you can also call another celery task to take care of the results and pass <em>entries</em> to it). </p> <p>Just simply add this to the end of your task's code.</p> <p><strong>Redis</strong></p> <pre><code>from redis import StrictRedis redis = StrictRedis(host='localhost', port=6379, db=0) redis.set("scraping:tasks:results:TASK-ID-HERE", json.dumps(entries)) </code></pre> <p>It's the easiest way to save your results, but you can also use Redis <a href="http://redis.io/topics/data-types">lists/maps</a>.</p> <p><em>Just for reference, it's how you'd do it using lists</em></p> <pre><code>with redis.pipeline() as pipe: for item in entries: pipe.rpush("scraping:tasks:results", json.dumps(item)) pipe.execute() </code></pre> <p>---- <strong>EDIT</strong></p> <p>As I've mentioned, you can define another celery task to take care of the results of the current scraping. so basically you have what follows:</p> <pre><code>@celery_app.task def handle_scraping_results(entries): you do whatever you want with the entries array now </code></pre> <p>And call it at the end of your p_panties task like this:</p> <pre><code>handle_scraping_results.delay(entries) </code></pre> <p>What RabbitMQ does here, is to deliver the message from your <strong>p_panties</strong> task, to <strong>handle_scraping_results</strong> task. You need to notice that these are not simple functions, sharing the same memory address space, they can be in different processes, on different servers ! It's actually what celery is for. You can't call a function that's in a different process. RabbitMQ comes along here and takes a message from process A (having task p_panties), and delivers it to process B (having task handle_result) (message passing is a perfect method for RPC).</p> <p>You can't save anything in rabbitmq, it's not like redis. I entice you to read more on <a href="http://docs.celeryproject.org/en/latest/getting-started/introduction.html">celery</a>, since you seem to have chosen it on wrong basis. Using celery wouldn't have solved your problem, it actually adds to it (since it might be hard to understand in the beginning). If you don't need async processing, just get rid of celery altogether. let your code be a single function and you can easily calla it from a python shell or manage.py shell like how I've described above.</p> <p>--------- <strong>Edit II</strong></p> <p>You want to persist every few hours in the DB. So you have to persist whenever your task finishes somewhere or otherwise the results are lost.</p> <p>You have two options</p> <ol> <li>To persist in the DB whenever your task finishes (This will not be every few hours)</li> <li>To persist in Redis whenever your task finishes, and then every hours or so, you'll have a <a href="http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html">periodic task</a>, to persist them in a django database.</li> </ol> <p>First way is easy, you just uncomment the code you've commented in your own code. Second way needs a little more work.</p> <p>Considering your results are being persisted in redis as I told you, you can have a periodic task like below to handle persisting into DB for you.</p> <pre><code>redis_keys = redis.get("scraping:tasks:results:*") for key in redis_keys: value_of_redis_key = redis.get(key) entries = json.loads(entries) for entry in entries: post = Post() post.title = entry['text'] title = post.title if not Post.objects.filter(title=title): post.title = entry['text'] post.name = entry['name'] post.url = entry['url'] post.body = entry['comments'] post.image_url = entry['src'] post.video_path = entry['embed'] post.author = entry['author'] post.video = entry['video'] post.status = 'draft' post.save() post.tags.add("video", "Musica") </code></pre> <hr>
6
2016-09-11T17:46:19Z
[ "python", "django", "queue", "rabbitmq", "django-celery" ]
how do i properly indent my code on python
38,933,049
<p>I use python 3.5.0 and I'm not sure if my code is properly indented and the reason why I don't know is because I am a new to python starting this in secondary and not sure what's entirely correct. <strong>So is there any way to find out how to indent my code properly?</strong> because many people have said its wrong but not how to fix it. please help thanks </p> <pre><code>#create treasure hunt game #section 1 create menu for user def output_menu(): print(' treasure hunt ') print('------------------') #ask user if they want to play print('would you like to play?') while True: answer = input( 'yes or no?' ) #give option for 'yes they want to' or 'no they dont' if answer == 'no': print('ok goodbye. Press ENTER') #no allow them to quit by pressing enter quit() if answer == 'yes': print('ok! lets play!') #start game break else: print('thats doesnt seem right') #put while loop if response no valid name = input('what is your name') #ask user for name if they wish to play print('Good luck' + name) while True: size = input('What size grid would you like, 8 or 16?') #when done allow user to pick a grid between 8 and 16 if size == 8: create_grid(8,8) import random #put 5 of each chest and bandit all over the grid but in random space banditCount = 5 * xRows / 8 chestcount = 5 * yColumns / 8 if size == 16: create_grid(16,16) import random #put 10 of each chest and bandit all over the grid but in random space banditCount = 10 * xRows / 16 chestcount = 10 * yColumns / 16 break else: #if user picks diiferent grid size put a while loop print('unknown/unsupported gridsize please try again?') </code></pre>
-1
2016-08-13T13:10:00Z
38,933,442
<p>I think you're asking why flow of your program isn't controlled properly which could have to do with indentation, but in this case it doesn't. All of your intends are tabs (which they should be) so there's no problem there. </p> <p>One suggestion I would have is to put a while loop around the section that asks for yes or no input. Right now if the user provides invalid input the game just continues, but I'm guessing you want it to request input again. Same thing with the grid size section. Good luck!</p>
0
2016-08-13T13:54:55Z
[ "python", "pygame" ]
Group by two columns and count the occurrences of each combination in pandas
38,933,071
<p>I have the following data frame:</p> <pre><code>data = pd.DataFrame({'user_id' : ['a1', 'a1', 'a1', 'a2','a2','a2','a3','a3','a3'], 'product_id' : ['p1','p1','p2','p1','p1','p1','p2','p2','p3']}) product_id user_id p1 a1 p1 a1 p2 a1 p1 a2 p1 a2 p1 a2 p2 a3 p2 a3 p3 a3 </code></pre> <p>in real case there might be some other columns as well, but what i need to do is to group by data frame by product_id and user_id columns and count number of each combination and add it as a new column in a new dat frame</p> <p>output should be something like this:</p> <pre><code>user_id product_id count a1 p1 2 a1 p2 1 a2 p1 3 a3 p2 2 a3 p3 1 </code></pre> <p>I have tried the following code:</p> <pre><code>grouped=data.groupby(['user_id','product_id']).count() </code></pre> <p>but the result is:</p> <pre><code>user_id product_id a1 p1 p2 a2 p1 a3 p2 p3 </code></pre> <p>actually the most important thing for me is to have a column names count that has the number of occurrences , i need to use the column later.</p>
1
2016-08-13T13:12:38Z
38,933,130
<p>Maybe this is what you want?</p> <pre><code>&gt;&gt;&gt; data = pd.DataFrame({'user_id' : ['a1', 'a1', 'a1', 'a2','a2','a2','a3','a3','a3'], 'product_id' : ['p1','p1','p2','p1','p1','p1','p2','p2','p3']}) &gt;&gt;&gt; count_series = data.groupby(['user_id', 'product_id']).size() &gt;&gt;&gt; count_series user_id product_id a1 p1 2 p2 1 a2 p1 3 a3 p2 2 p3 1 dtype: int64 &gt;&gt;&gt; new_df = count_series.to_frame(name = 'size').reset_index() &gt;&gt;&gt; new_df user_id product_id size 0 a1 p1 2 1 a1 p2 1 2 a2 p1 3 3 a3 p2 2 4 a3 p3 1 &gt;&gt;&gt; new_df['size'] 0 2 1 1 2 3 3 2 4 1 Name: size, dtype: int64 </code></pre>
2
2016-08-13T13:17:38Z
[ "python", "pandas", "dataframe", "data-analysis" ]
How to create multiple objects with django transactions?
38,933,134
<p>I have to retrieve M objects from a list of Q objects and then maps the M objects to an User. To achieve this, I need to run the code inside a transaction and roll back the DB in the case 1 of M objects are not created:</p> <pre><code>def polls(request, template_name='polls/polls.html'): question_list = random.sample(list(Question.objects.all()), 3) try: with transaction.atomic(): for question in question_list: UserToQuestion.objects.create( user=request.user.id, question=question.id ) except IntegrityError: handle_exception() </code></pre> <p>How I can achieve this? How the exception should be handled? The django documentation doesn't show a real example.</p> <p>Is also possible perform this task during the user registration overriding the save method in way each registered user is mapped to N questions?</p>
0
2016-08-13T13:18:18Z
38,934,168
<p>You need to use <a href="https://simpleisbetterthancomplex.com/tutorial/2016/07/28/how-to-create-django-signals.html" rel="nofollow">django signals</a> while doing user registration. Also you do not need <code>with transaction.atomic():</code> part. You need to use <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#bulk-create" rel="nofollow">bulk create</a></p>
0
2016-08-13T15:20:26Z
[ "python", "django", "django-models", "transactions" ]
How to create multiple objects with django transactions?
38,933,134
<p>I have to retrieve M objects from a list of Q objects and then maps the M objects to an User. To achieve this, I need to run the code inside a transaction and roll back the DB in the case 1 of M objects are not created:</p> <pre><code>def polls(request, template_name='polls/polls.html'): question_list = random.sample(list(Question.objects.all()), 3) try: with transaction.atomic(): for question in question_list: UserToQuestion.objects.create( user=request.user.id, question=question.id ) except IntegrityError: handle_exception() </code></pre> <p>How I can achieve this? How the exception should be handled? The django documentation doesn't show a real example.</p> <p>Is also possible perform this task during the user registration overriding the save method in way each registered user is mapped to N questions?</p>
0
2016-08-13T13:18:18Z
38,942,389
<p>First of all, we create a signal, in order to map the related questions to an user when the user is registered. The signal is triggered from post_save() and the call-back function retrieve N random questions and map it to the user. The signal must be connected, to do it, we use the decorator @receiver. We also need to use a transaction, cause of bulk_create() method.</p> <h1>signals.py</h1> <pre><code>import random from django.dispatch import receiver from django.contrib.auth.models import User from django.db import transaction from django.db.models.signals import post_save from polls.models import Question, UserToQuestion @transaction.atomic @receiver(post_save, sender=User) def sig_user_registered(instance, **kwargs): question_list = random.sample(list(Question.objects.all()), 3) UserToQuestion.objects.bulk_create([ UserToQuestion(user=instance, question=question) for question in question_list ]) </code></pre> <p>The signal must be imported. To do it, we use the method ready().</p> <h1>apps.py</h1> <pre><code>from django.apps import AppConfig class AccountConfig(AppConfig): name = 'account' def ready(self): import account.signals </code></pre> <p>Finally, we load the application</p> <h1>settings.py</h1> <pre><code>INSTALLED_APPS = [ # Django apps # ... # Third-party apps # ... # Your apps 'account.apps.AccountConfig', # ... ] </code></pre>
0
2016-08-14T12:45:36Z
[ "python", "django", "django-models", "transactions" ]
Yahtzee, using a dictionary instead of list of attributes
38,933,138
<p>So my issue is that currently I have code for my yahtzee (I will not post all of the code, but the important stuff is looking like this (and it works):</p> <pre><code>from terminaltables import AsciiTable class Player: def __init__(self,name): self.name=name self.ones=0 self.twos=0 self.threes=0 self.fours=0 self.fives=0 self.sixs=0 self.abovesum=0 self.bonus=0 self.onepair=0 self.twopair=0 self.threepair=0 self.fourpair=0 self.smalladder=0 self.bigladder=0 self.house=0 self.chance=0 self.yatzy=0 self.totalsum=0 def welcome(): global spelarlista spelarlista=[] print("Welcome to the yahtzee game!") players = int(input("How many players: ")) rounds=0 while not players==rounds: player=input("What is your name?: ") rounds=rounds+1 spelarlista.append(Player(player)) table_data = [["Name"] + spelarlista, ['Ones'] + [player.ones for player in spelarlista], ['Twos'] + [player.twos for player in spelarlista], ['Threes'] + [player.threes for player in spelarlista], ['Fours'] + [player.fours for player in spelarlista], ['Fives'] + [player.fives for player in spelarlista], ['Sixs'] + [player.sixs for player in spelarlista]] table = AsciiTable(table_data) table.inner_row_border = True print(table.table) spelarlista[0].add() welcome() </code></pre> <p>The issue right now is that I want to add a dictionary instead of all those self.ones, self.twos etc. If you take a look at my welcome method, you can see that I have <code>[player.ones for player in spelarlista]</code>and I need this to assign the players points, how can I fix so this work for a dictionary instead? The dictionary is neccesary for my next method, add, if you were curious!</p> <p>Thanks in advance!</p>
-4
2016-08-13T13:18:57Z
38,933,527
<pre><code>dict_names = ['ones', 'twos', ..., 'totalsum'] self.dict = {name:0 for name in dict_names} </code></pre> <p>and to access you'd use <code>player.dict['fours']</code> instead if <code>player.fours</code></p>
1
2016-08-13T14:06:13Z
[ "python" ]
spark cannot create LabeledPoint
38,933,198
<p>I always get this error: AnalysisException: u"cannot resolve 'substring(l,1,-1)' due to data type mismatch: argument 1 requires (string or binary) type, however, 'l' is of array type.;"</p> <p>Quite confused because l[0] is a string, and matches arg 1. dataframe has only one column named 'value', which is a comma separated string. And I want to convert this original dataframe to another dataframe of object LabeledPoint, with the first element to be 'label' and the others to be 'features'.</p> <pre><code>from pyspark.mllib.regression import LabeledPoint def parse_points(dataframe): df1=df.select(split(dataframe.value,',').alias('l')) u_label_point=udf(LabeledPoint) df2=df1.select(u_label_point(col('l')[0],col('l')[1:-1])) return df2 parsed_points_df = parse_points(raw_data_df) </code></pre>
-2
2016-08-13T13:25:39Z
38,933,848
<p>I think you what to create LabeledPoint in dataframe. So you can:</p> <p>def parse_points(df):</p> <pre><code>df1=df.select(split(df.value,',').alias('l')) df2=df1.map(lambda seq: LabeledPoint(float(seq[0][0]),seq[0][1:])) # since map applies lambda in each tuple return df2.toDF() #this will convert pipelinedRDD to dataframe </code></pre> <p>parsed_points_df = parse_points(raw_data_df)</p>
0
2016-08-13T14:44:17Z
[ "python", "apache-spark" ]
Pyspark tuple object has no attribute split
38,933,253
<p>I am struggling with a Pyspark assignment. I am required to get a sum of all the viewing numbers per channels. I have 2 sets of files: 1 showing the show and views per show the other showing the shows and what channel they are shown on (can be multiple). </p> <p>I have performed a join operation on the 2 files and the result looks like ..</p> <pre><code>[(u'Surreal_News', (u'BAT', u'11')), (u'Hourly_Sports', (u'CNO', u'79')), (u'Hourly_Sports', (u'CNO', u'3')), </code></pre> <p>I now need to extract the channel as the key and then I think do a reduceByKey to get the sum of views for the channels.</p> <p>I have written this function to extract the chan as key with the views alongside, which I could then use a reduceByKey function to sum the results. However when I try to display results of below function with collect() I get an "AttributeError: 'tuple' object has no attribute 'split'" error</p> <pre><code>def extract_chan_views(show_chan_views): key_value = show_chan_views.split(",") chan_views = key_value[1].split(",") chan = chan_views[0] views = int(chan_views[1]) return (chan,views) </code></pre>
-1
2016-08-13T13:32:48Z
38,933,356
<p><em>Since this is an assignment, I'll try to explain what's going on rather than just doing the answer. Hopefully that will be more helpful!</em></p> <p>This actually isn't anything to do with pySpark; it's just a plain Python issue. Like the error is saying, you're trying to split a tuple, when <code>split</code> is a string operation. Instead access them by index. The object you're passing in:</p> <pre><code>[(u'Surreal_News', (u'BAT', u'11')), (u'Hourly_Sports', (u'CNO', u'79')), (u'Hourly_Sports', (u'CNO', u'3')), </code></pre> <p>is a list of tuples, where the first index is a unicode string and the second is another tuple. You can split them apart like this (I'll annotate each step with comments):</p> <pre><code>for item in your_list: #item = (u'Surreal_News', (u'BAT', u'11')) on iteration one first_index, second_index = item #this will unpack the two indices #now: #first_index = u'Surreal_News' #second_index = (u'BAT', u'11') first_sub_index, second_sub_index = second_index #unpack again #now: #first_sub_index = u'BAT' #second_sub_index = u'11' </code></pre> <p>Note that you never had to split on commas anywhere. Also note that the <code>u'11'</code> is a string, not an integer in your data. It can be converted, as long as you're sure it's never malformed, with <code>int(u'11')</code>. Or if you prefer specifying indices to unpacking, you can do the same thing:</p> <pre><code>first_index, second_index = item </code></pre> <p>is equivalent to:</p> <pre><code>first_index = item[0] second_index = item[1] </code></pre> <p>Also note that this gets more complicated if you are unsure what form the data will take - that is, if sometimes the objects have two items in them, other times three. In that case unpacking and indexing in a generalized way for a loop require a bit more thought.</p>
1
2016-08-13T13:45:14Z
[ "python", "indexing", "pyspark" ]
Running old django app in new virtual environment
38,933,309
<p>I have a django app i was running in python 2.7 and django 1.7.10.However am trying to transition it to django 1.8. I have created a new virtualenv,installed python2.7 and django 1.8 in it and moved the app there.However when i run the server it still reads django 1.7.10.What could be the problem ?</p> <p>console <a href="http://i.stack.imgur.com/0ONKi.png" rel="nofollow">enter image description here</a></p>
0
2016-08-13T13:38:17Z
38,933,515
<p>You do not need to move application for new virtual environment you just need to activate it probably you did not activate new one. Actually also you do not need a new virtual environment for upgrade. Just <code>pip install -U django==1.8</code> it will upgrade your django and then make necessary edits. </p>
0
2016-08-13T14:04:29Z
[ "python", "django" ]
Getting fields of derived class
38,933,342
<p>In Python, I can get a classes fields with <code>__dict__</code>. Here I have two questions:</p> <p>Is there a better way to get fields? Because it only brings fields that has values. How can I get fields that exist only in class itself, not the base class?</p>
0
2016-08-13T13:42:35Z
38,933,395
<p>Check this:</p> <pre><code>from types import FunctionType class A (object): def test(self): pass class B(A): def test12(self): pass print([x for x,y in A.__dict__.items() if type(y) == FunctionType]) print([x for x,y in B.__dict__.items() if type(y) == FunctionType]) </code></pre> <p>For attributes which are not methods, try this:</p> <pre><code>attributes = [x for x,y in B.__dict__.items() if (type(y) != FunctionType and type != callable)] [a for a in attributes if not(a.startswith('__') and a.endswith('__'))] </code></pre>
1
2016-08-13T13:49:40Z
[ "python", "inheritance" ]