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 |
|---|---|---|---|---|---|---|---|---|---|
Multiply number list by range of numbers
| 39,336,824
|
<p>I'm trying to write code for a modulus 11 but I'm failing to make it more python-like.</p>
<p>As of now I'm using a weight and increasing it, checking when it reaches a number and then set it to it's original value.</p>
<p>Let's say I have a list of numbers
<code>1..20</code> and I'd like to multiply them by <code>2,3,4,5,6,7,8,9,2,3,4,etc</code> so that each index would be multiplied by an increasing number.</p>
<p>1x2, 2x3, 3x4, 4x5, 5x6, 6x7, 7x8, 8x9, 9x2, 10x3, etc..</p>
<p>Is there an elegant way to do this?</p>
<p>Unelegant way:</p>
<pre><code>def mod11(list, max_weight=9):
sum = 0
weight = 2
for item in reversed(list):
sum += item * weight
weight += 1
if weight > max_weight:
weight = 2
mod = 11 - sum % 11
if mod > 9:
return 0
else:
return mod
</code></pre>
| 4
|
2016-09-05T19:46:51Z
| 39,336,875
|
<p>maybe oneliner : </p>
<pre><code>s = map(lambda x : x*(x+1),list(range(1,20)))
</code></pre>
<p>basically <strong>map</strong> is core function used to make same operation on every element of table. first parameter is function which will be applied to every element. And If You want to remember generate another values used to multiplication maybe try some <strong>generator</strong></p>
| 0
|
2016-09-05T19:51:25Z
|
[
"python"
] |
Multiply number list by range of numbers
| 39,336,824
|
<p>I'm trying to write code for a modulus 11 but I'm failing to make it more python-like.</p>
<p>As of now I'm using a weight and increasing it, checking when it reaches a number and then set it to it's original value.</p>
<p>Let's say I have a list of numbers
<code>1..20</code> and I'd like to multiply them by <code>2,3,4,5,6,7,8,9,2,3,4,etc</code> so that each index would be multiplied by an increasing number.</p>
<p>1x2, 2x3, 3x4, 4x5, 5x6, 6x7, 7x8, 8x9, 9x2, 10x3, etc..</p>
<p>Is there an elegant way to do this?</p>
<p>Unelegant way:</p>
<pre><code>def mod11(list, max_weight=9):
sum = 0
weight = 2
for item in reversed(list):
sum += item * weight
weight += 1
if weight > max_weight:
weight = 2
mod = 11 - sum % 11
if mod > 9:
return 0
else:
return mod
</code></pre>
| 4
|
2016-09-05T19:46:51Z
| 39,336,962
|
<p>Ok, I am not quite sure if I understand your question correctly, since you talk about modulus 11, but also seem to use numbers from 2 up to and including 9.</p>
<p>But let's first start with writing the 1..20 as a list, that would be possible as follows:</p>
<pre><code>list(range(1,21)) (This is if you want to include the 20)
</code></pre>
<p>Next, to turn some integer into a number between 2 and 9 you could do the following:</p>
<pre><code>x -> x % 8 + 2
</code></pre>
<p>Combining these two, you could make a list comprehension:</p>
<pre><code>[((x-1) % 8 + 2) * x for x in xrange(1,21)]
</code></pre>
<p>(the -1 is added to start the first number from 2 instead of from 3)</p>
| 1
|
2016-09-05T19:58:33Z
|
[
"python"
] |
Multiply number list by range of numbers
| 39,336,824
|
<p>I'm trying to write code for a modulus 11 but I'm failing to make it more python-like.</p>
<p>As of now I'm using a weight and increasing it, checking when it reaches a number and then set it to it's original value.</p>
<p>Let's say I have a list of numbers
<code>1..20</code> and I'd like to multiply them by <code>2,3,4,5,6,7,8,9,2,3,4,etc</code> so that each index would be multiplied by an increasing number.</p>
<p>1x2, 2x3, 3x4, 4x5, 5x6, 6x7, 7x8, 8x9, 9x2, 10x3, etc..</p>
<p>Is there an elegant way to do this?</p>
<p>Unelegant way:</p>
<pre><code>def mod11(list, max_weight=9):
sum = 0
weight = 2
for item in reversed(list):
sum += item * weight
weight += 1
if weight > max_weight:
weight = 2
mod = 11 - sum % 11
if mod > 9:
return 0
else:
return mod
</code></pre>
| 4
|
2016-09-05T19:46:51Z
| 39,336,991
|
<p>You don't have to worry about resetting the multiplier if you use <a href="https://docs.python.org/2/library/itertools.html#itertools.cycle" rel="nofollow"><code>itertools.cycle</code></a>:</p>
<pre><code>>>> itertools.cycle(range(2, 10))
2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5, ...
</code></pre>
<p>so you can simplify your function like below:</p>
<pre><code>from itertools import cycle
def mod11(lst, max_weight=9):
multipliers = cycle(range(2, max_weight + 1))
zipped = zip(lst, multipliers))
summed = sum(a * b for a, b in zipped)
mod = 11 - (summed % 11)
return (0 if mod > 9 else mod)
</code></pre>
| 1
|
2016-09-05T20:00:32Z
|
[
"python"
] |
Multiply number list by range of numbers
| 39,336,824
|
<p>I'm trying to write code for a modulus 11 but I'm failing to make it more python-like.</p>
<p>As of now I'm using a weight and increasing it, checking when it reaches a number and then set it to it's original value.</p>
<p>Let's say I have a list of numbers
<code>1..20</code> and I'd like to multiply them by <code>2,3,4,5,6,7,8,9,2,3,4,etc</code> so that each index would be multiplied by an increasing number.</p>
<p>1x2, 2x3, 3x4, 4x5, 5x6, 6x7, 7x8, 8x9, 9x2, 10x3, etc..</p>
<p>Is there an elegant way to do this?</p>
<p>Unelegant way:</p>
<pre><code>def mod11(list, max_weight=9):
sum = 0
weight = 2
for item in reversed(list):
sum += item * weight
weight += 1
if weight > max_weight:
weight = 2
mod = 11 - sum % 11
if mod > 9:
return 0
else:
return mod
</code></pre>
| 4
|
2016-09-05T19:46:51Z
| 39,337,007
|
<p>You can use the current index to determine the multiplier:</p>
<pre><code>>>> [(index % 8 + 2) * item for index, item in enumerate(range(1, 21))]
[2, 6, 12, 20, 30, 42, 56, 72, 18, 30, 44, 60, 78, 98, 120, 144, 34, 54, 76, 100]
#^ resets ^ resets ^
</code></pre>
<p>Or, you can <a href="https://docs.python.org/3/library/itertools.html#itertools.cycle" rel="nofollow">"cycle"</a> the sequence of multipliers and zip with the input sequence:</p>
<pre><code>>>> from itertools import cycle
>>> [x * y for x, y in zip(range(1, 21), cycle(range(2, 10)))]
[2, 6, 12, 20, 30, 42, 56, 72, 18, 30, 44, 60, 78, 98, 120, 144, 34, 54, 76, 100]
</code></pre>
| 2
|
2016-09-05T20:01:38Z
|
[
"python"
] |
Multiply number list by range of numbers
| 39,336,824
|
<p>I'm trying to write code for a modulus 11 but I'm failing to make it more python-like.</p>
<p>As of now I'm using a weight and increasing it, checking when it reaches a number and then set it to it's original value.</p>
<p>Let's say I have a list of numbers
<code>1..20</code> and I'd like to multiply them by <code>2,3,4,5,6,7,8,9,2,3,4,etc</code> so that each index would be multiplied by an increasing number.</p>
<p>1x2, 2x3, 3x4, 4x5, 5x6, 6x7, 7x8, 8x9, 9x2, 10x3, etc..</p>
<p>Is there an elegant way to do this?</p>
<p>Unelegant way:</p>
<pre><code>def mod11(list, max_weight=9):
sum = 0
weight = 2
for item in reversed(list):
sum += item * weight
weight += 1
if weight > max_weight:
weight = 2
mod = 11 - sum % 11
if mod > 9:
return 0
else:
return mod
</code></pre>
| 4
|
2016-09-05T19:46:51Z
| 39,337,134
|
<p>A lot of good answers here already, and in case you would like to use <code>numpy</code> (usually good for this sort of thing), here's an alternative:</p>
<pre><code>In [1]: import numpy as np
In [2]: a = np.arange(1, 21) # like range in numpy array
In [3]: a - 1 #Â calculation performs per element wise... so will a * n
Out[3]:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19])
In [4]: a * ((a - 1) % 8 + 2) # directly translate the calculation
Out[4]:
array([ 2, 6, 12, 20, 30, 42, 56, 72, 18, 30, 44, 60, 78,
98, 120, 144, 34, 54, 76, 100])
</code></pre>
| 1
|
2016-09-05T20:13:31Z
|
[
"python"
] |
Multiply number list by range of numbers
| 39,336,824
|
<p>I'm trying to write code for a modulus 11 but I'm failing to make it more python-like.</p>
<p>As of now I'm using a weight and increasing it, checking when it reaches a number and then set it to it's original value.</p>
<p>Let's say I have a list of numbers
<code>1..20</code> and I'd like to multiply them by <code>2,3,4,5,6,7,8,9,2,3,4,etc</code> so that each index would be multiplied by an increasing number.</p>
<p>1x2, 2x3, 3x4, 4x5, 5x6, 6x7, 7x8, 8x9, 9x2, 10x3, etc..</p>
<p>Is there an elegant way to do this?</p>
<p>Unelegant way:</p>
<pre><code>def mod11(list, max_weight=9):
sum = 0
weight = 2
for item in reversed(list):
sum += item * weight
weight += 1
if weight > max_weight:
weight = 2
mod = 11 - sum % 11
if mod > 9:
return 0
else:
return mod
</code></pre>
| 4
|
2016-09-05T19:46:51Z
| 39,337,222
|
<p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.starmap" rel="nofollow">starmap</a> and <a href="https://docs.python.org/2/library/itertools.html#itertools.cycle" rel="nofollow">cycle</a> from itertools.</p>
<p>First create a list of tuples to multiply together:</p>
<pre><code>>>> from itertools import starmap, cycle
>>> li=zip(range(1,21), cycle(range(2,10)))
>>> li
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 2), (10, 3), (11, 4), (12, 5), (13, 6), (14, 7), (15, 8), (16, 9), (17, 2), (18, 3), (19, 4), (20, 5)]
</code></pre>
<p>Then use <code>starmap</code> and <code>mul</code> (from operator) to multiply:</p>
<pre><code>>>> from operator import mul
>>> list(starmap(mul, li))
[2, 6, 12, 20, 30, 42, 56, 72, 18, 30, 44, 60, 78, 98, 120, 144, 34, 54, 76, 100]
</code></pre>
<p>If you wanted a straight comprehension, you can do:</p>
<pre><code>>>> [x*y for x, y in ((e+1, (e%8)+2) for e in range(20))]
[2, 6, 12, 20, 30, 42, 56, 72, 18, 30, 44, 60, 78, 98, 120, 144, 34, 54, 76, 100]
</code></pre>
| 1
|
2016-09-05T20:20:41Z
|
[
"python"
] |
how to serve local static files in development when hosted in S3
| 39,336,973
|
<p>I'm storing my static files in S3 according to this tutorial: <a href="https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/" rel="nofollow">https://www.caktusgroup.com/blog/2014/11/10/Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files/</a></p>
<p>I am developing a lot of javascript and want to serve my javascript files locally only when in my development environment. Otherwise I would have to keep uploading my js files every time I want to test.</p>
<p>My static files settings look like this currently:</p>
<pre><code>STATICFILES_LOCATION = 'static'
STATICFILES_STORAGE = 'my.custom_storage.StaticStorage'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)
</code></pre>
<p>I created a local_settings.py file with setttings that point locally:</p>
<pre><code>STATICFILES_LOCATION = '/local/myapp/common/static/'
STATICFILES_STORAGE = ''
STATIC_URL = '/static/'
STATIC_ROOT = "/local/myapp/common/static/"
</code></pre>
<p>No matter what I change here, my app looks for the js files at the S3 url: <a href="http://s3.amazonaws.com" rel="nofollow">http://s3.amazonaws.com</a>...</p>
<p><strong>How can I have my app look locally for static files when in development so I can rapidly test my js files?</strong></p>
| 0
|
2016-09-05T19:59:18Z
| 39,337,686
|
<p>I set the following in my local_settings.py:</p>
<pre><code>STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
</code></pre>
<p>Then it looks for all static assets at localhost.</p>
| 0
|
2016-09-05T21:03:53Z
|
[
"javascript",
"python",
"django",
"amazon-s3",
"django-staticfiles"
] |
Getting queue where task came from
| 39,336,983
|
<p>I have a Celery application with 2 queues in which tasks of a given class (say, MyTask) are consumed round-robin. Some instances of MyTask are routed to the first queue, while other instances go to the second one.</p>
<p>Sometimes, a task needs to instantiate another object of MyTask and invoke <code>apply_async</code> again. Plus, the new task MUST be routed to the same queue as the one that is invoking it.</p>
<p>Problem is, I couldn't find in Celery's docs a way to get the queue from which the first task was consumed. Is there a straightforward, clean way of doing this?</p>
| 1
|
2016-09-05T20:00:01Z
| 39,355,161
|
<p>See <code>delivery_info</code> on <a href="http://docs.celeryproject.org/en/latest/userguide/tasks.html#context" rel="nofollow">Task context</a>.</p>
| 1
|
2016-09-06T17:59:58Z
|
[
"python",
"celery"
] |
How to get the title of links in the html page using BeautifulSoup python?
| 39,336,994
|
<p>Consider the html :</p>
<pre><code><li><img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /><a href="pdffiles/Special Exam_Aug_2016.pdf" target="_blank"> Student Notice </a></li>
<li><img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /><a href="pdffiles/Sangam_University_Bus_Route_Chart_Aug16.pdf" style="font-size:14px" target="_blank">UPDATED BUS ROUTE </a></li>
<li><img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /><a href="pdffiles/Sangam_University_Faculty_Requirement_Aug2016.jpg" target="_blank">Application are invited </a></li>
</code></pre>
<p>I want to extract the following titles and save them in a <code>list</code>:</p>
<pre><code>Student Notice
UPDATED BUS ROUTE
Application are invited
</code></pre>
<p>How can I do it using <code>urllib2</code> and <code>BeautifulSoup</code>?</p>
| -1
|
2016-09-05T20:00:45Z
| 39,337,147
|
<p>Which python and BeautifulSoup do you use?
In case of python2x and BS v. 3:</p>
<pre><code>from BeautifulSoup import BeautifulSoup
text = """<li><img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /><a href="pdffiles/Special Exam_Aug_2016.pdf" target="_blank"> Student Notice </a></li>
<li><img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /><a href="pdffiles/Sangam_University_Bus_Route_Chart_Aug16.pdf" style="font-size:14px" target="_blank">UPDATED BUS ROUTE </a></li>
<li><img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /><a href="pdffiles/Sangam_University_Faculty_Requirement_Aug2016.jpg" target="_blank">Application are invited </a></li>"""
soup = BeautifulSoup(text)
for link in soup.findAll('a'):
print link.contents[0]
</code></pre>
<p>BS 4 a bit differs:</p>
<pre><code>soup = BeautifulSoup(text, 'html.parser')
for link in soup.find_all('a'):
print link.contents[0]
</code></pre>
| 0
|
2016-09-05T20:14:33Z
|
[
"python",
"web-scraping",
"beautifulsoup",
"urllib2"
] |
How to get the title of links in the html page using BeautifulSoup python?
| 39,336,994
|
<p>Consider the html :</p>
<pre><code><li><img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /><a href="pdffiles/Special Exam_Aug_2016.pdf" target="_blank"> Student Notice </a></li>
<li><img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /><a href="pdffiles/Sangam_University_Bus_Route_Chart_Aug16.pdf" style="font-size:14px" target="_blank">UPDATED BUS ROUTE </a></li>
<li><img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /><a href="pdffiles/Sangam_University_Faculty_Requirement_Aug2016.jpg" target="_blank">Application are invited </a></li>
</code></pre>
<p>I want to extract the following titles and save them in a <code>list</code>:</p>
<pre><code>Student Notice
UPDATED BUS ROUTE
Application are invited
</code></pre>
<p>How can I do it using <code>urllib2</code> and <code>BeautifulSoup</code>?</p>
| -1
|
2016-09-05T20:00:45Z
| 39,337,174
|
<p>You don't need <code>urllib</code> if you already have the html...urllib is used to make a request to a web server which then returns the html, you can simply do this when you have the html</p>
<pre><code>>>> from bs4 import BeautifulSoup
>>> a = """<li><img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /><a href="pdffiles/Special Exam_Aug_2016.pdf" target="_blank"> Student Notice </a></li>
... <li><img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /><a href="pdffiles/Sangam_University_Bus_Route_Chart_Aug16.pdf" style="font-size:14px" target="_blank">UPDATED BUS ROUTE </a></li>
... <li><img alt="SangamUniversity-animated" class="newimg" src="images/new_animated.gif" /><a href="pdffiles/Sangam_University_Faculty_Requirement_Aug2016.jpg" target="_blank">Application are invited </a></li>"""
>>> b = BeautifulSoup(a, 'html.parser')
>>> c = b.find_all('li')
>>> for elem in c:
... print(elem.a.string)
...
Student Notice
UPDATED BUS ROUTE
Application are invited
</code></pre>
| 0
|
2016-09-05T20:17:13Z
|
[
"python",
"web-scraping",
"beautifulsoup",
"urllib2"
] |
ElementTree Remove Element
| 39,337,042
|
<p>Python noob here. Wondering what's the cleanest and best way to <strong>remove</strong> all the "<code>profile</code>" tags with <code>updated</code> attribute value of <code>true</code>. </p>
<p>I have tried the following code but it's throwing: <strong>SyntaxError("cannot use absolute path on element")</strong></p>
<pre><code> root.remove(root.findall("//Profile[@updated='true']"))
</code></pre>
<p>XML:</p>
<pre><code><parent>
<child type="First">
<profile updated="true">
<other> </other>
</profile>
</child>
<child type="Second">
<profile updated="true">
<other> </other>
</profile>
</child>
<child type="Third">
<profile>
<other> </other>
</profile>
</child>
</parent>
</code></pre>
| 1
|
2016-09-05T20:05:27Z
| 39,337,426
|
<p>If you are using <code>xml.etree.ElementTree</code>, you should use <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.remove" rel="nofollow"><code>remove()</code></a> method to remove a node, but this requires you to have the parent node reference. Hence, the solution:</p>
<pre><code>import xml.etree.ElementTree as ET
data = """
<parent>
<child type="First">
<profile updated="true">
<other> </other>
</profile>
</child>
<child type="Second">
<profile updated="true">
<other> </other>
</profile>
</child>
<child type="Third">
<profile>
<other> </other>
</profile>
</child>
</parent>"""
root = ET.fromstring(data)
for child in root.findall("child"):
for profile in child.findall(".//profile[@updated='true']"):
child.remove(profile)
print(ET.tostring(root))
</code></pre>
<p>Prints:</p>
<pre><code><parent>
<child type="First">
</child>
<child type="Second">
</child>
<child type="Third">
<profile>
<other> </other>
</profile>
</child>
</parent>
</code></pre>
<hr>
<p>Note that with <code>lxml.etree</code> this would be a bit simpler:</p>
<pre><code>root = ET.fromstring(data)
for profile in root.xpath(".//child/profile[@updated='true']"):
profile.getparent().remove(profile)
</code></pre>
<p>where <code>ET</code> is:</p>
<pre><code>import lxml.etree as ET
</code></pre>
| 0
|
2016-09-05T20:39:16Z
|
[
"python",
"xml",
"python-2.7",
"scripting",
"elementtree"
] |
Adding Acces-Control-Allow-Origin to app.yml
| 39,337,067
|
<p>I'm following these instructions from Google App Engine docs :</p>
<p><a href="https://cloud.google.com/appengine/docs/python/config/appref" rel="nofollow">https://cloud.google.com/appengine/docs/python/config/appref</a></p>
<p>If you search for CORS, you'll see the example I am trying to copy. </p>
<p>My app.yaml file looks like:</p>
<pre><code>runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: main.app
http_headers: Access-Control-Allow-Origin: *
libraries:
- name: ssl
version: latest
</code></pre>
<p>However when I go to update it I get this error:</p>
<pre><code>appcfg.py: error: Error parsing ./app.yaml: Unable to assign value 'Access-Control-Allow-Origin' to attribute 'http_headers':
Value 'Access-Control-Allow-Origin' for http_headers is not of the expected type HttpHeadersDict
</code></pre>
<p>Why am I getting this error? What am I doing differently than the docs?</p>
| 1
|
2016-09-05T20:07:04Z
| 39,337,637
|
<p>Unfortunately that's not valid <a href="http://yaml.org/" rel="nofollow">yaml</a>.</p>
<p>You have an indentation problem. Also you have to quote the <code>*</code>. Should be:</p>
<pre><code>handlers:
- url: /.*
script: main.app
http_headers:
Access-Control-Allow-Origin: "*"
</code></pre>
| 4
|
2016-09-05T20:59:23Z
|
[
"python",
"google-app-engine",
"cors"
] |
Quickly filter elements in Python array by minimum and maximum values
| 39,337,082
|
<p>I have a somewhat large <code>numpy</code> array of floats (<code>large_array</code>, ~2e7 elements). I need to generate a new array, filtering out all elements beyond certain minimum and maximum values.</p>
<p>I can do this with a simple:</p>
<pre><code>import numpy as np
large_array = np.random.uniform(0., 10000., 20000000)
min_val, max_val = 500., 2700.
arr_f = []
for _ in large_array:
if min_val <= _ <= max_val:
arr_f.append(_)
</code></pre>
<p>but it takes a really long time.</p>
<p>How can I speed this up?</p>
| 3
|
2016-09-05T20:08:26Z
| 39,337,132
|
<p>try this:</p>
<pre><code>In [18]: large_array.shape
Out[18]: (20000000,)
In [26]: new = large_array[(large_array >= min_val) & (large_array <= max_val)]
In [27]: new
Out[27]: array([ 814.24315891, 1611.53346093, 624.31833231, ..., 1999.08383068, 2212.9825087 , 1786.08963269])
In [28]: new.shape
Out[28]: (4400475,)
</code></pre>
| 1
|
2016-09-05T20:13:13Z
|
[
"python",
"arrays",
"numpy"
] |
Convert a string to JSON
| 39,337,100
|
<p>I would like to convert this string to a JSON dict:</p>
<pre><code>{u'Processes': [[u'root', u'3606', u'0.0', u'0.2', u'76768', u'16664', u'?', u'Ss', u'20:40', u'0:01', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4088', u'0.0', u'0.2', u'88544', u'20156', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4090', u'0.0', u'0.2', u'88552', u'20140', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4097', u'0.0', u'0.2', u'88552', u'20112', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4110', u'0.0', u'0.2', u'88548', u'20160', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0']], u'Titles': [u'USER', u'PID', u'%CPU', u'%MEM', u'VSZ', u'RSS', u'TTY', u'STAT', u'START', u'TIME', u'COMMAND']}
</code></pre>
<p>So I used json.dumps and json.loads but the output was not a valid JSON.
I understand that JSON needs double quotes instead of simple quotes, but I don't think that the solution is to search and replace is the best way to resolve this problem.
Is there a more proper way to do it ?</p>
| 2
|
2016-09-05T20:09:55Z
| 39,337,138
|
<p>Use <a href="https://docs.python.org/3.5/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval</code></a> to convert string to valid Python object.</p>
<blockquote>
<p>Safely evaluate an expression node or a string containing a Python
literal or container display. The string or node provided may only
consist of the following Python literal structures: strings, bytes,
numbers, tuples, lists, dicts, sets, booleans, and None.</p>
</blockquote>
<pre><code>s = "{u'Processes': [[u'root', u'3606', u'0.0', u'0.2', u'76768', u'16664', u'?', u'Ss', u'20:40', u'0:01', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4088', u'0.0', u'0.2', u'88544', u'20156', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4090', u'0.0', u'0.2', u'88552', u'20140', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4097', u'0.0', u'0.2', u'88552', u'20112', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4110', u'0.0', u'0.2', u'88548', u'20160', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0']], u'Titles': [u'USER', u'PID', u'%CPU', u'%MEM', u'VSZ', u'RSS', u'TTY', u'STAT', u'START', u'TIME', u'COMMAND']}"
o = ast.literal_eval(s)
assert 'Processes' in o
</code></pre>
<p>Use <a href="https://docs.python.org/3.5/library/json.html#json.dumps" rel="nofollow"><code>json.dumps</code></a> to dump it to JSON string.</p>
<pre><code>import json
json.dumps(o)
# '{"Titles": ["USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND"], "Processes": [["root", "3606", "0.0", "0.2", "76768", "16664", "?", "Ss", "20:40", "0:01", "/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0"], ["root", "4088", "0.0", "0.2", "88544", "20156", "?", "S", "20:40", "0:00", "/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0"], ["root", "4090", "0.0", "0.2", "88552", "20140", "?", "S", "20:40", "0:00", "/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0"], ["root", "4097", "0.0", "0.2", "88552", "20112", "?", "S", "20:40", "0:00", "/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0"], ["root", "4110", "0.0", "0.2", "88548", "20160", "?", "S", "20:40", "0:00", "/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0"]]}'
</code></pre>
<p>Or use <code>json.dump</code> to dump it to file object, if that's what you want.</p>
| 2
|
2016-09-05T20:14:09Z
|
[
"python",
"json"
] |
Convert a string to JSON
| 39,337,100
|
<p>I would like to convert this string to a JSON dict:</p>
<pre><code>{u'Processes': [[u'root', u'3606', u'0.0', u'0.2', u'76768', u'16664', u'?', u'Ss', u'20:40', u'0:01', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4088', u'0.0', u'0.2', u'88544', u'20156', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4090', u'0.0', u'0.2', u'88552', u'20140', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4097', u'0.0', u'0.2', u'88552', u'20112', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4110', u'0.0', u'0.2', u'88548', u'20160', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0']], u'Titles': [u'USER', u'PID', u'%CPU', u'%MEM', u'VSZ', u'RSS', u'TTY', u'STAT', u'START', u'TIME', u'COMMAND']}
</code></pre>
<p>So I used json.dumps and json.loads but the output was not a valid JSON.
I understand that JSON needs double quotes instead of simple quotes, but I don't think that the solution is to search and replace is the best way to resolve this problem.
Is there a more proper way to do it ?</p>
| 2
|
2016-09-05T20:09:55Z
| 39,337,257
|
<p>Try this,</p>
<pre><code>import json
data = {u'Processes': [[u'root', u'3606', u'0.0', u'0.2', u'76768', u'16664', u'?', u'Ss', u'20:40', u'0:01', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4088', u'0.0', u'0.2', u'88544', u'20156', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4090', u'0.0', u'0.2', u'88552', u'20140', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4097', u'0.0', u'0.2', u'88552', u'20112', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0'], [u'root', u'4110', u'0.0', u'0.2', u'88548', u'20160', u'?', u'S', u'20:40', u'0:00', u'/usr/local/bin/python2 /usr/local/bin/gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0']], u'Titles': [u'USER', u'PID', u'%CPU', u'%MEM', u'VSZ', u'RSS', u'TTY', u'STAT', u'START', u'TIME', u'COMMAND']}
data = json.dumps(data) # dict to string
data = json.loads(data) # string to json
print data['Processes']
</code></pre>
| 0
|
2016-09-05T20:24:52Z
|
[
"python",
"json"
] |
Testing if a pandas DataFrame exists
| 39,337,115
|
<p>In my code, I have several variables which can either contain a pandas DataFrame or nothing at all. Let's say I want to test and see if a certain DataFrame has been created yet or not. My first thought would be to test for it like this:</p>
<pre><code>if df1:
# do something
</code></pre>
<p>However, that code fails in this way:</p>
<pre><code>ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code></pre>
<p>Fair enough. Ideally, I would like to have a presence test that works for either a DataFrame or Python None. </p>
<p>Here is one way this can work:</p>
<pre><code>if not isinstance(df1, type(None)):
# do something
</code></pre>
<p>However, testing for type is really slow.</p>
<pre><code>t = timeit.Timer('if None: pass')
t.timeit()
# approximately 0.04
t = timeit.Timer('if isinstance(x, type(None)): pass', setup='x=None')
t.timeit()
# approximately 0.4
</code></pre>
<p>Ouch. Along with being slow, testing for NoneType isn't very flexible, either. </p>
<p>A different solution would be to initialize <code>df1</code> as an empty DataFrame, so that the type would be the same in both the null and non-null cases. I could then just test using <code>len()</code>, or <code>any()</code>, or something like that. Making an empty DataFrame seems kind of silly and wasteful, though.</p>
<p>Another solution would be to have an indicator variable: <code>df1_exists</code>, which is set to False until <code>df1</code> is created. Then, instead of testing <code>df1</code>, I would be testing <code>df1_exists</code>. But this doesn't seem all that elegant, either.</p>
<p>Is there a better, more Pythonic way of handling this issue? Am I missing something, or is this just an awkward side effect all the awesome things about pandas? </p>
| 3
|
2016-09-05T20:11:45Z
| 39,337,192
|
<blockquote>
<p>In my code, I have several variables which can either contain a pandas DataFrame or nothing at all</p>
</blockquote>
<p>They Pythonic way of indicating "nothing" is via <code>None</code>, and for checking "not nothing" via</p>
<pre><code>if df1 is not None:
...
</code></pre>
<p>I am not sure how critical time is here, but since you measured things:</p>
<pre><code>In [82]: t = timeit.Timer('if x is not None: pass', setup='x=None')
In [83]: t.timeit()
Out[83]: 0.022536039352416992
In [84]: t = timeit.Timer('if isinstance(x, type(None)): pass', setup='x=None')
In [85]: t.timeit()
Out[85]: 0.11571192741394043
</code></pre>
<p>So checking that something <code>is not None</code>, is also faster than the <code>isinstance</code> alternative.</p>
| 3
|
2016-09-05T20:18:03Z
|
[
"python",
"pandas"
] |
Testing if a pandas DataFrame exists
| 39,337,115
|
<p>In my code, I have several variables which can either contain a pandas DataFrame or nothing at all. Let's say I want to test and see if a certain DataFrame has been created yet or not. My first thought would be to test for it like this:</p>
<pre><code>if df1:
# do something
</code></pre>
<p>However, that code fails in this way:</p>
<pre><code>ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code></pre>
<p>Fair enough. Ideally, I would like to have a presence test that works for either a DataFrame or Python None. </p>
<p>Here is one way this can work:</p>
<pre><code>if not isinstance(df1, type(None)):
# do something
</code></pre>
<p>However, testing for type is really slow.</p>
<pre><code>t = timeit.Timer('if None: pass')
t.timeit()
# approximately 0.04
t = timeit.Timer('if isinstance(x, type(None)): pass', setup='x=None')
t.timeit()
# approximately 0.4
</code></pre>
<p>Ouch. Along with being slow, testing for NoneType isn't very flexible, either. </p>
<p>A different solution would be to initialize <code>df1</code> as an empty DataFrame, so that the type would be the same in both the null and non-null cases. I could then just test using <code>len()</code>, or <code>any()</code>, or something like that. Making an empty DataFrame seems kind of silly and wasteful, though.</p>
<p>Another solution would be to have an indicator variable: <code>df1_exists</code>, which is set to False until <code>df1</code> is created. Then, instead of testing <code>df1</code>, I would be testing <code>df1_exists</code>. But this doesn't seem all that elegant, either.</p>
<p>Is there a better, more Pythonic way of handling this issue? Am I missing something, or is this just an awkward side effect all the awesome things about pandas? </p>
| 3
|
2016-09-05T20:11:45Z
| 39,338,381
|
<p><strong><em>Option 1</em></strong> (my preferred option)</p>
<h3>This is @Ami Tavory's</h3>
<p><strong><em>Please select his answer if you like this approach</em></strong></p>
<p>It is very idiomatic python to initialize a variable with <code>None</code> then check for <code>None</code> prior to doing something with that variable.</p>
<pre><code>df1 = None
if df1 is not None:
print df1.head()
</code></pre>
<hr>
<p><strong><em>Option 2</em></strong></p>
<p>However, setting up an empty dataframe isn't at all a bad idea.</p>
<pre><code>df1 = pd.DataFrame()
if not df1.empty:
print df1.head()
</code></pre>
<hr>
<p><strong><em>Option 3</em></strong></p>
<p>Just try it.</p>
<pre><code>try:
print df1.head()
# catch when df1 is None
except AttributeError:
pass
# catch when it hasn't even been defined
except NameError:
pass
</code></pre>
<hr>
<h3>Timing</h3>
<p><strong><em>When <code>df1</code> is in initialized state or doesn't exist at all</em></strong></p>
<p><a href="http://i.stack.imgur.com/b1Dd6.png" rel="nofollow"><img src="http://i.stack.imgur.com/b1Dd6.png" alt="enter image description here"></a></p>
<p><strong><em>When <code>df1</code> is a dataframe with something in it</em></strong></p>
<pre><code>df1 = pd.DataFrame(np.arange(25).reshape(5, 5), list('ABCDE'), list('abcde'))
df1
</code></pre>
<p><a href="http://i.stack.imgur.com/iCAQK.png" rel="nofollow"><img src="http://i.stack.imgur.com/iCAQK.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/AgsSN.png" rel="nofollow"><img src="http://i.stack.imgur.com/AgsSN.png" alt="enter image description here"></a></p>
| 3
|
2016-09-05T22:30:55Z
|
[
"python",
"pandas"
] |
How do i get each byte into a list
| 39,337,208
|
<p>I want to open a MIDI file and analyse each byte. But i am VERY unfamiliar with handeling bytes and bits. Midi's are written in hexadecimal if that does any difference.</p>
<p>What i want to do is put each byte into a list, and then make a for loop to check each one. How would i go about doing that?</p>
<p>I've come this far (which isn't very far):</p>
<pre><code># Open MIDI file
mFile = open("test.mid", 'rb')
# Checks if file is MIDI
hChunk = mFile.read(4)
if hChunk != b'MThd':
raise ValueError('Not a MIDI file')
print(mFile.read())
</code></pre>
<p>Also if anyone has any easy to understand MIDI format explanation links, that would be appreciated! :)</p>
| 1
|
2016-09-05T20:19:23Z
| 39,337,451
|
<p>just completed your code to scan the first 40 bytes of data. It prints the decimal value as well as the hex value using both C-like <code>%</code> formatting and more pythonic <code>format</code> method, which may be more understandable if format specification is in hex.</p>
<p>midi file has been downloaded <a href="https://en.wikipedia.org/wiki/File:MIDI_sample.mid?qsrc=3044" rel="nofollow">here</a> and saved in the directory of the script (hence the strange <code>__file__</code> stuff to compute proper dir when testing)</p>
<pre><code>import os
# Open MIDI file
mFile = open(os.path.join(os.path.dirname(__file__),"MIDI_sample.mid"), 'rb')
# Checks if file is MIDI
hChunk = mFile.read(4)
if hChunk != b'MThd':
raise ValueError('Not a MIDI file')
contents = mFile.read()
mFile.close()
total_len = len(contents)
for i in range(0,40):
print(contents[i],"x%02X"% contents[i],"x{:02X}".format(contents[i]))
</code></pre>
| 1
|
2016-09-05T20:41:10Z
|
[
"python",
"list",
"python-3.x",
"byte",
"midi"
] |
How to access values of list inside list- Python
| 39,337,263
|
<p>I'm trying to make a game using pygame but I'm having problems with lists inside other lists.</p>
<p>inside the class of Enemy/Enemy 2 i have the following code:</p>
<pre><code>ei = [[Enemy(), Enemy()][Enemy2()]]
for wave in ei:
if self in wave:
print(ei.index(self))
</code></pre>
<p>The object is inside the list, I have checked by printing out <code>ei</code> in bulk, however this code just returns 'None'.</p>
<p>I tried to <code>print('True')</code> instead of the index, however it still prints <code>None</code></p>
| 0
|
2016-09-05T20:25:21Z
| 39,337,480
|
<p>I tried to codify your question:</p>
<pre><code>ei = [[Enemy(), Enemy()][Enemy2()]]
for wave in ei:
if self In wave:
print(ei.index(self))
</code></pre>
<p>What do you mean by <code>[[Enemy(), Enemy()][Enemy2()]]</code>?
You are trying to get the <code>Enemy2()</code>th element of <code>[Enemy(), Enemy()]</code> which is meaningless (<strong>Type Error</strong>).</p>
<p>You are also creating recursively <code>Enemy</code> / <code>Enemy2</code> objects (assuming this code is in <code>__init__</code>) (<strong>Maximum Recursive Depth Error</strong>), and checking if <code>self</code> is in the objects you have just created, when these elements are not even <code>Enemy</code> or <code>Enemy2</code> typed (<strong>another Type error</strong>).</p>
<p>And the <code>In</code> in line 3 <strong>must</strong> give you an error (<strong>Syntax Error</strong>). You can not run this code, so if you got <code>None</code> instead of detailed traceback, you should go get a new debugger.</p>
| 0
|
2016-09-05T20:44:19Z
|
[
"python",
"list",
"nested-lists"
] |
How to access values of list inside list- Python
| 39,337,263
|
<p>I'm trying to make a game using pygame but I'm having problems with lists inside other lists.</p>
<p>inside the class of Enemy/Enemy 2 i have the following code:</p>
<pre><code>ei = [[Enemy(), Enemy()][Enemy2()]]
for wave in ei:
if self in wave:
print(ei.index(self))
</code></pre>
<p>The object is inside the list, I have checked by printing out <code>ei</code> in bulk, however this code just returns 'None'.</p>
<p>I tried to <code>print('True')</code> instead of the index, however it still prints <code>None</code></p>
| 0
|
2016-09-05T20:25:21Z
| 39,344,148
|
<p>I am guessing, and there are several problems in your example. But maaaybe you want this:</p>
<pre><code>for index, wave in enumerate(ei):
if self in wave:
print(index)
</code></pre>
<p>See my comments or elaborate your question --as already recommended by other users, provide a MCVE and fix/explain the variables and classes.</p>
| 0
|
2016-09-06T08:28:22Z
|
[
"python",
"list",
"nested-lists"
] |
Python 3.5.1 Formatting Floats Issue
| 39,337,275
|
<p>I am trying to create a app that compares loans with various interest rates for a programming assignment. I generally understand what I am doing and could complete the assignment but am running into an issue with the .format function. I'm trying to format floats so that they can be printed as results. Here is my code: </p>
<pre><code># Prompts the user to enter a loan amount
loan_amount = eval(input("Enter loan amount in dollars (exclude commas):"))
# Prompts the user to enter a time period
length_years = eval(input("Enter the amount of years as an integer:"))
# Displays the header
print("{0:20s}{1:20s}{2:20s}".format("Interest Rate", "Monthly Payment",
"Total Payment"))
interest_rate = 5.0
while (interest_rate <= 8.0):
monthly_interest_rate = interest_rate / 12
monthly_payment = (monthly_interest_rate / 100) * loan_amount
total_payment = ((interest_rate / 100) * length_years) * loan_amount
print("{<20.6f}{<20.6f}{<20.6f}".format(interest_rate, monthly_payment, total_payment))
interest_rate = interest_rate +.25
</code></pre>
<p>And this is the error I receive: </p>
<pre><code>Enter loan amount in dollars (exclude commas):1000
Enter the amount of years as an integer:10
Traceback (most recent call last):
Interest Rate Monthly Payment Total Payment
File "/Users/Andrew/PycharmProjects/PA1/pa1_main.py", line 45, in <module>
main()
File "/Users/Andrew/PycharmProjects/PA1/pa1_main.py", line 42, in main
print("{<20.6f}{<20.6f}{<20.6f}".format(interest_rate, monthly_payment, total_payment))
KeyError: '<20'
Process finished with exit code 1
</code></pre>
| 1
|
2016-09-05T20:26:10Z
| 39,337,333
|
<p>You can omit the numbering (and it'll be auto-numbered for you), but you still need to use the <code>:</code> colon to separate the identifier from the formatting specification:</p>
<pre><code>print("{:<20.6f}{:<20.6f}{:<20.6f}".format(interest_rate, monthly_payment, total_payment))
</code></pre>
<p>Without the <code>:</code> separator, Python interprets the content before a <code>.</code> as a keyword argument to look up (and <code>.6f</code> as an attribute on the object).</p>
<p>As a side note: rather than use <code>eval()</code> (and open your script to abuse), I'd use <code>int()</code> (for whole numbers), and <code>float()</code> or <code>decimal.Decimal()</code> to convert input into the correct type:</p>
<pre><code>loan_amount = float(input("Enter loan amount in dollars (exclude commas):"))
length_years = int(input("Enter the amount of years as an integer:"))
</code></pre>
| 3
|
2016-09-05T20:31:46Z
|
[
"python",
"floating-point",
"python-3.5"
] |
tkinter won't update entry box with function
| 39,337,348
|
<p>Lately I've bean learning how to use the tkinter module in Python 3 to create a GUI. Unfortunately I've become stuck on an issue where my Entry widgets won't update. To understand the problem I wrote a short test case that populates an Entry widget with the string 'hello'.</p>
<pre><code>class SettingsWindow():
def __init__(self):
self.root = tk.Tk()
main_frame = ttk.Frame(self.root, padding=(15, 15, 15, 15))
main_frame.grid()
start_time = tk.StringVar()
start_time_ent = ttk.Entry(main_frame, textvariable=start_time, width=5)
start_time.set('hello')
start_time_ent.grid()
main_frame.mainloop()
if __name__ == '__main__':
app = SettingsWindow()
</code></pre>
<p>The issue arises when I attempt to organize my work in terms of methods:</p>
<pre><code>class SettingsWindow():
def __init__(self):
self.root = tk.Tk()
main_frame = ttk.Frame(self.root, padding=(15, 15, 15, 15))
main_frame.grid()
self.general_settings(main_frame, parent_column=1, parent_row=2)
main_frame.mainloop()
def general_settings(self, parent_frame, parent_column=0, parent_row=0):
start_time = tk.StringVar()
start_time_ent = ttk.Entry(parent_frame, textvariable=start_time, width=5)
start_time.set('hello')
start_time_ent.grid()
if __name__ == '__main__':
app = SettingsWindow()
</code></pre>
<p>When I run the second version of the code, the window loads with an empty Entry widget. My only guess on why this happens is <code>start_time.set('hello')</code> is stuck in some queue and I'm missing a command when compiling the window. Any suggestions?</p>
| 1
|
2016-09-05T20:33:01Z
| 39,337,468
|
<p>The ttk widgets are particularly sensitive to the garbage collector. Make <code>start_time</code> an instance variable rather than a local variable.</p>
| 0
|
2016-09-05T20:42:58Z
|
[
"python",
"python-3.x",
"user-interface",
"tkinter"
] |
Python implementation of Mergesort for Linked list doesn't work
| 39,337,414
|
<p>I couldn't find a simple implementation of <code>Merge Sort</code> in Python for <code>Linked Lists</code> anywhere. Here's what I tried:</p>
<h3>Definition for singly-linked list:</h3>
<pre><code>class ListNode:
def __init__(self, x):
self.val = x
self.next = None
</code></pre>
<h3>Merge Sort Implementation:</h3>
<pre><code>def mergeSortLinkedList(A):
# Base case length of 0 or 1:
if A == None or A.next == None:
return A
leftHalf, rightHalf = splitTheList(A)
mergeSortLinkedList(leftHalf)
mergeSortLinkedList(rightHalf)
# The above two lines should be modified to the following. Thanks to the answers.
# leftHalf = mergeSortLinkedList(leftHalf)
# rightHalf = mergeSortLinkedList(rightHalf)
return mergeTheLists(leftHalf, rightHalf)
</code></pre>
<p>Split:</p>
<pre><code>def splitTheList(sourceList):
if sourceList == None or sourceList.next == None:
leftHalf = sourceList
rightHalf = None
return leftHalf, rightHalf
else:
midPointer = sourceList
frontRunner = sourceList.next
# totalLength += 1 - This is unnecessary
while frontRunner != None:
frontRunner = frontRunner.next
if frontRunner != None:
frontRunner = frontRunner.next
midPointer = midPointer.next
leftHalf = sourceList
rightHalf = midPointer.next
midPointer.next = None
return leftHalf, rightHalf
</code></pre>
<p>Merge:</p>
<pre><code>def mergeTheLists(leftHalf, rightHalf):
fake_head = ListNode(None)
curr = fake_head
while leftHalf and rightHalf:
if leftHalf.val < rightHalf.val:
curr.next = leftHalf
leftHalf = leftHalf.next
else:
curr.next = rightHalf
rightHalf = rightHalf.next
curr = curr.next
if leftHalf == None:
curr.next = rightHalf
elif rightHalf == None:
curr.next = leftHalf
return fake_head.next
</code></pre>
<h3>Data:</h3>
<pre><code># Node A:
nodeA1 = ListNode(2)
nodeA2 = ListNode(1)
nodeA1.next = nodeA2
nodeA3 = ListNode(9)
nodeA2.next = nodeA3
nodeA4 = ListNode(3)
nodeA3.next = nodeA4
# Node C:
nodeC1 = ListNode(5)
nodeA4.next = nodeC1
nodeC2 = ListNode(6)
nodeC1.next = nodeC2
nodeC3 = ListNode(4)
nodeC2.next = nodeC3
nodeC4 = ListNode(5)
nodeC3.next = nodeC4
</code></pre>
<p>Expected output when <code>mergeSortLinkedList(nodeA1)</code> is called:</p>
<pre><code>1 2 3 4 5 5 6 9
</code></pre>
<p>I get the following instead:</p>
<pre><code>2 5 6 9
</code></pre>
<p>I am unable to figure out where the miss is. Please help.</p>
| 2
|
2016-09-05T20:38:17Z
| 39,338,528
|
<p>Try changing the lines in the mergeSort function to:</p>
<pre><code>leftHalf = mergeSortLinkedList(leftHalf)
rightHalf = mergeSortLinkedList(rightHalf)
</code></pre>
| 2
|
2016-09-05T22:51:04Z
|
[
"python",
"algorithm",
"sorting",
"linked-list",
"mergesort"
] |
Python implementation of Mergesort for Linked list doesn't work
| 39,337,414
|
<p>I couldn't find a simple implementation of <code>Merge Sort</code> in Python for <code>Linked Lists</code> anywhere. Here's what I tried:</p>
<h3>Definition for singly-linked list:</h3>
<pre><code>class ListNode:
def __init__(self, x):
self.val = x
self.next = None
</code></pre>
<h3>Merge Sort Implementation:</h3>
<pre><code>def mergeSortLinkedList(A):
# Base case length of 0 or 1:
if A == None or A.next == None:
return A
leftHalf, rightHalf = splitTheList(A)
mergeSortLinkedList(leftHalf)
mergeSortLinkedList(rightHalf)
# The above two lines should be modified to the following. Thanks to the answers.
# leftHalf = mergeSortLinkedList(leftHalf)
# rightHalf = mergeSortLinkedList(rightHalf)
return mergeTheLists(leftHalf, rightHalf)
</code></pre>
<p>Split:</p>
<pre><code>def splitTheList(sourceList):
if sourceList == None or sourceList.next == None:
leftHalf = sourceList
rightHalf = None
return leftHalf, rightHalf
else:
midPointer = sourceList
frontRunner = sourceList.next
# totalLength += 1 - This is unnecessary
while frontRunner != None:
frontRunner = frontRunner.next
if frontRunner != None:
frontRunner = frontRunner.next
midPointer = midPointer.next
leftHalf = sourceList
rightHalf = midPointer.next
midPointer.next = None
return leftHalf, rightHalf
</code></pre>
<p>Merge:</p>
<pre><code>def mergeTheLists(leftHalf, rightHalf):
fake_head = ListNode(None)
curr = fake_head
while leftHalf and rightHalf:
if leftHalf.val < rightHalf.val:
curr.next = leftHalf
leftHalf = leftHalf.next
else:
curr.next = rightHalf
rightHalf = rightHalf.next
curr = curr.next
if leftHalf == None:
curr.next = rightHalf
elif rightHalf == None:
curr.next = leftHalf
return fake_head.next
</code></pre>
<h3>Data:</h3>
<pre><code># Node A:
nodeA1 = ListNode(2)
nodeA2 = ListNode(1)
nodeA1.next = nodeA2
nodeA3 = ListNode(9)
nodeA2.next = nodeA3
nodeA4 = ListNode(3)
nodeA3.next = nodeA4
# Node C:
nodeC1 = ListNode(5)
nodeA4.next = nodeC1
nodeC2 = ListNode(6)
nodeC1.next = nodeC2
nodeC3 = ListNode(4)
nodeC2.next = nodeC3
nodeC4 = ListNode(5)
nodeC3.next = nodeC4
</code></pre>
<p>Expected output when <code>mergeSortLinkedList(nodeA1)</code> is called:</p>
<pre><code>1 2 3 4 5 5 6 9
</code></pre>
<p>I get the following instead:</p>
<pre><code>2 5 6 9
</code></pre>
<p>I am unable to figure out where the miss is. Please help.</p>
| 2
|
2016-09-05T20:38:17Z
| 39,339,667
|
<p>You don't use the return values from the recursive call. The code should be:</p>
<pre><code>def mergeSortLinkedList(A):
if A is None or A.next is None:
return A
leftHalf, rightHalf = splitTheList(A)
left = mergeSortLinkedList(leftHalf)
right = mergeSortLinkedList(rightHalf)
return mergeTheLists(left, right)
</code></pre>
<p>After the call of the function, the argument in some cases doesn't point to the head of the sorted list.</p>
<p>The next bug in the code is usage of undefined variable totalLength.</p>
| 1
|
2016-09-06T02:09:54Z
|
[
"python",
"algorithm",
"sorting",
"linked-list",
"mergesort"
] |
imports python3 in another folder
| 39,337,460
|
<p>When I run launch.py it fails and when I run main.py directly it works.
launch.py just imports and runs main.py. Why?</p>
<pre><code>âââ dir
â  âââ bla.py
â  âââ __init__.py
â  âââ main.py
âââ __init__.py
âââ launch.py
launch.py
---------
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from dir import main
main.main()
main.py
-------
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import bla
bla.pront()
bla.py
------
def pront():
print('pront')
</code></pre>
<p>EDITED:</p>
<p><a href="http://i.stack.imgur.com/cgfvU.png" rel="nofollow">enter image description here</a></p>
| 1
|
2016-09-05T20:41:58Z
| 39,337,533
|
<p>I believe I see the answer...
<br>
You have not defined main, perhaps try that. The reason why it works when called directly is because Python scripts are run in the order in which functions appear unless a specific function is called.</p>
<p>Try changing main.py to</p>
<pre><code>import bla
def mainfunction():
bla.pront()
</code></pre>
<p>Then change launch.py to</p>
<pre><code>import main
main.mainfunction()
</code></pre>
<p>I hope this helps! :)</p>
| -1
|
2016-09-05T20:47:34Z
|
[
"python",
"import",
"module",
"folder"
] |
imports python3 in another folder
| 39,337,460
|
<p>When I run launch.py it fails and when I run main.py directly it works.
launch.py just imports and runs main.py. Why?</p>
<pre><code>âââ dir
â  âââ bla.py
â  âââ __init__.py
â  âââ main.py
âââ __init__.py
âââ launch.py
launch.py
---------
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from dir import main
main.main()
main.py
-------
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import bla
bla.pront()
bla.py
------
def pront():
print('pront')
</code></pre>
<p>EDITED:</p>
<p><a href="http://i.stack.imgur.com/cgfvU.png" rel="nofollow">enter image description here</a></p>
| 1
|
2016-09-05T20:41:58Z
| 39,338,088
|
<p>Using your layout and with the following files, we don't have problems.</p>
<h3>launch.py</h3>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from dir import main
if __name__ == "__main__":
main. main()
</code></pre>
<h3>main.py</h3>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from . import bla
except:
import bla
def main():
bla.pront()
if __name__ == "__main__":
main()
</code></pre>
<p>The <code>try ... except</code> structure is used in case the <strong><em>main.py</em></strong> was used inside or outside the package.</p>
<p>Of course, there is a lot of info about it. You can start with <a href="http://stackoverflow.com/questions/16981921/relative-imports-in-python-3">this</a>.</p>
| 1
|
2016-09-05T21:50:32Z
|
[
"python",
"import",
"module",
"folder"
] |
Using ROS message classes outside of ROS
| 39,337,522
|
<p>I have a ROS node written in Python that captures messages and writes them to disk (e.g. using <code>pickle</code>). I want to use these files later, in another Python script, outside of ROS, but I need to import the message classes.</p>
<p>Is that possible?</p>
<p>Thanks!</p>
| 1
|
2016-09-05T20:46:54Z
| 39,611,619
|
<p>Unfortunately I don't think it's possible to just import the message files outside of any ROS dependencies. For example, if you look inside one of the generated message class files:</p>
<pre><code>---/your_catkin_ws/devel/lib/python2.7/dist-packages/your_package/msg/_Message.py
</code></pre>
<p>You will see that it depends <strong>at least</strong> on genpy and other message types contained in your message. Base messages are the same (in <code>/opt/ros/indigo/lib/python2.7/dist-packages/std_msgs/msg</code>).</p>
<p>While you could try to copy the minimum amount of dependencies until It Finally Works(!), it's a little un-elegant and probably going to be a brittle solution.</p>
<p>I believe the best solution is to convert your message to a generic non-ROS type, then store it in your pickle (so essentially what you've been doing already).</p>
| 1
|
2016-09-21T08:45:06Z
|
[
"python",
"ros"
] |
How to get 2 or more LinearRegionItem to overlap each other
| 39,337,545
|
<p>I have added 2 <code>LinearRegionItems</code> to a <code>pyqtgraph</code> plot. When I move the boundary of 1 over the other, the boundary never overlaps the other.</p>
<p>I would like to know how to allow overlapping. This is a functionality that I need, where I am selecting different regions of the data plot to be used later on.</p>
| 1
|
2016-09-05T20:48:26Z
| 39,413,892
|
<p>Sorry, there was a bug in my code which was handling the case where a part of one LinearRegionItem overlapped with another LinearRegionItem.</p>
<p>Now I see that one linearRegionItem can lie on top of another one.</p>
<p>Consider this solved</p>
| 0
|
2016-09-09T14:26:10Z
|
[
"python",
"pyqtgraph"
] |
How to implement simple Monte Carlo function in pymc
| 39,337,589
|
<p>I'm trying to get my head around how to implement a Monte Carlo function in python using pymc to replicate a spreadsheet by Douglas Hubbard in his book <a href="http://www.howtomeasureanything.com/wp-content/uploads/2015/03/HTMA_3rd_Ch6.xlsx" rel="nofollow">How to Measure Anything</a></p>
<p>My attempt was:</p>
<pre><code>import numpy as np
import pandas as pd
from pymc import DiscreteUniform, Exponential, deterministic, Poisson, Uniform, Normal, Stochastic, MCMC, Model
maintenance_saving_range = DiscreteUniform('maintenance_saving_range', lower=10, upper=21)
labour_saving_range = DiscreteUniform('labour_saving_range', lower=-2, upper=9)
raw_material_range = DiscreteUniform('maintenance_saving_range', lower=3, upper=10)
production_level_range = DiscreteUniform('maintenance_saving_range', lower=15000, upper=35000)
@deterministic(plot=False)
def rate(m = maintenance_saving_range, l = labour_saving_range, r=raw_material_range, p=production_level_range):
return (m + l + r) * p
model = Model([rate, maintenance_saving_range, labour_saving_range, raw_material_range, production_level_range])
mc = MCMC(model)
</code></pre>
<p>Unfortunately, I'm getting an error: <code>ValueError: A tallyable PyMC object called maintenance_saving_range already exists. This will cause problems for some database backends.</code></p>
<p>What have I got wrong?</p>
| 1
|
2016-09-05T20:53:07Z
| 39,347,046
|
<p>Ah, it was a copy and paste error. </p>
<p>I'd called three distributions by the same name.</p>
<p>Here's the code that works.</p>
<pre><code>import numpy as np
import pandas as pd
from pymc import DiscreteUniform, Exponential, deterministic, Poisson, Uniform, Normal, Stochastic, MCMC, Model
%matplotlib inline
import matplotlib.pyplot as plt
maintenance_saving_range = DiscreteUniform('maintenance_saving_range', lower=10, upper=21)
labour_saving_range = DiscreteUniform('labour_saving_range', lower=-2, upper=9)
raw_material_range = DiscreteUniform('raw_material_range', lower=3, upper=10)
production_level_range = DiscreteUniform('production_level_range', lower=15000, upper=35000)
@deterministic(plot=False, name="rate")
def rate(m = maintenance_saving_range, l = labour_saving_range, r=raw_material_range, p=production_level_range):
#out = np.empty(10000)
out = (m + l + r) * p
return out
model = Model([rate, maintenance_saving_range, labour_saving_range, raw_material_range])
mc = MCMC(model)
mc.sample(iter=10000)
</code></pre>
| 0
|
2016-09-06T10:42:10Z
|
[
"python",
"pymc"
] |
Python Error in Displaying Image
| 39,337,619
|
<p>On this Image</p>
<p><a href="http://i.stack.imgur.com/GLcQa.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/GLcQa.jpg" alt="enter image description here"></a></p>
<p>I am trying to apply:</p>
<pre><code>from PIL import Image
img0 = PIL.Image.open('Entertainment.jpg')
img0 = np.float32(img0)
showarray(img0/255.0)
</code></pre>
<p>And I get this error:</p>
<pre><code>TypeErrorTraceback (most recent call last)
<ipython-input-20-c181acf634a8> in <module>()
2 img0 = PIL.Image.open('Entertainment.jpg')
3 img0 = np.float32(img0)
----> 4 showarray(img0/255.0)
<ipython-input-8-b253b18ff9a7> in showarray(a, fmt)
11 f = BytesIO()
12 PIL.Image.fromarray(a).save(f, fmt)
---> 13 display(Image(data=f.getvalue()))
14
15 def visstd(a, s=0.1):
TypeError: 'module' object is not callable
</code></pre>
<p>I can't understand why. </p>
<p>What is not callable here?<br>
How can I just display the image? </p>
| 1
|
2016-09-05T20:56:56Z
| 39,337,768
|
<p><code>Image</code> is a module that you imported </p>
<pre><code>from PIL import Image
</code></pre>
<p>You can't call it </p>
<pre><code>Image(data=f.getvalue())
</code></pre>
<p>There's a show method that may be useful </p>
<pre><code>img0 = PIL.Image.open('Entertainment.jpg')
img0.show()
</code></pre>
| 0
|
2016-09-05T21:14:40Z
|
[
"python",
"image",
"python-imaging-library"
] |
embedding resources in python scripts
| 39,337,630
|
<p>I'd like to figure out how to embed binary content in a python script. For instance, I don't want to have any external files around (images, sound, ... ), I want all this content living inside of my python scripts.</p>
<p>Little example to clarify, let's say I got this small snippet:</p>
<pre><code>from StringIO import StringIO
from PIL import Image, ImageFilter
embedded_resource = StringIO(open("Lenna.png", "rb").read())
im = Image.open(embedded_resource)
im.show()
im_sharp = im.filter(ImageFilter.SHARPEN)
im_sharp.show()
</code></pre>
<p>As you can see, the example is reading the external file 'Lenna.png'</p>
<p><a href="http://i.stack.imgur.com/3p4GL.png" rel="nofollow"><img src="http://i.stack.imgur.com/3p4GL.png" alt="enter image description here"></a></p>
<p><strong>Question</strong></p>
<p>How to proceed to embed "Lenna.png" as a resource (variable) into my python script. What's the fastest way to achieve this simple task using python?</p>
| 1
|
2016-09-05T20:58:45Z
| 39,337,715
|
<p>The best way to go about this is converting your picture into a python string, and have it in a separate file called something like <code>resources.py</code>, then you simply parse it.</p>
<p>If you are looking to embed the whole thing inside a single binary, then you're looking at something like <a href="http://py2exe.org/" rel="nofollow">py2exe</a>. <a href="http://www.py2exe.org/index.cgi/data_files" rel="nofollow">Here</a> is an example embedding external files</p>
<p>In the first scenario, you could even use <code>base64</code> to (de)code the picture, something like this:</p>
<pre><code>import base64
file = open('yourImage.png');
encoded = base64.b64encode(file.read())
data = base64.b64decode(encoded) # Don't forget to file.close() !
</code></pre>
| 3
|
2016-09-05T21:08:16Z
|
[
"python",
"embedded-resource"
] |
embedding resources in python scripts
| 39,337,630
|
<p>I'd like to figure out how to embed binary content in a python script. For instance, I don't want to have any external files around (images, sound, ... ), I want all this content living inside of my python scripts.</p>
<p>Little example to clarify, let's say I got this small snippet:</p>
<pre><code>from StringIO import StringIO
from PIL import Image, ImageFilter
embedded_resource = StringIO(open("Lenna.png", "rb").read())
im = Image.open(embedded_resource)
im.show()
im_sharp = im.filter(ImageFilter.SHARPEN)
im_sharp.show()
</code></pre>
<p>As you can see, the example is reading the external file 'Lenna.png'</p>
<p><a href="http://i.stack.imgur.com/3p4GL.png" rel="nofollow"><img src="http://i.stack.imgur.com/3p4GL.png" alt="enter image description here"></a></p>
<p><strong>Question</strong></p>
<p>How to proceed to embed "Lenna.png" as a resource (variable) into my python script. What's the fastest way to achieve this simple task using python?</p>
| 1
|
2016-09-05T20:58:45Z
| 39,350,365
|
<p>You might find the following class rather useful for embedding resources in your program. To use it, call the <code>package</code> method with paths to the files that you want to embed. The class will print out a <code>DATA</code> attribute that should be used to replace the one already found in the class. If you want to add files to your pre-built data, use the <code>add</code> method instead. To use the class in your program, make calls to the <code>load</code> method using context manager syntax. The returned value is a <code>Path</code> object that can be used as a filename argument to other functions or for the purpose of directly loading the reconstituted file. See this <a href="http://pastebin.com/bRZuq72L" rel="nofollow">SMTP Client</a> for example usage.</p>
<pre><code>import base64
import contextlib
import pathlib
import pickle
import pickletools
import sys
import zlib
class Resource:
"""Manager for resources that would normally be held externally."""
WIDTH = 76
__CACHE = None
DATA = b''
@classmethod
def package(cls, *paths):
"""Creates a resource string to be copied into the class."""
cls.__generate_data(paths, {})
@classmethod
def add(cls, *paths):
"""Include paths in the pre-generated DATA block up above."""
cls.__preload()
cls.__generate_data(paths, cls.__CACHE.copy())
@classmethod
def __generate_data(cls, paths, buffer):
"""Load paths into buffer and output DATA code for the class."""
for path in map(pathlib.Path, paths):
if not path.is_file():
raise ValueError('{!r} is not a file'.format(path))
key = path.name
if key in buffer:
raise KeyError('{!r} has already been included'.format(key))
with path.open('rb') as file:
buffer[key] = file.read()
pickled = pickle.dumps(buffer, pickle.HIGHEST_PROTOCOL)
optimized = pickletools.optimize(pickled)
compressed = zlib.compress(optimized, zlib.Z_BEST_COMPRESSION)
encoded = base64.b85encode(compressed)
cls.__print(" DATA = b'''")
for offset in range(0, len(encoded), cls.WIDTH):
cls.__print("\\\n" + encoded[
slice(offset, offset + cls.WIDTH)].decode('ascii'))
cls.__print("'''")
@staticmethod
def __print(line):
"""Provides alternative printing interface for simplicity."""
sys.stdout.write(line)
sys.stdout.flush()
@classmethod
@contextlib.contextmanager
def load(cls, name, delete=True):
"""Dynamically loads resources and makes them usable while needed."""
cls.__preload()
if name not in cls.__CACHE:
raise KeyError('{!r} cannot be found'.format(name))
path = pathlib.Path(name)
with path.open('wb') as file:
file.write(cls.__CACHE[name])
yield path
if delete:
path.unlink()
@classmethod
def __preload(cls):
"""Warm up the cache if it does not exist in a ready state yet."""
if cls.__CACHE is None:
decoded = base64.b85decode(cls.DATA)
decompressed = zlib.decompress(decoded)
cls.__CACHE = pickle.loads(decompressed)
def __init__(self):
"""Creates an error explaining class was used improperly."""
raise NotImplementedError('class was not designed for instantiation')
</code></pre>
| 1
|
2016-09-06T13:34:10Z
|
[
"python",
"embedded-resource"
] |
Sorting function in Pandas, returns messy data
| 39,337,648
|
<p>I am trying to sort data in a CSV file using sort function in Pandas using the following code. I have 229 rows in original file. But the output of sorting is 245 rows, because some of the data in a field were printed in the next row and some of the rows do not have any value. </p>
<pre><code>sample=pd.read_csv("sample.csv" , encoding='latin-1', skipinitialspace=True)
sample_sorted = sample.sort_values(by = ['rating'])
sample_sorted.to_csv("sample_sorted.csv")
</code></pre>
<p>I think, this problem happened because in some cells data was entered by generating new lines. For example this is the content of a cell in original file. When I sort the original file, the second line was printed in a new row and 3 rows left empty between first and second line. </p>
<pre><code>"Side effects are way to extreme.
E-mail me if you have experianced the same things."
</code></pre>
<p>Any suggestion? Thanks !</p>
| 4
|
2016-09-05T21:00:44Z
| 39,338,666
|
<p>You could try to remove the newlines in your problem column.</p>
<pre><code>sample=pd.read_csv("sample.csv" , encoding='latin-1', skipinitialspace=True)
sample["problem_column"] = (sample["problem_column"].
apply(lambda x: " ".join([word for word in x.split()])
)
</code></pre>
<p>and see if that helps at all. It's difficult to see why that's happening without a reproducible sample. </p>
| 2
|
2016-09-05T23:12:49Z
|
[
"python",
"sorting",
"pandas"
] |
C function to Python (different results)
| 39,337,652
|
<p>I am trying to port this snippet of code to python from C. The outputs are different even though it's the same code.</p>
<p>This is the C version of the code which works:</p>
<pre><code>int main(void)
{
uint8_t pac[] = {0x033,0x55,0x22,0x65,0x76};
uint8_t len = 5;
uint8_t chan = 0x64;
btLeWhiten(pac, len, chan);
for(int i = 0;i<=len;i++)
{
printf("Whiten %02d \r\n",pac[i]);
}
while(1)
{
}
return 0;
}
void btLeWhiten(uint8_t* data, uint8_t len, uint8_t whitenCoeff)
{
uint8_t m;
while(len--){
for(m = 1; m; m <<= 1){
if(whitenCoeff & 0x80){
whitenCoeff ^= 0x11;
(*data) ^= m;
}
whitenCoeff <<= 1;
}
data++;
}
}
</code></pre>
<p>What I currently have in Python is:</p>
<pre><code>def whiten(data, len, whitenCoeff):
idx = len
while(idx > 0):
m = 0x01
for i in range(0,8):
if(whitenCoeff & 0x80):
whitenCoeff ^= 0x11
data[len - idx -1 ] ^= m
whitenCoeff <<= 1
m <<= 0x01
idx = idx - 1
pac = [0x33,0x55,0x22,0x65,0x76]
len = 5
chan = 0x64
def main():
whiten(pac,5,chan)
print pac
if __name__=="__main__":
main()
</code></pre>
<p>The problem i see is that whitenCoeff always remain 8 bits in the C snippet but it gets larger than 8 bits in Python on each loop pass.</p>
| 3
|
2016-09-05T21:01:11Z
| 39,337,731
|
<p>In C you are writing data from 0 to len-1 but in Python you are writing data from -1 to len-2. Remove the -1 from this line:</p>
<pre><code>data[len - idx -1 ] ^= m
</code></pre>
<p>like this</p>
<pre><code>data[len - idx] ^= m
</code></pre>
<p>you also need to put this line outside the if:</p>
<pre><code>whitenCoeff <<= 1
</code></pre>
| 1
|
2016-09-05T21:10:19Z
|
[
"python",
"bit-manipulation",
"lfsr"
] |
C function to Python (different results)
| 39,337,652
|
<p>I am trying to port this snippet of code to python from C. The outputs are different even though it's the same code.</p>
<p>This is the C version of the code which works:</p>
<pre><code>int main(void)
{
uint8_t pac[] = {0x033,0x55,0x22,0x65,0x76};
uint8_t len = 5;
uint8_t chan = 0x64;
btLeWhiten(pac, len, chan);
for(int i = 0;i<=len;i++)
{
printf("Whiten %02d \r\n",pac[i]);
}
while(1)
{
}
return 0;
}
void btLeWhiten(uint8_t* data, uint8_t len, uint8_t whitenCoeff)
{
uint8_t m;
while(len--){
for(m = 1; m; m <<= 1){
if(whitenCoeff & 0x80){
whitenCoeff ^= 0x11;
(*data) ^= m;
}
whitenCoeff <<= 1;
}
data++;
}
}
</code></pre>
<p>What I currently have in Python is:</p>
<pre><code>def whiten(data, len, whitenCoeff):
idx = len
while(idx > 0):
m = 0x01
for i in range(0,8):
if(whitenCoeff & 0x80):
whitenCoeff ^= 0x11
data[len - idx -1 ] ^= m
whitenCoeff <<= 1
m <<= 0x01
idx = idx - 1
pac = [0x33,0x55,0x22,0x65,0x76]
len = 5
chan = 0x64
def main():
whiten(pac,5,chan)
print pac
if __name__=="__main__":
main()
</code></pre>
<p>The problem i see is that whitenCoeff always remain 8 bits in the C snippet but it gets larger than 8 bits in Python on each loop pass.</p>
| 3
|
2016-09-05T21:01:11Z
| 39,337,750
|
<p><code>whitenCoeff <<= 1</code> in C becomes 0 after a while because it is a 8-bit data.</p>
<p>In python, there's no such limit, so you have to write:</p>
<pre><code>whitenCoeff = (whitenCoeff<<1) & 0xFF
</code></pre>
<p>to mask higher bits out.</p>
<p>(don't forget to check vz0 remark on array boundary)</p>
<p>plus there was an indentation issue.</p>
<p>rewritten code which gives same result:</p>
<pre><code>def whiten(data, whitenCoeff):
idx = len(data)
while(idx > 0):
m = 0x01
for i in range(0,8):
if(whitenCoeff & 0x80):
whitenCoeff ^= 0x11
data[-idx] ^= m
whitenCoeff = (whitenCoeff<<1) & 0xFF
m <<= 0x01
idx = idx - 1
pac = [0x33,0x55,0x22,0x65,0x76]
chan = 0x64
def main():
whiten(pac,chan)
print(pac)
if __name__=="__main__":
main()
</code></pre>
<p>Slightly off-topic: Note that the C version already has problems:</p>
<pre><code>for(int i = 0;i<=len;i++)
</code></pre>
<p>should be</p>
<pre><code>for(int i = 0;i<len;i++)
</code></pre>
| 1
|
2016-09-05T21:12:31Z
|
[
"python",
"bit-manipulation",
"lfsr"
] |
C function to Python (different results)
| 39,337,652
|
<p>I am trying to port this snippet of code to python from C. The outputs are different even though it's the same code.</p>
<p>This is the C version of the code which works:</p>
<pre><code>int main(void)
{
uint8_t pac[] = {0x033,0x55,0x22,0x65,0x76};
uint8_t len = 5;
uint8_t chan = 0x64;
btLeWhiten(pac, len, chan);
for(int i = 0;i<=len;i++)
{
printf("Whiten %02d \r\n",pac[i]);
}
while(1)
{
}
return 0;
}
void btLeWhiten(uint8_t* data, uint8_t len, uint8_t whitenCoeff)
{
uint8_t m;
while(len--){
for(m = 1; m; m <<= 1){
if(whitenCoeff & 0x80){
whitenCoeff ^= 0x11;
(*data) ^= m;
}
whitenCoeff <<= 1;
}
data++;
}
}
</code></pre>
<p>What I currently have in Python is:</p>
<pre><code>def whiten(data, len, whitenCoeff):
idx = len
while(idx > 0):
m = 0x01
for i in range(0,8):
if(whitenCoeff & 0x80):
whitenCoeff ^= 0x11
data[len - idx -1 ] ^= m
whitenCoeff <<= 1
m <<= 0x01
idx = idx - 1
pac = [0x33,0x55,0x22,0x65,0x76]
len = 5
chan = 0x64
def main():
whiten(pac,5,chan)
print pac
if __name__=="__main__":
main()
</code></pre>
<p>The problem i see is that whitenCoeff always remain 8 bits in the C snippet but it gets larger than 8 bits in Python on each loop pass.</p>
| 3
|
2016-09-05T21:01:11Z
| 39,337,824
|
<p>You've got a few more problems.</p>
<ol>
<li><code>whitenCoeff <<= 1;</code> is outside of the <code>if</code> block in your C code, but it's inside of the <code>if</code> block in your Python code.</li>
<li><code>data[len - idx -1 ] ^= m</code> wasn't translated correctly, it works backwards from the C code.</li>
</ol>
<p>This code produces the same output as your C code:</p>
<pre><code>def whiten(data, whitenCoeff):
for index in range(len(data)):
for i in range(8):
if (whitenCoeff & 0x80):
whitenCoeff ^= 0x11
data[index] ^= (1 << i)
whitenCoeff = (whitenCoeff << 1) & 0xff
return data
if __name__=="__main__":
print whiten([0x33,0x55,0x22,0x65,0x76], 0x64)
</code></pre>
| 1
|
2016-09-05T21:20:42Z
|
[
"python",
"bit-manipulation",
"lfsr"
] |
C function to Python (different results)
| 39,337,652
|
<p>I am trying to port this snippet of code to python from C. The outputs are different even though it's the same code.</p>
<p>This is the C version of the code which works:</p>
<pre><code>int main(void)
{
uint8_t pac[] = {0x033,0x55,0x22,0x65,0x76};
uint8_t len = 5;
uint8_t chan = 0x64;
btLeWhiten(pac, len, chan);
for(int i = 0;i<=len;i++)
{
printf("Whiten %02d \r\n",pac[i]);
}
while(1)
{
}
return 0;
}
void btLeWhiten(uint8_t* data, uint8_t len, uint8_t whitenCoeff)
{
uint8_t m;
while(len--){
for(m = 1; m; m <<= 1){
if(whitenCoeff & 0x80){
whitenCoeff ^= 0x11;
(*data) ^= m;
}
whitenCoeff <<= 1;
}
data++;
}
}
</code></pre>
<p>What I currently have in Python is:</p>
<pre><code>def whiten(data, len, whitenCoeff):
idx = len
while(idx > 0):
m = 0x01
for i in range(0,8):
if(whitenCoeff & 0x80):
whitenCoeff ^= 0x11
data[len - idx -1 ] ^= m
whitenCoeff <<= 1
m <<= 0x01
idx = idx - 1
pac = [0x33,0x55,0x22,0x65,0x76]
len = 5
chan = 0x64
def main():
whiten(pac,5,chan)
print pac
if __name__=="__main__":
main()
</code></pre>
<p>The problem i see is that whitenCoeff always remain 8 bits in the C snippet but it gets larger than 8 bits in Python on each loop pass.</p>
| 3
|
2016-09-05T21:01:11Z
| 39,370,028
|
<p>I solved it by anding the python code with 0xFF. That keeps the variable from increasing beyond 8 bits.</p>
| 0
|
2016-09-07T12:30:52Z
|
[
"python",
"bit-manipulation",
"lfsr"
] |
Tensorflow slim train and validate inception model
| 39,337,691
|
<p>I'm trying to fine tune inception models, and validate it with test data. But all the examples given at tensorflow slime web page only either fine-tuning or testing, there is not any example that doing both at same graph and session. </p>
<p>Basically I want to this. </p>
<pre><code>with tf.Graph().as_default():
image, image_raw, label,image_name, label_name = dut.distorted_inputs(params,is_training=is_training)
test_image, test_image_raw, test_label,test_image_name, test_label_name = dut.distorted_inputs(params,is_training=False)
# I'm creating as it is suggested at github slim page:
logits, _ =inception.inception_v2(image, num_classes=N, is_training=True)
tf.get_variable_scope().reuse_variables()
logits_tes, _ =inception.inception_v2(test_image, num_classes=N, is_training=Test)
err=tf.sub(logits, label)
losses = tf.reduce_mean(tf.reduce_sum(tf.square(err)))
# total_loss = model_loss+losses
total_loss = losses+slim.losses.get_total_loss()
test_err=tf.sub(test_logits, test_label)
test_loss= tf.reduce_mean(tf.reduce_sum(tf.square(test_err)))
optimizer = tf.train.AdamOptimizer(learning_rate=0.001)
train_op = slim.learning.create_train_op(total_loss, optimizer)
final_loss = slim.learning.train(
train_op,
logdir=params["cp_file"],
init_fn=ut.get_init_fn(slim,params),
number_of_steps=2,
summary_writer=summary_writer
)
</code></pre>
<p>this code fails As it can be seen, I don't have loop separately to call my test models, I want to test my model on my test data at each 10th batch.</p>
| 0
|
2016-09-05T21:04:18Z
| 39,358,463
|
<p>Does calling train with number_of_steps=10 and then using the evaluation code work?</p>
| -1
|
2016-09-06T21:58:45Z
|
[
"python",
"neural-network",
"tensorflow",
"deep-learning",
"conv-neural-network"
] |
What is the default value that Python chooses when adding two variables?
| 39,337,729
|
<p>Suppose we have the following context: </p>
<pre><code>x = 3
y = 4
z = x + y
</code></pre>
<p>Will <code>z</code> be an <code>int</code> or <code>float</code>, etc? I am well aware that floating numbers do end with <code>.something</code>, however its unclear to me whether Python will favour the floating point type over the integer type, given the circumstances that it is unpredictable whether the user is going to change this variable to another type or not.</p>
| 1
|
2016-09-05T21:10:12Z
| 39,337,755
|
<p>When <em>mixing</em> types, you'll always get the 'wider' type, where a complex number is wider than float, which in turn is wider than an integer. When both values are the same type (so <em>not</em> mixing types), you will just get that one type as the result.</p>
<p>From the <a href="https://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex" rel="nofollow"><em>Numeric Types</em> documentation</a>:</p>
<blockquote>
<p>Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the ânarrowerâ type is widened to that of the other, where plain integer is narrower than long integer is narrower than floating point is narrower than complex. Comparisons between numbers of mixed type use the same rule.</p>
</blockquote>
<p>So when you are summing numbers of different types, Python will widen the narrower type to be the same as the wider type. For an operation with an integer and a floating point number, you'll get a float, as float is wider.</p>
<p>However, there is no point in changing the type if both operands are the same type. Changing the type in that case would be very surprising.</p>
| 3
|
2016-09-05T21:13:11Z
|
[
"python",
"python-3.x",
"types"
] |
What is the default value that Python chooses when adding two variables?
| 39,337,729
|
<p>Suppose we have the following context: </p>
<pre><code>x = 3
y = 4
z = x + y
</code></pre>
<p>Will <code>z</code> be an <code>int</code> or <code>float</code>, etc? I am well aware that floating numbers do end with <code>.something</code>, however its unclear to me whether Python will favour the floating point type over the integer type, given the circumstances that it is unpredictable whether the user is going to change this variable to another type or not.</p>
| 1
|
2016-09-05T21:10:12Z
| 39,337,860
|
<p>For example:</p>
<pre><code>>>> type(3 + 4)
<class 'int'>
>>> type(3.0 + 4)
<class 'float'>
>>> type(3.0 + 4.0)
<class 'float'>
</code></pre>
<p>If the difference between a float or integer is important to your application, explicitly convert the user input into a float so you know what you are dealing with every time.</p>
<pre><code>user_input = float(input())
</code></pre>
| 1
|
2016-09-05T21:25:19Z
|
[
"python",
"python-3.x",
"types"
] |
What is the default value that Python chooses when adding two variables?
| 39,337,729
|
<p>Suppose we have the following context: </p>
<pre><code>x = 3
y = 4
z = x + y
</code></pre>
<p>Will <code>z</code> be an <code>int</code> or <code>float</code>, etc? I am well aware that floating numbers do end with <code>.something</code>, however its unclear to me whether Python will favour the floating point type over the integer type, given the circumstances that it is unpredictable whether the user is going to change this variable to another type or not.</p>
| 1
|
2016-09-05T21:10:12Z
| 39,338,116
|
<p>The <em>mixing</em> rules Martijn described are a good way to think about built in numeric types. More broadly, any object can support arithmetic operators such as <code>+</code> and <code>*</code> as long as the methods are implemented. With objects <code>a</code> and <code>b</code> when you apply an arithmetic operation like <code>a + b</code> python will call <code>a.__add__(b)</code>. If that function returns <code>NotImplemented</code> then python will fall back on <code>b.__radd__(a)</code>. Using this approach it is possible for only one of the two objects to know how to work with the other, and choose to act like the <em>wider</em> type.</p>
<p>For example the work for <code>4.0 + 3</code> is done by the float, and <code>3 + 4.0</code> is <em>also</em> computed by the float. To make your own numeric type that in some sense <em>wider</em> than a built in you all you need to do is implement your own <code>__add__</code> and <code>__radd</code>__ methods that returns your wider type. This relies on the builtins returning <code>NotImplemented</code> for an object they don't recognize.</p>
| 0
|
2016-09-05T21:54:09Z
|
[
"python",
"python-3.x",
"types"
] |
What is the default value that Python chooses when adding two variables?
| 39,337,729
|
<p>Suppose we have the following context: </p>
<pre><code>x = 3
y = 4
z = x + y
</code></pre>
<p>Will <code>z</code> be an <code>int</code> or <code>float</code>, etc? I am well aware that floating numbers do end with <code>.something</code>, however its unclear to me whether Python will favour the floating point type over the integer type, given the circumstances that it is unpredictable whether the user is going to change this variable to another type or not.</p>
| 1
|
2016-09-05T21:10:12Z
| 39,338,265
|
<p>This is easy to test. By default, if you perform arithmetic on two integers, Python will store the result as an integer. You can see that here.</p>
<pre><code>>>> x = 1
>>> y = 2
>>> z = x + y
>>> type(z)
<class 'int'>
</code></pre>
<p>The type function will tell you what the 'type' of an object is in Python. Here we can see that the type of the z variable is int, which stands for integer.</p>
<p>If we were to perform arithmetic on two different types, say integer and float, and the result was a decimal, then the result will be stored as a float.</p>
<pre><code>>>> x = 2.55
>>> y = 3
>>> z = x / 3
>>> type(z)
<class 'float'>
</code></pre>
<p>Now, if you were to perform arithmetic on an integer and a float and the result were to come out as a non-decimal, Python will STILL store this as a float. You can see that here.</p>
<pre><code>>>> x = 2.5
>>> y = 1.25
>>> z = x / y
>>> type(z)
<class 'float'>
>>> print(z)
2.0
</code></pre>
<p>In conclusion, when you do arithmetic, Python will store the result as an integer only if the two numbers involved were also integer. If one was float, then the new variable will also be of float type (or class).</p>
<p>Hope this helps :)</p>
| 1
|
2016-09-05T22:16:04Z
|
[
"python",
"python-3.x",
"types"
] |
Distance beetween lists in Python 3
| 39,337,736
|
<p>Python 3.4</p>
<p>I have many lists, like that:</p>
<pre><code>A=[(1,2),(3,4),..]
...
N=[(10,2),(3,4),...]
</code></pre>
<p>I want to merge the lists, if exist minimum distance (between their points) < 10.</p>
<p>measure is <code>sqrt((x1-x2)^2+(y1-y2)^2)</code></p>
<p>For example we have list with 3 matrix: </p>
<pre><code>L= [A, B, C]
A=[(1,2), (3,4)]
B=[(4,5), (100,1)]
C=[(1,2),(3,6)]
</code></pre>
<p>AFTER(we merger A and C because they are close): </p>
<pre><code>L=[[(1,2),(3,4),(1,2),(3,6)],[(4,5),(100,1)]]
</code></pre>
<p>But how?</p>
<p>Many thanks.</p>
| 0
|
2016-09-05T21:11:07Z
| 39,337,944
|
<p>I suggest you look at some form of <a href="https://en.wikipedia.org/wiki/Cluster_analysis" rel="nofollow">cluster analysis</a></p>
| 0
|
2016-09-05T21:34:42Z
|
[
"python",
"python-3.x"
] |
Why Python scope my variable outside my function?
| 39,337,756
|
<p>i start with Python. I like to try new language. So i've got a "simple" problem about scope and Python.</p>
<p>Here is a recursive function</p>
<pre><code>def foo(myarray)
if myarray == False:
myarray = [[0] * 5 for _ in range(5)]
myarray[0][0] = 1
"some code ..."
foo(myarray)
myarray = False
foo(myarray)
</code></pre>
<p>I don't want to share my var "myarray" in global env. I juste want Python scope "myarray" only in the function not outside. But Python shared "myarray" as it were a global var. How can restrict the scope to the function ?</p>
| -6
|
2016-09-05T21:13:26Z
| 39,337,818
|
<p>Disregarding the myriad of syntax errors, your <code>myarray</code> variable seems to be declared globally and that's why it has global scope?</p>
| 2
|
2016-09-05T21:20:04Z
|
[
"python",
"python-3.x"
] |
Python UDF for Pig in Azure Data Factory On demand HDInsight cluster
| 39,337,791
|
<p>How to include python UDF for pig when using Azure data factory and azure blob to store the pig script?</p>
| 0
|
2016-09-05T21:16:47Z
| 39,651,902
|
<p>@abu,</p>
<p>I recommend you can refer to the official document to konw how to use Pig and Python On Azure HDinsight.
<a href="https://azure.microsoft.com/en-in/documentation/articles/hdinsight-python/" rel="nofollow">https://azure.microsoft.com/en-in/documentation/articles/hdinsight-python/</a>
If you store your pig script into Azure storage, pleaes try to use <code>WASB:// path</code> to load your files.</p>
| 0
|
2016-09-23T03:02:17Z
|
[
"python",
"azure",
"apache-pig",
"hdinsight",
"azure-data-factory"
] |
Rabbitmq one queue multiple consumers
| 39,337,821
|
<p>I've multiple consumers which are polling on the same queue, and checking the queue every X seconds, basically after X seconds it could be that at least two consumers can launch <code>basic.get</code> at the very same time. </p>
<p>Question are:<br>
1.If at least two consumers at the same time can get the same message?</p>
<p>2.According to what I understood only <code>basic_ack</code> will delete a mesage from the queue, so suppose we have the following scenario: </p>
<p><code>Consumer1</code> takes msg with basic.get and before it reaches <code>basic_ack</code> line , <code>Consumer2</code> is getting this message also (<code>basic.get</code>), now <code>Consumer1</code> reaches the <code>basic.ack</code>, and only now <code>Consumer2</code> reaches its own <code>basic.ack</code>.<br>
What will happen When Consumer2 will reach its <code>basic.ack</code>?<br>
Will the message be processes by Consumer2 as well, because actions are not atomic?</p>
<p>My code logic of consumer using python pika is as follows:</p>
<p><code>while true:
m_frame =None
while(m_frame is None):<br>
self.connection.sleep(10)
m_frame,h_frame,body = self.channel.basic_get('test_queue')
self.channel.basic_ack(m_frame.delivery_tag)
[Doing some long logic - couple of minutes]
</code> </p>
<p><strong>Please note that I don't use basic.consume</strong> </p>
<p>So I don't know if round robin fetching is included for such usage</p>
| 1
|
2016-09-05T21:20:17Z
| 39,340,382
|
<blockquote>
<p>1.If at least two consumers at the same time can get the same message?</p>
</blockquote>
<p>no - a single message will only be delivered to a single consumer.</p>
<p>Because of that, your scenario #2 doesn't come into play at all. </p>
<p>You'll never have 2 consumers working on the same message, unless you <code>nack</code> the message back to the queue but continue processing it anyways.</p>
| 2
|
2016-09-06T03:51:29Z
|
[
"python",
"python-2.7",
"rabbitmq",
"pika"
] |
bytes casted to int by a list constructor
| 39,337,840
|
<p>I want to read <em>n</em> bytes a binary file and store each byte in a list. However, when I do so, each byte is casted into an <code>int</code>.</p>
<p>First I create a random file.</p>
<pre><code>$ head -c 16 > random.file
</code></pre>
<p>Then I try to read it:</p>
<pre class="lang-py prettyprint-override"><code>>>> with open('random.file', 'rb') as fp:
... l = list(fp.read(8))
... print(fp.read(8))
...
b'@\xc2\xdf\x9f\xbbv\xa1\x90'
>>> l
[79, 233, 19, 116, 252, 50, 248, 144]
>>> type(l[0])
<class 'int'>
</code></pre>
<p>So I understand that my byte value cannot go over <code>255</code> however the fact that Python is automatically casting is causing issues since don't get the expected type.</p>
<p>Is that normal? How can I avoid this?</p>
| 2
|
2016-09-05T21:22:46Z
| 39,338,141
|
<p>Any single byte you access in a list of bytes is just a single int value:</p>
<pre><code>>>> b"foo"[0]
102
</code></pre>
<p>If you want to create a new list that consists of lists of bytes with the length 1, you'll have to do that explicitly:</p>
<pre><code>>>> c = b"foo"
>>> l = []
>>> for i in range(0, len(c)):
... l.append(c[i:i+1])
>>> l
[b'f', b'o', b'o']
</code></pre>
<p>But I'm not really sure I see any reason for doing that, as accessing the single values, which is now embedded inside a new list, will just, again, return an int.</p>
| 1
|
2016-09-05T21:57:16Z
|
[
"python",
"types",
"casting"
] |
Python iterating from the middle of a cycle to before the start
| 39,337,849
|
<p>I've been working on programming a board game to practice python. I use a cycle to do turn order like this:</p>
<pre><code>turncycle = [0,1,2,3]
for turnindex in cycle(turncycle):
#.
#...turn stuff
#...turnindex is used for active player
#.
</code></pre>
<p>What I want to do is given a turn index start a mini turn where an event-card triggers and they have to something. Is there a way to rebuild the list so I can change [0,1,2,3] into [1,2,3,0] or cycle starting from 1,2, or 3 and then cycle through the rest once?</p>
| 0
|
2016-09-05T21:23:29Z
| 39,337,913
|
<p>What about something like this?</p>
<pre><code>def next_cycle(lst):
return turncycle[1:] + turncycle[:1]
turncycle = [0, 1, 2, 3]
for turnindex in range(len(turncycle)):
turncycle = next_cycle(turncycle)
print turncycle
</code></pre>
| 1
|
2016-09-05T21:31:22Z
|
[
"python",
"list",
"iteration",
"cycle"
] |
Python iterating from the middle of a cycle to before the start
| 39,337,849
|
<p>I've been working on programming a board game to practice python. I use a cycle to do turn order like this:</p>
<pre><code>turncycle = [0,1,2,3]
for turnindex in cycle(turncycle):
#.
#...turn stuff
#...turnindex is used for active player
#.
</code></pre>
<p>What I want to do is given a turn index start a mini turn where an event-card triggers and they have to something. Is there a way to rebuild the list so I can change [0,1,2,3] into [1,2,3,0] or cycle starting from 1,2, or 3 and then cycle through the rest once?</p>
| 0
|
2016-09-05T21:23:29Z
| 39,338,299
|
<p>Cobbled together something from the <a href="https://docs.python.org/2.7/library/itertools.html#recipes" rel="nofollow">itertools recipes</a></p>
<pre><code>import itertools
a = [0,1,2,3,4,5,6,7]
def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(itertools.islice(iterator, n, n), None)
def cycle(turncycle, start = 0):
# limit to the original number of turns
no_of_turns = len(turncycle)
# make a non-ending cycle
turncycle = itertools.cycle(turncycle)
# advance to the start position
consume(turncycle, start)
# return a new turn cycle - from the itertools take() recipe
return itertools.islice(turncycle, no_of_turns)
>>>
>>> for n in cycle(a):
print(n),
0 1 2 3 4 5 6 7
>>> for n in cycle(a, 4):
print(n),
4 5 6 7 0 1 2 3
>>> for n in cycle(a, 20):
print(n),
4 5 6 7 0 1 2 3
>>>
</code></pre>
<hr>
<p><code>cycle</code> may need to be tweaked a bit depending on what you think the <code>start</code> parameter means.</p>
<p>It could probably be renamed <code>roll()</code>.</p>
| 1
|
2016-09-05T22:20:06Z
|
[
"python",
"list",
"iteration",
"cycle"
] |
How to Detect an Empty Value
| 39,337,888
|
<p>I'm currently making a Python script for account creation. My script is as follows:</p>
<pre><code>import csv
nms = []
with open('nms.txt', newline='') as inputfile:
for row in csv.reader(inputfile):
nms.append(row)
counter = 0
## End of tings
while True:
print ("Please enter your user name. This must be unique.")
usernm = input ("")
while True:
if nms[1][counter] != (""):
print (".")
else:
break
if usernm == nms[1][counter]:
print ("Unfortunately this user name is in use. Please try a different user name.")
counter = counter + 1
print ("end")
</code></pre>
<p>The issue is that with the way I've made my script, where I've tried to stop the program checking if the username is equal to a blank value, it of course errors, is there a better method of detecting a null value? So that when it actually see's one, it will break out of the while loop? The rest of my program thus far seems to work fine.</p>
| 1
|
2016-09-05T21:28:27Z
| 39,337,936
|
<p>I'm not sure I see the need for the counter variable, but you can check if an item exists in an iterable object with <code>in</code></p>
<pre><code>if usernm in nms:
# user already exists
</code></pre>
<blockquote>
<p>I've tried to stop the program checking if the username is equal to a blank value</p>
</blockquote>
<p>It looks like you checked if the second value of <code>nms</code> at the character of the index <code>counter</code> is an empty string. You didn't check the username that was input at all. </p>
<pre><code>if usernm.trim() == "":
# username is blank
</code></pre>
| 0
|
2016-09-05T21:33:46Z
|
[
"python",
"input",
null,
"value"
] |
python copy files with time stamp
| 39,337,896
|
<p>I would like to copy file with date time stamp. the below code is not working on windows. I am new to python so please help me. </p>
<pre><code>import shutil
import datetime
shutil.copyfile('C:\\Users\\Documents\\error.log','C:\\Users\\Documents\datetime.now().strftime("%Y%m%d-%H%M%S").log')
</code></pre>
| 2
|
2016-09-05T21:29:39Z
| 39,337,988
|
<p>In your code, you have the code enclosed in the string. You need to run the code out of the string, and combine it with the string. A solution would be</p>
<pre><code>import shutil
import datetime
shutil.copyfile('C:\\Users\\Documents\\error.log','C:\\Users\\Documents\' + datetime.now().strftime("%Y%m%d-%H%M%S") + '.log')
</code></pre>
<p><strong>UPDATE</strong>
Forgot to add the second datetime to the statement</p>
<pre><code>import shutil
import datetime
shutil.copyfile('C:\\Users\\Documents\\error.log','C:\\Users\\Documents\' + datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + '.log')
</code></pre>
| 1
|
2016-09-05T21:39:26Z
|
[
"python",
"shutil",
"copyfile"
] |
Accessing <li> element with no class id using Beautiful soup
| 39,337,909
|
<p>I am trying to scrape the companies in the li in the ul table under final result. The source code looks like this</p>
<p>import string
import re
import urllib2
import datetime
import bs4
from bs4 import BeautifulSoup</p>
<p>class AJSpider(object):</p>
<pre><code>def __init__(self):
print ("initisizing")
self.date = str(datetime.date.today())
self.cur_url = "https://youinvest.moneyam.com/modules/forward-diary/?date={date}&period=month"
self.datas = []
print ("initisization done")
def get_page(self,cur_date):
url = self.cur_url
try:
my_page = urllib2.urlopen(url.format(date = cur_date)).read().decode("utf-8")
my_soup = BeautifulSoup(my_page, "html.parser")
except:
print ('Failed')
return my_soup
def get_final(self, soup_page):
temp_data = []
final_result_section = soup_page.find("h3", text="Final Result")
print final_result_section
def start_spider(self):
my_page = self.get_page(self.date)
self.get_final(my_page)
def main():
my_spider = AJSpider()
my_spider.start_spider()
if __name__ == '__main__':
main()
</code></pre>
<p>I found a similar quesiton in stackoverflow
<a href="http://stackoverflow.com/questions/17683475/beautiful-soup-accessing-li-elements-from-ul-with-no-id">Beautiful Soup: Accessing <li> elements from <ul> with no id</a> , but this one here does have a class id, which makes things a lot easier.</p>
<p>In my scenario, how may I extract the li element from the ul table please? the only identifier here is really the content of the h3 tag, which is Final Result, however it is not a id so I have no idea how to make use of it.</p>
<p>Many thanks!</p>
| 4
|
2016-09-05T21:30:48Z
| 39,337,929
|
<p>Find the <code>h3</code> element <em>by text</em> and get the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-next-siblings-and-find-next-sibling" rel="nofollow">following <code>ul</code> list</a>:</p>
<pre><code>ul = soup.find("h3", text="Final Result").find_next_sibling("ul")
for li in ul.find_all("li"):
print(li.span.get_text(), li.a.get_text())
</code></pre>
<hr>
<p>Note that in the recent versions of BeautifulSoup, <code>text</code> argument was renamed to <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-string-argument" rel="nofollow"><code>string</code></a>, but they both work because of the backwards compatibility.</p>
| 3
|
2016-09-05T21:33:07Z
|
[
"python",
"html",
"beautifulsoup",
"html-lists"
] |
Django. Customize action for model
| 39,338,058
|
<p>I need to edit the "Add Object" action in the admin. It needs to redirect the user to a custom cause the logic required for adding objects is too complex to be managed in the admin. So, how do I make this possible? i.e:</p>
<p><a href="http://i.stack.imgur.com/ChoP7.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/ChoP7.jpg" alt="enter image description here"></a></p>
<p>The picture shows a django-suit admin, but the question is the same. How can I make that button redirect to a custom url? Or, how can I create a similar button that redirects to a custom url (I could disable the default create and leave only the custom button).</p>
| 0
|
2016-09-05T21:47:27Z
| 39,338,221
|
<p>Override <code>change_list_template</code> html, the block <code>object-tools-items</code>. It's where add button is placed.</p>
<pre><code>class MyModelAdmin(admin.ModelAdmin):
change_list_template = 'change_list.html'
</code></pre>
<p>In your <code>change_list.html</code></p>
<pre><code>{% extends "admin/change_list.html" %}
{% load i18n admin_static admin_list %}
{% block object-tools-items %}
{% if has_add_permission %}
<li>
<a href="your/custom/url" class="addlink">
{% blocktrans with cl.opts.verbose_name as name %}Add {{ name }}{% endblocktrans %}
</a>
</li>
{% endif %}
{% endblock %}
</code></pre>
<p>You need to add your new html in any dir that is included on <code>TEMPLATE_DIRS</code> options. But, you should do it inside your model's app. </p>
<pre><code>-app
-templates
-admin
change_list.html
</code></pre>
<p>Add above dir in TEMPLATE DIRS paths.</p>
| 1
|
2016-09-05T22:10:24Z
|
[
"python",
"django",
"django-admin"
] |
How to reference Django application url in admin index template
| 39,338,080
|
<p>I'm currently making changes to the admin/index.html template and I need to reference the url in my application using the name space 'hello' in a href tag for a link, but I'm having trouble doing at the admin level. The name of my application is clean and the url pattern in urls.py file is below.</p>
<pre><code>urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^HelloWorld/$', views.hello, name='hello'),
]
</code></pre>
<p>I'm trying to avoid hard coding the below href tag in admin/index.html. Any suggestions would be a great help
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<h3>Hello World</h3>
<a href="http://127.0.0.1:8000/clean/HelloWorld">Test</a>
</div></code></pre>
</div>
</div>
</p>
| 0
|
2016-09-05T21:49:29Z
| 39,338,374
|
<p>You can simply use:</p>
<pre><code><div>
<h3>Hello World</h3>
<a href="{% url 'hello' %}">Test</a>
</div>
</code></pre>
<p>Django provides the ability to "reverse" URLs (i.e. provided the name of the URL, and arguments if necessary, the actual URL is generated) in order to avoid such hardcoding.You can read more about URL reversing in the official docs <a href="https://docs.djangoproject.com/en/1.10/topics/http/urls/#reverse-resolution-of-urls" rel="nofollow">here</a>.</p>
| 2
|
2016-09-05T22:29:44Z
|
[
"python",
"html",
"django"
] |
Kivy Checkbox restrict click
| 39,338,204
|
<p>I am trying to create a checkbox in my float layout area. I am getting the checkbox to generate but every time I click it goes from True to False even if it not on the box. Could someone provide some insight?</p>
<p>My code:</p>
<pre><code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.checkbox import CheckBox
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition
from kivy.uix.textinput import TextInput
from kivy.uix.widget import Widget
#######``Windows``#######
class MainScreen(Screen):
pass
class AnotherScreen(Screen):
def add(self, *args):
a = self.ids["a"].text
a = int(a)
self.ids["adds"]
plus = 1 + a
print plus
class ScreenManagement(ScreenManager):
pass
presentation = Builder.load_file("GUI_Style.kv")
class MainApp(App):
def build(self):
return presentation
if __name__ == "__main__":
MainApp().run()
</code></pre>
<p>My KV File:</p>
<pre><code>#: import NoTransition kivy.uix.screenmanager.NoTransition
ScreenManagement:
transition: NoTransition()
MainScreen:
AnotherScreen:
<MainScreen>:
background_color: 0.5, 1, 0.22, 1
name: "main"
FloatLayout:
Button:
text: "Quit"
font_size: 50
color: 0,1,0,1
font_size: 25
size_hint: 0.3,0.2
pos_hint: {"x":0, "y":0}
on_release: app.window().stop()
Button:
on_release: app.root.current = "other"
text: "Next Screen"
font_size: 50
color: 0,1,0,1
font_size: 25
size_hint: 0.3,0.2
pos_hint: {"right":1, "top":1}
<AnotherScreen>:
name: "other"
canvas.before:
Color:
rgba: 1, 1, 1, 1
Rectangle:
pos: self.pos
size: self.size
FloatLayout:
CheckBox:
pos_hint: {"x":0.2, "y":0.2}
on_release: True
TextInput:
id: a
font_size: 25
password: True
pos_hint: {"x":0.5, "y":0.5}
size_hint: 0.3,0.2
text: "Insert Side A here"
Button:
id: adds
background_color: 0,0,1,1
color: 0,1,0,1
font_size: 25
on_release: root.add()
pos_hint: {"x":0, "y":0}
size_hint: 0.3,0.2
text: "plus"
Button:
color: 0,1,0,1
background_color: 0,0,1,1
font_size: 25
size_hint: 0.3,0.2
text: "Back Home"
on_release: app.root.current = "main"
pos_hint: {"right":1, "top":1}
</code></pre>
| 0
|
2016-09-05T22:07:50Z
| 39,339,591
|
<p>Try placing the CheckBox in a Widget and it works. I mean:</p>
<pre><code>FloatLayout:
Widget:
CheckBox:
pos_hint: {"x":0.2, "y":0.2}
on_release: True
TextInput:
id: a
font_size: 25
password: True
pos_hint: {"x":0.5, "y":0.5}
size_hint: 0.3,0.2
text: "Insert Side A here"
Button:
id: adds
background_color: 0,0,1,1
color: 0,1,0,1
font_size: 25
on_release: root.add()
pos_hint: {"x":0, "y":0}
size_hint: 0.3,0.2
text: "plus"
</code></pre>
<p>of course it ruins your layout but it solves the problem you are having.</p>
| 0
|
2016-09-06T01:57:53Z
|
[
"python",
"python-2.7",
"checkbox",
"kivy",
"kivy-language"
] |
How can I print out the correct response based on input?
| 39,338,238
|
<p>I'm new to Python and I have a very simple problem that I'd like explained to me. I'm making a text adventure game and I'd like to be able to call another function inside a function so my code is organized better. </p>
<p>This is what I have that's working:</p>
<pre><code>def displayIntro():
print("You come to a crossroads on your trip home.")
print ("You can go LEFT towards the DEMON FOREST or RIGHT to SKULL MOUNTAIN")
print()
def choosePath():
path = ""
while path != "LEFT" and path != "RIGHT":
path = input("Which path will you choose? LEFT or RIGHT? --> ")
if path == "RIGHT":
print("You take the path to SKULL MOUNTAIN.")
elif path == "LEFT":
print ("You take the path to the DEMON FOREST.")
displayIntro()
choosePath()
choosenPath()
</code></pre>
<p>But I'd like it to look something like this, but I don't know how to make it work:</p>
<pre><code>def displayIntro():
print("You come to a crossroads on your trip home.")
print ("You can go LEFT towards the DEMON FOREST or RIGHT to SKULL MOUNTAIN")
print()
def choosePath():
path = ""
while path != "LEFT" and path != "RIGHT":
path = input("Which path will you choose? LEFT or RIGHT? --> ")
return path
def checkPath(choosePath):
if choosePath == "RIGHT":
print("You take the path to SKULL MOUNTAIN.")
elif choosePath == "LEFT":
print("You take the path to the DEMON FOREST.")
displayIntro()
choosePath()
checkPath()
</code></pre>
| -1
|
2016-09-05T22:12:09Z
| 39,338,254
|
<p>You're not passing the return value of <code>choosePath()</code> to <code>checkPath()</code>. It should be:</p>
<pre><code>path = choosePath()
checkPath(path)
</code></pre>
<p>Or as a one-liner:</p>
<pre><code>checkPath(choosePath())
</code></pre>
| 2
|
2016-09-05T22:15:04Z
|
[
"python"
] |
How can I print out the correct response based on input?
| 39,338,238
|
<p>I'm new to Python and I have a very simple problem that I'd like explained to me. I'm making a text adventure game and I'd like to be able to call another function inside a function so my code is organized better. </p>
<p>This is what I have that's working:</p>
<pre><code>def displayIntro():
print("You come to a crossroads on your trip home.")
print ("You can go LEFT towards the DEMON FOREST or RIGHT to SKULL MOUNTAIN")
print()
def choosePath():
path = ""
while path != "LEFT" and path != "RIGHT":
path = input("Which path will you choose? LEFT or RIGHT? --> ")
if path == "RIGHT":
print("You take the path to SKULL MOUNTAIN.")
elif path == "LEFT":
print ("You take the path to the DEMON FOREST.")
displayIntro()
choosePath()
choosenPath()
</code></pre>
<p>But I'd like it to look something like this, but I don't know how to make it work:</p>
<pre><code>def displayIntro():
print("You come to a crossroads on your trip home.")
print ("You can go LEFT towards the DEMON FOREST or RIGHT to SKULL MOUNTAIN")
print()
def choosePath():
path = ""
while path != "LEFT" and path != "RIGHT":
path = input("Which path will you choose? LEFT or RIGHT? --> ")
return path
def checkPath(choosePath):
if choosePath == "RIGHT":
print("You take the path to SKULL MOUNTAIN.")
elif choosePath == "LEFT":
print("You take the path to the DEMON FOREST.")
displayIntro()
choosePath()
checkPath()
</code></pre>
| -1
|
2016-09-05T22:12:09Z
| 39,338,261
|
<p>You have to pass the return value of <code>choosePath</code> to <code>checkPath</code>.</p>
<pre><code>checkPath(choosePath())
</code></pre>
<p><code>checkPath</code> takes a parameter, so you need to supply a value. That value is the return value of <code>choosePath</code>, either "LEFT" or "RIGHT". Once you pass it in, the <code>checkPath</code> function will execute, checking the string and printing accordingly. Replace the <code>choosePath</code> and <code>checkPath</code> call with the above code.</p>
| 1
|
2016-09-05T22:15:39Z
|
[
"python"
] |
Forbidden (CSRF token missing or incorrect.) Django + AngularJs
| 39,338,369
|
<p>When I try to render to my second page in my django framework I get following error. I think that there is something wrong with my url page and views.py but can't figure it out, nothing gives a step forward..</p>
<pre><code>Forbidden (CSRF token missing or incorrect.): /renderbonds
[06/Sep/2016 00:21:55] "POST /renderbonds HTTP/1.1" 403 2502
</code></pre>
<p>this is my html/django form</p>
<pre><code><form action="{% url 'renderbonds'%}" method="post" >
<input type="submit" value="calculate bonds" class='button expand radius'/>
</form>
</code></pre>
<p>Views.py python file:</p>
<pre><code>def home(request):
tmpl_vars = {
'all_posts': Post.objects.reverse(),
'form': PostForm()
}
return render(request, 'pricing/bonds.html', tmpl_vars)
def renderbonds(request):
"""render shortcut : http://stackoverflow.com/questions/10388033/csrf-verification-failed-request-aborted"""
if request.method == 'POST':
post_text = request.POST.get('the_post')
response_data = {}
post = Post(text=post_text, author=request.user)
post.save()
"""DATA MEEGEVEN"""
response_data['year'] = post.year
response_data['cashflow'] = post.cashflow
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
else:
tmpl_vars = {
'all_posts': Post.objects.reverse(),
'form': PostForm()
}
return render(request,'pricing/bonds.html', tmpl_vars)
</code></pre>
<p>my urls:</p>
<pre><code>urlpatterns = [
url(r'^$', views.calc,name='calc'),
url(r'^$', views.home,'home'),
url(r'^create_post/$',views.create_post,'create_post'),
url(r'^renderbonds', views.home, name='home'),
url(r'^/renderbonds', views.home, name='home'),
url(r'^renderbonds/', views.home, name='home')
]
</code></pre>
| 0
|
2016-09-05T22:29:30Z
| 39,338,383
|
<p>The issue is not with your urls or your views, but with your template. Try adding <code>{% csrf_token %}</code> nested under your <code><form></form></code> tags in your template. </p>
<pre><code><form action="{% url 'renderbonds'%}" method="post" >
<input type="submit" value="calculate bonds" class='button expand radius'/>
{% csrf_token %}
</form>
</code></pre>
<p>See <a href="https://docs.djangoproject.com/en/1.10/ref/csrf/" rel="nofollow">the docs</a> for more details. </p>
| 2
|
2016-09-05T22:31:08Z
|
[
"python",
"angularjs",
"django"
] |
Python crash course 8-10
| 39,338,405
|
<p>I'm currently reading Python Crash Course by Eric Matthes and doing some of the problem sets. One of them is giving me some difficulty and I was hoping someone could help me with it. </p>
<blockquote>
<p>8-9. Magicians: Make a list of magician's names. Pass the list to a function called show_magicians(), which prints the name of each magician in the list.</p>
<p>8-10. Great Magicians: Start with a copy of your program from exercise 8-9. Write a function make_great() that modifies the list of magicians by adding the phrase <em>the great</em> to each magician's name. Call show_magicians() to see that the list has actually been modified. </p>
</blockquote>
<p>And this is what I have for 8-9:</p>
<pre><code>magician_names=['Alice', 'Alex', 'Blake']
def show_magicians(n):
for magician in n:
print (magician)
show_magicians(magician_names)
</code></pre>
<p>I just don't really know what to do for 8-10</p>
| 2
|
2016-09-05T22:34:05Z
| 39,338,427
|
<p>To do this, you can append to a string and reassign to add words to the end of each element:</p>
<pre><code>magician += " the great"
</code></pre>
<p>Here, the <code>+=</code> operator appends a string, then reassigns, which is equivalent to the following:</p>
<pre><code>magician = magician + " the great"
</code></pre>
<p>Now, you can add this to a function like so:</p>
<pre><code>def make_great(list_magicians):
for i in range(len(list_magicians)):
list_magicians[i] += " the great"
make_great(magician_names)
show_magicians(magician_names)
</code></pre>
<p>The output is:</p>
<pre><code>Alice the great
Alex the great
Blake the great
</code></pre>
<p>How this works is that we use a 'counter' for loop, similar to the ones in languages like C, (you can also use <code>enumerate</code> here), that loops through each element by using subscripts. Then it appends the string " the great" to all elements.</p>
<hr>
<p>The reason why you cannot just do a simple <code>for-in</code> loop and modify those values is because <code>for-in</code> copies the value in the variable before <code>in</code>:</p>
<pre><code>for magician in list_magicians: # magician is a temporary variable, does not hold actual reference to real elements
</code></pre>
<p>If they don't hold an actual reference, you cannot modify the reference, hence the reason you need to use counter loops to access the actual reference through subscript.</p>
| 1
|
2016-09-05T22:37:08Z
|
[
"python"
] |
Python crash course 8-10
| 39,338,405
|
<p>I'm currently reading Python Crash Course by Eric Matthes and doing some of the problem sets. One of them is giving me some difficulty and I was hoping someone could help me with it. </p>
<blockquote>
<p>8-9. Magicians: Make a list of magician's names. Pass the list to a function called show_magicians(), which prints the name of each magician in the list.</p>
<p>8-10. Great Magicians: Start with a copy of your program from exercise 8-9. Write a function make_great() that modifies the list of magicians by adding the phrase <em>the great</em> to each magician's name. Call show_magicians() to see that the list has actually been modified. </p>
</blockquote>
<p>And this is what I have for 8-9:</p>
<pre><code>magician_names=['Alice', 'Alex', 'Blake']
def show_magicians(n):
for magician in n:
print (magician)
show_magicians(magician_names)
</code></pre>
<p>I just don't really know what to do for 8-10</p>
| 2
|
2016-09-05T22:34:05Z
| 39,338,440
|
<p>Okay, you already know how to iterate through the list. You want to make a similar function, where you modify the string referred to my <code>magician</code> to say, "the Great".</p>
<p>So, if you had a string "Smedley" and you wanted to change that to a string "Smedley the Great" how would you do it?</p>
<p><strong>update</strong></p>
<p>So now that the answer's been given away anyway, there are a couple of other options that are more "functional" and arguably safer since you're protected from aliasing etc.</p>
<p>Option 1: create a new list, eg: (These examples done with <a href="https://ipython.org/" rel="nofollow">iPython</a> which is a very handy tool, worth installing for learning Python)</p>
<pre><code>def make_great_1(lst):
rtn = []
for m in lst:
rtn.append(m+" the Great")
return rtn
In [7]: mages = [ 'Gandalf', 'Mickey' ]
In [8]: make_great_1(mages)
Out[8]: ['Gandalf the Great', 'Mickey the Great']
</code></pre>
<p>Option 2: use a list comprehension:</p>
<pre><code>In [9]: [ mg+" the Great" for mg in mages ]
Out[9]: ['Gandalf the Great', 'Mickey the Great']
</code></pre>
<p>Now, the problem says to <em>modify</em> the list, and it's easy to imagine that means you should modify the strings, but in fact Python (unless you use a <code>MutableString</code>) just makes a copy anyway. If you want to be really picky, either of these options could be re-done to assign the new list to <code>mages</code> in my case, or <code>magician_names</code> in yours.</p>
| 1
|
2016-09-05T22:38:29Z
|
[
"python"
] |
Python crash course 8-10
| 39,338,405
|
<p>I'm currently reading Python Crash Course by Eric Matthes and doing some of the problem sets. One of them is giving me some difficulty and I was hoping someone could help me with it. </p>
<blockquote>
<p>8-9. Magicians: Make a list of magician's names. Pass the list to a function called show_magicians(), which prints the name of each magician in the list.</p>
<p>8-10. Great Magicians: Start with a copy of your program from exercise 8-9. Write a function make_great() that modifies the list of magicians by adding the phrase <em>the great</em> to each magician's name. Call show_magicians() to see that the list has actually been modified. </p>
</blockquote>
<p>And this is what I have for 8-9:</p>
<pre><code>magician_names=['Alice', 'Alex', 'Blake']
def show_magicians(n):
for magician in n:
print (magician)
show_magicians(magician_names)
</code></pre>
<p>I just don't really know what to do for 8-10</p>
| 2
|
2016-09-05T22:34:05Z
| 39,338,445
|
<p>The question asks you to modify <code>magician_names</code>. Since each entry in <code>magician_names</code> is a <code>str</code>, and <code>strs</code> are unmodifiable, you cannot simply modify each <code>str</code> in <code>magician_names</code> by appending <code>" the great"</code> to it. Instead, you need to <em>replace</em> each <code>str</code> in <code>magician_names</code> with its modified version.</p>
<p>So this seemingly straightforward approach:</p>
<pre><code>def make_great(l):
for name in l:
name += " the great"
make_great(magician_names)
</code></pre>
<p>does not modify <code>magician_names</code>. It simply creates a new <code>str</code> object and assigns that to the <code>name</code> variable local to the <code>for loop</code>. Each element of <code>magician_names</code> is unchanged, i.e. it still points to the same <code>str</code> object.</p>
<p>But this approach:</p>
<pre><code>def make_great(l):
for index, name in enumerate(l):
l[index] = name + " the great"
make_great(magician_names)
</code></pre>
<p>changes the <code>str</code> objects pointed to by <code>magician_names</code> and hence modifies <code>magician_names</code> as required.</p>
<p><hr>
To your comment, </p>
<pre><code>for index, name in enumerate(l):
l[index] = name + " the great"
</code></pre>
<p>is just the Pythonic way to write:</p>
<pre><code>for index in range(len(l)):
name = l[index]
l[index] = name + " the great"
</code></pre>
<p><code>enumerate(l)</code> returns an iterable (actually a lazy generator) that yields a matched <code>index, element</code> pair for each element in <code>l</code>.</p>
| 1
|
2016-09-05T22:38:54Z
|
[
"python"
] |
Quadractic Formula mix up
| 39,338,450
|
<p>So I made a python code that solves for x using the quadratic formula. Everything works out in the end except for the signs. For instance, if you want to factor x^2 + 10x + 25, my code outputs -5, -5 when the answer should be 5, 5.</p>
<pre><code>def quadratic_formula():
a = int(input("a = "))
b = int(input("b = "))
c = int(input("c = "))
bsq = b * b
fourac = 4 * a * c
sqrt = (bsq - fourac) ** (.5)
oppb = -b
numerator_add = (oppb) + (sqrt)
numerator_sub = (oppb) - (sqrt)
twoa = 2 * a
addition_answer = (numerator_add) / (twoa)
subtraction_answer = (numerator_sub) / (twoa)
print(addition_answer)
print(subtraction_answer)
</code></pre>
| 3
|
2016-09-05T22:39:47Z
| 39,338,510
|
<p>Your solution is fine, let's prove it using <a href="http://www.sympy.org/en/index.html" rel="nofollow">sympy</a>:</p>
<pre><code>>>> (x**2+10*x+25).subs(x,-5)
0
</code></pre>
<p>As you can see, -5 is one of the roots while 5</p>
<pre><code>>>> (x**2+10*x+25).subs(x,5)
100
</code></pre>
<p>is not, now... if you expand your 2 roots [-5,-5] like:</p>
<pre><code>>>> ((x+5)*(x+5)).expand()
x**2 + 10*x + 25
</code></pre>
<p>You can see like the result matches.</p>
<p>In fact, you can also confirm the roots are correct displaying the quadratic equation:</p>
<p><a href="http://i.stack.imgur.com/GXyQ1.png" rel="nofollow"><img src="http://i.stack.imgur.com/GXyQ1.png" alt="enter image description here"></a></p>
<p>I'd strongly recommend you review the concept of <a href="http://www.sosmath.com/algebra/factor/fac08/fac08.html" rel="nofollow">The Quadratic Formula</a> and when it's clear just come back to the coding</p>
| 5
|
2016-09-05T22:48:48Z
|
[
"python",
"math",
"quadratic"
] |
Curl "Connection Refused" when connecting to server with external IP address
| 39,338,451
|
<p>I've created a RESTful server and I can successfully make requests and get responses when I use my local IP address. I would like it to be exposed externally to the internet. I set up a port forwarding rule but I cannot seem to get things working. From what I'm reading the "Connection Refused" with (7) means something is blocking it whether it's a firewall or ISP issue. Any ideas on what to do? </p>
<p>Here's my curl command that works with my local IP:</p>
<pre><code>Pako-2:Pokebot pako$ curl -X GET http://192.168.1.8:30000/api/v1/getrecord/test
{"data": [{"id": 1, "title": "learn python"}, {"id": 2, "title": "get paid"}]}
</code></pre>
<p>This is what I see when I try using my external IP address given to me by <a href="http://www.whatsmyip.org/" rel="nofollow">What's my ip</a></p>
<pre><code>Pako-2:Pokebot pako$ curl -X GET http://MyIpHere:30000/api/v1/getrecord/test
curl: (7) Failed to connect to myIPAddress port 30000: Connection refused
</code></pre>
<p>Here's the port forwarding rule I made in my router/modem
<a href="http://i.stack.imgur.com/GULGI.png" rel="nofollow"><img src="http://i.stack.imgur.com/GULGI.png" alt="enter image description here"></a></p>
<p>Here are my router/modem advanced settings options. I tried tweaking my firewall settings, but no luck. I tried with NAT only and also with Low Security Level with all ports checked. </p>
<p><a href="http://i.stack.imgur.com/Cee9s.png" rel="nofollow"><img src="http://i.stack.imgur.com/Cee9s.png" alt="enter image description here"></a>
<a href="http://i.stack.imgur.com/qUZGL.png" rel="nofollow"><img src="http://i.stack.imgur.com/qUZGL.png" alt="enter image description here"></a>
<a href="http://i.stack.imgur.com/tVnpr.png" rel="nofollow"><img src="http://i.stack.imgur.com/tVnpr.png" alt="enter image description here"></a>
<a href="http://i.stack.imgur.com/ZMGhj.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZMGhj.png" alt="enter image description here"></a></p>
<p>-----------------Edit-----------------</p>
<p>Here is the port forwarding screen, should I just set 30000 as the begin and end?
<a href="http://i.stack.imgur.com/Rnp1U.png" rel="nofollow"><img src="http://i.stack.imgur.com/Rnp1U.png" alt="enter image description here"></a></p>
<p>Here is some python code for my server:</p>
<pre><code>from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
import threading
import argparse
import re
import cgi
import json
TODOS = [
{'id': 1, 'title': 'learn python'},
{'id': 2, 'title': 'get paid'},
]
class LocalData(object):
records = {}
class HTTPRequestHandler(BaseHTTPRequestHandler):
print "HTTPRequestHandler BaseHTTPRequestHandler = ", BaseHTTPRequestHandler
def do_POST(self):
print "do_POST"
if None != re.search('/api/v1/addrecord/*', self.path):
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
if ctype == 'application/json':
length = int(self.headers.getheader('content-length'))
data = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
recordID = self.path.split('/')[-1]
LocalData.records[recordID] = data
print "record %s is added successfully" % recordID
else:
data = {}
self.send_response(200)
self.end_headers()
else:
self.send_response(403)
self.send_header('Content-Type', 'application/json')
self.end_headers()
return
def do_GET(self):
print "do_GET"
self.send_response(200)
self.end_headers()
self.wfile.write(json.dumps({'data': TODOS}))
return
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
allow_reuse_address = True
def shutdown(self):
self.socket.close()
HTTPServer.shutdown(self)
class SimpleHttpServer():
def __init__(self, ip, port):
self.server = ThreadedHTTPServer((ip, port), HTTPRequestHandler)
def start(self):
self.server_thread = threading.Thread(target=self.server.serve_forever)
self.server_thread.daemon = True
self.server_thread.start()
def waitForThread(self):
self.server_thread.join()
def addRecord(self, recordID, jsonEncodedRecord):
LocalData.records[recordID] = jsonEncodedRecord
def stop(self):
self.server.shutdown()
self.waitForThread()
if __name__ == '__main__':
server = SimpleHttpServer("0.0.0.0", 30000)
print 'HTTP Server Running...........'
server.start()
server.waitForThread()
</code></pre>
<p>------------------- Edit 2--------------------</p>
<p>Tried only having 1 port, not a begin/end range and it's expecting a range...
<a href="http://i.stack.imgur.com/dKiYN.png" rel="nofollow"><img src="http://i.stack.imgur.com/dKiYN.png" alt="enter image description here"></a>
<a href="http://i.stack.imgur.com/utpob.png" rel="nofollow"><img src="http://i.stack.imgur.com/utpob.png" alt="enter image description here"></a></p>
| 1
|
2016-09-05T22:39:49Z
| 39,338,861
|
<p>I find it strange that you'd be getting connection refused from within the local network because the router should be able to detect that the external IP is a reference to itself. </p>
<p>That ability may depend on the router, but that's been my experience with networking. </p>
<p>That being said, if you'd like to test the external firewall after playing with the port forwarding rules, then you need a device not on the local network. </p>
<p>If another device like a smart phone with a cell plan isn't available to you, then you could try to use <a href="http://www.canyouseeme.org" rel="nofollow">CanYouSeeMe</a> to test if the port is being opened. </p>
<p>You may also want to set DHCP reservation for your server. In other words, set a static IP address. </p>
| 1
|
2016-09-05T23:49:17Z
|
[
"python",
"curl",
"networking",
"portforwarding"
] |
Time complexity for a sublist in Python
| 39,338,520
|
<p>In Python, what is the time complexity when we create a sublist from an existing list?</p>
<p>For example, here data is the name of our existing list and list1 is our sublist created by slicing data.</p>
<pre><code>data = [1,2,3,4,5,6..100,...1000....,10^6]
list1 = data[101:10^6]
</code></pre>
<p>What is the running time for creating list1?</p>
<pre><code>Is it O(10^6) i.e.O(N), or O(1)?
</code></pre>
| 4
|
2016-09-05T22:49:38Z
| 39,338,537
|
<p>Getting a list slice in python is <code>O(M - N)</code> / <code>O(10^6 - 101)</code></p>
<p><a href="https://wiki.python.org/moin/TimeComplexity">Here</a> you can check python list operations time complexity </p>
<p>By underneath, python lists are represented like arrays. So, you can iterate starting on some index(N) and stopping in another one(M)</p>
| 7
|
2016-09-05T22:51:56Z
|
[
"python",
"performance",
"list",
"big-o",
"sublist"
] |
Cut a polygon with two lines in shapely
| 39,338,550
|
<p>I am trying to cut a <code>shapely.geometry.Polygon</code> instance into two parts with two lines. For example, in the code below, <code>polygon</code> is a ring and if we cut it with <code>line1</code> and <code>line2</code> we should get two partial rings, one w/ 270 degrees and one with 90 degrees. Would there be a clean way to do this?</p>
<p>Thank you!</p>
<p>Shawn</p>
<pre><code>from shapely.geometry import Point, LineString, Polygon
polygon = Point(0, 0).buffer(2).difference(Point(0, 0).buffer(1))
line1 = LineString([(0, 0), (3, 3)])
line2 = LineString([(0, 0), (3, -3)])
</code></pre>
| 1
|
2016-09-05T22:53:56Z
| 39,340,336
|
<p>Ken Watford answered <a href="http://community-gispython-org-community-projects.955323.n3.nabble.com/Community-Shapely-how-to-split-a-polygon-with-a-line-td1915160.html" rel="nofollow">here</a> about using <code>buffer</code> and <code>difference</code> to do the trick, w/ the drawback of losing a bit of the area. An example code below:</p>
<pre><code>from shapely.geometry import Point, LineString, Polygon
polygon = Point(0, 0).buffer(2).difference(Point(0, 0).buffer(1))
line1 = LineString([(0, 0), (3, 3)])
line2 = LineString([(0, 0), (3, -3)])
line1_pol = line1.buffer(1e-3)
line2_pol = line2.buffer(1e-3)
new_polygon = polygon.difference(line1_pol).difference(line2_pol)
</code></pre>
<p>Works for now, and I'd be interested to see whether there is another (potentially w/o losing area) method!</p>
| 1
|
2016-09-06T03:46:11Z
|
[
"python",
"shapely"
] |
How to place marker on one line and get coordinates
| 39,338,575
|
<p>1)I want to place a marker on one line,(between two points) in function of the lenght of the line.</p>
<p>2)I want to know the coordinates of this point/marker.</p>
<pre><code>import matplotlib.pyplot as plt
import math
x1 = 0
x2 = 9
y1 = 5
y2 = 7
plt.plot((x1, x2), (y1, y2))
lenghtline1 = math.sqrt((x1-x2)**2 + (y1-y2)**2)
</code></pre>
<p>Here the distance between the two points is 9.2 , </p>
<p>How can i put a marker in the line(between the two points) to 6 from point1?</p>
<p>How can i know the coordinates (x,y) of this marker?
thank you</p>
| 0
|
2016-09-05T22:58:24Z
| 39,339,391
|
<p>Point with distance <code>len</code> to the first point will have coordinates</p>
<pre><code> x = x1 + (x2-x1) * len / lenghtline1
y = y1 + (y2-y1) * len / lenghtline1
</code></pre>
| 0
|
2016-09-06T01:22:45Z
|
[
"python",
"python-3.x",
"numpy",
"math",
"matplotlib"
] |
How to place marker on one line and get coordinates
| 39,338,575
|
<p>1)I want to place a marker on one line,(between two points) in function of the lenght of the line.</p>
<p>2)I want to know the coordinates of this point/marker.</p>
<pre><code>import matplotlib.pyplot as plt
import math
x1 = 0
x2 = 9
y1 = 5
y2 = 7
plt.plot((x1, x2), (y1, y2))
lenghtline1 = math.sqrt((x1-x2)**2 + (y1-y2)**2)
</code></pre>
<p>Here the distance between the two points is 9.2 , </p>
<p>How can i put a marker in the line(between the two points) to 6 from point1?</p>
<p>How can i know the coordinates (x,y) of this marker?
thank you</p>
| 0
|
2016-09-05T22:58:24Z
| 39,350,709
|
<pre><code>from pylab import *
from scipy import interpolate
x = rand(21).cumsum() # create some 21 random x values
y = rand(len(x)) # the corresponding y values
plot(x, y, ".-")
xc = x[:-1] + diff(x)/2.
yc = interpolate.interp1d(x, y, kind="linear")(xc) # (xc, yc) are the marker positions
lengths = sqrt(diff(x)**2 + diff(y)**2) # lengths of the sections
scatter(xc,yc,c=cm.gray(lengths/lengths.max()), s=40) # visualization
show()
</code></pre>
| 0
|
2016-09-06T13:49:43Z
|
[
"python",
"python-3.x",
"numpy",
"math",
"matplotlib"
] |
Can't connect to mysql using sqlalchemy. Library not loaded error
| 39,338,631
|
<p>I am trying to run a simple test code to connect ti a mysql db using sql alchemy.
The code is as follows:</p>
<pre><code>from sqlalchemy import (create_engine, Table, Column, Integer, String, MetaData)
import settings
import sys
try:
db = create_engine('mysql://daniel:dani@localhost/test')
db.connect()
except:
print('opps ', sys.exc_info()[1])
</code></pre>
<p>I get the following error:</p>
<pre><code>dlopen(//anaconda/lib/python3.5/site-packages/_mysql.cpython-35m-darwin.so, 2): Library not loaded: libssl.1.0.0.dylib
Referenced from: //anaconda/lib/python3.5/site-packages/_mysql.cpython-35m-darwin.so
Reason: image not found
[Finished in 1.4s]
</code></pre>
<p>But running on terminal:</p>
<pre><code>locate libssl.1.0.0.dylib
</code></pre>
<p>I get:</p>
<pre><code>/Applications/Dtella.app/Contents/Frameworks/libssl.1.0.0.dylib
/Applications/XAMPP/xamppfiles/lib/libssl.1.0.0.dylib
/Users/dpereira14/anaconda/envs/dato-env/lib/libssl.1.0.0.dylib
/Users/dpereira14/anaconda/lib/libssl.1.0.0.dylib
/Users/dpereira14/anaconda/pkgs/openssl-1.0.1k-1/lib/libssl.1.0.0.dylib
/anaconda/lib/libssl.1.0.0.dylib
/anaconda/pkgs/openssl-1.0.2g-0/lib/libssl.1.0.0.dylib
/opt/local/lib/libssl.1.0.0.dylib
/usr/local/Cellar/openssl/1.0.1j/lib/libssl.1.0.0.dylib
</code></pre>
<p>I have no clue how to fix this error.</p>
<p>Thanks!</p>
| 0
|
2016-09-05T23:06:03Z
| 39,338,962
|
<p>I also had some problems with SQLAlchemy with mysql, i changed localhost in the create_engine to 127.0.0.1:port, and also had to use pymysql. Ended up working with this:</p>
<p><code>engine = create_engine('mysql+pymysql://user:password@127.0.0.1:port/db')</code></p>
<p>pymysql is installed via pip.</p>
| 0
|
2016-09-06T00:05:50Z
|
[
"python",
"mysql",
"sqlalchemy"
] |
Can't connect to mysql using sqlalchemy. Library not loaded error
| 39,338,631
|
<p>I am trying to run a simple test code to connect ti a mysql db using sql alchemy.
The code is as follows:</p>
<pre><code>from sqlalchemy import (create_engine, Table, Column, Integer, String, MetaData)
import settings
import sys
try:
db = create_engine('mysql://daniel:dani@localhost/test')
db.connect()
except:
print('opps ', sys.exc_info()[1])
</code></pre>
<p>I get the following error:</p>
<pre><code>dlopen(//anaconda/lib/python3.5/site-packages/_mysql.cpython-35m-darwin.so, 2): Library not loaded: libssl.1.0.0.dylib
Referenced from: //anaconda/lib/python3.5/site-packages/_mysql.cpython-35m-darwin.so
Reason: image not found
[Finished in 1.4s]
</code></pre>
<p>But running on terminal:</p>
<pre><code>locate libssl.1.0.0.dylib
</code></pre>
<p>I get:</p>
<pre><code>/Applications/Dtella.app/Contents/Frameworks/libssl.1.0.0.dylib
/Applications/XAMPP/xamppfiles/lib/libssl.1.0.0.dylib
/Users/dpereira14/anaconda/envs/dato-env/lib/libssl.1.0.0.dylib
/Users/dpereira14/anaconda/lib/libssl.1.0.0.dylib
/Users/dpereira14/anaconda/pkgs/openssl-1.0.1k-1/lib/libssl.1.0.0.dylib
/anaconda/lib/libssl.1.0.0.dylib
/anaconda/pkgs/openssl-1.0.2g-0/lib/libssl.1.0.0.dylib
/opt/local/lib/libssl.1.0.0.dylib
/usr/local/Cellar/openssl/1.0.1j/lib/libssl.1.0.0.dylib
</code></pre>
<p>I have no clue how to fix this error.</p>
<p>Thanks!</p>
| 0
|
2016-09-05T23:06:03Z
| 39,341,459
|
<p>You are using python , so you have add mysqldb with mysql. Try the below code.</p>
<pre><code>try:
db = create_engine('mysql+mysqldb://daniel:dani@localhost/test')
db.connect()
except:
print('opps ', sys.exc_info()[1])
</code></pre>
| 0
|
2016-09-06T05:49:25Z
|
[
"python",
"mysql",
"sqlalchemy"
] |
How to get results from pyparsing Forward object?
| 39,338,654
|
<p>Let us assume we have the following string</p>
<pre><code>string = """
object obj1{
attr1 value1;
object obj2 {
attr2 value2;
}
}
object obj3{
attr3 value3;
attr4 value4;
}
"""
</code></pre>
<p>There is a nested object, and we use Forward to parse this. </p>
<pre><code>from pyparsing import *
word = Word(alphanums)
attribute = word.setResultsName("name")
value = word.setResultsName("value")
object_grammar = Forward()
attributes = attribute + value + Suppress(";") + LineEnd().suppress()
object_type = Suppress("object ") + word.setResultsName("object_type") + Suppress('{') + LineEnd().suppress()
object_grammar <<= object_type+\
OneOrMore(attributes|object_grammar) + Suppress("}") | Suppress("};")
for i, (obj, _, _) in enumerate(object_grammar.scanString(string)):
print('\n')
print('Enumerating over object {}'.format(i))
print('\n')
print('This is the object type {}'.format(obj.object_type))
print(obj.asXML())
print(obj.asDict())
print(obj.asList())
print(obj)
print(obj.dump())
</code></pre>
<p>These are the results. The obj.asXML() function contains all the information, however since it has been flattened, the order of the information is essential to parsing the result. Is this the best way to do it? I must be missing something. I would like a solution that works for both nested and not nested objects, i.e. for obj1, obj2 and obj3.</p>
<p>Also, <code>setResultsName('object_type')</code> doesn't return the <code>object_type</code> for the parent object. The output of the program above is shown below. Any suggestions?</p>
<pre><code>Enumerating over object 0
This is the object type obj2
<ITEM>
<object_type>obj1</object_type>
<name>attr1</name>
<value>value1</value>
<object_type>obj2</object_type>
<name>attr2</name>
<value>value2</value>
</ITEM>
{'object_type': 'obj2', 'name': 'attr2', 'value': 'value2'}
['obj1', 'attr1', 'value1', 'obj2', 'attr2', 'value2']
['obj1', 'attr1', 'value1', 'obj2', 'attr2', 'value2']
['obj1', 'attr1', 'value1', 'obj2', 'attr2', 'value2']
- name: attr2
- object_type: obj2
- value: value2
Enumerating over object 1
This is the object type obj3
<ITEM>
<object_type>obj3</object_type>
<name>attr3</name>
<value>value3</value>
<name>attr4</name>
<value>value4</value>
</ITEM>
{'object_type': 'obj3', 'name': 'attr4', 'value': 'value4'}
['obj3', 'attr3', 'value3', 'attr4', 'value4']
['obj3', 'attr3', 'value3', 'attr4', 'value4']
['obj3', 'attr3', 'value3', 'attr4', 'value4']
- name: attr4
- object_type: obj3
- value: value4
</code></pre>
| 1
|
2016-09-05T23:10:41Z
| 39,339,359
|
<p>I was able to work around this by using <code>listAllMatches=True</code> in the setResultsNames function. This gave me as asXML() result that had structure that I could retrieve information from. It still relies on the order of the XML and requires using zip for get the <code>name</code> and <code>value</code> for a <code>attribute</code> together. I'll leave this question open to see if I get a better way of doing this.</p>
| 2
|
2016-09-06T01:17:03Z
|
[
"python",
"pyparsing"
] |
How to get results from pyparsing Forward object?
| 39,338,654
|
<p>Let us assume we have the following string</p>
<pre><code>string = """
object obj1{
attr1 value1;
object obj2 {
attr2 value2;
}
}
object obj3{
attr3 value3;
attr4 value4;
}
"""
</code></pre>
<p>There is a nested object, and we use Forward to parse this. </p>
<pre><code>from pyparsing import *
word = Word(alphanums)
attribute = word.setResultsName("name")
value = word.setResultsName("value")
object_grammar = Forward()
attributes = attribute + value + Suppress(";") + LineEnd().suppress()
object_type = Suppress("object ") + word.setResultsName("object_type") + Suppress('{') + LineEnd().suppress()
object_grammar <<= object_type+\
OneOrMore(attributes|object_grammar) + Suppress("}") | Suppress("};")
for i, (obj, _, _) in enumerate(object_grammar.scanString(string)):
print('\n')
print('Enumerating over object {}'.format(i))
print('\n')
print('This is the object type {}'.format(obj.object_type))
print(obj.asXML())
print(obj.asDict())
print(obj.asList())
print(obj)
print(obj.dump())
</code></pre>
<p>These are the results. The obj.asXML() function contains all the information, however since it has been flattened, the order of the information is essential to parsing the result. Is this the best way to do it? I must be missing something. I would like a solution that works for both nested and not nested objects, i.e. for obj1, obj2 and obj3.</p>
<p>Also, <code>setResultsName('object_type')</code> doesn't return the <code>object_type</code> for the parent object. The output of the program above is shown below. Any suggestions?</p>
<pre><code>Enumerating over object 0
This is the object type obj2
<ITEM>
<object_type>obj1</object_type>
<name>attr1</name>
<value>value1</value>
<object_type>obj2</object_type>
<name>attr2</name>
<value>value2</value>
</ITEM>
{'object_type': 'obj2', 'name': 'attr2', 'value': 'value2'}
['obj1', 'attr1', 'value1', 'obj2', 'attr2', 'value2']
['obj1', 'attr1', 'value1', 'obj2', 'attr2', 'value2']
['obj1', 'attr1', 'value1', 'obj2', 'attr2', 'value2']
- name: attr2
- object_type: obj2
- value: value2
Enumerating over object 1
This is the object type obj3
<ITEM>
<object_type>obj3</object_type>
<name>attr3</name>
<value>value3</value>
<name>attr4</name>
<value>value4</value>
</ITEM>
{'object_type': 'obj3', 'name': 'attr4', 'value': 'value4'}
['obj3', 'attr3', 'value3', 'attr4', 'value4']
['obj3', 'attr3', 'value3', 'attr4', 'value4']
['obj3', 'attr3', 'value3', 'attr4', 'value4']
- name: attr4
- object_type: obj3
- value: value4
</code></pre>
| 1
|
2016-09-05T23:10:41Z
| 39,438,974
|
<p>While you have successfully processed your input string, let me suggest some refinements to your grammar.</p>
<p>When defining a recursive grammar, one usually wants to maintain some structure in the output results. In your case, the logical piece to structure is the content of each object, which is surrounded by opening and closing braces. Conceptually:</p>
<pre><code>object_content = '{' + ZeroOrMore(attribute_defn | object_defn) + '}'
</code></pre>
<p>Then the supporting expressions are just (still conceptually):</p>
<pre><code>attribute_defn = identifier + attribute_value + ';'
object_defn = 'object' + identifier + object_content
</code></pre>
<p>The actual Python/pyparsing for this looks like:</p>
<pre><code>LBRACE,RBRACE,SEMI = map(Suppress, "{};")
word = Word(alphas, alphanums)
attribute = word
# expand to include other values if desired, such as ints, reals, strings, etc.
attribute_value = word
attributeDefn = Group(word("name") + value("value") + SEMI)
OBJECT = Keyword("object")
object_header = OBJECT + word("object_name")
object_grammar = Forward()
object_body = Group(LBRACE
+ ZeroOrMore(object_grammar | attributeDefn)
+ RBRACE)
object_grammar <<= Group(object_header + object_body("object_content"))
</code></pre>
<p><code>Group</code> does two things for us: it structures the results into sub-objects; and it keeps the results names at one level from stepping on those at a different level (so no need for <code>listAllMatches</code>).</p>
<p>Now instead of <code>scanString</code>, you can just process your input using <code>OneOrMore</code>:</p>
<pre><code>print(OneOrMore(object_grammar).parseString(string).dump())
</code></pre>
<p>Giving:</p>
<pre><code>[['object', 'obj1', [['attr1', 'value1'], ['object', 'obj2', [['attr2', 'value2']]]]], ['object', 'obj3', [['attr3', 'value3'], ['attr4', 'value4']]]]
[0]:
['object', 'obj1', [['attr1', 'value1'], ['object', 'obj2', [['attr2', 'value2']]]]]
- object_content: [['attr1', 'value1'], ['object', 'obj2', [['attr2', 'value2']]]]
[0]:
['attr1', 'value1']
- name: attr1
- value: value1
[1]:
['object', 'obj2', [['attr2', 'value2']]]
- object_content: [['attr2', 'value2']]
[0]:
['attr2', 'value2']
- name: attr2
- value: value2
- object_name: obj2
- object_name: obj1
[1]:
['object', 'obj3', [['attr3', 'value3'], ['attr4', 'value4']]]
- object_content: [['attr3', 'value3'], ['attr4', 'value4']]
[0]:
['attr3', 'value3']
- name: attr3
- value: value3
[1]:
['attr4', 'value4']
- name: attr4
- value: value4
- object_name: obj3
</code></pre>
<p>I started to just make simple changes to your code, but there was a fatal flaw in your original. Your parser separated the left and right braces into two separate expressions - while this "works", it defeats the ability to define the group structure of the results. </p>
| 1
|
2016-09-11T17:50:04Z
|
[
"python",
"pyparsing"
] |
how to reference angular component template from django app
| 39,338,707
|
<p>I have the following angular component:</p>
<pre><code>angular.
module('phoneList').
component('phoneList', {
templateUrl: 'phone-list.template.html',
controller: function PhoneListController() {
this.phones = [
{
name: 'Nexus S',
snippet: 'Fast just got faster with Nexus S.',
age: 1
}, {
name: 'Motorola XOOM⢠with Wi-Fi',
snippet: 'The Next, Next Generation tablet.',
age: 2
}, {
name: 'MOTOROLA XOOMâ¢',
snippet: 'The Next, Next Generation tablet.',
age: 3
}
];
this.orderProp = 'age';
}
});
</code></pre>
<p>This template: <code>templateUrl: 'phone-list.template.html',</code> and the component are inside of my django app.</p>
<p>I have placed the template in:</p>
<blockquote>
<p>myapp > templates > myapp > phone-list.template.html</p>
</blockquote>
<p>The reference gives me a 404 as well as angular error: </p>
<blockquote>
<p><a href="http://127.0.0.1:8000/myapp/phone-list.template.html" rel="nofollow">http://127.0.0.1:8000/myapp/phone-list.template.html</a></p>
</blockquote>
<p><strong>Do I need to create a django url entry?
Do I need use a django url tag in the component?</strong></p>
| 0
|
2016-09-05T23:20:37Z
| 39,338,813
|
<p>Templates in the <code>templates</code> folder in Django are available to the template loader only. They are not served and can not be accessed via HTTP directly. But that is what Angular does.</p>
<p>If you need to render the template in Django, make sure you have created a view and an endpoint for it in your <code>urls.py</code>.</p>
<p>If no rendering is needed and Django can use the template directly serve them like <a href="https://docs.djangoproject.com/en/1.10/howto/static-files/" rel="nofollow" title="static files">static files</a>.</p>
| 2
|
2016-09-05T23:38:47Z
|
[
"python",
"angularjs",
"node.js",
"django"
] |
ElementTree Write to an XML
| 39,338,733
|
<p>What's the easiest way to write an edited XML root to a new file? This is what I have so far and it's throwing <strong>AttributeError: 'module' object has no attribute 'write'</strong> <br>
PS: I can't use any other api besides ElementTree.</p>
<pre><code>import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement, Comment
from ElementTree_pretty import prettify
tree = ET.parse('file-to-be-edited.xml')
root = tree.getroot()
#Process XML here
ET.write('file-after-edits.xml')
</code></pre>
| 0
|
2016-09-05T23:25:18Z
| 39,338,848
|
<p><strong>AttributeError: 'module' object has no attribute 'write'</strong> is saying that you cannot call the write method directly from ElementTree class, it is not a static method, try using <code>tree.write('file-after-edits.xml')</code>, tree is your object from ElementTree.</p>
| 0
|
2016-09-05T23:45:40Z
|
[
"python",
"xml",
"elementtree"
] |
ElementTree Write to an XML
| 39,338,733
|
<p>What's the easiest way to write an edited XML root to a new file? This is what I have so far and it's throwing <strong>AttributeError: 'module' object has no attribute 'write'</strong> <br>
PS: I can't use any other api besides ElementTree.</p>
<pre><code>import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement, Comment
from ElementTree_pretty import prettify
tree = ET.parse('file-to-be-edited.xml')
root = tree.getroot()
#Process XML here
ET.write('file-after-edits.xml')
</code></pre>
| 0
|
2016-09-05T23:25:18Z
| 39,338,941
|
<p>Your <code>tree</code> is a <code>ElementTree</code> object which provides a <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write" rel="nofollow"><code>write()</code></a> method to write the tree. For example:</p>
<pre><code>#Process XML here
tree.write('file-after-edits.xml', encoding='utf8')
</code></pre>
| 0
|
2016-09-06T00:02:26Z
|
[
"python",
"xml",
"elementtree"
] |
Pandas pd.DataFrame converts to Tuples instead of Dataframe
| 39,338,746
|
<p>I first use BeautifulSoup:</p>
<pre><code>mydivs = soup.findAll('div', {"class": "content"})
</code></pre>
<p>so that each <code>mydiv</code> in <code>mydivs</code> looks like this for example:</p>
<pre><code><div class="content">A number of hats by me <br/><br/>three now though ... </div>
</code></pre>
<p>I then want to store each of the text blocks in each <code>div</code> as rows in a dataframe. I want the dataframe to look something like:</p>
<pre><code>index posts
0 <div class="content">A number of <br/><br/>three ... </div>
1 <div class="content">Stack ... <br/><br/>overflow ... </div>
...
</code></pre>
<p>This is the code I tried</p>
<pre><code>A=[]
indices=[]
j=0
for div in mydivs:
A.append(div)
indices.append(j)
j+=1
DF = pd.DataFrame({'index': indices, "posts": A})
</code></pre>
<p>When I then print out the <code>shape</code> I get</p>
<pre><code>print DF.shape()
TypeError: 'tuple' object is not callable
</code></pre>
<p>However, I want <code>DF</code> to be a dataframe, not a <code>tuple</code>. How can I fix this?</p>
| 2
|
2016-09-05T23:26:45Z
| 39,338,796
|
<p>shape is an attribute of <code>DF</code>. That attribute is a <code>tuple</code>. You are trying to call it with the <code>()</code> which is throwing the error. If you want the shape just do <code>DF.shape</code></p>
<pre><code>print DF.shape
</code></pre>
<p><strong><em>not</em></strong></p>
<pre><code>print DF.shape()
</code></pre>
| 4
|
2016-09-05T23:35:01Z
|
[
"python",
"pandas",
"dataframe"
] |
Finding the highest value with the given constraints
| 39,338,764
|
<pre><code>c = [416,585,464]
A0 = [100,50,200]
A1 = [100,100,200]
A2 = [100,150,100]
A3 = [100,200,0]
A4 = [100,250,0]
b = [300,300,300,300,300]
for num in A0,A1,A2,A3,A4:
t0 = num[0]*1 + num[1]*1 + num[2]*1
t1 = num[0]*0 + num[1]*1 + num[2]*0
t2 = num[0]*0 + num[1]*0 + num[2]*0
t3 = num[0]*0 + num[1]*0 + num[2]*1
t4 = num[0]*1 + num[1]*0 + num[2]*0
t5 = num[0]*0 + num[1]*1 + num[2]*1
t6 = num[0]*1 + num[1]*1 + num[2]*0
t7 = num[0]*1 + num[1]*0 + num[2]*1
</code></pre>
<p>Now check each of the values in <code>t0</code> against each of its corresponding values in the <code>b</code> array. If any of the values from <code>t0</code> are greater than <code>300</code>, then <code>t0</code> is discarded.</p>
<p>If not, then multiply each <code>t_</code> value by the each corresponding <code>c</code> array value, and after that determine the highest value and print it.</p>
<p>For example: <code>t1</code> has <code>50,100,150,200,250</code>, all of which are equal to or below <code>300</code>, so we take <code>0*c[0] + 1*c[1] + 0*c[2]</code>, which gives us <code>585</code>. However, that isn't the highest value. The highest value is <code>1049</code>, which is acquired by <code>t5</code>. It has <code>250,300,250,200,250</code>. Taking <code>0*c[0] + 1*c[1] + 1*c[2]</code> gives <code>1049</code></p>
<p>I am stuck here.</p>
| -3
|
2016-09-05T23:29:24Z
| 39,340,214
|
<p>I guess this does what you wantâat least it produces sums from the data similar to those you mentioned in your question. I found your sample code is <em>very</em> misleading since it doesn't produce the kind of <code>t_</code> values you refer to in the written problem description below it.</p>
<pre><code>from itertools import compress
c = [416,585,464]
A0 = [100,50,200]
A1 = [100,100,200]
A2 = [100,150,100]
A3 = [100,200,0]
A4 = [100,250,0]
b = [300,300,300,300,300]
selectors = [(1, 1, 1), (0, 1, 0), (0, 0, 0), (0, 0, 1),
(1, 0, 0), (0, 1, 1), (1, 1, 0), (1, 0, 1)]
nums_limits = zip((A0, A1, A2, A3, A4), b)
maximum = None
for selector in selectors:
if all(sum(compress(nums, selector)) <= limit for nums,limit in nums_limits):
total = sum(compress(c, selector))
if maximum is None or total > maximum:
maximum = total
print(maximum) # -> 1049
</code></pre>
<p>You can replace most of that with one (longish) <a href="https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions" rel="nofollow">generator expression</a> similar to the one in <a href="http://ideone.com/38FQTM" rel="nofollow">linked code</a> in one of @Stefan Pochmann's comments, so this does exactly the same thing:</p>
<pre><code>print(max(sum(compress(c, selector)) for selector in selectors
if all(sum(compress(nums, selector)) <= limit
for nums, limit in zip((A0, A1, A2, A3, A4), b))))
</code></pre>
| 0
|
2016-09-06T03:28:13Z
|
[
"python",
"arrays",
"list"
] |
Insertion-sort error in Python
| 39,338,851
|
<p>I am trying to make an insertion sorting program that sorted a list in ascending order. I'm getting the error:</p>
<pre><code>line 16, in <module> if listNums[x] < listNums[i]:
</code></pre>
<p>For this program: </p>
<pre><code> listNums = [54, 21, 76, 43, 65, 98, 65, 32, 34, 38]
x = 1
i = 0
Copy = 0
for z in range (0, len(listNums)):
if listNums[x] < listNums[i]:
Copy = listNums[i]
listNums[i] = listNums[x]
listNums[x] = Copy
i = i + 1
x = x + 1
print(listNums)
</code></pre>
| 0
|
2016-09-05T23:46:34Z
| 39,338,863
|
<p>Chances are it's a bounds error because <code>x</code> eventually increments up to <code>len(listNums)</code> which is 1 beyond the bounds of the zero-indexed array.</p>
<p>Try only iterating through <code>range(0, len(listNums)-1)</code>.</p>
| 1
|
2016-09-05T23:49:31Z
|
[
"python",
"python-3.x",
"insertion-sort"
] |
Insertion-sort error in Python
| 39,338,851
|
<p>I am trying to make an insertion sorting program that sorted a list in ascending order. I'm getting the error:</p>
<pre><code>line 16, in <module> if listNums[x] < listNums[i]:
</code></pre>
<p>For this program: </p>
<pre><code> listNums = [54, 21, 76, 43, 65, 98, 65, 32, 34, 38]
x = 1
i = 0
Copy = 0
for z in range (0, len(listNums)):
if listNums[x] < listNums[i]:
Copy = listNums[i]
listNums[i] = listNums[x]
listNums[x] = Copy
i = i + 1
x = x + 1
print(listNums)
</code></pre>
| 0
|
2016-09-05T23:46:34Z
| 39,339,420
|
<p>I'd just like to point out that there is a better way to do it, namely</p>
<pre><code>listNums = [54, 21, 76, 43, 65, 98, 65, 32, 34, 38]
listNums.sort()
print listNums
</code></pre>
<p>which gives </p>
<pre><code>[21, 32, 34, 38, 43, 54, 65, 65, 76, 98]
=> None
</code></pre>
<p>(compiled on repl.it)</p>
<p>Hope this helps!</p>
| 0
|
2016-09-06T01:28:39Z
|
[
"python",
"python-3.x",
"insertion-sort"
] |
Insertion-sort error in Python
| 39,338,851
|
<p>I am trying to make an insertion sorting program that sorted a list in ascending order. I'm getting the error:</p>
<pre><code>line 16, in <module> if listNums[x] < listNums[i]:
</code></pre>
<p>For this program: </p>
<pre><code> listNums = [54, 21, 76, 43, 65, 98, 65, 32, 34, 38]
x = 1
i = 0
Copy = 0
for z in range (0, len(listNums)):
if listNums[x] < listNums[i]:
Copy = listNums[i]
listNums[i] = listNums[x]
listNums[x] = Copy
i = i + 1
x = x + 1
print(listNums)
</code></pre>
| 0
|
2016-09-05T23:46:34Z
| 39,363,625
|
<p>This is not an <code>insertion sort error</code>
In the last iteration i.e. len(listNums)th iteration, the value of x goes beyond the length of list that's why it gives <code>IndexError: list index out of range</code> </p>
| 0
|
2016-09-07T07:21:58Z
|
[
"python",
"python-3.x",
"insertion-sort"
] |
Parsing with multiple loops opening files
| 39,339,007
|
<p>I'm trying to count the number of lines contained by a file that looks like this:</p>
<pre><code>-StartACheck
---Lines--
-EndACheck
-StartBCheck
---Lines--
-EndBCheck
</code></pre>
<p>with this:</p>
<pre><code>count=0
z={}
for line in file:
s=re.search(r'\-+Start([A-Za-z0-9]+)Check',line)
if s:
e=s.group(1)
for line in file:
z.setdefault(e,[]).append(count)
q=re.search(r'\-+End',line)
if q:
count=0
break
for a,b in z.items():
print(a,len(b))
</code></pre>
<p>I want to basically store the number of lines present inside ACheck , BCheck etc in a dictionary but I keep getting the wrong output</p>
<p>Something like this</p>
<pre><code>A,15
B,9
</code></pre>
<p>etc</p>
<p>I found out that even though the code should work, it doesn't because of the way the file is opened. I can't change the way it is opened and was looking for an implementation that only opens the file once but counts the same things and gives the exact same output without all the added functions of the newer python version. </p>
| -1
|
2016-09-06T00:14:44Z
| 39,340,686
|
<p>This kind of problem can be resolved with a <a href="https://en.wikipedia.org/wiki/Finite-state_machine" rel="nofollow">finite state machine</a>. This is a complex matter that would need more explanation than what I could write here. You should look into it to further understand what you can do with it. </p>
<p>But first of all, I'm going to do a few presumptions:</p>
<ul>
<li>The input file doesn't have any errors</li>
<li>If you have more than one section with the same name, you want their count to be combined</li>
<li>Even though you have tagged this question python 2.7, because you are using <code>print()</code>, I'll presume you are using python 3.x</li>
</ul>
<p>Here's my suggestion:</p>
<pre><code>import re
input_filename = "/home/evens/Temporaire/StackOverflow/Input_file-39339007.txt"
matchers = {
'start_section' : re.compile(r'\-+Start([A-Za-z0-9]+)Check'),
'end_section' : re.compile(r'\-+End'),
}
inside_section = False # Am I inside a section ?
section_name = None # Which section am I in ?
tally = {} # Sums of each section
with open(input_filename) as file_read:
for line in file_read:
line_matches = {k: v.match(line) for (k, v) in matchers.items()}
if inside_section:
if line_matches['end_section']:
future_inside_section = False
else:
future_inside_section = True
if section_name in tally:
tally[section_name] += 1
else:
tally[section_name] = 1
else:
if line_matches['start_section']:
future_inside_section = True
section_name = line_matches['start_section'].group(1)
# Just before we go in the future
inside_section = future_inside_section
for (a,b) in tally.items():
print('Total of all "{}" sections: {}'.format(a, b))
</code></pre>
<p>What this code does is determine :</p>
<ul>
<li>How it should change its state (Am I going to be inside or outside a section on the next line?)</li>
<li>What else should be done:
<ul>
<li>Change the name of the section I'm in ?</li>
<li>Count this line in the present section ?</li>
</ul></li>
</ul>
<p>But even this code has its problems:</p>
<ul>
<li>It doesn't check to see if a section start has a matching section end (<code>-StartACheck</code> could be ended by <code>-EndATotallyInvalidCheck</code>)</li>
<li>It doesn't handle the case where two consecutive section starts (or ends) are detected (Error? Nested sections?)</li>
<li>It doesn't handle the case where there are lines outside a section</li>
<li>And probably other corner cases. </li>
</ul>
<p>How you want to handle these cases is up to you</p>
<p>This code could probably be further simplified but I don't want to be too complex for now.</p>
<p>Hope this helps. Don't hesitate to ask if you need further explanations.</p>
| 0
|
2016-09-06T04:31:03Z
|
[
"python",
"python-2.7"
] |
How to write large JSON data?
| 39,339,044
|
<p>I have been trying to write large amount (>800mb) of data to JSON file; I did some fair amount of trial and error to get this code:</p>
<pre><code>def write_to_cube(data):
with open('test.json') as file1:
temp_data = json.load(file1)
temp_data.update(data)
file1.close()
with open('test.json', 'w') as f:
json.dump(temp_data, f)
f.close()
</code></pre>
<p>to run it just call the function <code>write_to_cube({"some_data" = data})</code></p>
<p>Now the problem with this code is that it's fast for the small amount of data, but the problem comes when <code>test.json</code> file has more than 800mb in it. When I try to update or add data to it, it takes ages.</p>
<p>I know there are external libraries such as <code>simplejson</code> or <code>jsonpickle</code>, I am not pretty sure on how to use them.</p>
<p>Is there any other way to this problem?</p>
<p><strong>Update:</strong></p>
<p>I am not sure how this can be a duplicate, other articles say nothing about writing or updating a large JSON file, rather they say only about parsing.</p>
<p><a href="http://stackoverflow.com/questions/2400643/is-there-a-memory-efficient-and-fast-way-to-load-big-json-files-in-python">Is there a memory efficient and fast way to load big json files in python?</a></p>
<p><a href="http://stackoverflow.com/questions/10382253/reading-rather-large-json-files-in-python">Reading rather large json files in Python</a></p>
<p>None of the above resolve this question a duplicate. They don't say anything about writing or update.</p>
| 0
|
2016-09-06T00:21:56Z
| 39,340,868
|
<p>So the problem is that you have a long operation. Here are a few approaches that I usually do:</p>
<ol>
<li>Optimize the operation: This rarely works. I wouldn't recommend any superb library that would parse the json a few seconds faster</li>
<li>Change your logic: If the purpose is to save and load data, probably you would like to try something else, like storing your object into a binary file instead.</li>
<li>Threads and callback, or deferred objects in some web frameworks. In case of web applications, sometimes, the operation takes longer than a request can wait, we can do the operation in background (some cases are: zipping files, then send the zip to user's email, sending SMS by calling another third party's api...)</li>
</ol>
| 0
|
2016-09-06T04:51:10Z
|
[
"python",
"json"
] |
Is it possible write a single def for both ComboBox and RadioBox events?
| 39,339,124
|
<p>Here the code writes parts of a string selected by the user. After each event, the TextCtrl gains one more piece of the string until it's time to the user to copy the text to the clipboard. It works fine, but it's not elegant since there is too much repetition in the code.</p>
<pre><code>import wx
import pyperclip
class Ementor(wx.Frame):
def __init__(self, parent, title):
super(Ementor, self).__init__(parent, title = title,size = (500,300))
self.InitUI()
def InitUI(self):
pnl = wx.Panel(self)
menubar=wx.MenuBar()
filem=wx.Menu()
clearmenuitem = filem.Append(wx.NewId(), "Clea&r","Clear TextBox")
self.Bind(wx.EVT_MENU, self.onClear, clearmenuitem)
exitmenuitem = filem.Append(wx.NewId(), "Exi&t", "Bye bye")
self.Bind(wx.EVT_MENU, self.onExit, exitmenuitem)
editm=wx.Menu()
copymenuitem = editm.Append(wx.NewId(), "&Copy", "Copy String")
self.Bind(wx.EVT_MENU, self.onCopy, copymenuitem)
helpm=wx.Menu()
helpmenuitem = helpm.Append(wx.NewId(), "&About","Details")
self.Bind(wx.EVT_MENU, self.onHelp, helpmenuitem)
menubar.Append(filem, '&File')
menubar.Append(editm, '&Edit')
menubar.Append(helpm, '&Help')
self.SetMenuBar(menubar)
# Campos de preenchimento da ementa
lblList = ['Processo Administrativo Sancionador. ','Processo Administrativo Contencioso. ','Processo Administrativo Simplificado. ']
self.rbox = wx.RadioBox(pnl, label = 'Tipo', pos = (10,10), choices = lblList, majorDimension = 3, style = wx.RA_SPECIFY_ROWS)
self.rbox.Bind(wx.EVT_RADIOBOX,self.onRadioBox)
statusAnalise = ['Julgamento Originario. ','Julgamento Recursal. ']
self.rbox1 = wx.RadioBox(pnl, label = 'Estágio da Análise', pos = (10,120), choices=statusAnalise, majorDimension = 2, style = wx.RA_SPECIFY_ROWS)
self.rbox1.Bind(wx.EVT_RADIOBOX,self.onRadioBox1)
tipoJulgamento = ['Recurso conhecido e provido. ','Recurso conhecido e nao provido. ','Recurso nao conhecido']
self.combo = wx.ComboBox(pnl, choices=tipoJulgamento, pos=(10,200))
self.combo.Bind(wx.EVT_COMBOBOX, self.onCombo)
tipoProcedimento = ['Fiscalizacao ordinaria - PAF. ','Fiscalizacao Extraordinaria. ']
self.combo1 = wx.ComboBox(pnl, choices=tipoProcedimento, pos=(10,230))
self.combo1.Bind(wx.EVT_COMBOBOX, self.onCombo1)
#Ãrea de concatenação
self.t3 = wx.TextCtrl(pnl,pos=(310,10),size = (180,170),style = wx.TE_MULTILINE)
self.Centre()
self.Show(True)
# Funcoes para eventos
def onRadioBox(self, e):
rb = self.rbox.GetStringSelection()
**self.t3.AppendText(str(rb).upper())** #here set text to
def onRadioBox1(self, e):
rb1 = self.rbox1.GetStringSelection()
**self.t3.AppendText(str(rb1).upper())** #here
def onClear(self, e):
self.t3.SetValue('')
def onExit(self, e):
self.Destroy()
def onCopy(self, e):
pyperclip.copy(self.t3.GetValue())
def onCombo(self, e):
cbx = self.combo.GetValue()
**self.t3.AppendText(str(cbx).upper())** #here
def onCombo1(self, e):
cbx1 = self.combo1.GetValue()
**self.t3.AppendText(str(cbx1).upper())** #here
def onHelp(self, e):
msgbox = wx.MessageBox('Feito por ²David Gesrob ® 2016-09-04', 'About...', wx.ICON_INFORMATION | wx.STAY_ON_TOP)
ex = wx.App()
Ementor(None,'Ementor')
ex.MainLoop()
</code></pre>
| 0
|
2016-09-06T00:36:11Z
| 39,339,386
|
<p>You can use <code>e.GetEventObject()</code> to get access to widget which send event.</p>
<p>And then you can use <code>isinstance</code> to recognize widget type.</p>
<pre><code>def onSelect(self, e):
widget = e.GetEventObject()
if isinstance(widget, wx.RadioBox):
self.t3.AppendText(str(widget.GetStringSelection()).upper())
elif isinstance(widget, wx.ComboBox):
self.t3.AppendText(str(widget.GetValue()).upper())
</code></pre>
<p>Now you can use it with any RadioBox and ComboBox</p>
| 0
|
2016-09-06T01:20:54Z
|
[
"python",
"wxpython"
] |
pandas read_csv and keep only certain rows (python)
| 39,339,142
|
<p>I am aware of the skiprows that allows you to pass a list with the indices of the rows to skip. However, I have the index of the rows I want to keep.</p>
<p>Say that my cvs file looks like this for millions of rows:</p>
<pre><code> A B
0 1 2
1 3 4
2 5 6
3 7 8
4 9 0
</code></pre>
<p>The list of indices i would like to load are only 2,3, so</p>
<pre><code>index_list = [2,3]
</code></pre>
<p>The input for the skiprows function would be [0,1,4]. However, I only have available [2,3].</p>
<p>I am trying something like:</p>
<pre><code>pd.read_csv(path, skiprows = ~index_list)
</code></pre>
<p>but no luck.. any suggestions?</p>
<p>thank and I appreciate all the help,</p>
| 2
|
2016-09-06T00:39:34Z
| 39,339,691
|
<p>I think you would need to find the number of lines first, like <a href="http://stackoverflow.com/a/1019572/2029132">this</a>.</p>
<pre><code>num_lines = sum(1 for line in open('myfile.txt'))
</code></pre>
<p>Then you would need to delete the indices of <code>index_list</code>:</p>
<pre><code>to_exclude = [i for i in num_lines if i not in index_list]
</code></pre>
<p>and then load your data:</p>
<pre><code>pd.read_csv(path, skiprows = to_exclude)
</code></pre>
| 2
|
2016-09-06T02:14:44Z
|
[
"python",
"pandas"
] |
Get href from leftmost column in table with XPath
| 39,339,188
|
<p>I am attempted to extract <code>href</code> text from a table here: <a href="https://en.wikipedia.org/wiki/List_of_first-person_shooters" rel="nofollow">https://en.wikipedia.org/wiki/List_of_first-person_shooters</a></p>
<p>Here is the top of the table:</p>
<pre><code><table class="wikitable sortable" style="font-size: 85%; text-align: left;">
<tr style="background: #ececec">
<th>Title</th>
<th>Developer</th>
<th>Platform(s)</th>
<th>Release Date</th>
</tr>
<tr>
<th><i><a href="/wiki/007_Legends" title="007 Legends">007 Legends</a></i></th>
<td><a href="/wiki/Eurocom" title="Eurocom">Eurocom</a>, <a href="/wiki/Activision" title="Activision">Activision</a></td>
<td>PS3, X360, Wii U, WIN</td>
<td>2012-10-16</td>
</tr>
<tr>
<th><i><a href="/wiki/007:_Quantum_of_Solace" title="007: Quantum of Solace">007: Quantum of Solace</a></i></th>
<td><a href="/wiki/Treyarch" title="Treyarch">Treyarch</a>, <a href="/wiki/Beenox" title="Beenox">Beenox</a></td>
<td>DS, PS3, Wii, WIN, X360</td>
<td>2008-10-31</td>
</tr>
<tr>
<th><i><a href="/wiki/3D_Monster_Chase" title="3D Monster Chase">3D Monster Chase</a></i></th>
<td><a href="/w/index.php?title=Romik&amp;action=edit&amp;redlink=1" class="new" title="Romik (page does not exist)">Romik</a></td>
<td>AMSCPC, ZX</td>
<td>1985</td>
</tr>
</code></pre>
<p>The following XPath query obtains the href text from the table, but I only want the first column from each row. Is this possible with XPath, preferable without counters? I am using Python library <code>lxml</code>:</p>
<pre><code>tree.xpath('//table[@class="wikitable sortable"]//a/@href')
</code></pre>
<p>retrieves:</p>
<pre><code>['/wiki/007_Legends', '/wiki/Eurocom', '/wiki/Activision', '/wiki/007:_Quantum_of_Solace', '/wiki/Treyarch', '/wiki/Beenox', '/wiki/3D_Monster_Chase', '/w/index.php?title=Romik&action=edit&redlink=1', '/wiki/Ace_of_Spades_(video_game)', '/w/index.php?title=Ben_Aksoy&action=edit&redlink=1', '/wiki/Alcatraz:_Prison_Escape', '/wiki/Zombie_Studios', '/wiki/CodeRED:_Alien_Arena', '/w/index.php?title=COR_Entertainment&action=edit&redlink=1', '/wiki/FreeBSD', '/wiki/Alien_Breed_3D', '/wiki/Team17', '/wiki/Alien_Breed_3D_II:_The_Killing_Grounds', '/wiki/Team17',
</code></pre>
<p>However, I would like only the first item in each row</p>
| 2
|
2016-09-06T00:47:17Z
| 39,339,244
|
<p>Only first column use <code><th></code> and <code><i></code> so use it</p>
<pre><code>tree.xpath('//table[@class="wikitable sortable"]//th//a/@href')
</code></pre>
<p>or</p>
<pre><code>tree.xpath('//table[@class="wikitable sortable"]//i/a/@href')
</code></pre>
| -1
|
2016-09-06T00:57:51Z
|
[
"python",
"html",
"xml",
"xpath",
"lxml"
] |
Get href from leftmost column in table with XPath
| 39,339,188
|
<p>I am attempted to extract <code>href</code> text from a table here: <a href="https://en.wikipedia.org/wiki/List_of_first-person_shooters" rel="nofollow">https://en.wikipedia.org/wiki/List_of_first-person_shooters</a></p>
<p>Here is the top of the table:</p>
<pre><code><table class="wikitable sortable" style="font-size: 85%; text-align: left;">
<tr style="background: #ececec">
<th>Title</th>
<th>Developer</th>
<th>Platform(s)</th>
<th>Release Date</th>
</tr>
<tr>
<th><i><a href="/wiki/007_Legends" title="007 Legends">007 Legends</a></i></th>
<td><a href="/wiki/Eurocom" title="Eurocom">Eurocom</a>, <a href="/wiki/Activision" title="Activision">Activision</a></td>
<td>PS3, X360, Wii U, WIN</td>
<td>2012-10-16</td>
</tr>
<tr>
<th><i><a href="/wiki/007:_Quantum_of_Solace" title="007: Quantum of Solace">007: Quantum of Solace</a></i></th>
<td><a href="/wiki/Treyarch" title="Treyarch">Treyarch</a>, <a href="/wiki/Beenox" title="Beenox">Beenox</a></td>
<td>DS, PS3, Wii, WIN, X360</td>
<td>2008-10-31</td>
</tr>
<tr>
<th><i><a href="/wiki/3D_Monster_Chase" title="3D Monster Chase">3D Monster Chase</a></i></th>
<td><a href="/w/index.php?title=Romik&amp;action=edit&amp;redlink=1" class="new" title="Romik (page does not exist)">Romik</a></td>
<td>AMSCPC, ZX</td>
<td>1985</td>
</tr>
</code></pre>
<p>The following XPath query obtains the href text from the table, but I only want the first column from each row. Is this possible with XPath, preferable without counters? I am using Python library <code>lxml</code>:</p>
<pre><code>tree.xpath('//table[@class="wikitable sortable"]//a/@href')
</code></pre>
<p>retrieves:</p>
<pre><code>['/wiki/007_Legends', '/wiki/Eurocom', '/wiki/Activision', '/wiki/007:_Quantum_of_Solace', '/wiki/Treyarch', '/wiki/Beenox', '/wiki/3D_Monster_Chase', '/w/index.php?title=Romik&action=edit&redlink=1', '/wiki/Ace_of_Spades_(video_game)', '/w/index.php?title=Ben_Aksoy&action=edit&redlink=1', '/wiki/Alcatraz:_Prison_Escape', '/wiki/Zombie_Studios', '/wiki/CodeRED:_Alien_Arena', '/w/index.php?title=COR_Entertainment&action=edit&redlink=1', '/wiki/FreeBSD', '/wiki/Alien_Breed_3D', '/wiki/Team17', '/wiki/Alien_Breed_3D_II:_The_Killing_Grounds', '/wiki/Team17',
</code></pre>
<p>However, I would like only the first item in each row</p>
| 2
|
2016-09-06T00:47:17Z
| 39,339,558
|
<blockquote>
<p>I only want the first column from each row</p>
</blockquote>
<p>This XPath,</p>
<pre><code> //table[@class="wikitable sortable"]//tr/*[1]//a/@href
</code></pre>
<p>will select only the <code>a/@href</code> found in the first column of each <code>tr</code>:</p>
<pre><code>/wiki/007_Legends
/wiki/007:_Quantum_of_Solace
/wiki/3D_Monster_Chase
</code></pre>
<p>regardless of whether the first column is a <code>td</code> or <code>th</code>.</p>
<p>If you're only interested in the <code>td</code> entries, then you can replace the <code>*</code> with <code>td</code>,</p>
<pre><code>//table[@class="wikitable sortable"]//tr/td[1]//a/@href
</code></pre>
<p>then you'll select the <code>a/@href</code> attributes with these values:</p>
<pre><code>/wiki/Eurocom
/wiki/Activision
/wiki/Treyarch
/wiki/Beenox
/w/index.php?title=Romik&action=edit&redlink=1
</code></pre>
| 1
|
2016-09-06T01:53:33Z
|
[
"python",
"html",
"xml",
"xpath",
"lxml"
] |
Difference between self.request and request in Django class-based view
| 39,339,221
|
<p>In django, for class-based view like <code>ListView</code> and <code>DetailView</code>, methods like <code>get()</code> or <code>post()</code> or other functions defined by developer take parameters include <code>self</code> and <code>request</code>. I learnt that in <code>self</code> these is actually a <code>self.request</code> field, so wha's the difference between <code>self.request</code> and <code>request</code>? </p>
<p>Example, this is the function in a class based view and used to handle user's login requirement:</p>
<pre><code>def login(self, request):
name = request.POST['name']
pwd = request.POST['password']
user = authenticate(username=name, password=pwd)
if user is not None:
request.session.set_expiry(0)
login(request, user)
log_message = 'Login successfully.'
else:
log_message = 'Fail to login.'
return HttpResponseRedirect(reverse('blog:testindex'))
</code></pre>
<p>This is the function used to handle user's register:</p>
<pre><code>def register(self, request):
user_name = self.request.POST['username']
firstname = self.request.POST['firstname']
lastname = self.request.POST['lastname']
pwd = self.request.POST['password']
e_mail = self.request.POST['email']
user = User.objects.create(username=user_name, first_name=firstname, last_name=lastname, email=e_mail)
user.set_password(pwd)
try:
user.save()
user = authenticate(username=user_name, password=pwd)
login(self.request, user)
except Exception:
pass
else:
return HttpResponseRedirect(reverse('blog:testindex'))
</code></pre>
<p>In the first function, it used data stored in <code>request</code> and in the second one, it used <code>self.request</code>, both work functionally. What's the difference?</p>
<p>Thanks for your answers.</p>
| 3
|
2016-09-06T00:52:41Z
| 39,340,089
|
<p>For a subclass of <code>View</code>, they're the same object. <code>self.request = request</code> is set in <code>view</code> function that <code>as_view()</code> returns. I looked into the history, but only found setting <code>self.request</code> and then immediately passing request into the view function.</p>
| 0
|
2016-09-06T03:11:32Z
|
[
"python",
"django"
] |
Django passing a variable to Httpresponseredirect throws exception
| 39,339,237
|
<p>The problem I Have right now is that I get a :</p>
<p>Reverse for 'documentation' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []</p>
<p>when I try to redirect to another view using HttpResponseRedirect</p>
<p>Here is my urls.py</p>
<pre><code> url(r'^documentation/([0-9])/$', views.documents, name='documentation'),
</code></pre>
<p>here my views.py</p>
<pre><code>def view1(request):
if request.method == 'POST':
profe = request.POST.get('value')
a = value.encode('ascii', 'ignore')
b = int(a)
return HttpResponseRedirect(reverse('documentation', args=(b,)))
else:
return render(request, "anhtml.html", info)
def documents(request,valor):
...something...
return render(request, "anotherhtml.html", ..something..)
</code></pre>
<p>Thanks</p>
<p>template (anhtml.html)</p>
<pre><code>...
<form method="POST" action="">
{% csrf_token %}
{% for p in ps %}
<tr>
<td><button id="boton1" button type="submit" name = "valor" value ="{{p.idp}}" class="btn btn-success btn-sm">{{p.nombre}} {{p.apellido}}</button>
</td>
<td>algo</a> </td>
</tr>
{%endfor%}
</form>
</code></pre>
| 0
|
2016-09-06T00:56:22Z
| 39,339,361
|
<p>I think the problem is not with the HttpResponseRedirect, but with the call to reverse().</p>
<p>When you pass args, you should use the list notation for the values:</p>
<pre><code>return HttpResponseRedirect(reverse('documentation', args=[b]))
</code></pre>
<p>That should help, at least.</p>
| 0
|
2016-09-06T01:17:26Z
|
[
"python",
"django"
] |
What data structure should I use to process large amounts of text data?
| 39,339,357
|
<p>I'm trying to do some text classication using scikit-learn's TfidfVectorizer and the Nearest Neighbor algorithm.</p>
<p>I need to find similarity metrics between two data sets containing 18000 entries each. I'm unsure about what data structure can be best used to calculate what I think should be 18000*18000 similarity metrics.</p>
<p>I've only considered DataFrames so far.</p>
| -1
|
2016-09-06T01:16:48Z
| 39,339,780
|
<p>If you don't need any intermediate data for further analyses you can use a generator to hold your data points then run the algorithms through generators calls. Otherwise you'd probably want a list.</p>
| 0
|
2016-09-06T02:29:29Z
|
[
"python",
"numpy",
"scikit-learn",
"text-processing"
] |
Grok learning python programming
| 39,339,374
|
<p>I am wondering how to solve this problem:</p>
<p>You are curious about the most popular and least popular colours of cars and decide to write a program to calculate the frequency of car colours.</p>
<p>Your program should read in the colour of each car until a blank line is entered, and then print out (in any order) all the different colours of car with counts.</p>
<p>For example:</p>
<pre><code>Car: red
Car: white
Car: blue
Car: green
Car: white
Car: silver
Car:
Cars that are green: 1
Cars that are silver: 1
Cars that are red: 1
Cars that are white: 2
Cars that are blue: 1
</code></pre>
<p>â
Here is another example:</p>
<pre><code>Car: red
Car: white
Car: white
Car: red
Car: white
Car: white
Car: white
Car:
Cars that are red: 2
Cars that are white: 5
</code></pre>
| -4
|
2016-09-06T01:19:47Z
| 39,339,438
|
<p>You have to call <code>input</code> multiple times with a sentinel value, then count the objects, then iterate over the keys and values, and then print a formatted string for each count. Reasonably straightforward with one line of code:</p>
<pre><code>print(*('Cars that are {}: {}'.format(*item) for item in __import__('collections').Counter(iter(lambda: input('Car: '), '')).items()), sep='\n')
</code></pre>
| 0
|
2016-09-06T01:32:54Z
|
[
"python"
] |
Iterate through the rows of a dataframe and reassign minimum values by group
| 39,339,401
|
<p>I am working with a dataframe that looks like this.</p>
<pre><code> id time diff
0 0 34 nan
1 0 36 2
2 1 43 7
3 1 55 12
4 1 59 4
5 2 2 -57
6 2 10 8
</code></pre>
<p>What is an efficient way find the minimum values for 'time' by id, then set 'diff' to nan at those minimum values. I am looking for a solution that results in:</p>
<pre><code> id time diff
0 0 34 nan
1 0 36 2
2 1 43 nan
3 1 55 12
4 1 59 4
5 2 2 nan
6 2 10 8
</code></pre>
| 4
|
2016-09-06T01:24:38Z
| 39,339,552
|
<p>You can group the time by id and calculate a logical vector where if the time is minimum within the group, the value is True, else False, and use the logical vector to assign <code>NaN</code> to the corresponding rows:</p>
<pre><code>import numpy as np
import pandas as pd
df.loc[df.groupby('id')['time'].apply(lambda g: g == min(g)), "diff"] = np.nan
df
# id time diff
#0 0 34 NaN
#1 0 36 2.0
#2 1 43 NaN
#3 1 55 12.0
#4 1 59 4.0
#5 2 2 NaN
#6 2 10 8.0
</code></pre>
| 4
|
2016-09-06T01:52:43Z
|
[
"python",
"pandas"
] |
Iterate through the rows of a dataframe and reassign minimum values by group
| 39,339,401
|
<p>I am working with a dataframe that looks like this.</p>
<pre><code> id time diff
0 0 34 nan
1 0 36 2
2 1 43 7
3 1 55 12
4 1 59 4
5 2 2 -57
6 2 10 8
</code></pre>
<p>What is an efficient way find the minimum values for 'time' by id, then set 'diff' to nan at those minimum values. I am looking for a solution that results in:</p>
<pre><code> id time diff
0 0 34 nan
1 0 36 2
2 1 43 nan
3 1 55 12
4 1 59 4
5 2 2 nan
6 2 10 8
</code></pre>
| 4
|
2016-09-06T01:24:38Z
| 39,339,583
|
<p><code>groupby('id')</code> and use <code>idxmin</code> to find the location of minimum values of <code>'time'</code>. Finally, use <code>loc</code> to assign <code>np.nan</code></p>
<pre><code>df.loc[df.groupby('id').time.idxmin(), 'diff'] = np.nan
df
</code></pre>
<p><a href="http://i.stack.imgur.com/qsTwZ.png"><img src="http://i.stack.imgur.com/qsTwZ.png" alt="enter image description here"></a></p>
| 6
|
2016-09-06T01:57:03Z
|
[
"python",
"pandas"
] |
Start inner loop from position of the outer
| 39,339,476
|
<p>In my example I have two loops. One nested within the other. Is there a way I can start the inner loop from the index of the outer. Here is pseudo code. </p>
<pre><code>arrayOfWords = ["one","two","five"]
arrayOfWords2 = ["one","two","three","four","five"]
tottalWordlist = []
for index, jString in enumerate(arrayOfWords):
gWord = arrayOfWords[index]
indexClone = index
arrayOfWords2Count = range(len(arrayOfWords2)-1)
for indexClone in arrayOfWords2Count:
if gWord == arrayOfWords2[indexClone]:
tottalWordlist.append(gWord)
break
</code></pre>
| 0
|
2016-09-06T01:40:25Z
| 39,339,509
|
<p>You're almost there. You just need to add the starting index to the <code>range</code> object.</p>
<pre><code>arrayOfWords2Count = range(indexClone, len(arrayOfWords2))
for i in arrayOfWords2Count:
if gWord == arrayOfWords2[i]:
</code></pre>
<p>Also, you don't need to subtract one from the endpoint, as that end is exclusive.</p>
| 4
|
2016-09-06T01:45:07Z
|
[
"python"
] |
Start inner loop from position of the outer
| 39,339,476
|
<p>In my example I have two loops. One nested within the other. Is there a way I can start the inner loop from the index of the outer. Here is pseudo code. </p>
<pre><code>arrayOfWords = ["one","two","five"]
arrayOfWords2 = ["one","two","three","four","five"]
tottalWordlist = []
for index, jString in enumerate(arrayOfWords):
gWord = arrayOfWords[index]
indexClone = index
arrayOfWords2Count = range(len(arrayOfWords2)-1)
for indexClone in arrayOfWords2Count:
if gWord == arrayOfWords2[indexClone]:
tottalWordlist.append(gWord)
break
</code></pre>
| 0
|
2016-09-06T01:40:25Z
| 39,339,590
|
<p>in my understanding, you are looking for whether outer list's element in inner list begin with outer element's index.</p>
<pre><code>arrayOfWords = ["one","two","five"]
arrayOfWords2 = ["one","two","three","four","five"]
print [ item for i,item in enumerate(arrayOfWords) if item in arrayOfWords2[i:] ]
['one', 'two', 'five']
</code></pre>
| 2
|
2016-09-06T01:57:44Z
|
[
"python"
] |
The right syntax to use near '''?
| 39,339,512
|
<p>I am running a Python bot which connects to a SQL database and updates values in tables.</p>
<p>I have the following code:</p>
<p><code>mycursor.execute("SELECT * FROM reputation WHERE username = '" + str(critiquer) + "'")</code></p>
<p>I am receiving the error "...check the manual that corresponds to your MySQL server version for the right syntax to use near ''' at line 1"</p>
<p>I've done some debugging and there is no problem with the string "critiquer," and the row exists in the table.</p>
<p>Would appreciate some insight into this problem.</p>
| -2
|
2016-09-06T01:45:17Z
| 39,339,561
|
<p>Try using a parametrized query:</p>
<pre><code>mycursor.execute("SELECT * FROM reputation WHERE username = '?'", critiquer)
</code></pre>
| 1
|
2016-09-06T01:54:22Z
|
[
"python",
"mysql"
] |
How to transform several lists of words to a pandas dataframe?
| 39,339,560
|
<p>I have file .txt that contains a list of words like this:</p>
<pre><code>5.91686268506 exclusively, catering, provides, arms, georgia, formal, purchase, choose
5.91560417296 hugh, senlis
5.91527936181 italians
5.91470429433 soil, cultivation, fertile
5.91468087491 increases, moderation
....
5.91440227412 farmers, descendants
</code></pre>
<p>I would like to transform such data into a pandas table that I expect to show into a html/bootstrap template as follows (*):</p>
<pre><code>COL_A COL_B
5.91686268506 exclusively, catering, provides, arms, georgia, formal, purchase, choose
5.91560417296 hugh, senlis
5.91527936181 italians
5.91470429433 soil, cultivation, fertile
5.91468087491 increases, moderation
....
5.91440227412 farmers, descendants
</code></pre>
<p>So I tried the following with pandas:</p>
<pre><code>import pandas as pd
df = pd.read_csv('file.csv',
sep = ' ', names=['Col_A', 'Col_B'])
df.head(20)
</code></pre>
<p>However, my table doesnt have the above desired sructure:</p>
<pre><code> COL_A COL_B
6.281426 engaged, chance, makes, meeting, nations, things, believe, tries, believing, knocked, admits, awkward
6.277438 sweden NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
6.271190 artificial, ammonium NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
6.259790 boats, prefix NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
6.230612 targets, tactical, wing, missile, squadrons NaN NaN NaN NaN NaN NaN NaN
</code></pre>
<p>Any idea of how to get the data as the (*) tabular format?</p>
| 2
|
2016-09-06T01:54:02Z
| 39,339,609
|
<p>Because you have space between words and if you specify space as delimiter, it will naturally separate them. To get what you need, you can try to set the <code>sep</code> as a regular expression <code>(?<!,)</code>, <code>?<!</code> is a negative look behind syntax, which means separate on space only when it is not preceded by a comma and it should work for your case:</p>
<pre><code>pd.read_csv("~/test.csv", sep = "(?<!,) ", names=['weight', 'topics'])
# weight topics
#0 5.916863 exclusively, catering, provides, arms, georgia...
#1 5.915604 hugh, senlis
#2 5.915279 italians
#3 5.914704 soil, cultivation, fertile
#4 5.914681 increases, moderation
#5 5.914402 farmers, descendants
</code></pre>
| 6
|
2016-09-06T02:00:10Z
|
[
"python",
"python-3.x",
"csv",
"pandas"
] |
Django custom context_processors in render_to_string method
| 39,339,569
|
<p>I'm building a function to send email and I need to use a context_processor variable inside the HTML template of the email, but this don't work.</p>
<p>Example:</p>
<pre><code>def send_email(plain_body_template_name, html_body_template_name):
plain_body = loader.render_to_string(plain_body_template_name, context)
html_body = loader.render_to_string(html_body_template_name, context)
email_msg = EmailMultiAlternatives(body=plain_body)
email_msg.attach_alternative(html_body, 'text/html')
email_message.send()
</code></pre>
<p>In my custom <code>context_processor.py</code> I just have a function that receive a <code>HttpRequest</code> and return a dict like <code>{'foo': 'bar'}</code>, and in the template I try to render using <code>{{foo}}</code>.</p>
<p>I added the context_processor in the <code>TEMPLATE['OPTIONS']['context_processors']</code> too.</p>
| 0
|
2016-09-06T01:55:24Z
| 39,340,015
|
<p>Assuming you're using the <code>django</code> backend in your <code>TEMPLATE</code> with</p>
<p><code>'BACKEND': 'django.template.backends.django.DjangoTemplates',
</code></p>
<p>django is seeing that you haven't passed in a request and opting for a basic <code>Context</code> to wrap your dict instead of a <code>RequestContext</code> which will handle the <code>context_processors</code> you've defined. </p>
<p>You can probably get away with doing</p>
<p><code>html_body = loader.render_to_string(html_body_template_name, context, request=request)
</code></p>
<p>but you'd need to pass in the request object.</p>
<p>This might not make sense though. Are you emailing the person making the request? Does the context make sense to include? </p>
<p>If your context processor doesn't need the <code>request</code> then I'd either make it a simple utility function (if it's only called here) or make the request parameter optional, import it into this module, and add it directly into the context</p>
<p><code>context = {"my_var": 1}
context.update(your_extra_context())
loader.render_to_string(...)
</code></p>
<p>There are some complicated ways of updating a <code>Context()</code> in layers, but I don't think that's necessary here.</p>
| 1
|
2016-09-06T03:02:31Z
|
[
"python",
"django"
] |
Why am I getting the following error: NameError: name 'models' is not defined
| 39,339,593
|
<p>Whenever I run the program, I get the following error:</p>
<pre><code>NameError at /table/
name 'models' is not defined
</code></pre>
<p>It says that there's an error on line 4 in my views. </p>
<p>Here is my views.py:</p>
<pre><code>from django.shortcuts import render
def display(request):
return render(request, 'template.tmpl', {'obj': models.Book.objects.all()})
</code></pre>
<p>Here is my models.py:</p>
<pre><code>from django.db import models
class Book(models.Model):
author = models.CharField(max_length = 20)
title = models.CharField(max_length = 40)
publication_year = models.IntegerField()
</code></pre>
<p>Here is my urls.py:</p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
# /table/
url(r'^$', views.display, name='display'),
]
</code></pre>
<p>Can somebody please tell me what is wrong?</p>
| -1
|
2016-09-06T01:57:55Z
| 39,339,611
|
<p>You are referencing <code>models.Book</code> in your view, but you have not imported <code>models</code>. In your views.py you need to do <code>from myapp import models</code>. Or you can do <code>from myapp.models import Book</code> and change it in your view function to just <code>Book.objects.all()</code>.</p>
| 4
|
2016-09-06T02:00:45Z
|
[
"python",
"django"
] |
Removing "\n"s when printing sentences from text file in python?
| 39,339,621
|
<p>I am trying to print a list of sentences from a text file (one of the Project Gutenberg eBooks). When I print the file as a single string string it looks fine:</p>
<pre><code>file = open('11.txt','r+')
alice = file.read()
print(alice[:500])
</code></pre>
<p>Output is:</p>
<pre><code>ALICE'S ADVENTURES IN WONDERLAND
Lewis Carroll
THE MILLENNIUM FULCRUM EDITION 3.0
CHAPTER I. Down the Rabbit-Hole
Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, 'and what is the use of a book,' thought Alice 'without pictures or
conversations?'
So she was considering in her own mind (as well as she could, for the
hot d
</code></pre>
<p>Now, when I split it into sentences (The assignment was specifically to do this by "splitting at the periods," so it's a very simplified split), I get this:</p>
<pre><code>>>> print(sentences[:5])
["ALICE'S ADVENTURES IN WONDERLAND\n\nLewis Carroll\n\nTHE MILLENNIUM FULCRUM EDITION 3", '0\n\n\n\n\nCHAPTER I', " Down the Rabbit-Hole\n\nAlice was beginning to get very tired of sitting by her sister on the\nbank, and of having nothing to do: once or twice she had peeped into the\nbook her sister was reading, but it had no pictures or conversations in\nit, 'and what is the use of a book,' thought Alice 'without pictures or\nconversations?'\n\nSo she was considering in her own mind (as well as she could, for the\nhot day made her feel very sleepy and stupid), whether the pleasure\nof making a daisy-chain would be worth the trouble of getting up and\npicking the daisies, when suddenly a White Rabbit with pink eyes ran\nclose by her", "\n\nThere was nothing so VERY remarkable in that; nor did Alice think it so\nVERY much out of the way to hear the Rabbit say to itself, 'Oh dear!\nOh dear! I shall be late!' (when she thought it over afterwards, it\noccurred to her that she ought to have wondered at this, but at the time\nit all seemed quite natural); but when the Rabbit actually TOOK A WATCH\nOUT OF ITS WAISTCOAT-POCKET, and looked at it, and then hurried on,\nAlice started to her feet, for it flashed across her mind that she had\nnever before seen a rabbit with either a waistcoat-pocket, or a watch\nto take out of it, and burning with curiosity, she ran across the field\nafter it, and fortunately was just in time to see it pop down a large\nrabbit-hole under the hedge", '\n\nIn another moment down went Alice after it, never once considering how\nin the world she was to get out again']
</code></pre>
<p>Where do the extra "\n" characters come from and how can I remove them?</p>
| -1
|
2016-09-06T02:01:53Z
| 39,339,657
|
<p>The <code>\n</code>, or newline, characters come from the blank lines in the file. They are an escape character that basically acts like a hit on the 'return' key. On the first line, it ends with a <code>\n</code> character, and next line also ends in a <code>\n</code>.</p>
<p>To remove them what you can do is loop over the list and replace every element's <code>\n</code> with <code>''</code>:</p>
<pre><code>x = ["test\n\n","test\n"]
for index, element in enumerate(x):
x[index] = x[index].replace("\n", "")
print(x)
</code></pre>
<p>Where <code>x</code> is your list. This now loops and replaces all newlines with empty strings. The output is:</p>
<pre><code>["test", "test"]
</code></pre>
<p>You can create a function like so:</p>
<pre><code>def replace_newlines(list):
for index, element in enumerate(list):
list[index] = list[index].replace("\n", "")
return list
</code></pre>
<p>Now you can do:</p>
<pre><code>print(replace_newlines(sentences))
</code></pre>
| 0
|
2016-09-06T02:08:27Z
|
[
"python",
"split",
"format",
"sentence"
] |
Removing "\n"s when printing sentences from text file in python?
| 39,339,621
|
<p>I am trying to print a list of sentences from a text file (one of the Project Gutenberg eBooks). When I print the file as a single string string it looks fine:</p>
<pre><code>file = open('11.txt','r+')
alice = file.read()
print(alice[:500])
</code></pre>
<p>Output is:</p>
<pre><code>ALICE'S ADVENTURES IN WONDERLAND
Lewis Carroll
THE MILLENNIUM FULCRUM EDITION 3.0
CHAPTER I. Down the Rabbit-Hole
Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, 'and what is the use of a book,' thought Alice 'without pictures or
conversations?'
So she was considering in her own mind (as well as she could, for the
hot d
</code></pre>
<p>Now, when I split it into sentences (The assignment was specifically to do this by "splitting at the periods," so it's a very simplified split), I get this:</p>
<pre><code>>>> print(sentences[:5])
["ALICE'S ADVENTURES IN WONDERLAND\n\nLewis Carroll\n\nTHE MILLENNIUM FULCRUM EDITION 3", '0\n\n\n\n\nCHAPTER I', " Down the Rabbit-Hole\n\nAlice was beginning to get very tired of sitting by her sister on the\nbank, and of having nothing to do: once or twice she had peeped into the\nbook her sister was reading, but it had no pictures or conversations in\nit, 'and what is the use of a book,' thought Alice 'without pictures or\nconversations?'\n\nSo she was considering in her own mind (as well as she could, for the\nhot day made her feel very sleepy and stupid), whether the pleasure\nof making a daisy-chain would be worth the trouble of getting up and\npicking the daisies, when suddenly a White Rabbit with pink eyes ran\nclose by her", "\n\nThere was nothing so VERY remarkable in that; nor did Alice think it so\nVERY much out of the way to hear the Rabbit say to itself, 'Oh dear!\nOh dear! I shall be late!' (when she thought it over afterwards, it\noccurred to her that she ought to have wondered at this, but at the time\nit all seemed quite natural); but when the Rabbit actually TOOK A WATCH\nOUT OF ITS WAISTCOAT-POCKET, and looked at it, and then hurried on,\nAlice started to her feet, for it flashed across her mind that she had\nnever before seen a rabbit with either a waistcoat-pocket, or a watch\nto take out of it, and burning with curiosity, she ran across the field\nafter it, and fortunately was just in time to see it pop down a large\nrabbit-hole under the hedge", '\n\nIn another moment down went Alice after it, never once considering how\nin the world she was to get out again']
</code></pre>
<p>Where do the extra "\n" characters come from and how can I remove them?</p>
| -1
|
2016-09-06T02:01:53Z
| 39,339,696
|
<p>You may not want to use regex, but I would do:</p>
<pre><code>import re
new_sentences = []
for s in sentences:
new_sentences.append(re.sub(r'\n{2,}', '\n', s))
</code></pre>
<p>This should replace all instances of two or more <code>'\n'</code> with a single newline, so you still have newlines, but don't have "extra" newlines. </p>
<p>If you want to avoid creating a new list, and instead modify the existing one (credit to @gavriel and Andrew L.: I hadn't thought of using enumerate when I first posted my answer):</p>
<pre><code>import re
for i, s in enumerate(sentences):
sentences[i] = re.sub(r'\n{2,}', '\n', s)
</code></pre>
<p>The extra newlines aren't really extra, by which I mean they are meant to be there and are visible in the text in your question: the more <code>'\n'</code> there are, the more space there is visible between the lines of text (i.e., one between the chapter heading and the first paragraph, and many between the edition and the chapter heading. </p>
| 2
|
2016-09-06T02:16:28Z
|
[
"python",
"split",
"format",
"sentence"
] |
Removing "\n"s when printing sentences from text file in python?
| 39,339,621
|
<p>I am trying to print a list of sentences from a text file (one of the Project Gutenberg eBooks). When I print the file as a single string string it looks fine:</p>
<pre><code>file = open('11.txt','r+')
alice = file.read()
print(alice[:500])
</code></pre>
<p>Output is:</p>
<pre><code>ALICE'S ADVENTURES IN WONDERLAND
Lewis Carroll
THE MILLENNIUM FULCRUM EDITION 3.0
CHAPTER I. Down the Rabbit-Hole
Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, 'and what is the use of a book,' thought Alice 'without pictures or
conversations?'
So she was considering in her own mind (as well as she could, for the
hot d
</code></pre>
<p>Now, when I split it into sentences (The assignment was specifically to do this by "splitting at the periods," so it's a very simplified split), I get this:</p>
<pre><code>>>> print(sentences[:5])
["ALICE'S ADVENTURES IN WONDERLAND\n\nLewis Carroll\n\nTHE MILLENNIUM FULCRUM EDITION 3", '0\n\n\n\n\nCHAPTER I', " Down the Rabbit-Hole\n\nAlice was beginning to get very tired of sitting by her sister on the\nbank, and of having nothing to do: once or twice she had peeped into the\nbook her sister was reading, but it had no pictures or conversations in\nit, 'and what is the use of a book,' thought Alice 'without pictures or\nconversations?'\n\nSo she was considering in her own mind (as well as she could, for the\nhot day made her feel very sleepy and stupid), whether the pleasure\nof making a daisy-chain would be worth the trouble of getting up and\npicking the daisies, when suddenly a White Rabbit with pink eyes ran\nclose by her", "\n\nThere was nothing so VERY remarkable in that; nor did Alice think it so\nVERY much out of the way to hear the Rabbit say to itself, 'Oh dear!\nOh dear! I shall be late!' (when she thought it over afterwards, it\noccurred to her that she ought to have wondered at this, but at the time\nit all seemed quite natural); but when the Rabbit actually TOOK A WATCH\nOUT OF ITS WAISTCOAT-POCKET, and looked at it, and then hurried on,\nAlice started to her feet, for it flashed across her mind that she had\nnever before seen a rabbit with either a waistcoat-pocket, or a watch\nto take out of it, and burning with curiosity, she ran across the field\nafter it, and fortunately was just in time to see it pop down a large\nrabbit-hole under the hedge", '\n\nIn another moment down went Alice after it, never once considering how\nin the world she was to get out again']
</code></pre>
<p>Where do the extra "\n" characters come from and how can I remove them?</p>
| -1
|
2016-09-06T02:01:53Z
| 39,339,706
|
<p>You'll understand where the <code>\n</code> characters come from with this little example:</p>
<pre><code>alice = """ALICE'S ADVENTURES IN WONDERLAND
Lewis Carroll
THE MILLENNIUM FULCRUM EDITION 3.0
CHAPTER I. Down the Rabbit-Hole
Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, 'and what is the use of a book,' thought Alice 'without pictures or
conversations?'
So she was considering in her own mind (as well as she could, for the
hot d"""
print len(alice.split("."))
print len(alice.split("\n"))
</code></pre>
<p>It all depends the way you're splitting your text, the above example will give this output:</p>
<pre><code>3
19
</code></pre>
<p>Which means there are 3 substrings if you were to split the text using <code>.</code> or 19 substrings if you splitted using <code>\n</code> as separator. You can read more about <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow">str.split</a></p>
<p>In your case you've splitted your text using <code>.</code>, so the 3 substrings will contain multiple newlines characters <code>\n</code>, to get rid of them you can either split these substrings again or just get rid of them using <a href="https://docs.python.org/2/library/string.html#string.replace" rel="nofollow">str.replace</a></p>
| 1
|
2016-09-06T02:17:46Z
|
[
"python",
"split",
"format",
"sentence"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.