title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
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 3
2014-05-01 01:00:01 2
2014-05-01 01:00:02 3
2014-05-01 01:00:03 2
2014-05-01 01:00:04 1
</code></pre>
<p>I'm trying to get my table to have an extra column and look like this:</p>
<pre><code> datetime output secondsuntildecrease
2014-05-01 01:00:00 3 1
2014-05-01 01:00:01 2 3
2014-05-01 01:00:02 3 1
2014-05-01 01:00:03 2 1
2014-05-01 01:00:04 1
</code></pre>
<p>thanks in advance!</p>
| 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 & (s.index > s.name)]
if s.empty:
return np.nan
else:
return (s.index[0] - s.name).total_seconds()
df['secondsuntildecrease'] = df['output'].apply(lambda x: df['output'] < x).apply(f, axis=1)
df
</code></pre>
<p>outputs</p>
<pre><code> output secondsuntildecrease
2014-05-01 01:00:00 3 1.0
2014-05-01 01:00:01 2 3.0
2014-05-01 01:00:02 3 1.0
2014-05-01 01:00:03 2 1.0
2014-05-01 01:00:04 1 NaN
</code></pre>
| 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 3
2014-05-01 01:00:01 2
2014-05-01 01:00:02 3
2014-05-01 01:00:03 2
2014-05-01 01:00:04 1
</code></pre>
<p>I'm trying to get my table to have an extra column and look like this:</p>
<pre><code> datetime output secondsuntildecrease
2014-05-01 01:00:00 3 1
2014-05-01 01:00:01 2 3
2014-05-01 01:00:02 3 1
2014-05-01 01:00:03 2 1
2014-05-01 01:00:04 1
</code></pre>
<p>thanks in advance!</p>
| 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'] < x['output']) & (df['datetime'] > x['datetime']), 'datetime'].min()) - pd.to_datetime(x[
'datetime']), axis=1)
</code></pre>
<p>output</p>
<pre><code> datetime output seconds_until
0 2014/05/01 01:00:00 3 00:00:01
1 2014/05/01 01:00:01 2 00:00:03
2 2014/05/01 01:00:02 3 00:00:01
3 2014/05/01 01:00:03 2 00:00:01
4 2014/05/01 01:00:04 1 NaT
</code></pre>
| 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 3
2014-05-01 01:00:01 2
2014-05-01 01:00:02 3
2014-05-01 01:00:03 2
2014-05-01 01:00:04 1
</code></pre>
<p>I'm trying to get my table to have an extra column and look like this:</p>
<pre><code> datetime output secondsuntildecrease
2014-05-01 01:00:00 3 1
2014-05-01 01:00:01 2 3
2014-05-01 01:00:02 3 1
2014-05-01 01:00:03 2 1
2014-05-01 01:00:04 1
</code></pre>
<p>thanks in advance!</p>
| 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 = pd.DataFrame(
dict(output=[3, 2, 3, 2, 1],
datetime=pd.DatetimeIndex(start='2014-05-01 01:00:00', periods=5, freq='S'))
)
gt0 = np.triu(np.subtract.outer(df.output, df.output), 1) > 0
idx = np.where(gt0.any(1), gt0.argmax(1), np.nan)
-(df.datetime - df.loc[idx, 'datetime'].values).dt.total_seconds()
0 1.0
1 3.0
2 1.0
3 1.0
4 NaN
Name: datetime, dtype: float64
</code></pre>
<hr>
<h3>Timing</h3>
<p><strong><em>Mine and ayhan's seem the most performant over small sample</em></strong></p>
<p><a href="http://i.stack.imgur.com/jjeth.png" rel="nofollow"><img src="http://i.stack.imgur.com/jjeth.png" alt="enter image description here"></a></p>
<p><strong><em>ayhan's is best over 10,000 rows</em></strong></p>
<p><a href="http://i.stack.imgur.com/EFqb1.png" rel="nofollow"><img src="http://i.stack.imgur.com/EFqb1.png" alt="enter image description here"></a></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 using Django Rest ModelSerializer and CreateAPIView methods. Let say that I have a model Location with a unique field 'address'. I want to return an existing instance when the address already exists on my database. If the address does not exist, I want to create an entry in the database and populate other computed values for the object.</p>
<pre><code>class Location(models.Model):
address = models.CharField(max_length=100, unique=True,)
thing1 = models.CharField(max_length=100, blank=True, null=True, )
thing2 = models.CharField(max_length=100, blank=True, null=True, )
def compute_things(self, address):
somevalue1 = ...
somevalue2 = ....
return somevalue1, somevalue2
</code></pre>
<p>Now, I am not exactly sure how to write the serializer and view so that:</p>
<ol>
<li>A new location is created and returned with all the fields
initialized when a new address is seen for the first time</li>
<li>An existing location that matches 'address' in the database is
returned in lieu of step 1</li>
</ol>
<p>What else should I define for the model? How do I write APIView and CreateSerializer to get the right thing? Where should I call the compute_thing() in order to populate the missing fields.</p>
<p>For the serializer:</p>
<pre><code>class LocationCreateSerializer(ModelSerializer):
class Meta:
model = Location
</code></pre>
<p>And for the APIView:</p>
<pre><code>class LocationCreateAPIView(CreateAPIView):
serializer_class = LocationCreateSerializer
queryset = Location.objects.all()
</code></pre>
<p>The APIView and Serializer above are not enough for what I need. What else do I need to add to model, View and Serializer to get that behavior that I am seeking? </p>
<p>I don't want the View nor the Serializer to return validation errors for duplicate 'addresses'--just the existing instance and not an error. It looks like restore_object() is deprecated. Is there a way to accomplish what I am seeking?</p>
| 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 using Django Rest ModelSerializer and CreateAPIView methods. Let say that I have a model Location with a unique field 'address'. I want to return an existing instance when the address already exists on my database. If the address does not exist, I want to create an entry in the database and populate other computed values for the object.</p>
<pre><code>class Location(models.Model):
address = models.CharField(max_length=100, unique=True,)
thing1 = models.CharField(max_length=100, blank=True, null=True, )
thing2 = models.CharField(max_length=100, blank=True, null=True, )
def compute_things(self, address):
somevalue1 = ...
somevalue2 = ....
return somevalue1, somevalue2
</code></pre>
<p>Now, I am not exactly sure how to write the serializer and view so that:</p>
<ol>
<li>A new location is created and returned with all the fields
initialized when a new address is seen for the first time</li>
<li>An existing location that matches 'address' in the database is
returned in lieu of step 1</li>
</ol>
<p>What else should I define for the model? How do I write APIView and CreateSerializer to get the right thing? Where should I call the compute_thing() in order to populate the missing fields.</p>
<p>For the serializer:</p>
<pre><code>class LocationCreateSerializer(ModelSerializer):
class Meta:
model = Location
</code></pre>
<p>And for the APIView:</p>
<pre><code>class LocationCreateAPIView(CreateAPIView):
serializer_class = LocationCreateSerializer
queryset = Location.objects.all()
</code></pre>
<p>The APIView and Serializer above are not enough for what I need. What else do I need to add to model, View and Serializer to get that behavior that I am seeking? </p>
<p>I don't want the View nor the Serializer to return validation errors for duplicate 'addresses'--just the existing instance and not an error. It looks like restore_object() is deprecated. Is there a way to accomplish what I am seeking?</p>
| 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()
def post(self, request, format=None):
address = None
if 'address' in self.request.data:
address = self.request.data['address']
else:
return Response(status=HTTP_400_BAD_REQUEST)
try:
location = Location.objects.get(address=address)
serializer = self.get_serializer(location)
return Response(serializer.data, status=HTTP_200_OK)
except Location.DoesNotExist:
pass
serializer = LocationCreateSerializer(data=self.request.data)
if serializer.is_valid():
somevalue1, somevalue2 = Location.compute_things(self, address=address)
if (not somevalue1) | (not somevalue2):
return Response(status=HTTP_400_BAD_REQUEST)
serializer.save(address=address, thing1=somevalue1, thing2=somevalue2)
return Response(serializer.data, status=HTTP_201_CREATED)
return Response(status=HTTP_400_BAD_REQUEST)
</code></pre>
<p>If you have a better solution, please post it. I'd like to continue learning.</p>
| 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_all_tweets(screen_name):
#authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
#initialize a list to hold all the tweepy Tweets
alltweets = []
new_tweets = api.home_timeline (screen_name = screen_name,count=20)
#save most recent tweets
alltweets.extend(new_tweets)
#save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
while len(new_tweets) > 0:
print ("getting tweets before %s" % (oldest))
#all subsiquent requests use the max_id param to prevent duplicates
new_tweets = api.home_timeline(screen_name = screen_name,count=20,max_id=oldest)
#save most recent tweets
alltweets.extend(new_tweets)
#update the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
print ("...%s tweets downloaded so far" % (len(alltweets)))
#transform the tweepy tweets into a 2D array that will populate the csv
outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in alltweets]
#write the csv
with open('%s_tweetsBQ.csv' % screen_name, 'w') as f:
writer = csv.writer(f)
writer.writerow(["id","created_at","text"])
writer.writerows(outtweets)
pass
if __name__ == '__main__':
#pass in the username of the account you want to download
get_all_tweets("BQ")
</code></pre>
| 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_all_tweets(screen_name):
#authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
#initialize a list to hold all the tweepy Tweets
alltweets = []
new_tweets = api.home_timeline (screen_name = screen_name,count=20)
#save most recent tweets
alltweets.extend(new_tweets)
#save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
while len(new_tweets) > 0:
print ("getting tweets before %s" % (oldest))
#all subsiquent requests use the max_id param to prevent duplicates
new_tweets = api.home_timeline(screen_name = screen_name,count=20,max_id=oldest)
#save most recent tweets
alltweets.extend(new_tweets)
#update the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
print ("...%s tweets downloaded so far" % (len(alltweets)))
#transform the tweepy tweets into a 2D array that will populate the csv
outtweets = [[tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in alltweets]
#write the csv
with open('%s_tweetsBQ.csv' % screen_name, 'w') as f:
writer = csv.writer(f)
writer.writerow(["id","created_at","text"])
writer.writerows(outtweets)
pass
if __name__ == '__main__':
#pass in the username of the account you want to download
get_all_tweets("BQ")
</code></pre>
| 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 suggest that you take a look at : <a href="https://dev.twitter.com/rest/public/rate-limiting" rel="nofollow">https://dev.twitter.com/rest/public/rate-limiting</a> for more details.</p>
| 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*#+]', '', '+*#+0#01231340010')
</code></pre>
<p>but it is removing later 0s too.</p>
<p>I tried to use regex groups, but still it's not working ( or I am doing something wrong for sure ).</p>
<p>Any help will be appreciated.</p>
<p>Thanks in advance.</p>
| 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>>>> 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.dropwhile" rel="nofollow"><code>itertools.dropwhile()</code></a>:</p>
<pre><code>>>> from itertools import dropwhile
>>> not_allowed = {'0', '*', '#', '+'}
>>> ''.join(dropwhile(lambda x: x in not_allowed, s))
'1231340010'
</code></pre>
| 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*#+]', '', '+*#+0#01231340010')
</code></pre>
<p>but it is removing later 0s too.</p>
<p>I tried to use regex groups, but still it's not working ( or I am doing something wrong for sure ).</p>
<p>Any help will be appreciated.</p>
<p>Thanks in advance.</p>
| 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*#+]', '', '+*#+0#01231340010')
</code></pre>
<p>but it is removing later 0s too.</p>
<p>I tried to use regex groups, but still it's not working ( or I am doing something wrong for sure ).</p>
<p>Any help will be appreciated.</p>
<p>Thanks in advance.</p>
| 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*#+]', '', '+*#+0#01231340010')
</code></pre>
<p>but it is removing later 0s too.</p>
<p>I tried to use regex groups, but still it's not working ( or I am doing something wrong for sure ).</p>
<p>Any help will be appreciated.</p>
<p>Thanks in advance.</p>
| 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*#+]', '', '+*#+0#01231340010')
</code></pre>
<p>but it is removing later 0s too.</p>
<p>I tried to use regex groups, but still it's not working ( or I am doing something wrong for sure ).</p>
<p>Any help will be appreciated.</p>
<p>Thanks in advance.</p>
| 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><strong>Pattern details</strong>:</p>
<ul>
<li><code>^</code> - start of string</li>
<li><code>[^1-9]+</code> - 1 or more (<code>+</code>) characters other than digits from 1-9 range (excluding <code>0</code>)</li>
</ul>
<p>I say "safer" meaning that there can be other prefixes not enumerated in the question, like <code>p</code>, etc.</p>
| 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 function here:</p>
<pre><code>def test_get_can_edit(self):
self.request1 = RequestFactory().post('./fake_path')
self.request1.user = SimpleLazyObject(self.user1)
self.request1.query_params = {}
self.serializer1 = ConferenceSerializer(context={'request': self.request1})
self.canEdit1 = self.serializer1.get_can_edit(self.conference)
</code></pre>
<p>When I run the test, it fails the the error: <code>'User' object is not callable</code>, and references the following line in the serializer <code>get_can_edit</code> function:</p>
<pre><code>user = User.objects.get(username=request.user)
</code></pre>
<p>However, when running in browser, the get_can_edit function performs correctly and has no problem with the 'User' objet being callable.</p>
<p>I originally assumed that there was a problem with the format of the fake data I was creating (I'm using <a href="https://factoryboy.readthedocs.io/en/latest/index.html" rel="nofollow">factory_boy</a> and <a href="https://docs.djangoproject.com/en/1.9/topics/testing/advanced/" rel="nofollow">RequestFactory</a> to create the fake data). Using a debugger, I went into the get_can_edit function both by calling the test, and through the server by making a real request. In both cases, <code>request.user</code> and <code>obj.admin</code> were in the correct form, so I ruled out a data formatting error.</p>
<p>Next, I tried </p>
<pre><code>User.objects.get(username=request.user)
</code></pre>
<p>in the debuggers. It worked for the real request in the server, and returned the same <code>'User' object is not callable</code> error for the fake request in the test. I did a quick stack overflow/google search for <code>object is not callable</code> errors in Django, but it looked like other cases were solved by making sure a model was imported correctly (mine is definitely imported correctly).</p>
<p>So at this point I know that there's a problem with my test case that does not exist with the real request, but I can't really figure out what it is, and I'm running out of ideas.</p>
<p>Full code:</p>
<p><a href="https://github.com/TomHeatwole/osf-meetings/blob/feature/conference-tests/meetings/conferences/serializers.py" rel="nofollow">The serializer</a></p>
<p><a href="https://github.com/TomHeatwole/osf-meetings/blob/feature/conference-tests/meetings/conferences/tests.py" rel="nofollow">The test</a></p>
<p>Thanks so much, let me know if there's an easier way to go about this.</p>
<p><br><br></p>
<p>UPDATE:
So I went back in the two different debuggers and did <code>User.objects.all()</code>. The one in the server with the real request returned the correct list of users. The one in the test with the fake request just returned anonymoususer. Because I'm using factory_boy to create my fake users, django can't find it in <code>User.objects</code>.</p>
<p>I've been told not to make real requests in my unit tests, so creating an actual user is out of the question. </p>
<p>I also tried changing the <code>get_can_edit</code> function to not check <code>User.objects.</code>. <code>request.user</code> is a <code>SimpleLazyObject</code> containing the user. What I tried doing was <code>request.user.id</code> and comparing it to <code>obj.admin.id</code>, but apparently when you do pretty much anything to a <code>SimpleLazyObject</code>, it consults <code>User.objects</code> to get to the actual User associated with it, so it still had the same error <code>'User' object is not callable</code>. </p>
<p>So the bottom line is this: <strong>I need to add a fake user to <code>User.objects</code> without making a real request</strong></p>
| 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(APITestCase):
"""
Base class to initialize the test cases
"""
self.user = YourUserFactory.create_batch(1)
self.user_client = self.get_client(user=self.user)
</code></pre>
<p>In your Test</p>
<pre><code>class YourTestClass(BaseAPITestCase):
def test_get_can_edit(self):
response = self.user_client.post('./fake_path')
# proccess your response
</code></pre>
| 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 function here:</p>
<pre><code>def test_get_can_edit(self):
self.request1 = RequestFactory().post('./fake_path')
self.request1.user = SimpleLazyObject(self.user1)
self.request1.query_params = {}
self.serializer1 = ConferenceSerializer(context={'request': self.request1})
self.canEdit1 = self.serializer1.get_can_edit(self.conference)
</code></pre>
<p>When I run the test, it fails the the error: <code>'User' object is not callable</code>, and references the following line in the serializer <code>get_can_edit</code> function:</p>
<pre><code>user = User.objects.get(username=request.user)
</code></pre>
<p>However, when running in browser, the get_can_edit function performs correctly and has no problem with the 'User' objet being callable.</p>
<p>I originally assumed that there was a problem with the format of the fake data I was creating (I'm using <a href="https://factoryboy.readthedocs.io/en/latest/index.html" rel="nofollow">factory_boy</a> and <a href="https://docs.djangoproject.com/en/1.9/topics/testing/advanced/" rel="nofollow">RequestFactory</a> to create the fake data). Using a debugger, I went into the get_can_edit function both by calling the test, and through the server by making a real request. In both cases, <code>request.user</code> and <code>obj.admin</code> were in the correct form, so I ruled out a data formatting error.</p>
<p>Next, I tried </p>
<pre><code>User.objects.get(username=request.user)
</code></pre>
<p>in the debuggers. It worked for the real request in the server, and returned the same <code>'User' object is not callable</code> error for the fake request in the test. I did a quick stack overflow/google search for <code>object is not callable</code> errors in Django, but it looked like other cases were solved by making sure a model was imported correctly (mine is definitely imported correctly).</p>
<p>So at this point I know that there's a problem with my test case that does not exist with the real request, but I can't really figure out what it is, and I'm running out of ideas.</p>
<p>Full code:</p>
<p><a href="https://github.com/TomHeatwole/osf-meetings/blob/feature/conference-tests/meetings/conferences/serializers.py" rel="nofollow">The serializer</a></p>
<p><a href="https://github.com/TomHeatwole/osf-meetings/blob/feature/conference-tests/meetings/conferences/tests.py" rel="nofollow">The test</a></p>
<p>Thanks so much, let me know if there's an easier way to go about this.</p>
<p><br><br></p>
<p>UPDATE:
So I went back in the two different debuggers and did <code>User.objects.all()</code>. The one in the server with the real request returned the correct list of users. The one in the test with the fake request just returned anonymoususer. Because I'm using factory_boy to create my fake users, django can't find it in <code>User.objects</code>.</p>
<p>I've been told not to make real requests in my unit tests, so creating an actual user is out of the question. </p>
<p>I also tried changing the <code>get_can_edit</code> function to not check <code>User.objects.</code>. <code>request.user</code> is a <code>SimpleLazyObject</code> containing the user. What I tried doing was <code>request.user.id</code> and comparing it to <code>obj.admin.id</code>, but apparently when you do pretty much anything to a <code>SimpleLazyObject</code>, it consults <code>User.objects</code> to get to the actual User associated with it, so it still had the same error <code>'User' object is not callable</code>. </p>
<p>So the bottom line is this: <strong>I need to add a fake user to <code>User.objects</code> without making a real request</strong></p>
| 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 line:</p>
<pre><code>class UserFactory(factory.Factory):
</code></pre>
<p>But apparently instead of <code>factory.Factory</code>, it was supposed to say <code>factory.DjangoModelFactory</code> like so:</p>
<pre><code>class UserFactory(factory.DjangoModelFactory):
</code></pre>
<p>This was a little obnoxious since the <code>factory_boy</code> <a href="https://factoryboy.readthedocs.io/en/latest/index.html" rel="nofollow">documentation</a> has an example on the first page with <code>factory.Factory</code> but later on tells you to use <code>DjangoModelFactory</code>. I guess that's what I get deserve for not reading the documentation thoroughly.</p>
| 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 &> 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 the questions <a href="http://stackoverflow.com/questions/11495783/redirect-subprocess-stderr-to-stdout">Redirect subprocess stderr to stdout</a>, <a href="http://stackoverflow.com/questions/1956142/how-to-redirect-stderr-in-python">How to redirect stderr in Python?</a>, and Example 10.10 from <a href="http://www.diveintopython.net/scripts_and_streams/stdin_stdout_stderr.html" rel="nofollow">here</a>, and then I tried the following:</p>
<pre><code>import sys
fsock = open('out.txt', 'w')
sys.stdout = sys.stderr = fsock
print "a"
</code></pre>
<p>which rightly prints the letter "a" in the file out.txt; however, when I try the following:</p>
<pre><code>import sys
fsock = open('out.txt', 'w')
sys.stdout = sys.stderr = fsock
print "a # missing end quote, will give error
</code></pre>
<p>I get the error message "SyntaxError ..." on the terminal, but not in the file out.txt. What do I need to do to send the SyntaxError to the file out.txt? I do not want to write an Exception, because in that case I have to write too many Exceptions in the script. I am using Python 2.7.</p>
<p>Update: As pointed out in the answers and comments below, that SyntaxError will always output to screen, I replaced the line</p>
<pre><code>print "a # missing end quote, will give error
</code></pre>
<p>by</p>
<pre><code>print 1/0 # Zero division error
</code></pre>
<p>The ZeroDivisionError is output to file, as I wanted to have it in my question.</p>
| 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 correct way to have an exception generated on purpose in your code - from simple test cases like yours, up to implementing complex flow control patterns, is to use the Pyton command <code>raise</code>.</p>
<p>Just leave your print there, and a line like this at the end:</p>
<pre><code>raise Exception
</code></pre>
<p>Then you can see that your trick will work.</p>
<p>Your program could fail in runtime in many other ways without an explict raise, like, if you force a division by 0, or simply try to use an unassigned (and therefore "undeclared") variable - but a deliberate SyntaxError will have the effect that the program never runs to start with - not even the first few lines.</p>
| 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, I could have Python connect to some list that contains all the URLs I need and it would iterate through the list and print all the scraped text into a single CSV. I've tried to write a "test" version of this code by creating a 2 URL long list and trying to get my code to scrape both URLs. However, as you can see, my code only scrapes the most recent url in the list and does not hold onto the first page it scraped. I think this is due to a deficiency in my print statement since it will always write over itself. Is there a way to have everything I scraped held somewhere until the loop goes through the entire list AND then print everything.</p>
<p>Feel free to totally dismantle my code. I know nothing of computer languages. I just keep getting assigned these tasks and use Google to do my best.</p>
<pre><code>import urllib
import re
from bs4 import BeautifulSoup
data_file_name = 'C:\\Users\\confusedanalyst\\Desktop\\python_test.csv'
urlTable = ['url1','url2']
def extractText(string):
page = urllib.request.urlopen(string)
soup = BeautifulSoup(page, 'html.parser')
##Extracts all paragraph and header variables from URL as GroupObjects
text = soup.find_all("p")
headers1 = soup.find_all("h1")
headers2 = soup.find_all("h2")
headers3 = soup.find_all("h3")
##Forces GroupObjects into str
text = str(text)
headers1 = str(headers1)
headers2 = str(headers2)
headers3 = str(headers3)
##Strips HTML tags and brackets from extracted strings
text = text.strip('[')
text = text.strip(']')
text = re.sub('<[^<]+?>', '', text)
headers1 = headers1.strip('[')
headers1 = headers1.strip(']')
headers1 = re.sub('<[^<]+?>', '', headers1)
headers2 = headers2.strip('[')
headers2 = headers2.strip(']')
headers2 = re.sub('<[^<]+?>', '', headers2)
headers3 = headers3.strip('[')
headers3 = headers3.strip(']')
headers3 = re.sub('<[^<]+?>', '', headers3)
print_to_file = open (data_file_name, 'w' , encoding = 'utf')
print_to_file.write(text + headers1 + headers2 + headers3)
print_to_file.close()
for i in urlTable:
extractText (i)
</code></pre>
| 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 mode points to a string beginning with one of the following
sequences (Additional characters may follow these sequences.):
``r'' Open text file for reading. The stream is positioned at the
beginning of the file.
``r+'' Open for reading and writing. The stream is positioned at the
beginning of the file.
``w'' Truncate file to zero length or create text file for writing.
The stream is positioned at the beginning of the file.
``w+'' Open for reading and writing. The file is created if it does not
exist, otherwise it is truncated. The stream is positioned at
the beginning of the file.
``a'' Open for writing. The file is created if it does not exist. The
stream is positioned at the end of the file. Subsequent writes
to the file will always end up at the then current end of file,
irrespective of any intervening fseek(3) or similar.
``a+'' Open for reading and writing. The file is created if it does not
exist. The stream is positioned at the end of the file. Subse-
quent writes to the file will always end up at the then current
end of file, irrespective of any intervening fseek(3) or similar.
</code></pre>
| 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>
<p>Traceback:</p>
<p>File
"/opt/conda/lib/python2.7/site-packages/django/core/handlers/base.py"
in get_response
149. response = self.process_exception_by_middleware(e, request)</p>
<p>File
"/opt/conda/lib/python2.7/site-packages/django/core/handlers/base.py"
in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)</p>
<p>File "/code/fileUpload_app/views.py" in msa_result
174. result1 = generate_hist(db, **processing_dict)</p>
<p>File "/code/fileUpload_app/post_processing.py" in generate_hist
182. fig1 = plt.figure()</p>
<p>File "/opt/conda/lib/python2.7/site-packages/matplotlib/pyplot.py" in
figure
527. **kwargs)</p>
<p>File
"/opt/conda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py"
in new_figure_manager
46. return new_figure_manager_given_figure(num, thisFig)</p>
<p>File
"/opt/conda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py"
in new_figure_manager_given_figure
53. canvas = FigureCanvasQTAgg(figure)</p>
<p>File
"/opt/conda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py"
in <strong>init</strong>
76. FigureCanvasQT.<strong>init</strong>(self, figure)</p>
<p>File
"/opt/conda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4.py"
in <strong>init</strong>
68. _create_qApp()</p>
<p>File
"/opt/conda/lib/python2.7/site-packages/matplotlib/backends/backend_qt5.py"
in _create_qApp
138. raise RuntimeError('Invalid DISPLAY variable')</p>
<p>Exception Type: RuntimeError at /upload/msa_result/1/ Exception Value:
Invalid DISPLAY variable</p>
</blockquote>
<p>I am using a docker to host my web project.</p>
<p>My code includes these :</p>
<pre><code>import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
def generate_hist(db, **kwargs):
fig1 = plt.figure()
hist = mat2[0, 0:pin_num]
fig1 = plt.hist(hist)
plt.savefig("fileUpload_app/static/img/result/hist.jpg")
</code></pre>
| 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 <em>distanceMatrixReturn</em> for this example.</p>
<pre><code> distanceMatrixReturn = {
{'destination_addresses': ['This would be ADDRESS 1'],
'status': 'OK',
'rows': [
{
'elements': [
{
'duration_in_traffic': {
'text': '10 mins', 'value': 619},
'status': 'OK',
'distance': {'text': '2.8 mi', 'value': 4563},
'duration': {'text': '9 mins', 'value': 540}}]}],
}]
}],
'origin_addresses': ['This would be ADDRESS 2']
}
</code></pre>
<p>Now, being a python newbie struggling with nested dictionaries and lists;
Here is my thought process:</p>
<p>I want to access the value <code>'2.8 mi'</code> that to my impression, is within a dictionary tied to the key 'text', which is in turn inside a dictionary assigned to the key <code>'distance'</code>, which is in another dictionary with the key <code>'duration_in_traffic'</code>.</p>
<p>The key <code>'duration_in_traffic'</code> seems to be within a list, tied to the dictionary key <code>'elements'</code>, which in turn is in a list tied to another dictionary key, <code>'rows'</code>.</p>
<p>Now, this seems very very convoluted and there must be an easy way to handle this situation, or maybe my logic is just off about the nested within nested elements and the method of accessing them.</p>
<p>For example, among other posts here, I've read the following to try and figure out the process of intepreting something seemingly similar. <a href="http://stackoverflow.com/questions/6521892/how-to-access-a-dictionary-key-value-present-inside-a-list">How to access a dictionary key value present inside a list?</a></p>
<p>Please let me know if I structured the distanceMatrixReturn on this post poorly. I spaced it to try and make it more readable, I hope I've achieved that.</p>
| 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 going to parse out the data the same way - you'll just break it out over different parts of your program.</p>
<p>As for which option is best - the needs of your program will dictate that.</p>
| 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 <em>distanceMatrixReturn</em> for this example.</p>
<pre><code> distanceMatrixReturn = {
{'destination_addresses': ['This would be ADDRESS 1'],
'status': 'OK',
'rows': [
{
'elements': [
{
'duration_in_traffic': {
'text': '10 mins', 'value': 619},
'status': 'OK',
'distance': {'text': '2.8 mi', 'value': 4563},
'duration': {'text': '9 mins', 'value': 540}}]}],
}]
}],
'origin_addresses': ['This would be ADDRESS 2']
}
</code></pre>
<p>Now, being a python newbie struggling with nested dictionaries and lists;
Here is my thought process:</p>
<p>I want to access the value <code>'2.8 mi'</code> that to my impression, is within a dictionary tied to the key 'text', which is in turn inside a dictionary assigned to the key <code>'distance'</code>, which is in another dictionary with the key <code>'duration_in_traffic'</code>.</p>
<p>The key <code>'duration_in_traffic'</code> seems to be within a list, tied to the dictionary key <code>'elements'</code>, which in turn is in a list tied to another dictionary key, <code>'rows'</code>.</p>
<p>Now, this seems very very convoluted and there must be an easy way to handle this situation, or maybe my logic is just off about the nested within nested elements and the method of accessing them.</p>
<p>For example, among other posts here, I've read the following to try and figure out the process of intepreting something seemingly similar. <a href="http://stackoverflow.com/questions/6521892/how-to-access-a-dictionary-key-value-present-inside-a-list">How to access a dictionary key value present inside a list?</a></p>
<p>Please let me know if I structured the distanceMatrixReturn on this post poorly. I spaced it to try and make it more readable, I hope I've achieved that.</p>
| 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 <em>distanceMatrixReturn</em> for this example.</p>
<pre><code> distanceMatrixReturn = {
{'destination_addresses': ['This would be ADDRESS 1'],
'status': 'OK',
'rows': [
{
'elements': [
{
'duration_in_traffic': {
'text': '10 mins', 'value': 619},
'status': 'OK',
'distance': {'text': '2.8 mi', 'value': 4563},
'duration': {'text': '9 mins', 'value': 540}}]}],
}]
}],
'origin_addresses': ['This would be ADDRESS 2']
}
</code></pre>
<p>Now, being a python newbie struggling with nested dictionaries and lists;
Here is my thought process:</p>
<p>I want to access the value <code>'2.8 mi'</code> that to my impression, is within a dictionary tied to the key 'text', which is in turn inside a dictionary assigned to the key <code>'distance'</code>, which is in another dictionary with the key <code>'duration_in_traffic'</code>.</p>
<p>The key <code>'duration_in_traffic'</code> seems to be within a list, tied to the dictionary key <code>'elements'</code>, which in turn is in a list tied to another dictionary key, <code>'rows'</code>.</p>
<p>Now, this seems very very convoluted and there must be an easy way to handle this situation, or maybe my logic is just off about the nested within nested elements and the method of accessing them.</p>
<p>For example, among other posts here, I've read the following to try and figure out the process of intepreting something seemingly similar. <a href="http://stackoverflow.com/questions/6521892/how-to-access-a-dictionary-key-value-present-inside-a-list">How to access a dictionary key value present inside a list?</a></p>
<p>Please let me know if I structured the distanceMatrixReturn on this post poorly. I spaced it to try and make it more readable, I hope I've achieved that.</p>
| 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) # -> "2.8 mi"
</code></pre>
<p>On Python 3 you will have to import <code>reduce</code> from <code>functools</code> first. </p>
| 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 predict(X,W):
return np.dot(X,W)
def gradient(X, Y, W, regTerm=0):
return (-np.dot(X.T, Y) + np.dot(np.dot(X.T,X),W))/(m*k) + regTerm * W /(n*k)
def cost(X, Y, W, regTerm=0):
m, k = Y.shape
n, k = W.shape
Yhat = predict(X, W)
return np.trace(np.dot(Y-Yhat,(Y-Yhat).T))/(2*m*k) + regTerm * np.trace(np.dot(W,W.T)) / (2*n*k)
def Rsquared(X, Y, W):
m, k = Y.shape
SSres = cost(X, Y, W)
Ybar = np.mean(Y,axis=0)
Ybar = np.matlib.repmat(Ybar, m, 1)
SStot = np.trace(np.dot(Y-Ybar,(Y-Ybar).T))
return 1-SSres/SStot
m = 10
n = 200
k = 1
trX = np.random.rand(m, n)
trX[:, 0] = 1
for i in range(2, n):
trX[:, i] = trX[:, 1] ** i
trY = trX[:, 1] ** 3 + 5
trY = np.reshape(trY, (m, k))
W = np.random.rand(n, k)
numIter = 10000
learningRate = 0.5
for i in range(0, numIter):
W = W - learningRate * gradient(trX, trY, W)
domain = np.linspace(0,1,100000)
powerDomain = np.copy(domain)
m = powerDomain.shape[0]
powerDomain = np.reshape(powerDomain, (m, 1))
powerDomain = np.matlib.repmat(powerDomain, 1, n)
for i in range(1, n):
powerDomain[:, i] = powerDomain[:, 0] ** i
print(Rsquared(trX, trY, W))
plt.plot(trX[:, 1],trY,'o', domain, predict(powerDomain, W),'r')
plt.show()
</code></pre>
<p>the R^2 I'm getting is very close to 1, meaning I found a very good fit to the training data, but it isn't shown on the plots. When I plot the data, it usually looks like this:</p>
<p><a href="http://i.stack.imgur.com/5KSNp.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/5KSNp.jpg" alt="enter image description here"></a></p>
<p>it looks as if I'm underfitting the data, but with such a complex hypothesis, with 200 features (meaning i allow polynomials up to x^200) and only 10 training examples, I should very clearly be overfitting data, so I expect the red line to pass through all the blue points and go wild between them.</p>
<p>This isn't what I'm getting which is confusing to me.
What's wrong?</p>
| 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 subprocess.check_output(). I know how I can ignore the error return code, but I don't want to do it this way.</p>
<p>So I have been thinking. Is there any way to get the number of items currently in stash? I know there is a command 'git stash list', but is there something more suited for my needs or some easy and safe way to parse the output of git stash list?</p>
<p>Also appreciate other approaches to solve this problem.</p>
| 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 subprocess.check_output(). I know how I can ignore the error return code, but I don't want to do it this way.</p>
<p>So I have been thinking. Is there any way to get the number of items currently in stash? I know there is a command 'git stash list', but is there something more suited for my needs or some easy and safe way to parse the output of git stash list?</p>
<p>Also appreciate other approaches to solve this problem.</p>
| 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 script code is to check the result of <code>git rev-parse refs/stash</code> before and after <code>git stash save</code>. If it <em>changes</em> (from failure to something, or something to something-else), you have created a new stash, which you can then pop when you are done.</p>
<p>More recent versions of Git have <code>git stash create</code>, which creates the commit-pair as usual but does not put them into the <code>refs/stash</code> reference. If there is nothing to save, <code>git stash create</code> does nothing and outputs nothing. This is a better way to deal with the problem, but is Git-version-dependent.</p>
| 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)
while True:
data_set_num = infile.readline()
if not data_set_num: break
for arr in (a, b, c):
new_arr = get_new_array(infile)
try:
arr = np.stack((arr, new_arr))
except:
arr = np.array(new_arr)
</code></pre>
<p>But after execution of the loop, I don't have anything:</p>
<pre><code>>>> a.shape
()
</code></pre>
<p>Same for <code>b</code> and <code>c</code>. Clearly I did not understand how <code>arr</code> references the three arrays. Anyone know how to do what I am trying to do? I can, of course, unroll the inner loop, but that seems horribly "unpythonic".</p>
| 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, new_arr))</code> or <code>np.array(new_arr)</code>, both of which return new arrays. The name <code>arr</code> gets bound to the new reference, not <code>a</code> or <code>b</code> or <code>c</code>.</p>
<p>A direct solution would be to make a list of arrays instead of using <code>a</code>, <code>b</code>, <code>c</code>. Do something like </p>
<pre><code>x = [np.array(0) for _ in range(3)]
while True:
data_set_num = infile.readline()
if not data_set_num:
break
for ind, arr in enumerate(x):
new_arr = get_new_array(infile)
try:
x[ind] = np.stack((arr, new_arr))
except:
x[ind] = np.array(new_arr)
</code></pre>
<p>There are a couple of major flaws here. For one thing, you should not be using <code>try...except</code> for something so simple. For another, if you must stack arrays together, try to do it all at once instead of doing incremental reallocations.</p>
<p>Also, your code appears to be looping over the same set of arrays over and over within the <code>while True:</code> loop.</p>
| 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)
while True:
data_set_num = infile.readline()
if not data_set_num: break
for arr in (a, b, c):
new_arr = get_new_array(infile)
try:
arr = np.stack((arr, new_arr))
except:
arr = np.array(new_arr)
</code></pre>
<p>But after execution of the loop, I don't have anything:</p>
<pre><code>>>> a.shape
()
</code></pre>
<p>Same for <code>b</code> and <code>c</code>. Clearly I did not understand how <code>arr</code> references the three arrays. Anyone know how to do what I am trying to do? I can, of course, unroll the inner loop, but that seems horribly "unpythonic".</p>
| 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(np.stack((arr, new_arr)))
except:
arrays.append(np.array(new_arr))
break
print str(arrays[0])
print str(arrays[1])
print str(arrays[2])
</code></pre>
| 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 is not allowed
</code></pre>
<p>This is because django always includes every single field in the update SQL, even if that field has not changed.</p>
<p>In Citus, you must pick a field to be your partitioning field, and then you cannot change it. So, when I'm saving an object, it doesn't like that the partition key is in the update statement, even if it didn't change.</p>
<p>I know that you can pass the <code>update_fields</code> keyword arg to the <code>save</code> method, but I'm wondering if I can somehow tell django to NEVER include a field when updating?</p>
| 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'])
return super(Class, self).save(**kwargs)
</code></pre>
<p>A more dynamic option, if you do not want to update this method everytime you change the fields of your class, would be to use the <a href="https://docs.djangoproject.com/en/1.9/ref/models/meta/#django.db.models.options.Options.get_fields" rel="nofollow"><code>Meta</code></a> API to get all fields of the class and exclude your partition field</p>
<pre><code>def save(self, **kwargs):
kwargs.setdefault(
'update_fields',
[f.name for f in self.__class__._meta.get_fields() if f.name != 'partition_field']
)
return super(Class, self).save(**kwargs)
</code></pre>
<p>There are several other methods by which Django will attempt to update your models. Maybe a base class that all your models inherit from that implement these methods would work</p>
| 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 iteration and I need guidance because 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 despite repeatedly looking a docs and examples.</p>
<p>If I was printing a report, I want a table looking like this (delimiter can be a space)</p>
<pre><code>MSEa Ca MSEb Cb
1421 7 1184 3
925 2 1077 4
</code></pre>
<p>so I can choose the smallest MSE and C pairing in each MSE column.</p>
<p>What I have is </p>
<pre><code>MSEV
[matrix([[ 1421]]), 7, matrix([[ 1184]]), 3, matrix([[ 925]]), 2, matrix([[ 1077]]), 4]
type(MSEPCV)
<type 'list'>
</code></pre>
<p>MSE is a scalar from matrix math,
MSEV is initiated as MSEV = [] {type(MSEPCV) },
MSEV is created from MSE {type(MSE) } and COUNT {type(COUNT) }</p>
<p>I thought it would be easiest to make everything a list and tried tolist() but the squackets remain.</p>
| 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 item in x, if x is a matrix
except AttributeError:
return x # if x is not a matrix or array, just return x
print([extract_number(x) for x in MSEV])
</code></pre>
<p>This will output the list in the standard way that Python displays lists</p>
<pre><code>[1421, 7, 1184, 3, 925, 2, 1077, 4]
</code></pre>
<p>To display it more nicely you can look into string formatting and do something like this:</p>
<pre><code>print("""MSEa Ca MSEb Cb
{:4}{:6}{:6}{:7}
{:4}{:6}{:6}{:7}""".format(*msev))
</code></pre>
| 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 iteration and I need guidance because 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 despite repeatedly looking a docs and examples.</p>
<p>If I was printing a report, I want a table looking like this (delimiter can be a space)</p>
<pre><code>MSEa Ca MSEb Cb
1421 7 1184 3
925 2 1077 4
</code></pre>
<p>so I can choose the smallest MSE and C pairing in each MSE column.</p>
<p>What I have is </p>
<pre><code>MSEV
[matrix([[ 1421]]), 7, matrix([[ 1184]]), 3, matrix([[ 925]]), 2, matrix([[ 1077]]), 4]
type(MSEPCV)
<type 'list'>
</code></pre>
<p>MSE is a scalar from matrix math,
MSEV is initiated as MSEV = [] {type(MSEPCV) },
MSEV is created from MSE {type(MSE) } and COUNT {type(COUNT) }</p>
<p>I thought it would be easiest to make everything a list and tried tolist() but the squackets remain.</p>
| 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 </p>
<ul>
<li><p>matrices: basically, never. <code>np.matrix</code> is an endless source of confusion. Better use arrays, use <code>dot</code> for matrix multiplication, or <code>@</code> operator if you can use python 3.5+ only.</p></li>
<li><p>arrays: use them when you know the dimensions and sizes (<code>shape</code>, in numpy parlance) in advance. </p></li>
<li><p>lists: use lists when you need to append/remove elements. </p></li>
</ul>
<p>As to how to convert things: given a list, <code>lst</code>, <code>np.asarray(lst)</code> is a numpy array. Given an array, <code>arr</code>, <code>arr.tolist()</code> is a list. Given a matrix, <code>np.asarray</code> conveerts it into an array, and if your matrix is 1-by-1, <code>m[0, 0]</code> is a scalar.</p>
| 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 iteration and I need guidance because 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 despite repeatedly looking a docs and examples.</p>
<p>If I was printing a report, I want a table looking like this (delimiter can be a space)</p>
<pre><code>MSEa Ca MSEb Cb
1421 7 1184 3
925 2 1077 4
</code></pre>
<p>so I can choose the smallest MSE and C pairing in each MSE column.</p>
<p>What I have is </p>
<pre><code>MSEV
[matrix([[ 1421]]), 7, matrix([[ 1184]]), 3, matrix([[ 925]]), 2, matrix([[ 1077]]), 4]
type(MSEPCV)
<type 'list'>
</code></pre>
<p>MSE is a scalar from matrix math,
MSEV is initiated as MSEV = [] {type(MSEPCV) },
MSEV is created from MSE {type(MSE) } and COUNT {type(COUNT) }</p>
<p>I thought it would be easiest to make everything a list and tried tolist() but the squackets remain.</p>
| 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]: alist=[matrix([[ 1421]]), 7, matrix([[ 1184]]), 3, matrix([[ 925]]), 2, matrix([[ 1077]]), 4]
In [376]: alist
Out[376]:
[matrix([[1421]]),
7,
matrix([[1184]]),
3,
matrix([[925]]),
2,
matrix([[1077]]),
4]
</code></pre>
<p>I'll run it through a list comprehension with a <code>ifelse</code> expression that extracts the element from the matrices. I could also have defined a simple helper function as Stuart did:</p>
<pre><code>In [379]: newlist=[x[0,0] if isinstance(x,np.matrix) else x for x in alist]
In [380]: newlist
Out[380]: [1421, 7, 1184, 3, 925, 2, 1077, 4]
</code></pre>
<p>now turn it into an array - and use reshape to make it 2 rows.</p>
<pre><code>In [381]: Marray=np.array(newlist).reshape(2,-1)
In [382]: Marray
Out[382]:
array([[1421, 7, 1184, 3],
[ 925, 2, 1077, 4]])
</code></pre>
<p><code>np.savetxt</code> is the <code>numpy</code> function to write <code>csv</code> style files:</p>
<pre><code>In [386]: np.savetxt('test.txt',Marray)
In [387]: cat test.txt
1.421000000000000000e+03 7.000000000000000000e+00 1.184000000000000000e+03 3.000000000000000000e+00
9.250000000000000000e+02 2.000000000000000000e+00 1.077000000000000000e+03 4.000000000000000000e+00
</code></pre>
<p>Oops, default format is float; change that to integer:</p>
<pre><code>In [388]: np.savetxt('test.txt',Marray, '%d')
</code></pre>
<p>and look at the resulting file (just like doing <code>cat</code> in a linux shell)</p>
<pre><code>In [389]: cat test.txt
1421 7 1184 3
925 2 1077 4
</code></pre>
<p>and with a header line:</p>
<pre><code>In [392]: np.savetxt('test.txt',Marray, '%d',header='MSEa Ca MSEb Cb')
In [393]: cat test.txt
# MSEa Ca MSEb Cb
1421 7 1184 3
925 2 1077 4
</code></pre>
<p>Format can be refined, but that gives the idea.</p>
| 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 script. any idea how interrupt the "running" of the script??</p>
<p>the code which i have write as now:</p>
<pre><code>import string
X=[]
Y=[]
with open('D:/test_data/CLOUDS1.txt') as f:
content = f.readlines()
for line in content:
row = line.split()
X.append(row[0])
Y.append(row[1])
for i in X,Y:
print i
for j in Y:
j.replace(',' , '.')
print j
</code></pre>
<p>Q4) how i can make a list of point from X,Y??</p>
| -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 script. any idea how interrupt the "running" of the script??</p>
<p>the code which i have write as now:</p>
<pre><code>import string
X=[]
Y=[]
with open('D:/test_data/CLOUDS1.txt') as f:
content = f.readlines()
for line in content:
row = line.split()
X.append(row[0])
Y.append(row[1])
for i in X,Y:
print i
for j in Y:
j.replace(',' , '.')
print j
</code></pre>
<p>Q4) how i can make a list of point from X,Y??</p>
| -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
content = f.readlines() # Reads the rest of the lines
</code></pre>
<h2>Question 2 and 4</h2>
<p>Assuming your file content looks similar to</p>
<pre><code>x_coord y_coord
23,4 45,6
15,6 24,1
65,2 96,03
</code></pre>
<p>When replacing parts of a string, the string is not changed in-place. You have to assign the result of the replace call to a new variable and use it:</p>
<pre><code>points = []
for l in content:
parts = l.split()
x = float(parts[0].replace(',', '.'))
y = float(parts[1].replace(',', '.'))
points.append([x, y])
</code></pre>
<p>Or, in condensed form:</p>
<pre><code>points = [[float(p.replace(',', '.')) for p in l.split()] for l in content]
</code></pre>
<p>The result in either case is a 2-dimensional list (i.e. a list of lists) where each element in the outer list is a list with 2 elements representing the <code>x</code> and <code>y</code> coordinates of your points:</p>
<pre><code>[[23.4, 45.6], [15.6, 24.1], [65.2, 96.03]]
</code></pre>
| 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>) where my code does some data analysis and then 1) displays some results and 2) saves some other information to JSON, which is to be used for D3 in its own <code>@app.route(/visualization/)</code>. Because of complications with Javascript, I want to display my D3 visualization in an <code>iframe</code> of its own. Right now I can load the <code>/home/</code> page, type in text and hit "Submit", which then redirects me to <code>/results/</code>, and prints everything correctly except the <code>iframe</code>. The problem is: I'm unable to get <code>@app.route(/visualization/)</code> to take information from my WTForm (in the same way that <code>results</code> is able to), so that the image can load the proper JSON file.</p>
<p>Here's some of my code to better illustrate the problem.</p>
<p><code>app.py</code>: </p>
<pre><code># Home
@app.route("/home/", methods=["GET", "POST"])
def gohome():
error = None
with open('somedata.pickle', 'rb')as f:
some_content = pickle.load(f)
try:
if request.method == "POST":
attempted_pmid = request.form['pmid']
except Exception as e:
#flash(e)
return render_template("dashboard.html", error=error)
return render_template("dashboard.html", some_content=some_content)
# My WTForm for handling user-entered pmids
class pmidForm(Form):
pmid = TextField('PubmedID')
# Results
@app.route("/results/", methods=["GET", "POST"])
def trying():
form = pmidForm(secret_key='potato')
try:
if request.method == 'POST':
entry = form.pmid.data #THIS IS THE USER INPUT FROM THE FORM #referencing 'class pmidForm'
pmid_list = multiple_pmid_input(entry) #list for handling multiple pmids
print(pmid_list)
for user_input in pmid_list:
print(str(user_input))
user_input = str(user_input)
# DO STUFF HERE #
# SAVE A JSON FILE TO A FOLDER #
return render_template('results.html')
except Exception as e:
return(str(e))
# Visualization
@app.route('/visualization/', methods=["GET", "POST"]) #for iframe
def visualization():
#need to get last user_input
form = pmidForm(secret_key='potato')
try:
if request.method == 'POST':
entry = form.pmid.data
pmid_list = multiple_pmid_input(entry)
for user_input in pmid_list:
print("This is the user input on /visualization/")
print(str(user_input))
user_input = str(user_input)
#Load
if user_input == pmid_list[-1]:
load_path = '/the/path/'+str(user_input)+'/'
completeName = os.path.join(load_path, ((str(user_input))+'.json'))
print(completeName)
with open(completeName, 'w') as load_data:
jsonDict = json.load(load_data)
print(jsonDict)
return render_template('visualization.html', jsonDict=jsonDict)
except Exception as e:
return(str(e))
</code></pre>
<p>So as I have it now, <code>home</code> and <code>results</code> work fine together with the existing WTForm I have. I will do everything properly. But in <code>results.html</code> I need to load <code>visualization.html</code> in an <code>iframe</code> like so:</p>
<p>Line in <code>results.html</code>: </p>
<pre><code><iframe id="vis1" src="https://www.website.com/visualization/" width="1000" height="1000"></iframe>
</code></pre>
<p>With this configuration if I run my <code>app.py</code>, everything displays like normal except the <code>iframe</code> which displays:</p>
<blockquote>
<p>local variable 'jsonDict' referenced before assignment</p>
</blockquote>
<p>Here, I assume that's in reference to my <code>visualization.html</code> which has the Jinja code:</p>
<pre><code>var myjson = {{ jsonDict|tojson }};
</code></pre>
<p>So obviously the <code>@app.route(/visualization/)</code> isn't getting the information from the WTForm as it should. How can I get this second <code>@app.route</code> to recognize the content in the WTForm like how it works with <code>results</code>?</p>
<p>Also, this may seem hacky, but I have very good reasons for putting my D3 in an <code>iframe</code>. It's because I need to be able to toggle through multiple html's like <code>/visualization</code>/ that each have complicated Javascript that conflict with each other. The best thing I can do is isolate them all in <code>iframe</code>'s. </p>
| 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 way I was able to access the "1234" and use it in that html. </p>
| 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
11 A
12 a
13 b
14 b
15 c
16 c
In[16]: df.ix[12, "s"] = 'B'
In[17]: df
Out[17]:
s
11 A
12 B
13 b
14 b
15 c
16 c
</code></pre>
<p>Is it possible to do the same based on position not index value, something like this, but it shows ValueError (<code>ValueError: Can only index by location with a [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array]</code>):</p>
<pre><code>In[18]: df.iloc[1, "s"] = 'b'
</code></pre>
<p>And, if I try something like this:</p>
<pre><code>df.s.iloc[1] = "b"
</code></pre>
<p>I get this warning : </p>
<pre><code>SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
</code></pre>
| 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 source that 'implied' that python could be embedded into php. So my question is, is there a way to write up a python script, embed it into php, then take that php and embed it into html? If so, how? Thanks.</p>
| -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><head><title>Hello</title></head>
<body>
Hello HTML WORLD!!!
</body>
</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 if you visit the page you will see the same content ... so lets add something for php to do</p>
<p>index.php</p>
<pre><code><head><title>Hello</title></head>
<body>
Hello <?php echo "PHP"; ?>WORLD!!!
</body>
</code></pre>
<p>see we ran a little bit of php code there</p>
<p>you can call an external program from php like</p>
<pre><code><?php
$result = exec('python some_script.py');
?>
</code></pre>
<p>but really it sounds like whatever you are trying to do is absolutely the wrong way to go about it ...</p>
<p>just use a python web framework like <code>django</code>(if you need lots of features) or <code>flask</code> if you just need something simple</p>
<p>actually it sounds like <a href="http://php.net/manual/en/function.passthru.php" rel="nofollow">http://php.net/manual/en/function.passthru.php</a></p>
<p><code><?php passthrough(command); ?></code></p>
<p>is more what you want ...</p>
| 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 following directories: Home/USB storage/DCIM/MyScreenshot.png</p>
<p>however, when I add this to my python kivy script, repackage the aplication and run it on my phone once more the program quits as soon as I press the save button.</p>
<p>I am thinking that there is some other way, perhaps that one should not add the directory in front of the name, but I am not sure, please any help welcome.</p>
<p>Regards
Cid-El</p>
<p>ps. I don't think it neccesary to add my code, however just leave me a comment if you would like me to add it</p>
| 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 following directories: Home/USB storage/DCIM/MyScreenshot.png</p>
<p>however, when I add this to my python kivy script, repackage the aplication and run it on my phone once more the program quits as soon as I press the save button.</p>
<p>I am thinking that there is some other way, perhaps that one should not add the directory in front of the name, but I am not sure, please any help welcome.</p>
<p>Regards
Cid-El</p>
<p>ps. I don't think it neccesary to add my code, however just leave me a comment if you would like me to add it</p>
| 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 setting is x:
package.someFunction(x=1)
elif setting is y:
package.someFunction(y=1)
elif setting is z:
package.someFunction(z=1)
</code></pre>
<p>Is there a more pythonic way to do it? Can I assign the parameter name to some variable pass it that way?</p>
| 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> line to be however you're getting that setting. It just needs to equal the name of the argument in <code>package.someFunction</code> that you want to apply the value to.</p>
| 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 initial thought was just to have the user open up the python program and change the addresses to whatever they want and then run it, but I came into a few problems</p>
<ol>
<li>That's probably not the best practice to let the user do that</li>
<li>The user needs python installed</li>
<li>If I create an executable from my current code, the user won't be able to change the addresses to what they want</li>
</ol>
<p>What would be the best way to allow users to enter their own addresses? The point of this script was to automate a proccess so getting user input didn't really make sense for me to do</p>
| 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 does not have to install it separately.</p>
<ol>
<li>Use a configuration file that the script reads the addresses from.</li>
<li>Pass the addresses as arguments on the command line.</li>
<li>Ask a network service for the addresses.</li>
</ol>
| 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 uNormalize (u):
r = [0.0] * 2
u_len = uLength(u)
if u_len > 0.0:
u_invLen = 1.0 / u_len
r[0] = u[0] * u_invLen
r[1] = u[1] * u_invLen
return r
def angle(dotProduct):
return math.degrees(math.acos(dotProduct))
p1,p2 = (0,0),(1,1) #<---- edge 1
p3,p4 = (0,0),(1,0) #<---- edge 2
dir = uDirection(p1,p2)
dir2 = uDirection(p3,p4)
dir_n = uNormalize(dir)
dir2_n = uNormalize(dir2)
dotProduct = dotUV(dir_n, dir2_n)
ang1 = angle(dotProduct)
#ang1 = 45
</code></pre>
<p>The angle of difference is 45 degrees, if I want to then rotate edge 2 (p3,p4) to match edge 1 (p1,p2), I need to determine if the rotation needed is clockwise or counterclockwise. Currently its counter-clockwise but if the positions of the edges were reversed, it would still give me 45 degrees of difference but the direction edge 2 would have to move would be clockwise. Is there a way I can modify what I have to determine clockwise v. counterclockwise?</p>
| 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] < 0:
pass # Rotate CW
else
pass # Rotate CCW
</code></pre>
<p>Should do the trick.</p>
<p>If you intend to rotate <code>e2</code> step-wise on a timely basis, you need to control your rotation speed along with the <code>dt</code> (time delta between current and last frame) similar to:</p>
<pre><code>rotspeed = .5 # Whatever suits your framerate and desired speed
if e1[0] * e2[1] - e1[0] * e2[1] < 0:
angle = 2 * math.pi - rotspeed * dt # Rotate CW
else:
angle = rotspeed * dt # Rotate CCW
x = math.cos(math.atan2(e2[0], e2[1]) + angle)
y = math.sin(math.atan2(e2[0], e2[1]) + angle)
next_e2 = [x, y]
</code></pre>
| 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 uNormalize (u):
r = [0.0] * 2
u_len = uLength(u)
if u_len > 0.0:
u_invLen = 1.0 / u_len
r[0] = u[0] * u_invLen
r[1] = u[1] * u_invLen
return r
def angle(dotProduct):
return math.degrees(math.acos(dotProduct))
p1,p2 = (0,0),(1,1) #<---- edge 1
p3,p4 = (0,0),(1,0) #<---- edge 2
dir = uDirection(p1,p2)
dir2 = uDirection(p3,p4)
dir_n = uNormalize(dir)
dir2_n = uNormalize(dir2)
dotProduct = dotUV(dir_n, dir2_n)
ang1 = angle(dotProduct)
#ang1 = 45
</code></pre>
<p>The angle of difference is 45 degrees, if I want to then rotate edge 2 (p3,p4) to match edge 1 (p1,p2), I need to determine if the rotation needed is clockwise or counterclockwise. Currently its counter-clockwise but if the positions of the edges were reversed, it would still give me 45 degrees of difference but the direction edge 2 would have to move would be clockwise. Is there a way I can modify what I have to determine clockwise v. counterclockwise?</p>
| 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 angle which translates to the direction of rotation:</p>
<pre><code>def angle(dotProduct):
sign = math.asin(dotProduct) // abs(math.asin(dotProduct))
return sign * math.degrees(math.acos(dotProduct))
</code></pre>
<p>A <code>+ve</code> will mean clockwise and <code>-ve</code> coounterclockwise, or vice-versa.</p>
| 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 there are no friendly line breaks in this code; imagine fully minified code. I have just added breaks so it's easier to visualize. But, any actual solution to this would not be able to rely on line breaks or spaces since they will not exist in reality.</p>
<pre><code><tr id="link">
<td><a href="https://www.somewebsite.com" target="_target">Title</a></td>
<td>Value 1</td><td style="width:20ch">Value 2</td>
<td></td><td></td><td>Value 3</td>
<td>Value 4</td><td>Value 5</td><td>Value 6</td>
<td>Value 7</td><td>Value 8</td><td>Value 9</td></tr>
</code></pre>
<p>My desired output from this is <code>https://www.somewebsite.com, Title, Value 1, Value 2, , , Value 3, ...</code> (etc.)</p>
<p>Basically, I want to replace all values in tags with commas but retain the URL. I cannot find any way in Python to parse something like this since the scan(), find(), etc. functions in Python do not seem to keep track of the file pointer globally as I'm used to in languages like C. So, no matter what I do I'm continually just looking at the beginning of the line.</p>
| 0 | 2016-08-04T20:34:27Z | 38,883,925 | <pre><code>from bs4 import BeautifulSoup
html_doc = """
<tr id="link">
<td><a href="https://www.somewebsite.com" target="_target">Title</a></td>
<td>Value 1</td><td style="width:20ch">Value 2</td>
<td></td><td></td><td>Value 3</td>
<td>Value 4</td><td>Value 5</td><td>Value 6</td>
<td>Value 7</td><td>Value 8</td><td>Value 9</td></tr>"""
for tr in BeautifulSoup(html_doc, 'html.parser').find_all('tr'):
row = []
for td in tr.find_all('td'):
anchor = td.find('a')
row.extend([anchor['href'], anchor.text] if anchor else [td.text])
print(', '.join(row))
</code></pre>
| 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 = open("slist.txt","r")
for num in host_list:
do
for aline in sfile.realines():
if num =! aline.split()
print num
sfile.close()
</code></pre>
| -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_file]
sfile.close()
</code></pre>
| 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.</p></li>
<li><p>If the middle button is pressed, the turtle should change to a different random color.</p></li>
<li><p>You should also change the color if the use presses the space bar.</p></li>
</ul>
<p>Any suggestions on how to start?</p>
<p>Here is some code I have tried so far:</p>
<pre><code>def k2(x,y): turtle.penup() turtle.setposition(x,y) turtle.pendown() turtle.circle(radius)
</code></pre>
<p>This is the top from turtle </p>
<pre><code>import * setup(500, 500) Screen() title("Turtle Keys") move = Turtle() showturtle()
</code></pre>
<p>This is the bottom </p>
<pre><code>onkey(k1, "Up") onkey(k2, "Left") onkey(k3, "Right") onkey(k4, "Down") listen() mainloop()
</code></pre>
| 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
colors = ["red", "orange", "yellow", "green", "blue", "violet"]
radius = 10
width = 20
LEFT, MIDDLE, RIGHT = 1, 2, 3
def k1(x=None, y=None): # dummy arguments so can be a click or key
turtle.color(random.choice(colors))
def k2(x, y):
turtle.penup()
turtle.setposition(x, y)
turtle.pendown()
for _ in range(4):
turtle.forward(width)
turtle.right(90)
def k3(x, y):
turtle.penup()
turtle.setposition(x, y)
turtle.pendown()
turtle.circle(radius)
turtle.setup(500, 500)
turtle.Screen().title("Turtle Keys")
turtle.onkey(k1, " ")
turtle.onscreenclick(k2, btn=LEFT)
turtle.onscreenclick(k1, btn=MIDDLE)
turtle.onscreenclick(k3, btn=RIGHT)
turtle.listen()
turtle.mainloop()
</code></pre>
| 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 to keep the number the same as the last. This is subset of my current ID and TRUE columns, and GROUP is shown as desired. I also have columns LATITUDE and LONGITUDE that I use in my sort.</p>
<pre><code>ID TRUE GROUP
3828 0 1
3828 0 2
3828 1 2
3828 1 2
3828 1 2
4529 0 1
4529 1 1
4529 0 2
4529 1 2
4529 0 3
4529 0 4
4529 1 4
4529 0 5
4529 1 5
4529 1 5
</code></pre>
<p>I was hoping to do something like below, but this is giving me all 0s</p>
<pre><code>trip.registerTempTable("trip_temp")
trip2 = sqlContext.sql('select *, sum(cast(TRUE = 0 as int)) over(partition by ID order by ID, LATITUDE, LONGITUDE) as GROUP from trip_temp')
</code></pre>
| 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>TRUE IS NOT TRUE</code>)</p>
<pre><code>spark.createDataFrame(
[(3828, 0, 1), (3828, 1, 2)], ("ID", "TRUE", "GROUP")
).createOrReplaceTempView("trip_temp")
spark.sql("SELECT TRUE = 0 AS foo FROM trip_temp LIMIT 2").show()
// +-----+
// | foo|
// +-----+
// |false|
// |false|
// +-----+
</code></pre>
<p>If you really want to make it work use backticks:</p>
<pre><code>spark.sql("SELECT `TRUE` = 0 AS foo FROM trip_temp LIMIT 2").show()
// +-----+
// | foo|
// +-----+
// | true|
// |false|
// +-----+
</code></pre>
<p>but please don't.</p>
| 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 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
WARNING: No route found for IPv6 destination :: (no default route?). This affects only IPv6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/anaconda3/lib/python3.5/site-packages/pandas/__init__.py", line 13, in <module>
__import__(dependency)
File "/usr/local/anaconda3/lib/python3.5/site-packages/pytz/__init__.py", line 29, in <module>
from pkg_resources import resource_stream
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 664, in _load_unlocked
File "<frozen importlib._bootstrap>", line 634, in _load_backward_compatible
File "/usr/local/anaconda3/lib/python3.5/site-packages/setuptools-20.3-py3.5.egg/pkg_resources/__init__.py", line 71, in <module>
File "path/parser.py", line 62, in <module>
file_temp = sys.argv[1]
IndexError: list index out of range
</code></pre>
<p>Using Ipython instead of python works for some reason:</p>
<pre><code>[path]$ ipython
Python 3.5.2 |Anaconda custom (64-bit)| (default, Jul 2 2016, 17:53:06)
Type "copyright", "credits" or "license" for more information.
IPython 5.0.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: import pandas as pd
In [2]:
</code></pre>
<p>To add more weirdness I can not connect to any kernels using jupyter hub in this directory.</p>
<p>EDIT: This appears to be a problem with importing pandas anywhere on this machine if there is a file called parser.py. The problem does not happen on my laptop. This machine has Anaconda my laptop does not. I don't have a solution on how to fix the problem though.</p>
| 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 directory is first in the python path it will attempt to use the wrong file as a dependency. One way that this can be used to your advantage is if you want to hot patch a specific file in a library without altering the whole library.</p>
| 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 used this to start myself off but I've run into an issue already, probably because of the Django version I'm using.</p>
<p><a href="http://patrick.arminio.info/additional-admin-views/" rel="nofollow">http://patrick.arminio.info/additional-admin-views/</a></p>
<p>The issue I'm having is</p>
<pre><code>TypeError at /admin/customers/order/1/review/
review() missing 1 required positional argument: 'id'
</code></pre>
<p>I'm not entirely sure how to fix this. My code is here:</p>
<pre><code>class OrderAdmin(admin.ModelAdmin):
review_template = 'review.html'
def get_urls(self):
urls = super(OrderAdmin, self).get_urls()
review_urls = patterns('',
(r'\d+/review/$', self.admin_site.admin_view(self.review)),
)
return review_urls + urls
def review(self, request, id):
order = Order.objects.get(pk=id)
return render_to_response(self.review_template, {
'title': 'Review order: %s' % order.id,
'entry': order,
'opts': self.model._meta,
'root_path': self.admin_site.urls,
}, context_instance=RequestContext(request))
</code></pre>
<p>I'm new to Django and most useful information is in the Book, not the docs, which is far to long for Django to call itself <em>The web framework for perfectionists with deadlines.</em></p>
| 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<id>\d+)/review/$',
</code></pre>
| 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 a:
current = a[key_to_find]
a[key_to_find] = int(current) + aantaltoevoeging
def Toevoeging_methode_minus(key_to_find, definition):
if key_to_find in a:
current = a[key_to_find]
a[key_to_find] = int(current) - aantaltoevoeging
a = {}
with open("variabelen.csv") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
a[row['Product']] = row['Aantal']
print a
print("""
1. Toevoegen
2. Aftrek
3. Check
""")
askmenu = int(raw_input("Menu Nummer? "))
if askmenu is 1:
toevoegproduct = raw_input("Productnummer > ")
aantaltoevoeging = int(raw_input("Hoeveel > "))
Toevoeging_methode_plus(toevoegproduct, aantaltoevoeging)
print a
elif askmenu is 2:
toevoegproduct = raw_input("Productnummer > ")
aantaltoevoeging = int(raw_input("Hoeveel > "))
Toevoeging_methode_minus(toevoegproduct, aantaltoevoeging)
print a
elif askmenu is 3:
checknummer = raw_input("Productnummer > ")
if checknummer in a:
print a[checknummer]
else:
print "oops"
</code></pre>
| 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.DictReader(csvfile, delimiter=',')
for row in reader:
a[row['Product']] = row['Aantal']
print a
</code></pre>
<p>Output:</p>
<pre><code>{'233': '60'}
{'2234': '1', '233': '60'}
1. Toevoegen
2. Aftrek
3. Check
Menu Nummer? 1
Productnummer > 233
Hoeveel > 1
{'2234': '1', '233': 61}
</code></pre>
<p>Now the value of <code>233</code> is becoming 61 which is expected</p>
| 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
</code></pre>
<p>You can convert a hex value to an int with <code>int("ff462", 16)</code>. How can I read in the data making sure that the first two columns are converted to dtype uint32?</p>
| 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
</code></pre>
<p>You can convert a hex value to an int with <code>int("ff462", 16)</code>. How can I read in the data making sure that the first two columns are converted to dtype uint32?</p>
| 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 recent comments of all the threads combined. It does not care about individual threads currently. Any ideas on how to limit the bot to only reply to one comment per thread?</p>
<p>Thanks</p>
| 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 be removed manually or whole lot of other scenarios. So probably best approach now is to do it dynamically and if it slows bot down later on you might consider adding above methods as lookup for faster responses.</p>
<p>What I'm talking about now is everytime you check comment, you should get <code>submission_id</code> and scan all comments to make sure no bot reply has ben added yet (or ceratian threshold has not been passed).</p>
<pre><code>def scan():
for c in reddit_client.get_comments('chosen_subreddit'):
if keyword not in c.body.lower(): #check main requirement
continue
if c.author == None: #comment deleted
continue
if c.author.name == bot_name: #don't bother with comments made by bot
continue
answer(c,c.link_id[3:])
def answer(comment, sub_id)
sub = reddit_client.get_submission(submission_id=sub_id)
sub.replace_more_comments(limit=None,threshold=0)
flat_comments = praw.helpers.flatten_tree(sub.comments)
if len([com for com in flat_comments if com.author != None and com.author.name.lower() == bot_name.lower()]) > 0:
return False
#here you can prepare response and do other stuff
#....
#....
comment.reply(prepared_response)
return True
</code></pre>
| 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)
except:
give_up_and_move_on()
else:
process_data()
else:
process_data()
</code></pre>
<p>I was wondering if there's a way to eliminate one of the else clauses, since they're the same code.</p>
| 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 >= MAX_RETRIES:
give_up_and_move_on()
</code></pre>
| 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</code> and <code>numpy</code>. </p>
<p>When I use Python from the command line, I can successfully import <code>matplotlib</code>:</p>
<pre><code>$ python3
>>> import matplotlib
>>> # no error
</code></pre>
<p>However, when I try and import <code>matplotlib</code> from an iPython notebook inside of Jupyterhub, I'm told no such module exists:</p>
<pre><code>import matplotlib
-----------------------
ImportError
...
ImportError: No module named 'matplotlib'
</code></pre>
<p>Why does Jupyterhub not recognize the module despite my being able to use it through other means? </p>
| 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/python3/kernel.json
...
{
"argv": [
"/PATH/TO/ANACONDA/bin/python",
</code></pre>
| 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 http://pypi.python.org/simple/Pillow/
Best match: Pillow 3.3.0
Downloading https://pypi.python.org/packages/e0/27/f61098a12f14690689924de93ffdd101463083a80bf8ff3e0c218addf05b/Pillow-3.3.0.tar.gz#md5=b5a15b03bf402fe254636c015fcf04da
Processing Pillow-3.3.0.tar.gz
Running Pillow-3.3.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-c1OEYc/Pillow-3.3.0/egg-dist-tmp-iwARkP
Single threaded build, not installing mp_compile:1 processes
warning: no files found matching '*.sh'
no previously-included directories found matching 'docs/_static'
warning: no previously-included files found matching '.coveragerc'
warning: no previously-included files found matching '.editorconfig'
warning: no previously-included files found matching '.landscape.yaml'
warning: no previously-included files found matching 'appveyor.yml'
warning: no previously-included files found matching 'build_children.sh'
warning: no previously-included files found matching 'tox.ini'
warning: no previously-included files matching '.git*' found anywhere in distribution
warning: no previously-included files matching '*.pyc' found anywhere in distribution
warning: no previously-included files matching '*.so' found anywhere in distribution
--------------------------------------------------------------------
PIL SETUP SUMMARY
--------------------------------------------------------------------
version Pillow 3.3.0
platform linux2 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3]
--------------------------------------------------------------------
--- JPEG support available
*** OPENJPEG (JPEG2000) support not available
--- ZLIB (PNG/ZIP) support available
*** LIBIMAGEQUANT support not available
*** LIBTIFF support not available
--- FREETYPE2 support available
*** LITTLECMS2 support not available
*** WEBP support not available
*** WEBPMUX support not available
--------------------------------------------------------------------
To add a missing option, make sure you have the required
library and headers.
To check the build, run the selftest.py script.
Adding Pillow 3.3.0 to easy-install.pth file
Installing pilfont.py script to /usr/local/bin
Installing thresholder.py script to /usr/local/bin
Installing gifmaker.py script to /usr/local/bin
Installing viewer.py script to /usr/local/bin
Installing createfontdatachunk.py script to /usr/local/bin
Installing enhancer.py script to /usr/local/bin
Installing pilconvert.py script to /usr/local/bin
Installing pilfile.py script to /usr/local/bin
Installing player.py script to /usr/local/bin
Installing explode.py script to /usr/local/bin
Installing pildriver.py script to /usr/local/bin
Installing painter.py script to /usr/local/bin
Installing pilprint.py script to /usr/local/bin
Installed /usr/local/lib/python2.7/dist-packages/Pillow-3.3.0-py2.7-linux-armv6l.egg
Processing dependencies for Pillow
Finished processing dependencies for Pillow
</code></pre>
<p>And the output of the error:</p>
<pre><code>root@rasp01:/data/server# python
Python 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import Image
Illegal instruction
root@rasp01:/data/server#
</code></pre>
<p>Does anyone have an idea what is wrong here? Thanks in advance! </p>
| 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 http://pypi.python.org/simple/Pillow/
Best match: Pillow 3.3.0
Downloading https://pypi.python.org/packages/e0/27/f61098a12f14690689924de93ffdd101463083a80bf8ff3e0c218addf05b/Pillow-3.3.0.tar.gz#md5=b5a15b03bf402fe254636c015fcf04da
Processing Pillow-3.3.0.tar.gz
Running Pillow-3.3.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-c1OEYc/Pillow-3.3.0/egg-dist-tmp-iwARkP
Single threaded build, not installing mp_compile:1 processes
warning: no files found matching '*.sh'
no previously-included directories found matching 'docs/_static'
warning: no previously-included files found matching '.coveragerc'
warning: no previously-included files found matching '.editorconfig'
warning: no previously-included files found matching '.landscape.yaml'
warning: no previously-included files found matching 'appveyor.yml'
warning: no previously-included files found matching 'build_children.sh'
warning: no previously-included files found matching 'tox.ini'
warning: no previously-included files matching '.git*' found anywhere in distribution
warning: no previously-included files matching '*.pyc' found anywhere in distribution
warning: no previously-included files matching '*.so' found anywhere in distribution
--------------------------------------------------------------------
PIL SETUP SUMMARY
--------------------------------------------------------------------
version Pillow 3.3.0
platform linux2 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3]
--------------------------------------------------------------------
--- JPEG support available
*** OPENJPEG (JPEG2000) support not available
--- ZLIB (PNG/ZIP) support available
*** LIBIMAGEQUANT support not available
*** LIBTIFF support not available
--- FREETYPE2 support available
*** LITTLECMS2 support not available
*** WEBP support not available
*** WEBPMUX support not available
--------------------------------------------------------------------
To add a missing option, make sure you have the required
library and headers.
To check the build, run the selftest.py script.
Adding Pillow 3.3.0 to easy-install.pth file
Installing pilfont.py script to /usr/local/bin
Installing thresholder.py script to /usr/local/bin
Installing gifmaker.py script to /usr/local/bin
Installing viewer.py script to /usr/local/bin
Installing createfontdatachunk.py script to /usr/local/bin
Installing enhancer.py script to /usr/local/bin
Installing pilconvert.py script to /usr/local/bin
Installing pilfile.py script to /usr/local/bin
Installing player.py script to /usr/local/bin
Installing explode.py script to /usr/local/bin
Installing pildriver.py script to /usr/local/bin
Installing painter.py script to /usr/local/bin
Installing pilprint.py script to /usr/local/bin
Installed /usr/local/lib/python2.7/dist-packages/Pillow-3.3.0-py2.7-linux-armv6l.egg
Processing dependencies for Pillow
Finished processing dependencies for Pillow
</code></pre>
<p>And the output of the error:</p>
<pre><code>root@rasp01:/data/server# python
Python 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import Image
Illegal instruction
root@rasp01:/data/server#
</code></pre>
<p>Does anyone have an idea what is wrong here? Thanks in advance! </p>
| 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 http://pypi.python.org/simple/Pillow/
Best match: Pillow 3.3.0
Downloading https://pypi.python.org/packages/e0/27/f61098a12f14690689924de93ffdd101463083a80bf8ff3e0c218addf05b/Pillow-3.3.0.tar.gz#md5=b5a15b03bf402fe254636c015fcf04da
Processing Pillow-3.3.0.tar.gz
Running Pillow-3.3.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-c1OEYc/Pillow-3.3.0/egg-dist-tmp-iwARkP
Single threaded build, not installing mp_compile:1 processes
warning: no files found matching '*.sh'
no previously-included directories found matching 'docs/_static'
warning: no previously-included files found matching '.coveragerc'
warning: no previously-included files found matching '.editorconfig'
warning: no previously-included files found matching '.landscape.yaml'
warning: no previously-included files found matching 'appveyor.yml'
warning: no previously-included files found matching 'build_children.sh'
warning: no previously-included files found matching 'tox.ini'
warning: no previously-included files matching '.git*' found anywhere in distribution
warning: no previously-included files matching '*.pyc' found anywhere in distribution
warning: no previously-included files matching '*.so' found anywhere in distribution
--------------------------------------------------------------------
PIL SETUP SUMMARY
--------------------------------------------------------------------
version Pillow 3.3.0
platform linux2 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3]
--------------------------------------------------------------------
--- JPEG support available
*** OPENJPEG (JPEG2000) support not available
--- ZLIB (PNG/ZIP) support available
*** LIBIMAGEQUANT support not available
*** LIBTIFF support not available
--- FREETYPE2 support available
*** LITTLECMS2 support not available
*** WEBP support not available
*** WEBPMUX support not available
--------------------------------------------------------------------
To add a missing option, make sure you have the required
library and headers.
To check the build, run the selftest.py script.
Adding Pillow 3.3.0 to easy-install.pth file
Installing pilfont.py script to /usr/local/bin
Installing thresholder.py script to /usr/local/bin
Installing gifmaker.py script to /usr/local/bin
Installing viewer.py script to /usr/local/bin
Installing createfontdatachunk.py script to /usr/local/bin
Installing enhancer.py script to /usr/local/bin
Installing pilconvert.py script to /usr/local/bin
Installing pilfile.py script to /usr/local/bin
Installing player.py script to /usr/local/bin
Installing explode.py script to /usr/local/bin
Installing pildriver.py script to /usr/local/bin
Installing painter.py script to /usr/local/bin
Installing pilprint.py script to /usr/local/bin
Installed /usr/local/lib/python2.7/dist-packages/Pillow-3.3.0-py2.7-linux-armv6l.egg
Processing dependencies for Pillow
Finished processing dependencies for Pillow
</code></pre>
<p>And the output of the error:</p>
<pre><code>root@rasp01:/data/server# python
Python 2.7.3 (default, Mar 18 2014, 05:13:23)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from PIL import Image
Illegal instruction
root@rasp01:/data/server#
</code></pre>
<p>Does anyone have an idea what is wrong here? Thanks in advance! </p>
| 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 the SQL query, and I need to compensate for that. The only value that needs to change is the first in each tuple. Here is the code I have so far:</p>
<pre><code>import pymysql
cnx=pymysql.connect(dbstuff)
cursor=cnx.cursor()
cursor.execute("SELECT * FROM og_tbl ORDER BY ip_addr,Port ASC")
results=cursor.fetchall()
i=1
list=[]
for line in results:
list.append((i,line[1:]))
i += 1
values = ', '.join(map(str,list))
query="INSERT INTO tmp_tbl VALUES {}".format(values)
cursor.execute(query)
cnx.commit()
cnx.close()
</code></pre>
<p>This gives me the results of each tuple that looks like the following. I can't figure out how to do this differently so that the parentheses are only on the outside of each tuple.</p>
<blockquote>
<p>(1, (sqlstuff)),(2, (sqlstuff)), etc</p>
</blockquote>
| 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> to generate the new values:</p>
<pre><code>lst = [(i,)+line[1:] for i, line in enumerate(results, 1)]
</code></pre>
<p>On a side note, be careful to not use the name <code>list</code> as this already being used by a builtin.</p>
| 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
</code></pre>
<p>I want to save all these entries in a file which I need to access later to get specific entries only.</p>
<p>If I need to access one of the timestamp records using a date and specific time, how can it be done? For example, I need to find the entries for <code>2014-31-10</code> for the time between <code>20:00</code> and <code>20:05</code>, how can it be done?</p>
<p>Any help would be appreciated!</p>
<p>Updated:</p>
<pre><code>import datetime
import ipaddress
from random import randint
for x in ip_range.hosts():
for h in range(24): #24 hours
for i in range(60): # 60 minutes
f.write(str(t_stamp)+'\t'+str(x)+'\t0\t'+str(randint(0,100))+'%\n')
f.write(str(t_stamp)+'\t'+str(x)+'\t1\t'+str(randint(0,100))+'%\n')
t_stamp += 60 # one minute
</code></pre>
<p>Now I am looking to create a log file for every minute. How can that be done?</p>
| 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
</code></pre>
<p>I want to save all these entries in a file which I need to access later to get specific entries only.</p>
<p>If I need to access one of the timestamp records using a date and specific time, how can it be done? For example, I need to find the entries for <code>2014-31-10</code> for the time between <code>20:00</code> and <code>20:05</code>, how can it be done?</p>
<p>Any help would be appreciated!</p>
<p>Updated:</p>
<pre><code>import datetime
import ipaddress
from random import randint
for x in ip_range.hosts():
for h in range(24): #24 hours
for i in range(60): # 60 minutes
f.write(str(t_stamp)+'\t'+str(x)+'\t0\t'+str(randint(0,100))+'%\n')
f.write(str(t_stamp)+'\t'+str(x)+'\t1\t'+str(randint(0,100))+'%\n')
t_stamp += 60 # one minute
</code></pre>
<p>Now I am looking to create a log file for every minute. How can that be done?</p>
| 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><code>import datetime
tvalue = datetime.datetime(2014,10,31,0,0).timestamp() #yy mm dd 0 0
startval = ((REQD_HOUR)*3600 + (REQD_MIN)*60) #required start time
endval = ((REQD_HOUR_E)*3600 + (REQD_MIN_E)*60) # range end time
while (endval > startval):
print(tvalue+startval)
startval+=60
</code></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> </p>
<p>Im trying to run some analysis on a Python list containing closing prices. </p>
<p>I understand that I must convert the list before handing it over to TA-Lib, since I have seen all examples doing that. </p>
<p>However this is met by a <code>only length-1 arrays can be converted to Python scalars</code></p>
| 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 clobbering the other modules namespace, leading to the error. This is well put <a href="http://stackoverflow.com/a/34110138/6388893">here</a>.</p>
<p>So I just imported talib cleanly:</p>
<pre><code>import talib
</code></pre>
<p>The final code that works is:</p>
<pre><code>def macd(prices):
print "Running MACD"
prices = np.array(prices, dtype=float)
print prices
macd, macdsignal, macdhist = talib.MACD(prices, fastperiod=12, slowperiod=26, signalperiod=9)
print "MACD "+macd
</code></pre>
| 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 number of pages for some PDF file."
pdf = CGPDFDocumentCreateWithProvider (CGDataProviderCreateWithFilename (pdfPath))
return pdf.getNumberOfPages()
if __name__ == '__main__':
for filename in sys.argv[1:]:
pdfnum=pdfnum+pageCount(filename)
print pdfnum
</code></pre>
<p>I can't find anything in Apple's reference material that corresponds with the words used here. I have no idea why we're Creating a new PDF document, when we only want to read attributes of an existing document.
The PDFDocument object has a pageCount method, but we're defining our own function with that name here, and that's not the 'getNumberOfPages' that seems to be the method mentioned in the script. I can't find that word in Apple's reference at all.</p>
<p>In short: I don't see how I link up the terms used in Apple's reference material with words that I might want to use in my scripts.</p>
| 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 old, and some of the methods have since been deprecated.</p>
| 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>>>> a="foo\r\nbar"
>>> print(str(a.find("\r\n")))
3
</code></pre>
<p>This works fine, but if the first variable <code>a</code> is casted as byte it won't work anymore.</p>
<pre><code>>>> a=b"foo\r\nbar"
>>> print(str(a.find("\r\n")))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
</code></pre>
<p>It doesn't work either if I cast the variable <code>a</code> as a string again.</p>
<pre><code>>>> print(str(str(a).find("\r\n")))
-1
</code></pre>
<p>How can I check for <code>\r\n</code> in a byte variable?</p>
| 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>>>> a=b"foo\r\nbar"
>>> print(a.decode("utf-8").find("\r\n"))
3
</code></pre>
<p>Your varibale <code>a</code> is encoded which is why it can't be compared with a unicode string like <code>"\r\n"</code>. </p>
| 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>>>> a="foo\r\nbar"
>>> print(str(a.find("\r\n")))
3
</code></pre>
<p>This works fine, but if the first variable <code>a</code> is casted as byte it won't work anymore.</p>
<pre><code>>>> a=b"foo\r\nbar"
>>> print(str(a.find("\r\n")))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
</code></pre>
<p>It doesn't work either if I cast the variable <code>a</code> as a string again.</p>
<pre><code>>>> print(str(str(a).find("\r\n")))
-1
</code></pre>
<p>How can I check for <code>\r\n</code> in a byte variable?</p>
| 0 | 2016-08-04T21:30:53Z | 38,777,804 | <p>Search for a byte string too (as the error suggests!):</p>
<pre><code>>>> a=b"foo\r\nbar"
>>> 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>>>> a="foo\r\nbar"
>>> print(str(a.find("\r\n")))
3
</code></pre>
<p>This works fine, but if the first variable <code>a</code> is casted as byte it won't work anymore.</p>
<pre><code>>>> a=b"foo\r\nbar"
>>> print(str(a.find("\r\n")))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
</code></pre>
<p>It doesn't work either if I cast the variable <code>a</code> as a string again.</p>
<pre><code>>>> print(str(str(a).find("\r\n")))
-1
</code></pre>
<p>How can I check for <code>\r\n</code> in a byte variable?</p>
| 0 | 2016-08-04T21:30:53Z | 38,777,812 | <pre><code>>>> a = b"foo\r\nbar"
>>> 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><form action="{% url 'social:begin' 'facebook' %}">
<button type="submit" class="btn btn-primary"><span class="fa fa-facebook">&nbsp</span>Login with Facebook </button>
</form>
<form action="{% url 'social:begin' 'google-oauth2' %}">
<button type="submit" class="btn btn-danger"><span class="fa fa-google">&nbsp</span>Login with Google</button>
</form>
</code></pre>
<p>As you can see, the url arguments are not intuitive, sometimes they are the name of the social network, like <code>facebook</code>, sometimes it is something more complex like <code>google-oauth2</code>. Is there a way I can figure out what argument to pass into de function? Now, I need login buttons for instagram and twitter. I can't find a clear reference in the docs about this.</p>
<p>Best,</p>
<p>Alejandro.</p>
| 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 <code>name</code>. In the case of Instagram, it looks like this:</p>
<pre><code>class InstagramOAuth2(BaseOAuth2):
name = 'instagram'
....
</code></pre>
<p>So, that means the social login button should look something like this:</p>
<pre><code>{% url 'social:begin' 'instagram' %}
</code></pre>
| 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 production, so in those contexts thread means "green" thread.</p>
<p>The <a href="https://github.com/miguelgrinberg/Flask-SocketIO/issues/268" rel="nofollow">open issue</a> is related to using a message queue, which is necessary when you have multiple servers. In that set up, the accesses to the queue are not thread safe at this time. This is a bug that needs to be fixed, but as a workaround, you can create a different <code>socketio</code> object per thread.</p>
<p>On second question regarding if <code>socketio.emit()</code> is atomic, the answer is no. This is not a simple socket write operation. The payload needs to be formatted in certain way to comply with the Socket.IO protocol, then depending on the selected transport (long-polling or websocket) the write happens in a completely different way.</p>
| 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 to your example, the answer is <strong>No, you don't always get a float, it depends of the other object</strong>.</p>
<p>For example, you can see in the Python Fraction source code the implementation of <code>__mul__</code> and <code>__rmul__</code> : <a href="https://hg.python.org/cpython/file/tip/Lib/fractions.py#l421" rel="nofollow">https://hg.python.org/cpython/file/tip/Lib/fractions.py#l421</a> and the function which does the computing : <a href="https://hg.python.org/cpython/file/tip/Lib/fractions.py#l377" rel="nofollow">https://hg.python.org/cpython/file/tip/Lib/fractions.py#l377</a> .</p>
| -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) without losing any information, but it can't do it other way around. </p>
<p>Here is link (<a href="https://docs.python.org/2.4/lib/typesnumeric.html" rel="nofollow">https://docs.python.org/2.4/lib/typesnumeric.html</a>)
It suggests obvious thing i forgot. Complex numbers are more commont than Float. So if you will try to multiply float to complex. you will get complex. </p>
<p>"Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the ``narrower'' type is widened to that of the other, where plain integer is narrower than long integer is narrower than floating point is narrower than complex. Comparisons between numbers of mixed type use the same rule."</p>
| 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 < 100km
centerLat = 30.0 # latitude of circle center, decimal degrees
centerLon = -100.0 # Longitude of circle center, decimal degrees
# parameters
N = 10 # number of discrete sample points to be generated along the circle
# generate points
circlePoints = []
for k in xrange(N):
# compute
angle = math.pi*2*k/N
dx = radius*math.cos(angle)
dy = radius*math.sin(angle)
point = {}
point['lat']=centerLat + (180/math.pi)*(dy/6378137)
point['lon']=centerLon + (180/math.pi)*(dx/6378137)/math.cos(centerLat*math.pi/180)
# add to list
circlePoints.append(point)
print circlePoints
</code></pre>
<p>The distance between these points is constant, as it should be. </p>
<p>My JS version is, as far as I know, equivalent:</p>
<pre><code> var nodesCount = 8;
var coords = [];
for (var i = 0; i <= nodesCount; i++) {
var radius = 1000;
var angle = Math.PI*2*i/nodesCount;
var dx = radius*Math.cos(angle);
var dy = radius*Math.sin(angle);
coords.push([(rootLongitude + (180 / Math.PI) * (dx / EARTH_RADIUS) / Math.cos(rootLatitude * Math.PI / 180)),(rootLatitude + (180 / Math.PI) * (dy / EARTH_RADIUS))]);
}
</code></pre>
<p>But when I output this, the coordinates are not equidistant from the center. </p>
<p>This is enormously frustrating -- I've been trying to debug this for a day. Can anyone see what's making the JS code fail?</p>
| 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 = "10 GB/s";
var centerLat = 35.088878;
var centerLon = -106.65262;
var EARTH_RADIUS = 6378137;
var mymap = L.map('mapid').setView([centerLat, centerLon], 11);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw', {
maxZoom: 18,
attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
id: 'mapbox.streets'
}).addTo(mymap);
function drawNext(centerLat, centerLon) {
var coords = [];
for (var i = 0; i < nodesCount; i++) {
var radius = linkDistance * 1000;
var angle = Math.PI * 2 * i / nodesCount;
var dx = radius * Math.cos(angle);
var dy = radius * Math.sin(angle);
var lat = centerLon + (180 / Math.PI) * (dy / 6378137);
var lon = centerLat + (180 / Math.PI) * (dx / 6378137) / Math.cos(centerLon * Math.PI / 180);
coords.push([lat, lon]);
}
for (var i = 0; i < coords.length; i++) {
new L.Circle(coords[i], 500, {
color: 'black',
fillColor: '#f03',
fillOpacity: 0.1
}).addTo(mymap);
console.log("added circle to: " + coords[i]);
}
}
drawNext(centerLon, centerLat);
var popup = L.popup();
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(mymap);
}
mymap.on('click', onMapClick);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#mapid {
height: 500px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://npmcdn.com/leaflet@1.0.0-rc.2/dist/leaflet-src.js"></script>
<link href="https://npmcdn.com/leaflet@1.0.0-rc.2/dist/leaflet.css" rel="stylesheet"/>
<div id="mapid"></div></code></pre>
</div>
</div>
</p>
| 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>
<pre><code># Read the config file and put every line in a seperate entry in a list
configHandle = [item.rstrip('\n') for item in open('config.conf')]
# Strip comment items from the configHandle
for item in configHandle:
if item.startswith('#'):
configHandle.remove(item)
# remove all empty items in handle
configHandle = filter(lambda a: a != '', configHandle)
print configHandle
</code></pre>
<p>This works but I think it is a bit of a nasty solution.</p>
<p>When I try:</p>
<pre><code># Read the config file and put every line in a seperate entry in a list
configHandle = [item.rstrip('\n') for item in open('config.conf')]
# Strip comment items and empty items from the configHandle
for item in configHandle:
if item.startswith('#'):
configHandle.remove(item)
elif len(item) == 0:
configHandle.remove(item)
</code></pre>
<p>This, however, fails. I cannot figure out why.</p>
<p>Can someone push me in the right direction?</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>
<pre><code># Read the config file and put every line in a seperate entry in a list
configHandle = [item.rstrip('\n') for item in open('config.conf')]
# Strip comment items from the configHandle
for item in configHandle:
if item.startswith('#'):
configHandle.remove(item)
# remove all empty items in handle
configHandle = filter(lambda a: a != '', configHandle)
print configHandle
</code></pre>
<p>This works but I think it is a bit of a nasty solution.</p>
<p>When I try:</p>
<pre><code># Read the config file and put every line in a seperate entry in a list
configHandle = [item.rstrip('\n') for item in open('config.conf')]
# Strip comment items and empty items from the configHandle
for item in configHandle:
if item.startswith('#'):
configHandle.remove(item)
elif len(item) == 0:
configHandle.remove(item)
</code></pre>
<p>This, however, fails. I cannot figure out why.</p>
<p>Can someone push me in the right direction?</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 at the end of the block automatically<sup>1</sup>:</p>
<pre><code>with open('config.conf') as infile :
configHandle = infile.splitlines()
configHandle = [line for line in configHandle if line and not line.startswith('#')]
</code></pre>
<hr>
<p><sub>
1. Because there is no guarantee for external links to be collected by garbage-collector. And you need to close them explicitly, which can be done by calling the <code>close()</code> method of a file object, or as mentioned as a more pythonic way use a <code>with</code> statement.
</sub></p>
| 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>
<pre><code># Read the config file and put every line in a seperate entry in a list
configHandle = [item.rstrip('\n') for item in open('config.conf')]
# Strip comment items from the configHandle
for item in configHandle:
if item.startswith('#'):
configHandle.remove(item)
# remove all empty items in handle
configHandle = filter(lambda a: a != '', configHandle)
print configHandle
</code></pre>
<p>This works but I think it is a bit of a nasty solution.</p>
<p>When I try:</p>
<pre><code># Read the config file and put every line in a seperate entry in a list
configHandle = [item.rstrip('\n') for item in open('config.conf')]
# Strip comment items and empty items from the configHandle
for item in configHandle:
if item.startswith('#'):
configHandle.remove(item)
elif len(item) == 0:
configHandle.remove(item)
</code></pre>
<p>This, however, fails. I cannot figure out why.</p>
<p>Can someone push me in the right direction?</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>
<pre><code># Read the config file and put every line in a seperate entry in a list
configHandle = [item.rstrip('\n') for item in open('config.conf')]
# Strip comment items from the configHandle
for item in configHandle:
if item.startswith('#'):
configHandle.remove(item)
# remove all empty items in handle
configHandle = filter(lambda a: a != '', configHandle)
print configHandle
</code></pre>
<p>This works but I think it is a bit of a nasty solution.</p>
<p>When I try:</p>
<pre><code># Read the config file and put every line in a seperate entry in a list
configHandle = [item.rstrip('\n') for item in open('config.conf')]
# Strip comment items and empty items from the configHandle
for item in configHandle:
if item.startswith('#'):
configHandle.remove(item)
elif len(item) == 0:
configHandle.remove(item)
</code></pre>
<p>This, however, fails. I cannot figure out why.</p>
<p>Can someone push me in the right direction?</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 been stated in other answers, it is a very bad idea to attempt to modify a list while you are iterating through it. The answers to <a href="http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python">this</a> stackoverflow question provides alternatives to using <code>filter</code> to remove from a list based on a condition.</p>
| 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']
list2 = ['eeez', 'fffz', 'dddz', 'cccz', 'iiiz', 'jjjz', 'aaaz', 'gggz', 'hhhz', 'bbbz']
len = len(list1)
i = 0
while i < len:
j = 0
while j < len:
if difflib.SequenceMatcher(None, list1[i], list2[j]).ratio() > 0.5:
eltMove = list2.pop(j)
list2.insert(i, eltMove)
break
j += 1
i += 1
print(list2)
</code></pre>
<p>Output :</p>
<pre><code>['aaaz', 'bbbz', 'cccz', 'dddz', 'eeez', 'fffz', 'gggz', 'hhhz', 'iiiz', 'jjjz']
</code></pre>
<p>But it doesn't work in some cases where there is an element in list2 that match a bit with an element in list1, which break the loop and skip next elements even if they can match better.</p>
| 1 | 2016-08-04T21:41:52Z | 38,778,122 | <pre><code>while i < len:
j = 0
new_l = []
while j < 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 then calculates the max, finds out the index of the max value and then pops/inserts.</p>
<p>Hope this is what you needed</p>
<pre><code>for i, a in enumerate(list1):
new_l = [difflib.SequenceMatcher(None, a, b).ratio() for b in list2]
ind = new_l.index(max(new_l))
eltMove = list2.pop(ind)
list2.insert(i, eltMove)
</code></pre>
<p>Shortened out the code</p>
<p>Considering @Jose Raul Barreras's reply, the appropriate modification of the above would be:</p>
<pre><code>tmp = []
for i, a in enumerate(list1):
new_l = [difflib.SequenceMatcher(None, a, b).ratio() for b in list2]
ind = new_l.index(max(new_l))
eltMove = list2.pop(ind)
tmp.append(eltMove)
>>> tmp
['aaaz', 'bbbz', 'cccz', 'dddz', 'eeez', 'fffz', 'gggz', 'hhhz', 'iiiz', 'jjjz',
'aaaz', 'bbbz', 'cccz', 'dddz', 'eeez', 'fffz', 'gggz', 'hhhz', 'iiiz', 'jjjz']
</code></pre>
| 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']
list2 = ['eeez', 'fffz', 'dddz', 'cccz', 'iiiz', 'jjjz', 'aaaz', 'gggz', 'hhhz', 'bbbz']
len = len(list1)
i = 0
while i < len:
j = 0
while j < len:
if difflib.SequenceMatcher(None, list1[i], list2[j]).ratio() > 0.5:
eltMove = list2.pop(j)
list2.insert(i, eltMove)
break
j += 1
i += 1
print(list2)
</code></pre>
<p>Output :</p>
<pre><code>['aaaz', 'bbbz', 'cccz', 'dddz', 'eeez', 'fffz', 'gggz', 'hhhz', 'iiiz', 'jjjz']
</code></pre>
<p>But it doesn't work in some cases where there is an element in list2 that match a bit with an element in list1, which break the loop and skip next elements even if they can match better.</p>
| 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_value = difflib.SequenceMatcher(None, elem1, elem2).ratio()
if (current_value > best_value) and (elem2 in tmp_list):
best_value = current_value
best = elem2
position = i
del tmp_list[position]
res.append(best)
return res
a = ['aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg', 'hhhh', 'iiii', 'jjjj']*2
b = ['eeez', 'fffz', 'dddz', 'cccz', 'iiiz', 'jjjz', 'aaaz', 'gggz', 'hhhz', 'bbbz']*2
print(closest_list(a,b))
</code></pre>
<p><strong>Output:</strong></p>
<blockquote>
<p>['aaaz', 'bbbz', 'cccz', 'dddz', 'eeez', 'fffz', 'gggz', 'hhhz',
'iiiz', 'jjjz', 'aaaz', 'bbbz', 'cccz', 'dddz', 'eeez', 'fffz',
'gggz', 'hhhz', 'iiiz', 'jjjz']</p>
</blockquote>
<p>The solution given by @M. Klugerford fails with this data. </p>
| 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 correctly.</p>
<p>I've tried something like:</p>
<pre><code>hours = input("How many hours per day? ")
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
main()
</code></pre>
<p>What I'm trying to do, is make the program display an error msg, if they enter more than 24 hours, and if they do, then skip to the bottom code that asks if they want to try another calculation. And if they enter 24 hours or less, then continue the program with no error msg. I've spent about 2 days trying to fix this, searched google for hours, I may have seen the right answer but can't seem to make it work. I assume I need some kind of while True statement, or if;then, but as many times as i have tried, I'm pulling my hair out at this point. The code to the entire program is below:</p>
<pre><code>def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
# print ("Don't be silly, there isn't more than 24 hours in a day!")
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of
%s cents per Kilo-watt hour, you will add $%s to your monthly
electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
</code></pre>
<p>I'm new to programming, I've only been learning Python for a few weeks, many thanks in advance for any advice.</p>
| 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 you should add more error testing and messages for negative numbers, etc.</p>
<pre><code>def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of %s cents per Kilo-watt hour, you will add $%s to your monthly electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
</code></pre>
| 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 correctly.</p>
<p>I've tried something like:</p>
<pre><code>hours = input("How many hours per day? ")
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
main()
</code></pre>
<p>What I'm trying to do, is make the program display an error msg, if they enter more than 24 hours, and if they do, then skip to the bottom code that asks if they want to try another calculation. And if they enter 24 hours or less, then continue the program with no error msg. I've spent about 2 days trying to fix this, searched google for hours, I may have seen the right answer but can't seem to make it work. I assume I need some kind of while True statement, or if;then, but as many times as i have tried, I'm pulling my hair out at this point. The code to the entire program is below:</p>
<pre><code>def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
# print ("Don't be silly, there isn't more than 24 hours in a day!")
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of
%s cents per Kilo-watt hour, you will add $%s to your monthly
electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
</code></pre>
<p>I'm new to programming, I've only been learning Python for a few weeks, many thanks in advance for any advice.</p>
| 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:</p>
<pre><code>while hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
hours = int(input("How many hours per day? "))
</code></pre>
<p>If you don't sure the user will input a number you should use a <code>try/catch</code> statemant.</p>
<p>Except from this you should validate you indent the code correctly</p>
| 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 correctly.</p>
<p>I've tried something like:</p>
<pre><code>hours = input("How many hours per day? ")
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
main()
</code></pre>
<p>What I'm trying to do, is make the program display an error msg, if they enter more than 24 hours, and if they do, then skip to the bottom code that asks if they want to try another calculation. And if they enter 24 hours or less, then continue the program with no error msg. I've spent about 2 days trying to fix this, searched google for hours, I may have seen the right answer but can't seem to make it work. I assume I need some kind of while True statement, or if;then, but as many times as i have tried, I'm pulling my hair out at this point. The code to the entire program is below:</p>
<pre><code>def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
# print ("Don't be silly, there isn't more than 24 hours in a day!")
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of
%s cents per Kilo-watt hour, you will add $%s to your monthly
electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
</code></pre>
<p>I'm new to programming, I've only been learning Python for a few weeks, many thanks in advance for any advice.</p>
| 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 ValueError if a non-integer was entered
except ValueError:
print("Please enter an integer")
continue
#2 checks to make sure the integer is in the right range
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
continue
if hours < 1:
print("Enter a positive integer")
continue
#everything is good, bail out of the loop
break
</code></pre>
<p>Basically, it starts by going into an 'infinite' loop. It gets the input, goes through all the checks to see if it is valid, and hits the break (leaving the loop) if everything went okay. If the data was bad in any way, it informs the user and restarts the loop with the continue. <code>hours = 0</code> is declared outside the loop so it is still accessible in the scope outside, so it can be used elsewhere.</p>
<p>Edit: adding an idea to the example code that I thought of after seeing @Ohad Eytan's answer</p>
| 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 correctly.</p>
<p>I've tried something like:</p>
<pre><code>hours = input("How many hours per day? ")
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
main()
</code></pre>
<p>What I'm trying to do, is make the program display an error msg, if they enter more than 24 hours, and if they do, then skip to the bottom code that asks if they want to try another calculation. And if they enter 24 hours or less, then continue the program with no error msg. I've spent about 2 days trying to fix this, searched google for hours, I may have seen the right answer but can't seem to make it work. I assume I need some kind of while True statement, or if;then, but as many times as i have tried, I'm pulling my hair out at this point. The code to the entire program is below:</p>
<pre><code>def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
# print ("Don't be silly, there isn't more than 24 hours in a day!")
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of
%s cents per Kilo-watt hour, you will add $%s to your monthly
electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
</code></pre>
<p>I'm new to programming, I've only been learning Python for a few weeks, many thanks in advance for any advice.</p>
| 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) run per day"))
# Check that the hours number is good before getting to the cost
while (hours > 24) or (hours < 0):
print("Don't be silly, theres not more than 24 or less than 0 hours in a day ")
hours = int(input("Enter the number of hours that appliance(s) run per day "))
cost = int(input("Enter the cost in cents per KwH you pay for electricty "))
# We don't need an auxiliary variable x here
total = (watts * hours / 1000.0 * 30) * cost
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of %s cents per Kilo-watt hour, you will add $%s to your monthly electric bill""") % (watts, hours, cost, total)
print star
if __name__ == '__main__':
playagain = 'yes'
while playagain == 'yes':
main()
print 'Would you like to do another Calculation? (yes or no)'
playagain = raw_input()
# Checking that the user's input is whether yes or no
while playagain not in ['yes', 'no']:
print "It's a yes/no question god damn it"
print 'Would you like to do another Calculation? (yes or no)'
playagain = raw_input()
</code></pre>
| 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.42814804, 0.43201894, 0.43973886, 0.44125302,
0.41176999],
[ 0.46509004, 0.46221505, 0.48824086, 0.50088744, 0.53040384,
0.53592231, 0.49710228, 0.49821022, 0.47720381, 0.49096272,
0.50438366, 0.47173162, 0.48813669, 0.45032002, 0.44776794,
0.43910269, 0.43326132, 0.42064458, 0.43472954, 0.45577299,
0.43604956]])
</code></pre>
<p>I want to count how many cells exceed a given value, let's say <code>0.5</code>, and set those that don't to <code>0.0</code>. This is what I do:</p>
<pre><code>count=0
value=0.5
for i in range(myarray.shape[0]):
for j in range(myarray.shape[1]):
if myarray[i][j]<value:
myarray[i][j]=0
elif myarray[i][j]>=value:
count=count+1
percentage=round(100*count/(myarray.shape[0]*myarray.shape[1]),2)
</code></pre>
<p>However, I get this error: <code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()</code>, pointing at the line where I check <code>if myarray[i][j]<value</code>. </p>
<p><strong>Why does this happen and how to fix it?</strong> What is the truth value?</p>
| 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 < 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,7]
if elem < 6:
# this doesn't make sense
</code></pre>
<p>Instead, you can get the truth value of whether any or all elements satisfy the condition. For example:</p>
<pre><code>elem = np.array([5,7])
if np.any(elem<6):
# this is true, because 5 < 6
if np.all(elem<6):
# this isn't true, because 7 > 6
</code></pre>
<p>I ran your example code above and found no error, so I'm not sure what the issue is. But this is what you should look out for. Consider printing the element you are comparing to see if it is an array.</p>
<hr>
<p>Also, this is a shorter way of doing what you want to do:</p>
<pre><code>myarray = np.array( putarrayhere )
count = sum(myarray >= value)
</code></pre>
| 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.42814804, 0.43201894, 0.43973886, 0.44125302,
0.41176999],
[ 0.46509004, 0.46221505, 0.48824086, 0.50088744, 0.53040384,
0.53592231, 0.49710228, 0.49821022, 0.47720381, 0.49096272,
0.50438366, 0.47173162, 0.48813669, 0.45032002, 0.44776794,
0.43910269, 0.43326132, 0.42064458, 0.43472954, 0.45577299,
0.43604956]])
</code></pre>
<p>I want to count how many cells exceed a given value, let's say <code>0.5</code>, and set those that don't to <code>0.0</code>. This is what I do:</p>
<pre><code>count=0
value=0.5
for i in range(myarray.shape[0]):
for j in range(myarray.shape[1]):
if myarray[i][j]<value:
myarray[i][j]=0
elif myarray[i][j]>=value:
count=count+1
percentage=round(100*count/(myarray.shape[0]*myarray.shape[1]),2)
</code></pre>
<p>However, I get this error: <code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()</code>, pointing at the line where I check <code>if myarray[i][j]<value</code>. </p>
<p><strong>Why does this happen and how to fix it?</strong> What is the truth value?</p>
| 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.47591957, 0.436558 , 0.43335574,0.44053621, 0.42814804, 0.43201894, 0.43973886, 0.44125302, 0.41176999],[ 0.46509004, 0.46221505, 0.48824086, 0.50088744, 0.53040384,0.53592231, 0.49710228, 0.49821022, 0.47720381, 0.49096272,0.50438366, 0.47173162, 0.48813669, 0.45032002, 0.44776794,0.43910269, 0.43326132, 0.42064458, 0.43472954, 0.45577299,0.43604956]])
</code></pre>
<p>and the code works</p>
<p>but setting:</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.47591957, 0.436558 , 0.43335574,0.44053621, 0.42814804, 0.43201894, 0.43973886, 0.44125302, 0.41176999],[ 0.46509004, 0.46221505, 0.48824086, 0.50088744, 0.53040384,0.53592231, 0.49710228, 0.49821022, 0.47720381, 0.49096272,0.50438366, 0.47173162, 0.48813669, 0.45032002, 0.44776794,0.43910269, 0.43326132, 0.42064458, 0.43472954, 0.45577299,0.43604956]]])
</code></pre>
<p>yielded similar errors</p>
| 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.42814804, 0.43201894, 0.43973886, 0.44125302,
0.41176999],
[ 0.46509004, 0.46221505, 0.48824086, 0.50088744, 0.53040384,
0.53592231, 0.49710228, 0.49821022, 0.47720381, 0.49096272,
0.50438366, 0.47173162, 0.48813669, 0.45032002, 0.44776794,
0.43910269, 0.43326132, 0.42064458, 0.43472954, 0.45577299,
0.43604956]])
</code></pre>
<p>I want to count how many cells exceed a given value, let's say <code>0.5</code>, and set those that don't to <code>0.0</code>. This is what I do:</p>
<pre><code>count=0
value=0.5
for i in range(myarray.shape[0]):
for j in range(myarray.shape[1]):
if myarray[i][j]<value:
myarray[i][j]=0
elif myarray[i][j]>=value:
count=count+1
percentage=round(100*count/(myarray.shape[0]*myarray.shape[1]),2)
</code></pre>
<p>However, I get this error: <code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()</code>, pointing at the line where I check <code>if myarray[i][j]<value</code>. </p>
<p><strong>Why does this happen and how to fix it?</strong> What is the truth value?</p>
| 1 | 2016-08-04T21:43:42Z | 38,778,231 | <p>Regardless the error you can simply do:</p>
<pre><code>myarray[myarray<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.</p>
<p>Is it a numpy bug? Anything I should do differently?</p>
| 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 b)
{
Py_complex r;
r.real = a.real*b.real - a.imag*b.imag;
r.imag = a.real*b.imag + a.imag*b.real;
return r;
}
</code></pre>
<p>When the inputs have infinite real or imaginary parts, complex multiplication tends to cause <code>inf-inf</code> subtraction and <code>0*inf</code> multiplication, leading to <code>nan</code> components in the result. We can see that <code>1j * numpy.inf</code> has one <code>nan</code> component and one <code>inf</code> component:</p>
<pre><code>In [5]: 1j * numpy.inf
Out[5]: (nan+infj)
</code></pre>
<p>and multiplying the result by <code>1</code> produces two <code>nan</code> components:</p>
<pre><code>In [4]: 1j * numpy.inf * 1
Out[4]: (nan+nanj)
</code></pre>
| 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 the width in characters with only the screen pixels while still being able to support both Windows and Linux?</strong></p>
<p>For the sake of the question, let's assume none of the users have changed their shell settings from the default ones.</p>
| 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 the model and the second set would be an entry. Basically making the queries variable, based on what the user chooses on the front end. How would I send that variable sort option to the view, and then return it back to the webpage. What about using a dictionary? Please help</p>
<p>This <a href="http://stackoverflow.com/questions/4720079/django-query-filter-with-variable-column">SO question</a> has proven to be a little helpful, but still cannot grasp it completely. </p>
| 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. </p>
| 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 experiments simulating this situation lead to a Exception RuntimeError: 'maximum recursion depth exceeded'. </p>
<p>When I move creating the next element in the chain to the container managing these objects the problem seems to disappear, this despite building in my naive understanding a call stack of the same depth. I call create through all the previously created objects. (see example code).</p>
<p>I am inclined to conclude that the recursion depth limit is somehow set per object (be it a class or an instance). Which when creating recursively via <strong>init</strong> probably puts everything on the stack of the class, where as if we create them recursively through a line of instances of the same class all the objects will have very limited recursion depth.</p>
<p>I am seeking some confirmation for this hypothesis, but find it hard to get either confirmation or refutation. </p>
<pre><code>import sys
class Chunk(object):
pre=None
post=None
def __init__(self, container,pre):
print 'Chunk Created'
self.pre=pre
self.container=container
def create(self,x):
if self.post == None:
self.post=Chunk(self.container,self)
newChunk =self.post
else:
newChunk =self.post.create(x+1)
return newChunk
def droprefs(self):
print 'refcount droprefs start: ', sys.getrefcount(self)
if not self.pre ==None:
self.pre.droprefs()
self.pre=None
self.post=None
self.container=None
print 'refcount droprefs end: ', sys.getrefcount(self)
def claimContainer(self):
self.container.setmasterchunk(self)
self.pre.droprefs()
self.pre=None
class Container(object):
masterchunk=None
def __init__(self):
self.masterchunk=Chunk(self, None)
def setmasterchunk(self, chunk):
print 'refcount 5: ', sys.getrefcount(self.masterchunk)
self.masterchunk=chunk
print 'refcount 6: ', sys.getrefcount(self.masterchunk)
def testrecursion(self,n):
for i in range(n):
print 'refcount 6: ', sys.getrefcount(self.masterchunk)
newChunk=self.masterchunk.create(1)
return newChunk
def testhistoryremoval(self,chunk):
chunk.claimContainer()
if __name__ == '__main__':
C=Container()
middle=C.testrecursion(300)
last=C.testrecursion(600)
last=C.testhistoryremoval(middle)
if middle== C.masterchunk:
print 'SUCCESS'
</code></pre>
<p>Note added: </p>
<p>Code showing the maximum recursion depth:</p>
<pre><code>import sys
from time import sleep
class Chunk(object):
pre=None
post=None
def __init__(self, container,pre,n):
print 'Chunk Created'
self.pre=pre
self.container=container
if n>0:
self.post=Chunk(self.container,self,n-1)
def droprefs(self):
print 'refcount droprefs start: ', sys.getrefcount(self)
if not self.pre ==None:
self.pre.droprefs()
self.pre=None
self.post=None
self.container=None
print 'refcount droprefs end: ', sys.getrefcount(self)
def claimContainer(self):
self.container.setmasterchunk(self)
self.pre.droprefs()
self.pre=None
class Container(object):
masterchunk=None
def __init__(self):
pass
def setmasterchunk(self, chunk):
print 'refcount 5: ', sys.getrefcount(self.masterchunk)
self.masterchunk=chunk
print 'refcount 6: ', sys.getrefcount(self.masterchunk)
def testrecursion(self,n):
self.masterchunk=Chunk(self,None,n)
if __name__ == '__main__':
print('Try 10')
C0=Container()
C0.testrecursion(10)
sleep(2)
print('Try 1000')
C1=Container()
C1.testrecursion(1000)
</code></pre>
| 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. If this one doesn't exceed the stack depth, it will complete smoothly -- the prior stack entries do not affect the new one.</p>
| 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 experiments simulating this situation lead to a Exception RuntimeError: 'maximum recursion depth exceeded'. </p>
<p>When I move creating the next element in the chain to the container managing these objects the problem seems to disappear, this despite building in my naive understanding a call stack of the same depth. I call create through all the previously created objects. (see example code).</p>
<p>I am inclined to conclude that the recursion depth limit is somehow set per object (be it a class or an instance). Which when creating recursively via <strong>init</strong> probably puts everything on the stack of the class, where as if we create them recursively through a line of instances of the same class all the objects will have very limited recursion depth.</p>
<p>I am seeking some confirmation for this hypothesis, but find it hard to get either confirmation or refutation. </p>
<pre><code>import sys
class Chunk(object):
pre=None
post=None
def __init__(self, container,pre):
print 'Chunk Created'
self.pre=pre
self.container=container
def create(self,x):
if self.post == None:
self.post=Chunk(self.container,self)
newChunk =self.post
else:
newChunk =self.post.create(x+1)
return newChunk
def droprefs(self):
print 'refcount droprefs start: ', sys.getrefcount(self)
if not self.pre ==None:
self.pre.droprefs()
self.pre=None
self.post=None
self.container=None
print 'refcount droprefs end: ', sys.getrefcount(self)
def claimContainer(self):
self.container.setmasterchunk(self)
self.pre.droprefs()
self.pre=None
class Container(object):
masterchunk=None
def __init__(self):
self.masterchunk=Chunk(self, None)
def setmasterchunk(self, chunk):
print 'refcount 5: ', sys.getrefcount(self.masterchunk)
self.masterchunk=chunk
print 'refcount 6: ', sys.getrefcount(self.masterchunk)
def testrecursion(self,n):
for i in range(n):
print 'refcount 6: ', sys.getrefcount(self.masterchunk)
newChunk=self.masterchunk.create(1)
return newChunk
def testhistoryremoval(self,chunk):
chunk.claimContainer()
if __name__ == '__main__':
C=Container()
middle=C.testrecursion(300)
last=C.testrecursion(600)
last=C.testhistoryremoval(middle)
if middle== C.masterchunk:
print 'SUCCESS'
</code></pre>
<p>Note added: </p>
<p>Code showing the maximum recursion depth:</p>
<pre><code>import sys
from time import sleep
class Chunk(object):
pre=None
post=None
def __init__(self, container,pre,n):
print 'Chunk Created'
self.pre=pre
self.container=container
if n>0:
self.post=Chunk(self.container,self,n-1)
def droprefs(self):
print 'refcount droprefs start: ', sys.getrefcount(self)
if not self.pre ==None:
self.pre.droprefs()
self.pre=None
self.post=None
self.container=None
print 'refcount droprefs end: ', sys.getrefcount(self)
def claimContainer(self):
self.container.setmasterchunk(self)
self.pre.droprefs()
self.pre=None
class Container(object):
masterchunk=None
def __init__(self):
pass
def setmasterchunk(self, chunk):
print 'refcount 5: ', sys.getrefcount(self.masterchunk)
self.masterchunk=chunk
print 'refcount 6: ', sys.getrefcount(self.masterchunk)
def testrecursion(self,n):
self.masterchunk=Chunk(self,None,n)
if __name__ == '__main__':
print('Try 10')
C0=Container()
C0.testrecursion(10)
sleep(2)
print('Try 1000')
C1=Container()
C1.testrecursion(1000)
</code></pre>
| 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 href="https://github.com/python/cpython/blob/a3527d7169c091b7e244406a8ae7dd254b69ee1f/Include/pystate.h#L78" rel="nofollow">pystate.h</a>:</p>
<pre><code>typedef struct _ts {
/* See Python/ceval.c for comments explaining most fields */
//...
int recursion_depth;
//...
}
</code></pre>
<p><a href="https://github.com/python/cpython/blob/master/Python/ceval.c#L710" rel="nofollow">ceval.c</a>:</p>
<pre><code>/* the macro Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall()
if the recursion_depth reaches _Py_CheckRecursionLimit.
If USE_STACKCHECK, the macro decrements _Py_CheckRecursionLimit
to guarantee that _Py_CheckRecursiveCall() is regularly called.
Without USE_STACKCHECK, there is no need for this. */
int
_Py_CheckRecursiveCall(const char *where)
{
PyThreadState *tstate = PyThreadState_GET();
//...
if (tstate->recursion_depth > recursion_limit) {
--tstate->recursion_depth;
tstate->overflowed = 1;
PyErr_Format(PyExc_RecursionError,
"maximum recursion depth exceeded%s",
where);
return -1;
}
//...
}
</code></pre>
<p><code>tstate</code> is shorthand for thread-state.</p>
| 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 experiments simulating this situation lead to a Exception RuntimeError: 'maximum recursion depth exceeded'. </p>
<p>When I move creating the next element in the chain to the container managing these objects the problem seems to disappear, this despite building in my naive understanding a call stack of the same depth. I call create through all the previously created objects. (see example code).</p>
<p>I am inclined to conclude that the recursion depth limit is somehow set per object (be it a class or an instance). Which when creating recursively via <strong>init</strong> probably puts everything on the stack of the class, where as if we create them recursively through a line of instances of the same class all the objects will have very limited recursion depth.</p>
<p>I am seeking some confirmation for this hypothesis, but find it hard to get either confirmation or refutation. </p>
<pre><code>import sys
class Chunk(object):
pre=None
post=None
def __init__(self, container,pre):
print 'Chunk Created'
self.pre=pre
self.container=container
def create(self,x):
if self.post == None:
self.post=Chunk(self.container,self)
newChunk =self.post
else:
newChunk =self.post.create(x+1)
return newChunk
def droprefs(self):
print 'refcount droprefs start: ', sys.getrefcount(self)
if not self.pre ==None:
self.pre.droprefs()
self.pre=None
self.post=None
self.container=None
print 'refcount droprefs end: ', sys.getrefcount(self)
def claimContainer(self):
self.container.setmasterchunk(self)
self.pre.droprefs()
self.pre=None
class Container(object):
masterchunk=None
def __init__(self):
self.masterchunk=Chunk(self, None)
def setmasterchunk(self, chunk):
print 'refcount 5: ', sys.getrefcount(self.masterchunk)
self.masterchunk=chunk
print 'refcount 6: ', sys.getrefcount(self.masterchunk)
def testrecursion(self,n):
for i in range(n):
print 'refcount 6: ', sys.getrefcount(self.masterchunk)
newChunk=self.masterchunk.create(1)
return newChunk
def testhistoryremoval(self,chunk):
chunk.claimContainer()
if __name__ == '__main__':
C=Container()
middle=C.testrecursion(300)
last=C.testrecursion(600)
last=C.testhistoryremoval(middle)
if middle== C.masterchunk:
print 'SUCCESS'
</code></pre>
<p>Note added: </p>
<p>Code showing the maximum recursion depth:</p>
<pre><code>import sys
from time import sleep
class Chunk(object):
pre=None
post=None
def __init__(self, container,pre,n):
print 'Chunk Created'
self.pre=pre
self.container=container
if n>0:
self.post=Chunk(self.container,self,n-1)
def droprefs(self):
print 'refcount droprefs start: ', sys.getrefcount(self)
if not self.pre ==None:
self.pre.droprefs()
self.pre=None
self.post=None
self.container=None
print 'refcount droprefs end: ', sys.getrefcount(self)
def claimContainer(self):
self.container.setmasterchunk(self)
self.pre.droprefs()
self.pre=None
class Container(object):
masterchunk=None
def __init__(self):
pass
def setmasterchunk(self, chunk):
print 'refcount 5: ', sys.getrefcount(self.masterchunk)
self.masterchunk=chunk
print 'refcount 6: ', sys.getrefcount(self.masterchunk)
def testrecursion(self,n):
self.masterchunk=Chunk(self,None,n)
if __name__ == '__main__':
print('Try 10')
C0=Container()
C0.testrecursion(10)
sleep(2)
print('Try 1000')
C1=Container()
C1.testrecursion(1000)
</code></pre>
| 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 for anything?
chunk = self
while chunk.post is not None:
chunk = chunk.post
chunk.post = Chunk(self.container, chunk)
return self.post # this matches the old code but you may actually want `return self.post`
</code></pre>
<p>You could do something similar with <code>droprefs</code>. Your current code seems to iterate from the end of the list forwards, which may or may not be what you want. Here's a direct translation to iterative behavior:</p>
<pre><code>def droprefs(self):
chunk = self
while chunk:
next = chunk.pre # this iterates backwards, to go forwards use `next = chunk.post`
chunk.pre = None
chunk.post = None
chunk.container = None
chunk = next
</code></pre>
<p>I'd also note that unless you're expect external code to hold references to earlier <code>Chunk</code>s, you probably don't need to use <code>droprefs</code> at all. After <code>claimContainer</code> does <code>self.pre = None</code>, the garbage collector should be able to clean up all the earlier <code>Chunk</code> instances, since there are no more external references to them. Getting rid of their references to each other might make it work faster (since the <code>pre</code> and <code>post</code> attributes form reference cycles), but it is not strictly necessary.</p>
| 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 href="https://data.police.uk/data" rel="nofollow">https://data.police.uk/data</a>
. Launch this in Google Chrome and open the Developer Tools. When you select a date range, select some force and click <code>Generate File</code>, you can see a <code>POST</code> request being made with a <code>Location</code> key in the Response header.</p>
<pre><code>import requests
from urlparse import urlparse, urljoin
BASE = 'https://data.police.uk'
FORM_PATH = 'data'
form_url = urljoin(BASE, FORM_PATH)
# Get data download URL
client = requests.session()
try:
client.get(form_url)
except requests.exceptions.ConnectionError as e:
print (e)
sys.exit()
csrftoken = client.cookies.values()
l = [('forces', 'cleveland')]
t = ('csrfmiddlewaretoken', csrftoken[0])
d_from = ('date_from', '2014-05')
d_to = ('date_to', '2016-05')
l.extend((t, d_from, d_to))
r = client.post(form_url, headers=dict(Referer=form_url), data=l)
</code></pre>
<p>Querying the response headers gives me:</p>
<pre><code>In [4]: r.headers
Out[4]: {'Content-Length': '4332', 'Content-Language': 'en-gb', 'Content-Encoding': 'gzip', 'Set-Cookie': 'csrftoken=aGQ7kO4tQ2cPD0Fp2svxxYBRe4rAk0kw; expires=Thu, 03-Aug-2017 22:11:44 GMT; Max-Age=31449600; Path=/', 'Vary': 'Cookie, Accept-Language', 'Server': 'nginx', 'Connection': 'keep-alive', 'Date': 'Thu, 04 Aug 2016 22:11:44 GMT', 'Content-Type': 'text/html; charset=utf-8'}
</code></pre>
<p>Question: How do I get the <code>Location</code> key from the response header?</p>
<p><strong>EDIT</strong></p>
<p>Answer: Had to specify <code>l.append(['include_crime', 'on'])</code>. Works after this.</p>
| 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".</p>
| -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>
<pre><code>BACKPACK = {'granola bar': 1, 'cooked meat': 1, 'raw meat': 1, 'dried foods': 1}
HEALTH = 25
def rest():
print formatter()
foods = ['granola bars', 'cooked meat', 'dried foods']
for food in foods:
if food in BACKPACK:
eat_food(BACKPACK, HEALTH)
break
else:
print "You don't have any food in your pack." \
" You decide to go hunting."
# go_hunting()
def eat_food(food, health):
print food
print health
</code></pre>
<p>What I want to do is print out a list of the available foods to be eaten, if the keys in the dict correspond with the list in the function.</p>
<p>For example if I have this:</p>
<pre><code>BACKPACK = {'cooked meat': 1, 'raw meat': 1}
foods = ['granola bars', 'cooked meat', 'dried foods', 'raw meat']
</code></pre>
<p>This should output:</p>
<pre><code>1. cooked meat
2. raw meat
</code></pre>
<p>I apologize for the confusion</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)
else:
print "You don't have any food in your pack." \
" You decide to go hunting."
# go_hunting()
def eat_food(food,health):
#get rid of food
#add health
print food
rest()
</code></pre>
| 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>
<pre><code>BACKPACK = {'granola bar': 1, 'cooked meat': 1, 'raw meat': 1, 'dried foods': 1}
HEALTH = 25
def rest():
print formatter()
foods = ['granola bars', 'cooked meat', 'dried foods']
for food in foods:
if food in BACKPACK:
eat_food(BACKPACK, HEALTH)
break
else:
print "You don't have any food in your pack." \
" You decide to go hunting."
# go_hunting()
def eat_food(food, health):
print food
print health
</code></pre>
<p>What I want to do is print out a list of the available foods to be eaten, if the keys in the dict correspond with the list in the function.</p>
<p>For example if I have this:</p>
<pre><code>BACKPACK = {'cooked meat': 1, 'raw meat': 1}
foods = ['granola bars', 'cooked meat', 'dried foods', 'raw meat']
</code></pre>
<p>This should output:</p>
<pre><code>1. cooked meat
2. raw meat
</code></pre>
<p>I apologize for the confusion</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:
if y in foods:
back[y] = 1
for key, value in back.items():
print("1. " + str(key))
def eat_food(food, health):
print(food)
print(health)
rest()
</code></pre>
| 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>
<pre><code>BACKPACK = {'granola bar': 1, 'cooked meat': 1, 'raw meat': 1, 'dried foods': 1}
HEALTH = 25
def rest():
print formatter()
foods = ['granola bars', 'cooked meat', 'dried foods']
for food in foods:
if food in BACKPACK:
eat_food(BACKPACK, HEALTH)
break
else:
print "You don't have any food in your pack." \
" You decide to go hunting."
# go_hunting()
def eat_food(food, health):
print food
print health
</code></pre>
<p>What I want to do is print out a list of the available foods to be eaten, if the keys in the dict correspond with the list in the function.</p>
<p>For example if I have this:</p>
<pre><code>BACKPACK = {'cooked meat': 1, 'raw meat': 1}
foods = ['granola bars', 'cooked meat', 'dried foods', 'raw meat']
</code></pre>
<p>This should output:</p>
<pre><code>1. cooked meat
2. raw meat
</code></pre>
<p>I apologize for the confusion</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) & 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 such elementw you can therefore just write:</p>
<pre><code>if intersection:
do_sth
else:
do_sth_else
</code></pre>
| 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:
# frames are equal
raise AssertionError
</code></pre>
<p>This will use the same logic that <code>assert_frame_equal()</code> uses for comparing data frames, so the question of what constitutes equality is avoided - inequality is simply the opposite of whatever <code>assert_frame_equal()</code> determines.</p>
| 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)
raise AssertionError('DataFrames are equal.')
except AssertionError:
pass
</code></pre>
<p>Add <code>*args</code> and/or <code>**kwargs</code> as desired for flexibility.</p>
| 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 = request.json
current_app.logger.info("New data: {}".format(data))
current_app.logger.info("Userid: {}".format(userid))
socketio.emit('import', data, namespace='/events', room=userid)
return 'ok'
</code></pre>
<p>I also tried:</p>
<pre><code> with current_app.app_context():
socketio.emit('import', data, namespace='/events', room=userid)
</code></pre>
<p>On the SocketIO Context 'on.connect'</p>
<pre><code>@socketio.on('connect', namespace='/events')
def events_connect():
current_app.logger.info("CONNECT {}".format(request.namespace))
userid = request.sid
current_app.clients[userid] = request.namespace
</code></pre>
<p>The method update_client will be called from a thread.</p>
<p>On the Client side:</p>
<pre><code>$(document).ready(function(){
var socket = io.connect('http://' + document.domain + ':' + location.port +'/events');
var userid;
socket.on('connect', function() {
console.log("on connect");
});
socket.on('import', function (event) {
console.log("On import" +event);
});
</code></pre>
<p>When I call the <code>emit('import', 'test')</code> in the <code>@socketio.on('connect')</code> method the messages arrives at the client and the log message is printed.</p>
<p>There is an example in the documentation:</p>
<pre><code>@app.route('/ping')
def ping():
socketio.emit('ping event', {'data': 42}, namespace='/chat')
</code></pre>
<p>Do I miss something or why does the message not arrive at the client?</p>
<p>Edit:</p>
<p>The socketio is created in the <code>app/__init__.py</code> function</p>
<pre><code>socketio = SocketIO()
create_app():
app = Flask(__name__)
socketio.init_app(app)
</code></pre>
<p>manage.py</p>
<pre><code>from app import socketio
if __name__ == '__main__':
socketio.run(app)
</code></pre>
<p>Flask-SocketIO==2.6</p>
<p>eventlet==0.19.0</p>
| 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.</p>
<pre><code>gunicorn --worker-class eventlet -w 1 manage:app
</code></pre>
<p>I use Flask 0.11 with Flask-Migrate 2.0. Perhaps I missed something, since Flask 0.11 has a new startup command.</p>
| 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 (UserTeamLink and UserCompanyLink) are Orm tabels.</p>
<pre><code>obj = UserTeamLink
q1 = session.query(func.count(obj.type).label("cnt")).filter(obj.type == 'admin').filter(obj.user_id == id) ; str(q1) ; q1.all()
obj = UserCompanyLink
q2 = session.query(func.count(obj.type).label("cnt")).filter(obj.type == 'admin').filter(obj.user_id == id) ; str(q2) ; q2.all()
my_union = q1.union_all(q2)
query = select([func.sum(my_union.c.cnt).label("total_cnt")], from_obj=my_union)
query.all()
</code></pre>
<p>however, the line "query = select([func.sum(my_union.c.cnt).label("total_cnt")], from_obj=my_union)" breaks with: </p>
<pre><code>AttributeError: 'BaseQuery' object has no attribute 'c'
</code></pre>
<p>The entire output is as follows:</p>
<pre><code>>>> obj = UserTeamLink
>>> q1 = session.query(func.count(obj.type).label("cnt")).filter(obj.type == 'admin').filter(obj.user_id == id) ; str(q1) ; q1.all()
'SELECT count(user_team.type) AS cnt \nFROM user_team \nWHERE user_team.type = :type_1 AND user_team.user_id = :user_id_1'
[(0L,)]
>>> obj = UserCompanyLink
>>> q2 = session.query(func.count(obj.type).label("cnt")).filter(obj.type == 'admin').filter(obj.user_id == id) ; str(q2) ; q2.all()
'SELECT count(user_company.type) AS cnt \nFROM user_company \nWHERE user_company.type = :type_1 AND user_company.user_id = :user_id_1'
[(0L,)]
>>>
>>> my_union = q1.union_all(q2)
>>> query = select([func.sum(my_union.c.cnt).label("total_cnt")], from_obj=my_union)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'BaseQuery' object has no attribute 'c'
</code></pre>
<p>Is there a way to fix this?</p>
<p>In summary what I'm attempting to do is select counts from both tables, then union into another table and then add them.</p>
<p>Thank you.</p>
| 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 (UserTeamLink and UserCompanyLink) are Orm tabels.</p>
<pre><code>obj = UserTeamLink
q1 = session.query(func.count(obj.type).label("cnt")).filter(obj.type == 'admin').filter(obj.user_id == id) ; str(q1) ; q1.all()
obj = UserCompanyLink
q2 = session.query(func.count(obj.type).label("cnt")).filter(obj.type == 'admin').filter(obj.user_id == id) ; str(q2) ; q2.all()
my_union = q1.union_all(q2)
query = select([func.sum(my_union.c.cnt).label("total_cnt")], from_obj=my_union)
query.all()
</code></pre>
<p>however, the line "query = select([func.sum(my_union.c.cnt).label("total_cnt")], from_obj=my_union)" breaks with: </p>
<pre><code>AttributeError: 'BaseQuery' object has no attribute 'c'
</code></pre>
<p>The entire output is as follows:</p>
<pre><code>>>> obj = UserTeamLink
>>> q1 = session.query(func.count(obj.type).label("cnt")).filter(obj.type == 'admin').filter(obj.user_id == id) ; str(q1) ; q1.all()
'SELECT count(user_team.type) AS cnt \nFROM user_team \nWHERE user_team.type = :type_1 AND user_team.user_id = :user_id_1'
[(0L,)]
>>> obj = UserCompanyLink
>>> q2 = session.query(func.count(obj.type).label("cnt")).filter(obj.type == 'admin').filter(obj.user_id == id) ; str(q2) ; q2.all()
'SELECT count(user_company.type) AS cnt \nFROM user_company \nWHERE user_company.type = :type_1 AND user_company.user_id = :user_id_1'
[(0L,)]
>>>
>>> my_union = q1.union_all(q2)
>>> query = select([func.sum(my_union.c.cnt).label("total_cnt")], from_obj=my_union)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'BaseQuery' object has no attribute 'c'
</code></pre>
<p>Is there a way to fix this?</p>
<p>In summary what I'm attempting to do is select counts from both tables, then union into another table and then add them.</p>
<p>Thank you.</p>
| 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"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.