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
Python pandas calculate time until value in a column is greater than it is in current period
38,775,814
<p>I have a pandas dataframe in python with several columns and a datetime stamp. I want to create a new column, that calculates the time until output is less than what it is in the current period.</p> <p>My current table looks something like this:</p> <pre><code> datetime output 2014-05-01 01:00:00 ...
4
2016-08-04T19:27:07Z
38,776,571
<pre><code>df = pd.DataFrame([3, 2, 3, 2, 1], index=pd.DatetimeIndex(start='2014-05-01 01:00:00', periods=5, freq='S'), columns=['output']) def f(s): s = s[s &amp; (s.index &gt; s.name)] if s.empty: return np.nan else: return (s.index[0] - s.name).total_seconds() df['secondsuntildecrease']...
2
2016-08-04T20:09:00Z
[ "python", "datetime", "pandas", "time" ]
Python pandas calculate time until value in a column is greater than it is in current period
38,775,814
<p>I have a pandas dataframe in python with several columns and a datetime stamp. I want to create a new column, that calculates the time until output is less than what it is in the current period.</p> <p>My current table looks something like this:</p> <pre><code> datetime output 2014-05-01 01:00:00 ...
4
2016-08-04T19:27:07Z
38,776,600
<p>Here's a one liner</p> <pre><code>df['seconds_until'] = df.apply(lambda x: pd.to_datetime(df.loc[(df['output'] &lt; x['output']) &amp; (df['datetime'] &gt; x['datetime']), 'datetime'].min()) - pd.to_datetime(x[ 'datetime']), axis=1) </code></pre> <p>output</p> <pre><code> datetime output seconds_un...
1
2016-08-04T20:10:55Z
[ "python", "datetime", "pandas", "time" ]
Python pandas calculate time until value in a column is greater than it is in current period
38,775,814
<p>I have a pandas dataframe in python with several columns and a datetime stamp. I want to create a new column, that calculates the time until output is less than what it is in the current period.</p> <p>My current table looks something like this:</p> <pre><code> datetime output 2014-05-01 01:00:00 ...
4
2016-08-04T19:27:07Z
38,777,114
<p>Use numpy's outer subtract to get matrix of differences.</p> <p>Then filter using numpy's triangle function to ensure we only take differences for future times and stay out of the past.</p> <p>Use numpy's where to make sure we don't get all False</p> <p>Finally, take the difference in time.</p> <pre><code>df = p...
2
2016-08-04T20:45:27Z
[ "python", "datetime", "pandas", "time" ]
Django Rest ModelSerializer Find or Create Pattern
38,775,829
<p>I am new to Django. Reading a lot of ways to do the same thing--but not finding the proverbial needle in a haystack. One such needle is a simple "Find or Create" pattern for Django Rest.</p> <p>I am trying to find a simple example of how to go about implementing a find or create pattern for one of my model data usi...
0
2016-08-04T19:27:37Z
38,789,565
<p>You missed one thing, that is, </p> <p><code>fields =("Here will be your models fields. That you want to serialize.")</code> That is after the <code>model = Location</code> in serializer.</p> <p>And you can follow official doc of <code>Django-REST-Framework</code></p>
0
2016-08-05T12:44:12Z
[ "python", "django", "rest", "serialization", "views" ]
Django Rest ModelSerializer Find or Create Pattern
38,775,829
<p>I am new to Django. Reading a lot of ways to do the same thing--but not finding the proverbial needle in a haystack. One such needle is a simple "Find or Create" pattern for Django Rest.</p> <p>I am trying to find a simple example of how to go about implementing a find or create pattern for one of my model data usi...
0
2016-08-04T19:27:37Z
38,808,222
<p>Ok, I figured out the answer to my own question. I am not sure this is the best solution; however, for anyone that needs a solution, here is what I ended up doing:</p> <pre><code>class LocationCreateAPIView(CreateAPIView): serializer_class = LocationCreateSerializer queryset = Location.objects.all() de...
0
2016-08-06T19:57:55Z
[ "python", "django", "rest", "serialization", "views" ]
Getting this error when using tweepy
38,775,997
<p>Python code used to gather tweets and send it to a csv file</p> <p>keeps returning error</p> <p>tweepy.error.RateLimitError: [{'code': 88, 'message': 'Rate limit exceeded'}]</p> <p>trying to get the most recent timeline and send all these tweets to the csv file</p> <p>thanks for any help</p> <pre><code>def get_...
0
2016-08-04T19:37:36Z
38,776,084
<p>Did you tried to add this option on tweepy initialization, so it will wait instead of failing, when rate limit is reached :</p> <pre><code>api = tweepy.API(auth, wait_on_rate_limit=True) </code></pre>
0
2016-08-04T19:43:04Z
[ "python", "csv", "twitter", "tweepy" ]
Getting this error when using tweepy
38,775,997
<p>Python code used to gather tweets and send it to a csv file</p> <p>keeps returning error</p> <p>tweepy.error.RateLimitError: [{'code': 88, 'message': 'Rate limit exceeded'}]</p> <p>trying to get the most recent timeline and send all these tweets to the csv file</p> <p>thanks for any help</p> <pre><code>def get_...
0
2016-08-04T19:37:36Z
38,776,142
<p>Your code is okay, you just reached the Twitter Streaming API limit. It takes about one hour to let you extract tweets again.</p> <p>You should add the <code>wait_on_rate_limit=True</code> option when initializing tweetpy :</p> <pre><code>api = tweepy.API(auth, wait_on_rate_limit=True) </code></pre> <p>I strongly...
0
2016-08-04T19:45:01Z
[ "python", "csv", "twitter", "tweepy" ]
Regex to strip only start of string
38,776,050
<p>I am trying to match phone number using regex by stripping unwanted prefixes like 0, *, # and +</p> <p>e.g.</p> <pre><code>+*#+0#01231340010 </code></pre> <p>should produce, </p> <pre><code>1231340010 </code></pre> <p>I am using python re module</p> <p>I tried following, </p> <pre><code>re.sub(r'[0*#+]', '', ...
2
2016-08-04T19:41:22Z
38,776,099
<p>Add the start of the string check (<code>^</code>) and <code>*</code> quantifier (0 or more occurences):</p> <pre><code>&gt;&gt;&gt; re.sub(r'^[0*#+]*', '', '+*#+0#01231340010') '1231340010' </code></pre> <p>Or, a non-regex approach using <a href="https://docs.python.org/2/library/itertools.html#itertools.dropwhil...
2
2016-08-04T19:43:38Z
[ "python", "regex" ]
Regex to strip only start of string
38,776,050
<p>I am trying to match phone number using regex by stripping unwanted prefixes like 0, *, # and +</p> <p>e.g.</p> <pre><code>+*#+0#01231340010 </code></pre> <p>should produce, </p> <pre><code>1231340010 </code></pre> <p>I am using python re module</p> <p>I tried following, </p> <pre><code>re.sub(r'[0*#+]', '', ...
2
2016-08-04T19:41:22Z
38,776,107
<p>You'll want to use the <code>^</code> to mark only from the beginning and add a <code>*</code> to get any that appear</p> <pre><code>re.sub(r'^[0*#+]*', '', '+*#+0#01231340010') #'1231340010' </code></pre>
1
2016-08-04T19:43:50Z
[ "python", "regex" ]
Regex to strip only start of string
38,776,050
<p>I am trying to match phone number using regex by stripping unwanted prefixes like 0, *, # and +</p> <p>e.g.</p> <pre><code>+*#+0#01231340010 </code></pre> <p>should produce, </p> <pre><code>1231340010 </code></pre> <p>I am using python re module</p> <p>I tried following, </p> <pre><code>re.sub(r'[0*#+]', '', ...
2
2016-08-04T19:41:22Z
38,776,108
<p>You can try with following regex:</p> <pre><code>0*(\d+)$ </code></pre> <p>It will match all digits from the end except leading zeros.</p>
0
2016-08-04T19:43:50Z
[ "python", "regex" ]
Regex to strip only start of string
38,776,050
<p>I am trying to match phone number using regex by stripping unwanted prefixes like 0, *, # and +</p> <p>e.g.</p> <pre><code>+*#+0#01231340010 </code></pre> <p>should produce, </p> <pre><code>1231340010 </code></pre> <p>I am using python re module</p> <p>I tried following, </p> <pre><code>re.sub(r'[0*#+]', '', ...
2
2016-08-04T19:41:22Z
38,776,130
<p>Anchor the regex to the start of the string with '^'. e.g.</p> <pre><code>re.sub(r'^[0*#+]', '', ...) </code></pre>
1
2016-08-04T19:44:37Z
[ "python", "regex" ]
Regex to strip only start of string
38,776,050
<p>I am trying to match phone number using regex by stripping unwanted prefixes like 0, *, # and +</p> <p>e.g.</p> <pre><code>+*#+0#01231340010 </code></pre> <p>should produce, </p> <pre><code>1231340010 </code></pre> <p>I am using python re module</p> <p>I tried following, </p> <pre><code>re.sub(r'[0*#+]', '', ...
2
2016-08-04T19:41:22Z
38,776,948
<p>I believe what you are doing is trying to remove everything before the first digit from <code>[1-9]</code> range in the string. It is <em>safer</em> then to use</p> <pre><code>re.sub(r'^[^1-9]+', '', input) </code></pre> <p>See the <a href="https://regex101.com/r/pM7wJ3/1" rel="nofollow">regex demo</a></p> <p><st...
2
2016-08-04T20:33:29Z
[ "python", "regex" ]
Django REST Framework - Unit Test Error
38,776,096
<p>I am currently writing a unit test for the following <code>get_can_edit</code> function in my serializer:</p> <pre><code>def get_can_edit(self, obj): request = self.context.get('request') user = User.objects.get(username=request.user) return user == obj.admin </code></pre> <p>In my test, I call the fun...
0
2016-08-04T19:43:36Z
38,777,547
<p>It's better to create a base class in order to use it across all your tests. Also that class extend from <code>APIClient</code> DRF class, that supports HTTP methods and you don't need to create <code>Request</code> objects manually.</p> <pre><code>from rest_framework.test import APITestCase class BaseAPITestCase...
2
2016-08-04T21:17:24Z
[ "python", "django", "unit-testing", "django-rest-framework" ]
Django REST Framework - Unit Test Error
38,776,096
<p>I am currently writing a unit test for the following <code>get_can_edit</code> function in my serializer:</p> <pre><code>def get_can_edit(self, obj): request = self.context.get('request') user = User.objects.get(username=request.user) return user == obj.admin </code></pre> <p>In my test, I call the fun...
0
2016-08-04T19:43:36Z
38,796,934
<p>It was solved here: <a href="http://stackoverflow.com/questions/38795394/django-rest-framework-fake-objects-for-unit-tests">Django REST Framework - Fake objects for unit tests</a></p> <p>Basically <code>factory_boy</code> factories needed to be set up differently. Where I defined my factories I had the following li...
1
2016-08-05T19:58:02Z
[ "python", "django", "unit-testing", "django-rest-framework" ]
Python: Redirect stdout and stderr to same file
38,776,104
<p>I would like to redirect the standard error and standard output of a Python script to the same output file. From the terminal I could use </p> <pre><code>$ python myfile.py &amp;&gt; out.txt </code></pre> <p>to do the same task that I want, but I need to do it from the Python script itself. </p> <p>I looked into ...
0
2016-08-04T19:43:48Z
38,776,152
<p>A SyntaxError in a Python file like the above is raised before your program even begins to run: Python files are compiled just like in any other compiled language - if the parser or compiler can't find sense in your Python file, no executable bytecode is generated, therefore the program does not run.</p> <p>The cor...
2
2016-08-04T19:45:30Z
[ "python", "python-2.7", "stderr" ]
Scraping text from multiple web pages in Python
38,776,230
<p>I've been tasked to scrape all the text off of any webpage a certain client of ours hosts. I've managed to write a script that will scrape the text off a single webpage, and you can manually replace the URL in the code each time you want to scrape a different webpage. But obviously this is very inefficient. Ideally,...
1
2016-08-04T19:49:42Z
38,776,270
<p>Try this, 'w' will open the file with a pointer at the the beginning of the file. You want the pointer at the end of the file</p> <p><code>print_to_file = open (data_file_name, 'a' , encoding = 'utf')</code></p> <p>here is all of the different read and write modes for future reference</p> <pre><code>The argument ...
0
2016-08-04T19:52:25Z
[ "python" ]
docker/matplotlib: RuntimeError: Invalid DISPLAY variable
38,776,267
<p>I tried lots of solving method, none of them worked.</p> <p>I tried <code>echo $DISPLAY</code> not working</p> <p>Error Message:</p> <blockquote> <p>Environment:</p> <p>Request Method: GET Request URL: <a href="http://10.231.xx.xx:8000/upload/" rel="nofollow">http://10.231.xx.xx:8000/upload/</a></p> ...
0
2016-08-04T19:52:10Z
38,796,940
<p>The reason is that I <code>import seaborn</code> before I <code>import matplotlib</code>. This caused matplotlib not running in the right place.</p>
0
2016-08-05T19:58:20Z
[ "python", "django", "matplotlib", "docker" ]
Accessings deeply nested dictionary/list elements/values in Python
38,776,350
<p>I've been racking my brain on this problem and the logic needed to step through this output from Google Maps API.</p> <p>Essentially I'm using google maps Distance_Matrix: Here is an example of the returned information from a call of the API for distance/time between two addresses, which I've assigned to variable <...
0
2016-08-04T19:56:42Z
38,776,499
<p>While ugly, it's pretty straightforward:</p> <pre><code>distanceMatrixReturn['rows'][0]['elements'][0]['duration_in_traffic']['distance']['text'] </code></pre> <p>There's not really any <em>cleaner</em> way to do this, unless you want to create <code>namedtuple</code>s or classes, but effectively you're still goin...
0
2016-08-04T20:04:30Z
[ "python", "list", "dictionary", "nested" ]
Accessings deeply nested dictionary/list elements/values in Python
38,776,350
<p>I've been racking my brain on this problem and the logic needed to step through this output from Google Maps API.</p> <p>Essentially I'm using google maps Distance_Matrix: Here is an example of the returned information from a call of the API for distance/time between two addresses, which I've assigned to variable <...
0
2016-08-04T19:56:42Z
38,776,539
<p>If you trying to access <code>2.8 mi</code> from <code>distanceMatrixReturn</code>, you could do this:</p> <pre><code> distanceMatrixReturn['rows'][0]['elements'][0]['duration_in_traffic']['distance']['text'] </code></pre>
0
2016-08-04T20:06:50Z
[ "python", "list", "dictionary", "nested" ]
Accessings deeply nested dictionary/list elements/values in Python
38,776,350
<p>I've been racking my brain on this problem and the logic needed to step through this output from Google Maps API.</p> <p>Essentially I'm using google maps Distance_Matrix: Here is an example of the returned information from a call of the API for distance/time between two addresses, which I've assigned to variable <...
0
2016-08-04T19:56:42Z
38,776,626
<p>Your dictionary is broken, so it's hard to imagine the right path. Anyway.</p> <pre><code>from operator import getitem path = ["rows", 0, "elements", 0, "duration_in_traffic", "distance", "text"] reduce(getitem, path, distanceMatrixReturn) # -&gt; "2.8 mi" </code></pre> <p>On Python 3 you will have to import <c...
1
2016-08-04T20:12:14Z
[ "python", "list", "dictionary", "nested" ]
Trying to plot a simple function - python
38,776,418
<p>I implemented a simple linear regression and I want to try it out by fitting a non linear model</p> <p>specifically I am trying to fit a model for the function <code>y = x^3 + 5</code> for example</p> <p>this is my code</p> <pre><code>import numpy as np import numpy.matlib import matplotlib.pyplot as plt def pre...
2
2016-08-04T20:00:38Z
38,776,823
<p>You forgot to set <code>powerDomain[:,0]=1</code>, that's why your plot goes wrong at <code>0</code>. And yes you are over fitting: look how quickly your plot fires up as soon as you get out of your training domain.</p>
0
2016-08-04T20:24:20Z
[ "python", "numpy", "plot", "machine-learning", "linear-regression" ]
Only call 'git stash pop' if there is anything to pop
38,776,447
<p>I am creating a post-commit script in Python and calling git commands using subprocess.</p> <p>In my script I want to stash all changes before I run some commands and then pop them back. The problem is that if there was nothing to stash, stash pop returns a none-zero error code resulting in an exception in subproce...
1
2016-08-04T20:02:17Z
38,776,533
<p>You can simply try calling <code>git stash show stash@{0}</code>. If this returns successfully, there is something stashed.</p>
2
2016-08-04T20:06:35Z
[ "python", "git" ]
Only call 'git stash pop' if there is anything to pop
38,776,447
<p>I am creating a post-commit script in Python and calling git commands using subprocess.</p> <p>In my script I want to stash all changes before I run some commands and then pop them back. The problem is that if there was nothing to stash, stash pop returns a none-zero error code resulting in an exception in subproce...
1
2016-08-04T20:02:17Z
38,776,587
<p>Don't do that!</p> <p>Suppose that <code>git stash save</code> saves nothing, but there <em>are</em> already some items in the stash. Then, when you're all done, you pop the most recent stash, which <em>is not one you created</em>.</p> <p>What did you just do to the user?</p> <p>One way to do this in shell scrip...
4
2016-08-04T20:10:04Z
[ "python", "git" ]
numpy, choice in loop between concatenating or initializing
38,776,473
<p>I have several arrays that I want to initialize. I want to loop through each array so that the array holds no data, it gets initialized by some method, but if it does hold data, new data gets added to it via <code>numpy.stack</code>. I tried this:</p> <pre><code>a = np.array(0) b = np.array(0) c = np.array(0) wh...
1
2016-08-04T20:03:15Z
38,777,408
<p>Barring the fact that concatenating arrays via stacking is a terrible way to go about doing it, you can need to fix the name binding issue in your code.</p> <p>The problem is that <code>arr</code> references (gets bound to) the arrays one-by-one (as you would expect). Then it gets replaced by <code>np.stack((arr, n...
1
2016-08-04T21:06:10Z
[ "python", "arrays", "numpy" ]
numpy, choice in loop between concatenating or initializing
38,776,473
<p>I have several arrays that I want to initialize. I want to loop through each array so that the array holds no data, it gets initialized by some method, but if it does hold data, new data gets added to it via <code>numpy.stack</code>. I tried this:</p> <pre><code>a = np.array(0) b = np.array(0) c = np.array(0) wh...
1
2016-08-04T20:03:15Z
38,777,423
<pre><code>import numpy as np arrays = [] while True: #data_set_num = infile.readline() #if not data_set_num: break arr = np.array(0) for count in range(3): #new_arr = get_new_array(infile) new_arr = np.array([[count+1,count+2],[count+3,count+4]]) try: arrays.append(n...
1
2016-08-04T21:07:27Z
[ "python", "arrays", "numpy" ]
Django - NEVER update a column when saving
38,776,538
<p>I am trying to use citus data (<a href="https://www.citusdata.com/" rel="nofollow">https://www.citusdata.com/</a>) with Django.</p> <p>Most everything is working so far, except trying to <code>save</code> a model that has already been saved:</p> <pre><code>NotSupportedError: modifying the partition value of rows i...
1
2016-08-04T20:06:46Z
38,776,776
<p>Django does not provide this functionality "out of the box". You could override the <code>save</code> method of your class to set all fields other than your partition field as the value for <code>update_fields</code></p> <pre><code>def save(self, **kwargs): kwargs.setdefault('update_fields', ['field1', 'field2'...
1
2016-08-04T20:21:16Z
[ "python", "django", "citus" ]
Appending lists, arrays, matrices
38,776,613
<p>As a way to learn Python/NumPy I’m programming my SAS IML dissertation of 20 years ago in Python 2.7.11. The method involves monte carlo simulations with multiple loops inside the outer loop. I’ve been successful with a simple example. I’m at the point where I need to accumulate statistics from each iteratio...
1
2016-08-04T20:11:35Z
38,776,902
<p>You have somehow ended up with a list containing a mixture of single-element matrices and ordinary numbers. If you cannot avoid this, then you could always clean up the list for printing using something like the following:</p> <pre><code>def extract_number(x): try: return x.item(0) # returns first it...
1
2016-08-04T20:29:49Z
[ "python", "arrays", "numpy", "matrix" ]
Appending lists, arrays, matrices
38,776,613
<p>As a way to learn Python/NumPy I’m programming my SAS IML dissertation of 20 years ago in Python 2.7.11. The method involves monte carlo simulations with multiple loops inside the outer loop. I’ve been successful with a simple example. I’m at the point where I need to accumulate statistics from each iteratio...
1
2016-08-04T20:11:35Z
38,777,061
<blockquote> <p>I’m a little (or a lot) confused about how and when to use lists, arrays, and matrices and how to convert one to the other</p> </blockquote> <p>Since you tagged it <code>numpy</code>, I am going to assume you mean <code>numpy.array</code> and <code>numpy.matrix</code>. Then, in short, when to use <...
0
2016-08-04T20:41:40Z
[ "python", "arrays", "numpy", "matrix" ]
Appending lists, arrays, matrices
38,776,613
<p>As a way to learn Python/NumPy I’m programming my SAS IML dissertation of 20 years ago in Python 2.7.11. The method involves monte carlo simulations with multiple loops inside the outer loop. I’ve been successful with a simple example. I’m at the point where I need to accumulate statistics from each iteratio...
1
2016-08-04T20:11:35Z
38,780,756
<p>I'm not sure where your <code>matrix</code> comes from, and why the mix of matrix and numbers, but I'll try to process it. </p> <p>For ease of copy-n-paste I'll define <code>matrix</code> (I've loaded numpy as <code>np</code>). I'm working in a Ipython session:</p> <pre><code>In [373]: matrix=np.matrix In [375]:...
0
2016-08-05T03:45:37Z
[ "python", "arrays", "numpy", "matrix" ]
Multi Questioning
38,776,678
<p>i read data from txt. 1st line is the row's labels and from 2nd to end the data.</p> <p>Q1)how i can skip line 1?</p> <p>the data is in form 34,5 and not 34.5 so i can't use float() i try str.replace() with not success</p> <p>Q2) any other idea or suggestion in conversion?</p> <p>Q3)i use python through QGIS as ...
-3
2016-08-04T20:15:41Z
38,776,845
<p>1.</p> <p>Replace:</p> <pre><code>content = f.readlines() for line in content: </code></pre> <p>With:</p> <pre><code>header = f.readline() for line in f: </code></pre> <p>4.</p> <pre><code>zip(X,Y) </code></pre>
0
2016-08-04T20:25:49Z
[ "python", "replace" ]
Multi Questioning
38,776,678
<p>i read data from txt. 1st line is the row's labels and from 2nd to end the data.</p> <p>Q1)how i can skip line 1?</p> <p>the data is in form 34,5 and not 34.5 so i can't use float() i try str.replace() with not success</p> <p>Q2) any other idea or suggestion in conversion?</p> <p>Q3)i use python through QGIS as ...
-3
2016-08-04T20:15:41Z
38,776,931
<h2>Question 1</h2> <p>If you want to skip the first line, you have to read it from the buffer. If you don't need the column headings, just don't store the result into a variable:</p> <pre><code>with open('D:/test_data/CLOUDS1.txt') as f: f.readline() # Reads the first line but does not store the result conte...
1
2016-08-04T20:32:23Z
[ "python", "replace" ]
Can I use one WTForm for multiple @app.route's?
38,776,679
<p>I need to access information from my WTForm in multiple @app.route's in my <code>app.py</code>, so that I can post data visualization for my app. Currently, I have a <code>@app.route(/home/)</code> page and user-entered text on this page is processed by a WTForm, and then passed to <code>@app.route(/results/</code>)...
0
2016-08-04T20:15:46Z
38,906,951
<p>The answer is no, you can't submit one form to multiple routes or share data between multiple routes. My sollution to the problem of needing to share data between multiple routes was to create dynamic URLs. So instead of always going to a <code>results</code> page, it would go to <code>results/1234</code> and this w...
0
2016-08-11T22:16:10Z
[ "python", "iframe", "flask", "flask-wtforms" ]
Python pandas: replace values based on location not index value
38,776,699
<p>Here is my df:</p> <pre><code>In[12]: df = pd.DataFrame(data = list("aabbcc"), columns = ["s"], index=range(11,17)) In[13]: df Out[13]: s 11 a 12 a 13 b 14 b 15 c 16 c </code></pre> <p>Now, replacing values based on index values:</p> <pre><code>In[14]: df.loc[11, "s"] = 'A' In[15]: df Out[15]: s ...
1
2016-08-04T20:16:41Z
38,776,838
<p>You can use get_loc to get the location of the column and pass that to iloc:</p> <pre><code>df.iloc[1, df.columns.get_loc('s')] = 'B' df Out: s 11 a 12 B 13 b 14 b 15 c 16 c </code></pre> <p>Or the other way around:</p> <pre><code>df.loc[df.index[1], 's'] = 'B' </code></pre>
2
2016-08-04T20:25:19Z
[ "python", "pandas" ]
Embedding python to php then php to html
38,776,757
<p>So I've searched all over this site for a way to combine python into my html, but the only help I could find was to use a framework made for python to use primarily python code for a web application. This is not what I want. So upon further research I found that php embeds nicely into html. I then found another s...
-1
2016-08-04T20:20:02Z
38,776,960
<p>a php is effectively an html file that can run code</p> <p>index.html</p> <pre><code>&lt;head&gt;&lt;title&gt;Hello&lt;/title&gt;&lt;/head&gt; &lt;body&gt; Hello HTML WORLD!!! &lt;/body&gt; </code></pre> <p>you can take this <code>index.html</code> and rename it to <code>index.php</code> it is now a php file but ...
0
2016-08-04T20:34:10Z
[ "php", "python", "html" ]
Android- How to save a image in folder of choice
38,776,767
<p>I am writing a app for android that saves a picture of the app, I've had trouble in finding the image after its been saved, so I researched and heard that its saved under root access, now my question is: how should I go ahead in saving it somewhere not under root access? for example: my file manager have the followi...
1
2016-08-04T20:20:40Z
38,838,560
<p>Use:</p> <pre><code>from kivy.app import platform if platform() == 'android': DATA_FOLDER = os.getenv('EXTERNAL_STORAGE') or os.path.expanduser("~") #create your own sub folders and files... </code></pre> <p>to get to the root of the external drive.</p>
1
2016-08-08T21:09:09Z
[ "android", "python", "kivy" ]
Android- How to save a image in folder of choice
38,776,767
<p>I am writing a app for android that saves a picture of the app, I've had trouble in finding the image after its been saved, so I researched and heard that its saved under root access, now my question is: how should I go ahead in saving it somewhere not under root access? for example: my file manager have the followi...
1
2016-08-04T20:20:40Z
38,838,653
<p><a href="https://developer.android.com/training/camera/photobasics.html#TaskPath" rel="nofollow">https://developer.android.com/training/camera/photobasics.html#TaskPath</a></p> <p>check out the "Save the Full-Size Photo" part.</p>
1
2016-08-08T21:15:31Z
[ "android", "python", "kivy" ]
Pythonic way to pass optional parameter by variable name
38,776,860
<p>I'm sorry if the question is a bit unclear, I'm not sure how to phrase it.</p> <p>I'm working with a package that has a function with a number of optional parameters. Say there are three parameters: x, y, z. I will always pass the same value, just to a different parameter. So I could do this:</p> <pre><code>if set...
2
2016-08-04T20:27:19Z
38,776,894
<p>I would build a dictionary with <code>setting</code> as the key and the static value as the value. This way, you don't have to do that awkward switching.</p> <p>For example:</p> <pre><code>setting = 'x' kwargs = {setting: 1} package.someFunction(**kwargs) </code></pre> <p>Just change the <code>setting = 'x'</code...
5
2016-08-04T20:29:21Z
[ "python" ]
Editing python script/executable
38,776,882
<p>I have a working python program that sets IP/gateway/broadcast addresses for different devices using pySerial.</p> <p>The basic idea would be that the user enters the addresses themselves and the program does the rest</p> <pre><code>IP = 'x.x.x.x' broadcast = 'x.x.x.x' gateway = 'x.x.x.x' </code></pre> <p>My init...
0
2016-08-04T20:28:29Z
38,776,922
<p>There are several possible ways to do this, although the user will still need Python in some form to run your application. Having said that, if you package your application with a tool such as <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a>, it will package a minimal Python interpreter so that the user do...
1
2016-08-04T20:31:56Z
[ "python", "serial-port", "executable", "py2exe", "pyserial" ]
Comparing Edges to determine if a difference in an angle requires clockwise or counter clockwise rotation to match
38,776,955
<p>In python, I have a script that I can use to determine the difference in angles between two edges:</p> <pre><code>#python import math def uDirection (v1, v2): return (v2[0]-v1[0], v2[1]-v1[1]) def dotUV (u1, u2): return (u1[0]*u2[0] + u1[1]*u2[1]) def uLength (u): return math.sqrt(dotUV(u,u)) def uN...
0
2016-08-04T20:33:55Z
38,777,187
<p>Let the two vectors <code>e1</code> and <code>e2</code>. I assume you seek to rotate <em>the smalles angle</em> between these two:</p> <pre><code>if e1[0] * e2[1] - e1[0] * e2[1] &lt; 0: pass # Rotate CW else pass # Rotate CCW </code></pre> <p>Should do the trick.</p> <p>If you intend to rotate <code>e2</...
0
2016-08-04T20:51:35Z
[ "python", "rotation" ]
Comparing Edges to determine if a difference in an angle requires clockwise or counter clockwise rotation to match
38,776,955
<p>In python, I have a script that I can use to determine the difference in angles between two edges:</p> <pre><code>#python import math def uDirection (v1, v2): return (v2[0]-v1[0], v2[1]-v1[1]) def dotUV (u1, u2): return (u1[0]*u2[0] + u1[1]*u2[1]) def uLength (u): return math.sqrt(dotUV(u,u)) def uN...
0
2016-08-04T20:33:55Z
38,777,209
<p>The reason why you get a <code>45</code> both ways is because the <code>cos</code> function is an <em>even function</em>, so both negative and positive dot products of the same magnitude will map to the same value. </p> <p>You could use the <em>arcsin</em> of the <code>dotProduct</code> to determine the sign of the...
0
2016-08-04T20:53:05Z
[ "python", "rotation" ]
How do you replace HTML tags with commas (for CSV) in Python?
38,776,968
<p>I have an extremely long HTML file that I cannot modify but would like to parse for CSV output. Imagine the following code repeated hundreds of times all on the same line. I realize this would be much simpler if there were line breaks, but I have no control over how the file is created. You should also know that the...
0
2016-08-04T20:34:27Z
38,883,925
<pre><code>from bs4 import BeautifulSoup html_doc = """ &lt;tr id="link"&gt; &lt;td&gt;&lt;a href="https://www.somewebsite.com" target="_target"&gt;Title&lt;/a&gt;&lt;/td&gt; &lt;td&gt;Value 1&lt;/td&gt;&lt;td style="width:20ch"&gt;Value 2&lt;/td&gt; &lt;td&gt;&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;td&gt;Value 3&lt;/td&g...
0
2016-08-10T21:32:39Z
[ "python", "csv", "parsing", "html-parsing", "tokenize" ]
Python: verify if elements of list exist in file and print if they dont
38,777,037
<p>I have list which is output of a function, I want to verify if elements of array are in the file (text file containing server names) and I want to print only those servers which are not in the file.</p> <p>Thinking of something on these lines:</p> <pre><code>host_list = ['abc.server.com', 'xyz.server.com'] sfile =...
-1
2016-08-04T20:39:31Z
38,777,095
<p>Here's a simple way to do what you are trying to do:</p> <pre><code>host_list = ['abc.server.com', 'xyz.server.com'] sfile = open("slist.txt","r") hosts_in_file = set() for line in sfile: for server in line.strip().split(): hosts_in_file.add(server) print [host for host in host_list if host not in hosts_in_...
1
2016-08-04T20:44:07Z
[ "python" ]
Creating a turtle program that does commands based upon the button pressed
38,777,134
<p>I haven't been able to find anything online for this but I need to create a program that: </p> <ul> <li><p>If the left button is pressed, the turtle should move to that location and draw a small square.</p></li> <li><p>If the right button is pressed, the turtle should move that that location and draw a small circle...
0
2016-08-04T20:46:55Z
38,779,108
<p>Below is my guess as to what you and your code snippets describe. Note that I changed the circle and square functions from the left and right keyboard buttons to the left and right mouse buttons which seemed to make more sense in the context of, "move to that location":</p> <pre><code>import turtle import random ...
0
2016-08-04T23:51:16Z
[ "python", "command", "turtle-graphics" ]
Cumulative sum of a partition in PySpark
38,777,174
<p>I need to create a column with a group number that increments based on the values in the colmn TRUE. I can partition by ID so I'm thinking this would reset the increment when the ID changes, which I want to do. Within ID, I want to increment the group number whenever TRUE is not equal to 1. When TRUE = 1 I want it t...
0
2016-08-04T20:50:35Z
38,788,608
<p>Never use restricted keywords as column names. Even if this may work in some systems it is error prone, may stop working if you change parser and generally speaking is really bad practice. <code>TRUE</code> is boolean literal and will be never equal to <code>0</code> (with implicit cast it is equivalent to <code>TRU...
0
2016-08-05T11:53:39Z
[ "python", "sql", "apache-spark", "pyspark", "apache-spark-sql" ]
Anaconda python executes a python file in directory when I import pandas
38,777,175
<p>This is a head scratcher. I have a directory with Ipython notebooks and python code. Somehow when I try to import pandas one of the pandas files attempts to execute, the execution causes the import to bomb.</p> <pre><code>[path]$ python Python 3.5.2 |Anaconda custom (64-bit)| (default, Jul 2 2016, 17:53:06) [GCC...
0
2016-08-04T20:50:42Z
38,833,926
<p>This appears to be a symptom of how python works, how paths in python work, and how imports in python work. The short answer is that you can not have a file in your python path that has the same name as a python file called from a library that you import. This creates a name collision and because the current direc...
0
2016-08-08T16:09:10Z
[ "python", "ipython", "anaconda", "jupyter" ]
Django additional views in Django admin - URL trouble
38,777,196
<p>I'm adding an additional view to <code>django-admin</code>. My goal is to override the <code>change_form</code> to make the fields read only and add some custom forms to it for working with the <code>foreign_key</code> objects, and to also have an edit page which would be the additional view I'm creating.</p> <p>I ...
0
2016-08-04T20:52:08Z
38,777,551
<p>Your url pattern does not capture any values, so does not have anything to pass onto the view method. You need to use capturing parentheses:</p> <pre><code> r'(\d+)/review/$', </code></pre> <p>although usually you would use a named group to send the value as a keyword argument:</p> <pre><code>r'(?P&lt;id&gt;\d+)...
0
2016-08-04T21:17:45Z
[ "python", "django", "django-admin", "django-urls", "django-1.9" ]
CSV database style changes in python like switching data into a file
38,777,205
<p>I'm having troubles coming up with a way to change data of a certain row in a csv file to the new value assigned through the script itself.</p> <p>I hope you guys could help me with this problem. Here is my code:</p> <pre><code>import csv def Toevoeging_methode_plus(key_to_find, definition): if key_to_find in...
0
2016-08-04T20:52:38Z
38,778,071
<p>I made a csv file variabelen.csv from the link you provided(you need to convert to your Excel-File to csv file).</p> <pre><code>Product,Aantal 233,60 2234,1 </code></pre> <p>I added comma delimiter in your <code>with open</code> block:</p> <pre><code>with open("variabelen.csv") as csvfile: reader = csv.DictRe...
0
2016-08-04T21:56:38Z
[ "python", "csv", "writing" ]
Read in a dataframe and convert some columns
38,777,235
<p>I would like to read in a dataframe using read_csv. For example:</p> <pre><code>data = pd.read_csv("foo.txt", sep=' ', header=None, dtype={0:np.uint32, 1:np.uint32, 2:np.str}) </code></pre> <p>Except foo.txt has the awkward property that the first two columns are in hex. E.g</p> <pre><code>ff462 44e44 house </co...
0
2016-08-04T20:54:46Z
38,777,371
<p>Apparently this works (<a href="http://stackoverflow.com/questions/31528340/converting-a-string-of-numbers-to-hex-and-back-to-dec-pandas-python">cf.here</a>):</p> <pre><code>data['1'] = data.1.apply(lambda x: int(x,base=0) ) data['1'] = data['1'].astype(np.uint32) </code></pre>
1
2016-08-04T21:02:33Z
[ "python", "pandas" ]
Read in a dataframe and convert some columns
38,777,235
<p>I would like to read in a dataframe using read_csv. For example:</p> <pre><code>data = pd.read_csv("foo.txt", sep=' ', header=None, dtype={0:np.uint32, 1:np.uint32, 2:np.str}) </code></pre> <p>Except foo.txt has the awkward property that the first two columns are in hex. E.g</p> <pre><code>ff462 44e44 house </co...
0
2016-08-04T20:54:46Z
38,777,373
<p>You can read in the data as a string and then convert it...</p> <pre><code>data = pd.read_csv("foo.txt", sep=' ', header=None, dtype=str) data.iloc[:, [0, 1]] = df.iloc[:, [0, 1]].apply(lambda x: int(x, base=16)).astype(np.uint32) </code></pre>
1
2016-08-04T21:02:44Z
[ "python", "pandas" ]
PRAW limiting Reddit bot per thread
38,777,303
<p>I created a Reddit bot with PRAW which automatically responds with a message when it finds key words. The issue is that people are spamming the key words now and one of the mods told me to limit the bot to reply to one comment per thread. I'm not a master programmer but I believe the bot only scans the 25 most recen...
0
2016-08-04T20:58:15Z
38,922,147
<p>There are multiple solutions to your problem. Keeping a database with threads that you already responded would be most clean, or in this case since it's very little information, you could just save thread ids to file.</p> <p>This however would be problematic if this database/file would get lost, or bot post would b...
0
2016-08-12T16:00:07Z
[ "python", "limit", "bots", "reddit", "praw" ]
Use the same else block for nested try blocks in python
38,777,355
<p>I'm fitting a function to some data and some initial parameter values cause an overflow error. I want to catch it in my code, give it new initial parameters, and try again. My solution is to nest try except blocks.</p> <pre><code>try: foo(args1) except: args2 = make_new_args() try: foo(args2) ...
0
2016-08-04T21:01:05Z
38,777,493
<p>This looks a lot like some retry logic with modifications to the arguments; you could try this:</p> <pre><code>MAX_RETRIES = 2 for retries in range(MAX_RETRIES): try: foo(args) except: args = make_new_args() else: process_data() break if retries + 1 &gt;= MAX_RETRIES...
0
2016-08-04T21:12:36Z
[ "python", "python-3.x", "error-handling" ]
Jupyterhub Notebook doesn't recognize Python modules
38,777,378
<p>I'm trying to run Jupyterhub on a Ubuntu 14.04 VM. I've successfully done this before on a similar Amazon EC2 instance, but for some reason it's not cooperating with me here.</p> <p>I've installed both the Python 27 and Python 35 Anaconda packages, so I expect to be able to access libraries like <code>matplotlib</c...
0
2016-08-04T21:03:06Z
38,796,742
<p>Fixed myself. I needed to specify a different Python instance in a generated <code>kernel.json</code> file.</p> <p>To generate the <code>kernel.json</code> file:</p> <pre><code>sudo anaconda3/bin/ipython kernel install </code></pre> <p>Then edit it:</p> <pre><code>sudo nano /usr/local/share/jupyter/kernels/pytho...
0
2016-08-05T19:43:36Z
[ "python", "matplotlib", "python-import", "jupyter", "jupyterhub" ]
Python Pillow not working on raspbian
38,777,429
<p>I installed Pillow 3.3.0 using easy_install (pip install results in the same behavior). After succesfull installation I get an "illegal instruction" error when I import the Image class.</p> <p>The output of the installation:</p> <pre><code>root@rasp01:/data/server# easy_install Pillow Searching for Pillow Reading ...
1
2016-08-04T21:08:02Z
38,777,620
<p>You could try </p> <pre><code> from PIL import * </code></pre> <p>and just import everything from the library instead</p> <p>or if that doesn't work try</p> <pre><code> import PIL </code></pre>
3
2016-08-04T21:23:35Z
[ "python", "raspberry-pi", "raspbian", "pillow", "easy-install" ]
Python Pillow not working on raspbian
38,777,429
<p>I installed Pillow 3.3.0 using easy_install (pip install results in the same behavior). After succesfull installation I get an "illegal instruction" error when I import the Image class.</p> <p>The output of the installation:</p> <pre><code>root@rasp01:/data/server# easy_install Pillow Searching for Pillow Reading ...
1
2016-08-04T21:08:02Z
38,803,939
<p>Raspberry Pi uses ARM, PILLOW that is installed is not compatible, hence the instruction is illegal.</p> <p>Try installing PILLOW with <code>sudo apt-get</code> command</p>
0
2016-08-06T11:45:12Z
[ "python", "raspberry-pi", "raspbian", "pillow", "easy-install" ]
Python Pillow not working on raspbian
38,777,429
<p>I installed Pillow 3.3.0 using easy_install (pip install results in the same behavior). After succesfull installation I get an "illegal instruction" error when I import the Image class.</p> <p>The output of the installation:</p> <pre><code>root@rasp01:/data/server# easy_install Pillow Searching for Pillow Reading ...
1
2016-08-04T21:08:02Z
38,818,433
<p>Thanks for your replies. Eventually I installed PIL using:</p> <pre><code> sudo apt-get install python-imaging </code></pre> <p>This installed PIL in the right architecture an is working.</p>
0
2016-08-07T20:50:36Z
[ "python", "raspberry-pi", "raspbian", "pillow", "easy-install" ]
Syntax error on if in Python
38,777,599
<pre><code>petname = ['Zophie', 'Pooka', 'Fat-tail'];\ print ('what is your pets name?');\ name = input();\ if name not in petname:;\ </code></pre> <p>i get syntax error for my code above? can someone please help</p>
-5
2016-08-04T21:21:39Z
38,777,710
<p>You need to do it this way, if i am correct to assume this is your purpose:</p> <pre><code>petname = ['Zophie', 'Pooka', 'Fat-tail'] print ('What is your pets name?') name = input() if name not in petname: print ('Your pet is not in the list') else: print ('Your pet is in the list') </code></pre>
1
2016-08-04T21:30:20Z
[ "python" ]
Copying and modifying a list of tuples
38,777,623
<p>I'm attempting to rebuild a SQL table by creating a list of tuples from a query, creating a new list of tuples with the data I need changed, then inserting that list of tuples back into SQL. I seem to have everything down except for one part thing. When I recreate the list, there could be any number of columns in th...
0
2016-08-04T21:23:45Z
38,777,694
<p>You have the slice of the tuple returning a tuple, which gets inserted in another tuple before <em>appending</em>. You should instead add the new value as a tuple to the slice. </p> <p>I have replaced the <em>for loop</em> with a <em>list comprehension</em> and used <code>enumerate</code> starting at <code>1</code...
0
2016-08-04T21:29:00Z
[ "python" ]
How to create a UNIX timestamp for every minute in Python
38,777,630
<p>I want to create a UNIX timestamp for the date <code>2014-10-31</code> for every minute of the day. I have got a timestamp for the date but not for every minute -</p> <pre><code>import datetime date = '2014-10-31' t_stamp = int(time.mktime(datetime.datetime.strptime(date, "%Y-%m-%d").timetuple())) print t_stamp </c...
0
2016-08-04T21:23:54Z
38,777,719
<pre><code>t_stamp = int(time.mktime(datetime.datetime.strptime(date, "%Y-%m-%d").timetuple())) for h in range(24): 24 hours for i in range(60): # 60 minutes print t_stamp t_stamp += 60 # one minute </code></pre>
1
2016-08-04T21:31:12Z
[ "python", "datetime", "timestamp" ]
How to create a UNIX timestamp for every minute in Python
38,777,630
<p>I want to create a UNIX timestamp for the date <code>2014-10-31</code> for every minute of the day. I have got a timestamp for the date but not for every minute -</p> <pre><code>import datetime date = '2014-10-31' t_stamp = int(time.mktime(datetime.datetime.strptime(date, "%Y-%m-%d").timetuple())) print t_stamp </c...
0
2016-08-04T21:23:54Z
38,778,057
<p>Hope this helps. </p> <p><em>Storing timestamps in a database is simply redundant unless the required values cannot be corelated i.e. billing transactions' time. Here, your required range values have a start and end time, and you know them. You also know the interval between each value is 1 minute.</em> </p> <pre>...
-1
2016-08-04T21:55:37Z
[ "python", "datetime", "timestamp" ]
TA-Lib Python Wrapper only length-1 arrays error
38,777,651
<p><strong>Code:</strong></p> <pre><code> def macd(prices): print "Running MACD" prices = np.asarray(prices) print prices macd, macdsignal, macdhist = MACD(prices, fastperiod=12, slowperiod=26, signalperiod=9) print "MACD "+macd </code></pre> <p><strong>Explanation:</strong> ...
0
2016-08-04T21:25:38Z
38,778,091
<p>I was importing the talib module like so, just like in <a href="https://mrjbq7.github.io/ta-lib/func.html" rel="nofollow">TA-Libs website</a>:</p> <pre><code>from talib.abstract import MACD </code></pre> <p>However, this is frowned upon in the community and today I found out why. One modules namespace was clobberi...
0
2016-08-04T21:58:50Z
[ "python", "python-2.7", "ta-lib" ]
How does Mac OS reference relate to python usage?
38,777,654
<p>I'm trying to learn python and the way that it interacts with OS X's APIs, particularly for PDF. I have the following script, gleaned from the internet for getting the number of pages in a PDF:</p> <pre><code>#!/usr/bin/python import sys from CoreGraphics import * pdfnum=0 def pageCount(pdfPath): "Return the...
1
2016-08-04T21:25:54Z
38,870,599
<p>It seems that the only place you can find these terms is inside: /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/CoreGraphics/<strong>init</strong>.py</p> <p>This file lists all the method names used by python, and what the OS X reference name is. The trouble is that the python list is ol...
0
2016-08-10T10:19:45Z
[ "python", "osx", "pdf" ]
How to check if a specific string is in a variable that byte-variable
38,777,714
<p>I have a variable that is received on a socket in <em>byte</em> form and I need to check whether a specific string is contained.</p> <p>For instance:</p> <pre><code>&gt;&gt;&gt; a="foo\r\nbar" &gt;&gt;&gt; print(str(a.find("\r\n"))) 3 </code></pre> <p>This works fine, but if the first variable <code>a</code> is c...
0
2016-08-04T21:30:53Z
38,777,780
<p>You have to <a href="https://docs.python.org/2/library/codecs.html" rel="nofollow">decode</a> your bytes object into a string since casting it won't work.<br> Try the following code:</p> <pre><code>&gt;&gt;&gt; a=b"foo\r\nbar" &gt;&gt;&gt; print(a.decode("utf-8").find("\r\n")) 3 </code></pre> <p>Your varibale <cod...
1
2016-08-04T21:36:14Z
[ "python", "string", "casting" ]
How to check if a specific string is in a variable that byte-variable
38,777,714
<p>I have a variable that is received on a socket in <em>byte</em> form and I need to check whether a specific string is contained.</p> <p>For instance:</p> <pre><code>&gt;&gt;&gt; a="foo\r\nbar" &gt;&gt;&gt; print(str(a.find("\r\n"))) 3 </code></pre> <p>This works fine, but if the first variable <code>a</code> is c...
0
2016-08-04T21:30:53Z
38,777,804
<p>Search for a byte string too (as the error suggests!):</p> <pre><code>&gt;&gt;&gt; a=b"foo\r\nbar" &gt;&gt;&gt; print(str(a.find(b"\r\n"))) 3 </code></pre>
1
2016-08-04T21:38:06Z
[ "python", "string", "casting" ]
How to check if a specific string is in a variable that byte-variable
38,777,714
<p>I have a variable that is received on a socket in <em>byte</em> form and I need to check whether a specific string is contained.</p> <p>For instance:</p> <pre><code>&gt;&gt;&gt; a="foo\r\nbar" &gt;&gt;&gt; print(str(a.find("\r\n"))) 3 </code></pre> <p>This works fine, but if the first variable <code>a</code> is c...
0
2016-08-04T21:30:53Z
38,777,812
<pre><code>&gt;&gt;&gt; a = b"foo\r\nbar" &gt;&gt;&gt; print(a.find(b"\r\n")) 3 </code></pre> <p>or you can decode the string as TheGirrafish said</p>
1
2016-08-04T21:38:20Z
[ "python", "string", "casting" ]
Python Social Auth - - Django - find url names
38,777,751
<p>So, when using python social auth with django, one has to point the login social button to different urls, depending on the social network. This is an example:</p> <pre><code>&lt;form action="{% url 'social:begin' 'facebook' %}"&gt; &lt;button type="submit" class="btn btn-primary"&gt;&lt;span class="fa fa-faceb...
0
2016-08-04T21:34:11Z
38,778,265
<p>I think the documentation lacks a reference to this. If anyone needs to find the name of the app to use in the <code>{% url %}</code> declaration, it can be found in the source code under <code>social.apps.backends</code>- each backend is a python file that declares a class, each class declares an attribute called <...
0
2016-08-04T22:16:19Z
[ "python", "django", "python-social-auth" ]
How do I check if a string exists within a string within a column
38,777,782
<p>What I want to do I figured would look like this:</p> <pre><code>(t in df[self.target]).any() </code></pre> <p>But I am getting:</p> <pre><code>AttributeError: 'bool' object has no attribute 'any' </code></pre>
4
2016-08-04T21:36:29Z
38,777,862
<p>I'm assuming it's a pandas DataFrame. Try this</p> <pre><code>(df[self.target] == t).any() </code></pre> <p>EDIT:</p> <pre><code>any((t in k for k in df[self.target])) </code></pre>
0
2016-08-04T21:42:11Z
[ "python", "pandas", "conditional", "any" ]
How do I check if a string exists within a string within a column
38,777,782
<p>What I want to do I figured would look like this:</p> <pre><code>(t in df[self.target]).any() </code></pre> <p>But I am getting:</p> <pre><code>AttributeError: 'bool' object has no attribute 'any' </code></pre>
4
2016-08-04T21:36:29Z
38,778,598
<p>You can use Pandas <code>str</code> methods (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html#pandas.Series.str.contains" rel="nofollow">docs</a>).</p> <pre><code>df[self.target].str.contains(t).any() </code></pre>
4
2016-08-04T22:52:21Z
[ "python", "pandas", "conditional", "any" ]
Is Flask-SocketIO's emit function thread safe?
38,777,793
<p>I have a Flask-SocketIO application. Can I safely call <code>socketio.emit()</code> from different threads? Is <code>socketio.emit()</code> atomic like the normal <code>socket.send()</code>?</p>
2
2016-08-04T21:37:26Z
38,798,235
<p>The <code>socketio.emit()</code> function is thread safe, or I should say that it is intended to be thread-safe, as there is currently one open issue related to this. Note that 'thread' in this context means a supported threading model. Most people use Flask-SocketIO in conjunction with eventlet or gevent in product...
1
2016-08-05T21:52:51Z
[ "python", "flask", "socket.io", "flask-socketio" ]
How could I determine what type python cast to?
38,777,822
<p>is it always casting result to float if there is one( or more ) element in calculation?</p> <p>for example:</p> <pre><code>1*1.0 # float from fractions import Fraction Fraction(1) * 1.0 # float </code></pre>
-1
2016-08-04T21:39:01Z
38,777,921
<p>No, it works because the Fraction class implements a <code>__mul__</code> (and probably <code>__rmul__</code>) method used to define the result of a multiplication with an other object (a float in your case).</p> <p>That's called operator overloading.</p> <p>EDIT: I don't understand why I got downvoted. According ...
-1
2016-08-04T21:45:53Z
[ "python" ]
How could I determine what type python cast to?
38,777,822
<p>is it always casting result to float if there is one( or more ) element in calculation?</p> <p>for example:</p> <pre><code>1*1.0 # float from fractions import Fraction Fraction(1) * 1.0 # float </code></pre>
-1
2016-08-04T21:39:01Z
38,778,007
<p>I'd say it does always cast to float if one of arguments is float, because float is most common number type. So if you do some operation (multiplication in your case) with float and other number interpreter can be sure it's posible to convert other number to float (doesn't mater is it int, Fraction or even Bool) wi...
2
2016-08-04T21:52:44Z
[ "python" ]
why is this formula for a circle giving me an ellipsoid in Javascript but a circle in Python?
38,777,840
<p>I adapted the following code for python found on this <a href="http://stackoverflow.com/a/15890673/2075859">page</a>: for a Javascript equivalent.</p> <pre><code>import math # inputs radius = 1000.0 # m - the following code is an approximation that stays reasonably accurate for distances &lt; 100km centerLat = 30...
0
2016-08-04T21:40:15Z
38,778,438
<p>You somehow got lat/lon reversed. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var linkDistance = 10; //$('#linkDistance').val(); var nodesCount = 8; var bandwidth ...
1
2016-08-04T22:33:33Z
[ "javascript", "python", "gps", "geometry", "trigonometry" ]
Python remove items from list
38,777,841
<p>I'm having some troubles with removing items from a list. I'm looking for a more elegant solution. Preferably a solution in one for-loop or filter. </p> <p>The objective of the piece of code: remove all empty entries and all entries starting with a '#' from the config handle.</p> <p>At the moment i'm using:</p> <...
0
2016-08-04T21:40:22Z
38,777,880
<p>You aren't allowed to modify an item that you're iterating over.</p> <p>Instead you should use things like <code>filter</code> or list comprehensions.</p> <pre><code>configHandle = filter(lambda a: (a != '') and not a.startswith('#'), configHandle) </code></pre>
0
2016-08-04T21:42:58Z
[ "python", "list", "items" ]
Python remove items from list
38,777,841
<p>I'm having some troubles with removing items from a list. I'm looking for a more elegant solution. Preferably a solution in one for-loop or filter. </p> <p>The objective of the piece of code: remove all empty entries and all entries starting with a '#' from the config handle.</p> <p>At the moment i'm using:</p> <...
0
2016-08-04T21:40:22Z
38,777,881
<p>Because You're changing the list while iterating over it. You can use a list comprehension to get ride of this problem:</p> <pre><code>configHandle = [i for i in configHandle if i and not i.startswith('#')] </code></pre> <p>Also for opening a file you better to use a <code>with</code> statement that close the file...
1
2016-08-04T21:43:03Z
[ "python", "list", "items" ]
Python remove items from list
38,777,841
<p>I'm having some troubles with removing items from a list. I'm looking for a more elegant solution. Preferably a solution in one for-loop or filter. </p> <p>The objective of the piece of code: remove all empty entries and all entries starting with a '#' from the config handle.</p> <p>At the moment i'm using:</p> <...
0
2016-08-04T21:40:22Z
38,777,889
<p>Don't remove items while you iterating, it's a <a class='doc-link' href="http://stackoverflow.com/documentation/python/3553/common-pitfalls/949/changing-the-sequence-you-are-iterating-over#t=201608042142236253862">common pitfall</a></p>
1
2016-08-04T21:43:27Z
[ "python", "list", "items" ]
Python remove items from list
38,777,841
<p>I'm having some troubles with removing items from a list. I'm looking for a more elegant solution. Preferably a solution in one for-loop or filter. </p> <p>The objective of the piece of code: remove all empty entries and all entries starting with a '#' from the config handle.</p> <p>At the moment i'm using:</p> <...
0
2016-08-04T21:40:22Z
38,777,891
<p>Your <code>filter</code> expression is good; just include the additional condition you're looking for:</p> <pre><code>configHandle = filter(lambda a: a != '' and not a.startswith('#'), configHandle) </code></pre> <p><br/></p> <p>There are other options if you don't want to use <code>filter</code>, but, as has bee...
0
2016-08-04T21:43:55Z
[ "python", "list", "items" ]
Matching elements of two lists which are almost the same
38,777,857
<p>Let's suppose I have two lists of strings. I want to reorder the second list by getting the element that most resembles the corresponding element of the first list.</p> <p>I already do this :</p> <pre><code>import difflib list1 = ['aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg', 'hhhh', 'iiii', 'jjjj'] lis...
1
2016-08-04T21:41:52Z
38,778,122
<pre><code>while i &lt; len: j = 0 new_l = [] while j &lt; len: new_l.append(difflib.SequenceMatcher(None, list1[i], list2[j]).ratio()) j += 1 ind = new_l.index(max(new_l)) eltMove = list2.pop(ind) list2.insert(i, eltMove) i += 1 </code></pre> <p>It stores the ratios and th...
2
2016-08-04T22:01:23Z
[ "python", "difflib" ]
Matching elements of two lists which are almost the same
38,777,857
<p>Let's suppose I have two lists of strings. I want to reorder the second list by getting the element that most resembles the corresponding element of the first list.</p> <p>I already do this :</p> <pre><code>import difflib list1 = ['aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg', 'hhhh', 'iiii', 'jjjj'] lis...
1
2016-08-04T21:41:52Z
38,778,585
<p>My two cents. And yes, the solution could be more pythonic...</p> <pre><code>import difflib def closest_list(list1, list2): tmp_list = list2 res = [] for elem1 in list1: best_value = 0 best = None position = None for i, elem2 in enumerate(list2): current_valu...
2
2016-08-04T22:50:49Z
[ "python", "difflib" ]
How to give an error msg based on user input in my program?
38,777,883
<p>So I've written an Electric Bill Calculator in Python. The great news is that it works! However, I need to make it work better. When asked how many hours per day, the user can type in 25, or any other number they want. Obviously there isn't 25 hours in a day. I've tried a few things but I cannot get it to work corre...
3
2016-08-04T21:43:06Z
38,777,922
<p>I put your error message in an if statment, and the calculation code in an else. This way it won't do the calculation when the hour isn't correct and instead will exit main and go back to the while loop and ask the user if they will like to play again. Also as other user's have pointed out following what I did below...
0
2016-08-04T21:46:01Z
[ "python", "if-statement", "error-handling", "while-loop" ]
How to give an error msg based on user input in my program?
38,777,883
<p>So I've written an Electric Bill Calculator in Python. The great news is that it works! However, I need to make it work better. When asked how many hours per day, the user can type in 25, or any other number they want. Obviously there isn't 25 hours in a day. I've tried a few things but I cannot get it to work corre...
3
2016-08-04T21:43:06Z
38,777,942
<p>The input you get from the user is a <code>string</code> type, but you compare it to <code>int</code> type. That's an error. You should cast the <code>string</code> to <code>int</code> first:</p> <pre><code>hours = int(input("How many hours per day? ")) # ----^--- </code></pre> <p>Then you can do something like...
0
2016-08-04T21:47:27Z
[ "python", "if-statement", "error-handling", "while-loop" ]
How to give an error msg based on user input in my program?
38,777,883
<p>So I've written an Electric Bill Calculator in Python. The great news is that it works! However, I need to make it work better. When asked how many hours per day, the user can type in 25, or any other number they want. Obviously there isn't 25 hours in a day. I've tried a few things but I cannot get it to work corre...
3
2016-08-04T21:43:06Z
38,777,964
<p>My python skills are a little rusty, but when I have to do stuff like checking input, I usually use a structure something like this:</p> <pre><code>hours = 0 while True: hours = input("How many hours per day? ") #first make sure they entered an integer try: tmp = int(hours) #this operaion throws a Va...
0
2016-08-04T21:48:44Z
[ "python", "if-statement", "error-handling", "while-loop" ]
How to give an error msg based on user input in my program?
38,777,883
<p>So I've written an Electric Bill Calculator in Python. The great news is that it works! However, I need to make it work better. When asked how many hours per day, the user can type in 25, or any other number they want. Obviously there isn't 25 hours in a day. I've tried a few things but I cannot get it to work corre...
3
2016-08-04T21:43:06Z
38,778,062
<p>An optimized version of @JamesRusso code :</p> <pre><code>def main(): star = '*' * 70 print star print ("Nick's Electric Bill Calculator") print star watts = int(input("Enter the watts of appliance, or total watts of appliances")) hours = int(input("Enter the number of hours that appliance(s...
0
2016-08-04T21:56:06Z
[ "python", "if-statement", "error-handling", "while-loop" ]
Python: "Use a.any() or a.all()" while traversing a numpy.ndarray
38,777,890
<p>In a <code>numpy.ndarray</code> like this one:</p> <pre><code>myarray= array([[ 0.47174344, 0.45314669, 0.46395022, 0.47440382, 0.50709627, 0.53350065, 0.5233444 , 0.49974663, 0.48721607, 0.46239652, 0.4693633 , 0.47263569, 0.47591957, 0.436558 , 0.43335574, 0.44053621, 0.42...
1
2016-08-04T21:43:42Z
38,778,077
<p>Normally, you can compare two numbers to get a truth value. For example:</p> <pre><code>elem = 5 if elem &lt; 6: # do something </code></pre> <p>is equivalent to:</p> <pre><code>if true: # do something </code></pre> <p>However, you can't compare an array to a value. For example:</p> <pre><code>elem = [5...
1
2016-08-04T21:56:57Z
[ "python", "numpy", "for-loop", "ambiguity" ]
Python: "Use a.any() or a.all()" while traversing a numpy.ndarray
38,777,890
<p>In a <code>numpy.ndarray</code> like this one:</p> <pre><code>myarray= array([[ 0.47174344, 0.45314669, 0.46395022, 0.47440382, 0.50709627, 0.53350065, 0.5233444 , 0.49974663, 0.48721607, 0.46239652, 0.4693633 , 0.47263569, 0.47591957, 0.436558 , 0.43335574, 0.44053621, 0.42...
1
2016-08-04T21:43:42Z
38,778,186
<p>Yeah I think your numpy.array has an extra bracket or it is encompassing another array.</p> <p>Tried Manually set array as </p> <pre><code>myarray=np.array([[ 0.47174344, 0.45314669, 0.46395022, 0.47440382, 0.50709627,0.53350065, 0.5233444 , 0.49974663, 0.48721607, 0.46239652, 0.4693633 , 0.47263569, 0.4...
1
2016-08-04T22:07:14Z
[ "python", "numpy", "for-loop", "ambiguity" ]
Python: "Use a.any() or a.all()" while traversing a numpy.ndarray
38,777,890
<p>In a <code>numpy.ndarray</code> like this one:</p> <pre><code>myarray= array([[ 0.47174344, 0.45314669, 0.46395022, 0.47440382, 0.50709627, 0.53350065, 0.5233444 , 0.49974663, 0.48721607, 0.46239652, 0.4693633 , 0.47263569, 0.47591957, 0.436558 , 0.43335574, 0.44053621, 0.42...
1
2016-08-04T21:43:42Z
38,778,231
<p>Regardless the error you can simply do:</p> <pre><code>myarray[myarray&lt;value]=0 np.count_nonzero(myarray) </code></pre> <p>to get your desired result</p>
1
2016-08-04T22:12:34Z
[ "python", "numpy", "for-loop", "ambiguity" ]
Complex infinities - funny reslts - a numpy bug?
38,777,914
<p>I've noticed funny results with complex infinities.</p> <pre><code>In [1]: import numpy as np In [2]: np.isinf(1j * np.inf) Out[2]: True In [3]: np.isinf(1 * 1j * np.inf) Out[3]: True In [4]: np.isinf(1j * np.inf * 1) Out[4]: False </code></pre> <p>This is <code>nan</code> related. But the end result is bizarre...
6
2016-08-04T21:45:29Z
38,778,042
<p>It's not a NumPy bug. <code>numpy.inf</code> is a regular Python float, and the strange results come from the regular Python complex multiplication algorithm, which is <a href="https://hg.python.org/cpython/file/3.5/Objects/complexobject.c#l42">this</a>:</p> <pre><code>Py_complex _Py_c_prod(Py_complex a, Py_complex...
5
2016-08-04T21:55:06Z
[ "python", "numpy" ]
How to calculate the width of the Windows CMD shell in pixels?
38,778,079
<p>I'm working on a Python shell script that is supposed to fill a percentage of the user's screen. The shell's width, however, is calculated in characters instead of pixels, and I find it difficult to compare them to the screen resolution (which is obviously in pixels).</p> <p><strong>How can I effectively calculate ...
2
2016-08-04T21:57:08Z
38,778,425
<p>You cant but the default command prompt dimensions are 677, 343. The height being 677 and the width being 343, hope this helps.</p>
0
2016-08-04T22:32:06Z
[ "python", "linux", "shell", "cmd" ]
Pass kwargs into Django Filter
38,778,080
<p>When viewing model entries from within Django Admin, you can specify filters. How can I mimic this behavior? Not to familiar with <code>kwargs</code> but something similar to this: </p> <pre><code>foo = Model.objects.filter(**__exact='**') </code></pre> <p>where the first set of <code>**</code> would be a field in...
0
2016-08-04T21:57:14Z
38,778,107
<p>You can unpack a python dict as your filter parameters using <code>**</code></p> <pre><code>your_filters = { 'field_1__exact': value_1, 'field_2__gte': value_2, } Model.objects.filter(**your_filters) </code></pre> <p>Said that, you can built your query filters(a python dict) dynamically based on an user input. </...
1
2016-08-04T22:00:21Z
[ "python", "django", "django-templates", "django-admin", "django-views" ]
Is python maximum recurrence depth per object?
38,778,142
<p>I am refactoring a Python signal processing framework because of a maximum recurrence depth error we experienced. </p> <p>The most likely explanation for the error is that sometimes a large number of instances of a single class are created recursively from the class' its <strong>init</strong> method. Indeed experi...
0
2016-08-04T22:03:31Z
38,778,295
<p>No, it's a global recursion depth. The situation you describe implies that when you exceed the stack limit, you catch the exception and continue with the next object. This process removes the associated stack entries -- unravelling the recursion to its starting point.</p> <p>You start fresh with the next object. ...
0
2016-08-04T22:19:07Z
[ "python", "recursion", "stack" ]
Is python maximum recurrence depth per object?
38,778,142
<p>I am refactoring a Python signal processing framework because of a maximum recurrence depth error we experienced. </p> <p>The most likely explanation for the error is that sometimes a large number of instances of a single class are created recursively from the class' its <strong>init</strong> method. Indeed experi...
0
2016-08-04T22:03:31Z
38,778,327
<p>In the implementation I use, setting</p> <pre><code>sys.setrecursionlimit(907) </code></pre> <p>demonstrates that this is the recursion depth you reach.</p> <hr> <p>To your question, the answer is no. In the source code of CPython you can see that the recursion depth is per thread, not per object.</p> <p><a hre...
0
2016-08-04T22:22:27Z
[ "python", "recursion", "stack" ]
Is python maximum recurrence depth per object?
38,778,142
<p>I am refactoring a Python signal processing framework because of a maximum recurrence depth error we experienced. </p> <p>The most likely explanation for the error is that sometimes a large number of instances of a single class are created recursively from the class' its <strong>init</strong> method. Indeed experi...
0
2016-08-04T22:03:31Z
38,778,440
<p>You can rewrite your methods to be iterative instead of recursive. This avoids the possibility of recursion depth errors regardless of how deep your data structure becomes.</p> <p>The <code>create</code> method would become something like this:</p> <pre><code>def create(self, x): # the `x` arg is not actually used...
0
2016-08-04T22:34:06Z
[ "python", "recursion", "stack" ]
Get location from response header
38,778,240
<p>I am trying to get the <code>Location</code> value from a <code>POST</code> request using python's requests module. However, when I look at the response's headers, I don't see any such key. Performing the same request using Google Chrome does show the key.</p> <p>This is where I am trying to download data from: <a ...
0
2016-08-04T22:13:48Z
38,779,024
<h1>EDIT2</h1> <p>You need to pass the <code>include_crime = on</code> statement as well, since you are not selecting any dataset. On the webpage if you don't select any checkbox, you will get the same page and you will not get any location header. That is why your r.content has "Please select at least one dataset".</...
-2
2016-08-04T23:41:33Z
[ "python", "python-requests" ]
How to iterate through a dict to see if a occurence of a list matches one or more of the keys?
38,778,257
<p>I have a dict that looks like this:</p> <pre><code>BACKPACK = {'granola bar': 1, 'cooked meat': 1, 'raw meat': 1, 'dried foods': 1} </code></pre> <p>What I want to do is check if one or more elements inside of a list occur in that dict, if so I want to go to the next method, if not I want to do something else.</p>...
0
2016-08-04T22:15:14Z
38,778,388
<p>EDIT: your loop was the wrong way use this</p> <pre><code>BACKPACK ={'cooked meat': 1, 'raw meat': 1} HEALTH = 25 def rest(): # print formatter() foods = ['granola bars', 'cooked meat', 'dried foods', 'raw meat'] for food in BACKPACK: if food in foods: eat_food(food,HEALTH) ...
1
2016-08-04T22:29:00Z
[ "python", "list", "dictionary" ]
How to iterate through a dict to see if a occurence of a list matches one or more of the keys?
38,778,257
<p>I have a dict that looks like this:</p> <pre><code>BACKPACK = {'granola bar': 1, 'cooked meat': 1, 'raw meat': 1, 'dried foods': 1} </code></pre> <p>What I want to do is check if one or more elements inside of a list occur in that dict, if so I want to go to the next method, if not I want to do something else.</p>...
0
2016-08-04T22:15:14Z
38,778,518
<p>Is <em>this</em> what you need? It should work properly now:</p> <pre><code>BACKPACK = {'raw meat': 1, 'raw meat': 1, 'granola bar': 1, 'dried foods': 1, 'cooked meat': 1} HEALTH = 25 def rest(): foods = ['granola bar', 'cooked meat', 'dried foods'] back = {} for x in foods: for y in BACKPACK: ...
1
2016-08-04T22:44:00Z
[ "python", "list", "dictionary" ]
How to iterate through a dict to see if a occurence of a list matches one or more of the keys?
38,778,257
<p>I have a dict that looks like this:</p> <pre><code>BACKPACK = {'granola bar': 1, 'cooked meat': 1, 'raw meat': 1, 'dried foods': 1} </code></pre> <p>What I want to do is check if one or more elements inside of a list occur in that dict, if so I want to go to the next method, if not I want to do something else.</p>...
0
2016-08-04T22:15:14Z
38,778,745
<p>If you just want to get all keys that are in a list, you should use <strong>sets</strong>:</p> <pre><code>intersection = set(mylist) &amp; set(mydict.keys()) </code></pre> <p>If there aren't any, intersection will be an empty set with a false bool, otherwise it will have a true bool. To check whether there are suc...
0
2016-08-04T23:08:37Z
[ "python", "list", "dictionary" ]
Assert Two Frames Are Not Equal
38,778,266
<p>I need to test that two pandas dataframes are <em>not</em> equal. Is there an equivalent to pandas <code>assert_frame_equal</code> function that does this? If not, what's the best/safest way to assert that the frames aren't equal?</p>
3
2016-08-04T22:16:22Z
38,778,345
<p>Yes there is :</p> <pre><code># Let us suppose you have two dataframes df1 and df2 # Check for equality by using df1.equals(df2) </code></pre> <p>Use <code>not</code> to assert that they are not equal</p>
-1
2016-08-04T22:24:26Z
[ "python", "unit-testing", "pandas" ]
Assert Two Frames Are Not Equal
38,778,266
<p>I need to test that two pandas dataframes are <em>not</em> equal. Is there an equivalent to pandas <code>assert_frame_equal</code> function that does this? If not, what's the best/safest way to assert that the frames aren't equal?</p>
3
2016-08-04T22:16:22Z
38,778,401
<p>You could write your own assertion function that uses <code>assert_frame_equal()</code> and inverts the result:</p> <pre><code>def assert_frame_not_equal(*args, **kwargs): try: assert_frame_equal(*args, **kwargs) except AssertionError: # frames are not equal pass else: # ...
4
2016-08-04T22:30:21Z
[ "python", "unit-testing", "pandas" ]
Assert Two Frames Are Not Equal
38,778,266
<p>I need to test that two pandas dataframes are <em>not</em> equal. Is there an equivalent to pandas <code>assert_frame_equal</code> function that does this? If not, what's the best/safest way to assert that the frames aren't equal?</p>
3
2016-08-04T22:16:22Z
38,778,418
<p>Assuming <code>assert_frame_equal</code> behaves like <code>assert</code> (meaning either nothing happens or it raises <code>AssertionError</code>) then you probably can just wrap it in a <code>try</code>:</p> <pre><code>def assert_frame_not_equal(df1, df2): try: assert_frame_equal(df1, df2) rai...
2
2016-08-04T22:31:31Z
[ "python", "unit-testing", "pandas" ]
Sending events outside from Flask SocketIO event context
38,778,315
<p>When I try to send a socket message outside from the SocketIO event context, the message does not arrive at the client.</p> <p>Method outside of the context:</p> <pre><code>@main.route('/import/event', methods=['POST']) def update_client(): from .. import socketio userid = request.json['userid'] data = re...
1
2016-08-04T22:20:55Z
38,802,050
<p>I found a solution.</p> <p>When I run the application with the flask internal server, the messages are not received by the client.</p> <pre><code>python manage.py run </code></pre> <p>But when I run the server with gunicorn all works like a charm.</p> <p>So the solution here is to use the gunicorn with eventlet....
0
2016-08-06T08:12:09Z
[ "python", "flask", "flask-socketio" ]
sqlalchemy - How to select count from a union query
38,778,331
<p>My goal is that I have two tables, each describes a relationship between a user and either a "team" or "company"</p> <p>If there are any rows that says "admin" in the tables for the userid, then I want to know that, otherwise if no rows then i need to know that as well.</p> <p>What I have so far is as follows (Use...
0
2016-08-04T22:22:47Z
38,783,111
<p>You need to use <code>my_union</code> as subquery</p> <pre><code>my_union = q1.union_all(q2).subquery() query = select([func.sum(my_union.c.cnt).label("total_cnt")], from_obj=my_union) </code></pre>
0
2016-08-05T07:02:58Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
sqlalchemy - How to select count from a union query
38,778,331
<p>My goal is that I have two tables, each describes a relationship between a user and either a "team" or "company"</p> <p>If there are any rows that says "admin" in the tables for the userid, then I want to know that, otherwise if no rows then i need to know that as well.</p> <p>What I have so far is as follows (Use...
0
2016-08-04T22:22:47Z
38,802,208
<p>Here's my own problem solved, I used a slightly different approach than @r-m-n's however I think both should work:</p> <pre><code> q_union = q1.union_all(q2) q_union_cnt = db.session.query(func.sum(q_union.subquery().columns.cnt).label("total_cnt")) admin_points = q_union_cnt.scalar() </code></pre>
0
2016-08-06T08:29:27Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]