title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Django: send json response from view to a specific template | 38,923,165 | <p>The main requirement is to send a json object from django view to a specific template named output.html (already present in templates directory), <strong>as a part of response</strong>. Also, the json response contains <strong>model</strong> and <strong>pk</strong> attribute, I want to remove them and send only the <strong>fields</strong> json attribute.</p>
<p><strong>When I try as follows :</strong></p>
<pre><code>def view_personal_details (request):
personal_detail_json = personal_details.objects.all()
personal_detail = serializers.serialize('json', personal_detail_json)
return HttpResponse (serializers.serialize('json', personal_detail_json), content_type='application/json');
</code></pre>
<p>I get json in a new page.</p>
<p><strong>And when I try as follows :</strong></p>
<pre><code>def view_personal_details (request):
personal_detail_json = personal_details.objects.all()
personal_detail = serializers.serialize('json', personal_detail_json)
return render (request, "webFiles/output.html", {'personal_detail': personal_detail})
</code></pre>
<p>I have to access the data via <strong>{{ personal_detail }}</strong> in my html, and not from response.</p>
<p>Also, the json response is as follows :</p>
<pre><code>[
{
model: "buglockerApp.personal_details",
pk: "001",
fields: {
name: "Rajiv Gupta",
email: "rajiv@247-inc.com",
doj: "2016-06-22",
dob: "2016-06-22",
address: "Bangalore",
contact: "9909999999"
}
}
]
</code></pre>
<p>I don't want the <strong>model</strong> and <strong>pk</strong> to be sent as the response. Only <strong>fields</strong> should be sent as a part of response to webFiles/output.html file.</p>
<p>Thanks in advance!!</p>
| 0 | 2016-08-12T17:05:26Z | 38,923,629 | <p>The default serializers always add the model and pk so that the data can be deserialized back into objects. Either you can write a custom serializer or can simply remove the unwanted data. </p>
<pre><code>personal_details = [pd['fields'] for pd in personal_details]
</code></pre>
<p>This should give you a new list of dicts with personal details</p>
| 0 | 2016-08-12T17:37:14Z | [
"python",
"json",
"django"
] |
Django: send json response from view to a specific template | 38,923,165 | <p>The main requirement is to send a json object from django view to a specific template named output.html (already present in templates directory), <strong>as a part of response</strong>. Also, the json response contains <strong>model</strong> and <strong>pk</strong> attribute, I want to remove them and send only the <strong>fields</strong> json attribute.</p>
<p><strong>When I try as follows :</strong></p>
<pre><code>def view_personal_details (request):
personal_detail_json = personal_details.objects.all()
personal_detail = serializers.serialize('json', personal_detail_json)
return HttpResponse (serializers.serialize('json', personal_detail_json), content_type='application/json');
</code></pre>
<p>I get json in a new page.</p>
<p><strong>And when I try as follows :</strong></p>
<pre><code>def view_personal_details (request):
personal_detail_json = personal_details.objects.all()
personal_detail = serializers.serialize('json', personal_detail_json)
return render (request, "webFiles/output.html", {'personal_detail': personal_detail})
</code></pre>
<p>I have to access the data via <strong>{{ personal_detail }}</strong> in my html, and not from response.</p>
<p>Also, the json response is as follows :</p>
<pre><code>[
{
model: "buglockerApp.personal_details",
pk: "001",
fields: {
name: "Rajiv Gupta",
email: "rajiv@247-inc.com",
doj: "2016-06-22",
dob: "2016-06-22",
address: "Bangalore",
contact: "9909999999"
}
}
]
</code></pre>
<p>I don't want the <strong>model</strong> and <strong>pk</strong> to be sent as the response. Only <strong>fields</strong> should be sent as a part of response to webFiles/output.html file.</p>
<p>Thanks in advance!!</p>
| 0 | 2016-08-12T17:05:26Z | 38,924,020 | <p>you can do the following in python2.7</p>
<pre><code>import json
from django.http import JsonResponse
def view_personal_details (request):
personal_detail = serializers.serialize('json', personal_details.objects.all())
output = [d['fields'] for d in json.loads(personal_detail)]
# return render (request, "webFiles/output.html", {'personal_detail': output})
# for ajax response
return JsonResponse({'personal_detail': output})
</code></pre>
<p>or you can read the following for more clarification <br>
<a href="https://docs.djangoproject.com/en/1.10/topics/serialization/#serialization-of-natural-keys" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/serialization/#serialization-of-natural-keys</a><br>
<a href="https://github.com/django/django/blob/master/django/core/serializers/base.py#L53" rel="nofollow">https://github.com/django/django/blob/master/django/core/serializers/base.py#L53</a></p>
| 0 | 2016-08-12T18:04:50Z | [
"python",
"json",
"django"
] |
matplotlib interactive⦠isn't | 38,923,185 | <p>I'm running Python 3.5.1 with matplotlib version 1.5.1 and iPython 5.0.0. I can't seem to get matplotlib's interactive feature working. I can run a command to create a plot:</p>
<pre><code>import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,2,3])
</code></pre>
<p>This doesn't show a figure until I manually execute <code>plt.show()</code>, at which point iPython hangs until I close the figure window. I have interactive set to True in my matplotlibrc file.</p>
<p>It's been a year or so since I used matplotlib. The last time I used it, I got interactive without having to execute <code>plt.show()</code>. <strong>Has something changed or am I doing something wrong?</strong></p>
| 1 | 2016-08-12T17:06:25Z | 38,923,236 | <p>You were probably using interactive mode previously.</p>
<p>Start ipython with:</p>
<pre><code>ipython --pylab
</code></pre>
<p>Then your plots will show up instantly.</p>
| 2 | 2016-08-12T17:11:16Z | [
"python",
"matplotlib",
"interactive"
] |
Using the .loc function of the pandas dataframe | 38,923,280 | <p>i have a pandas dataframe whose one of the column is : </p>
<pre><code> a = [1,0,1,0,1,3,4,6,4,6]
</code></pre>
<p>now i want to create another column such that any value greater than 0 and less than 5 is assigned 1 and rest is assigned 0 ie:</p>
<pre><code>a = [1,0,1,0,1,3,4,6,4,6]
b = [1,0,1,0,1,1,1,0,1,0]
</code></pre>
<p>now i have done this </p>
<pre><code>dtaframe['b'] = dtaframe['a'].loc[0 < dtaframe['a'] < 5] = 1
dtaframe['b'] = dtaframe['a'].loc[dtaframe['a'] >4 or dtaframe['a']==0] = 0
</code></pre>
<p>but the code throws and error . what to do ?</p>
| 3 | 2016-08-12T17:13:57Z | 38,923,354 | <p>When using comparison operators and boolean logic to filter dataframes you can't use the pythonic idiom of <code>a < myseries < b</code>. Instead you need to <code>(a < myseries) & (myseries < b)</code></p>
<pre><code>cond1 = (0 < dtaframe['a'])
cond2 = (dtaframe['a'] <= 5)
dtaframe['b'] = (cond1 & cond2) * 1
</code></pre>
| 3 | 2016-08-12T17:19:49Z | [
"python",
"pandas",
"dataframe"
] |
Using the .loc function of the pandas dataframe | 38,923,280 | <p>i have a pandas dataframe whose one of the column is : </p>
<pre><code> a = [1,0,1,0,1,3,4,6,4,6]
</code></pre>
<p>now i want to create another column such that any value greater than 0 and less than 5 is assigned 1 and rest is assigned 0 ie:</p>
<pre><code>a = [1,0,1,0,1,3,4,6,4,6]
b = [1,0,1,0,1,1,1,0,1,0]
</code></pre>
<p>now i have done this </p>
<pre><code>dtaframe['b'] = dtaframe['a'].loc[0 < dtaframe['a'] < 5] = 1
dtaframe['b'] = dtaframe['a'].loc[dtaframe['a'] >4 or dtaframe['a']==0] = 0
</code></pre>
<p>but the code throws and error . what to do ?</p>
| 3 | 2016-08-12T17:13:57Z | 38,923,436 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow"><code>between</code></a> to get Boolean values, then <code>astype</code> to convert from Boolean values to 0/1:</p>
<pre><code>dtaframe['b'] = dtaframe['a'].between(0, 5, inclusive=False).astype(int)
</code></pre>
<p>The resulting output:</p>
<pre><code> a b
0 1 1
1 0 0
2 1 1
3 0 0
4 1 1
5 3 1
6 4 1
7 6 0
8 4 1
9 6 0
</code></pre>
<p><strong>Edit</strong></p>
<p>For multiple ranges, you could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow"><code>pandas.cut</code></a>:</p>
<pre><code>dtaframe['b'] = pd.cut(dtaframe['a'], bins=[0,1,6,9], labels=False, include_lowest=True)
</code></pre>
<p>You'll need to be careful about how you define <code>bins</code>. Using <code>labels=False</code> will return integer indicators for each bin, which happens to correspond with the labels you provided. You could also manually specify the labels for each bin, e.g. <code>labels=[0,1,2]</code>, <code>labels=[0,17,19]</code>, <code>labels=['a','b','c']</code>, etc. You may need to use <code>astype</code> if you manually specify the labels, as they'll be returned as categories.</p>
<p>Alternatively, you could combine <code>loc</code> and <code>between</code> to manually specify each range:</p>
<pre><code>dtaframe.loc[dtaframe['a'].between(0,1), 'b'] = 0
dtaframe.loc[dtaframe['a'].between(2,6), 'b'] = 1
dtaframe.loc[dtaframe['a'].between(7,9), 'b'] = 2
</code></pre>
| 4 | 2016-08-12T17:24:24Z | [
"python",
"pandas",
"dataframe"
] |
Using the .loc function of the pandas dataframe | 38,923,280 | <p>i have a pandas dataframe whose one of the column is : </p>
<pre><code> a = [1,0,1,0,1,3,4,6,4,6]
</code></pre>
<p>now i want to create another column such that any value greater than 0 and less than 5 is assigned 1 and rest is assigned 0 ie:</p>
<pre><code>a = [1,0,1,0,1,3,4,6,4,6]
b = [1,0,1,0,1,1,1,0,1,0]
</code></pre>
<p>now i have done this </p>
<pre><code>dtaframe['b'] = dtaframe['a'].loc[0 < dtaframe['a'] < 5] = 1
dtaframe['b'] = dtaframe['a'].loc[dtaframe['a'] >4 or dtaframe['a']==0] = 0
</code></pre>
<p>but the code throws and error . what to do ?</p>
| 3 | 2016-08-12T17:13:57Z | 38,924,007 | <p>Try this with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow">np.where</a>:</p>
<pre><code>dtaframe['b'] = np.where(([dtaframe['a'] > 4) | (dtaframe['a']==0),0, dtaframe['a'])
</code></pre>
| 1 | 2016-08-12T18:03:54Z | [
"python",
"pandas",
"dataframe"
] |
Does tweepy handle rate limit - code 429 | 38,923,298 | <p>I have a wrapper class for the twitter authentication where there is a line: </p>
<pre><code>self.__api = tweepy.API(self.auth,
wait_on_rate_limit=False,
wait_on_rate_limit_notify=False)
</code></pre>
<p>When I instantiate the wrapper class to get api object of twitter: </p>
<pre><code>api_call = myWrapper(self.CONSUMER_KEY, self.CONSUMER_SECRET,
self.ACCESS_KEY, self.ACCESS_SECRET, True, True)
</code></pre>
<p>Based on my understanding setting up wait_on_rate_limit and wait_on_rate_limit_notify to True should default take care the rate issue (Based on tweepy documentation). </p>
<p>But I get following error when I am iterating over list of users and try to get their timeline <strong>(~3400)</strong>
<code>tweepy.error.TweepError: Twitter error response: status code = 429</code></p>
<p>I tried following: </p>
<pre><code>remaining = int(api_call.api.last_response.getheader('X-Rate-Limit-Remaining'))
</code></pre>
<p>but it says <code>last_response</code> attribute is not available.</p>
| 0 | 2016-08-12T17:14:59Z | 38,923,993 | <p>No, you have to create a handler for this exception.</p>
| 0 | 2016-08-12T18:02:58Z | [
"python",
"tweepy"
] |
Import "request" object in a views' function without pass it as argument | 38,923,306 | <p>please, I need help with that "request" object that is making me despair...</p>
<p>I read that theoretically "request" in views is an "HttpRequest" object but I have a script which needs to call a views.py function, which needs to use that "request" so receive it as argument.</p>
<p>Then I tried to import that object in my script in so many modes, but it seems always <strong>"not be the same"</strong> and I get annoying errors as:
<strong>"'HttpRequest' object has no attribute 'session'"</strong></p>
<p>Is there another way to use "request" object in a view's function avoiding to pass as argument?
Something like this:?</p>
<pre><code>def view_function():
request = ??
form = fooform
bar = request.session['foo']
context{
'form' = form
'bar' = bar
}
return render(request, "foo.html", context)
</code></pre>
<p>I know that's not elegant, but I'm still learning and I really don't need for this program an elegant solution.
Thanks in advance</p>
| -1 | 2016-08-12T17:15:39Z | 38,930,991 | <p>I fixed it! The argument with @Daniel Roseman made me realise that I forgot to pass the "request" parameter when I call my script main funcion. That's why my external script "didn't know" what "request" was.</p>
<p>Thanks @Daniel Roseman for your patience!</p>
| 0 | 2016-08-13T08:52:22Z | [
"python",
"django",
"parameters",
"request",
"arguments"
] |
Why do some variables need to global while others don't? | 38,923,350 | <p>In the code below, why do I have to set the <code>num</code> variable to <code>global</code> inside the function but not <code>folder</code> or <code>rename_prefix</code>? If I remove the <code>global</code> from the function, <code>num</code> cannot be used in the function but the <code>folder</code> and <code>rename_prefix</code> variable still can? I don't understand. Can someone explain my misunderstanding of global and local variables. Thanks </p>
<pre><code>import os
# User Input
folder = r'F:\Pictures\2016\iPhone Pics\rename_test'
rename_prefix = 'Renamed_' # ENTER WHAT YOU WANT PREFIX OF IMAGE TO BE
num = 0
def file_renamer():
global num
for root, dir2, files in os.walk(folder):
print 'Renaming Files in {} \n'.format(root)
if len(dir2) > 0:
print 'Found the following sub folders {} \n'.format(dir2)
#print 'Found {} subfolders named {} and {}'.format(len(dir2),dir2[0],dir2[1])
#num = 0 uncomment if you want each folder to start renaming files at 0
for x in files:
local_folder = os.path.join(folder, root)
old = os.path.join(local_folder, x)
#if x.startswith('IMG'):
if old.lower().endswith(('.jpg')):
print 'Renaming {0}'.format(x)
num2 = '{0}.jpg'.format(num)
rename_name = rename_prefix + num2
rename_path = os.path.join(local_folder, rename_prefix + num2)
os.rename(old, rename_path)
print 'Successfully renamed {0} to {1} \n'.format(x, rename_name)
num += 1
elif old.lower().endswith('.png'):
print 'Renaming {0}'.format(x)
num2 = '{0}.png'.format(num)
rename_name = rename_prefix + num2
rename_path = os.path.join(local_folder, rename_prefix + num2)
os.rename(old, rename_path)
print 'Successfully renamed {0} to {1} \n'.format(x, rename_name)
num += 1
elif old.lower().endswith('.mov'):
print 'Renaming {0}'.format(x)
num2 = '{0}.mov'.format(num)
rename_name = rename_prefix + num2
rename_path = os.path.join(local_folder, rename_prefix + num2)
os.rename(old, rename_path)
print 'Successfully renamed {0} to {1} \n'.format(x, rename_name)
num += 1
else:
print 'IDK what file type {0} is !!, skipping...'.format(x)
continue
#else:
#print '{} Does not meet renaming criteria, moving to next file'.format(x)
#continue
print 'Finished Renaming all files in {}'.format(folder)
file_renamer()enter code here
</code></pre>
| 1 | 2016-08-12T17:19:34Z | 38,923,618 | <pre><code>x = 0
def function_name():
x = 2
function_name()
x #yields:0
</code></pre>
<p>but if you define:</p>
<pre><code>def function_name():
global x
x = 2
</code></pre>
<p>then execute</p>
<pre><code>function_name()
x #yields 2
</code></pre>
| 1 | 2016-08-12T17:36:49Z | [
"python",
"global-variables"
] |
Why do some variables need to global while others don't? | 38,923,350 | <p>In the code below, why do I have to set the <code>num</code> variable to <code>global</code> inside the function but not <code>folder</code> or <code>rename_prefix</code>? If I remove the <code>global</code> from the function, <code>num</code> cannot be used in the function but the <code>folder</code> and <code>rename_prefix</code> variable still can? I don't understand. Can someone explain my misunderstanding of global and local variables. Thanks </p>
<pre><code>import os
# User Input
folder = r'F:\Pictures\2016\iPhone Pics\rename_test'
rename_prefix = 'Renamed_' # ENTER WHAT YOU WANT PREFIX OF IMAGE TO BE
num = 0
def file_renamer():
global num
for root, dir2, files in os.walk(folder):
print 'Renaming Files in {} \n'.format(root)
if len(dir2) > 0:
print 'Found the following sub folders {} \n'.format(dir2)
#print 'Found {} subfolders named {} and {}'.format(len(dir2),dir2[0],dir2[1])
#num = 0 uncomment if you want each folder to start renaming files at 0
for x in files:
local_folder = os.path.join(folder, root)
old = os.path.join(local_folder, x)
#if x.startswith('IMG'):
if old.lower().endswith(('.jpg')):
print 'Renaming {0}'.format(x)
num2 = '{0}.jpg'.format(num)
rename_name = rename_prefix + num2
rename_path = os.path.join(local_folder, rename_prefix + num2)
os.rename(old, rename_path)
print 'Successfully renamed {0} to {1} \n'.format(x, rename_name)
num += 1
elif old.lower().endswith('.png'):
print 'Renaming {0}'.format(x)
num2 = '{0}.png'.format(num)
rename_name = rename_prefix + num2
rename_path = os.path.join(local_folder, rename_prefix + num2)
os.rename(old, rename_path)
print 'Successfully renamed {0} to {1} \n'.format(x, rename_name)
num += 1
elif old.lower().endswith('.mov'):
print 'Renaming {0}'.format(x)
num2 = '{0}.mov'.format(num)
rename_name = rename_prefix + num2
rename_path = os.path.join(local_folder, rename_prefix + num2)
os.rename(old, rename_path)
print 'Successfully renamed {0} to {1} \n'.format(x, rename_name)
num += 1
else:
print 'IDK what file type {0} is !!, skipping...'.format(x)
continue
#else:
#print '{} Does not meet renaming criteria, moving to next file'.format(x)
#continue
print 'Finished Renaming all files in {}'.format(folder)
file_renamer()enter code here
</code></pre>
| 1 | 2016-08-12T17:19:34Z | 38,923,624 | <p>As people in the comments point out, the reason that you don't need to use <code>global</code> for <code>folder</code> and <code>rename_prefix</code> but you do for <code>num</code> is that you're only reading the former two whilst you're setting the latter.</p>
<p>If you didn't declare <code>num</code> global, what would happen is that assignments to <code>num</code> would create and assign to a new local variable <code>num</code> which would shadow the global <code>num</code>, instead of actually setting the value of the already-defined global <code>num</code> as you might expect.</p>
| 2 | 2016-08-12T17:36:56Z | [
"python",
"global-variables"
] |
Reducing the number of queries in Django | 38,923,367 | <p>I'm creating a Django app that tracks awards that a person receives. Below is a simplified representation of two models that I have:</p>
<pre><code>class AwardHolder(models.Model):
name = models.CharField()
def get_total_awards(self):
entries = self.award_set.all()
calc = entries.aggregate(sum=Sum('units_awarded'))
return calc.get('sum') or 0
class Award(models.Model)
date_awarded = models.DateField()
units_awarded = models.IntegerField()
award_holder = models.ForeignKey(AwardHolder)
</code></pre>
<p>I created a summary page for the award holder where he can see his total awards. I use the <code>get_total_awards</code> function above. That all works well, but then I created an overview page to display the total awards per award holder. I use the function below to get the total awards per award holder:</p>
<pre><code>def get_all_awards():
qs = AwardHolder.objects.all()
awards = []
for ah in qs:
awards.append((ah, ah.get_total_awards())
return awards
</code></pre>
<p>This generates a large number of queries since it hits the db every loop. Is there a way I can use <code>prefetch_related</code> or some other db trick to reduce the number of db queries, without having to rewrite <code>get_all_awards()</code>?</p>
<p>The actual code I use has a lot more fields and is more complicated than this example. There's about 10 functions similar to <code>get_all_awards()</code>, so rewriting it will be quite some work. However, for 100 award holders my code generated a whopping 18000 queries, so I know I have to fix this somehow.</p>
| 1 | 2016-08-12T17:20:34Z | 38,923,739 | <p><code>get_all_awards</code> does not necessarily have to call <code>get_total_awards</code>. You're repeating the same query for each entity instead of using a functionality Django already provides: <code>annotate</code>. </p>
<p>You can modify <code>get_all_awards</code> to use <code>annotate</code> and use <code>get_total_awards</code> only when the award applies to a single entity.</p>
<pre><code>def get_all_awards():
qs = AwardHolder.objects.annotate(sum=Sum('award__units_awarded'))
awards = []
for ah in qs:
awards.append((ah, ah.sum))
return awards
</code></pre>
<p>You may even drop the <code>for</code> loop and use the result from the queryset <code>qs</code> directly.</p>
<p>So you get the advantage of an optimized query when multiple objects and their related objects are being fetched, as opposed to running individual queries for each entity.</p>
| 1 | 2016-08-12T17:44:59Z | [
"python",
"django"
] |
Reducing the number of queries in Django | 38,923,367 | <p>I'm creating a Django app that tracks awards that a person receives. Below is a simplified representation of two models that I have:</p>
<pre><code>class AwardHolder(models.Model):
name = models.CharField()
def get_total_awards(self):
entries = self.award_set.all()
calc = entries.aggregate(sum=Sum('units_awarded'))
return calc.get('sum') or 0
class Award(models.Model)
date_awarded = models.DateField()
units_awarded = models.IntegerField()
award_holder = models.ForeignKey(AwardHolder)
</code></pre>
<p>I created a summary page for the award holder where he can see his total awards. I use the <code>get_total_awards</code> function above. That all works well, but then I created an overview page to display the total awards per award holder. I use the function below to get the total awards per award holder:</p>
<pre><code>def get_all_awards():
qs = AwardHolder.objects.all()
awards = []
for ah in qs:
awards.append((ah, ah.get_total_awards())
return awards
</code></pre>
<p>This generates a large number of queries since it hits the db every loop. Is there a way I can use <code>prefetch_related</code> or some other db trick to reduce the number of db queries, without having to rewrite <code>get_all_awards()</code>?</p>
<p>The actual code I use has a lot more fields and is more complicated than this example. There's about 10 functions similar to <code>get_all_awards()</code>, so rewriting it will be quite some work. However, for 100 award holders my code generated a whopping 18000 queries, so I know I have to fix this somehow.</p>
| 1 | 2016-08-12T17:20:34Z | 38,923,743 | <p>Use a model manager to always annotate <code>AwardHolders</code></p>
<pre><code>class AwardHolderQuerySet(models.QuerySet):
def all(self):
return self.annotate(Count('award__units_awarded'))
class AwardHolder(models.Model):
name = models.CharField()
objects = AwardHolderQuerySet.as_manager()
...
</code></pre>
| 1 | 2016-08-12T17:45:16Z | [
"python",
"django"
] |
Python Tkinter: how to reopen application by clicking Dock icon on Mac? | 38,923,478 | <p>I bind the close button with root.withdraw(), so the application will close its window instead of quitting, but seems the application hangs on, and cannot be reopened by clicking Dock icon</p>
<p>How to bind the method root.deiconify() to do this?</p>
<p>I package the application with pyinstaller</p>
<p>Update:
The python tkinter application seems hanging on after run root.iconify() or root.withdraw(), so there is no respond by clicking the icon on Dock. Here is the test code</p>
<pre><code>from Tkinter import *
from ScrolledText import ScrolledText
import threading, time, os
def printnumber(output):
n = 1
while 1:
output.insert(END, '%s\n'%str(n))
output.see(END)
n += 1
time.sleep(1)
def runing(output):
output.insert(END, 'Start\n')
output.see(END)
threading.Thread(target=printnumber, args=(output, )).start()
root = Tk()
text_output = ScrolledText(root, undo=1, highlightthickness=0, font='system', )
text_output.pack()
Button(root, text='Start', command=runing(text_output)).pack()
root.protocol('WM_DELETE_WINDOW', lambda :root.iconify())
os.system('''/usr/bin/osascript -e 'tell app "System Events" to set frontmost of every process whose unix id is %s to true' '''%os.getpid())
root.mainloop()
</code></pre>
| -2 | 2016-08-12T17:26:42Z | 38,924,838 | <p>If you are using OS X 10.9 or later and a Python from a python.org 64-bit/32-bit installer, application windows may not update properly due to a Tk problem. Install the latest ActiveTcl 8.5.18.0 if possible. (Also, a critical OS X 10.9 problem that could cause Python to crash when used interactively has been fixed as of the 3.4.0, 3.3.3, and 2.7.6 installers.)</p>
<ul>
<li>That was taken from this link <a href="https://www.python.org/download/mac/tcltk/" rel="nofollow">https://www.python.org/download/mac/tcltk/</a></li>
</ul>
<p>There is a whole section Talking about different problems with Tk/IDLE depending on what version of OS X you're using.</p>
| 0 | 2016-08-12T19:00:31Z | [
"python",
"tkinter"
] |
Python Tkinter: how to reopen application by clicking Dock icon on Mac? | 38,923,478 | <p>I bind the close button with root.withdraw(), so the application will close its window instead of quitting, but seems the application hangs on, and cannot be reopened by clicking Dock icon</p>
<p>How to bind the method root.deiconify() to do this?</p>
<p>I package the application with pyinstaller</p>
<p>Update:
The python tkinter application seems hanging on after run root.iconify() or root.withdraw(), so there is no respond by clicking the icon on Dock. Here is the test code</p>
<pre><code>from Tkinter import *
from ScrolledText import ScrolledText
import threading, time, os
def printnumber(output):
n = 1
while 1:
output.insert(END, '%s\n'%str(n))
output.see(END)
n += 1
time.sleep(1)
def runing(output):
output.insert(END, 'Start\n')
output.see(END)
threading.Thread(target=printnumber, args=(output, )).start()
root = Tk()
text_output = ScrolledText(root, undo=1, highlightthickness=0, font='system', )
text_output.pack()
Button(root, text='Start', command=runing(text_output)).pack()
root.protocol('WM_DELETE_WINDOW', lambda :root.iconify())
os.system('''/usr/bin/osascript -e 'tell app "System Events" to set frontmost of every process whose unix id is %s to true' '''%os.getpid())
root.mainloop()
</code></pre>
| -2 | 2016-08-12T17:26:42Z | 38,967,103 | <p>Finally I found the solution from here <a href="http://www.tkdocs.com/tutorial/menus.html" rel="nofollow">http://www.tkdocs.com/tutorial/menus.html</a></p>
<pre><code>root.createcommand('tk::mac::ReopenApplication', root.deiconify)
</code></pre>
| 0 | 2016-08-16T05:17:35Z | [
"python",
"tkinter"
] |
Infeasible solution with redundant constraints - PuLP and COIN-OR | 38,923,713 | <p>im working with an LP model in python using <code>PuLP</code> with <code>CBC</code>. The model has a lot of constraints, and of course many of them are redundant. i will show an example of that. </p>
<pre><code>#import libraries
from pulp import LpVariable, LpProblem, LpMaximize, lpSum, LpConstraint, LpStatus, value
prob = LpProblem("test_model", LpMaximize)
set_pt=[i for i in range(100)] #set of var
var = LpVariable.dicts("var",set_pt,lowBound=0,cat='Continuous')
# The objective function is added to 'prob' first
prob += lpSum([var[i] for i in set_pt]), "f(v)"
#constraits
for i in set_pt:
prob += LpConstraint(var[i] <= 300000), "max margin "+str(i)
prob += LpConstraint(var[i] <= 30000000000), "ma2 margin "+str(i)
#solve
prob.writeLP("price_mod2.lp")
print 'solver begin'
prob.solve()
# The status of the solution is printed to the screen
print "Status:", LpStatus[prob.status]
</code></pre>
<p>the result of this is: </p>
<pre><code>solver begin
Status: Infeasible
</code></pre>
<p>of course in this example both constraints are obviously redundant and in the problem that im solving is a little bit more difficult to see witch of the constraints are redundant. </p>
<p>i don't know if the problem is with the solver (<code>CBC</code>), so i can use maybe <code>CPLEX</code> instead and solve the problem of the redundant constraints, or the problem is <code>PuLP</code> and i need to use another library. Or maybe i need to model the problem to make it redundancy proof. </p>
<p>any guidance ?
Thanks!</p>
<p><strong>Edit:</strong> I tried with open solver (in excel) using <code>CBC</code> and it worked, so i think that must be a problem with the implementation in <code>PuLP</code>, or maybe im doing something wrong or maybe there is not way to add redundant constraint in <code>PuLP</code></p>
| 0 | 2016-08-12T17:43:01Z | 38,924,225 | <p>I didn't use pulp much, so i can't explain the internals here (which make your case fail), but <em>you are using pulp's constraint-mechanism in a wrong way</em>.</p>
<h3>Your approach (fails):</h3>
<pre><code>for i in set_pt:
prob += LpConstraint(var[i] <= 300000), "max margin "+str(i)
prob += LpConstraint(var[i] <= 30000000000), "ma2 margin "+str(i)
</code></pre>
<h3>Working alternative A (using overloaded operators)</h3>
<pre><code>for i in set_pt:
prob += var[i] <= 300000, "max margin "+str(i)
prob += var[i] <= 30000000000, "ma2 margin "+str(i)
</code></pre>
<h3>Working alternative B (explicit use of <code>LpConstraint</code>; needs importing)</h3>
<pre><code>for i in set_pt:
prob += LpConstraint(var[i], LpConstraintLE, 300000), "max margin "+str(i)
prob += LpConstraint(var[i], LpConstraintLE, 30000000000), "ma2 margin "+str(i)
</code></pre>
<p>The latter is more like your initial approach. But your usage doesn't look like something the function expects (see <a href="http://www.coin-or.org/PuLP/pulp.html#constraints" rel="nofollow">docs</a>)</p>
| 0 | 2016-08-12T18:19:45Z | [
"python",
"constraints",
"linear-programming",
"pulp",
"coin-or-cbc"
] |
Very weird python flask behaviour | 38,923,728 | <p>When ever I access my python flask website and go to myurl.com/newuser I get the necessary html page returned. this page has a submit button and it is supposed to pass info to the the server when pressed. but when it is pressed it redirects me to the 'index' method of the website and the information is not passed on to the database? I do not understand this, here is my code: (sql info missed obviously)</p>
<pre><code>from flask import Flask, redirect, render_template, request, url_for
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["DEBUG"] = True
SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
username="",
password="",
hostname="",
databasename="",
)
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
db = SQLAlchemy(app)
class Users(db.Model):
__tablename__ = "userstable"
userid = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(4096))
password = db.Column(db.String(4096))
@app.route("/", methods=["GET", "POST"])
def index():
return render_template("index.html")
@app.route("/newuser", methods=["GET", "POST"])
def NewUser():
if request.method == "GET":
return render_template("NewUser.html")
usernameSet = Users(username=request.form["Username"])
passwordSet = Users(password=request.form["Password"])
db.session.add(usernameSet)
db.session.add(passwordSet)
db.session.commit()
return redirect(url_for('NewUser'))
</code></pre>
<p>NewUser Template:</p>
<pre class="lang-html prettyprint-override"><code><html>
<body>
<form action="." method="POST">
<input type="text" value="" name="Username">
<input type="text" value="" name="Password">
<input type="submit" value="Submit">
</form>
</body>
</html>
</code></pre>
| -6 | 2016-08-12T17:44:05Z | 38,930,365 | <p>Like Martijn said, change </p>
<pre><code> usernameSet = Users(username=request.form["Username"])
passwordSet = Users(password=request.form["Password"])
db.session.add(usernameSet)
db.session.add(passwordSet)
</code></pre>
<p>to</p>
<pre><code> user = Users(username=request.form["Username"], password=request.form["Password"])
db.session.add(user)
</code></pre>
<p>But the real problem might be with your html form, where you have to add form action to include the receiving URL.</p>
<pre><code> <form action="/newuser" method="POST">
</code></pre>
| 0 | 2016-08-13T07:30:24Z | [
"python",
"flask"
] |
Assign multiple values to multiple slices of a numpy array at once | 38,923,763 | <p>I have a numpy array, a list of start/end indexes that define ranges within the array, and a list of values, where the number of values is the same as the number of ranges. Doing this assignment in a loop is currently very slow, so I'd like to assign the values to the corresponding ranges in the array in a vectorized way. Is this possible to do?</p>
<p>Here's a concrete, simplified example:</p>
<p><code>a = np.zeros([10])</code></p>
<p>Here's the list of start and a list of end indexes that define ranges within <code>a</code>, like this:</p>
<pre><code>starts = [0, 2, 4, 6]
ends = [2, 4, 6, 8]
</code></pre>
<p>And here's a list of values I'd like to assign to each range:</p>
<p><code>values = [1, 2, 3, 4]</code></p>
<p>I have two problems. The first is that I can't figure out how to index into the array using multiple slices at the same time, since the list of ranges is constructed dynamically in the actual code. Once I'm able to extract the ranges, I'm not sure how to assign multiple values at once - one value per range.</p>
<p>Here's how I've tried creating a list of slices and the problems I've run into when using that list to index into the array:</p>
<pre><code>slices = [slice(start, end) for start, end in zip(starts, ends)]
In [97]: a[slices]
...
IndexError: too many indices for array
In [98]: a[np.r_[slices]]
...
IndexError: arrays used as indices must be of integer (or boolean) type
</code></pre>
<p>If I use a static list, I can extract multiple slices at once, but then assignment doesn't work the way I want:</p>
<pre><code>In [106]: a[np.r_[0:2, 2:4, 4:6, 6:8]] = [1, 2, 3]
/usr/local/bin/ipython:1: DeprecationWarning: assignment will raise an error in the future, most likely because your index result shape does not match the value array shape. You can use `arr.flat[index] = values` to keep the old behaviour.
#!/usr/local/opt/python/bin/python2.7
In [107]: a
Out[107]: array([ 1., 2., 3., 1., 2., 3., 1., 2., 0., 0.])
</code></pre>
<p>What I actually want is this:</p>
<p>np.array([1., 1., 2., 2., 3., 3., 4., 4., 0., 0.])</p>
| 1 | 2016-08-12T17:46:45Z | 38,924,029 | <p>One possibility is to zip the start, end index with the values and broadcast the index and values manually:</p>
<pre><code>starts = [0, 2, 4, 6]
ends = [2, 4, 6, 8]
values = [1, 2, 3, 4]
a = np.zeros(10)
import numpy as np
# calculate the index array and value array by zipping the starts, ends and values and expand it
idx, val = zip(*[(list(range(s, e)), [v] * (e-s)) for s, e, v in zip(starts, ends, values)])
# assign values
a[np.array(idx).flatten()] = np.array(val).flatten()
a
# array([ 1., 1., 2., 2., 3., 3., 4., 4., 0., 0.])
</code></pre>
<p>Or write a for loop to assign values one range by another:</p>
<pre><code>for s, e, v in zip(starts, ends, values):
a[slice(s, e)] = v
a
# array([ 1., 1., 2., 2., 3., 3., 4., 4., 0., 0.])
</code></pre>
| 1 | 2016-08-12T18:05:22Z | [
"python",
"numpy",
"vectorization"
] |
Assign multiple values to multiple slices of a numpy array at once | 38,923,763 | <p>I have a numpy array, a list of start/end indexes that define ranges within the array, and a list of values, where the number of values is the same as the number of ranges. Doing this assignment in a loop is currently very slow, so I'd like to assign the values to the corresponding ranges in the array in a vectorized way. Is this possible to do?</p>
<p>Here's a concrete, simplified example:</p>
<p><code>a = np.zeros([10])</code></p>
<p>Here's the list of start and a list of end indexes that define ranges within <code>a</code>, like this:</p>
<pre><code>starts = [0, 2, 4, 6]
ends = [2, 4, 6, 8]
</code></pre>
<p>And here's a list of values I'd like to assign to each range:</p>
<p><code>values = [1, 2, 3, 4]</code></p>
<p>I have two problems. The first is that I can't figure out how to index into the array using multiple slices at the same time, since the list of ranges is constructed dynamically in the actual code. Once I'm able to extract the ranges, I'm not sure how to assign multiple values at once - one value per range.</p>
<p>Here's how I've tried creating a list of slices and the problems I've run into when using that list to index into the array:</p>
<pre><code>slices = [slice(start, end) for start, end in zip(starts, ends)]
In [97]: a[slices]
...
IndexError: too many indices for array
In [98]: a[np.r_[slices]]
...
IndexError: arrays used as indices must be of integer (or boolean) type
</code></pre>
<p>If I use a static list, I can extract multiple slices at once, but then assignment doesn't work the way I want:</p>
<pre><code>In [106]: a[np.r_[0:2, 2:4, 4:6, 6:8]] = [1, 2, 3]
/usr/local/bin/ipython:1: DeprecationWarning: assignment will raise an error in the future, most likely because your index result shape does not match the value array shape. You can use `arr.flat[index] = values` to keep the old behaviour.
#!/usr/local/opt/python/bin/python2.7
In [107]: a
Out[107]: array([ 1., 2., 3., 1., 2., 3., 1., 2., 0., 0.])
</code></pre>
<p>What I actually want is this:</p>
<p>np.array([1., 1., 2., 2., 3., 3., 4., 4., 0., 0.])</p>
| 1 | 2016-08-12T17:46:45Z | 38,924,976 | <p>This will do the trick in a fully vectorized manner:</p>
<pre><code>counts = ends - starts
idx = np.ones(counts.sum(), dtype=np.int)
idx[np.cumsum(counts)[:-1]] -= counts[:-1]
idx = np.cumsum(idx) - 1 + np.repeat(starts, counts)
a[idx] = np.repeat(values, count)
</code></pre>
| 1 | 2016-08-12T19:12:04Z | [
"python",
"numpy",
"vectorization"
] |
Python pexpect: var.expect('string') not returning expected values when 'string' isn't found | 38,923,804 | <p>I am working with the following bit of Python code. The code is fairly simple, pexpect sends <code>echo testcase</code> to the terminal, then monitors the terminal for the subsequent appearance of <code>testcase</code>, then verifies that it saw the echo by setting <code>bool_value=True</code> (assuming it sees the expected output).</p>
<pre><code>#!/usr/bin/python
import pexpect
print('Testing case where pexpect finds the expected value: ')
testcase = pexpect.spawn('echo testcase')
bool_value = not testcase.expect('testcase')
print bool_value
testcase.close()
print('Testing case where pexpect does not find the expected value: ')
testcase = pexpect.spawn('echo testcase')
bool_value = not testcase.expect('someothervalue')
print bool_value
testcase.close()
</code></pre>
<p>What I expect to see is that after the first test case, bool_value would print <code>True</code>. In this case it does, but only after adding the odd hack of setting <code>bool_value = not testcase.expect('testcase')</code> (setting it to the inverse of what expect() returns).</p>
<p>In the second test case, <code>testcase.expect()</code> does not see the expected value of <code>someothervalue</code>, so I would expect it to return <code>false</code>. Instead, it returns an exception:</p>
<pre><code>Traceback (most recent call last):
File "./echotest.py", line 12, in <module>
bool_value = not testcase.expect('someothervalue')
File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1418, in expect
timeout, searchwindowsize)
File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1433, in expect_list
timeout, searchwindowsize)
File "/usr/lib/python2.7/dist-packages/pexpect/__init__.py", line 1521, in expect_loop
raise EOF(str(err) + '\n' + str(self))
pexpect.EOF: End Of File (EOF). Exception style platform.
<pexpect.spawn object at 0x7f7667a9db10>
version: 3.1
command: /bin/echo
args: ['/bin/echo', 'testcase']
searcher: <pexpect.searcher_re object at 0x7f7667a9d790>
buffer (last 100 chars): ''
before (last 100 chars): 'testcase\r\n'
after: <class 'pexpect.EOF'>
match: None
match_index: None
exitstatus: 0
flag_eof: True
pid: 4619
child_fd: 3
closed: False
timeout: 30
delimiter: <class 'pexpect.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1
</code></pre>
<p>I'm really not sure how to correct this behavior based on what the documentation is telling me. Adding <code>testcase.expect(pexpect.EOF())</code> per <a href="http://stackoverflow.com/questions/17879585/eof-when-using-pexpect-and-pxssh">this previous implementation</a> returns the same error.</p>
<p>How do I correctly implement this function?</p>
| 0 | 2016-08-12T17:49:23Z | 38,924,591 | <p>It turns out that when the system was not outputting something <code>pexpect</code> was looking for, it would hit <code>pexpect.EOF</code> without triggering any sort of action. Because I don't tell it what to do when it hits EOF without seeing any other strings it's expecting, it returns an exception instead.</p>
<p>Here is my code with corrections and test cases.</p>
<pre><code>#!/usr/bin/python
import pexpect
"""
Test for some known good value.
"""
print('Testing case where pexpect finds the expected value: ')
testcase = pexpect.spawn('echo testcase')
bool_value = testcase.expect([pexpect.EOF,'testcase','badcase'])
if bool_value == 0:
print('Unknown value presented to script.')
elif bool_value == 1:
print('Success.')
elif bool_value == 2:
print('Failed.')
print bool_value
testcase.close()
"""
Test for some known bad response
"""
print('Testing case where pexpect finds an expected bad value: ')
testcase = pexpect.spawn('echo badcase')
bool_value = testcase.expect([pexpect.EOF,'testcase','badcase'])
if bool_value == 0:
print('Unknown value presented to script.')
elif bool_value == 1:
print('Success.')
elif bool_value == 2:
print('Failed.')
print bool_value
testcase.close()
"""
If it gets no expected response at all, it will reach EOF. We have to define
some behavior for that case.
"""
print('Testing case where pexpect does not find any expected value: ')
testcase = pexpect.spawn('echo unknown')
bool_value = testcase.expect([pexpect.EOF,'testcase','badcase'])
if bool_value == 0:
print('Unknown value presented to script.')
elif bool_value == 1:
print('Success.')
elif bool_value == 2:
print('Failed.')
print bool_value
testcase.close()
</code></pre>
| 0 | 2016-08-12T18:46:02Z | [
"python",
"python-2.7",
"pexpect"
] |
Python script not entering for loop | 38,923,891 | <p>I'm writing a script from a tutorial I found online that essentially just reads the news. The script now compiles and launches, but doesn't actually do anything. After debugging, I found that it doesn't enter into the for-loop, and I'm not sure why. </p>
<pre><code>import subprocess
import requests
from bs4 import BeautifulSoup
import textwrap
head = 'mpg123 -q '
tail = ' &'
url = 'http://www.ndtv.com/article/list/top-stories/'
r = requests.get(url)
soup = BeautifulSoup(r.content)
print '1'
g_data = soup.find_all("div",{"class":"natory_intro"})
log = open("/home/pi/logs/newslog.txt","w")
for item in g_data:
print '2'
#print >> log, item.text
shorts = textwrap.wrap(item.text, 100)
print '3'
for sentance in shorts:
print '4'
sendthis = sentance.join(['"http://translate.google.com/translate_tts?t1=en&q=', '"'])
print[head + sendthis + tail]
#print subprocess.call(head + sendthis + tail, shell=True)
print subprocess.check_output (head + sendthis + tail, shell=True)
print '5'
</code></pre>
<p><code>g_data</code> was loaded with the data from the website, so there is an item in <code>g_data</code>, but it still doesn't get caught in the loop. It's probably a really simple fix, but I just can't see it right now. Any help is appreciated. </p>
| -1 | 2016-08-12T17:56:49Z | 38,923,985 | <p>You have a typo on this line</p>
<pre><code>g_data = soup.find_all("div",{"class":"natory_intro"})
</code></pre>
<p>Should be</p>
<pre><code>g_data = soup.find_all("div",{"class":"nstory_intro"})
</code></pre>
| 2 | 2016-08-12T18:02:33Z | [
"python",
"beautifulsoup",
"raspberry-pi"
] |
Python script not entering for loop | 38,923,891 | <p>I'm writing a script from a tutorial I found online that essentially just reads the news. The script now compiles and launches, but doesn't actually do anything. After debugging, I found that it doesn't enter into the for-loop, and I'm not sure why. </p>
<pre><code>import subprocess
import requests
from bs4 import BeautifulSoup
import textwrap
head = 'mpg123 -q '
tail = ' &'
url = 'http://www.ndtv.com/article/list/top-stories/'
r = requests.get(url)
soup = BeautifulSoup(r.content)
print '1'
g_data = soup.find_all("div",{"class":"natory_intro"})
log = open("/home/pi/logs/newslog.txt","w")
for item in g_data:
print '2'
#print >> log, item.text
shorts = textwrap.wrap(item.text, 100)
print '3'
for sentance in shorts:
print '4'
sendthis = sentance.join(['"http://translate.google.com/translate_tts?t1=en&q=', '"'])
print[head + sendthis + tail]
#print subprocess.call(head + sendthis + tail, shell=True)
print subprocess.check_output (head + sendthis + tail, shell=True)
print '5'
</code></pre>
<p><code>g_data</code> was loaded with the data from the website, so there is an item in <code>g_data</code>, but it still doesn't get caught in the loop. It's probably a really simple fix, but I just can't see it right now. Any help is appreciated. </p>
| -1 | 2016-08-12T17:56:49Z | 38,924,051 | <p>I think it doesn't enter the loop because <code>g_data</code> is an empty list.</p>
<p>Check the website, make sure you can get items by class name <code>"natory_intro"</code>.</p>
<p>I run:</p>
<pre><code>import subprocess
import requests
from bs4 import BeautifulSoup
import textwrap
head = 'mpg123 -q '
tail = ' &'
url = 'http://www.ndtv.com/article/list/top-stories/'
r = requests.get(url)
soup = BeautifulSoup(r.content)
g_data = soup.find_all("div",{"class":"natory_intro"})
print g_data
</code></pre>
<p>I get</p>
<pre><code>[]
</code></pre>
<p>Edit:</p>
<p>I guess this is what you want:</p>
<pre><code>#ins_storylist > ul > li:nth-child(1) > div.new_storylising_contentwrap > div.nstory_intro
</code></pre>
<p>Just change <code>"natory_intro"</code> to <code>"nstory_intro"</code>.</p>
| 0 | 2016-08-12T18:06:56Z | [
"python",
"beautifulsoup",
"raspberry-pi"
] |
Making an animation of Newton's Method for finding roots of a function | 38,923,909 | <p>Earlier for my Calculus class, I had the idea to create a graph that would update itself to show the progression of Newton's Method for finding the roots of a function. So my question was, using Python and Sympy to handle all the messing calculus behind the issue, how was I going to graph this in an informative way.</p>
<p>On first glance, Sympy's latest library doesn't seem to offer any way to simply add multiple graphs onto an existing graph, which is a problem. </p>
<p>Hopefully someone finds the following answer of use :)</p>
| 0 | 2016-08-12T17:57:38Z | 38,923,910 | <p>After about 2 days of work I've managed to come up with this solution however. I am still using Sympy as the backend for derivative computation and function input, but I am converting those expressions into lambda functions to generate values that I can feed into coordinates for Matplotlib. I've also cleaned up the code and added comments to the most important parts.</p>
<p>To use this programme (only tested on Windows) I installed the latest Anaconda package.</p>
<pre><code>'''
Created on Aug 10, 2016
@author: Clement Hathaway
Example: enter in:
6*x**3 -73*x**2 -86*x +273
-20
-10
20
-2200
2000
GO!
'''
from numpy import linspace
from sympy.parsing.sympy_parser import parse_expr
from sympy import *
from sympy.solvers.solveset import solveset, solveset_real
import matplotlib.pyplot as plt
#from numpy.doc.constants import lines
def distanceFromRoot(x, values): ## Return the lowest distance between the supplied roots
currentDistance = abs(x-values[0])
if len(values) > 1: ## Only run if there is more than one root
for value in values:
newDist = abs(x-value)
if newDist < currentDistance:
currentDistance = newDist
return currentDistance
def generateTangents(x0, real_roots, accuracy):
if distanceFromRoot(x0, real_roots) > accuracy: ## Continue if the value we have calculated is still too far from a real root
tangent = simplify(dy.subs(x, x0)*(x-x0)+(y.subs(x,x0))) ## Find equation of tangent at our x0
tangent_intercept = solve(tangent, x)[0] ## Find tangent's x intercept
lam_tan = lambdify(x, tangent, modules=['numpy']) ## Function to generate y values of the tangent line
tan_y_vals = lam_tan(x_values) ## Y values of the tangent line to plot
text.set_text("Current x-estimate: " + str(N(tangent_intercept))) ## Display estimate
plt.plot(x_values, tan_y_vals, 'b-') ## Plot our new y values with a colour of blue and a ocnsistent line
plt.draw() ## Draw the plot
plt.pause(0.5) ## Pause for 1 second before drawing the next line
generateTangents(N(tangent_intercept), real_roots, accuracy) ## Call itself again recursively
else: ## Do nothing
## Display some ending text
print("Found value to be: " + str(x0))
print("With real roots: " + str(real_roots))
pass
if __name__ == '__main__':
## Equation
x = symbols('x')
y = parse_expr(str(raw_input("Enter Equation: ")))
dy = diff(y, x) ## Differentiate y in terms of x
x0 = float(input("Enter starting value for x: "))
roots = solveset_real(y, x) ## Find roots of y in terms of x
roots_array = [] ## Get in terms of array
for root in roots:
roots_array.append(N(root))
## Setup Values
x_min = int(input("Enter x-axis min: "))
x_max = int(input("Enter x-axis max: "))
y_min = int(input("Enter y-axis min: "))
y_max = int(input("Enter y-axis max: "))
res = 200
## Convert to use with other library
lam_y = lambdify(x, y, modules=['numpy']) ## Functions of our main func
lam_dy = lambdify(x, dy, modules=['numpy']) ## Differential of our eq
## Calculate starting values
x_values = linspace(x_min, x_max, res) ## Array of x values between xmin and max seperated by res
y_values = lam_y(x_values) ## Calculated y values
## Graph Setup
plt.axis([x_min, x_max, y_min, y_max]) ## Setup graph axis
plt.grid() ## Enable the graph grid
plt.ion() ## Make graph interactive to add future lines
## Plot main Function
y0_values = linspace(0,0, res)
plt.plot(x_values, y_values, 'g-', linewidth=2)
plt.plot(x_values, y0_values,'k-', linewidth=2) ## Create more noticable x axis
text = plt.text(0,5,"Current x-estimate: " + str(x0), fontsize = 30)
plt.draw()
plt.pause(0.1)
## Start generating tangent lines! weo
generateTangents(x0, roots_array, 0.0000001)
## Keep the graph from disappearing
plt.ioff()
plt.show()
</code></pre>
| 0 | 2016-08-12T17:57:38Z | [
"python",
"matplotlib",
"graph",
"sympy",
"newtons-method"
] |
Numpy array from characters in BDF file | 38,923,943 | <p>I have a file, font_file.bdf, and need to get the characters contained in it as numpy arrays where each element is one pixel.</p>
<p>Here's the snippet of that file which defines the '?' character:</p>
<pre><code>STARTCHAR question
ENCODING 63
SWIDTH 1000 0
DWIDTH 6 0
BBX 5 7 0 0
BITMAP
70
88
08
10
20
00
20
ENDCHAR
</code></pre>
<p>I researched .bdf files to understand how they encode data. Basically, it's a bitmap with bit-depth of 1. I found a pillow module, PIL.BdfFontFile, which can interpret bdf files. After experimenting with this module a while I was able to get a PIL image for each of the characters in the font and save them to see that it is working like so:</p>
<pre><code>from PIL.BdfFontFile import BdfFontFile
fp = open("font_file.bdf", "r")
bdf_file = BdfFontFile(fp)
bdf_file.compile()
char = '?'
_, __, bounding_box, image = bdf_file[ord(char)]
image.save(char + ".png")
</code></pre>
<p>The saved image looks like the following: <a href="http://i.stack.imgur.com/lSLeL.png" rel="nofollow">Question Mark</a>. and from looking at its properties it has a bit-depth of 1, which makes sense. (I'm not sure why it seems inverted, but I could do that kind of manipulation with numpy if still needed.)</p>
<p>Once I had that, I tried to convert to a numpy array:</p>
<pre><code>print numpy.array(image, dtype=numpy.int)
</code></pre>
<p>which gave me an array that no longer seems to represent the corresponding character any longer:</p>
<pre><code>[[1 1 1 1 1]
[0 1 0 1 1]
[1 1 1 1 1]
[1 1 1 1 0]
[1 0 1 0 1]
[1 0 1 1 1]
[0 1 1 1 1]]
</code></pre>
<p>I was hoping for something that looked more like this:</p>
<pre><code>[[0 1 1 1 0]
[1 0 0 0 1]
[0 0 0 0 1]
[0 0 0 1 0]
[0 0 1 0 0]
[0 0 0 0 0]
[0 0 1 0 0]]
</code></pre>
<p>Worst case-scenario, I could make an algorithm myself that converts the data in the PIL image to a numpy array, but I feel like there has to be an easier way given my past experience with converting between PIL Images and numpy arrays (It's usually quite straight-forward.)</p>
<p>Any ideas about how to get the PIL image to convert to a numpy array properly or another solution to my problem would be appreciated.</p>
| 1 | 2016-08-12T17:59:53Z | 39,020,645 | <p>It turns out the unexpected behavior I was seeing was due to a bug in PIL as described in this SO question: <a href="http://stackoverflow.com/questions/2761645/error-converting-pil-bw-images-to-numpy-arrays">Error Converting PIL B&W images to Numpy Arrays</a>.</p>
<p>So the key to solving my problem was to convert the image to grayscale before creating the numpy array.</p>
<p>My final solution with doing a small numpy conversion into the described format was as follows:</p>
<pre><code>fp = open("font_file.bdf", "r")
bdf_file = BdfFontFile(fp)
bdf_file.compile()
char = '?'
_, __, bounding_box, image = bdf_file[ord(char)]
print numpy.array(image.convert('L')) / 255
</code></pre>
<p>which gave me this:</p>
<pre><code>[[0 1 1 1 0]
[1 0 0 0 1]
[0 0 0 0 1]
[0 0 0 1 0]
[0 0 1 0 0]
[0 0 0 0 0]
[0 0 1 0 0]]
</code></pre>
| 0 | 2016-08-18T14:20:25Z | [
"python",
"numpy",
"fonts",
"bitmap",
"python-imaging-library"
] |
Variable with List comprehension | 38,923,962 | <p>I'm trying to rewrite my old code using list comprehension and I was wondering if there's a way to use a variable called "result" instead of <code>int(round(sorted_l[sorted_l.index(i)] // sorted_l1[sorted_l1.index(i1)]))</code>
in the code below, because I will need to reuse it within the function.</p>
<pre><code>list1 = [2, 4, 6]
list2 = [1, 2, 3]
def a_function(lst, lst1):
sorted_l = sorted(lst)
sorted_l1 = sorted(lst1)
my_list = [int(round(sorted_l[sorted_l.index(i)] // sorted_l1[sorted_l1.index(i1)])) for i in sorted_l for i1 in sorted_l1]
most_common = lst.count()
print my_list
</code></pre>
| 0 | 2016-08-12T18:01:06Z | 38,924,226 | <p>Not really sure what you're trying to do, but the function I wrote below behaves equivalent to yours up until the line <code>most_common = lst.count()</code> which is invalid, as Chris Rands points out in the comments.</p>
<p>If you clarify what it is you're actually trying to achieve, I can edit this code accordingly.</p>
<pre><code>list1 = [2, 4, 6]
list2 = [1, 2, 3]
def a_function(a, b):
sorted_a = sorted(a)
sorted_b = sorted(b)
for element_a in sorted_a:
for element_b in sorted_b:
# Can someone smarter than me let me know if
# anything in this line is redundant?
yield int(round(element_a)) // element_b
print(list(a_function(list1, list2)))
</code></pre>
<p><strong>Output</strong></p>
<pre><code>[2, 1, 0, 4, 2, 1, 6, 3, 2]
</code></pre>
| 0 | 2016-08-12T18:19:51Z | [
"python",
"list",
"for-loop",
"list-comprehension"
] |
Variable with List comprehension | 38,923,962 | <p>I'm trying to rewrite my old code using list comprehension and I was wondering if there's a way to use a variable called "result" instead of <code>int(round(sorted_l[sorted_l.index(i)] // sorted_l1[sorted_l1.index(i1)]))</code>
in the code below, because I will need to reuse it within the function.</p>
<pre><code>list1 = [2, 4, 6]
list2 = [1, 2, 3]
def a_function(lst, lst1):
sorted_l = sorted(lst)
sorted_l1 = sorted(lst1)
my_list = [int(round(sorted_l[sorted_l.index(i)] // sorted_l1[sorted_l1.index(i1)])) for i in sorted_l for i1 in sorted_l1]
most_common = lst.count()
print my_list
</code></pre>
| 0 | 2016-08-12T18:01:06Z | 38,924,261 | <p><code>sorted_l[sorted_l.index(i)]</code> is the exact same as <code>i</code>. </p>
<p><code>sorted_l1[sorted_l1.index(i1)]</code> is the exact same as <code>i1</code>. </p>
<p>You are doing integer division, which truncates the decimal, so what are you rounding?</p>
<pre><code>int(round( v1 // v2 ))
</code></pre>
<hr>
<p>That being said, all that can be simplified to </p>
<pre><code>[int(round(i / i1)) for i in sorted_l for i1 in sorted_l1]
</code></pre>
<p>And outputs </p>
<pre><code>[2, 1, 0, 4, 2, 1, 6, 3, 2]
</code></pre>
<blockquote>
<p>I was wondering if there's a way to use a variable called "result"</p>
</blockquote>
<p>Yes, assign that list to a variable named <code>result</code>. </p>
<p>If you want to find the "most common" element, you can't use a list-comprehension, but you can do this </p>
<pre><code>from collections import Counter
result = [int(round(i / i1)) for i in list1 for i1 in list2]
most_common = Counter(result).most_common()[0][0] # 2 occurs most frequently
</code></pre>
| 1 | 2016-08-12T18:22:07Z | [
"python",
"list",
"for-loop",
"list-comprehension"
] |
Object going out of scope and being garbage collected in PySide/PyQt | 38,923,978 | <p>I'm having issues with a non-Qt object falling out of scope and being garbage collected by Python. In the generic example below, I create an object when one button is clicked and want to use that object when the other button is clicked. After the slot for the 1st button is finished executing, the object is garbage collected.</p>
<pre><code># Started from http://zetcode.com/gui/pysidetutorial/firstprograms/ and
# connections program from chap 4 of Summerfield's PyQt book
import sys
from PySide import QtGui
def createThingy():
thing1 = thingy("thingName", 3, wid)
lbl1.setText(thing1.name + " created.")
return
def updateNum():
lbl1.setText("number: " + str(thing1.number))
return
class thingy(object):
def __init__(self, name, number, mainWindow):
self.name = name
self.number = number
def func1(self):
return "Something to return"
def rtnNum(self):
return "Num: " + str(self.number)
app = QtGui.QApplication(sys.argv)
wid = QtGui.QWidget()
wid.resize(250, 150)
wid.setWindowTitle('Example')
btn1 = QtGui.QPushButton("Create thingy")
btn2 = QtGui.QPushButton("Number")
lbl1 = QtGui.QLabel("---")
vlayout = QtGui.QVBoxLayout()
vlayout.addWidget(btn1)
vlayout.addWidget(btn2)
vlayout.addWidget(lbl1)
wid.setLayout(vlayout)
btn1.clicked.connect(createThingy)
btn2.clicked.connect(updateNum)
wid.show()
wid.raise_()
sys.exit(app.exec_())
</code></pre>
<p>This sort of behavior is mentioned on the PySide pitfalls page, <a href="https://wiki.qt.io/PySide_Pitfalls" rel="nofollow">https://wiki.qt.io/PySide_Pitfalls</a>, as well as the question "Python PySide (Internal c++ Object Already Deleted)" <a href="http://stackoverflow.com/a/5339238/2599816">http://stackoverflow.com/a/5339238/2599816</a> (this question doesn't really answer my question since the author's solution is to avoid the problem).</p>
<p>Because the object is not a Qt object, passing it a parent is not a viable option. Additionally, I do not want to create the object at the start of the program as some other questions/answers have suggested elsewhere (can't find links to them again). Further, the object should not be modified to solve this problem but the solution should be implemented in the GUI, i.e. keep the object generic for use as a library in other programs.</p>
<ul>
<li>How do I make the object an attribute of my window or widget as suggested by the pitfalls page?</li>
<li>While making it an attribute of the window/widget is an option, is there a better design/more elegant solution/best practice to use?</li>
</ul>
<p>Thanks for the help.</p>
| 1 | 2016-08-12T18:02:11Z | 38,927,433 | <p>Create a subclass of <code>QWidget</code> to keep all the child objects as attributes:</p>
<pre><code>import sys
from PySide import QtGui
class Widget(QtGui.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.resize(250, 150)
self.setWindowTitle('Example')
self.btn1 = QtGui.QPushButton("Create thingy")
self.btn2 = QtGui.QPushButton("Number")
self.lbl1 = QtGui.QLabel("---")
vlayout = QtGui.QVBoxLayout()
vlayout.addWidget(self.btn1)
vlayout.addWidget(self.btn2)
vlayout.addWidget(self.lbl1)
self.setLayout(vlayout)
self.btn1.clicked.connect(self.createThingy)
self.btn2.clicked.connect(self.updateNum)
def createThingy(self):
self.thing1 = thingy("thingName", 3, wid)
self.lbl1.setText(self.thing1.name + " created.")
def updateNum(self):
self.lbl1.setText("number: " + str(self.thing1.number))
class thingy(object):
def __init__(self, name, number, mainWindow):
self.name = name
self.number = number
def func1(self):
return "Something to return"
def rtnNum(self):
return "Num: " + str(self.number)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
wid = Widget()
wid.show()
sys.exit(app.exec_())
</code></pre>
| 0 | 2016-08-12T22:48:08Z | [
"python",
"qt",
"garbage-collection",
"pyqt",
"pyside"
] |
Object going out of scope and being garbage collected in PySide/PyQt | 38,923,978 | <p>I'm having issues with a non-Qt object falling out of scope and being garbage collected by Python. In the generic example below, I create an object when one button is clicked and want to use that object when the other button is clicked. After the slot for the 1st button is finished executing, the object is garbage collected.</p>
<pre><code># Started from http://zetcode.com/gui/pysidetutorial/firstprograms/ and
# connections program from chap 4 of Summerfield's PyQt book
import sys
from PySide import QtGui
def createThingy():
thing1 = thingy("thingName", 3, wid)
lbl1.setText(thing1.name + " created.")
return
def updateNum():
lbl1.setText("number: " + str(thing1.number))
return
class thingy(object):
def __init__(self, name, number, mainWindow):
self.name = name
self.number = number
def func1(self):
return "Something to return"
def rtnNum(self):
return "Num: " + str(self.number)
app = QtGui.QApplication(sys.argv)
wid = QtGui.QWidget()
wid.resize(250, 150)
wid.setWindowTitle('Example')
btn1 = QtGui.QPushButton("Create thingy")
btn2 = QtGui.QPushButton("Number")
lbl1 = QtGui.QLabel("---")
vlayout = QtGui.QVBoxLayout()
vlayout.addWidget(btn1)
vlayout.addWidget(btn2)
vlayout.addWidget(lbl1)
wid.setLayout(vlayout)
btn1.clicked.connect(createThingy)
btn2.clicked.connect(updateNum)
wid.show()
wid.raise_()
sys.exit(app.exec_())
</code></pre>
<p>This sort of behavior is mentioned on the PySide pitfalls page, <a href="https://wiki.qt.io/PySide_Pitfalls" rel="nofollow">https://wiki.qt.io/PySide_Pitfalls</a>, as well as the question "Python PySide (Internal c++ Object Already Deleted)" <a href="http://stackoverflow.com/a/5339238/2599816">http://stackoverflow.com/a/5339238/2599816</a> (this question doesn't really answer my question since the author's solution is to avoid the problem).</p>
<p>Because the object is not a Qt object, passing it a parent is not a viable option. Additionally, I do not want to create the object at the start of the program as some other questions/answers have suggested elsewhere (can't find links to them again). Further, the object should not be modified to solve this problem but the solution should be implemented in the GUI, i.e. keep the object generic for use as a library in other programs.</p>
<ul>
<li>How do I make the object an attribute of my window or widget as suggested by the pitfalls page?</li>
<li>While making it an attribute of the window/widget is an option, is there a better design/more elegant solution/best practice to use?</li>
</ul>
<p>Thanks for the help.</p>
| 1 | 2016-08-12T18:02:11Z | 38,928,325 | <p>It is being garbage collected because the scope is lost once the function execution ends. You need to save the reference, and there are two ways of doing it:</p>
<ol>
<li>Save the object in a global variable, so it won't get collected by the gc and also stay accessible on the other function.</li>
<li>Wrap the whole thing in a <code>QWidget</code> implementation, saving the created object in the widget object (via self).</li>
</ol>
<p>Please let me know if I wasn't clear or accurate enough. <br>
Hope it helps. <br>
Cheers.</p>
| 0 | 2016-08-13T01:22:46Z | [
"python",
"qt",
"garbage-collection",
"pyqt",
"pyside"
] |
Tkinter, show Calendar in Toplevel window on button click | 38,924,167 | <p>I deleted my previous question about this in order to simplify my question and communicate the question clearer. I've got a project with multiple classes inside of it and I'd like to get a Calendar to display in a new window once I click a button. I am currently using <a href="http://svn.python.org/projects/sandbox/trunk/ttk-gsoc/samples/ttkcalendar.py" rel="nofollow">this</a> Calendar script with a minor change inside of my overall script. I changed Frame to Toplevel in the first part of the Calendar script like this:</p>
<pre><code>class Calendar(tk.Toplevel):
def __init__(self, parent, **kw):
Toplevel.__init__(self, parent, **kw)
</code></pre>
<p>Now this does create the Calendar in a Toplevel window along with the rest of my script but it does it as soon as the program is started. I want to get it to show when it is called later on by the user. </p>
<p>example:</p>
<pre><code>class Application(tk.Tk): # tk.Tk creates main window
def __init__(self):
tk.Tk.__init__(self)
self.title("T")
self.geometry('550x320')#x,y
self.create_options()
self.calendar = Calendar(self)
def create_options(self):
self.widgets = tk.Frame(self)
tk.Button(self,
text = "...", command=self.show_Calendar
).place(x=525, y=130)
</code></pre>
<p>which would call this:</p>
<pre><code>def show_Calendar(self):
'''shows calendar'''
toplevel = Toplevel()
toplevel.Calendar.place(x=0, y=0)
</code></pre>
<p>The button does create a window but there is nothing in it. What would be the best way to get this Calendar to only show in the window that appears when the button is clicked? </p>
| 0 | 2016-08-12T18:14:59Z | 38,924,333 | <pre><code>self.calendar = Calendar(self)
</code></pre>
<p>Putting this line within your application <code>init</code> will create it at the same time that the application is created. You would want to move this into your <code>show_Calendar</code> method.</p>
<pre><code>def show_Calendar(self):
'''shows calendar'''
toplevel = Toplevel()
toplevel.Calendar.place(x=0, y=0)
</code></pre>
<p><code>toplevel = Toplevel()</code> does not make any sense here. You are creating a blank <code>Toplevel</code> and making it a local variable. This <code>Toplevel</code> is <strong>not</strong> related to your Calendar in any way. </p>
<p>Within the Calendar script, you made sure that the Calendar class inherits from <code>Toplevel</code>, so any time you create a Calendar, it will be attached to its own <code>Toplevel</code>.</p>
<pre><code>def show_Calendar(self):
'''shows calendar'''
self.calendar = Calendar(self)
</code></pre>
<p>I was looking at your previous question before you deleted it, and if you would also like to remove the calendar when the user changes focus, you should look into <a href="http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm" rel="nofollow">Events and Bindings</a> here, specifically <code><FocusOut></code>.</p>
| 1 | 2016-08-12T18:26:18Z | [
"python",
"tkinter",
"calendar"
] |
Django's Count with relationship spans | 38,924,248 | <p>Here are the relevant models:</p>
<pre><code>class WhatToWearCandidates(models.Model):
profile = models.ForeignKey(Profile, null=False, blank=False, related_name="outfit_candidates")
look = models.ForeignKey(StyleLook, null=False, blank=False, related_name="outfit_candidates")
class StyleLook(models.Model):
# Non important attributes
class LookItem(models.Model):
look = models.ForeignKey(StyleLook, null=False, blank=False, related_name="lookitems")
item = models.ForeignKey(Product, null=False, blank=False, related_name="looks")
</code></pre>
<p>I'll explain this, each WhatToWearCandidates has a StyleLook and Profile, for each profile we show the correct looks to them. StyleLook just contains details about itself.</p>
<p>Each StyleLook is composed of Products, in the table LookItem we connect which StyleLooks contain which Products.</p>
<p><strong>QUESTION</strong>: I'm trying to collect the WhatToWearCandidates that contain 4 or fewer Products efficiently.</p>
<p>I'm trying to use django's <code>annotate()</code> class</p>
<pre><code>all_candidates = WhatToWearCandidates.objects.filter(
look__lookitems__item__assignment=assignment.id, # This is to filter based on Products that belong in the current Assignment
profile_id=1, # Example profile
look_id=15 # Testing with 1 single look for the proper profile
).values('look_id').annotate(lcount=Count('look__lookitems'))
</code></pre>
<p>From the debugger <code>all_candidates</code> prints to <code>[{'look__id': 15L, 'lcount': 1}]</code>. I know that this look contains 6 products, so I expected lcount to equal 6.</p>
<p>To double check I tried a similar query from <code>StyleLook</code> instead.</p>
<pre><code>StyleLook.objects.filter(id__in=[15]).values('id').annotate(lcount=Count('lookitems'))
</code></pre>
<p>This returns <code>[{'id': 15L, 'lcount': 6}]</code>.</p>
<p>What am I doing wrong? How do I get <code>lcount</code> to equal 6 in the <code>WhatToWearCandidates</code> query?</p>
| 1 | 2016-08-12T18:21:02Z | 38,928,823 | <p>I think you're probably running into problems with <a href="https://docs.djangoproject.com/en/stable/topics/db/aggregation/#interaction-with-default-ordering-or-order-by" rel="nofollow">default ordering</a> in one of your models. Try adding <code>.order_by()</code> to the end of the query:</p>
<pre><code>all_candidates = WhatToWearCandidates.objects.filter(
look__lookitems__item__assignment=assignment.id,
profile_id=1,
).values('look_id').annotate(lcount=Count('look__lookitems')).order_by()
</code></pre>
| 0 | 2016-08-13T03:12:02Z | [
"python",
"django",
"count"
] |
Creating a Nested List in Python | 38,924,256 | <p>I'm trying to make a nested list in Python to contain information about points in a video, and I'm having a lot of trouble creating an array for the results to be saved in to. The structure of the list is simple: the top level is a reference to the frame, the next level is a reference to a marker, and the last level is the point of the marker. So for example, the list is setup as such:</p>
<p><code>markerList # a long list of every marker in every frame
markerList[0] # every marker in the first frame
markerList[0][0] # the first marker of the first frame
markerList[0][0][0] # the x value of the first marker of the first frame</code></p>
<p>Calling markerList[0] looks like this:</p>
<pre><code> array([[ 922.04443359, 903. ],
[ 987.83850098, 891.38830566],
[ 843.27374268, 891.70471191],
[ 936.38446045, 873.34661865],
[ 965.52880859, 840.44445801],
[ 822.19567871, 834.06298828],
[ 903.48956299, 830.62268066],
[ 938.70031738, 825.71557617],
[ 853.09545898, 824.47247314],
[ 817.84277344, 816.05029297],
[ 1057.91186523, 815.52935791],
[ 833.23632812, 787.48504639],
[ 924.24224854, 755.53997803],
[ 836.07800293, 720.02764893],
[ 937.83880615, 714.11199951],
[ 813.3493042 , 720.30566406],
[ 797.09521484, 705.72729492],
[ 964.31713867, 703.246521 ],
[ 934.9864502 , 697.27099609],
[ 815.1550293 , 688.91473389],
[ 954.94085693, 685.88171387],
[ 797.70239258, 672.35119629],
[ 877.05749512, 659.94250488],
[ 962.24786377, 659.26495361],
[ 843.66131592, 618.83868408],
[ 901.50476074, 585.42541504],
[ 863.41851807, 584.4977417 ]], dtype=float32)
</code></pre>
<p>The problem is that every frame contains a different number of markers. I want to create an empty array the same length as markerList (i.e., the same number of frames) in which every element is the same size as the largest frame in markerList. Some important caveats: first,I want to save the results into a .mat file where the final array (which I'll call finalStack) is a cell of cells. Second, I need to be able to reference and assign to any specific part of finalStack. So if I want to move a point to finalStack[0][22], I need to be able to do so without conflict. This basically just means I can't use append methods anywhere, but it's also unearthed my first problem - finding a way to create finalStack that doesn't cause every new assignment to be duplicated throughout the entire parent list. I've tried to do this a few different ways, and none work correctly.</p>
<p><strong>Attempts at a solution:</strong></p>
<p>Following another SO question, I attempted to create finalStack iteratively, but to no avail. I created the following function:</p>
<pre><code>def createFinalStack(numMarkers, numPoints, frames):
step = [[0]*numPoints for x in xrange(numMarkers)]
finalStack = [step]*frames
return finalStack
</code></pre>
<p>However, this causes all assignments to be copied across the parent list, such that assigning <code>finalStack[0][12]</code> leads to <code>finalStack[2][12] == finalStack[20][12] == finalStack[0][12]</code>. In this example, numMarkers= 40, numPoints = 2 (just x & y), and frames= 200. (So the final array should be 200 x 40 x 2.)</p>
<p>That said, this seems like the most straightforward way to do what I want, I just can't get past the copy error (I know it's a reference issue, I just don't know how to avoid it in this context).</p>
<p>Another seemingly simple solution would be to copy markerList using <code>copy.deepcopy(markerList)</code>, and pad any frames with less than 40 markers to get them to numMarkers = 40, and zero out anything else. But I can't come up with a good way to cycle through all of the frames, add points in the correct format, and then empty out everything else. </p>
<p>If this isn't enough information to work with, I can try to provide greater context and some other not-good-methods that didn't work at all. I've been stuck on this long enough that I'm convinced the solution is horribly simple, and I'm just missing the obvious. I hope you can prove me right!</p>
<p>Thanks!</p>
| 0 | 2016-08-12T18:21:39Z | 38,925,623 | <p>This illustrates what is going on:</p>
<pre><code>In [1334]: step=[[0]*3 for x in range(3)]
In [1335]: step
Out[1335]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
In [1336]: stack=[step]*4
In [1337]: stack
Out[1337]:
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
In [1338]: stack[0]
Out[1338]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
In [1339]: stack[0][2]=3
In [1340]: stack
Out[1340]:
[[[0, 0, 0], [0, 0, 0], 3],
[[0, 0, 0], [0, 0, 0], 3],
[[0, 0, 0], [0, 0, 0], 3],
[[0, 0, 0], [0, 0, 0], 3]]
In [1341]: step
Out[1341]: [[0, 0, 0], [0, 0, 0], 3]
</code></pre>
<p>When you use <code>alist*n</code> to create new list, the new list contains multiple pointers to the same underlying object. As a general rule, using <code>*n</code> to replicate a list is dangerous if you plan on changing values later on.</p>
<p>If instead I make an array of the right dimensions I don't have this problem:</p>
<pre><code>In [1342]: np.zeros((4,3,3),int)
Out[1342]:
array([[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
...
[0, 0, 0]]])
</code></pre>
<p>Or in list form:</p>
<pre><code>In [1343]: np.zeros((4,3,3),int).tolist()
Out[1343]:
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
</code></pre>
<p>If I assign a value in this list, I only change one item:</p>
<pre><code>In [1344]: stack=np.zeros((4,3,3),int).tolist()
In [1345]: stack[0][2]=3
In [1346]: stack
Out[1346]:
[[[0, 0, 0], [0, 0, 0], 3],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
</code></pre>
<p>I really should have used <code>stack[0][2][1]=3</code>, but you get the idea. If I make the same assignment in the array form I end up changing a whole row</p>
<pre><code>In [1347]: stack=np.zeros((4,3,3),int)
In [1348]: stack[0][2]=3
In [1349]: stack
Out[1349]:
array([[[0, 0, 0],
[0, 0, 0],
[3, 3, 3]],
[[0, 0, 0],
...
[0, 0, 0]]])
</code></pre>
<p>I should have used an expression like <code>stack[0,2,:]=4</code>.</p>
<p>It's probably possible to construct a triply next list like this where all initial values are independent. But this array approach is simpler.</p>
| 1 | 2016-08-12T19:58:31Z | [
"python",
"python-2.7",
"numpy"
] |
How to create multiple types of user with custom user model in django? | 38,924,271 | <p>I want to create multiple types of user in django app e.g one for Company and one for Employee.</p>
<p>What I had in mind was company will signup for itself and then employees will be created by company admin through his/her dashboard.</p>
<p>After creation employees will sign in directly.</p>
<p>So (if possible) only one sign in form can be used for company and employees.</p>
<pre><code>class Company(models.Model):
name = models.CharField(max_length=150)
logo = models.CharField(max_length=1000, blank=True)
admin_name = models.CharField(max_length=200)
admin_email = models.CharField(max_length=200) # can be used as 'username'
website = models.CharField(max_length=200, blank=True)
class CustomUserManager(auth_models.BaseUserManager):
def create_user(self, email, first_name, emp_id, password):
#
def create_superuser(self, email, first_name, emp_id, password):
#
class Users(auth_models.AbstractBaseUser, auth_models.PermissionsMixin):
company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
profile_pic = models.CharField(max_length=2000, blank=True)
email = models.EmailField(unique=True, null=True)
emp_id = models.CharField(max_length=50)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'emp_id', ]
objects = CustomUserManager()
</code></pre>
<p>I searched almost everywhere but couldn't find anything. If there is any way to solve this issue please let me know otherwise if you know any trick to get this thing done then it is also welcome.
Thanks in advance.</p>
| 0 | 2016-08-12T18:22:44Z | 38,925,133 | <p>You can just create groups for the different types of users:</p>
<pre><code>Group.objects.create(name='Company')
</code></pre>
<p>And then assign the user to the appropriate group:</p>
<pre><code>user.groups.add(group)
</code></pre>
<p>The last thing it sounds like you could do is to associate employees with the company user, so you can add a self reference to your Users model like this:</p>
<pre><code>company_user = models.ForeignKey("self", null=True, blank=True)
</code></pre>
<p>So, for those employees, you can then associate the user with that company user and leave it blank for the company user itself. </p>
<p>Although, you don't need to do that if you want to use the company foreign key you already have to track the related users that way. But if a company may have several "company users", you could then group up the employees to each.</p>
<p>I hope that helps.</p>
| 0 | 2016-08-12T19:22:10Z | [
"python",
"django",
"multiple-users",
"django-custom-user"
] |
python3 strftime output varies by platform | 38,924,289 | <p>Python3 <code>strftime</code> produces results that vary by platform. For example:</p>
<p>OS X 10.10.5</p>
<pre><code>>>> sys.version
'3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) \n[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]'
>>> datetime.datetime(1, 1, 1, 0, 0).strftime('%Y/%m/%d')
'0001/01/01'
</code></pre>
<p>Debian 8.5</p>
<pre><code>>>> sys.version
'3.5.2 (default, Aug 12 2016, 16:05:15) \n[GCC 4.9.2]'
>>> datetime.datetime(1, 1, 1, 0, 0).strftime('%Y/%m/%d')
'1/01/01'
</code></pre>
<p>Is this expected behavior? Why?</p>
| 3 | 2016-08-12T18:23:59Z | 38,924,621 | <p><code>strftime</code> is just a thin-wrapper around the <code>strftime</code> function defined in the <code>C</code> library you're using. See a related 'bug' <a href="http://bugs.python.org/issue9811" rel="nofollow">here</a>. This behavior <em>seems</em> to be another case of exactly that.</p>
<p>Differences between the output don't relate to Python since Python will just pass in the arguments and receives the output. Since different platforms have different implementations of the <code>C</code> stdlib, you'll get differing results in some edge cases. </p>
| 2 | 2016-08-12T18:47:55Z | [
"python",
"python-3.x",
"strftime"
] |
Sorting Python list | 38,924,305 | <p>I'm having trouble with my code sorting correctly. </p>
<pre><code>def generateList(attendeeList, criteria, workshoptitle):
for i in attendeeList:
if(criteria == 'Workshop1'):
criteria = 'Workshop B'
if(i['session1'] == criteria ):
temp = []
temp.append((i['lastname']))
temp.sort()
print(temp)
</code></pre>
<p>The output doesn't come out sorted by lastname</p>
<pre><code>['Smith']
['Robertson']
['Lovelace']
['Yu']
</code></pre>
| 0 | 2016-08-12T18:24:52Z | 38,924,336 | <p>Each time through the loop, you're just printing a list with a single item in it.</p>
<pre><code>temp = [] # empty list
temp.append((i['lastname'])) # list with one element
temp.sort() # list is already sorted (since it just has one element)
print(temp)
</code></pre>
<p>Maybe you wanted something like this:</p>
<pre><code>def generateList(attendeeList, criteria, workshoptitle):
lastnames = []
for i in attendeeList:
if(criteria == 'Workshop1'):
criteria = 'Workshop B'
if(i['session1'] == criteria ):
lastnames.append(i['lastname'])
lastnames.sort()
print(lastnames)
</code></pre>
<p><strong>EDIT</strong></p>
<p>More idiomatic Python, and returning the list instead of printing it:</p>
<pre><code>def generate_list(attendee_list, criteria, workshop_title):
if criteria == 'Workshop1':
criteria = 'Workshop B'
return sorted(attendee['lastname'] for attendee in attendee_list
if attendee['session1'] == criteria)
</code></pre>
| 3 | 2016-08-12T18:26:40Z | [
"python"
] |
Sorting Python list | 38,924,305 | <p>I'm having trouble with my code sorting correctly. </p>
<pre><code>def generateList(attendeeList, criteria, workshoptitle):
for i in attendeeList:
if(criteria == 'Workshop1'):
criteria = 'Workshop B'
if(i['session1'] == criteria ):
temp = []
temp.append((i['lastname']))
temp.sort()
print(temp)
</code></pre>
<p>The output doesn't come out sorted by lastname</p>
<pre><code>['Smith']
['Robertson']
['Lovelace']
['Yu']
</code></pre>
| 0 | 2016-08-12T18:24:52Z | 38,924,381 | <p>Your code does not do what you intend. Even if you do print the item each time you get it, you generate an empty list at each iteration.</p>
<p>You want to create the list before the loop, in the function body, then append to it, then sort it, then iterate through it if you want to additionally print it :</p>
<pre><code>def generateList(attendeeList, criteria, workshoptitle):
temp = []
if criteria == 'Workshop1':
criteria = 'Workshop B'
for i in attendeeList:
if i['session1'] == criteria :
temp.append(i['lastname'])
temp.sort()
for item in temp:
print(item)
return temp
</code></pre>
<p>Example run in IPython :</p>
<pre><code>In [7]: generateList([dict(session1="Workshop B",lastname="test1"), dict(session1="Workshop A", lastname="test2"), dict(session1="Workshop B", lastname="test3")], "Workshop1", ...)
test1
test3
Out[7]: ['test1', 'test3']
</code></pre>
| 0 | 2016-08-12T18:29:46Z | [
"python"
] |
decimal.Decimal(n) % 1 returns InvalidOperation, DivisionImpossible for all n >= 100 | 38,924,369 | <p>I am using Decimal objects in a django app, and found this strange error:</p>
<pre><code>ipdb> decimal.Decimal(10) % 1
Decimal('0')
ipdb> decimal.Decimal(100) % 1
*** decimal.InvalidOperation: [<class 'decimal.DivisionImpossible'>]
ipdb> decimal.Decimal(150) % 1
*** decimal.InvalidOperation: [<class 'decimal.DivisionImpossible'>]
ipdb> decimal.Decimal(79) % 1
Decimal('0')
ipdb> decimal.Decimal(100.1) % 2
Decimal('0.10')
ipdb> decimal.Decimal(1000) % 2
*** decimal.InvalidOperation: [<class 'decimal.DivisionImpossible'>]
</code></pre>
<p>Even more mysteriously, this doesn't happen in ipython until the numbers get very large:</p>
<pre><code>In [23]: decimal.Decimal(10**27) % 1
Out[23]: Decimal('0')
In [24]: decimal.Decimal(10**28) % 1
---------------------------------------------------------------------------
InvalidOperation Traceback (most recent call last)
<ipython-input-24-6ceaef82d283> in <module>()
----> 1 decimal.Decimal(10**28) % 1
InvalidOperation: [<class 'decimal.DivisionImpossible'>]
</code></pre>
<p>Note that the error is not confined to ipdb: I discovered this because Decimal(380) % 1 was breaking my django app.</p>
<p>The <a href="http://speleotrove.com/decimal/daexcep.html#refexcep">documentation</a> describing this error says:</p>
<blockquote>
<p>Division impossible</p>
<p>This occurs and signals invalid-operation if the integer result of a divide-integer or remainder operation had too many digits (would be longer than precision). The result is [0,qNaN].</p>
</blockquote>
<p>Any ideas?</p>
| 7 | 2016-08-12T18:29:00Z | 38,924,572 | <p>I think I figured it out.</p>
<p>Looking at the <a href="https://svn.python.org/projects/python/tags/r32/Lib/decimal.py" rel="nofollow">source code</a>, I found this:</p>
<pre><code># catch most cases of large or small quotient
expdiff = self.adjusted() - other.adjusted()
if expdiff >= context.prec + 1:
# expdiff >= prec+1 => abs(self/other) > 10**prec
return context._raise_error(DivisionImpossible)
if expdiff <= -2:
# expdiff <= -2 => abs(self/other) < 0.1
ans = self._rescale(ideal_exponent, context.rounding)
return ans._fix(context)
</code></pre>
<p>And in my django app, there's an adjustment to the prec:</p>
<pre><code>decimal.getcontext().prec = 2
</code></pre>
<p>This still looks slightly wrong to me, because:</p>
<pre><code>In [39]: decimal.getcontext().prec + 1
Out[39]: 3
In [40]: decimal.Decimal(100).adjusted() - decimal.Decimal(0).adjusted()
Out[40]: 2
</code></pre>
<p>And so it still looks like 100 is within the bounds of what it's checking for (that is, <code>2 < 3</code>), but I am pretty confident this is the source of the problem. If anyone can illuminate for me why the library does this, I would love to understand it better.</p>
| 4 | 2016-08-12T18:44:44Z | [
"python",
"django",
"decimal",
"python-3.5"
] |
Plucking an inner most item by its index with list comprehension | 38,924,373 | <p>I'm trying to get better at understanding list comprehension, and I started this thing with a list of tuples that I've cast to a list of lists.</p>
<p>With list comprehension, how can I pluck out from the inner most list's index that contains a <code>2</code> in the last index?</p>
<pre><code>results = [
[
[529L, u'wat', u'wat', 3L, 2], [530L, u'wat', u'wat', 3L, 1], [531L, u'wat', u'wat', 3L, 1]
], [
[533L, u'weeeee', u'weeeee', 3L, 1], [534L, u'weeeee', u'weeeee', 3L, 1]
]
]
</code></pre>
<p>Would be:</p>
<pre><code>results = [
[
[530L, u'wat', u'wat', 3L, 1], [531L, u'wat', u'wat', 3L, 1]
], [
[533L, u'weeeee', u'weeeee', 3L, 1], [534L, u'weeeee', u'weeeee', 3L, 1]
]
]
</code></pre>
| 0 | 2016-08-12T18:29:15Z | 38,924,423 | <pre><code>results = [[x for x in lst if x[-1]!=2] for lst in results]
</code></pre>
| 2 | 2016-08-12T18:34:03Z | [
"python",
"list-comprehension"
] |
Plucking an inner most item by its index with list comprehension | 38,924,373 | <p>I'm trying to get better at understanding list comprehension, and I started this thing with a list of tuples that I've cast to a list of lists.</p>
<p>With list comprehension, how can I pluck out from the inner most list's index that contains a <code>2</code> in the last index?</p>
<pre><code>results = [
[
[529L, u'wat', u'wat', 3L, 2], [530L, u'wat', u'wat', 3L, 1], [531L, u'wat', u'wat', 3L, 1]
], [
[533L, u'weeeee', u'weeeee', 3L, 1], [534L, u'weeeee', u'weeeee', 3L, 1]
]
]
</code></pre>
<p>Would be:</p>
<pre><code>results = [
[
[530L, u'wat', u'wat', 3L, 1], [531L, u'wat', u'wat', 3L, 1]
], [
[533L, u'weeeee', u'weeeee', 3L, 1], [534L, u'weeeee', u'weeeee', 3L, 1]
]
]
</code></pre>
| 0 | 2016-08-12T18:29:15Z | 38,924,497 | <p>Something like this:</p>
<pre><code>results_not_ending_in_2 = [
[inner_list for inner_list in outer_list if inner_list[-1] != 2]
for outer_list in results
]
</code></pre>
| 0 | 2016-08-12T18:39:18Z | [
"python",
"list-comprehension"
] |
Is there a standard way to partition an interable into equivalence classes given a relation in python? | 38,924,421 | <p>Say I have a finite iterable <code>X</code> and an equivalence relation <code>~</code> on <code>X</code>. We can define a function <code>my_relation(x1, x2)</code> that returns <code>True</code> if <code>x1~x2</code> and returns <code>False</code> otherwise. I want to write a function that partitions <code>X</code> into equivalence classes. That is, <code>my_function(X, my_relation)</code> should return a list of the equivalence classes of <code>~</code>. </p>
<p>Is there a standard way to do this in python? Better yet, is there a module designed to deal with equivalence relations?</p>
| 4 | 2016-08-12T18:33:57Z | 38,924,561 | <pre><code>In [1]: def my_relation(x):
...: return x % 3
...:
In [2]: from collections import defaultdict
In [3]: def partition(X, relation):
...: d = defaultdict(list)
...: for item in X:
...: d[my_relation(item)].append(item)
...: return d.values()
...:
In [4]: X = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
In [5]: partition(X, my_relation)
Out[5]: [[3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]]
</code></pre>
<p>For a binary function:</p>
<pre><code>from collections import defaultdict
from itertools import combinations
def partition_binary(Y, relation):
d = defaultdict(list)
for (a, b) in combinations(Y):
l = d[my_relation(a, b)]
l.append(a)
l.append(b)
return d.values()
</code></pre>
<p>You can do something like this:</p>
<pre><code>partition_binary(partition(X, rank), my_relation)
</code></pre>
<p>Oh, this obviously doesn't work if my_relation returns a boolean. I'd say come up with some abstract way to represent each isomorphism, although I suspect that's the goal of trying to do this in the first place.</p>
| 1 | 2016-08-12T18:43:47Z | [
"python",
"equivalence-classes"
] |
Is there a standard way to partition an interable into equivalence classes given a relation in python? | 38,924,421 | <p>Say I have a finite iterable <code>X</code> and an equivalence relation <code>~</code> on <code>X</code>. We can define a function <code>my_relation(x1, x2)</code> that returns <code>True</code> if <code>x1~x2</code> and returns <code>False</code> otherwise. I want to write a function that partitions <code>X</code> into equivalence classes. That is, <code>my_function(X, my_relation)</code> should return a list of the equivalence classes of <code>~</code>. </p>
<p>Is there a standard way to do this in python? Better yet, is there a module designed to deal with equivalence relations?</p>
| 4 | 2016-08-12T18:33:57Z | 38,924,631 | <p>I found <a href="http://code.activestate.com/recipes/499354-equivalence-partition/" rel="nofollow">this Python recipe</a> by John Reid. It was written in Python 2 and I adapted it to Python 3 to test it. The recipe includes a test to partition the set of integers <code>[-3,5)</code> into equivalence classes based on the relation <code>lambda x, y: (x - y) % 4 == 0</code>.</p>
<p>It seems to do what you want. Here's the adapted version I made in case you want it in Python 3:</p>
<pre><code>def equivalence_partition(iterable, relation):
"""Partitions a set of objects into equivalence classes
Args:
iterable: collection of objects to be partitioned
relation: equivalence relation. I.e. relation(o1,o2) evaluates to True
if and only if o1 and o2 are equivalent
Returns: classes, partitions
classes: A sequence of sets. Each one is an equivalence class
partitions: A dictionary mapping objects to equivalence classes
"""
classes = []
partitions = {}
for o in iterable: # for each object
# find the class it is in
found = False
for c in classes:
if relation(next(iter(c)), o): # is it equivalent to this class?
c.add(o)
partitions[o] = c
found = True
break
if not found: # it is in a new class
classes.append(set([o]))
partitions[o] = classes[-1]
return classes, partitions
def equivalence_enumeration(iterable, relation):
"""Partitions a set of objects into equivalence classes
Same as equivalence_partition() but also numbers the classes.
Args:
iterable: collection of objects to be partitioned
relation: equivalence relation. I.e. relation(o1,o2) evaluates to True
if and only if o1 and o2 are equivalent
Returns: classes, partitions, ids
classes: A sequence of sets. Each one is an equivalence class
partitions: A dictionary mapping objects to equivalence classes
ids: A dictionary mapping objects to the indices of their equivalence classes
"""
classes, partitions = equivalence_partition(iterable, relation)
ids = {}
for i, c in enumerate(classes):
for o in c:
ids[o] = i
return classes, partitions, ids
def check_equivalence_partition(classes, partitions, relation):
"""Checks that a partition is consistent under the relationship"""
for o, c in partitions.items():
for _c in classes:
assert (o in _c) ^ (not _c is c)
for c1 in classes:
for o1 in c1:
for c2 in classes:
for o2 in c2:
assert (c1 is c2) ^ (not relation(o1, o2))
def test_equivalence_partition():
relation = lambda x, y: (x - y) % 4 == 0
classes, partitions = equivalence_partition(
range(-3, 5),
relation
)
check_equivalence_partition(classes, partitions, relation)
for c in classes: print(c)
for o, c in partitions.items(): print(o, ':', c)
if __name__ == '__main__':
test_equivalence_partition()
</code></pre>
| 1 | 2016-08-12T18:48:24Z | [
"python",
"equivalence-classes"
] |
Is there a standard way to partition an interable into equivalence classes given a relation in python? | 38,924,421 | <p>Say I have a finite iterable <code>X</code> and an equivalence relation <code>~</code> on <code>X</code>. We can define a function <code>my_relation(x1, x2)</code> that returns <code>True</code> if <code>x1~x2</code> and returns <code>False</code> otherwise. I want to write a function that partitions <code>X</code> into equivalence classes. That is, <code>my_function(X, my_relation)</code> should return a list of the equivalence classes of <code>~</code>. </p>
<p>Is there a standard way to do this in python? Better yet, is there a module designed to deal with equivalence relations?</p>
| 4 | 2016-08-12T18:33:57Z | 38,924,644 | <p>The following function takes an iterable <code>a</code>, and an equivalence function <code>equiv</code>, and does what you ask:</p>
<pre><code>def partition(a, equiv):
partitions = [] # Found partitions
for e in a: # Loop over each element
found = False # Note it is not yet part of a know partition
for p in partitions:
if equiv(e, p[0]): # Found a partition for it!
p.append(e)
found = True
break
if not found: # Make a new partition for it.
partitions.append([e])
return partitions
</code></pre>
<p>Example:</p>
<pre><code>def equiv_(lhs, rhs):
return lhs % 3 == rhs % 3
a_ = range(10)
>>> partition(a_, equiv_)
[[0, 3, 6, 9], [1, 4, 7], [2, 5, 8]]
</code></pre>
| 1 | 2016-08-12T18:49:17Z | [
"python",
"equivalence-classes"
] |
Is there a standard way to partition an interable into equivalence classes given a relation in python? | 38,924,421 | <p>Say I have a finite iterable <code>X</code> and an equivalence relation <code>~</code> on <code>X</code>. We can define a function <code>my_relation(x1, x2)</code> that returns <code>True</code> if <code>x1~x2</code> and returns <code>False</code> otherwise. I want to write a function that partitions <code>X</code> into equivalence classes. That is, <code>my_function(X, my_relation)</code> should return a list of the equivalence classes of <code>~</code>. </p>
<p>Is there a standard way to do this in python? Better yet, is there a module designed to deal with equivalence relations?</p>
| 4 | 2016-08-12T18:33:57Z | 38,924,686 | <p>Would this work ?</p>
<pre><code>def equivalence_partition(iterable, relation):
classes = defaultdict(set)
for element in iterable:
for sample, known in classes.items():
if relation(sample, element):
known.add(element)
break
else:
classes[element].add(element)
return list(classes.values())
</code></pre>
<p>I tried it with :</p>
<pre><code>relation = lambda a, b: (a - b) % 2
equivalence_partition(range(4), relation)
</code></pre>
<p>Which returned :</p>
<pre><code>[{0, 1, 3}, {2}]
</code></pre>
<p>EDIT: If you want this to run as fast as possible, you may :</p>
<ul>
<li>wrap it in a Cython module (removing the defaultdict, there aren't much things to change)</li>
<li>want to try running it with PyPy</li>
<li>find a dedicated module (wasn't able to find any)</li>
</ul>
| 0 | 2016-08-12T18:51:34Z | [
"python",
"equivalence-classes"
] |
Is there a standard way to partition an interable into equivalence classes given a relation in python? | 38,924,421 | <p>Say I have a finite iterable <code>X</code> and an equivalence relation <code>~</code> on <code>X</code>. We can define a function <code>my_relation(x1, x2)</code> that returns <code>True</code> if <code>x1~x2</code> and returns <code>False</code> otherwise. I want to write a function that partitions <code>X</code> into equivalence classes. That is, <code>my_function(X, my_relation)</code> should return a list of the equivalence classes of <code>~</code>. </p>
<p>Is there a standard way to do this in python? Better yet, is there a module designed to deal with equivalence relations?</p>
| 4 | 2016-08-12T18:33:57Z | 38,924,694 | <p>I'm not aware of any python library dealing with equivalence relations.</p>
<p>Perhaps this snippet is useful:</p>
<pre><code>def rel(x1, x2):
return x1 % 5 == x2 % 5
data = range(18)
eqclasses = []
for x in data:
for eqcls in eqclasses:
if rel(x, eqcls[0]):
# x is a member of this class
eqcls.append(x)
break
else:
# x belongs in a new class
eqclasses.append([x])
eqclasses
=> [[0, 5, 10, 15], [1, 6, 11, 16], [2, 7, 12, 17], [3, 8, 13], [4, 9, 14]]
</code></pre>
| 1 | 2016-08-12T18:51:54Z | [
"python",
"equivalence-classes"
] |
How can I pause Monkeyrunner for user input? | 38,924,498 | <p>If I am running in monkeyrunner and want the user to be able to input something into my python script while my program is running how can I do that?</p>
<p>Currently <code>input()</code> never registers that I hit enter.</p>
<p>I don't know why this is. I have searched yesterday and today, and found no answer.<br>
I run my code by typing: <code>monkeyrunner.bat absolutePathnameToPythonFile</code><br>
I run the code from the command line on Windows 10. <br>Monkeyrunner is using python version 2.5.3</p>
<p>Here is my Code:</p>
<pre><code># -*- coding: utf-8 -*-
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
import sys
print("using python version: " + str(sys.version_info))
print("Enter anything to end program...")
character = input()
print(str(character)) #Never Gets here.
print("-Program Ended-")
</code></pre>
| 1 | 2016-08-12T18:39:26Z | 38,956,880 | <p>You can try <a href="https://github.com/dtmilano/AndroidViewClient" rel="nofollow">AndroidViewClient/culebra</a> which is a drop-in replacement for <code>monkeyrunner</code> in 99% of the cases and because it's python you won't have to deal with those jython problems.</p>
| 0 | 2016-08-15T14:19:10Z | [
"android",
"python",
"monkeyrunner"
] |
Tensorflow 0.10 (CUDA) on OSX segfaults on python import | 38,924,568 | <p>I've been trying to get tensorflow 0.10 up and running on my El Capitan Macbook Pro (Late 2013, GeForce GT 750M), so far without success. I've tried the <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html" rel="nofollow">official tensorflow documentation's instructions</a> and a number of other folks' approaches, including <a href="https://gist.github.com/Mistobaan/dd32287eeb6859c6668d" rel="nofollow">this one</a> and <a href="https://medium.com/@fabmilo/how-to-compile-tensorflow-with-cuda-support-on-osx-fd27108e27e1#.eww7dgmtr" rel="nofollow">this one</a>.</p>
<p>For reference, I'm trying to use Python3, CUDA 7.5, and tensorflow 0.10 on OSX 10.11.5.</p>
<p>I've gotten CUDA installed and it recognizes my GPU. I can successfully compile the <code>deviceQuery</code> sample in <code>/Developer/NVIDIA/CUDA-7.5/samples/1_Utilities/deviceQuery</code>. Its output when run is:</p>
<pre><code>./deviceQuery Starting...
CUDA Device Query (Runtime API) version (CUDART static linking)
Detected 1 CUDA Capable device(s)
Device 0: "GeForce GT 750M"
CUDA Driver Version / Runtime Version 7.5 / 7.5
CUDA Capability Major/Minor version number: 3.0
Total amount of global memory: 2048 MBytes (2147024896 bytes)
( 2) Multiprocessors, (192) CUDA Cores/MP: 384 CUDA Cores
GPU Max Clock rate: 926 MHz (0.93 GHz)
Memory Clock rate: 2508 Mhz
Memory Bus Width: 128-bit
L2 Cache Size: 262144 bytes
Maximum Texture Dimension Size (x,y,z) 1D=(65536), 2D=(65536, 65536), 3D=(4096, 4096, 4096)
Maximum Layered 1D Texture Size, (num) layers 1D=(16384), 2048 layers
Maximum Layered 2D Texture Size, (num) layers 2D=(16384, 16384), 2048 layers
Total amount of constant memory: 65536 bytes
Total amount of shared memory per block: 49152 bytes
Total number of registers available per block: 65536
Warp size: 32
Maximum number of threads per multiprocessor: 2048
Maximum number of threads per block: 1024
Max dimension size of a thread block (x,y,z): (1024, 1024, 64)
Max dimension size of a grid size (x,y,z): (2147483647, 65535, 65535)
Maximum memory pitch: 2147483647 bytes
Texture alignment: 512 bytes
Concurrent copy and kernel execution: Yes with 1 copy engine(s)
Run time limit on kernels: Yes
Integrated GPU sharing Host Memory: No
Support host page-locked memory mapping: Yes
Alignment requirement for Surfaces: Yes
Device has ECC support: Disabled
Device supports Unified Addressing (UVA): Yes
Device PCI Domain ID / Bus ID / location ID: 0 / 1 / 0
Compute Mode:
< Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >
deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 7.5, CUDA Runtime Version = 7.5, NumDevs = 1, Device0 = GeForce GT 750M
Result = PASS
</code></pre>
<p>I've also downloaded the cudnn-7.5 library and header and put those files in the correct locations in <code>/usr/local/cuda/lib</code> and <code>include</code>. </p>
<p>In the python3 interactive REPL, if I type in <code>import tensorflow</code>, I get the following output:</p>
<pre><code>Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcublas.7.5.dylib locally
I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcudnn.5.dylib locally
I tensorflow/stream_executor/dso_loader.cc:108] successfully opened CUDA library libcufft.7.5.dylib locally
Segmentation fault: 11
</code></pre>
<p>My question is, what do I need to do to successfully import the module without a segfault? In case it helps, I posted a gist of the <code>dtruss</code> output of running that command in the python3 REPL <a href="https://gist.github.com/danielthompson/617b093177f49c15d1dfb4d656c3b036" rel="nofollow">here</a>, and a gist of the diagnostic (crash) report with stacktrace <a href="https://gist.github.com/danielthompson/26fde46af631ddf3b3df3e86393750ab" rel="nofollow">here</a>.</p>
| 3 | 2016-08-12T18:44:29Z | 38,927,238 | <p>The problem is described in this comment: <a href="https://github.com/tensorflow/tensorflow/issues/2940#issuecomment-238952433" rel="nofollow">https://github.com/tensorflow/tensorflow/issues/2940#issuecomment-238952433</a></p>
<p>"There is a bug with loading libcuda.dylib - the default cuda install creates libcuda.dylib, but tensorflow tries to load libcuda.1.dylib . This fails, resorting to using the LD_LIBRARY_PATH which if NULL crashes. If you copy libcuda.dylib to libcuda.1.dylib it loads fine."</p>
<p>It would be pretty easy to fix the crash for everyone else with a pull request -- ie compile with <code>-c dbg</code> to see exactly which line is trying to use the null value, and adding something like this to the code </p>
<p><code>if (mystring == NULL) {
return;
}</code></p>
| 2 | 2016-08-12T22:24:08Z | [
"python",
"osx",
"tensorflow"
] |
Python/Django pass user input as keyword arguments? | 38,924,574 | <p>I am trying to pass what ever the user inputs into the url as keyword arguments (even if its not a real entry). When I try to assign the input name as the keyword arguments it fails.</p>
<pre><code>HTML:
<p class="search">
<form method="GET" action="{% url 'job' %}" class="sidebar-form">
<div class="ogsearchbar input-group">
<input class="searchbarz" type="text" name="user_input" id="user_input" placeholder="Enter Job Number" autocomplete="off" />
<span class="input-group-btn">
<button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
</p>
</code></pre>
<p>Django:</p>
<pre><code> def get_job(request):
if request.method == 'GET':
formvar = request.GET['user_input']
return HttpResponseRedirect('/jobs/' + formvar)
</code></pre>
| -2 | 2016-08-12T18:44:48Z | 38,924,730 | <p>What you want doesn't make sense. The <code>{{ }}</code> signs denote a context variable which is passed into the template from the server, before the template is rendered. But you're trying to use a value which is only defined when the user actually types something into the rendered page itself.</p>
<p>You could probably do this with some Javascript, but there doesn't seem to be much point. Drop the parameter from the URL and let the form send it in the query params, which you can access in your view as <code>request.GET</code>.</p>
| 1 | 2016-08-12T18:54:16Z | [
"python",
"html",
"django",
"forms",
"url"
] |
Python/Django pass user input as keyword arguments? | 38,924,574 | <p>I am trying to pass what ever the user inputs into the url as keyword arguments (even if its not a real entry). When I try to assign the input name as the keyword arguments it fails.</p>
<pre><code>HTML:
<p class="search">
<form method="GET" action="{% url 'job' %}" class="sidebar-form">
<div class="ogsearchbar input-group">
<input class="searchbarz" type="text" name="user_input" id="user_input" placeholder="Enter Job Number" autocomplete="off" />
<span class="input-group-btn">
<button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
</p>
</code></pre>
<p>Django:</p>
<pre><code> def get_job(request):
if request.method == 'GET':
formvar = request.GET['user_input']
return HttpResponseRedirect('/jobs/' + formvar)
</code></pre>
| -2 | 2016-08-12T18:44:48Z | 39,166,672 | <p>I decided to just go with javascript since my django code was not working with a request method when refreshing the page.</p>
| 0 | 2016-08-26T12:43:58Z | [
"python",
"html",
"django",
"forms",
"url"
] |
unordered_map<int, vector<float>> equivalent in Python | 38,924,598 | <p>I need a structure in Python which maps an integer index to a vector of floating point numbers. My data is like:</p>
<pre><code>[0] = {1.0, 1.0, 1.0, 1.0}
[1] = {0.5, 1.0}
</code></pre>
<p>If I were to write this in C++ I would use the following code for define / add / access as follows:</p>
<pre><code>std::unordered_map<int, std::vector<float>> VertexWeights;
VertexWeights[0].push_back(0.0f);
vertexWeights[0].push_back(1.0f);
vertexWeights[13].push_back(0.5f);
std::cout <<vertexWeights[0][0];
</code></pre>
<p>What is the equivalent structure of this in Python? </p>
| 1 | 2016-08-12T18:46:44Z | 38,924,653 | <p>I would go for a <code>dict</code> with integers as keys and <code>list</code> as items, e.g.</p>
<pre><code>m = dict()
m[0] = list()
m[0].append(1.0)
m[0].append(0.5)
m[13] = list()
m[13].append(13.0)
</code></pre>
<p>if it is not too much data</p>
| 0 | 2016-08-12T18:49:40Z | [
"python",
"c++",
"hashmap"
] |
unordered_map<int, vector<float>> equivalent in Python | 38,924,598 | <p>I need a structure in Python which maps an integer index to a vector of floating point numbers. My data is like:</p>
<pre><code>[0] = {1.0, 1.0, 1.0, 1.0}
[1] = {0.5, 1.0}
</code></pre>
<p>If I were to write this in C++ I would use the following code for define / add / access as follows:</p>
<pre><code>std::unordered_map<int, std::vector<float>> VertexWeights;
VertexWeights[0].push_back(0.0f);
vertexWeights[0].push_back(1.0f);
vertexWeights[13].push_back(0.5f);
std::cout <<vertexWeights[0][0];
</code></pre>
<p>What is the equivalent structure of this in Python? </p>
| 1 | 2016-08-12T18:46:44Z | 38,924,673 | <p>How about dictionary and lists like this:</p>
<pre><code>>>> d = {0: [1.0, 1.0, 1.0, 1.0], 1: [0.5, 1.0]}
>>> d[0]
[1.0, 1.0, 1.0, 1.0]
>>> d[1]
[0.5, 1.0]
>>>
</code></pre>
<p>The key can be integers and associated values can be stored as a list. Dictionary in Python is a hash map and the complexity is amortized <code>O(1)</code>.</p>
| 2 | 2016-08-12T18:50:35Z | [
"python",
"c++",
"hashmap"
] |
unordered_map<int, vector<float>> equivalent in Python | 38,924,598 | <p>I need a structure in Python which maps an integer index to a vector of floating point numbers. My data is like:</p>
<pre><code>[0] = {1.0, 1.0, 1.0, 1.0}
[1] = {0.5, 1.0}
</code></pre>
<p>If I were to write this in C++ I would use the following code for define / add / access as follows:</p>
<pre><code>std::unordered_map<int, std::vector<float>> VertexWeights;
VertexWeights[0].push_back(0.0f);
vertexWeights[0].push_back(1.0f);
vertexWeights[13].push_back(0.5f);
std::cout <<vertexWeights[0][0];
</code></pre>
<p>What is the equivalent structure of this in Python? </p>
| 1 | 2016-08-12T18:46:44Z | 38,924,684 | <p>A <strong><a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionary</a></strong> of this format -> <code>{ (int) key : (list) value }</code></p>
<pre><code>d = {} # Initialize empty dictionary.
d[0] = [1.0, 1.0, 1.0, 1.0] # Place key 0 in d, and map this array to it.
print d[0]
d[1] = [0.5, 1.0]
print d[1]
>>> [1.0, 1.0, 1.0, 1.0]
>>> [0.5, 1.0]
print d[0][0] # std::cout <<vertexWeights[0][0];
>>> 1.0
</code></pre>
| 1 | 2016-08-12T18:51:21Z | [
"python",
"c++",
"hashmap"
] |
Reading data in excel in python | 38,924,642 | <p>I basically have a text file with data as: </p>
<pre><code>Neighbor V State/Pf
10.230.2.91 4 1178
10.229.5.239 4 1177
10.229.6.239 4 1173
</code></pre>
<p>I want to read the values under neighbor column and put in excel. How can I achieve this? I am new to python, so please suggest me ways of doing this.</p>
| -3 | 2016-08-12T18:49:14Z | 38,924,758 | <p>Pandas has methods to transform data frames into Excel files (<code>pd.DataFrame.to_excel</code>), but I agree with bernie: It is not very clear how your data look like</p>
<p><strong>UPDATE</strong></p>
<p>So it would look like</p>
<pre><code>l = list(["Neighbor","10.230.2.91","10.229.5.239","10.229.6.239"])
df = pd.DataFrame(l[1:],columns=[l[0]])
df.to_excel("data.xls","data") # 2nd argument is the sheet name
</code></pre>
<p>You need to install the <code>xlwt</code> module which is not installed per default with Pandas</p>
| 0 | 2016-08-12T18:56:15Z | [
"python",
"excel"
] |
Reading data in excel in python | 38,924,642 | <p>I basically have a text file with data as: </p>
<pre><code>Neighbor V State/Pf
10.230.2.91 4 1178
10.229.5.239 4 1177
10.229.6.239 4 1173
</code></pre>
<p>I want to read the values under neighbor column and put in excel. How can I achieve this? I am new to python, so please suggest me ways of doing this.</p>
| -3 | 2016-08-12T18:49:14Z | 38,924,785 | <p>You'll want something simple that can output to a excel file.</p>
<p>You'll want to split your line into separate lines and only extract the parts that you want. In your case the <code>.split()</code> method would be very helpful. <code>.split()</code> takes your string and splits it based on the delimiter given (default is space). For example <code>string.split('\n')</code> will split the string by lines.</p>
<p>Something like this should be what you want:</p>
<pre><code>import xlwt
book = xlwt.Workbook(encoding="utf-8")
sheet1 = book.add_sheet("Sheet 1")
temp[0].split('\n')
i = 0
for dataLine in temp[0]:
sheet1.write(i, 0, dataLine.split()[0])
i += 1
book.save("excel.xls")
</code></pre>
<p>Note: If you do not want the Neighbors heading you can skip that line and start <code>i</code> at 1.</p>
| 0 | 2016-08-12T18:57:59Z | [
"python",
"excel"
] |
Clarification about Python imports | 38,924,645 | <p>What's the difference between <code>from foo import bar</code>and <code>import foo.bar as bar</code>?</p>
<p>Is there any difference as far as Python namespaces and scope are concerned? If you want to use something from <code>bar</code> (say a function called <code>whatever</code>), you'd call it as <code>bar.whatever()</code> using either approach.</p>
<p>I see both styles of imports in a code base I'm working with and was wondering what differences they entail, if any, and what would be considered the more "Pythonic" approach.</p>
| 5 | 2016-08-12T18:49:20Z | 38,924,783 | <p>When bar is not a module, there is a huge difference:</p>
<pre><code># foo.py
bar = object()
</code></pre>
<p>Here <code>from foo import bar</code> would be normal in python, but <code>import foo.bar as bar</code> would raise an <code>ImportError: No module named bar</code>.</p>
<p>Usually we only use the "as" construct to alias a name: either for adding some context to the name to improve readability, or to avoid a clash with another name. </p>
| 5 | 2016-08-12T18:57:54Z | [
"python",
"python-import"
] |
Clarification about Python imports | 38,924,645 | <p>What's the difference between <code>from foo import bar</code>and <code>import foo.bar as bar</code>?</p>
<p>Is there any difference as far as Python namespaces and scope are concerned? If you want to use something from <code>bar</code> (say a function called <code>whatever</code>), you'd call it as <code>bar.whatever()</code> using either approach.</p>
<p>I see both styles of imports in a code base I'm working with and was wondering what differences they entail, if any, and what would be considered the more "Pythonic" approach.</p>
| 5 | 2016-08-12T18:49:20Z | 38,924,784 | <p>There is a difference, both for when there is a <code>bar</code> module or package inside the <code>foo</code> package, and if <code>bar</code> is <em>not a module at all</em>.</p>
<p>Considered the following <code>foo</code> package:</p>
<pre><code>foo/
__init__.py
bar.py
</code></pre>
<p>If the <code>__init__.py</code> file defines a global name <code>bar</code> <em>too</em>, then the first example will import <em>that object</em>. The second example will import the <code>bar.py</code> module.</p>
<p>However, once the <code>foo.bar</code> module has been imported, the Python import machinery will set the name <code>bar</code> in the <code>foo</code> package, replacing any pre-existing <code>bar</code> global in <code>__init__.py</code>:</p>
<pre><code>$ ls -1 foo/
__init__.py
bar.py
$ cat foo/__init__.py
bar = 'from the foo package'
$ cat foo/bar.py
baz = 'from the foo.bar module'
$ python
Python 2.7.12 (default, Aug 3 2016, 18:12:10)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from foo import bar
>>> bar
'from the foo package'
>>> import foo.bar as bar
>>> bar
<module 'foo.bar' from 'foo/bar.pyc'>
>>> bar.baz
'from the foo.bar module'
>>> from foo import bar
>>> bar
<module 'foo.bar' from 'foo/bar.pyc'>
</code></pre>
<p>The other case is where there is <em>no</em> <code>bar.py</code> submodule. <code>foo</code> could either be a package, or a simple module. In that case <code>from foo import bar</code> will always look for an object in the <code>foo</code> module, and <code>import foo.bar as bar</code> will always fail:</p>
<pre><code>$ cat foo.py
bar = 'from the foo module'
$ python
Python 2.7.12 (default, Aug 3 2016, 18:12:10)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
>>> foo.bar
'from the foo module'
>>> from foo import bar
>>> bar
'from the foo module'
>>> import foo.bar as bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named bar
</code></pre>
<p>Note that in all cases where the import succeeds, you end up with a global name <code>bar</code> bound to <em>something</em>, either an object from a module, or a module object.</p>
| 4 | 2016-08-12T18:57:55Z | [
"python",
"python-import"
] |
Why I get random result from seemingly non-random code with python sklearn? | 38,924,726 | <h3>I updated the question based on the responses.</h3>
<p>I have a list of strings named "str_tuple". I want to compute some similarity measures between the first element in the list and the rest of the elements. I run the following six-line code snippet. </p>
<p>What completely baffles me is that the outcome seems to be completely random every time I run the code. However, I cannot see any randomness introduced in my six-liner. </p>
<h3>Update:</h3>
<p>It is pointed out that TruncatedSVD() has a "random_state" argument. Specifying "random_state" will give fixed result (which is completely True). However, if you change the "random_state", the result will change. But with other strings (e.g. str2), the result is the same regardless how you change "random_state". In fact, these strings are from the HOME_DEPOT Kaggle competition. I have a pd.Series containing thousands of such strings, most of them give non-random results behaving like str2 (no matter what "random_state" is set). For some unknown reasons, str1 is one of the examples that give random results every time you change "random_state". I start to think maybe some intrinsic characters with str1 make the difference. </p>
<pre><code>from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn.preprocessing import Normalizer
# str1 yields random results
str1 = [u'l bracket', u'simpson strong tie 12 gaug angl', u'angl make joint stronger provid consist straight corner simpson strong tie offer wide varieti angl various size thick handl light duti job project structur connect need bent skew match project outdoor project moistur present use zmax zinc coat connector provid extra resist corros look "z" end model number .versatil connector various 90 connect home repair projectsstrong angl nail screw fasten alonehelp ensur joint consist straight strongdimensions: 3 in. xbi 3 in. xbi 1 0.5 in. made 12 gaug steelgalvan extra corros resistanceinstal 10 d common nail 9 xbi 1 0.5 in. strong drive sd screw', u'simpson strong-tie', u'', u'versatile connector for various 90\xe2\xb0 connections and home repair projects stronger than angled nailing or screw fastening alone help ensure joints are consistently straight and strong dimensions: 3 in. x 3 in. x 1-1/2 in. made from 12-gauge steel galvanized for extra corrosion resistance install with 10d common nails or #9 x 1-1/2 in. strong-drive sd screws']
# str2 yields non-random result
str2 = [u'angl bracket', u'simpson strong tie 12 gaug angl', u'angl make joint stronger provid consist straight corner simpson strong tie offer wide varieti angl various size thick handl light duti job project structur connect need bent skew match project outdoor project moistur present use zmax zinc coat connector provid extra resist corros look "z" end model number .versatil connector various 90 connect home repair projectsstrong angl nail screw fasten alonehelp ensur joint consist straight strongdimensions: 3 in. xbi 3 in. xbi 1 0.5 in. made 12 gaug steelgalvan extra corros resistanceinstal 10 d common nail 9 xbi 1 0.5 in. strong drive sd screw', u'simpson strong-tie', u'', u'versatile connector for various 90\xe2\xb0 connections and home repair projects stronger than angled nailing or screw fastening alone help ensure joints are consistently straight and strong dimensions: 3 in. x 3 in. x 1-1/2 in. made from 12-gauge steel galvanized for extra corrosion resistance install with 10d common nails or #9 x 1-1/2 in. strong-drive sd screws']
vectorizer = CountVectorizer(token_pattern=r"\d+\.\d+|\d+\/\d+|\b\w+\b")
# replacing str1 with str2 gives non-ramdom result regardless of random_state
cmat = vectorizer.fit_transform(str1).astype(float) # sparse matrix
cmat = TruncatedSVD(2).fit_transform(cmat) # dense numpy array
cmat = Normalizer().fit_transform(cmat) # dense numpy array
sim = np.dot(cmat, cmat.T)
sim[0,1:].tolist()
</code></pre>
| 1 | 2016-08-12T18:54:06Z | 38,924,895 | <p>By default, <code>Truncated SVD</code> follows a randomized algorithm. So, you must specify the <code>RandomState</code> value to be set as <code>numpy.random.seed</code> value.</p>
<pre><code>cmat = TruncatedSVD(n_components=2, random_state=42).fit_transform(cmat)
</code></pre>
<blockquote>
<p><strong><a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html" rel="nofollow"><code>Docs</code></a></strong></p>
<p><em>class sklearn.decomposition.TruncatedSVD(n_components=2, algorithm='randomized', n_iter=5, random_state=None, tol=0.0)</em></p>
</blockquote>
<hr>
<p>Inorder for it to produce non-random output, the starting element of the list must be present more than once. That is to say, if the starting elements of <code>str1</code> are either <em>angl</em>, <em>versatile</em> or <em>simpson</em>, then it would give non random results. As, <code>str2</code> has <em>angl</em> repeated atleast more than once at the start of the list, it doesn't return random output.</p>
<p>Hence, randomness is a measure of dissimilarity among the occurences of elements in a given list. And, in those cases specifying the <code>RandomState</code> would be useful to generate a unique output. <br>
<em>[credit to @wen for pointing this out]</em></p>
| 3 | 2016-08-12T19:04:51Z | [
"python",
"random",
"machine-learning",
"scikit-learn"
] |
Pass extra arguments to nested Serializer in Django Rest Framework | 38,924,742 | <p>I have such serializer:</p>
<pre><code> class FirstModelSerializer(serializers.ModelSerializer):
secondModel = SecondModelSerializer()
class Meta:
model = FirstModel
fields = '__all__'
</code></pre>
<p>Where secondModel is ManyToMany field of FirstModel.</p>
<p>Is there any way to pass FirstModel object id to SecondModelSerializer?</p>
| 0 | 2016-08-12T18:54:44Z | 38,929,312 | <p>It was easier then I thought. I just had to use context like this</p>
<pre><code>class FirstModelSerializer(serializers.ModelSerializer):
secondModel = SerializerMethodField()
class Meta:
model = FirstModel
fields = '__all__'
def get_secondModel(self, obj):
return SecondModelSerializer(obj.secondModel.all(), many=True, context={'first_model_id': obj.id)).data
</code></pre>
<p>And use self.context.get('first_model_id') in SecondModelSerializer to get to this id.</p>
| 1 | 2016-08-13T04:50:01Z | [
"python",
"django",
"django-rest-framework"
] |
Reading in multiple files in directory using python | 38,924,803 | <p>I'm trying to open each file from a directory and print the contents, so I have a code as such:</p>
<pre><code>import os, sys
def printFiles(dir):
os.chdir(dir)
for f in os.listdir(dir):
myFile = open(f,'r')
lines = myFile.read()
print lines
myFile.close()
printFiles(sys.argv[1])
</code></pre>
<p>The program runs, but the problem here is that it is only printing one of the contents of the file, probably the last file that it has read. Does this have something to do with the open() function?</p>
<p>Edit: added last line that takes in sys.argv. That's the whole code, and it still only prints the last file.</p>
| 0 | 2016-08-12T18:59:04Z | 38,925,006 | <p>The code itself certainly should print the contents of every file.
However, if you supply a local path and not a global path it will not work.</p>
<p>For example, imagine you have the following folder structure:</p>
<pre><code>./a
./a/x.txt
./a/y.txt
./a/a
./a/a/x.txt
</code></pre>
<p>If you now run</p>
<pre><code>printFiles('a')
</code></pre>
<p>you will only get the contents of <em>x.txt</em>, because <em>os.listdir</em> will be executed from within <em>a</em>, and will list the contents of the internal <em>a/a</em> folder, which only has <em>x.txt</em>.</p>
| 0 | 2016-08-12T19:13:54Z | [
"python"
] |
Reading in multiple files in directory using python | 38,924,803 | <p>I'm trying to open each file from a directory and print the contents, so I have a code as such:</p>
<pre><code>import os, sys
def printFiles(dir):
os.chdir(dir)
for f in os.listdir(dir):
myFile = open(f,'r')
lines = myFile.read()
print lines
myFile.close()
printFiles(sys.argv[1])
</code></pre>
<p>The program runs, but the problem here is that it is only printing one of the contents of the file, probably the last file that it has read. Does this have something to do with the open() function?</p>
<p>Edit: added last line that takes in sys.argv. That's the whole code, and it still only prints the last file.</p>
| 0 | 2016-08-12T18:59:04Z | 38,925,260 | <p>There is problem with directory and file paths.</p>
<p>Option 1 - chdir:</p>
<pre><code>def printFiles(dir):
os.chdir(dir)
for f in os.listdir('.'):
myFile = open(f,'r')
# ...
</code></pre>
<p>Option 2 - computing full path:</p>
<pre><code>def printFiles(dir):
# no chdir here
for f in os.listdir(dir):
myFile = open(os.path.join(dir, f), 'r')
# ...
</code></pre>
<p>But you are combining both options - that's wrong.</p>
<p>This is why I prefer <a href="https://docs.python.org/3/library/pathlib.html#basic-use" rel="nofollow"><code>pathlib.Path</code></a> - it's much simpler:</p>
<pre><code>from pathlib import Path
def printFiles(dir):
dir = Path(dir)
for f in dir.iterdir():
myFile = f.open()
# ...
</code></pre>
| 1 | 2016-08-12T19:30:44Z | [
"python"
] |
Combining tuple elements from a list of tuples. Tuple elements are tuple and list | 38,924,829 | <p>I'm relatively new with Python and am having a hard time coming up with a way to make the following work. Currently, I have a list of tuples (larger than <code>list_one</code>. The elements inside these tuples are 1) a tuple, and 2) a string (these strings are always one of two values: in the example <code>'A'</code> or <code>'B'</code> (can also be <code>'D'</code> or <code>'Z'</code>, or any other two strings). The inner tuples include an <code>'id'</code> and a <code>list</code> of values (strings):</p>
<pre><code>list_one = [(('id1', ['v1', 'v2']), 'A'), (('id2', ['v3', 'v4', 'v5', 'v6']), 'A'), (('id3', ['v11']), 'B'), (('id4', ['v12', 'v13']), 'B'), (('id5', ['v14', 'v16']), 'B'), (('id6', ['v17', 'v18', 'v21']), 'A')]
</code></pre>
<p>I'm trying, unsuccessfully, to create a new list that looks as follows:</p>
<pre><code>new_list1 = [('id1',['v1', 'v2', 'v3', 'v4', 'v5', 'v6']), ('id3',['v11', 'v12', 'v13', 'v14', 'v16']), ('id6',['v17', 'v18', 'v21'])]
</code></pre>
<p>When the string value (A, B) changes it should create a new tuple with the first element being the id of the initial tuple where the A,B changes, and the second element being a list of the values ("v's") inside the initial lists. A list if dictionaries would also be fine, e.g:</p>
<pre><code>new_list2 = [{'id1': ['v1','v2', 'v3', 'v4', 'v5', 'v6']}, {'id3':['v11', 'v12', 'v13', 'v14', 'v16']}, {'id6':['v17', 'v18', 'v21']}]
</code></pre>
<p>I appreciate any guidance.</p>
<p>edit:</p>
<pre><code>s = list_one[0][1]
for tup in list_one:
if s in tup:
new_list.extend(tup[0][1])
else:
new_list.append(tup[0][1])
</code></pre>
<p>gives:</p>
<pre><code> ['v1', 'v2', 'v3', 'v4', 'v5', 'v6', ['v11'], ['v12', 'v13'], ['v14', 'v16'], 'v17', 'v18', 'v21']
</code></pre>
<p>which is not really what I'm looking for, as this creates a list around one the 'A' value, with lists of 'B' inside.</p>
| 2 | 2016-08-12T19:00:13Z | 38,926,100 | <p><strong>Edit</strong></p>
<p>This solves a related question, whereby all the lists corresponding to <code>'A'</code> and <code>'B'</code> values are aggregated, and the id is chose of the total first id for each group.</p>
<hr>
<p>Here you go </p>
<pre><code>letterKeyToFirstIDMap = {}
result_dict = {}
for tpl in list_one:
id = tpl[0][0]
lst = tpl[0][1]
letter_id = tpl[1]
if not letter_id in letterKeyToFirstIDMap:
letterKeyToFirstIDMap.update({letter_id: id})
result_dict.update({id:[]})
result_dict[letterKeyToFirstIDMap[letter_id]] += lst
print result_dict
</code></pre>
<p>What is done here is that for each letter key (say A) you want only the first id that is met (say id1) to be the key for the following list. You create a map to store the letterKey and its idKey the first time the pair appears and then just check if the letter key already exists in that map, using it's corresponding idKey if it does, and update the list. </p>
| 1 | 2016-08-12T20:36:30Z | [
"python",
"list"
] |
Combining tuple elements from a list of tuples. Tuple elements are tuple and list | 38,924,829 | <p>I'm relatively new with Python and am having a hard time coming up with a way to make the following work. Currently, I have a list of tuples (larger than <code>list_one</code>. The elements inside these tuples are 1) a tuple, and 2) a string (these strings are always one of two values: in the example <code>'A'</code> or <code>'B'</code> (can also be <code>'D'</code> or <code>'Z'</code>, or any other two strings). The inner tuples include an <code>'id'</code> and a <code>list</code> of values (strings):</p>
<pre><code>list_one = [(('id1', ['v1', 'v2']), 'A'), (('id2', ['v3', 'v4', 'v5', 'v6']), 'A'), (('id3', ['v11']), 'B'), (('id4', ['v12', 'v13']), 'B'), (('id5', ['v14', 'v16']), 'B'), (('id6', ['v17', 'v18', 'v21']), 'A')]
</code></pre>
<p>I'm trying, unsuccessfully, to create a new list that looks as follows:</p>
<pre><code>new_list1 = [('id1',['v1', 'v2', 'v3', 'v4', 'v5', 'v6']), ('id3',['v11', 'v12', 'v13', 'v14', 'v16']), ('id6',['v17', 'v18', 'v21'])]
</code></pre>
<p>When the string value (A, B) changes it should create a new tuple with the first element being the id of the initial tuple where the A,B changes, and the second element being a list of the values ("v's") inside the initial lists. A list if dictionaries would also be fine, e.g:</p>
<pre><code>new_list2 = [{'id1': ['v1','v2', 'v3', 'v4', 'v5', 'v6']}, {'id3':['v11', 'v12', 'v13', 'v14', 'v16']}, {'id6':['v17', 'v18', 'v21']}]
</code></pre>
<p>I appreciate any guidance.</p>
<p>edit:</p>
<pre><code>s = list_one[0][1]
for tup in list_one:
if s in tup:
new_list.extend(tup[0][1])
else:
new_list.append(tup[0][1])
</code></pre>
<p>gives:</p>
<pre><code> ['v1', 'v2', 'v3', 'v4', 'v5', 'v6', ['v11'], ['v12', 'v13'], ['v14', 'v16'], 'v17', 'v18', 'v21']
</code></pre>
<p>which is not really what I'm looking for, as this creates a list around one the 'A' value, with lists of 'B' inside.</p>
| 2 | 2016-08-12T19:00:13Z | 38,926,128 | <p>You can basically loop along, remembering what is the current key (initialized to <code>None</code>). </p>
<pre><code>key = None # This is 'A' or 'B' in your example, but it starts off as None
new_list = [] # This holds the final result
for r, l in [(r, l) for (l, r) in list_one]:
if r != key: # If the current is not the key, time to switch to a new one
id_ = l[0]
new_list.append({id_: []})
new_list[-1][id_].extend(l[1]) # Extend the current list
key = r # Make it the current key in any case.
>>> new_list
[{'id1': ['v1', 'v2', 'v3', 'v4', 'v5', 'v6']},
{'id3': ['v11', 'v12', 'v13', 'v14', 'v16']},
{'id6': ['v17', 'v18', 'v21']}]
</code></pre>
| 1 | 2016-08-12T20:39:13Z | [
"python",
"list"
] |
Parse non-standard semicolon separated "JSON" | 38,924,902 | <p>I have a non-standard "JSON" file to parse. Each item is semicolon separated instead of comma separated. I can't simply replace <code>;</code> with <code>,</code> because there might be some value containing <code>;</code>, ex. "hello; world". How can I parse this into the same structure that JSON would normally parse it?</p>
<pre><code>{
"client" : "someone";
"server" : ["s1"; "s2"];
"timestamp" : 1000000;
"content" : "hello; world";
...
}
</code></pre>
| 1 | 2016-08-12T19:05:16Z | 38,925,163 | <p>Use the Python <a href="https://docs.python.org/2/library/tokenize.html" rel="nofollow"><code>tokenize</code> module</a> to transform the text stream to one with commas instead of semicolons. The Python tokenizer is happy to handle JSON input too, even including semicolons. The tokenizer presents strings as <em>whole tokens</em>, and 'raw' semicolons are in the stream as single <code>token.OP</code> tokens for you to replace:</p>
<pre><code>import tokenize
import json
corrected = []
with open('semi.json', 'r') as semi:
for token in tokenize.generate_tokens(semi.readline):
if token[0] == tokenize.OP and token[1] == ';':
corrected.append(',')
else:
corrected.append(token[1])
data = json.loads(''.join(corrected))
</code></pre>
<p>This assumes that the format <em>becomes</em> valid JSON once you've replaced the semicolons with commas; e.g. no trailing commas before a closing <code>]</code> or <code>}</code> allowed, although you could even track the last comma added and remove it again if the next non-newline token is a closing brace.</p>
<p>Demo:</p>
<pre><code>>>> import tokenize
>>> import json
>>> open('semi.json', 'w').write('''\
... {
... "client" : "someone";
... "server" : ["s1"; "s2"];
... "timestamp" : 1000000;
... "content" : "hello; world"
... }
... ''')
>>> corrected = []
>>> with open('semi.json', 'r') as semi:
... for token in tokenize.generate_tokens(semi.readline):
... if token[0] == tokenize.OP and token[1] == ';':
... corrected.append(',')
... else:
... corrected.append(token[1])
...
>>> print ''.join(corrected)
{
"client":"someone",
"server":["s1","s2"],
"timestamp":1000000,
"content":"hello; world"
}
>>> json.loads(''.join(corrected))
{u'content': u'hello; world', u'timestamp': 1000000, u'client': u'someone', u'server': [u's1', u's2']}
</code></pre>
<p>Inter-token whitespace was dropped, but could be re-instated by paying attention to the <code>tokenize.NL</code> tokens and the <code>(lineno, start)</code> and <code>(lineno, end)</code> position tuples that are part of each token. Since the whitespace around the tokens doesn't matter to a JSON parser, I've not bothered with this.</p>
| 6 | 2016-08-12T19:24:08Z | [
"python",
"json",
"parsing"
] |
Parse non-standard semicolon separated "JSON" | 38,924,902 | <p>I have a non-standard "JSON" file to parse. Each item is semicolon separated instead of comma separated. I can't simply replace <code>;</code> with <code>,</code> because there might be some value containing <code>;</code>, ex. "hello; world". How can I parse this into the same structure that JSON would normally parse it?</p>
<pre><code>{
"client" : "someone";
"server" : ["s1"; "s2"];
"timestamp" : 1000000;
"content" : "hello; world";
...
}
</code></pre>
| 1 | 2016-08-12T19:05:16Z | 38,925,263 | <p>You can do some odd things and get it (probably) right.</p>
<p>Because strings on JSON cannot have control chars such as <code>\t</code>, you could replace every <code>;</code> to <code>\t,</code> so the file will be parsed correctly if your JSON parser is able to load non strict JSON (such as Python's).</p>
<p>After, you only need to convert your data back to JSON so you can replace back all these <code>\t,</code> to <code>;</code> and use a normal JSON parser to finally load the correct object.</p>
<p>Some sample code in Python:</p>
<pre><code>data = '''{
"client" : "someone";
"server" : ["s1"; "s2"];
"timestamp" : 1000000;
"content" : "hello; world"
}'''
import json
dec = json.JSONDecoder(strict=False).decode(data.replace(';', '\t,'))
enc = json.dumps(dec)
out = json.loads(dec.replace('\\t,' ';'))
</code></pre>
| 0 | 2016-08-12T19:30:53Z | [
"python",
"json",
"parsing"
] |
Parse non-standard semicolon separated "JSON" | 38,924,902 | <p>I have a non-standard "JSON" file to parse. Each item is semicolon separated instead of comma separated. I can't simply replace <code>;</code> with <code>,</code> because there might be some value containing <code>;</code>, ex. "hello; world". How can I parse this into the same structure that JSON would normally parse it?</p>
<pre><code>{
"client" : "someone";
"server" : ["s1"; "s2"];
"timestamp" : 1000000;
"content" : "hello; world";
...
}
</code></pre>
| 1 | 2016-08-12T19:05:16Z | 38,925,348 | <p>Using a simple character state machine, you can convert this text back to valid JSON. The basic thing we need to handle is to determine the current "state" (whether we are escaping a character, in a string, list, dictionary, etc), and replace ';' by ',' when in a certain state.</p>
<p>I don't know if this is properly way to write it, there is a probably a way to make it shorter, but I don't have enough programming skills to make an optimal version for this. </p>
<p>I tried to comment as much as I could :</p>
<pre><code>def filter_characters(text):
# we use this dictionary to match opening/closing tokens
STATES = {
'"': '"', "'": "'",
"{": "}", "[": "]"
}
# these two variables represent the current state of the parser
escaping = False
state = list()
# we iterate through each character
for c in text:
if escaping:
# if we are currently escaping, no special treatment
escaping = False
else:
if c == "\\":
# character is a backslash, set the escaping flag for the next character
escaping = True
elif state and c == state[-1]:
# character is expected closing token, update state
state.pop()
elif c in STATES:
# character is known opening token, update state
state.append(STATES[c])
elif c == ';' and state == ['}']:
# this is the delimiter we want to change
c = ','
yield c
assert not state, "unexpected end of file"
def filter_text(text):
return ''.join(filter_characters(text))
</code></pre>
<p>Testing with :</p>
<pre><code>{
"client" : "someone";
"server" : ["s1"; "s2"];
"timestamp" : 1000000;
"content" : "hello; world";
...
}
</code></pre>
<p>Returns :</p>
<pre><code>{
"client" : "someone",
"server" : ["s1"; "s2"],
"timestamp" : 1000000,
"content" : "hello; world",
...
}
</code></pre>
| 0 | 2016-08-12T19:38:17Z | [
"python",
"json",
"parsing"
] |
Parse non-standard semicolon separated "JSON" | 38,924,902 | <p>I have a non-standard "JSON" file to parse. Each item is semicolon separated instead of comma separated. I can't simply replace <code>;</code> with <code>,</code> because there might be some value containing <code>;</code>, ex. "hello; world". How can I parse this into the same structure that JSON would normally parse it?</p>
<pre><code>{
"client" : "someone";
"server" : ["s1"; "s2"];
"timestamp" : 1000000;
"content" : "hello; world";
...
}
</code></pre>
| 1 | 2016-08-12T19:05:16Z | 38,933,822 | <p>Pyparsing makes it easy to write a string transformer. Write an expression for the string to be changed, and add a parse action (a parse-time callback) to replace the matched text with what you want. If you need to avoid some cases (like quoted strings or comments), then include them in the scanner, but just leave them unchanged. Then, to actually transform the string, call <code>scanner.transformString</code>.</p>
<p>(It wasn't clear from your example whether you might have a ';' after the last element in one of your bracketed lists, so I added a term to suppress these, since a trailing ',' in a bracketed list is also invalid JSON.)</p>
<pre><code>sample = """
{
"client" : "someone";
"server" : ["s1"; "s2"];
"timestamp" : 1000000;
"content" : "hello; world";
}"""
from pyparsing import Literal, replaceWith, Suppress, FollowedBy, quotedString
import json
SEMI = Literal(";")
repl_semi = SEMI.setParseAction(replaceWith(','))
term_semi = Suppress(SEMI + FollowedBy('}'))
qs = quotedString
scanner = (qs | term_semi | repl_semi)
fixed = scanner.transformString(sample)
print(fixed)
print(json.loads(fixed))
</code></pre>
<p>prints:</p>
<pre><code>{
"client" : "someone",
"server" : ["s1", "s2"],
"timestamp" : 1000000,
"content" : "hello; world"}
{'content': 'hello; world', 'timestamp': 1000000, 'client': 'someone', 'server': ['s1', 's2']}
</code></pre>
| 0 | 2016-08-13T14:40:55Z | [
"python",
"json",
"parsing"
] |
Copying partial list in python | 38,924,992 | <p>I'm trying to collect the output from a system command that lists tickets (strings) separated by new lines. I specify what 'lastTicket' is and I want to copy the full list until I reach lastTicket. I'm getting the following error, "TypeError: list indices must be integers, not str" on line 5 below. How can I copy only the portion of the list that I need? Thanks.</p>
<pre><code>output = subprocess.check_output(cmd, shell=True)
allTickets = output.rstrip().split('\n')
idx = len(allTickets)
for ii in allTickets:
if lastTicket in allTickets[ii]:
idx = ii
break
print idx
tickets = allTickets[idx:len(allTickets)]
</code></pre>
| 0 | 2016-08-12T19:12:44Z | 38,925,049 | <p><code>li</code> is value in the <code>allTickets</code> (which I guess is String). You are passing that to get value <code>allTickets[ii]</code>. Array/list index are always integers. </p>
<p>I think you are looking for something like:</p>
<pre><code>for index, val in .........
if lastTicket in allTickets[index]:
</code></pre>
| -1 | 2016-08-12T19:16:17Z | [
"python",
"list"
] |
Copying partial list in python | 38,924,992 | <p>I'm trying to collect the output from a system command that lists tickets (strings) separated by new lines. I specify what 'lastTicket' is and I want to copy the full list until I reach lastTicket. I'm getting the following error, "TypeError: list indices must be integers, not str" on line 5 below. How can I copy only the portion of the list that I need? Thanks.</p>
<pre><code>output = subprocess.check_output(cmd, shell=True)
allTickets = output.rstrip().split('\n')
idx = len(allTickets)
for ii in allTickets:
if lastTicket in allTickets[ii]:
idx = ii
break
print idx
tickets = allTickets[idx:len(allTickets)]
</code></pre>
| 0 | 2016-08-12T19:12:44Z | 38,925,063 | <p>use either</p>
<pre><code>for ii in range(len(allTickets)):
if lastTicket in allTickets[ii]:
idx = ii
break
</code></pre>
<p>BTW are you sure you want <code>if lastTicket in allTickets[ii]:</code> and not <code>if lastTicket == allTickets[ii]:</code>? </p>
| 1 | 2016-08-12T19:17:16Z | [
"python",
"list"
] |
Copying partial list in python | 38,924,992 | <p>I'm trying to collect the output from a system command that lists tickets (strings) separated by new lines. I specify what 'lastTicket' is and I want to copy the full list until I reach lastTicket. I'm getting the following error, "TypeError: list indices must be integers, not str" on line 5 below. How can I copy only the portion of the list that I need? Thanks.</p>
<pre><code>output = subprocess.check_output(cmd, shell=True)
allTickets = output.rstrip().split('\n')
idx = len(allTickets)
for ii in allTickets:
if lastTicket in allTickets[ii]:
idx = ii
break
print idx
tickets = allTickets[idx:len(allTickets)]
</code></pre>
| 0 | 2016-08-12T19:12:44Z | 38,925,486 | <p>Use <code>enumerate</code> to get an index:</p>
<pre><code>for idx, ticket in enumerate(allTickets):
if lastTicket in ticket:
break
print idx
tickets = allTickets[idx:]
</code></pre>
| 0 | 2016-08-12T19:47:58Z | [
"python",
"list"
] |
How do I unit test HTTP Digest Authentication in Flask? | 38,925,016 | <p>I've got a flask app that implements a REST api. For reasons, I'm using HTTP Digest Authentication. I've used the Flask-HTTPAuth library to implement the digest authentication and it works; however, I am unable to authenticate in the unit tests. </p>
<p>For the unit tests, prior to setting up the authentication, I'm doing something like this:</p>
<pre><code>class FooTestCase(unittest.TestCase):
def setUp(self):
self.app = foo.app.test_client()
def test_root(self):
response = self.app.get('/')
# self.assert.... blah blah blah
</code></pre>
<p>Prior to implementing the authentication, this was fine. Now I get a 401, which is expected as the initial response for a digest auth request. I've searched and searched and followed a few suggestions related to http basic auth (using parameters data = { #various stuff} and follow_redirects=True) but I've had no success.</p>
<p>Does anyone have a clue how to implement unittests in this case?</p>
| 2 | 2016-08-12T19:14:18Z | 38,925,124 | <p>It's not neccessary to use real-world authentication in tests. Either disable authentication when running tests or create test user and use this test user in tests.</p>
<p>For example:</p>
<pre><code> @digest_auth.get_password
def get_pw(username):
if running_from_tests():
if username == 'test':
return 'testpw'
else:
return None
else:
# ... normal auth that you have
</code></pre>
<p>Of couse this test user must never be active in production :) For implementation of <code>running_from_tests()</code> see <a href="http://stackoverflow.com/questions/25188119/test-if-code-is-executed-from-within-a-py-test-session">Test if code is executed from within a py.test session</a> (if you are using py.test).</p>
| 0 | 2016-08-12T19:21:37Z | [
"python",
"flask",
"python-unittest",
"digest-authentication",
"flask-httpauth"
] |
How do I unit test HTTP Digest Authentication in Flask? | 38,925,016 | <p>I've got a flask app that implements a REST api. For reasons, I'm using HTTP Digest Authentication. I've used the Flask-HTTPAuth library to implement the digest authentication and it works; however, I am unable to authenticate in the unit tests. </p>
<p>For the unit tests, prior to setting up the authentication, I'm doing something like this:</p>
<pre><code>class FooTestCase(unittest.TestCase):
def setUp(self):
self.app = foo.app.test_client()
def test_root(self):
response = self.app.get('/')
# self.assert.... blah blah blah
</code></pre>
<p>Prior to implementing the authentication, this was fine. Now I get a 401, which is expected as the initial response for a digest auth request. I've searched and searched and followed a few suggestions related to http basic auth (using parameters data = { #various stuff} and follow_redirects=True) but I've had no success.</p>
<p>Does anyone have a clue how to implement unittests in this case?</p>
| 2 | 2016-08-12T19:14:18Z | 38,927,799 | <p>Unfortunately digest authentication is harder to test or bypass in Flask-HTTPAuth.</p>
<p>One option is to actually calculate the correct hashes and perform the full authentication during tests. You can see a few examples of this in the <a href="https://github.com/miguelgrinberg/Flask-HTTPAuth/tree/master/tests" rel="nofollow">Flask-HTTPAuth unit tests</a>. Here is one:</p>
<pre><code>def test_digest_auth_login_valid(self):
response = self.client.get('/digest')
self.assertTrue(response.status_code == 401)
header = response.headers.get('WWW-Authenticate')
auth_type, auth_info = header.split(None, 1)
d = parse_dict_header(auth_info)
a1 = 'john:' + d['realm'] + ':bye'
ha1 = md5(a1).hexdigest()
a2 = 'GET:/digest'
ha2 = md5(a2).hexdigest()
a3 = ha1 + ':' + d['nonce'] + ':' + ha2
auth_response = md5(a3).hexdigest()
response = self.client.get(
'/digest', headers={
'Authorization': 'Digest username="john",realm="{0}",'
'nonce="{1}",uri="/digest",response="{2}",'
'opaque="{3}"'.format(d['realm'],
d['nonce'],
auth_response,
d['opaque'])})
self.assertEqual(response.data, b'digest_auth:john')
</code></pre>
<p>In this example, the username is <code>john</code> and the password is <code>bye</code>. Presumably you have some predetermined credentials for a user that can be used in unit tests, so you would plug those in the <code>a1</code> variable above. This authentication dance can be included in an auxiliary function that wraps the sending of a request during tests, that way you don't have to repeat this in every test.</p>
| 2 | 2016-08-12T23:40:16Z | [
"python",
"flask",
"python-unittest",
"digest-authentication",
"flask-httpauth"
] |
how to compare two columns in pandas to make a third column ? | 38,925,082 | <p>i have two columns age and sex in a pandas dataframe </p>
<pre><code>sex = ['m', 'f' , 'm', 'f', 'f', 'f', 'f']
age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ]
</code></pre>
<p>now i want to extract a third column : like this
if age <=9 then output ' child' and if age >9 then output the respective gender </p>
<pre><code>sex = ['m', 'f' , 'm','f' ,'f' ,'f' , 'f']
age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ]
yes = ['m', 'f' ,'m' ,'child','child','child','f' ]
</code></pre>
<p>please help
ps . i am still working on it if i get anything i will immediately update </p>
| 2 | 2016-08-12T19:18:43Z | 38,925,156 | <p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p>
<pre><code>df['col3'] = np.where(df['age'] <= 9, 'child', df['sex'])
</code></pre>
<p>The resulting output:</p>
<pre><code> age sex col3
0 16 m m
1 15 f f
2 14 m m
3 9 f child
4 8 f child
5 2 f child
6 56 f f
</code></pre>
<p><strong>Timings</strong></p>
<p>Using the following setup to get a larger sample DataFrame:</p>
<pre><code>np.random.seed([3,1415])
n = 10**5
df = pd.DataFrame({'sex': np.random.choice(['m', 'f'], size=n), 'age': np.random.randint(0, 100, size=n)})
</code></pre>
<p>I get the following timings:</p>
<pre><code>%timeit np.where(df['age'] <= 9, 'child', df['sex'])
1000 loops, best of 3: 1.26 ms per loop
%timeit df['sex'].where(df['age'] > 9, 'child')
100 loops, best of 3: 3.25 ms per loop
%timeit df.apply(lambda x: 'child' if x['age'] <= 9 else x['sex'], axis=1)
100 loops, best of 3: 3.92 ms per loop
</code></pre>
| 6 | 2016-08-12T19:23:50Z | [
"python",
"pandas"
] |
how to compare two columns in pandas to make a third column ? | 38,925,082 | <p>i have two columns age and sex in a pandas dataframe </p>
<pre><code>sex = ['m', 'f' , 'm', 'f', 'f', 'f', 'f']
age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ]
</code></pre>
<p>now i want to extract a third column : like this
if age <=9 then output ' child' and if age >9 then output the respective gender </p>
<pre><code>sex = ['m', 'f' , 'm','f' ,'f' ,'f' , 'f']
age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ]
yes = ['m', 'f' ,'m' ,'child','child','child','f' ]
</code></pre>
<p>please help
ps . i am still working on it if i get anything i will immediately update </p>
| 2 | 2016-08-12T19:18:43Z | 38,925,166 | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html" rel="nofollow">pandas.DataFrame.where</a>. For example</p>
<pre><code>child.where(age<=9, sex)
</code></pre>
| 4 | 2016-08-12T19:24:12Z | [
"python",
"pandas"
] |
how to compare two columns in pandas to make a third column ? | 38,925,082 | <p>i have two columns age and sex in a pandas dataframe </p>
<pre><code>sex = ['m', 'f' , 'm', 'f', 'f', 'f', 'f']
age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ]
</code></pre>
<p>now i want to extract a third column : like this
if age <=9 then output ' child' and if age >9 then output the respective gender </p>
<pre><code>sex = ['m', 'f' , 'm','f' ,'f' ,'f' , 'f']
age = [16 , 15 , 14 , 9 , 8 , 2 , 56 ]
yes = ['m', 'f' ,'m' ,'child','child','child','f' ]
</code></pre>
<p>please help
ps . i am still working on it if i get anything i will immediately update </p>
| 2 | 2016-08-12T19:18:43Z | 38,925,236 | <pre><code>df = pd.DataFrame({'sex':['m', 'f' , 'm', 'f', 'f', 'f', 'f'],
'age':[16, 15, 14, 9, 8, 2, 56]})
df['yes'] = df.apply(lambda x: 'child' if x['age'] <= 9 else x['sex'], axis=1)
</code></pre>
<p>Result:</p>
<pre><code> age sex yes
0 16 m m
1 15 f f
2 14 m m
3 9 f child
4 8 f child
5 2 f child
6 56 f f
</code></pre>
| 1 | 2016-08-12T19:29:10Z | [
"python",
"pandas"
] |
IPython Notebook: Count number of cells in notebook | 38,925,125 | <p>Answering questions Stack Overflow, I use the same ipython notebook, which makes its easier to search previously given answers.</p>
<p>The notebook is starting to slow down. The question I have is: How do I count the numbers of cells in the notebook?</p>
| 3 | 2016-08-12T19:21:48Z | 38,925,464 | <ol>
<li>I recommend you don't use the same ipython notebook for everything. If using multiple notebooks would lead to repeat code, you should be able to factor out common functionality into actual python modules which your notebooks can import.</li>
<li>the notebook is just a json file, if you read the file as a json you can do it easily.</li>
</ol>
<p>For example:</p>
<pre><code>import json
document = json.load(open(filepath,'r'))
for worksheet in document['worksheets']:
print len(worksheet['cells'])
</code></pre>
| 5 | 2016-08-12T19:46:50Z | [
"python",
"ipython",
"ipython-notebook",
"jupyter-notebook"
] |
IPython Notebook: Count number of cells in notebook | 38,925,125 | <p>Answering questions Stack Overflow, I use the same ipython notebook, which makes its easier to search previously given answers.</p>
<p>The notebook is starting to slow down. The question I have is: How do I count the numbers of cells in the notebook?</p>
| 3 | 2016-08-12T19:21:48Z | 38,925,503 | <p>You could execute your notebook from the command line by:</p>
<pre><code>jupyter nbconvert --ExecutePreprocessor.allow_errors=True --to notebook --execute jupyter_notebook.ipynb
</code></pre>
<p>where: <code>jupyter_notebook.ipynb</code> should be replaced with your <code>filename.ipynb</code>.</p>
<p>With <code>allow_errors=True</code>, the notebook is executed until the end, regardless of any error encountered during the execution. The output notebook, will contain the stack-traces and error messages for all the cells raising exceptions.</p>
| 1 | 2016-08-12T19:48:44Z | [
"python",
"ipython",
"ipython-notebook",
"jupyter-notebook"
] |
IPython Notebook: Count number of cells in notebook | 38,925,125 | <p>Answering questions Stack Overflow, I use the same ipython notebook, which makes its easier to search previously given answers.</p>
<p>The notebook is starting to slow down. The question I have is: How do I count the numbers of cells in the notebook?</p>
| 3 | 2016-08-12T19:21:48Z | 38,926,044 | <p>There's actually no need to parse the json. Just read it as text and count instances of, for example, "cell type":</p>
<pre><code>with open(fname, 'r') as f:
counter = 0
for line in f:
if '"cell_type":' in line:
counter += 1
</code></pre>
<p>Or, even easier, <strong>just open your .ipynb notebook in a text editor, then highlight the same bit of text and see the count by hitting ctrl+F (or whatever the binding is for search).</strong></p>
<p>If any cells have markdown and you want to avoid those, you can just search on <code>"cell_type": "code",</code> too.</p>
<p>Although as others have said, you're better off not storing your code this way. Or at least, I imagine you can store it in ways that will make it much easier to access in the future, if you want it for reference.</p>
| 3 | 2016-08-12T20:31:46Z | [
"python",
"ipython",
"ipython-notebook",
"jupyter-notebook"
] |
handling a sequence of pyparsing expressions in any order and number | 38,925,138 | <p>Using pyparsing, I need to specify that two expressions can occur in any order and in any number between two braces. Below is my code. </p>
<pre><code>import pyparsing as pp
def updateList(someList):
def parseAction(str, loc, tokens):
someList.append(tokens[0])
return parseAction
msgNameList = []
ident = pp.Word(pp.alphanums + "_" + ".")
openBrace = pp.Suppress(pp.Literal("{"))
closeBrace = pp.Suppress(pp.Literal("}"))
fieldKw = pp.Keyword("field")
fieldExpr = fieldKw + ident + ident
msgKw = pp.Suppress(pp.Keyword("msg"))
msgName = ident.setParseAction(updateList(msgNameList))
msgExpr = pp.Forward()
msgBody = (openBrace + (pp.ZeroOrMore(fieldExpr) & pp.ZeroOrMore(msgExpr)) + closeBrace)
msgExpr << msgKw + msgName + pp.Optional(msgBody)
testStr1 = "msg msgNameA {msg msgNameAB {field type2 field2} field type1 field1}"
msgExpr.parseString(testStr1)
print msgNameList
msgNameList = []
testStr2 = "msg msgNameA {field type1 field1 msg msgNameAB {field type2 field2}}"
msgExpr.parseString(testStr2)
print msgNameList
</code></pre>
<p>which produces this output:</p>
<pre><code>['msgNameA', 'msgNameAB', 'type2', 'field2', 'type1', 'field1']
[]
</code></pre>
<p>Note that I add to msgNameList only upon parsing the msgName expression. (The eventual expression and parse functions for it will be more complicated.) </p>
<p>The output I want, for both test strings is:</p>
<pre><code>['msgNameA', 'msgNameAB']
</code></pre>
<p>I am certain that my parsing expression for msgBody is incorrect, but I cannot figure out how to express what I need in pyparsing. Within the braces, msgExpr or a fieldExpr can occur in any order and in any number (msgExpr ... fieldExpr ... or fieldExpr ... msgExpr ...). Some examples:</p>
<ol>
<li>msgExpr msgExpr fieldExpr fieldExpr fieldExpr msgExpr </li>
<li>fieldExpr msgExpr fieldExpr fieldExpr msgExpr fieldExpr </li>
<li>msgExpr fieldExpr fieldExpr </li>
</ol>
<p>I know there must be a way to do this, but I`m missing it. </p>
<p>Thanks in advance</p>
| 1 | 2016-08-12T19:22:21Z | 38,925,426 | <p>(First, in the future, please prepare a <a href="http://stackoverflow.com/help/mcve">MCVE</a> of your question. The gist of your question is</p>
<blockquote>
<p>Using pyparsing, I need to specify that two expressions can occur in any order and in any number between two braces. Below is my code. </p>
</blockquote>
<p>so please prepare a question containing only enough details for that.)</p>
<p>Suppose we start with</p>
<pre><code>from pyparsing import *
foo = Literal('foo')
bar = Literal('bar')
</code></pre>
<p>Then to specify "any order and any number between the brackets"</p>
<pre><code>openBrace = Suppress(Literal("{"))
closeBrace = Suppress(Literal("}"))
foo_or_bar = foo | bar
content = ZeroOrMore(foo_or_bar)
exp = openBrace + content + closeBrace
</code></pre>
<p>Now we can check:</p>
<pre><code>In [40]: exp.parseString('{foo}')
Out[40]: (['foo'], {})
In [41]: exp.parseString('{foobarfoo}')
Out[41]: (['foo', 'bar', 'foo'], {})
</code></pre>
| 2 | 2016-08-12T19:43:41Z | [
"python",
"python-2.7",
"parsing",
"pyparsing"
] |
Redshift Python UDFs Import on Every Function Call | 38,925,245 | <p>I'm starting to learn Python User-Defined Functions in Redshift and I have a couple of questions that I would need clarifications on. Assuming that I have defined the following function:</p>
<pre><code>CREATE OR REPLACE FUNCTION f_parse_url_query_string(url VARCHAR(MAX))
RETURNS varchar(max)
STABLE
AS $$
from urlparse import urlparse, parse_qsl
import json
return json.dumps(dict(parse_qsl(urlparse(url)[4])))
$$ LANGUAGE plpythonu;
</code></pre>
<p>Is this going to run the <code>imports</code> every time that the function is called or is this compiled by Redshift and just imported a single time?</p>
<p>My second question is whether there is a way to return a variable data type. For example, if I wanted to create a function that grabs the value of nested json fields, the result could be anything from a string to an integer or a boolean. Is there someway to create an autodetect on the function return type?</p>
| 1 | 2016-08-12T19:29:44Z | 38,928,574 | <p><strong>Execution</strong></p>
<p>Yes, the <code>import</code> will execute every time.</p>
<p>One way to avoid this is to use <code>IMMUTABLE</code> as the volatility of the function. This allows Redshift to cache the output of the function for the given input value, avoiding the need to run the Python function in future for the same input value.</p>
<p><strong>Return value</strong></p>
<p><strong>The data type of the return value is fixed and cannot be changed.</strong> A different return value can be defined for a different function name or a different input type (eg define one function that takes in an integer and returns an integer, and then another function with the same name but a string input type that returns a string as output).</p>
<p>Also, it would be very difficult to use a function that returns a different output data type -- the SQL statement that calls the UDF would be wanting a specific data type, not one that changes.</p>
| 1 | 2016-08-13T02:16:41Z | [
"python",
"user-defined-functions",
"amazon-redshift"
] |
Django manage.py runserver do not display "Welcome Page" | 38,925,323 | <p>I am following the Django Tutorial but I am getting a error when trying to load the welcome page, just after starting the server I did this tutorial in other pc and I did not have any problem. </p>
<p>Using:
Windows 7 / Djando 1.9 / Python 3.4.5</p>
<p>1 - I started the project
2 - python manage.py runserver
<a href="http://i.stack.imgur.com/Dte0A.png" rel="nofollow"><img src="http://i.stack.imgur.com/Dte0A.png" alt="enter image description here"></a></p>
<p>3 - When I access the page:</p>
<p><a href="http://i.stack.imgur.com/Bl6oW.png" rel="nofollow"><img src="http://i.stack.imgur.com/Bl6oW.png" alt="enter image description here"></a></p>
<p>4 - The I got on cmd</p>
<p><a href="http://i.stack.imgur.com/I2IzW.png" rel="nofollow"><img src="http://i.stack.imgur.com/I2IzW.png" alt="enter image description here"></a></p>
<p>I have already tried hundred of ports, ips, firewall disabling, django 1.10 ...</p>
<p>5 - urls.py</p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
</code></pre>
| 0 | 2016-08-12T19:35:45Z | 38,926,890 | <p>The problem is, you have no router or view defined for "/". All valid paths would be <a href="http://127.0.0.1/polls/" rel="nofollow">http://127.0.0.1/polls/</a>* and <a href="http://127.0.0.1/admin/" rel="nofollow">http://127.0.0.1/admin/</a>*.</p>
<pre><code>from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
# load urls of an app and define there more detailed
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
# load specific view in an app
url(r'^your_test_view','my_app.views.my_view', name="my_view"),
url(r'^$','my_app.views.my_home_view', name="home"),
]
</code></pre>
| 0 | 2016-08-12T21:45:47Z | [
"python",
"django",
"django-admin",
"django-manage.py"
] |
Pyspark Enforce Nullability on Read of Json File | 38,925,358 | <p>I'm trying to read a json file and enforce a schema on read using SQLContext but the nullability part seems to get ignored.
I have a schema something like this:</p>
<pre><code>StructType(List(StructField(some_field,StringType,false), StructField(some_other_field,StringType,false))
</code></pre>
<p>Now then, I want to read a json file and enforce that schema onto it as such:</p>
<pre><code>sqlc = SQLContext(sc)
df = sqlc.read.load("path/to/file", format="json", schema=schema)
</code></pre>
<p>The field names and data type seem to work just fine, but no matter what I put in for nullability, all the columns have nullable = true as such:</p>
<pre><code>root
|--some_field: string (nullable = true)
|--some_other_field: string (nullable = true)
</code></pre>
<p>How can I enforce nullability on my columns on read?</p>
<p>FYI. I'm using Python 2.7, pyspark 1.5.2</p>
| 1 | 2016-08-12T19:38:44Z | 38,956,571 | <p>According to the research I've found, this is a bug in Spark that did not get resolved until Spark 2.0.0. I would love if someone who is using Spark 2.0.0 or higher could confirm this bug is fixed, but until then, here is the Apache Jira ticket discussing the issue:</p>
<p><a href="https://issues.apache.org/jira/browse/SPARK-11319" rel="nofollow">https://issues.apache.org/jira/browse/SPARK-11319</a></p>
| 0 | 2016-08-15T14:02:14Z | [
"python",
"pyspark",
"nullable"
] |
Remove double quotes in table name during SQLAlchemy code execution (Teradata) | 38,925,364 | <p>I'm trying to write a basic ORM SQLAlchemy class to access a Teradata table. However, when SQLAlchemy creates and executes the SQL code, it puts my table name in double quotes, which prevents Teradata from recognizing the table as a valid table name (it's expecting the table name without quotes). Is there anyway to remove the quotes that SQLalchemy is executing with?</p>
<p>For example:</p>
<pre><code>class d_game_info(Base):
__tablename__ = 'dbo.d_game_info'
game_id = Column(Integer, primary_key = True)
game_name = Column()
Session = sessionmaker(bind=td_engine)
session = Session()
for instance in session.query(d_game_info).order_by(d_game_info.game_id):
print(instance.game_name)
</code></pre>
<p>Results in the error: </p>
<blockquote>
<p>"Object 'dbo.d_game_info' does not exist."</p>
</blockquote>
<p>because the code SQLAlchemy tries to execute is </p>
<pre><code>... FROM "dbo.d_game_info" ...
</code></pre>
<p>instead of </p>
<pre><code>... FROM dbo.d_game_info ...
</code></pre>
<p>So... is there a way to force it to execute code without the double quotes?</p>
<p>Thanks! </p>
| 0 | 2016-08-12T19:39:23Z | 38,925,589 | <p><code>dbo</code> is not part of the table's name; it's the schema name of the table. The way to specify the schema in SQLAlchemy is like this:</p>
<pre><code>class d_game_info(Base):
__table_args__ = {'schema' : 'dbo'}
</code></pre>
| 0 | 2016-08-12T19:55:49Z | [
"python",
"sql",
"sqlalchemy",
"teradata"
] |
Hubspot (Jinja): Adding variables to blog data for output in for loop | 38,925,456 | <p><em>Hubspot is built in jinja and provides a limited and customized jinja library for use by it's developers. no server side access is available and python does not work in it's templates</em> </p>
<p>Hello,</p>
<p>I am wondering if it is possible to add variables to the blog data.</p>
<p>Currently to build out a blog listing page you would set a for loop</p>
<pre><code>`{% for content in contents %}
{% endfor %}`
</code></pre>
<p>then you would call in variables that call in different parts of the blog posts</p>
<pre><code>{{ content.foo ))
</code></pre>
<p>These variables are for elements already and always included in a hubspot blog post such as</p>
<p>author
date
title
summary
absolute link
etc.</p>
<p>But is it possible to add to these variables. For instance, lets say I add an image module into the blog post template. Is there a way to access this on the listing page?</p>
<p>What I am actually trying to do is allow the option to show any list item in one or two columns based on the choice module I set up on the blog post template. If when creating a blog post you choose 1 column or 2 column, a class in the wrapper inside the loop on the listing page will change accordingly.</p>
<p>the issue I am having is that while the choice module value is available to the listing page template (when in a hubl template module on the blog template, not in the blog post template), and the choice drop down is on the blog editing template and the choice can be made and saved, The listing page only recognizes the default choice and not the choice chosen in the blog editor.</p>
<p>half way through writing this I decided to move the choice module to the blog page template from the main blog template and now the variable for the choices is unavailable to the listing page. Keeping the choice module in the main blog template outside of the blog page template makes the variable for the choice available but not individually by the blogs. Because the choices chosen on the blogs aren't saved per blog, only the default choice is available.</p>
<p>It would be great if there was a way to add it to the content variables so that you could do something like</p>
<pre><code>{{ content.widget_data.foo.value }}
</code></pre>
<p>within the contents loop, making the individual choices of the blog posts available.</p>
<p>any ideas?</p>
| 0 | 2016-08-12T19:46:10Z | 38,925,785 | <p>I answered my own question.</p>
<p>I used the developer info (I had to use a code beautifier and the in page search) but I found the choice widget within the data for each post.</p>
<p>I was expecting it to be something like</p>
<pre><code>{{ content.widget_data.foo.value }}
</code></pre>
<p>as this is how it works (minus content.) on a page, but it ended up being</p>
<pre><code>{{ content.widgets.foo.body.value }}
</code></pre>
<p>and it is now outputting the choices made per post.</p>
<p>In case this is helpful to anyone else, I would like to mention that the choices module is actually placed in the blog page template (not the main blog template or the listing template).</p>
<p>This can work for any module, custom or otherwise. You just have to find it in the data and target accordingly.</p>
<p>my data looks like:</p>
<pre><code>"contents": {
"objects": [{
"widgets": {
"columns": {
"css": {},
"child_css": {},
"name": "foo",
"type": "choice",
"label": "Choose Columns",
"smart_type": null,
"id": "columns",
"body": {
"value": "col-wrap-2"
}
}
},
</code></pre>
| 0 | 2016-08-12T20:11:30Z | [
"python",
"templates",
"jinja2",
"hubspot"
] |
Easy Way To Convert A List To A String, Still Formatted As A List | 38,925,519 | <p>This should be quite simple but I can't find a simple solution. Frankly this should be a one liner.</p>
<p>In Python 3, how can you convert a list, such as</p>
<pre><code>['hello','world']
</code></pre>
<p>to a string that is formatted exactly the same, like</p>
<pre><code>"['hello','world']"
</code></pre>
<p>I don't wish to split it into two words.</p>
<pre><code>// This is bad.
"hello world"
</code></pre>
<p>I want to keep the traditional list formatting. I initially thought you could just bind the list as a string like (str)list_name but apparently not. Is there not a simple function for this?</p>
<p>EDIT:</p>
<p>I found thanks to AChampion that it was a simple syntactical error. I was trying to bind a list to a string like this:</p>
<pre><code>//this is bad
(str)list_name
</code></pre>
<p>When I should have been writing it like this</p>
<pre><code>//this is good
str(list_name)
</code></pre>
<p>That gives me exactly what I was looking for. Thanks for the help and sorry I had to bring such a beginner question here. Still getting used to Python.</p>
| 0 | 2016-08-12T19:50:14Z | 38,925,555 | <p>Just simply say:</p>
<pre><code>lst = ['hello', 'world']
new_str = str(lst)
print(new_str) # prints out ["hello", "world"]
</code></pre>
<p>Python won't just convert the string to string format unless your explicitly tell it to. Like so:</p>
<pre><code>lst = ['hello', 'world']
str1 = str(''.join(lst))
print(str1)# prints 'helloworld'
</code></pre>
<p>Or if you want a function:</p>
<pre><code>def listToString(lst):
new_lst = str(lst)
return new_lst
</code></pre>
<p>Although the function is really more like a wrapper. I'd just convert the list using python bulitin <code>str()</code> straight up, rather then trying to put it in a wrapper function.</p>
| 1 | 2016-08-12T19:52:45Z | [
"python",
"string",
"list",
"data-type-conversion"
] |
Easy Way To Convert A List To A String, Still Formatted As A List | 38,925,519 | <p>This should be quite simple but I can't find a simple solution. Frankly this should be a one liner.</p>
<p>In Python 3, how can you convert a list, such as</p>
<pre><code>['hello','world']
</code></pre>
<p>to a string that is formatted exactly the same, like</p>
<pre><code>"['hello','world']"
</code></pre>
<p>I don't wish to split it into two words.</p>
<pre><code>// This is bad.
"hello world"
</code></pre>
<p>I want to keep the traditional list formatting. I initially thought you could just bind the list as a string like (str)list_name but apparently not. Is there not a simple function for this?</p>
<p>EDIT:</p>
<p>I found thanks to AChampion that it was a simple syntactical error. I was trying to bind a list to a string like this:</p>
<pre><code>//this is bad
(str)list_name
</code></pre>
<p>When I should have been writing it like this</p>
<pre><code>//this is good
str(list_name)
</code></pre>
<p>That gives me exactly what I was looking for. Thanks for the help and sorry I had to bring such a beginner question here. Still getting used to Python.</p>
| 0 | 2016-08-12T19:50:14Z | 38,925,708 | <p>Short answer is: You can't do exactly what you're asking.</p>
<p>You cannot take any list that you typed in Python and get a string with the exact same original formatting. Python is pretty lenient with spacing within lists, so you can construct lists as such:</p>
<ol>
<li><code>['hello', 'world']</code></li>
<li><code>['hello','world']</code></li>
<li><code>[ 'hello', 'world' ]</code></li>
<li><code>[ 'hello', 'world' ]</code></li>
</ol>
<p>When Python creates these lists as lists, it doesn't preserve information about how you wrote it. So, there's not a way to get that back.</p>
<p>If you just want a stringified list, you should probably use <a href="https://docs.python.org/3/library/json.html#json.dumps" rel="nofollow">json.dumps</a>.</p>
| 0 | 2016-08-12T20:05:13Z | [
"python",
"string",
"list",
"data-type-conversion"
] |
Easy Way To Convert A List To A String, Still Formatted As A List | 38,925,519 | <p>This should be quite simple but I can't find a simple solution. Frankly this should be a one liner.</p>
<p>In Python 3, how can you convert a list, such as</p>
<pre><code>['hello','world']
</code></pre>
<p>to a string that is formatted exactly the same, like</p>
<pre><code>"['hello','world']"
</code></pre>
<p>I don't wish to split it into two words.</p>
<pre><code>// This is bad.
"hello world"
</code></pre>
<p>I want to keep the traditional list formatting. I initially thought you could just bind the list as a string like (str)list_name but apparently not. Is there not a simple function for this?</p>
<p>EDIT:</p>
<p>I found thanks to AChampion that it was a simple syntactical error. I was trying to bind a list to a string like this:</p>
<pre><code>//this is bad
(str)list_name
</code></pre>
<p>When I should have been writing it like this</p>
<pre><code>//this is good
str(list_name)
</code></pre>
<p>That gives me exactly what I was looking for. Thanks for the help and sorry I had to bring such a beginner question here. Still getting used to Python.</p>
| 0 | 2016-08-12T19:50:14Z | 38,925,746 | <p>Both a lists <code>str()</code> and <code>repr()</code> forms are what you are asking for, assuming that the it is a list of simple strings.<br>
If you have a more complicated structure and wish to transfer (serialize) to string form and back to object form you may want to look into the <code>json</code> module:</p>
<pre><code>>>> import json
>>> json.dumps(['hello','world'])
'["hello", "world"]'
</code></pre>
| 1 | 2016-08-12T20:08:25Z | [
"python",
"string",
"list",
"data-type-conversion"
] |
how to choose status within all name in noSQL (MongoDB) | 38,925,537 | <p>I have this JSON type document</p>
<pre><code>{
"user": {
"honza": {
"email": "haha",
"telephone": "5454",
"status": "online"
},
"sara": {
"email": "sdfsdf",
"telephone": "656",
"status": "online"
},
"michal": {
"email": "sdfdsffdsfds",
"telephone": "45454",
"status": "offline"
}
}
}
</code></pre>
<p>I need to <strong>find names</strong>, which have <strong>online status</strong>. I'm totally begginer and couldn't find any example.</p>
| -1 | 2016-08-12T19:51:42Z | 38,926,284 | <p>You might consider using <strong>elemMatch</strong> in your query. </p>
<p><a href="https://docs.mongodb.com/manual/reference/operator/query/elemMatch/" rel="nofollow">https://docs.mongodb.com/manual/reference/operator/query/elemMatch/</a></p>
| 1 | 2016-08-12T20:51:46Z | [
"python",
"arrays",
"json",
"mongodb",
"nosql"
] |
Concat/merge xr.DataArray along an existing axis (Xarray | Python 3) | 38,925,559 | <p>Here is a toy example but I have 2 dataframes; (1) rows=samples, cols=attributes; and (2) rows=samples, cols=metadata-fields.</p>
<p>I want to <code>concat</code> or <code>merge</code> to create 3-dimensional <code>xr.DataArray</code>. I've done this multiple times but I can't figure out why it's not working in this case? I want to <code>concat</code> along the <code>patient_id</code> axis to have a 3D <code>xr.DataArray</code>.</p>
<p><strong>Why isn't <code>xr.concat</code> building the 3-dimensional <code>DataArray</code>? I think I'm incorrectly using the <code>dim</code> argument since it is supposed to <code>concat</code> along a new-axis but is there a way to do this along an existing axis?</strong> </p>
<p>I'm trying to use the method from <a href="http://stackoverflow.com/questions/36948476/create-dataarray-from-dict-of-2d-dataframes-arrays">Create DataArray from Dict of 2D DataFrames/Arrays</a> but it isn't working. I got <code>merge</code> to work but it puts it into a <code>DataSet</code> w/ 2 data variables</p>
<pre><code>np.random.seed(0)
patient_ids = ["patient_%d"%_ for _ in range(42)]
attr_ids = ["attr_%d"%_ for _ in range(481)]
meta_ids = ["meta_%d"%_ for _ in range(32)]
DA_A = xr.DataArray(pd.DataFrame(np.random.random((42,481)),
index=patient_ids,
columns=attr_ids),
dims=["patient_id","attribute"])
DA_B = xr.DataArray(pd.DataFrame(np.random.random((42,32)),
index=patient_ids,
columns=meta_ids),
dims=["patient_id","metadata"])
DA_A.coords
# Coordinates:
# * patient_id (patient_id) object 'patient_0' 'patient_1' 'patient_2' ...
# * attribute (attribute) object 'attr_0' 'attr_1' 'attr_2' 'attr_3' ...
DA_B.coords
# Coordinates:
# * patient_id (patient_id) object 'patient_0' 'patient_1' 'patient_2' ...
# * metadata (metadata) object 'meta_0' 'meta_1' 'meta_2' 'meta_3' ...
xr.concat([DA_A, DA_B], dim="patient_id")
# KeyError: 'attribute'
</code></pre>
| 1 | 2016-08-12T19:53:11Z | 38,949,242 | <p>You can't (yet) concatenate DataArrays with different dimensions. You need to broadcast them explicitly first, e.g.,</p>
<pre><code>In [38]: xr.concat(xr.broadcast(DA_A, DA_B), dim="patient_id")
Out[38]:
<xarray.DataArray (patient_id: 84, attribute: 481, metadata: 32)>
array([[[ 0.5488135 , 0.5488135 , 0.5488135 , ..., 0.5488135 ,
0.5488135 , 0.5488135 ],
...,
[ 0.79649197, 0.97094708, 0.95542135, ..., 0.37856775,
0.65855316, 0.37893685]]])
Coordinates:
* attribute (attribute) object 'attr_0' 'attr_1' 'attr_2' 'attr_3' ...
* metadata (metadata) object 'meta_0' 'meta_1' 'meta_2' 'meta_3' ...
* patient_id (patient_id) object 'patient_0' 'patient_1' 'patient_2' ...
</code></pre>
<p>But as jhamman mentions in the comment on your question, you might actually find it easier to work with a single <code>Dataset</code> object instead, with two different variables, e.g.,</p>
<pre><code>In [39]: xr.Dataset({'A': DA_A, 'B': DA_B})
Out[39]:
<xarray.Dataset>
Dimensions: (attribute: 481, metadata: 32, patient_id: 42)
Coordinates:
* patient_id (patient_id) object 'patient_0' 'patient_1' 'patient_2' ...
* attribute (attribute) object 'attr_0' 'attr_1' 'attr_2' 'attr_3' ...
* metadata (metadata) object 'meta_0' 'meta_1' 'meta_2' 'meta_3' ...
Data variables:
A (patient_id, attribute) float64 0.5488 0.7152 0.6028 0.5449 ...
B (patient_id, metadata) float64 0.2438 0.8216 0.9237 0.3999 ...
</code></pre>
| 1 | 2016-08-15T04:14:02Z | [
"python",
"pandas",
"python-xarray"
] |
Python chrs not showing properly | 38,925,560 | <p>When i have a string that has something like <code>"Hi \\x00"</code> and when i try and use something like</p>
<pre><code>thatstring = thatstring.replace("\\x00",chr(0))
</code></pre>
<p>and then save it to a file</p>
<pre><code>f = open("test.txt","r+")
f.seek(0)
f.write(thatstring)
f.truncate()
f.close()
</code></pre>
<p>and in the file it will come out as "Hi \NULL" (NULL is representing the chr)</p>
<p>I think the problem is that i am writing to the file in r+ mode instead of br+ so it will put a \ before the chr but i cant use br+ because it has to write to the file with a "byte like format" and my string would have to contain letters and "special chrs".</p>
<p>I am using python 3.x</p>
<p>How can i avoid this?</p>
| 1 | 2016-08-12T19:53:12Z | 38,925,718 | <p>Your text in the file is a <em>literal</em> <code>\\x00</code>, so <strong>two</strong> backslashes. Your code then only replaces <strong>one</strong> of those backslashes:</p>
<pre><code>>>> filecontents = r'Hi \\x00' # raw string literal to disable escape sequences
>>> list(filecontents.partition(' ')[-1]) # only the part after the space
['\\', '\\', 'x', '0', '0']
>>> filecontents.replace("\\x00", chr(0))
'Hi \\\x00'
>>> list(_.partition(' ')[-1]) # last result, everything after the space
['\\', '\x00']
</code></pre>
<p>File contents are not subject to Python's string literal escape expansions, so there is no need to escape the escape here.</p>
<p>Either replace <em>both</em> backslashes or only use one backslash in your file. Replacing both is easiest done with another raw string literal:</p>
<pre><code>thatstring = thatstring.replace(r"\\x00", chr(0))
</code></pre>
| 2 | 2016-08-12T20:05:53Z | [
"python",
"python-3.x"
] |
How to read specific fields from binary file using numpy? | 38,925,587 | <p>I have a binary file that I am reading containing an array of a data type: </p>
<pre><code>dt_particles = np.dtype([('id', np.int64), \
('x', np.float32), \
('y', np.float32), \
('z', np.float32), \
('vx', np.float32), \
('vy', np.float32), \
('vz', np.float32)])
</code></pre>
<p>I can read the entire array of <code>dt_particles</code> elements using: </p>
<pre><code>numpy.rec.fromfile(FILE_OBJ, dtype=dt_particles, shape=NUM_ELEMENTS)
</code></pre>
<p>How do I read only <code>id</code> field from the binary file and skip other fields?</p>
| 0 | 2016-08-12T19:55:48Z | 38,925,894 | <p>I haven't used <code>fromfile</code> much, but I doubt if it is possible to read selected fields. Clearly it is using the <code>dtype</code> to determine the layout and spacing of the elements. There's no parameter like <code>usecols</code> in <code>genfromtxt</code> to read selected fields or columns. And no way to say, read 8 bytes, and skip the next 6*4 bytes.</p>
<p>Just read the whole thing and select the desired field. It's got to read the whole file anyways.</p>
| 0 | 2016-08-12T20:19:42Z | [
"python",
"numpy",
"file-io"
] |
Is it possible to run the asyncio.Server instance while the event loop is already running | 38,925,616 | <p>I'm trying to understand, is it possible to run the <code>asyncio.Server</code> instance while the event loop is already running by <code>run_forever</code> method (from a separate thread, of course).
As I understand, the server can be started either by <code>loop.run_until_complete(asyncio.start_server(...))</code> or by
<code>await asyncio.start_server(...)</code>, if the loop is already running.
The first way is not acceptable for me, since the loop is already running by run_forever method. But I also can't use the await expression, since I'm going to start it from outside the "loop area" (e.g. from the main method, which can't be marked as async, right?)</p>
<pre><code>def loop_thread(loop):
asyncio.set_event_loop(loop)
try:
loop.run_forever()
finally:
loop.close()
print("loop clesed")
class SchedulerTestManager:
def __init__(self):
...
self.loop = asyncio.get_event_loop()
self.servers_loop_thread = threading.Thread(
target=loop_thread, args=(self.loop, ))
...
def start_test(self):
self.servers_loop_thread.start()
return self.servers_loop_thread
def add_router(self, router):
r = self.endpoint.add_router(router)
host = router.ConnectionParameters.Host
port = router.ConnectionParameters.Port
srv = TcpServer(host, port)
server_coro = asyncio.start_server(
self.handle_connection, self.host, self.port)
# does not work since add_router is not async
# self.server = await server_coro
# does not work, since the loop is already running
# self.server = self.loop.run_until_complete(server_coro)
return r
def maind():
st_manager = SchedulerTestManager()
thread = st_manager.start_test()
router = st_manager.add_router(router)
</code></pre>
<p>Of cource, the simplest solution is to add all routers (servers) before starting the test (running the loop). But I want try to implement it, so it would be possible to add a router when a test is already running. I thought the <code>loop.call_soon</code> (<code>call_soon_threadsafe</code>) methods can help me, but it seems the can't shedule a coroutine, but just a simple function.</p>
<p>Hope that my explanation is not very confusing. Thanks in advance! </p>
| 2 | 2016-08-12T19:57:57Z | 38,939,903 | <p>For communicating between event loop executed in one thread and conventional old good threaded code executed in other thread you might use <a href="https://github.com/aio-libs/janus" rel="nofollow">janus</a> library.</p>
<p>It's a queue with two interfaces: async and thread-safe sync one.</p>
<p>This is usage example:</p>
<pre><code>import asyncio
import janus
loop = asyncio.get_event_loop()
queue = janus.Queue(loop=loop)
def threaded(sync_q):
for i in range(100):
sync_q.put(i)
sync_q.join()
@asyncio.coroutine
def async_coro(async_q):
for i in range(100):
val = yield from async_q.get()
assert val == i
async_q.task_done()
fut = loop.run_in_executor(None, threaded, queue.sync_q)
loop.run_until_complete(async_coro(queue.async_q))
loop.run_until_complete(fut)
</code></pre>
<p>You may create a task waiting new messages from the queue in a loop and starting new servers on request. Other thread may push new message into the queue asking for a new server.</p>
| 1 | 2016-08-14T06:54:22Z | [
"python",
"python-asyncio"
] |
command error after start project in django | 38,925,638 | <p>After upgrading my django from 1.8 to 1.10, when i start a project(django-admin startproject lwc) there is an error:</p>
<p><code>CommandError: C:\Python34\binesh\lwc\lwc\settings.py already exists,</code> overlaying
a project or app into an existing directory won't replace conflicting files.
it creates a file for lwc, <code>manage.py</code> and another lwc folder in it, and settings.py in second lwc folder.</p>
<p>what is wrong with it?</p>
| 2 | 2016-08-12T19:59:37Z | 38,926,190 | <p>You might have Django installed twice. Running "pip uninstall django" twice, and then reinstalling new version again should help.</p>
| 0 | 2016-08-12T20:43:38Z | [
"python",
"django-upgrade"
] |
command error after start project in django | 38,925,638 | <p>After upgrading my django from 1.8 to 1.10, when i start a project(django-admin startproject lwc) there is an error:</p>
<p><code>CommandError: C:\Python34\binesh\lwc\lwc\settings.py already exists,</code> overlaying
a project or app into an existing directory won't replace conflicting files.
it creates a file for lwc, <code>manage.py</code> and another lwc folder in it, and settings.py in second lwc folder.</p>
<p>what is wrong with it?</p>
| 2 | 2016-08-12T19:59:37Z | 39,836,064 | <p>Uninstall django, delete your python/Lib/site-packages/django directory completely, then reinstall.</p>
<p>The installation of the new version, even though it claims to uninstall the old version, leaves old files hanging around, and they are quietly brought into the new version in various ways (e.g., manage.py can bring in syncdb if a sync.py is left over in the django directories).</p>
| 0 | 2016-10-03T16:18:54Z | [
"python",
"django-upgrade"
] |
flask-security roles_required with pluggable views | 38,925,644 | <p>I'm trying to require a role to access a view that I've defined as a MethodView. However, I can't seem to get the route to be named correctly.</p>
<p>If I simply require logging in with a decorator everything works:</p>
<pre><code>activities = Blueprint("activities", __name__, url_prefix="/activities")
class ActivitiesView(MethodView):
def get():
pass
def post():
pass
view = login_required(ActivitiesView.as_view("activities"))
activities.add_url_rule('/', view_func=view)
</code></pre>
<p>I get the desired route name, i.e. <code>activities.activities</code>:</p>
<pre><code>>>> current_app.url_map
Map([...
<Rule '/activities/' (HEAD, POST, OPTIONS, GET) -> activities.activities>,
...])
</code></pre>
<p>However, when I try to use <code>roles_required</code>, the name of the route is mangled and the <code>POST</code> method is no longer listed:</p>
<pre><code>view = roles_required("experimenter", ActivitiesView.as_view("activities"))
activities.add_url_rule('/', view_func=view)
>>> current_app.url_map
Map([...
<Rule '/activities/' (HEAD, OPTIONS, GET) -> activities.wrapper>,
...])
</code></pre>
<p>Switching the arguments to <code>add_url_rule</code> doesn't change anything. How can I use <code>roles_required</code> without messing up the route name?</p>
<p>Doing this fixes the route name, but not the missing POST method:</p>
<pre><code>view = roles_required("experimenter", endpoint="activities", ActivitiesView.as_view("activities"))
activities.add_url_rule('/', view_func=view)
</code></pre>
| 0 | 2016-08-12T19:59:49Z | 39,005,060 | <p>The solution is to call the decorator:</p>
<pre><code>view = roles_required("experimenter")(ActivitiesView.as_view("activities"))
activities.add_url_rule('/', view_func=view)
</code></pre>
<p>Alternatively:</p>
<pre><code>decorators = [roles_required("experimenter")]
</code></pre>
<p>Thanks to this article:</p>
<p><a href="http://scottlobdell.me/2015/04/decorators-arguments-python/" rel="nofollow">http://scottlobdell.me/2015/04/decorators-arguments-python/</a></p>
| 0 | 2016-08-17T19:45:03Z | [
"python",
"flask",
"flask-security"
] |
Nested for-loop the pythonic way to structure data? | 38,925,775 | <p>I have structured data in some sources and ultimately I would like to step through each source, by the same amount, but starting at different indexes, in order to re-structure the data. </p>
<p>I will go on to perform analysis on each item contained in each iterated slice of source. What is the python way to do this? A nested for loop?</p>
<pre><code>sources = ('source1', 'source2' 'source3')
for source in sources:
slices = ('[1::5]', '[2::5]''[3::5]')
for slice in slices:
iteratedSlice = source[slice]
</code></pre>
| 2 | 2016-08-12T20:11:00Z | 38,925,851 | <p>A nested for loop with <a href="https://docs.python.org/2/library/functions.html#slice" rel="nofollow"><code>slice</code></a> is a good starting point:</p>
<pre><code>sources = [source1, source2, source3]
slices = [slice(1,None,5), slice(2,None,5), slice(3,None,5)]
for source in sources:
for s in slices:
iteratedSlice = source[s]
</code></pre>
| 1 | 2016-08-12T20:16:14Z | [
"python",
"nested-loops"
] |
Nested for-loop the pythonic way to structure data? | 38,925,775 | <p>I have structured data in some sources and ultimately I would like to step through each source, by the same amount, but starting at different indexes, in order to re-structure the data. </p>
<p>I will go on to perform analysis on each item contained in each iterated slice of source. What is the python way to do this? A nested for loop?</p>
<pre><code>sources = ('source1', 'source2' 'source3')
for source in sources:
slices = ('[1::5]', '[2::5]''[3::5]')
for slice in slices:
iteratedSlice = source[slice]
</code></pre>
| 2 | 2016-08-12T20:11:00Z | 38,926,394 | <p>I'm sure there is a better way of doing what you need, but we're going to need give up more information. What are you going to do with your <em>iteratedSlice</em> variable? </p>
<pre><code>sources = ('source1', 'source2' 'source3')
for source in sources:
for n in range(1, 4):
iteratedSlice = source[n:5]
</code></pre>
| 0 | 2016-08-12T21:00:36Z | [
"python",
"nested-loops"
] |
Can't get stdout/stderr from (Python) subprocess.check_output() | 38,925,806 | <p>I'm trying to get the message from a <code>git add</code> command, to print to a log file later on.</p>
<pre><code>import subprocess
import os
filename = 'test.txt'
# Add changes
add_cmd = """git add "%s" """ % filename
os.system(add_cmd)
a = subprocess.check_output(add_cmd, shell=True, stderr=subprocess.STDOUT)
</code></pre>
<p>The <code>os.system()</code> call shows in screen:</p>
<pre><code>fatal: Not a git repository (or any of the parent directories): .git
</code></pre>
<p>which is correct, since this folder is not a <code>git</code> repo.</p>
<p>But the <code>subprocess.check_output()</code> call fails with:</p>
<pre><code> File "test.py", line 11, in <module>
a = subprocess.check_output(add_cmd, shell=True, stderr=subprocess.STDOUT)
File "/usr/lib/python2.7/subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command 'git add "test.txt" ' returned non-zero exit status 128
</code></pre>
<p>Why am I not able to catch the error message with <code>subprocess.check_output()</code>?</p>
| 0 | 2016-08-12T20:12:45Z | 38,925,818 | <p>From the documenation for <a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_output" rel="nofollow"><code>subprocess.check_output()</code></a>:</p>
<blockquote>
<p>If the return code was non-zero it raises a <code>CalledProcessError</code>. The <code>CalledProcessError</code> object will have the return code in the <code>returncode</code> attribute and any output in the <code>output</code> attribute.</p>
</blockquote>
<p><code>git add</code> returns a non-zero exit code when there is an error condition. Catch that exception, your output is there:</p>
<pre><code>try:
a = subprocess.check_output(add_cmd, shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as cpe:
print cpe.output
</code></pre>
<p>Demo:</p>
<pre><code>>>> import subprocess
>>> import os
>>> filename = 'test.txt'
>>> add_cmd = """git add "%s" """ % filename
>>> try:
... a = subprocess.check_output(add_cmd, shell=True, stderr=subprocess.STDOUT)
... except subprocess.CalledProcessError as cpe:
... print cpe.output
...
fatal: Not a git repository (or any of the parent directories): .git
>>> cpe.returncode
128
</code></pre>
<p>You probably don't need to use <code>shell=True</code>; pass in your arguments as a <em>list</em> instead and they'll be executed without an intermediary shell. This has the added advantage you don't need to worry about properly escaping <code>filename</code>:</p>
<pre><code>add_cmd = ['git', 'add', filename]
try:
a = subprocess.check_output(add_cmd, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as cpe:
print cpe.output
</code></pre>
| 3 | 2016-08-12T20:13:54Z | [
"python",
"git",
"subprocess",
"stdout",
"stderr"
] |
How do i declare more than one extra-index-url in pip.conf | 38,925,928 | <p>Where would I set this in pip.conf?</p>
<p>I want to add two(2) extra-index-urls in pip.conf, but I did not find a solution how to do this after some research in the docs.</p>
| 1 | 2016-08-12T20:22:39Z | 39,085,648 | <p>Although the example in <a href="https://pip.pypa.io/en/stable/user_guide/#config-file" rel="nofollow">the docs</a> is for <code>--find-links</code>, it says: </p>
<blockquote>
<p>Appending options like <code>--find-links</code> can be written on multiple lines:</p>
</blockquote>
<pre><code>[global]
find-links =
http://download.example.com
[install]
find-links =
http://mirror1.example.com
http://mirror2.example.com
</code></pre>
<p>So I believe you may be able to do the same for <code>extra-index-url</code>. While I am having issues with the indices I'm using to test, I can confirm that passing the argument twice at the command line has the same effect as separating the two indices on multiple lines like this example does.</p>
<p>edit: I can confirm that this does indeed work for <code>extra-index-url</code>.</p>
| 0 | 2016-08-22T17:43:56Z | [
"python",
"pip"
] |
How to add lines together from two different paragraphs? | 38,925,959 | <p>I'm trying to figure out how to input two different paragraphs with short lines (similar to how song lyrics are structured) and then combine them. One of them would have its first line first followed by the other paragraph's line under it, and so on.</p>
<p>Something like this:</p>
<p>Input 1:</p>
<pre class="lang-none prettyprint-override"><code>this is an example
line that is a run
on sentence
</code></pre>
<p>Input 2:</p>
<pre class="lang-none prettyprint-override"><code>i am another example
paragraph that is
very similar
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>this is an example
i am another example
line that is a run
paragraph that is
on sentence
very similar
</code></pre>
<p>I'm guessing it can be done with a for loop but I'm unsure how you would grab the lines and put them one after the other. Thanks for any help!</p>
| -4 | 2016-08-12T20:25:49Z | 38,926,054 | <p>How's this? </p>
<pre><code>input1 = """
this is an example
line that is a run
on sentence
"""
input2 = """
i am another example
paragraph that is
very similar
"""
input1_lines = input1.strip().splitlines()
input2_lines = input2.strip().splitlines()
for line1, line2 in zip(input1_lines, input2_lines):
print("{}\n{}".format(line1, line2))
</code></pre>
<p><strong>Output</strong></p>
<pre class="lang-none prettyprint-override"><code>this is an example
i am another example
line that is a run
paragraph that is
on sentence
very similar
</code></pre>
| 1 | 2016-08-12T20:32:27Z | [
"python",
"loops",
"for-loop",
"input"
] |
How to add lines together from two different paragraphs? | 38,925,959 | <p>I'm trying to figure out how to input two different paragraphs with short lines (similar to how song lyrics are structured) and then combine them. One of them would have its first line first followed by the other paragraph's line under it, and so on.</p>
<p>Something like this:</p>
<p>Input 1:</p>
<pre class="lang-none prettyprint-override"><code>this is an example
line that is a run
on sentence
</code></pre>
<p>Input 2:</p>
<pre class="lang-none prettyprint-override"><code>i am another example
paragraph that is
very similar
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>this is an example
i am another example
line that is a run
paragraph that is
on sentence
very similar
</code></pre>
<p>I'm guessing it can be done with a for loop but I'm unsure how you would grab the lines and put them one after the other. Thanks for any help!</p>
| -4 | 2016-08-12T20:25:49Z | 38,926,089 | <p>I know I'm late already, but here's another method:</p>
<pre><code>a = """ this is an example
line that is a run
on sentence"""
b = '''i am another example
paragraph that is
very similar'''
a_list = a.split("\n")
b_list = b.split("\n")
c = [[x, b_list[index]] for index, x in enumerate(a_list)]
c_string = "\n".join(x for i in c for x in i)
</code></pre>
<p>output is a string, like this:</p>
<p><code>' this is an example \ni am another example\n line that is a run\n paragraph that is\n on sentence\n very similar'</code></p>
<p>EDIT:
or you can do it in one line </p>
<pre><code>c = "\n".join(x for i in [[x, b.split("\n")[index]] for index, x in enumerate(a.split("\n"))] for x in i)
</code></pre>
| 1 | 2016-08-12T20:35:16Z | [
"python",
"loops",
"for-loop",
"input"
] |
How to add lines together from two different paragraphs? | 38,925,959 | <p>I'm trying to figure out how to input two different paragraphs with short lines (similar to how song lyrics are structured) and then combine them. One of them would have its first line first followed by the other paragraph's line under it, and so on.</p>
<p>Something like this:</p>
<p>Input 1:</p>
<pre class="lang-none prettyprint-override"><code>this is an example
line that is a run
on sentence
</code></pre>
<p>Input 2:</p>
<pre class="lang-none prettyprint-override"><code>i am another example
paragraph that is
very similar
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>this is an example
i am another example
line that is a run
paragraph that is
on sentence
very similar
</code></pre>
<p>I'm guessing it can be done with a for loop but I'm unsure how you would grab the lines and put them one after the other. Thanks for any help!</p>
| -4 | 2016-08-12T20:25:49Z | 38,926,242 | <p>The thing about izip is, what is the output of:</p>
<pre><code>input1 = """
this is an example
line that is a run
"""
input2 = """
i am another example
paragraph that is
on sentence
"""
input1_lines = input1.strip().splitlines()
input2_lines = input2.strip().splitlines()
for line1, line2 in zip(input1_lines, input2_lines):
print("{}\n{}".format(line1, line2))
</code></pre>
<p>So as an addition:</p>
<pre><code>input1 = [
'this is an example',
'line that is a run',
]
input2 = [
'i am another example',
'paragraph that is',
'on sentence',
]
output = ''
for i in range(3):
output += input1[i] + '\n' if len(input1) > i else '\n'
output += input2[i] + '\n' if len(input2) > i else '\n'
print(output)
</code></pre>
<p>You can check it at <a href="http://www.tutorialspoint.com/execute_python_online.php" rel="nofollow">http://www.tutorialspoint.com/execute_python_online.php</a></p>
| 1 | 2016-08-12T20:48:22Z | [
"python",
"loops",
"for-loop",
"input"
] |
How to add lines together from two different paragraphs? | 38,925,959 | <p>I'm trying to figure out how to input two different paragraphs with short lines (similar to how song lyrics are structured) and then combine them. One of them would have its first line first followed by the other paragraph's line under it, and so on.</p>
<p>Something like this:</p>
<p>Input 1:</p>
<pre class="lang-none prettyprint-override"><code>this is an example
line that is a run
on sentence
</code></pre>
<p>Input 2:</p>
<pre class="lang-none prettyprint-override"><code>i am another example
paragraph that is
very similar
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>this is an example
i am another example
line that is a run
paragraph that is
on sentence
very similar
</code></pre>
<p>I'm guessing it can be done with a for loop but I'm unsure how you would grab the lines and put them one after the other. Thanks for any help!</p>
| -4 | 2016-08-12T20:25:49Z | 38,926,272 | <p>You can use the string module functions. string.splitlines creates a list separated by newlines. The string.join function joins elements in a list by whatever characters come before the dot. For example:</p>
<pre><code>import string
lyric1 = """this is an example
line that is a run
on sentence"""
lyric2 = """i am another example
paragraph that is
very similar"""
def merge_lyrics(l1,l2):
l1 = l1.splitlines()
l2 = l2.splitlines()
lyrics = []
for i in range(len(l1)):
lyrics.append(l1[i])
lyrics.append(l2[i])
return("\n".join(lyrics))
mylyrics = merge_lyrics(lyric1,lyric2)
print mylyrics
</code></pre>
| 1 | 2016-08-12T20:50:32Z | [
"python",
"loops",
"for-loop",
"input"
] |
How to add lines together from two different paragraphs? | 38,925,959 | <p>I'm trying to figure out how to input two different paragraphs with short lines (similar to how song lyrics are structured) and then combine them. One of them would have its first line first followed by the other paragraph's line under it, and so on.</p>
<p>Something like this:</p>
<p>Input 1:</p>
<pre class="lang-none prettyprint-override"><code>this is an example
line that is a run
on sentence
</code></pre>
<p>Input 2:</p>
<pre class="lang-none prettyprint-override"><code>i am another example
paragraph that is
very similar
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>this is an example
i am another example
line that is a run
paragraph that is
on sentence
very similar
</code></pre>
<p>I'm guessing it can be done with a for loop but I'm unsure how you would grab the lines and put them one after the other. Thanks for any help!</p>
| -4 | 2016-08-12T20:25:49Z | 38,926,279 | <p>First, you need to enter data into program. You may use <code>input()</code> function to enter single line, if you need more you may create you own <code>inp()</code> function based on standard <code>input</code>. Like so:</p>
<pre><code> def inp():
res = []
line = input()
while line != '':
res.append(line)
line = input()
return res
</code></pre>
<p>Try to run it in console and enter several lines. Empty line is end of input:</p>
<pre><code>>>> d1=inp()
this is an example
line that is a run
on sentence
>>>
>>> print(d1)
['this is an example', 'line that is a run', 'on sentence']
</code></pre>
<p>The same for d2:</p>
<pre><code>>>> d2=inp()
i am another example
paragraph that is
very similar
>>> print(d2)
['i am another example', 'paragraph that is', 'very similar']
</code></pre>
<p>Next you have to mix them. It's easy to do using <code>zip</code> method to group elements into pairs and then <code>itertools.chain.from_iterable</code> to flatten a list of pairs. Like:</p>
<pre><code>>>> list(itertools.chain.from_iterable(zip(d1,d2)))
['this is an example', 'i am another example', 'line that is a run', 'paragraph that is', 'on sentence', 'very similar']
</code></pre>
<p>You may <code>join()</code> this array into one line with <code>'\n'</code> as a delimiter and <code>print</code> it:</p>
<pre><code>>>> print('\n'.join(itertools.chain.from_iterable(zip(d1,d2))))
this is an example
i am another example
line that is a run
paragraph that is
on sentence
very similar
</code></pre>
| 1 | 2016-08-12T20:51:17Z | [
"python",
"loops",
"for-loop",
"input"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.