title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
How to get the max/min value in Pandas DataFrame when nan value in it | 38,508,294 | <p>Since one column of my pandas dataframe has <code>nan</code> value, so when I want to get the max value of that column, it just return error. </p>
<pre><code>>>> df.iloc[:, 1].max()
'error:512'
</code></pre>
<p>How can I skip that <code>nan</code> value and get the max value of that column?</p>
| 2 | 2016-07-21T15:26:32Z | 38,515,089 | <p>When the df contains <code>NaN</code> values it reports <code>NaN</code> values, Using
<code>np.nanmax(df.values)</code> gave the desired answer.</p>
| 0 | 2016-07-21T22:02:54Z | [
"python",
"pandas"
] |
Put Header with Python - docx | 38,508,320 | <p>I am using Python-docx to create and write a Word document.</p>
<p>How i can put a text in document header using python-docx?</p>
<p><a href="http://image.prntscr.com/image/8757b4e6d6f545a5ab6a08a161e4c55e.png" rel="nofollow">http://image.prntscr.com/image/8757b4e6d6f545a5ab6a08a161e4c55e.png</a></p>
<p>Thanks</p>
| 0 | 2016-07-21T15:27:40Z | 38,508,977 | <p>You can use header.text like</p>
<pre><code>header = section.header
header.text = 'foobar'
</code></pre>
<p>see <a href="http://python-docx.readthedocs.io/en/latest/dev/analysis/features/header.html?highlight=header" rel="nofollow">http://python-docx.readthedocs.io/en/latest/dev/analysis/features/header.html?highlight=header</a> for more information</p>
| 1 | 2016-07-21T15:58:58Z | [
"python",
"python-2.7",
"python-docx"
] |
Put Header with Python - docx | 38,508,320 | <p>I am using Python-docx to create and write a Word document.</p>
<p>How i can put a text in document header using python-docx?</p>
<p><a href="http://image.prntscr.com/image/8757b4e6d6f545a5ab6a08a161e4c55e.png" rel="nofollow">http://image.prntscr.com/image/8757b4e6d6f545a5ab6a08a161e4c55e.png</a></p>
<p>Thanks</p>
| 0 | 2016-07-21T15:27:40Z | 38,515,968 | <p>Unfortunately this feature is not implemented yet. The page @SamRogers linked to is part of the enhancement proposal (aka. "analysis page"). The implementation is in progress however, by @eupharis, so might be available in a month or so. The ongoing pull request is here if you want to follow it. <a href="https://github.com/python-openxml/python-docx/pull/291" rel="nofollow">https://github.com/python-openxml/python-docx/pull/291</a></p>
| 1 | 2016-07-21T23:31:37Z | [
"python",
"python-2.7",
"python-docx"
] |
Equalivent of Qt.setGeometry() in tkinter | 38,508,348 | <p>What is the equal function of PyQt <code>setGeometry()</code> in tkinter? Or Is there any function works like that? I searched a bit but couldn't find, all of examples looks like tkinter works on a specific widget and we just can set width-height.</p>
<p><a href="http://zetcode.com/gui/pyqt4/firstprograms/" rel="nofollow"><strong>EDIT</strong></a>:</p>
<blockquote>
<p>The <code>setGeometry()</code> does two things. It locates the window on the
screen and sets its size. The first two parameters are the <strong>x</strong> and <strong>y</strong>
positions of the window. The third is the width and the fourth is the
height of the window.</p>
</blockquote>
| 0 | 2016-07-21T15:28:36Z | 38,509,359 | <p>The nearest thing tkinter has is probably the <a href="http://effbot.org/tkinterbook/place.htm" rel="nofollow">place</a> geometry manager. With it you can set the x,y coordinates (either absolute or relative) and the width and height attributes (also absolute or relative).</p>
<p>For example, to place a label at 100,100 and with a width and height 50% of its parent you would do something like this:</p>
<pre><code>import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Hello, world")
label.place(x=100, y=100, relwidth=.5, relheight=.5)
root.mainloop()
</code></pre>
<p>However, place is very rarely the right choice. Tkinter is very smart about picking the right size for widgets, and for laying them out. Without knowing the actual problem you're trying to solve it's hard to give good recommendations, but almost certainly, <a href="http://effbot.org/tkinterbook/pack.htm" rel="nofollow">pack</a> or <a href="http://effbot.org/tkinterbook/grid.htm" rel="nofollow">grid</a> will work better.</p>
| 1 | 2016-07-21T16:16:05Z | [
"python",
"tkinter",
"pyqt4",
"python-3.4",
"pyqt5"
] |
Equalivent of Qt.setGeometry() in tkinter | 38,508,348 | <p>What is the equal function of PyQt <code>setGeometry()</code> in tkinter? Or Is there any function works like that? I searched a bit but couldn't find, all of examples looks like tkinter works on a specific widget and we just can set width-height.</p>
<p><a href="http://zetcode.com/gui/pyqt4/firstprograms/" rel="nofollow"><strong>EDIT</strong></a>:</p>
<blockquote>
<p>The <code>setGeometry()</code> does two things. It locates the window on the
screen and sets its size. The first two parameters are the <strong>x</strong> and <strong>y</strong>
positions of the window. The third is the width and the fourth is the
height of the window.</p>
</blockquote>
| 0 | 2016-07-21T15:28:36Z | 38,509,811 | <p>You can also do something similar to @BryanOakley's answer by the <code>grid</code> geometry manager:<br></p>
<pre><code>from tkinter import *
root = Tk()
label = Label(root, bg='cyan')
label.grid(ipadx=100, ipady=50, padx=50, pady=50)
</code></pre>
<p><b>UPDATE:</b> Please feedback why you think this answer is not useful.</p>
| 0 | 2016-07-21T16:39:00Z | [
"python",
"tkinter",
"pyqt4",
"python-3.4",
"pyqt5"
] |
Getting last change time in Python on Windows | 38,508,351 | <p>I have two scripts, one in Python, one in Powershell, that get and compare the last modification of a file. The one in Powershell uses:</p>
<pre><code>$t = $f.LastWriteTime.ToFileTimeUtc()
</code></pre>
<p>This time is primary for me and I need to get the same information in Python. I am using <code>os.stat</code> and convert the UNIX timestamp to 'Windows File Time'* using this formula:</p>
<pre><code>statinfo = os.stat(file_name)
t = long(statinfo.st_mtime * 10000000L) + 11644473600L * 10000000L
</code></pre>
<p>However, I run into problems with rounding errors. <code>st_mtime</code> is a float and when I multiply it and cast to long, I am losing precision -- typically the error is less than 10 (i.e. less then 1 millisecond). I can of course fix my program so that it compares the numbers within this precision, but I would much rather have the same numbers.</p>
<p>There is a similar question on SO here: <a href="http://stackoverflow.com/questions/27534448/how-do-i-get-change-file-time-in-windows">How do I get *change* file time in Windows?</a> from which I gather I would have to access the structure FILE_BASIC_INFORMATION (<a href="http://msdn.microsoft.com/en-us/library/windows/hardware/ff545762(v=vs.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/windows/hardware/ff545762(v=vs.85).aspx</a>), however I am not sure how to do it without using IronPython, PyWin or similar Python extensions. Is there an easy way (maybe using <code>ctypes</code>) to access this information?</p>
<p>*A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). See <a href="https://msdn.microsoft.com/en-us/library/system.datetime.tofiletimeutc(v=vs.110).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/system.datetime.tofiletimeutc(v=vs.110).aspx</a></p>
| 3 | 2016-07-21T15:28:47Z | 38,524,858 | <p>So, for the benefit of anyone with this problem. Actually, it turns out that the question I mentioned, <a href="http://stackoverflow.com/questions/27534448/how-do-i-get-change-file-time-in-windows">How do I get *change* file time in Windows?</a>, is a bit misleading, as it mentions an obscure driver access only function <code>ZwQueryInformationFile</code>, while there is plain <code>GetFileTime</code> function you can use. Either way, these functions require file handle and that in turn requires calling <code>CreateFile</code> and <code>CloseHandle</code> and for large number of files (about one million in my case) this is quite expensive. So in the end I used <code>GetFileAttributesExW</code> that only requires path. By my measurements this is still little bit slower (about 10%) than <code>os.stat</code>, which I think is down to the overhead of calling functions through <code>ctypes</code>.</p>
<p>So after some copy-pasting from Internet, I put together the following code that does exactly what I wanted.</p>
<pre><code>from ctypes import windll, Structure, byref
from ctypes.wintypes import LPWSTR, DWORD, FILETIME
class WIN32_FILE_ATTRIBUTE_DATA(Structure):
_fields_ = [("dwFileAttributes", DWORD),
("ftCreationTime", FILETIME),
("ftLastAccessTime", FILETIME),
("ftLastWriteTime", FILETIME),
("nFileSizeHigh", DWORD),
("nFileSizeLow", DWORD)]
filename = 'path and file name'
wfad = WIN32_FILE_ATTRIBUTE_DATA()
GetFileExInfoStandard = 0
windll.kernel32.GetFileAttributesExW(LPWSTR(filename), GetFileExInfoStandard, byref(wfad))
lowtime = long(wfad.ftLastWriteTime.dwLowDateTime)
hightime = long(wfad.ftLastWriteTime.dwHighDateTime)
filetime = (hightime << 32) + lowtime
print filetime
</code></pre>
| 0 | 2016-07-22T11:04:35Z | [
"python",
"windows",
"ctypes"
] |
get specific index when using izip over list | 38,508,355 | <p>I want to iterate over a list and find the latest "consecutive value".</p>
<p>What does that mean, well:</p>
<p>If I have a list <code>priceValue = [423, 399, 390, 400, 430, 420, 423]</code>, my latest consecutive value will be the 2 last indexes: 420 to 423, index number: 5 and 6.</p>
<p>I want to iterate and get the index at the <strong>right place</strong></p>
<p>at this moment I use:</p>
<pre><code>for x, y in itertools.izip(priceValue, priceValue[1:]):
print x, y
if y > x:
#print x, y
print priceValue.index(y), priceValue.index(x)
</code></pre>
<p>But my problem is it will only print index "0" and "5" since the value 423 is found at index 0.</p>
<p>How do i get the right index?</p>
<p>NOTE: I can't tag "izip" in tags.</p>
| 1 | 2016-07-21T15:29:04Z | 38,508,443 | <p>Use <a href="https://docs.python.org/2/library/functions#enumerate" rel="nofollow"><code>enumerate</code></a> which yields index with original items:</p>
<pre><code>>>> for i, x in enumerate(['a', 'b', 'c']):
... print i, x # i: index, x: item
...
0 a
1 b
2 c
</code></pre>
<hr>
<pre><code>>>> import itertools
>>>
>>> xs = [423, 399, 390, 400, 430, 420, 423]
>>> [i for i, (x, y) in enumerate(itertools.izip(xs, xs[1:])) if y > x]
[2, 3, 5]
>>> [(i, i+1) for i, (x, y) in enumerate(itertools.izip(xs, xs[1:])) if y > x]
[(2, 3), (3, 4), (5, 6)]
</code></pre>
<hr>
<pre><code>for i, (x, y) in enumerate(itertools.izip(xs, xs[1:])):
if y > x:
print i, i + 1, x, y
# Prints
# 2 3 390 400
# 3 4 400 430
# 5 6 420 423
</code></pre>
| 0 | 2016-07-21T15:33:13Z | [
"python",
"loops"
] |
get specific index when using izip over list | 38,508,355 | <p>I want to iterate over a list and find the latest "consecutive value".</p>
<p>What does that mean, well:</p>
<p>If I have a list <code>priceValue = [423, 399, 390, 400, 430, 420, 423]</code>, my latest consecutive value will be the 2 last indexes: 420 to 423, index number: 5 and 6.</p>
<p>I want to iterate and get the index at the <strong>right place</strong></p>
<p>at this moment I use:</p>
<pre><code>for x, y in itertools.izip(priceValue, priceValue[1:]):
print x, y
if y > x:
#print x, y
print priceValue.index(y), priceValue.index(x)
</code></pre>
<p>But my problem is it will only print index "0" and "5" since the value 423 is found at index 0.</p>
<p>How do i get the right index?</p>
<p>NOTE: I can't tag "izip" in tags.</p>
| 1 | 2016-07-21T15:29:04Z | 38,508,543 | <pre><code>[(i, i+1) for i in range(len(priceValue)-1) if priceValue[i]<priceValue[i+1]]
</code></pre>
<p>Output :</p>
<pre><code>[(2, 3), (3, 4), (5, 6)]
</code></pre>
<p>Or more quite :</p>
<pre><code>res=[({i:priceValue[i], i+1:priceValue[i+1]}) for i in range(len(priceValue)-1) if priceValue[i]<priceValue[i+1]]
</code></pre>
<p>Output :</p>
<pre><code>[{2: 390, 3: 400}, {3: 400, 4: 430}, {5: 420, 6: 423}]
</code></pre>
| 0 | 2016-07-21T15:38:08Z | [
"python",
"loops"
] |
get specific index when using izip over list | 38,508,355 | <p>I want to iterate over a list and find the latest "consecutive value".</p>
<p>What does that mean, well:</p>
<p>If I have a list <code>priceValue = [423, 399, 390, 400, 430, 420, 423]</code>, my latest consecutive value will be the 2 last indexes: 420 to 423, index number: 5 and 6.</p>
<p>I want to iterate and get the index at the <strong>right place</strong></p>
<p>at this moment I use:</p>
<pre><code>for x, y in itertools.izip(priceValue, priceValue[1:]):
print x, y
if y > x:
#print x, y
print priceValue.index(y), priceValue.index(x)
</code></pre>
<p>But my problem is it will only print index "0" and "5" since the value 423 is found at index 0.</p>
<p>How do i get the right index?</p>
<p>NOTE: I can't tag "izip" in tags.</p>
| 1 | 2016-07-21T15:29:04Z | 38,508,547 | <p>If you dont mind avoiding for loops, you can also find the last consecutive value by calculating differences:</p>
<pre><code>import numpy as np
x = [423, 399, 390, 400, 430, 420, 423]
d = np.diff(x)
</code></pre>
<p>The index you want is the last positive index:</p>
<pre><code>np.where(d > 0)[0][-1]
>>> 5
</code></pre>
| 0 | 2016-07-21T15:38:15Z | [
"python",
"loops"
] |
Web-Scraping Max Retries Rejected | 38,508,357 | <p>I have issues scraping certain websites, while others work. For example, this works:</p>
<pre><code>page = requests.get('https://wsj.com/', proxies=proxydict)
</code></pre>
<p>But this doesn't:</p>
<pre><code>page = requests.get('https://www.privateequityinternational.com/', proxies=proxydict)
</code></pre>
<p>I get a "max retries" error, even though I only scrape 1 page (and haven't scraped it before).</p>
<p>I've tried using a header for the websites that won't scrape but it hasn't worked. Is there a specific header I should use? How do I scrape that second website I've shown above (<a href="http://www.privateequityinternational.com" rel="nofollow">www.privateequityinternational.com</a>)? Thank you.</p>
| 1 | 2016-07-21T15:29:14Z | 38,535,044 | <p>The issue is the page is served over <em>http</em> in your browser not <em>https</em>, you get a warning from google when you try to access the page using https:</p>
<pre><code>In [1]: import requests
...: page = requests.get('http://www.wsj.com')
...:
In [2]: page
Out[2]: <Response [200]>
</code></pre>
| 1 | 2016-07-22T20:52:10Z | [
"python",
"web-scraping",
"http-headers",
"python-requests",
"screen-scraping"
] |
Encode two ipv4 addresses in 64 bits | 38,508,422 | <p>If I have pairs of IP addresses like:</p>
<pre><code>IP1="168.2.65.33"
IP2="192.4.2.55"
</code></pre>
<p>I would like to encode each pair as a 64 bit value so that the first 32 bits is the first IP address and the second is the second IP address. I would then like to be able to save the 64 bit value to a file in such a way that I can read it back in and recover the two IP addresses.</p>
<p>The aim is save space.</p>
<p>Is it possible to do this in python?</p>
| 1 | 2016-07-21T15:32:24Z | 38,508,493 | <p>Don't worry about encoding them in 64 bits. An IPv4 address is 32 bits (4 bytes). If you write two of them to a file, it will be 8 bytes in size.</p>
<p>Use <a href="https://docs.python.org/2/library/socket.html#socket.inet_aton" rel="nofollow"><code>socket.inet_aton</code></a> to convert a human-readable IP address <em>string</em> to a packed binary raw 4-byte string:</p>
<pre><code>import socket
ip_addrs = ["168.2.65.33", "192.4.2.55"]
with open('data.out', 'wb') as f:
for ip in ip_addrs:
raw = socket.inet_aton(ip)
f.write(raw)
</code></pre>
<p>Result:</p>
<pre class="lang-none prettyprint-override"><code>$ hexdump -Cv data.out
00000000 a8 02 41 21 c0 04 02 37 |..A!...7|
00000008
</code></pre>
<p>The complementary conversion function <a href="https://docs.python.org/2/library/socket.html#socket.inet_ntoa" rel="nofollow"><code>socket.inet_ntoa</code></a> will convert a packed 4-byte string back into a human-readable IP address.</p>
<hr>
<p>Here's an example of writing and reading them back:</p>
<pre><code>import socket
ip_pairs = [
('1.1.1.1', '1.1.1.2'),
('2.2.2.2', '2.2.2.3'),
('3.3.3.3', '3.3.3.4'),
]
# Write them out
with open('data.out', 'wb') as f:
for ip1, ip2 in ip_pairs:
raw = socket.inet_aton(ip1) + socket.inet_aton(ip2)
f.write(raw)
def read_with_eof(f, n):
res = f.read(n)
if len(res) != n:
raise EOFError
return res
# Read them back in
result = []
with open('data.out', 'rb') as f:
while True:
try:
ip1 = socket.inet_ntoa(read_with_eof(f, 4))
ip2 = socket.inet_ntoa(read_with_eof(f, 4))
result.append((ip1, ip2))
except EOFError:
break
print 'Input:', ip_pairs
print 'Result:', result
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>$ python pairs.py
Input: [('1.1.1.1', '1.1.1.2'), ('2.2.2.2', '2.2.2.3'), ('3.3.3.3', '3.3.3.4')]
Result: [('1.1.1.1', '1.1.1.2'), ('2.2.2.2', '2.2.2.3'), ('3.3.3.3', '3.3.3.4')]
</code></pre>
| 5 | 2016-07-21T15:35:23Z | [
"python"
] |
Encode two ipv4 addresses in 64 bits | 38,508,422 | <p>If I have pairs of IP addresses like:</p>
<pre><code>IP1="168.2.65.33"
IP2="192.4.2.55"
</code></pre>
<p>I would like to encode each pair as a 64 bit value so that the first 32 bits is the first IP address and the second is the second IP address. I would then like to be able to save the 64 bit value to a file in such a way that I can read it back in and recover the two IP addresses.</p>
<p>The aim is save space.</p>
<p>Is it possible to do this in python?</p>
| 1 | 2016-07-21T15:32:24Z | 38,508,524 | <p>Yes, it's possible, like this:</p>
<pre><code>import struct
import os
IP1="168.2.65.233"
IP2="192.4.2.55"
s = struct.pack('>8B', *map(int, IP1.split('.') + IP2.split('.')))
with open('f', 'wb') as f:
f.write(s)
print(os.stat('f').st_size) #: 8.
</code></pre>
<p>This works in Python 2 and 3.</p>
<p>Based on Jonathon Reinhart's answer, you can also use <code>socket.inet_aton</code> instead of <code>struct.pack</code>.</p>
| 1 | 2016-07-21T15:36:54Z | [
"python"
] |
Encode two ipv4 addresses in 64 bits | 38,508,422 | <p>If I have pairs of IP addresses like:</p>
<pre><code>IP1="168.2.65.33"
IP2="192.4.2.55"
</code></pre>
<p>I would like to encode each pair as a 64 bit value so that the first 32 bits is the first IP address and the second is the second IP address. I would then like to be able to save the 64 bit value to a file in such a way that I can read it back in and recover the two IP addresses.</p>
<p>The aim is save space.</p>
<p>Is it possible to do this in python?</p>
| 1 | 2016-07-21T15:32:24Z | 38,508,747 | <p>In Python3 there is an <a href="https://docs.python.org/3/library/ipaddress.html" rel="nofollow"><code>ipaddress</code></a> module for working with IPs. Pack them into 32 bits each and add them together:</p>
<pre><code>from ipaddress import ip_address
original1 = ip_address('192.168.0.1')
original2 = ip_address('8.8.8.8')
out = original1.packed + original2.packed
</code></pre>
<p>Load them back in:</p>
<pre><code>loaded1 = ip_address(out[0:4])
loaded2 = ip_address(out[4:])
</code></pre>
<p>Try it online: <a href="https://repl.it/Ce3k/1" rel="nofollow">https://repl.it/Ce3k/1</a></p>
| 1 | 2016-07-21T15:47:33Z | [
"python"
] |
removing iterated string from string array | 38,508,447 | <p>I am writing a small script that lists the currently connected hard disks on my machine. I only need the disk identifier(disk0), not the partition ID(disk0s1, disk0s2, etc.)
How can I iterate through an array that contains diskID and partitionID and remove the partitionID entries? Here's what I'm trying so far:</p>
<pre><code> import os
allDrives = os.listdir("/dev/")
parsedDrives = []
def parseAllDrives():
parsedDrives = []
matching = []
for driveName in allDrives:
if 'disk' in driveName:
parsedDrives.append(driveName)
else:
continue
for itemName in parsedDrives:
if len(parsedDrives) != 0:
if 'rdisk' in itemName:
parsedDrives.remove(itemName)
else:
continue
else:
continue
#### this is where the problem starts: #####
# iterate through possible partition identifiers
for i in range(5):
#create a string for the partitionID
systemPostfix = 's' + str(i)
matching.append(filter(lambda x: systemPostfix in x, parsedDrives))
for match in matching:
if match in parsedDrives:
parsedDrives.remove(match)
print("found a mactch and removed it")
print("matched: %s" % matching)
print(parsedDrives)
parseAllDrives()
</code></pre>
<p>That last bit is just the most recent thing I've tried. Definitely open to going a different route.</p>
| 0 | 2016-07-21T15:33:28Z | 38,508,702 | <p>try beginning with</p>
<pre><code>allDrives = os.listdir("/dev/")
disks = [drive for drive in allDrives if ('disk' in drive)]
</code></pre>
<p>then, given disks id's are only 5-chars length</p>
<pre><code>short_disks = [disk[:6] for disk in disks]
unique_short_disks = list(set(short_disks))
</code></pre>
| 0 | 2016-07-21T15:45:03Z | [
"python",
"arrays",
"string",
"loops",
"system"
] |
Extract rows from python array in python | 38,508,457 | <p>I have a numpy array <code>X</code> with shape <code>(768, 8)</code>.</p>
<p>The last value for each row can either be <code>0</code> or <code>1</code>, I only want rows with value <code>1</code>, and call this <code>T</code>.</p>
<p>I did:</p>
<pre><code>T = [x for x in X if x[7]==1]
</code></pre>
<p>This is correct, however, this is now a list, not a numpy array (in fact I cannot print <code>T.shape</code>).</p>
<p>What should I do instead to keep this a numpy array?</p>
| 0 | 2016-07-21T15:33:48Z | 38,508,539 | <p>By calling </p>
<pre><code>T = [x for x in X if x[8]==1]
</code></pre>
<p>you are making <code>T</code> as a list. To convert it any list to a numpy array, just use:</p>
<pre><code>T = numpy.array([x for x in X if x[8]==1])
</code></pre>
<p>Here is what happens:</p>
<pre><code>In [1]: import numpy as np
In [2]: a = [1,2,3,4]
In [3]: a.T
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-3-9f69ed463660> in <module>()
----> 1 a.T
AttributeError: 'list' object has no attribute 'T'
In [4]: a = np.array(a)
In [5]: a.T
Out[5]: array([1, 2, 3, 4])
In [6]:
</code></pre>
| 0 | 2016-07-21T15:37:58Z | [
"python",
"numpy"
] |
Extract rows from python array in python | 38,508,457 | <p>I have a numpy array <code>X</code> with shape <code>(768, 8)</code>.</p>
<p>The last value for each row can either be <code>0</code> or <code>1</code>, I only want rows with value <code>1</code>, and call this <code>T</code>.</p>
<p>I did:</p>
<pre><code>T = [x for x in X if x[7]==1]
</code></pre>
<p>This is correct, however, this is now a list, not a numpy array (in fact I cannot print <code>T.shape</code>).</p>
<p>What should I do instead to keep this a numpy array?</p>
| 0 | 2016-07-21T15:33:48Z | 38,509,788 | <p>NumPy's boolean indexing gets the job done in a fully vectorized manner. This approach is generally more efficient (and arguably more elegant) than using list comprehensions and type conversions.</p>
<pre><code>T = X[X[:, -1] == 1]
</code></pre>
<p>Demo:</p>
<pre><code>In [232]: first_columns = np.random.randint(0, 10, size=(10, 7))
In [233]: last_column = np.random.randint(0, 2, size=(10, 1))
In [234]: X = np.hstack((first_columns, last_column))
In [235]: X
Out[235]:
array([[4, 3, 3, 2, 6, 2, 2, 0],
[2, 7, 9, 4, 7, 1, 8, 0],
[9, 8, 2, 1, 2, 0, 5, 1],
[4, 4, 4, 9, 6, 4, 9, 1],
[9, 8, 7, 6, 4, 4, 9, 0],
[8, 3, 3, 2, 9, 5, 5, 1],
[7, 1, 4, 5, 2, 4, 7, 0],
[8, 0, 0, 1, 5, 2, 6, 0],
[7, 9, 9, 3, 9, 3, 9, 1],
[3, 1, 8, 7, 3, 2, 9, 0]])
In [236]: mask = X[:, -1] == 1
In [237]: mask
Out[237]: array([False, False, True, True, False, True, False, False, True, False], dtype=bool)
In [238]: T = X[mask]
In [239]: T
Out[239]:
array([[9, 8, 2, 1, 2, 0, 5, 1],
[4, 4, 4, 9, 6, 4, 9, 1],
[8, 3, 3, 2, 9, 5, 5, 1],
[7, 9, 9, 3, 9, 3, 9, 1]])
</code></pre>
| 2 | 2016-07-21T16:37:33Z | [
"python",
"numpy"
] |
Appending Vowel Location Python | 38,508,554 | <p>I am trying to figure out why I am getting an empty list when this code is ran. The goal is to take a string, find the index of any vowels and append that index to a list. With an index starting at one instead of zero. Any tips where the error might be occurring would be great! If there is a general oversight you notice please let me know. Relatively new to python. thanks </p>
<pre><code>def vowel_indices(word):
vowels = ["a", "e", "i", "o", "u"]
vowel_idx = []
word.lower()
for idx, letter in enumerate(word, start = 1):
if letter == vowels:
vowel_idx.append(idx)
return vowel_idx
</code></pre>
| 1 | 2016-07-21T15:38:28Z | 38,508,585 | <p><code>if letter == vowels:</code> should be <code>if letter in vowels:</code></p>
<p>vowels is a list and a string can never be equal to a list and you should also move the return out of the loop as that will stop the function in it's track the first time it loops through</p>
| 1 | 2016-07-21T15:40:05Z | [
"python",
"indices",
"enumerate"
] |
Appending Vowel Location Python | 38,508,554 | <p>I am trying to figure out why I am getting an empty list when this code is ran. The goal is to take a string, find the index of any vowels and append that index to a list. With an index starting at one instead of zero. Any tips where the error might be occurring would be great! If there is a general oversight you notice please let me know. Relatively new to python. thanks </p>
<pre><code>def vowel_indices(word):
vowels = ["a", "e", "i", "o", "u"]
vowel_idx = []
word.lower()
for idx, letter in enumerate(word, start = 1):
if letter == vowels:
vowel_idx.append(idx)
return vowel_idx
</code></pre>
| 1 | 2016-07-21T15:38:28Z | 38,508,616 | <p>Method <code>lower</code> does not modify the string <em>in-place</em> (strings are <em>immutable</em>), so you should instead do:</p>
<pre><code>word = word.lower()
</code></pre>
<p>Then to check for the membership of a character in the list of <code>vowels</code>, you should use the <code>in</code> operator and not <code>==</code>:</p>
<pre><code>if letter in vowels:
</code></pre>
<p>And then the <code>return</code> statement should not be placed inside the <code>for</code> loop as this will make the function return immediately after the first iteration, which is not what you intend:</p>
<pre><code>for idx, letter in enumerate(word, start = 1):
if letter in vowels:
vowel_idx.append(idx)
return vowel_idx
</code></pre>
<hr>
<p>On an additional note, you can be less verbose and do the entire operation using a <em>list comprehension</em>:</p>
<pre><code>def vowel_indices(word):
return [idx for idx, l in enumerate(word.lower(), 1) if l in vowels]
</code></pre>
| 1 | 2016-07-21T15:41:15Z | [
"python",
"indices",
"enumerate"
] |
Appending Vowel Location Python | 38,508,554 | <p>I am trying to figure out why I am getting an empty list when this code is ran. The goal is to take a string, find the index of any vowels and append that index to a list. With an index starting at one instead of zero. Any tips where the error might be occurring would be great! If there is a general oversight you notice please let me know. Relatively new to python. thanks </p>
<pre><code>def vowel_indices(word):
vowels = ["a", "e", "i", "o", "u"]
vowel_idx = []
word.lower()
for idx, letter in enumerate(word, start = 1):
if letter == vowels:
vowel_idx.append(idx)
return vowel_idx
</code></pre>
| 1 | 2016-07-21T15:38:28Z | 38,509,188 | <p><strong>It work great</strong></p>
<pre><code>def vowel_indices(word):
vowels = ["a", "e", "i", "o", "u"]
word.lower()
indexes = [index for c,index in zip(word,range(len(word))) if c in vowels]
print(indexes)
</code></pre>
| 1 | 2016-07-21T16:08:19Z | [
"python",
"indices",
"enumerate"
] |
How to avoid gaps with matplotlib.fill_between and where | 38,508,556 | <p>I want to fill the area between two curves but only when the lower curve is >0.
I'm using <code>fill_between()</code> in <code>matplotlib</code> with a <code>where</code> condition (to test which curve is greater) and <code>numpy.maximum()</code> (to test whether the lower curve is >0). But there are gaps in the fill because the lower curve crosses the x-axis <em>between</em> integers while the result of the <code>maximum</code> hits the x-axis <em>at</em> an integer. How can I fix this?</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10)
a = np.array([101, 102, 71, 56, 49, 15, 29, 31, 45, 41])
b = np.array([52, 39, 8, -7, -12, -45, -23, -9, 14, 19])
fig, ax = plt.subplots()
ax.plot(x, a)
ax.plot(x, b)
ax.fill_between(x, a, np.maximum(b, 0), where=a >= b, alpha=0.25)
plt.axhline(0, color='black')
</code></pre>
<p><a href="http://i.stack.imgur.com/uOL6o.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/uOL6o.jpg" alt="enter image description here"></a></p>
<p>(I want the white triangles to be shaded as well.)</p>
| 2 | 2016-07-21T15:38:31Z | 38,509,267 | <p>By interpolating values using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html" rel="nofollow"><code>numpy.interp</code></a>:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10)
a = np.array([101, 102, 71, 56, 49, 15, 29, 31, 45, 41])
b = np.array([52, 39, 8, -7, -12, -45, -23, -9, 14, 19])
x2 = np.linspace(x[0], x[-1] + 1, len(x) * 100) # <---
a2 = np.interp(x2, x, a) # <---
b2 = np.interp(x2, x, b) # <---
x, a, b = x2, a2, b2 # <---
fig, ax = plt.subplots()
ax.plot(x, a)
ax.plot(x, b)
ax.fill_between(x, a, np.maximum(0, b), where=a>b, alpha=0.25)
plt.axhline(0, color='black')
</code></pre>
<p><a href="http://i.stack.imgur.com/46FiE.png" rel="nofollow"><img src="http://i.stack.imgur.com/46FiE.png" alt="output"></a></p>
<p><strong>UPDATE</strong></p>
<pre><code>x2 = np.linspace(x[0], x[-1] + 1, len(x) * 100)
</code></pre>
<p>should be replaced with:</p>
<pre><code>x2 = np.linspace(x[0], x[-1], len(x) * 100)
</code></pre>
<p><a href="http://i.stack.imgur.com/TyH9j.png" rel="nofollow"><img src="http://i.stack.imgur.com/TyH9j.png" alt="updated output"></a></p>
| 3 | 2016-07-21T16:12:23Z | [
"python",
"numpy",
"matplotlib"
] |
while loop until input is has fulfilled two statements | 38,508,564 | <pre><code>def ask_input(prompt, error):
while True:
value = input(prompt)
try:
int(value) > 1
break
except ValueError:
print(error)
else:
return value
</code></pre>
<p>So I want to make simple function that returns value if its integrel and greater than 1. So far the function seems to accept anything I put in. Do I need to make multiple loops or can I integrate both of statement in a while loop?</p>
| 0 | 2016-07-21T15:38:53Z | 38,508,592 | <p>Use <code>if</code> statement:</p>
<pre><code>while True:
value = input(prompt)
try:
if int(value) > 1:
return int(value) # return the value if condition met
except ValueError as error:
print(error)
</code></pre>
| 1 | 2016-07-21T15:40:23Z | [
"python",
"loops",
"while-loop"
] |
while loop until input is has fulfilled two statements | 38,508,564 | <pre><code>def ask_input(prompt, error):
while True:
value = input(prompt)
try:
int(value) > 1
break
except ValueError:
print(error)
else:
return value
</code></pre>
<p>So I want to make simple function that returns value if its integrel and greater than 1. So far the function seems to accept anything I put in. Do I need to make multiple loops or can I integrate both of statement in a while loop?</p>
| 0 | 2016-07-21T15:38:53Z | 38,508,849 | <p>Use a <strong>try/except</strong> to accept only integers. Then test the input for the greater than 1 condition using an <code>if</code> condition, return the value if it satisfies the condition. It's better to use <code>raw_input()</code> in this case as you want an integer literal as input, where as <code>input()</code> can also evaluate expressions potentially leading to unsanitized input.</p>
<pre><code>def ask_input(prompt, error):
while True:
try:
value = int(raw_input(prompt))
if value > 1: # Return the number if it's greater than 1.
return value
except ValueError: # Catch exception if value is not a base 10 int.
print error
</code></pre>
| 1 | 2016-07-21T15:52:31Z | [
"python",
"loops",
"while-loop"
] |
while loop until input is has fulfilled two statements | 38,508,564 | <pre><code>def ask_input(prompt, error):
while True:
value = input(prompt)
try:
int(value) > 1
break
except ValueError:
print(error)
else:
return value
</code></pre>
<p>So I want to make simple function that returns value if its integrel and greater than 1. So far the function seems to accept anything I put in. Do I need to make multiple loops or can I integrate both of statement in a while loop?</p>
| 0 | 2016-07-21T15:38:53Z | 38,509,087 | <p>Your code prompts the user for anything that can be converted to an integer, whether or not it is > 1, then return None. This is not what you intended.</p>
<p>There are 2 different problems here:</p>
<pre><code>int(value) > 1
</code></pre>
<p>If the input value is not parsable as an integer, then this will raise a ValueError that you catch and handle properly.
If the input value is parsable as an integer, then <code>int(value)</code> will convert it to an actual integer which will be compared to 1. The result of this comparison, however, is completely ignored since it is not stored in a variable or used.</p>
<p>Then the <code>break</code> will immediately leave the <code>while</code> loop, then the end of <code>ask_input</code> is reached, without a return statement. Because of that the <code>else</code> clause of your <code>try</code> is ignored.</p>
<p>I suggest the following code:</p>
<pre><code>def ask_input(prompt, error):
while True:
value = input(prompt)
try:
if int(value) > 1:
return value
except ValueError:
print(error)
</code></pre>
| 0 | 2016-07-21T16:03:42Z | [
"python",
"loops",
"while-loop"
] |
Pyspark (spark 1.6.x) ImportError: cannot import name Py4JJavaError | 38,508,603 | <p>I am using Apache-Spark (pyspark) and everything works fine. Now, I am trying to load a data that may or may not exist. So, I am trying to catch the Py4JJavaError and am trying to import it as follows:</p>
<pre><code>from py4j.java_gateway import Py4JJavaError
ImportError: cannot import name Py4JJavaError
</code></pre>
<p>When I unzip this file:
/usr/local/Cellar/apache-spark/1.6.2/python/lib/py4j-0.9-src.zip</p>
<p>And inspect this file:
java_gateway.py</p>
<p>I find no <code>Py4JJavaError</code>.</p>
<p>What am I doing wrong? Any other place / path I should be using instead?</p>
| 0 | 2016-07-21T15:40:42Z | 38,509,119 | <p>Try <code>from py4j.protocol import Py4JJavaError</code>.</p>
| 2 | 2016-07-21T16:05:01Z | [
"python",
"apache-spark",
"pyspark"
] |
Python download images with alernating variables | 38,508,715 | <p>I was trying to download images with url's that change but got an error.</p>
<pre><code>url_image="http://www.joblo.com/timthumb.php?src=/posters/images/full/"+str(title_2)+"-poster1.jpg&h=333&w=225"
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
headers = {'User-Agent': user_agent}
req = urllib.request.Request(url_image, None, headers)
print(url_image)
#image, h = urllib.request.urlretrieve(url_image)
with urllib.request.urlopen(req) as response:
the_page = response.read()
#print (the_page)
with open('poster.jpg', 'wb') as f:
f.write(the_page)
</code></pre>
<p>Traceback (most recent call last):
File "C:\Users\luke\Desktop\scraper\imager finder.py", line 97, in
with urllib.request.urlopen(req) as response:
File "C:\Users\luke\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 162, in urlopen
return opener.open(url, data, timeout)
File "C:\Users\luke\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 465, in open
response = self._open(req, data)
File "C:\Users\luke\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 483, in _open
'_open', req)
File "C:\Users\luke\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 443, in _call_chain
result = func(*args)
File "C:\Users\luke\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 1268, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "C:\Users\luke\AppData\Local\Programs\Python\Python35-32\lib\urllib\request.py", line 1243, in do_open
r = h.getresponse()
File "C:\Users\luke\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 1174, in getresponse
response.begin()
File "C:\Users\luke\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 282, in begin
version, status, reason = self._read_status()
File "C:\Users\luke\AppData\Local\Programs\Python\Python35-32\lib\http\client.py", line 264, in _read_status
raise BadStatusLine(line)
http.client.BadStatusLine: </p>
| 0 | 2016-07-21T15:45:37Z | 38,510,385 | <p>My advice is to use urlib2. In addition, I've written a nice function (I think) that will also allow gzip encoding (reduce bandwidth) if the server supports it. I use this for downloading social media files, but should work for anything.</p>
<p>I would try to debug your code, but since it's just a snippet (and the error messages are formatted badly), it's hard to know exactly where your error is occurring (it's certainly not line 97 in your code snippet).</p>
<p>This isn't as short as it could be, but it's clear and reusable. This is python 2.7, it looks like you're using 3 - in which case you google some other questions that address how to use urllib2 in python 3.</p>
<pre><code>import urllib2
import gzip
from StringIO import StringIO
def download(url):
"""
Download and return the file specified in the URL; attempt to use
gzip encoding if possible.
"""
request = urllib2.Request(url)
request.add_header('Accept-Encoding', 'gzip')
try:
response = urllib2.urlopen(request)
except Exception, e:
raise IOError("%s(%s) %s" % (_ERRORS[1], url, e))
payload = response.read()
if response.info().get('Content-Encoding') == 'gzip':
buf = StringIO(payload)
f = gzip.GzipFile(fileobj=buf)
payload = f.read()
return payload
def save_media(filename, media):
file_handle = open(filename, "wb")
file_handle.write(media)
file_handle.close()
title_2 = "10-cloverfield-lane"
media = download("http://www.joblo.com/timthumb.php?src=/posters/images/full/{}-poster1.jpg&h=333&w=225".format(title_2))
save_media("poster.jpg", media)
</code></pre>
| 0 | 2016-07-21T17:09:42Z | [
"python",
"image",
"download",
"urllib",
"python-3.5"
] |
Parsing complex Xml Python 3.4 | 38,508,775 | <p>I have the following xml :</p>
<pre><code><?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Suite>
<TestCase>
<TestCaseID>001</TestCaseID>
<TestCaseDescription>Hello</TestCaseDescription>
<TestSetup>
<Action>
<ActionCommand>gfdg</ActionCommand>
<TimeOut>dfgd</TimeOut>
<BamSymbol>gff</BamSymbol>
<Side>vfbgc</Side>
<PrimeBroker>fgfd</PrimeBroker>
<Size>fbcgc</Size>
<PMCode>fdgd</PMCode>
<Strategy>fdgf</Strategy>
<SubStrategy>fgf</SubStrategy>
<ActionLogEndPoint>fdgf</ActionLogEndPoint>
<IsActionResultLogged>fdgf</IsActionResultLogged>
<ValidationStep>
<IsValidated>fgdf</IsValidated>
<ValidationFormat>dfgf</ValidationFormat>
<ResponseEndpoint>gdf</ResponseEndpoint>
<ResponseParameterName>fdgfdg</ResponseParameterName>
<ResponseParameterValue>gff</ResponseParameterValue>
<ExpectedValue>fdgf</ExpectedValue>
<IsValidationResultLogged>gdfgf</IsValidationResultLogged>
<ValidationLogEndpoint>fdgf</ValidationLogEndpoint>
</ValidationStep>
</Action>
<Action>
<ActionCommand>New Order</ActionCommand>
<TimeOut>fdgf</TimeOut>
<BamSymbol>fdg</BamSymbol>
<Side>C(COVER)</Side>
<PrimeBroker>CSPB</PrimeBroker>
<Size>fdgd</Size>
<PMCode>GREE</PMCode>
<Strategy>Generalist</Strategy>
<SubStrategy>USLC</SubStrategy>
<ActionLogEndPoint>gfbhgf</ActionLogEndPoint>
<IsActionResultLogged>fdgf</IsActionResultLogged>
<ValidationStep>
<IsValidated>fdgd</IsValidated>
<ValidationFormat>dfgfd</ValidationFormat>
<ResponseEndpoint>dfgf</ResponseEndpoint>
<ResponseParameterName>fdgfd</ResponseParameterName>
<ResponseParameterValue>dfgf</ResponseParameterValue>
<ExpectedValue>fdg</ExpectedValue>
<IsValidationResultLogged>fdgdf</IsValidationResultLogged>
<ValidationLogEndpoint>fdgfd</ValidationLogEndpoint>
</ValidationStep>
</Action>
</TestCase>
</Suite>
</code></pre>
<p>Based on the ActionCommand i am getting either one block , the issue is could not get the sub parent tag (ValidationStep) and all its child tags . Can anyone help?</p>
<p>My code:</p>
<pre><code>for testSetup4 in root.findall(".TestCase/TestSetup/Action"):
if testSetup4.find('ActionCommand').text == "gfdg":
for c1 in testSetup4:
t2.append(c1.tag)
v2.append(c1.text)
for k,v in zip(t2, v2):
test_case[k] = v
</code></pre>
<p>I am not able to get ValidationStep (sub parent) and its corresponding tags.</p>
| 0 | 2016-07-21T15:48:30Z | 38,547,968 | <p>Simply add another loop to iterate through the <code><ValidationStep></code> node and its children. Also, you do not need the two other lists as you can update a dictionary during the parsing loop:</p>
<pre><code>import xml.etree.ElementTree as et
dom = et.parse('Input.xml')
root = dom.getroot()
test_case = {}
for testSetup4 in root.findall(".TestCase/TestSetup/Action"):
if testSetup4.find('ActionCommand').text == "gfdg":
for c1 in testSetup4:
test_case[c1.tag]= c1.text
for vd in testSetup4.findall("./ValidationStep/*"):
test_case[vd.tag]= vd.text
</code></pre>
<p>Alternatively, use the double slash operator to search for all children including grandchildren of <code><Action></code> element:</p>
<pre><code>for testSetup4 in root.findall(".TestCase/TestSetup/Action"):
if testSetup4.find('ActionCommand').text == "gfdg":
for c1 in testSetup4.findall(".//*"):
test_case[c1.tag]= c1.text
</code></pre>
| 0 | 2016-07-24T01:37:54Z | [
"python",
"xml"
] |
How to turn a system of sympy equations into matrix form | 38,508,780 | <p>How do I turn a system of sympy equations into a matrix form?</p>
<p>For example, how do I turn a system like this:</p>
<pre><code>equation_one = 4*a*x + 3*b*y
equation_two = 2*b*x + 1*a*y
</code></pre>
<p>Into a system like this:</p>
<pre><code>matrix_form = ([equation_one, equation_two], [x, y])
</code></pre>
<p>That will return this:</p>
<pre><code>[[4*a, 3*b],
[2*b, 1*a]]
</code></pre>
<p>Does a function like matrix_form() exist?</p>
| 2 | 2016-07-21T15:48:54Z | 38,509,562 | <p>After some searching, I found </p>
<pre><code>sympy.linear_eq_to_matrix(equations, *symbols)
</code></pre>
<p>This has solved my problem. </p>
| 3 | 2016-07-21T16:26:10Z | [
"python",
"sympy"
] |
beautifulsoup with get_text - handle spaces | 38,508,850 | <p>I using BS4 (python3) for extracting text from html file. My file looks like this:</p>
<pre><code><BODY>
<P>Hello World!</P>
</BODY>
</HTML>
</code></pre>
<p>When i calling <code>get_text()</code> method, the output is "Hello World!". Because it's HTML, I was expected to get "Hello World!" (two or more spaces are replaced with one space in HTML). </p>
<p>This Also relevant for this situation:</p>
<pre><code><BODY>
<P>Hello
World!</P>
</BODY>
</HTML>
</code></pre>
<p>I was expected to find "Hello World!" but it was "Hello \n World!".</p>
<p>How I can achieve my goal?</p>
| 1 | 2016-07-21T15:52:36Z | 38,508,894 | <p>The problem is, neither <code>get_text(strip=True)</code> nor joining the <code>.stripped_strings</code> would work here because there is a single <code>NavigableString</code> in the <code>p</code> element in the second case and it's value is <code>Hello\n World!</code>. The newline is inside the text node in other words.</p>
<p>In this case, you will have to <em>replace the newlines</em> manually:</p>
<pre><code>soup.p.get_text().replace("\n", "")
</code></pre>
<hr>
<p>Or, to also handle the <code>br</code> elements (replacing them with newlines), you can make a converting function that will prepare the text for you:</p>
<pre><code>from bs4 import BeautifulSoup, NavigableString
data = """
<BODY>
<P>Hello
World!</P>
<P>Hello
<BR/>
World!</P>
</BODY>
</HTML>
"""
def replace_with_newlines(element):
text = ''
for elem in element.children:
if isinstance(elem, NavigableString):
text += elem.replace("\n", "").strip()
elif elem.name == 'br':
text += '\n'
return text
soup = BeautifulSoup(data, "html.parser")
for p in soup.find_all("p"):
print(replace_with_newlines(p))
</code></pre>
<p>Prints (no newlines in the first case, a single newline in the second):</p>
<pre><code>Hello World!
Hello
World!
</code></pre>
| 0 | 2016-07-21T15:55:00Z | [
"python",
"python-3.x",
"beautifulsoup"
] |
Existing code on github, principal functions never called | 38,508,956 | <p>I am trying to work on an addon developed by Microsoft Azure for his old Cloud Service. The aim is to render Blender scenes using the Azure environment.</p>
<p>Here it is : <a href="https://github.com/Azure/azure-batch-apps-blender" rel="nofollow">https://github.com/Azure/azure-batch-apps-blender</a></p>
<p>As Microsoft doesn't support this addon anymore, and as it was originally created to work with the old Azure, I want to update it and make it work with the new Azure. Basically, here is what I understood :</p>
<ul>
<li>The python part is the Blender part, it defines the Blender UI, authentify the user and register the assets (Blender models ?) into Azure. Then it should start the process.</li>
<li>The C# part is the Azure part, aims to be executed on Azure and has a reference to an executable of Blender. It has a class to split the calculus and an other class to process the calculus.</li>
</ul>
<p>I'm using Visual Studio 2015 and Blender 2.77a. </p>
<p>What I don't understand is that the code seems to be short, especially the C# one. I don't understand how the split part is done (there is no logic around the blender model) and I don't understand why the principal functions of the principal classes (like Split in JobSplitter.cs) are never called ? Did I miss some code ?</p>
<p>I spent some days on various general documentation around Azure, but it didn't helped me that much with this specific application. I also asked Microsoft but this product isn't supported anymore.</p>
| 0 | 2016-07-21T15:58:08Z | 38,511,603 | <p>Thanks for your interest in the Blender plugin!
The "missing code" that you mention here is actually part of the old Batch Apps C# SDK, which exposed an interface, allowing us to override select functions with Blender specific functionality.
While I'm afraid I can't find any old documentation for it, this project should no longer be necessary, as using the Batch API, the tasks can be constructed in Python from the Blender plugin.</p>
<p>I've actually started porting this plugin to support the Batch API. You can find my code in the dev branch of my fork here:
<a href="https://github.com/annatisch/azure-batch-apps-blender/tree/dev" rel="nofollow">https://github.com/annatisch/azure-batch-apps-blender/tree/dev</a></p>
<p>There's still a lot of things that I have yet to clean up, including the dependency checking - but I've put some instructions in the issue filed here:
<a href="https://github.com/Azure/azure-batch-apps-blender/issues/7" rel="nofollow">https://github.com/Azure/azure-batch-apps-blender/issues/7</a></p>
<p>I'm hoping to make some progress on this project in August after Siggraph. Though I would be happy to accept any PRs!</p>
<p>Regarding the cloud-side code, as I mentioned above, this is now no longer necessary (though I may re-introduce something similar later for richer feature support) - as the entire cloud-side task is constructed within the plugin. The downside to this is that at present I haven't implemented the persisting of rendered frames to Azure Storage, but you can download them using the Azure Portal before the VM pool is deleted.
This plugin currently runs only Linux nodes for rendering (Ubuntu) and installs Blender dynamically with apt-get.</p>
<p>Please post to the Github issues board if you have any trouble using the updated plugin and I'll be happy to help. :)</p>
<p>Cheers</p>
| 1 | 2016-07-21T18:17:35Z | [
"c#",
"python",
"azure",
"blender",
"azure-batch"
] |
How to query AWS to get ELB names and attached instances to that using python boto modules? | 38,509,004 | <p>I am trying retrieve the ELB names and the attached instances ids using python boto modules. </p>
<pre><code>{
import boto
conn = boto.connect_elb()
conn.get_all_load_balancers()
}
</code></pre>
<p>Gives only load-balancer names now how can i retrieve the Instance-ids attached to the load-balancer ? </p>
| 0 | 2016-07-21T15:59:58Z | 38,509,222 | <p><code>conn.get_all_load_balancers()</code> - returns a list of elbs objects. Each elb object has a parameter <code>instances</code> that will show you attached instances. And from there you can get their Id's.<br>
If you want to find elb by name, then you need to filter first loop. </p>
<p>So something like this should work (Thanks @Frédéric Henri for update):</p>
<pre><code>import boto
conn = boto.connect_elb()
elbs = conn.get_all_load_balancers(load_balancer_names=['MY-ELB-NAME'])[0]
instances = [inst.id for elb in elbs for inst in elb.instances]
</code></pre>
| 2 | 2016-07-21T16:10:01Z | [
"python",
"amazon-web-services",
"boto"
] |
Sliding window iterator using rolling in pandas | 38,509,107 | <p>If it's single row, I can get the iterator as following</p>
<pre><code>import pandas as pd
import numpy as np
a = np.zeros((100,40))
X = pd.DataFrame(a)
for index, row in X.iterrows():
print index
print row
</code></pre>
<p>Now I want each iterator will return a subset X[0:9, :], X[5:14, :], X[10:19, :] etc. How do I achieve this with rolling (pandas.DataFrame.rolling)?</p>
| 2 | 2016-07-21T16:04:28Z | 38,509,466 | <p>That's not how rolling works. It "provides rolling transformations" (from <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html" rel="nofollow">the docs</a>).</p>
<p>You can loop and use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#different-choices-for-indexing" rel="nofollow">pandas indexing</a>?</p>
<pre><code>for i in range((X.shape[0] + 9) // 10):
X_subset = X.iloc[i * 10: (i + 1) * 10])
</code></pre>
| 1 | 2016-07-21T16:21:12Z | [
"python",
"pandas"
] |
Sliding window iterator using rolling in pandas | 38,509,107 | <p>If it's single row, I can get the iterator as following</p>
<pre><code>import pandas as pd
import numpy as np
a = np.zeros((100,40))
X = pd.DataFrame(a)
for index, row in X.iterrows():
print index
print row
</code></pre>
<p>Now I want each iterator will return a subset X[0:9, :], X[5:14, :], X[10:19, :] etc. How do I achieve this with rolling (pandas.DataFrame.rolling)?</p>
| 2 | 2016-07-21T16:04:28Z | 38,510,101 | <p>I'll experiment with the following dataframe.</p>
<h3>Setup</h3>
<pre><code>import pandas as pd
import numpy as np
from string import uppercase
def generic_portfolio_df(start, end, freq, num_port, num_sec, seed=314):
np.random.seed(seed)
portfolios = pd.Index(['Portfolio {}'.format(i) for i in uppercase[:num_port]],
name='Portfolio')
securities = ['s{:02d}'.format(i) for i in range(num_sec)]
dates = pd.date_range(start, end, freq=freq)
return pd.DataFrame(np.random.rand(len(dates) * num_sec, num_port),
index=pd.MultiIndex.from_product([dates, securities],
names=['Date', 'Id']),
columns=portfolios
).groupby(level=0).apply(lambda x: x / x.sum())
df = generic_portfolio_df('2014-12-31', '2015-05-30', 'BM', 3, 5)
df.head(10)
</code></pre>
<p><a href="http://i.stack.imgur.com/1eonn.png" rel="nofollow"><img src="http://i.stack.imgur.com/1eonn.png" alt="enter image description here"></a></p>
<p>I'll now introduce a function to roll a number of rows and concatenate into a single dataframe where I'll add a top level to the column index that indicates the location in the roll.</p>
<h3>Solution Step-1</h3>
<pre><code>def rolled(df, n):
k = range(df.columns.nlevels)
_k = [i - len(k) for i in k]
myroll = pd.concat([df.shift(i).stack(level=k) for i in range(n)],
axis=1, keys=range(n)).unstack(level=_k)
return [(i, row.unstack(0)) for i, row in myroll.iterrows()]
</code></pre>
<p>Though its hidden in the function, <code>myroll</code> would look like this</p>
<p><a href="http://i.stack.imgur.com/xs0kQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/xs0kQ.png" alt="enter image description here"></a></p>
<p>Now we can use it just like an iterator.</p>
<h3>Solution Step-2</h3>
<pre><code>for i, roll in rolled(df.head(5), 3):
print roll
print
0 1 2
Portfolio
Portfolio A 0.326164 NaN NaN
Portfolio B 0.201597 NaN NaN
Portfolio C 0.085340 NaN NaN
0 1 2
Portfolio
Portfolio A 0.278614 0.326164 NaN
Portfolio B 0.314448 0.201597 NaN
Portfolio C 0.266392 0.085340 NaN
0 1 2
Portfolio
Portfolio A 0.258958 0.278614 0.326164
Portfolio B 0.089224 0.314448 0.201597
Portfolio C 0.293570 0.266392 0.085340
0 1 2
Portfolio
Portfolio A 0.092760 0.258958 0.278614
Portfolio B 0.262511 0.089224 0.314448
Portfolio C 0.084208 0.293570 0.266392
0 1 2
Portfolio
Portfolio A 0.043503 0.092760 0.258958
Portfolio B 0.132221 0.262511 0.089224
Portfolio C 0.270490 0.084208 0.293570
</code></pre>
| 4 | 2016-07-21T16:53:11Z | [
"python",
"pandas"
] |
when will the python __call__ would be called? | 38,509,124 | <p>I tried to understand the following code. </p>
<pre><code>class Chain(object):
def __init__(self, path=''):
self._path = path
def __getattr__(self, path):
return Chain('%s/%s' % (self._path, path))
def __str__(self):
return self._path
__repr__ = __str__
def __call__(self, path):
return Chain('%s/%s' % (self._path, path))
print (Chain().abc.efg("string").repos)
</code></pre>
<p>The output is:</p>
<pre><code>/abc/efg/string/repos
</code></pre>
<p>What I don't understand is why the <code>__call__</code> method was not called in the <code>Chain(/abc)</code> , but was called in the <code>Chain(/abc/efg)</code></p>
| 1 | 2016-07-21T16:05:09Z | 38,509,247 | <p><code>abc</code> is considered an attribute rather than a method call. Therefore it should be handled by <code>__getattr__</code> instead of <code>__call__</code>.</p>
| 0 | 2016-07-21T16:11:30Z | [
"python"
] |
when will the python __call__ would be called? | 38,509,124 | <p>I tried to understand the following code. </p>
<pre><code>class Chain(object):
def __init__(self, path=''):
self._path = path
def __getattr__(self, path):
return Chain('%s/%s' % (self._path, path))
def __str__(self):
return self._path
__repr__ = __str__
def __call__(self, path):
return Chain('%s/%s' % (self._path, path))
print (Chain().abc.efg("string").repos)
</code></pre>
<p>The output is:</p>
<pre><code>/abc/efg/string/repos
</code></pre>
<p>What I don't understand is why the <code>__call__</code> method was not called in the <code>Chain(/abc)</code> , but was called in the <code>Chain(/abc/efg)</code></p>
| 1 | 2016-07-21T16:05:09Z | 38,509,332 | <p><code>__getattr__</code> is used for attribute lookup on a class instance. <code>__call__</code> is used when a class instance is used as a function.</p>
<pre><code>Chain() # creates a class instance
Chain().abc # calls __getattr__ which returns new instance
Chain().abc.efg # calls __getattr__ which returns new instance
Chain().abc.efg("string") # calls __call__
</code></pre>
<p><code>__getattr__</code> can only handle strings that python recognizes as valid variable names. <code>__call__</code> is useful when a non-conforming string is wanted. So, for instance, <code>Chain().abc.def("some string with spaces")</code> would be a good example.</p>
| 2 | 2016-07-21T16:15:14Z | [
"python"
] |
Calculator in Python can't print out the result I want | 38,509,137 | <p>I wanted to create this calculator in Python and I had some problems when it printed out. The problem was that everytime that I ran the program it printed out Check for errors. When I removed it, it started to print me out numbers put together. For example 1 + 2 = 12 or 2 + 5= 25, etc.This thing happened only when I tried to add two numbers, when I tried multiplying, subtracting or dividing it didn't print out anything. This is my code:</p>
<pre><code>print ("Enter your first number")
num1 = input()
print("Enter your second number")
num2 = input()
print("Enter operation")
operation = input()
if operation is "+":
print(num1 + num2)
elif operation is "*":
print(num1 * num2)
elif operation is "/":
print(num1 / num2)
elif operation is "-":
print(num1 - num2)
else:
print("Check for errors")
</code></pre>
| 0 | 2016-07-21T16:05:54Z | 38,509,225 | <p>I think you want to be using <code>==</code> instead of <code>is</code> to compare string literals with a variable. I'd expect your usage to always return false.</p>
| 0 | 2016-07-21T16:10:14Z | [
"python"
] |
Calculator in Python can't print out the result I want | 38,509,137 | <p>I wanted to create this calculator in Python and I had some problems when it printed out. The problem was that everytime that I ran the program it printed out Check for errors. When I removed it, it started to print me out numbers put together. For example 1 + 2 = 12 or 2 + 5= 25, etc.This thing happened only when I tried to add two numbers, when I tried multiplying, subtracting or dividing it didn't print out anything. This is my code:</p>
<pre><code>print ("Enter your first number")
num1 = input()
print("Enter your second number")
num2 = input()
print("Enter operation")
operation = input()
if operation is "+":
print(num1 + num2)
elif operation is "*":
print(num1 * num2)
elif operation is "/":
print(num1 / num2)
elif operation is "-":
print(num1 - num2)
else:
print("Check for errors")
</code></pre>
| 0 | 2016-07-21T16:05:54Z | 38,509,324 | <p>@Fjoni Yzeiri: Hi folk, </p>
<p>This is a common issue when starting with Python, as you don't declare the variable type of the input, it will save it as a <code>String</code>, so if you concatenate (<code>+</code> in Python) it will concatenate the two Inputs.</p>
<p>To solve this you have to explicitly cast this values into <code>Integers</code>, it means:</p>
<pre><code>print ("Enter your first number")
num1 = int(input()) # Cast to int here
print("Enter your second number")
num2 = int(input()) # Cast to int here
print("Enter operation")
operation = input()
if operation is "+":
print(num1 + num2)
elif operation is "*":
print(num1 * num2)
elif operation is "/":
print(num1 / num2)
elif operation is "-":
print(num1 - num2)
else:
print("Check for errors")
</code></pre>
<p>Of course, this is a very simple use case, if you want to learn a bit more, try to caught the exception when it tries to cast a non-integer string. It will teach you nice stuff ;)</p>
| 0 | 2016-07-21T16:15:03Z | [
"python"
] |
Calculator in Python can't print out the result I want | 38,509,137 | <p>I wanted to create this calculator in Python and I had some problems when it printed out. The problem was that everytime that I ran the program it printed out Check for errors. When I removed it, it started to print me out numbers put together. For example 1 + 2 = 12 or 2 + 5= 25, etc.This thing happened only when I tried to add two numbers, when I tried multiplying, subtracting or dividing it didn't print out anything. This is my code:</p>
<pre><code>print ("Enter your first number")
num1 = input()
print("Enter your second number")
num2 = input()
print("Enter operation")
operation = input()
if operation is "+":
print(num1 + num2)
elif operation is "*":
print(num1 * num2)
elif operation is "/":
print(num1 / num2)
elif operation is "-":
print(num1 - num2)
else:
print("Check for errors")
</code></pre>
| 0 | 2016-07-21T16:05:54Z | 38,509,354 | <p>The problem is solved now. Someone posted the answer but he deleted it I think and I couldn't upvote it. I needed to change </p>
<pre><code>num1 = input()
</code></pre>
<p>to </p>
<pre><code>num1 = int(input())
</code></pre>
| 0 | 2016-07-21T16:15:57Z | [
"python"
] |
How to create user specific file with unique name in the reducer phase of Hadoop Map Reduce Framework(In Python)) | 38,509,221 | <p>I have written one code for the reducer which will read the output from the mapper. And then It will create a new file with the key name And all the values corresponding to same key will be stored into one file.</p>
<p><strong>My code is:</strong></p>
<pre><code>!/usr/bin/env python
import sys
last_key = None #initialize these variables
for input_line in sys.stdin:
input_line = input_line.strip()
data = input_line.split("\t")
this_key = data[0]
if len(data) == 2:
value = data[1]
else:
value = None
if last_key == this_key:
if value:
fp.write('{0}\n'.format(value))
else:
if last_key:
fp.close()
fp = open('%s.txt' %this_key,'a')
if value:
fp.write('{0}\n'.format(value))
if not last_key:
fp = open('%s.txt' %this_key,'a')
if value:
fp.write('{0}\n'.format(value))
last_key = this_key
</code></pre>
<p>But It is not creating any file. </p>
<p>So, My question is what function should I need to use to create new files into HDFS.</p>
| 0 | 2016-07-21T16:10:01Z | 38,513,216 | <p>There are no straightforward solution to achieve this.You may follow below approaches to achieve this using Mapreduce:</p>
<p>Approach 1: Using partitioner</p>
<ol>
<li>Find out unique number of files.e.g. count unique number of '%this_key%' in file.</li>
<li>Set number of reducer to previous step result in mapreduce driver [each file per reducer].</li>
<li>Use partitioner to send the map-output to particular reducer.</li>
<li>Reducer emit only %value%.</li>
<li>At the end of job you will have same key value per file and you might rename reducer output files.</li>
</ol>
<p>Approach 2: if number of files are very less then use <a href="https://hadoop.apache.org/docs/r2.4.1/api/org/apache/hadoop/mapreduce/lib/output/MultipleOutputs.html" rel="nofollow">MultipleOutputs </a>.</p>
| 0 | 2016-07-21T19:52:22Z | [
"python",
"python-2.7",
"hadoop",
"hdfs",
"hadoop-streaming"
] |
Need to remove items from both a list and a dictionary of tuple value pairs at same time | 38,509,239 | <p>This is very related to a <a href="http://stackoverflow.com/questions/38506857/deleting-previous-token-in-a-sentence-if-same-as-current-token-python">previous question</a> but I realised that my objective is much more complicated:</p>
<p>I have a sentence: <code>"Forbes Asia 200 Best Under 500 Billion 2011"</code></p>
<p>I have tokens like:</p>
<pre><code>oldTokens = [u'Forbes', u'Asia', u'200', u'Best', u'Under', u'500', u'Billion', u'2011']
</code></pre>
<p>And the indices of where a previous parser has figured out where there should be location or number slots:</p>
<pre><code>numberTokenIDs = {(7,): 2011.0, (2,): 200.0, (5,6): 500000000000.00}
locationTokenIDs = {(0, 1): u'Forbes Asia'}
</code></pre>
<p>The token IDs correspond to the index of the tokens where there are locations or numbers, the objective is to obtain a new set of tokens like:</p>
<pre><code>newTokens = [u'Asia', u'200', u'Best', u'Under', u'500', u'2011']
</code></pre>
<p>With new number and location tokenIDs perhaps like (to avoid index out of bounds exceptions):</p>
<pre><code>numberTokenIDs = {(5,): 2011.0, (1,): 200.0, (4,): 500000000000.00}
locationTokenIDs = {(0,): u'Forbes Asia'}
</code></pre>
<p>Essentially I would like to go through the new reduced set of tokens, and be able to ultimately create a new sentence called:</p>
<pre><code>"LOCATION_SLOT NUMBER_SLOT Best Under NUMBER_SLOT NUMBER_SLOT"
</code></pre>
<p>via going through the new set of tokens and replacing the correct tokenID with either "LOCATION_SLOT" or "NUMBER_SLOT". If I did this with the current set of number and location token IDs, I would get:</p>
<pre><code>"LOCATION_SLOT LOCATION_SLOT NUMBER_SLOT Best Under NUMBER_SLOT NUMBER_SLOT NUMBER_SLOT".
</code></pre>
<p>How would I do this?</p>
<p>Another example is:</p>
<pre><code>Location token IDs are: (0, 1)
Number token IDs are: (3, 4)
Old sampleTokens [u'United', u'Kingdom', u'USD', u'1.240', u'billion']
</code></pre>
<p>Where I want to both delete tokens and also change location and number token IDs to be able to replace the sentence like:</p>
<pre><code>sampleTokens[numberTokenID] = "NUMBER_SLOT"
sampleTokens[locationTokenID] = "LOCATION_SLOT"
</code></pre>
<p>Such that the replaced tokens are <code>[u'LOCATION_SLOT', u'USD', u'NUMBER_SLOT']</code></p>
| 0 | 2016-07-21T16:11:05Z | 38,512,276 | <p>Not a very elegant, but working solution:</p>
<pre><code>oldTokens = [u'Forbes', u'Asia', u'200', u'Best', u'Under', u'500', u'Billion', u'2011']
numberTokenIDs = {(7,): 2011.0, (2,): 200.0, (5,6): 500000000000.00}
locationTokenIDs = {(0, 1): u'Forbes Asia'}
newTokens = []
newnumberTokenIDs = {}
newlocationTokenIDs = {}
new_ind = 0
skip = False
for ind in range(len(oldTokens)):
if skip:
skip=False
continue
for loc_ind in locationTokenIDs.keys():
if ind in loc_ind:
newTokens.append(oldTokens[ind+1])
newlocationTokenIDs[(new_ind,)] = locationTokenIDs[loc_ind]
new_ind += 1
if len(loc_ind) > 1: # Skip next position if there are 2 elements in a tuple
skip = True
break
else:
for num_ind in numberTokenIDs.keys():
if ind in num_ind:
newTokens.append(oldTokens[ind])
newnumberTokenIDs[(new_ind,)] = numberTokenIDs[num_ind]
new_ind += 1
if len(num_ind) > 1:
skip = True
break
else:
newTokens.append(oldTokens[ind])
new_ind += 1
newTokens
Out[37]: [u'Asia', u'200', u'Best', u'Under', u'500', u'2011']
newnumberTokenIDs
Out[38]: {(1,): 200.0, (4,): 500000000000.0, (5,): 2011.0}
newlocationTokenIDs
Out[39]: {(0,): u'Forbes Asia'}
</code></pre>
| 1 | 2016-07-21T18:55:32Z | [
"python",
"dictionary",
"tuples"
] |
How to get Python WebJob working on Azure | 38,509,344 | <p>I am struggling to deploy a Python WorkerRole on Microsoft Azure. Has anybody successfully gotten a Python process working on Microsoft Azure?</p>
<p>Microsoft seems to be telling people that their documentation related to Python on Azure is out of date, see <a href="https://azure.microsoft.com/en-us/documentation/articles/cloud-services-python-ptvs/#comment-2790110068" rel="nofollow">https://azure.microsoft.com/en-us/documentation/articles/cloud-services-python-ptvs/#comment-2790110068</a> and <a href="https://github.com/Microsoft/PTVS/issues/1447" rel="nofollow">https://github.com/Microsoft/PTVS/issues/1447</a>.</p>
<p>A Microsoft employ told me that I need to install my own Python interpreter when I deploy a WorkerRole. Does anybody know how to do that?</p>
<p>My worker.py file consists solely of <code>$print("in the worker".format(datetime.now()))</code></p>
<p>after I deploy the WorkerRole the following error is in both the ConfigureCloudService.err and LaunchWorker.err.</p>
<pre><code>gi : Cannot find path 'E:\approot\%INTERPRETERPATH%' because it does not exist.
At E:\approot\bin\ConfigureCloudService.ps1:189 char:15
+ Set-Alias py (gi $interpreter_path -EA Stop)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (E:\approot\%INTERPRETERPATH%:String) [Get-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand
</code></pre>
| -2 | 2016-07-21T16:15:37Z | 38,560,924 | <p>@andrewkittredge, I don't think you need to install Python environment manually before deploying a WorkerRole or a WebJob, because the Python runtime has been installed on Azure, just need to be specified or set up in the related configuration.</p>
<p>According to the <a href="https://azure.microsoft.com/en-us/documentation/articles/cloud-services-python-ptvs/" rel="nofollow">article</a>, you need to create a workrole via VS with PTVS. Then, <code>Install Python on the cloud service</code> means you need to set the Python variable to <code>on</code> on the startup tasks in the <code>ServiceDefinition.csdef</code> file as below.</p>
<pre><code><Variable name="PYTHON2" value="on" />
</code></pre>
<p>Please see the article <a href="https://azure.microsoft.com/en-us/documentation/articles/cloud-services-startup-tasks-common/" rel="nofollow">Common Cloud Service startup tasks</a> to know the startup tasks for Cloud Services.</p>
<p>Compared with <code>WorkerRole</code>, I think <code>WebJobs</code> is easier to use and deploy, please see the articles <a href="https://azure.microsoft.com/en-us/documentation/articles/web-sites-create-web-jobs/" rel="nofollow">Run Background tasks with WebJobs</a> and <a href="https://azure.microsoft.com/en-us/documentation/articles/websites-dotnet-deploy-webjobs/" rel="nofollow">Deploy WebJobs using Visual Studio</a>.</p>
| 0 | 2016-07-25T06:22:14Z | [
"python",
"azure",
"azure-sdk-python"
] |
Python Logging in Bottle not working in route | 38,509,377 | <p>I am trying to use the Python logging library to log messages in my Bottle app. The logging works as expected outside the route, but my app is not logging anything in a route. Any idea what's wrong?</p>
<pre><code>import logging
#logging
logger = logging.getLogger('myApp')
logger.setLevel(logging.INFO)
fh = logging.FileHandler('log.log')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.info("Starting my application.") #this logs as expected
@route('/myRoute', method='POST')
def returnWord():
userWord = (request.forms.get('submittedWord')).lower()
# this doesn't log anything
logger.info("testing logging inside route. word: %s" % (userWord))
return template('<b>Hello {{name}}</b>!', name=userWord)
if __name__ == "__main__":
daemon_run(host='0.0.0.0', port=8080)
</code></pre>
| 0 | 2016-07-21T16:17:12Z | 39,001,814 | <p>Your example works for me.
You are probably getting an error before getting to the line</p>
<pre><code>logger.info("testing logging inside route. word: %s" % (userWord))
</code></pre>
<p>Notice that you should see on your console the following line if your POST went well</p>
<blockquote>
<p>127.0.0.1 - - [17/Aug/2016 19:20:15] "POST /myRoute HTTP/1.1" 200 20</p>
</blockquote>
<p>To be sure you are own the right track add a simple function like this</p>
<pre><code>@route('/testy', method='GET')
def testy():
logger.info("testy is online :)")
return "COOL"
</code></pre>
<p>Direct your web browser to localhost:8080/testy and see the COOL message.
Now you'll also see the log message in your file.</p>
| 0 | 2016-08-17T16:25:14Z | [
"python",
"logging",
"routing",
"bottle"
] |
Accessing non-subscriptable properties | 38,509,475 | <p>Scripting the Blender, I successfully did <code>bpy.ops.render.render(some_args)</code> but <code>bpy.ops.render['render']</code> fails with BPyOpsSubMod object is not subscriptable. This puzzles me since I expected that, likewise in Javascript, any Python object is a dictionary and I can access object methods either by <code>obj.member</code> or <code>obj['member']</code>. How do I work around the non-subscriptable properties when I want to reference them by name?</p>
| 0 | 2016-07-21T16:21:31Z | 38,509,636 | <p>It's not true that every object <em>is</em> a dictionary. Every object <em>has</em> a dictionary, accessible through the name <a href="https://docs.python.org/3/library/stdtypes.html#object.__dict__" rel="nofollow"><code>.__dict__</code></a>.</p>
<p>You can use either</p>
<pre><code>bpy.ops.render.__dict__['render']
</code></pre>
<p>or</p>
<pre><code>getattr(bpy.ops.render, 'render')
</code></pre>
| -1 | 2016-07-21T16:30:02Z | [
"python",
"python-3.x",
"reference",
"attributes",
"members"
] |
multi-threadings and multi-processes pools in multiprocessing | 38,509,514 | <p>As for multi-threadings and multi-processes pools in <code>multiprocessing</code></p>
<pre><code> pool = Pool()
result = pool.map(func, arg)
pool.close()
pool.join()
</code></pre>
<p>Why <code>close</code> and <code>join</code> are necessary to make the code <strong>safe</strong>? What bad consequences can it make without them?</p>
<p>In a loop, it's better to put these lines inside or outside the loop?</p>
<p>For example,</p>
<pre><code> pool = Pool()
for x in a_ndarray:
result = pool.map(func, x)
save(result)
pool.close()
pool.join()
</code></pre>
<p>and</p>
<pre><code> pool = Pool()
for x in a_ndarray:
result = pool.map(func, x)
save(result)
pool.close()
pool.join()
</code></pre>
<p>I saw others suggested multi-processes for CPU-bound tasks and multi-threadings for IO-bound tasks. But what are the disadvantages of applying multi-threading to CPU-bound and multi-processes to IO-bound?</p>
| 0 | 2016-07-21T16:23:26Z | 38,510,437 | <p>@Lee Hi Folk,</p>
<p>Basically, these instructions will set some closure concepts into the current executions, it will say "I won't put more data into the queue(<code>close</code>) and I'll wait the end of the sub-processes before go on(<code>join</code>)".</p>
<p>From docs:</p>
<blockquote>
<p>close()</p>
<p>Indicate that no more data will be put on this queue by the current >process. The background thread will quit once it has flushed all buffered data to the pipe. This is called automatically when the queue is garbage collected.</p>
</blockquote>
<hr>
<blockquote>
<p>join()</p>
<p>Block until all items in the queue have been gotten and processed.</p>
<p>The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks.</p>
</blockquote>
<p>Source: <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">Python Docs</a></p>
<p>This will make better and safer your code because it will use this information to do a proper <em>Garbage Collection</em> and will avoid <em>weird or unwanted</em> behavior of the code like ending the main process before child processes end. </p>
<p>For example, if after launch the sub-processes you call a function that could vary in time execution:</p>
<pre><code>pool = Pool()
for x in a_ndarray:
result = pool(func, x)
save(result)
non_fixed_time_function() #this could take 0.1 s or 2 hours.
#pool.join() # Don't wait for child to finish
</code></pre>
<p>If you don't wait for child to finish, in a execution could do exactly as you want, in other could finish just one child or 2 children, and this would cause weird results.</p>
<p>About your second question, in that scenario, I would take the <code>.close()</code> and <code>.join()</code> methods inside the loop, before save the result.</p>
| 1 | 2016-07-21T17:12:32Z | [
"python",
"multithreading",
"multiprocessing"
] |
Numpy: Checking if a value is NaT | 38,509,538 | <pre><code>nat = np.datetime64('NaT')
nat == nat
>> FutureWarning: In the future, 'NAT == x' and 'x == NAT' will always be False.
np.isnan(nat)
>> TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
</code></pre>
<p>How can I check if a datetime64 is NaT? I can't seem to dig anything out of the docs. I know Pandas can do it, but I'd rather not add a dependency for something so basic.</p>
| 2 | 2016-07-21T16:25:01Z | 38,531,233 | <p>When you make a comparison at the first time, you always have a warning. But meanwhile returned result of comparison is correct:</p>
<pre><code>import numpy as np
nat = np.datetime64('NaT')
def nat_check(nat):
return nat == np.datetime64('NaT')
nat_check(nat)
Out[4]: FutureWarning: In the future, 'NAT == x' and 'x == NAT' will always be False.
True
nat_check(nat)
Out[5]: True
</code></pre>
<p>If you want to suppress the warning you can use the <a href="https://docs.python.org/3.5/library/warnings.html#temporarily-suppressing-warnings" rel="nofollow">catch_warnings</a> context manager:</p>
<pre><code>import numpy as np
import warnings
nat = np.datetime64('NaT')
def nat_check(nat):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return nat == np.datetime64('NaT')
nat_check(nat)
Out[5]: True
</code></pre>
<p>And finally you might check numpy version to handle changed behavior since version 1.12.0:</p>
<pre><code>def nat_check(nat):
if [int(x) for x in np.__version__.split('.')[:-1]] > [1, 11]:
return nat != nat
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return nat == np.datetime64('NaT')
</code></pre>
| 1 | 2016-07-22T16:22:26Z | [
"python",
"numpy"
] |
Numpy: Checking if a value is NaT | 38,509,538 | <pre><code>nat = np.datetime64('NaT')
nat == nat
>> FutureWarning: In the future, 'NAT == x' and 'x == NAT' will always be False.
np.isnan(nat)
>> TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
</code></pre>
<p>How can I check if a datetime64 is NaT? I can't seem to dig anything out of the docs. I know Pandas can do it, but I'd rather not add a dependency for something so basic.</p>
| 2 | 2016-07-21T16:25:01Z | 40,130,488 | <p>Another way would be to catch the exeption:</p>
<pre><code>def is_nat(npdatetime):
try:
npdatetime.strftime('%x')
return False
except:
return True
</code></pre>
| 0 | 2016-10-19T11:43:17Z | [
"python",
"numpy"
] |
Problems with newline parameter in numpy savetxt function | 38,509,654 | <p>Having the structured array like this :</p>
<p><code>[ (b'H', 0.9425, 0.1412, 7.1414) ... (b'N', 1.0037, 4.0524, 6.8000)]</code></p>
<p>I want to make a <code>.txt file</code> using <code>numpy.savetxt</code> where each element of the array is written in separate line:</p>
<pre><code>H 0.9425 0.1412 7.1414
N 1.0037 4.0524 6.8000
</code></pre>
<p>I set the <code>newline='\n'</code> but it doesn't work properly and all the elements are written in single line. The same problem with <strong><em>header</em></strong> parameter, the specified header is also printed in the same line.</p>
<p>Now it looks like this:</p>
<pre><code>29Shifts: 1.0 3.0 7.0b'C' 1.0029 3.5098 7.9883 b'N' 1.0039 4.0586 6.8008
29Shifts: 1.0 4.0 0.0b'C' 1.0029 4.5078 0.9873 b'N' 1.0039 5.0586 -0.2000
29Shifts: 1.0 5.0 9.0b'C' 1.0029 5.5078 9.9844 b'N' 1.0039 6.0586 8.7969
</code></pre>
<p>Here are the parameters used:</p>
<pre><code>np.savetxt(outfile, recarray, fmt=[b'%s','%-7.4f','%-7.4f','%-7.4f'], delimiter=' ', newline='\n', header='29\nShifts: 1.0 1.0 3.5\n', comments='')
</code></pre>
<p>Thank you</p>
| 0 | 2016-07-21T16:30:48Z | 38,518,321 | <p>I wonder if there's a problem with <code>\n</code> on your system; maybe Python is using one value, while your file viewer is expecting another (there are dos, linux, and mac standards).</p>
<p>I have no problem with this data and format in an Ipython session on a linux machine.</p>
<pre><code>In [88]: d=[ (b'H', 0.9425, 0.1412, 7.1414),(b'N', 1.0037, 4.0524, 6.8000)]
In [89]: data=np.array(d,'|S1,f,f,f')
In [90]: data
Out[90]:
array([(b'H', 0.9424999952316284, 0.1412000060081482, 7.14139986038208),
(b'N', 1.0037000179290771, 4.0524001121521, 6.800000190734863)],
dtype=[('f0', 'S1'), ('f1', '<f4'), ('f2', '<f4'), ('f3', '<f4')])
In [91]: np.savetxt('test.txt', data,fmt =[b'%s','%-7.4f','%-7.4f','%-7.4f'])
In [92]: cat test.txt
b'H' 0.9425 0.1412 7.1414
b'N' 1.0037 4.0524 6.8000
In [93]np.savetxt('test.txt', data,fmt=[b'%s','%-7.4f','%-7.4f','%-7.4f'],
delimiter=' ', newline='\n', header='29\nShifts: 1.0 1.0 3.5\n', comments ='')
In [94]: cat test.txt
29
Shifts: 1.0 1.0 3.5
b'H' 0.9425 0.1412 7.1414
b'N' 1.0037 4.0524 6.8000
</code></pre>
| 0 | 2016-07-22T04:44:29Z | [
"python",
"numpy"
] |
Execute another python script, then shut down current script | 38,509,674 | <p>I have a python script <code>script_a.py</code> that uses <code>subprocess.call()</code> that executes another script <code>script_b.py</code> as it's last instruction before ending. I need <code>script_b.py</code> to wait until <code>script_a.py</code> closes before proceeding with its own instructions. For this I am using a while loop within <code>script_b.py</code>. How can I do this? All of my current solutions I have tried have <code>script_a.py</code> waiting until <code>script_b.py</code> is finished before it closes itself. I have a feeling this might involve <code>atexit()</code> or something similar, but I am lost.</p>
<p>Many thanks!</p>
| 2 | 2016-07-21T16:31:43Z | 38,510,262 | <p>Your script_a.py would be:</p>
<pre><code>import subprocess
#do whatever stuff you want here
p = subprocess.Popen(["python","b.py"])
p.wait()
p.terminate()
#continue doing stuff
</code></pre>
| 1 | 2016-07-21T17:02:49Z | [
"python",
"subprocess",
"sys"
] |
Execute another python script, then shut down current script | 38,509,674 | <p>I have a python script <code>script_a.py</code> that uses <code>subprocess.call()</code> that executes another script <code>script_b.py</code> as it's last instruction before ending. I need <code>script_b.py</code> to wait until <code>script_a.py</code> closes before proceeding with its own instructions. For this I am using a while loop within <code>script_b.py</code>. How can I do this? All of my current solutions I have tried have <code>script_a.py</code> waiting until <code>script_b.py</code> is finished before it closes itself. I have a feeling this might involve <code>atexit()</code> or something similar, but I am lost.</p>
<p>Many thanks!</p>
| 2 | 2016-07-21T16:31:43Z | 38,511,400 | <p>you could make some totally hacky crap</p>
<p><strong>script_b.py</strong></p>
<pre><code>while not os.path.exists("a.done"):pass
time.sleep(0.2) # a little longer just to be really sure ...
os.remove("a.done")
... # rest of script b
</code></pre>
<p><strong>script_a.py</strong></p>
<pre><code>import atexit
atexit.register(lambda *a:open("a.done","w"))
</code></pre>
<hr>
<p>or instead of <code>Popen</code> just do</p>
<pre><code>os.execl("/usr/bin/python","script_b.py")
</code></pre>
| 1 | 2016-07-21T18:07:47Z | [
"python",
"subprocess",
"sys"
] |
Populate dictionary from list in loop | 38,509,704 | <p>I have the following code that works fine and I was wondering how to implement the same logic using list comprehension.</p>
<pre><code>def get_features(document, feature_space):
features = {}
for w in feature_space:
features[w] = (w in document)
return features
</code></pre>
<p>Also am I going to get any improvements in performance by using a list comprehension?</p>
<p>The thing is that both <code>feature_space</code> and <code>document</code> are relatively big and many iterations will run.</p>
<p><strong>Edit</strong>: Sorry for not making it clear at first, both <code>feature_space</code> and <code>document</code> are lists.</p>
<ul>
<li><code>document</code> is a list of words (a word may exist more than once!)</li>
<li><code>feature_space</code> is a list of labels (features)</li>
</ul>
| 3 | 2016-07-21T16:33:00Z | 38,509,750 | <p>Like this, with a <em>dict comprehension</em>:</p>
<pre><code>def get_features(document, feature_space):
return {w: (w in document) for w in feature_space}
</code></pre>
<p>The <code>features[key] = value</code> expression becomes the <code>key: value</code> part at the start, and the rest of the <code>for</code> loop(s) and any <code>if</code> statements follow in nesting order.</p>
<p>Yes, this will give you a performance boost, because you've now removed all <code>features</code> local name lookups and the <code>dict.__setitem__</code> calls.</p>
<p>Note that you need to make sure that <code>document</code> is a data structure that has fast membership tests. If it is a list, convert it to a <code>set()</code> first, for example, to ensure that membership tests take O(1) (constant) time, not the O(n) linear time of a list:</p>
<pre><code>def get_features(document, feature_space):
document = set(document)
return {w: (w in document) for w in feature_space}
</code></pre>
<p>With a <code>set</code>, this is now a O(K) loop instead of a O(KN) loop (where N is the size of <code>document</code>, <code>K</code> the size of <code>feature_space)</code>.</p>
| 3 | 2016-07-21T16:35:11Z | [
"python",
"python-3.x",
"dictionary-comprehension"
] |
Setting Flask dictionary value via Jinja | 38,509,765 | <p>If I was to use the following in my Jinja template:</p>
<pre><code>{% set data['enabled'] = True %}
</code></pre>
<p>I receive the error <code>TemplateSyntaxError: expected token '=', got '['</code>. Setting one word variables is fine, but as the error states, setting dictionary values through Jinja brings an error.</p>
<p>Is there a workaround for this issue? Thanks.</p>
| 0 | 2016-07-21T16:35:46Z | 38,509,972 | <p>Jinja2 tries to limit assignments in its code, to remove the logic from the view (check out an <a href="http://martinfowler.com/eaaDev/uiArchs.html" rel="nofollow">MVC explanation</a>).</p>
<p>If you still want to do an assignment you will have to use <a href="https://docs.python.org/3/library/stdtypes.html#dict.update" rel="nofollow">update</a> with a do block. For this you have to enable <a href="http://jinja.pocoo.org/docs/dev/extensions/#expression-statement" rel="nofollow">Expression Statements</a>. After that you can try something like this:</p>
<pre><code>{% do data.update({'enabled':'True'}) %}
</code></pre>
| 2 | 2016-07-21T16:46:36Z | [
"python",
"flask",
"jinja2"
] |
Get the current and next value in a Jinja for loop | 38,509,802 | <p>Is there a way to iterate over a list in Jinja2 that can access the nth and (n+1) th element in a single iteration?</p>
<pre><code>{% for x in my_list %}
<!-- print the current and the (current+1) -->
{{x}}, {{x+1}} <-- this is wrong but hopefully highlights the problem
{% endfor %}
</code></pre>
<p>Also, does the for loop allow for a "step" increment?</p>
| 0 | 2016-07-21T16:38:32Z | 38,514,019 | <p>Jinja has a <a href="http://jinja.pocoo.org/docs/dev/templates/#for" rel="nofollow"><code>loop.index</code></a> variable that you can use to access the next value in your list:</p>
<pre><code>@app.route('/')
def index():
return render_template_string("""
<body>
{% for x in my_list %}
<p>
{{ x }} {{ my_list[loop.index] }}<br>
</p>
{% endfor %}
</body>
""", my_list=range(10))
</code></pre>
<blockquote>
<p>0 1</p>
<p>1 2</p>
<p>2 3</p>
<p>3 4</p>
<p>4 5</p>
<p>5 6</p>
<p>6 7</p>
<p>7 8</p>
<p>8 9</p>
<p>9 </p>
</blockquote>
| 0 | 2016-07-21T20:42:07Z | [
"python",
"flask",
"jinja2"
] |
Define custom error messages on invalid attribute call | 38,509,807 | <p>How do I define custom error messages for specific invalid attribute calls in python? </p>
<p>I wrote a class thats attribute assignment is dependent on the input on instance creation and like to return a more descriptive error message if an unassigned attribute is called:</p>
<pre><code>class test:
def __init__(self, input):
if input == 'foo':
self.type = 'foo'
self.a = 'foo'
if input == 'bar':
self.type = 'bar'
self.b = 'bar'
class_a = test('foo')
print class_a.a
print class_a.b
</code></pre>
<p>On execution I get this error-message</p>
<pre><code>AttributeError: test instance has no attribute 'b'
</code></pre>
<p>Instead of that I'd like to get something like</p>
<pre><code>AttributeError: test instance is of type 'foo' and therefore has no b-attribute
</code></pre>
| 0 | 2016-07-21T16:38:51Z | 38,510,732 | <p>Override <strong>getattr</strong> in your class.</p>
<pre><code>class test(object):
def __init__(self, input):
if input == 'foo':
self.type = 'foo'
self.a = 'foo'
if input == 'bar':
self.type = 'bar'
self.b = 'bar'
def __getattr__(self, attr):
raise AttributeError("'test' object is of type '{}' and therefore has no {}-attribute.".format(self.type, attr))
</code></pre>
<p><strong>getattr</strong> is called when python can't find the attribute normally. Essentially, it's like an "except" clause when your class raises an AttributeError.</p>
| 1 | 2016-07-21T17:30:31Z | [
"python",
"class",
"error-handling",
"attributes"
] |
"Almost Equal" in Jasmine | 38,509,815 | <p><strong>The Story:</strong></p>
<p>In Python built-in <code>unittest</code> framework, there is an "approximate equality" assertion implemented via <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual"><code>assertAlmostEqual()</code></a> method:</p>
<pre><code>x = 0.1234567890
y = 0.1234567891
self.assertAlmostEqual(x, y)
</code></pre>
<p>Which has the number of decimal places to check configurable.</p>
<p>And, there is a <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.testing.assert_almost_equal.html"><code>numpy.testing.assert_almost_equal()</code></a> which also works for the arrays of floats:</p>
<pre><code>import numpy.testing as npt
import numpy as np
npt.assert_almost_equal(np.array([1.0,2.3333333333333]), np.array([1.0,2.33333334]))
</code></pre>
<p><strong>The Question:</strong></p>
<p>How to make an "almost equal" assertion <em>in JavaScript/Jasmine</em> for floats and array of floats?</p>
| 9 | 2016-07-21T16:39:13Z | 38,556,097 | <p>For a single float, use <a href="https://github.com/jasmine/jasmine/blob/master/src/core/matchers/toBeCloseTo.js"><code>toBeCloseTo</code></a>:</p>
<pre><code>expect(x).toBeCloseTo(y, 7)
</code></pre>
<p>For a float array, it seems the best you could do is loop over it and call <code>toBeCloseTo</code> for each pair of elements (or write your own matcher). See <a href="http://stackoverflow.com/questions/35318278/expect-an-array-of-float-numbers-to-be-close-to-another-array-in-jasmine">Expect an array of float numbers to be close to another array in Jasmine</a>.</p>
| 5 | 2016-07-24T19:49:45Z | [
"javascript",
"python",
"unit-testing",
"testing",
"jasmine"
] |
"Almost Equal" in Jasmine | 38,509,815 | <p><strong>The Story:</strong></p>
<p>In Python built-in <code>unittest</code> framework, there is an "approximate equality" assertion implemented via <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual"><code>assertAlmostEqual()</code></a> method:</p>
<pre><code>x = 0.1234567890
y = 0.1234567891
self.assertAlmostEqual(x, y)
</code></pre>
<p>Which has the number of decimal places to check configurable.</p>
<p>And, there is a <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.testing.assert_almost_equal.html"><code>numpy.testing.assert_almost_equal()</code></a> which also works for the arrays of floats:</p>
<pre><code>import numpy.testing as npt
import numpy as np
npt.assert_almost_equal(np.array([1.0,2.3333333333333]), np.array([1.0,2.33333334]))
</code></pre>
<p><strong>The Question:</strong></p>
<p>How to make an "almost equal" assertion <em>in JavaScript/Jasmine</em> for floats and array of floats?</p>
| 9 | 2016-07-21T16:39:13Z | 38,575,094 | <p>You can add a custom equality tester for the float type. It will be called on a single float and on each float present in an array:</p>
<pre class="lang-js prettyprint-override"><code>beforeEach(function () {
jasmine.addCustomEqualityTester(function floatEquality(a, b) {
if (a === +a && b === +b && (a !== (a|0) || b !== (b|0))) { // if float
return Math.abs(a - b) < 5e-8;
}
});
});
it("Should compare array of floats", function() {
expect([0.1234567890]).toEqual([0.1234567891]); // OK
expect([0.12345]).toEqual([0.12346]); // FAIL
});
</code></pre>
| 4 | 2016-07-25T18:34:30Z | [
"javascript",
"python",
"unit-testing",
"testing",
"jasmine"
] |
How to use certain elements in a list to compare elements in other lists and output a certain element if duplicates are found in Python? | 38,509,829 | <p>I am new here (and new to programming).
I have tried to locate the relevant questions with no luck.</p>
<p>Basically, I got some lists shown below:</p>
<pre><code>[0, 'a', 1, 3, 3.3, 220, 22.27]
[0, 'b', 1, 13, 3.3, 220, 23.19]
[0, 'c', 1, 23, 3.3, 220, 24.11]
[1, 'a', 1, 3, 3.5, 200, 20.02]
[1, 'b', 1, 43, 3.3, 220, 25.94]
[2, 'a', 1, 3, 3.3, 250, 26.86]
</code></pre>
<p>I would like to use list items of indices <code>1</code>, <code>2</code> and <code>3</code> as the comparison key and search within all the lists available with the given key. </p>
<p>If found, then I need it the output to be made up of the list items of indices <code>0</code>, <code>4</code>, <code>5</code> and <code>-1</code>.</p>
<p>So, with the given lists, the desired procedure is shown below.</p>
<p>First round:</p>
<ul>
<li>comparison key : <code>'a'</code>, <code>1</code>, <code>3</code> </li>
<li>go through the available lists</li>
<li><p>found the same key in </p>
<blockquote>
<p>[0, <strong>'a', 1, 3,</strong> 3.3, 220, 22.27]</p>
<p>[1, <strong>'a', 1, 3,</strong> 3.5, 200, 20.02]</p>
<p>[2, <strong>'a', 1, 3,</strong> 3.3, 250, 26.86]</p>
</blockquote></li>
<li><p>then create the output</p>
<blockquote>
<p>0, 3.3, 220, 22.27 </p>
<p>1, 3.5, 200, 20.02 </p>
<p>2, 3.3, 250, 26.86</p>
</blockquote></li>
</ul>
<p>I have no idea how to code this yet, so could anyone help me please?</p>
<p>Thanks in advance</p>
| 0 | 2016-07-21T16:39:41Z | 38,510,139 | <p>@wagaman: Hi Pal, Here a little snippet to do this job:</p>
<pre><code>universe = []
universe.append([0, 'a', 1, 3, 3.3, 220, 22.27])
universe.append([0, 'b', 1, 13, 3.3, 220, 23.19])
universe.append([0, 'c', 1, 23, 3.3, 220, 24.11])
universe.append([1, 'a', 1, 3, 3.5, 200, 20.02])
universe.append([1, 'b', 1, 43, 3.3, 220, 25.94])
universe.append([2, 'a', 1, 3, 3.3, 250, 26.86])
def extract_from_lists(universe, keys=[1,2,3], matches=['a',1,3]):
if len(keys) == len(matches):
for l in universe:
valid = True
for i in range(len(keys)):
if l[keys[i]] != matches[i]:
valid = False
break
if valid:
print("{},{},{},{}".format(l[0],l[4],l[5],l[-1]))
else:
print('Keys List and Matches List length must be equal.')
extract_from_lists(universe)
</code></pre>
<p>If you need further information about it, let me know, it's a very simple comparison and use basic concepts of python as default values of arguments, iteration and so.</p>
| 0 | 2016-07-21T16:55:30Z | [
"python",
"list",
"compare"
] |
How to use certain elements in a list to compare elements in other lists and output a certain element if duplicates are found in Python? | 38,509,829 | <p>I am new here (and new to programming).
I have tried to locate the relevant questions with no luck.</p>
<p>Basically, I got some lists shown below:</p>
<pre><code>[0, 'a', 1, 3, 3.3, 220, 22.27]
[0, 'b', 1, 13, 3.3, 220, 23.19]
[0, 'c', 1, 23, 3.3, 220, 24.11]
[1, 'a', 1, 3, 3.5, 200, 20.02]
[1, 'b', 1, 43, 3.3, 220, 25.94]
[2, 'a', 1, 3, 3.3, 250, 26.86]
</code></pre>
<p>I would like to use list items of indices <code>1</code>, <code>2</code> and <code>3</code> as the comparison key and search within all the lists available with the given key. </p>
<p>If found, then I need it the output to be made up of the list items of indices <code>0</code>, <code>4</code>, <code>5</code> and <code>-1</code>.</p>
<p>So, with the given lists, the desired procedure is shown below.</p>
<p>First round:</p>
<ul>
<li>comparison key : <code>'a'</code>, <code>1</code>, <code>3</code> </li>
<li>go through the available lists</li>
<li><p>found the same key in </p>
<blockquote>
<p>[0, <strong>'a', 1, 3,</strong> 3.3, 220, 22.27]</p>
<p>[1, <strong>'a', 1, 3,</strong> 3.5, 200, 20.02]</p>
<p>[2, <strong>'a', 1, 3,</strong> 3.3, 250, 26.86]</p>
</blockquote></li>
<li><p>then create the output</p>
<blockquote>
<p>0, 3.3, 220, 22.27 </p>
<p>1, 3.5, 200, 20.02 </p>
<p>2, 3.3, 250, 26.86</p>
</blockquote></li>
</ul>
<p>I have no idea how to code this yet, so could anyone help me please?</p>
<p>Thanks in advance</p>
| 0 | 2016-07-21T16:39:41Z | 38,516,669 | <p>Let us first define the input data:</p>
<pre><code>some_lists = [[0, 'a', 1, 3, 3.3, 220, 22.27],
[0, 'b', 1, 13, 3.3, 220, 23.19],
[0, 'c', 1, 23, 3.3, 220, 24.11],
[1, 'a', 1, 3, 3.5, 200, 20.02],
[1, 'b', 1, 43, 3.3, 220, 25.94],
[2, 'a', 1, 3, 3.3, 250, 26.86]]
</code></pre>
<p>We have to iterate over the sublists of <code>some_lists</code>. To that end we will use an index variable, say <code>x</code>. For each sublist <code>x</code> we need to check whether <code>x[1] == 'a' and x[2] == 1 and x[3] == 3</code> is fulfilled or not. This logical expression can be simplified through <a href="http://stackoverflow.com/questions/509211/explain-pythons-slice-notation">slice notation</a> to <code>x[1:4] == ['a', 1, 3]</code>. For those <code>x</code> that match the condition, we create the desired output by selecting the specified items, namely <code>[x[0], x[4], x[5], x[-1]]</code>. All this logic can be readily implemented through a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> in just one line of code:</p>
<pre><code>In [253]: [[x[0], x[4], x[5], x[-1]] for x in some_lists if x[1:4] == ['a', 1, 3]]
Out[253]: [[0, 3.3, 220, 22.27], [1, 3.5, 200, 20.02], [2, 3.3, 250, 26.86]]
</code></pre>
| 0 | 2016-07-22T01:05:32Z | [
"python",
"list",
"compare"
] |
Error loading a image file into ndarray with scipy.ndimage.imread | 38,509,870 | <p>Im trying to load a image file into a ndarray with something like this:</p>
<pre><code>image_data = ndimage.imread(image_file).astype(float)
</code></pre>
<p>but i get this error:</p>
<pre><code>/home/milos/anaconda3/envs/tensorflow/lib/python3.5/site-packages/scipy/ndimage/io.py in imread(fname, flatten, mode)
23 if _have_pil:
24 return _imread(fname, flatten, mode)
---> 25 raise ImportError("Could not import the Python Imaging Library (PIL)"
26 " required to load image files. Please refer to"
27 " http://pypi.python.org/pypi/PIL/ for installation"
ImportError: Could not import the Python Imaging Library (PIL) required to load image files. Please refer to http://pypi.python.org/pypi/PIL/ for installation instructions.
</code></pre>
<p>I have Pillow installed inside the environment from which im running the notebook, it also shows up on pip freeze.
I also tried running it from the console but got similar error.</p>
<p>Any ideas how to fix this? Or is there a alternative way to load a image into ndarray?</p>
| 0 | 2016-07-21T16:41:44Z | 38,510,552 | <p>Managed to do it in the end by bypassing scipy : </p>
<pre><code>from PIL import Image
img = Image.open(image_file)
image_data = np.array(img).astype(float)
</code></pre>
<p>would still like to know what the problem is with scipy, so please post if you know it</p>
<p>Edit :</p>
<p>Found a better solution:</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image_data = mpimg.imread(image_file)
</code></pre>
<p>this creates a numpy ndarray and normalizes the pixel depths to 0-1, and it worked nicely if i wanted to do a backwards conversion to check if its still good: </p>
<pre><code>plt.imshow(image_data)
</code></pre>
| 2 | 2016-07-21T17:20:00Z | [
"python",
"scipy"
] |
Error loading a image file into ndarray with scipy.ndimage.imread | 38,509,870 | <p>Im trying to load a image file into a ndarray with something like this:</p>
<pre><code>image_data = ndimage.imread(image_file).astype(float)
</code></pre>
<p>but i get this error:</p>
<pre><code>/home/milos/anaconda3/envs/tensorflow/lib/python3.5/site-packages/scipy/ndimage/io.py in imread(fname, flatten, mode)
23 if _have_pil:
24 return _imread(fname, flatten, mode)
---> 25 raise ImportError("Could not import the Python Imaging Library (PIL)"
26 " required to load image files. Please refer to"
27 " http://pypi.python.org/pypi/PIL/ for installation"
ImportError: Could not import the Python Imaging Library (PIL) required to load image files. Please refer to http://pypi.python.org/pypi/PIL/ for installation instructions.
</code></pre>
<p>I have Pillow installed inside the environment from which im running the notebook, it also shows up on pip freeze.
I also tried running it from the console but got similar error.</p>
<p>Any ideas how to fix this? Or is there a alternative way to load a image into ndarray?</p>
| 0 | 2016-07-21T16:41:44Z | 39,311,336 | <p>I'm using Python 2.7.x and encountering the same problem. I'm not sure what's going on with scipy.ndimage.imread() in this context either. Uninstalling Pillow (PIL) does not resolve the problem. So, I did the same as what Milos proposed and it worked:</p>
<pre><code>import PIL
import numpy as np
image_file = './my_image.png'
image_data = np.array(PIL.Image.open(image_file)).astype(float)
</code></pre>
| 0 | 2016-09-03T21:07:31Z | [
"python",
"scipy"
] |
Lost accent characters php | 38,509,878 | <p>good afternoon , I have a script in python to run it from PHP. The script makes a query to a database and returns a JSON object :</p>
<p><code>[{"ESC_DEF": 0, "ESC_EJE": 2017, "ESC_FEC_PRE": null, "ESC_USU_BAJA": null, "ESC_NOM": "prueba fran 3", "ESC_SIT": "ABIERTO", "ESC_USU_ALTA": "hep68", "RONDA_ID": 1, "ESC_ORI": "Gestión Económica", "ESC_SIT2": "BORRADOR", "ESC_FEC_FRCG": null, "ESC_TPO": "PRESUPUESTO", "ESC_ORG": "1214", "ESC_FEC_ALTA": "19/07/2016 10:39:20", "ESC_FEC_FIR": null, "CRE": 0.00, "ID_PTOEGE": null, "ESC_FEC_BAJA": null, "ESC_COD_BAJA": null, "ID": 3637, "EST_ORG_NOM": null}]</code></p>
<p>The command I use is :</p>
<pre><code>son_output = json.dumps((my_query), default=custom_json, ensure_ascii=False)`
</code></pre>
<p>In PHP I run and pick up the result as follows :</p>
<pre><code>exec('python3 sqlserver.py'. " ".$parametro, $output, $ret_code);
$json = implode($output);
echo utf8_encode(stripslashes($json));
</code></pre>
<p>But the content is displayed as follows :</p>
<blockquote>
<p>"ESC_ORI": "Gestixc3xb3n Econxc3xb3mica"</p>
</blockquote>
<p>Accented characters are not displayed correctly .</p>
<p>Sorry if I did not express myself well in English .</p>
| 0 | 2016-07-21T16:42:03Z | 38,510,338 | <p>"\xc3\xb3" is "ó". In removing the slashes with stripslashes($str) you're also losing the unicode escapes and therefore only getting the weird chars instead of the small latin o you're looking for. Not well versed in php but try running without that function.</p>
| 0 | 2016-07-21T17:07:06Z | [
"php",
"python",
"json",
"utf-8"
] |
How do I load balance phantomjs using docker-compose and haproxy? | 38,510,040 | <p>I have an application that uses selenium webdriver to interface with PhantomJS. To scale things up, I want to run multiple instances of PhantomJS and load balance them with haproxy. This is for a local application, so I'm not concerned with deployment to a production environment or anything like that.</p>
<p>Here's my <code>docker-compose.yml</code> file:</p>
<pre><code>version: '2'
services:
app:
build: .
volumes:
- .:/code
links:
- mongo
- haproxy
mongo:
image: mongo
phantomjs1:
image: wernight/phantomjs:latest
ports:
- 8910
entrypoint:
- phantomjs
- --webdriver=8910
- --ignore-ssl-errors=true
- --load-images=false
phantomjs2:
image: wernight/phantomjs:latest
ports:
- 8910
entrypoint:
- phantomjs
- --webdriver=8910
- --ignore-ssl-errors=true
- --load-images=false
phantomjs3:
image: wernight/phantomjs:latest
ports:
- 8910
entrypoint:
- phantomjs
- --webdriver=8910
- --ignore-ssl-errors=true
- --load-images=false
phantomjs4:
image: wernight/phantomjs:latest
ports:
- 8910
entrypoint:
- phantomjs
- --webdriver=8910
- --ignore-ssl-errors=true
- --load-images=false
haproxy:
image: haproxy
volumes:
- ./haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
ports:
- 8910:8910
links:
- phantomjs1
- phantomjs2
- phantomjs3
- phantomjs4
</code></pre>
<p>As you can see, I've got four instances of phantomjs, one haproxy instance, and one app (written in python).</p>
<p>Here's my <code>haproxy.cfg</code>:</p>
<pre><code>global
log 127.0.0.1 local0
log 127.0.0.1 local1 notice
maxconn 4096
daemon
defaults
log global
mode http
option httplog
option dontlognull
retries 3
option redispatch
maxconn 2000
timeout connect 5000
timeout client 50000
timeout server 50000
frontend phantomjs_front
bind *:8910
stats uri /haproxy?stats
default_backend phantomjs_back
backend phantomjs_back
balance roundrobin
server phantomjs1 phantomjs1:8910 check
server phantomjs2 phantomjs2:8910 check
server phantomjs3 phantomjs3:8910 check
server phantomjs4 phantomjs4:8910 check
</code></pre>
<p>I know I need to use sticky sessions or something in haproxy to get this to work, but I don't know how to do that.</p>
<p>Here's a relevant snippet of my python app code that connects to this service:</p>
<pre><code>def get_page(url):
driver = webdriver.Remote(
command_executor='http://haproxy:8910',
desired_capabilities=DesiredCapabilities.PHANTOMJS
)
driver.get(url)
source = driver.page_source
driver.close()
return source
</code></pre>
<p>The error I get when I try to run this code is this:</p>
<pre><code>phantomjs2_1 | [ERROR - 2016-07-12T23:35:25.454Z] RouterReqHand - _handle.error - {"name":"Variable Resource Not Found","message":"{\"headers\":{\"Accept\":\"application/json\",\"Accept-Encoding\":\"identity\",\"Connection\":\"close\",\"Content-Length\":\"96\",\"Content-Type\":\"application/json;charset=UTF-8\",\"Host\":\"172.19.0.7:8910\",\"User-Agent\":\"Python-urllib/3.5\"},\"httpVersion\":\"1.1\",\"method\":\"POST\",\"post\":\"{\\\"url\\\": \\\"\\\\\\\"http://www.REDACTED.com\\\\\\\"\\\", \\\"sessionId\\\": \\\"4eff6a60-4889-11e6-b4ad-095b9e1284ce\\\"}\",\"url\":\"/session/4eff6a60-4889-11e6-b4ad-095b9e1284ce/url\",\"urlParsed\":{\"anchor\":\"\",\"query\":\"\",\"file\":\"url\",\"directory\":\"/session/4eff6a60-4889-11e6-b4ad-095b9e1284ce/\",\"path\":\"/session/4eff6a60-4889-11e6-b4ad-095b9e1284ce/url\",\"relative\":\"/session/4eff6a60-4889-11e6-b4ad-095b9e1284ce/url\",\"port\":\"\",\"host\":\"\",\"password\":\"\",\"user\":\"\",\"userInfo\":\"\",\"authority\":\"\",\"protocol\":\"\",\"source\":\"/session/4eff6a60-4889-11e6-b4ad-095b9e1284ce/url\",\"queryKey\":{},\"chunks\":[\"session\",\"4eff6a60-4889-11e6-b4ad-095b9e1284ce\",\"url\"]}}","line":80,"sourceURL":"phantomjs://code/router_request_handler.js","stack":"_handle@phantomjs://code/router_request_handler.js:80:82"}
phantomjs2_1 |
phantomjs2_1 | phantomjs://platform/console++.js:263 in error
app_1 | Traceback (most recent call last):
app_1 | File "selenium_process.py", line 69, in <module>
app_1 | main()
app_1 | File "selenium_process.py", line 61, in main
app_1 | source = get_page(args.url)
app_1 | File "selenium_process.py", line 52, in get_page
app_1 | driver.get(url)
app_1 | File "/usr/local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 248, in get
app_1 | self.execute(Command.GET, {'url': url})
app_1 | File "/usr/local/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
app_1 | self.error_handler.check_response(response)
app_1 | File "/usr/local/lib/python3.5/site-packages/selenium/webdriver/remote/errorhandler.py", line 163, in check_response
app_1 | raise exception_class(value)
app_1 | selenium.common.exceptions.WebDriverException: Message: Variable Resource Not Found - {"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"96","Content-Type":"application/json;charset=UTF-8","Host":"172.19.0.7:8910","User-Agent":"Python-urllib/3.5"},"httpVersion":"1.1","method":"POST","post":"{\"url\": \"\\\"http://www.REDACTED.com\\\"\", \"sessionId\": \"4eff6a60-4889-11e6-b4ad-095b9e1284ce\"}","url":"/session/4eff6a60-4889-11e6-b4ad-095b9e1284ce/url","urlParsed":{"anchor":"","query":"","file":"url","directory":"/session/4eff6a60-4889-11e6-b4ad-095b9e1284ce/","path":"/session/4eff6a60-4889-11e6-b4ad-095b9e1284ce/url","relative":"/session/4eff6a60-4889-11e6-b4ad-095b9e1284ce/url","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/session/4eff6a60-4889-11e6-b4ad-095b9e1284ce/url","queryKey":{},"chunks":["session","4eff6a60-4889-11e6-b4ad-095b9e1284ce","url"]}}
app_1 |
</code></pre>
<p>So, how do I get load balancing working? What am I missing?</p>
<h1>UPDATE</h1>
<p>I figured out that I need some kind of session management in haproxy. The selenium webdriver and phantomjs communicate via sessions. The client sends a <code>POST /session</code> and receives a reply with the session id in the body. That reply looks something like this:</p>
<pre><code>{"sessionId":"5a27f2b0-48a5-11e6-97d7-7f5820fc7aa6","status":0,"value":{"browserName":"phantomjs","version":"2.1.1","driverName":"ghostdriver","driverVersion":"1.2.0","platform":"linux-unknown-64bit","javascriptEnabled":true,"takesScreenshot":true,"handlesAlerts":false,"databaseEnabled":false,"locationContextEnabled":false,"applicationCacheEnabled":false,"browserConnectionEnabled":false,"cssSelectorsEnabled":true,"webStorageEnabled":false,"rotatable":false,"acceptSslCerts":false,"nativeEvents":true,"proxy":{"proxyType":"direct"}}}
</code></pre>
<p>Then, as the session progresses, the session id is sent to the server as part of the URI in subsequent requests, such as <code>GET /session/5a27f2b0-48a5-11e6-97d7-7f5820fc7aa6/source</code>. How can I grab this stuff to use it for sticky sessions in haproxy?</p>
| 1 | 2016-07-21T16:50:06Z | 38,514,405 | <p>You should be able to add cookies within haproxy config itself..</p>
<pre><code>cookie SERVERID insert indirect nocache
server httpd1 10.0.0.19:9443 cookie httpd1 check
server httpd2 10.0.0.18:9443 cookie httpd2 check
</code></pre>
<p>Then sessions will be stick through haproxy itself.</p>
| 0 | 2016-07-21T21:09:43Z | [
"python",
"selenium",
"phantomjs",
"docker-compose",
"haproxy"
] |
Read in data and set it to the index of a DataFrame with Pandas | 38,510,059 | <p>I want to iterate through the rows of a DataFrame and assign values to a new DataFrame. I've accomplished that task indirectly like this:</p>
<pre><code>#first I read the data from df1 and assign it to df2 if something happens
counter = 0 #line1
for index,row in df1.iterrows(): #line2
value = row['df1_col'] #line3
value2 = row['df1_col2'] #line4
#try unzipping a file (pseudo code)
df2.loc[counter,'df2_col'] = value #line5
counter += 1 #line6
#except
print("Error, could not unzip {}") #line7
#then I set the desired index for df2
df2 = df2.set_index(['df2_col']) #line7
</code></pre>
<p>Is there a way to assign the values to the index of df2 directly in line5? Sorry my original question was unclear. I'm creating an index based on the something happening. </p>
| 2 | 2016-07-21T16:50:50Z | 38,510,181 | <p>No need to iterate, you can do: </p>
<pre><code>df2.index = df1['df1_col']
</code></pre>
<p>If you really want to iterate, save it to a list and set the index.</p>
| 0 | 2016-07-21T16:58:07Z | [
"python",
"pandas",
"dataframe"
] |
Read in data and set it to the index of a DataFrame with Pandas | 38,510,059 | <p>I want to iterate through the rows of a DataFrame and assign values to a new DataFrame. I've accomplished that task indirectly like this:</p>
<pre><code>#first I read the data from df1 and assign it to df2 if something happens
counter = 0 #line1
for index,row in df1.iterrows(): #line2
value = row['df1_col'] #line3
value2 = row['df1_col2'] #line4
#try unzipping a file (pseudo code)
df2.loc[counter,'df2_col'] = value #line5
counter += 1 #line6
#except
print("Error, could not unzip {}") #line7
#then I set the desired index for df2
df2 = df2.set_index(['df2_col']) #line7
</code></pre>
<p>Is there a way to assign the values to the index of df2 directly in line5? Sorry my original question was unclear. I'm creating an index based on the something happening. </p>
| 2 | 2016-07-21T16:50:50Z | 38,510,551 | <p>There are a bunch of ways to do this. According to your code, all you've done is created an empty <code>df2</code> dataframe with an index of values from <code>df1.df1_col</code>. You could do this directly like this:</p>
<pre><code>df2 = pd.DataFrame([], df1.df1_col)
# ^ ^
# | |
# specifies no data, yet |
# defines the index
</code></pre>
<p>If you are concerned about having to filter <code>df1</code> then you can do:</p>
<pre><code># cond is some boolean mask representing a condition to filter on.
# I'll make one up for you.
cond = df1.df1_col > 10
df2 = pd.DataFrame([], df1.loc[cond, 'df1_col'])
</code></pre>
| 4 | 2016-07-21T17:19:58Z | [
"python",
"pandas",
"dataframe"
] |
Python continue Not Working Properly | 38,510,108 | <p>I am writing a method using Python and I believe that the <code>continue</code> statement is not working properly. Can some explain to me what is wrong there?</p>
<p>The method code is below:</p>
<pre><code>def xlToLinkedDt(lst1, lst2, name1, name2):
logging.info(">> New iteration")
dates1, times1, dates2, times2 = [], [], [], []
for i, (dt1, dt2) in enumerate(zip(lst1, lst2)):
if bool(dt1) + bool(dt2) == 1:
name = name1 if not dt1 else name2
issues.append("The %s date of trip no. %d must be provided." %(name, i+1))
dates1.append("")
dates2.append("")
times1.append("")
times2.append("")
logging.info("Exiting loop")
continue
logging.info(Continued after bool condition.)
raise AssertionError("Stop!")
</code></pre>
<p>When I run this code I get an error and the following logging in one of the iterations:</p>
<pre><code>>> New iteration
>> Exiting loop
>> Continued after bool condition
</code></pre>
<p>The code is not supposed to log both messages, only one of them. Also when I replaced <code>continue</code> with <code>break</code> it worked well. What am I missing?</p>
| 0 | 2016-07-21T16:53:44Z | 38,510,174 | <blockquote>
<p>The code is not supposed to log both messages.</p>
</blockquote>
<p>Yes, it is.</p>
<p>After your code executes <em>continue</em>, the loop moves back to the beginning of the block inside the for-loop, in the next iteration. If the condition in your <code>if</code>-block is not met at the next iteration, you will get exactly the behaviour you describe.</p>
<pre><code>In [5]: for i in range(10):
print("Trying with i={:d}".format(i))
if i%2 == 0:
print("`i` even, continuing")
continue
print("What am I doing here?")
...:
Trying with i=0
`i` even, continuing
Trying with i=1
What am I doing here?
Trying with i=2
`i` even, continuing
Trying with i=3
What am I doing here?
Trying with i=4
`i` even, continuing
Trying with i=5
What am I doing here?
Trying with i=6
`i` even, continuing
Trying with i=7
What am I doing here?
Trying with i=8
`i` even, continuing
Trying with i=9
What am I doing here?
</code></pre>
<p>As you can see, there is still a <em>What am I doing here?</em> printed after the <em><code>i</code> even, continuing</em> notification, but it belongs to a later iteration of the loop. If we replace <code>continue</code> by <code>break</code>, we get very different behaviour:</p>
<pre><code>In [6]: for i in range(10):
print("Trying with i={:d}".format(i))
if i%2 == 0:
print("`i` even, not continuing")
break
print("What am I doing here?")
...:
Trying with i=0
`i` even, not continuing
</code></pre>
<p>As you can see, it stops immediately because (by our definition), 0 is even.</p>
| 2 | 2016-07-21T16:57:37Z | [
"python",
"for-loop",
"continue"
] |
Python continue Not Working Properly | 38,510,108 | <p>I am writing a method using Python and I believe that the <code>continue</code> statement is not working properly. Can some explain to me what is wrong there?</p>
<p>The method code is below:</p>
<pre><code>def xlToLinkedDt(lst1, lst2, name1, name2):
logging.info(">> New iteration")
dates1, times1, dates2, times2 = [], [], [], []
for i, (dt1, dt2) in enumerate(zip(lst1, lst2)):
if bool(dt1) + bool(dt2) == 1:
name = name1 if not dt1 else name2
issues.append("The %s date of trip no. %d must be provided." %(name, i+1))
dates1.append("")
dates2.append("")
times1.append("")
times2.append("")
logging.info("Exiting loop")
continue
logging.info(Continued after bool condition.)
raise AssertionError("Stop!")
</code></pre>
<p>When I run this code I get an error and the following logging in one of the iterations:</p>
<pre><code>>> New iteration
>> Exiting loop
>> Continued after bool condition
</code></pre>
<p>The code is not supposed to log both messages, only one of them. Also when I replaced <code>continue</code> with <code>break</code> it worked well. What am I missing?</p>
| 0 | 2016-07-21T16:53:44Z | 38,510,231 | <p>You used <code>continue</code>, I guess you meant <code>break</code>.</p>
<p><code>continue</code> will skip to the next iteration of your <code>for</code> loop.
<code>break</code> will leave the <code>for</code> loop.</p>
<p>Try that :</p>
<pre><code>def test():
print("Function start")
for i in range(10):
if i == 1:
print("Exiting loop")
continue
print("Am I printed or not ?")
print("I'm out of the loop")
</code></pre>
<p>Then replace <code>continue</code> by <code>break</code> and see what happens.
Since <code>print("Am I printed or not ?")</code> is part of the <code>for</code> loop, it will be executed on next for iteration after "Exiting loop", if you use <code>continue</code>. If you use <code>break</code>, it will be skipped.</p>
| 0 | 2016-07-21T17:00:33Z | [
"python",
"for-loop",
"continue"
] |
Difference between a list & a stack in python? | 38,510,140 | <p>What is the difference between a list & a stack in python? </p>
<p>I have read its explanation in the python documentation but there both the things seems to be same?</p>
<pre><code>>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
</code></pre>
| -2 | 2016-07-21T16:55:34Z | 38,510,166 | <p>A stack is a <em>data structure concept</em>. The documentation uses a Python <code>list</code> object to implement one. That's why that section of the tutorial is named <em>Using Lists as Stacks</em>.</p>
<p>Stacks are just things you add stuff to, and when you take stuff away from a stack again, you do so in reverse order, first in, last out style. Like a stack of books or hats or... <em>beer crates</em>:</p>
<p><a href="https://www.youtube.com/watch?v=9SReWtHt68A" rel="nofollow"><img src="http://i.stack.imgur.com/9jJBd.jpg" alt="beer crate stacking"></a></p>
<p>See the <a href="https://en.wikipedia.org/wiki/Stack_(abstract_data_type)" rel="nofollow">Wikipedia explanation</a>.</p>
<p>Lists on the other hand are far more versatile, you can add and remove elements anywhere in the list. You wouldn't try that with a stack of beer crates with someone on top!</p>
<p>You could implement a stack with a custom class:</p>
<pre><code>from collections import namedtuple
class _Entry(namedtuple('_Entry', 'value next')):
def _repr_assist(self, postfix):
r = repr(self.value) + postfix
if self.next is not None:
return self.next._repr_assist(', ' + r)
return r
class Stack(object):
def __init__(self):
self.top = None
def push(self, value):
self.top = _Entry(value, self.top)
def pop(self):
if self.top is None:
raise ValueError("Can't pop from an empty stack")
res, self.top = self.top.value, self.top.next
return res
def __repr__(self):
if self.top is None: return '[]'
return '[' + self.top._repr_assist(']')
</code></pre>
<p>Hardly a list in sight (somewhat artificially), but it is definitely a stack:</p>
<pre><code>>>> stack = Stack()
>>> stack.push(3)
>>> stack.push(4)
>>> stack.push(5)
>>> stack
[3, 4, 5]
>>> stack.pop()
5
>>> stack.push(6)
>>> stack
[3, 4, 6]
>>> stack.pop()
6
>>> stack.pop()
4
>>> stack.pop()
3
>>> stack
[]
</code></pre>
<p>The Python standard library doesn't come with a specific stack datatype; a <code>list</code> object does just fine. Just limit any use to <code>list.append()</code> and <code>list.pop()</code> (the latter with no arguments) to treat a list <em>as</em> a stack.</p>
| 7 | 2016-07-21T16:56:57Z | [
"python",
"list",
"stack"
] |
Difference between a list & a stack in python? | 38,510,140 | <p>What is the difference between a list & a stack in python? </p>
<p>I have read its explanation in the python documentation but there both the things seems to be same?</p>
<pre><code>>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
</code></pre>
| -2 | 2016-07-21T16:55:34Z | 38,510,167 | <p>A "stack" is a specific application of <code>list</code>, with operations limited to appending (pushing) to and popping (pulling) from the end.</p>
| 1 | 2016-07-21T16:57:05Z | [
"python",
"list",
"stack"
] |
Difference between a list & a stack in python? | 38,510,140 | <p>What is the difference between a list & a stack in python? </p>
<p>I have read its explanation in the python documentation but there both the things seems to be same?</p>
<pre><code>>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
</code></pre>
| -2 | 2016-07-21T16:55:34Z | 38,510,206 | <p>In python lists can also be used as stacks. Think of a list like a combination between your normal lists and a stack.
This is also described <a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow">here</a> </p>
<blockquote>
<p>The list methods make it very easy to use a list as a stack, where the
last element added is the first element retrieved (âlast-in,
first-outâ). To add an item to the top of the stack, use append(). To
retrieve an item from the top of the stack, use pop() without an
explicit index</p>
</blockquote>
<p>In fact you are using their exact example. Are you confused by the fact that it's a "combined data structure" ?</p>
<p>EDIT: as another user mentioned, it is a concept that is implemented using lists.</p>
| 0 | 2016-07-21T16:59:05Z | [
"python",
"list",
"stack"
] |
Difference between a list & a stack in python? | 38,510,140 | <p>What is the difference between a list & a stack in python? </p>
<p>I have read its explanation in the python documentation but there both the things seems to be same?</p>
<pre><code>>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
</code></pre>
| -2 | 2016-07-21T16:55:34Z | 38,525,709 | <p>Stack works in the concept of Last in First out.
We can perform push and pop operations in the stack
But compare to stack list is easy to do all operations like add,insert,delete,concat etc...
Stack is the application of stack and it's like data structures we use it more.</p>
| 0 | 2016-07-22T11:48:38Z | [
"python",
"list",
"stack"
] |
sudo/suid non-root nesting fails | 38,510,197 | <p>I have a python script (which must be called as root), which calls a bash script (which must be called as non-root), which sometimes needs to call sudo. This does not work - the "leaf" sudo calls give the message "$user is not in the sudoers file. This incident will be reported." How can I make this work?</p>
<p>The code (insert your non-root username in place of "your_username_here"):</p>
<p>tezt.py:</p>
<pre><code>#!/usr/bin/python3
import os
import pwd
import subprocess
def run_subshell_as_user(cmd_args, user_name=None, **kwargs):
cwd = os.getcwd()
user_obj = pwd.getpwnam(user_name)
# Set up the child process environment
new_env = os.environ.copy()
new_env["PWD"] = cwd
if user_name is not None:
new_env["HOME"] = user_obj.pw_dir
new_env["LOGNAME"] = user_name
new_env["USER"] = user_name
# This function is run after the fork and before the exec in the child
def suid_func():
os.setgid(user_obj.pw_gid)
os.setuid(user_obj.pw_uid)
return subprocess.Popen(
cmd_args,
preexec_fn=suid_func,
cwd=cwd,
env=new_env,
**kwargs).wait() == 0
run_subshell_as_user(["./tezt"], "your_username_here") # <-- HERE
</code></pre>
<p>tezt:</p>
<pre><code>#!/bin/bash
sudo ls -la /root
</code></pre>
<p>Then run it as:</p>
<pre><code>sudo ./tezt.py
</code></pre>
<p>Does anyone know why this doesn't work? The user can run sudo under normal circumstances. Why does "user -sudo-> root -suid-> user" work fine, but then when you try to sudo from there it fails?</p>
| 0 | 2016-07-21T16:58:53Z | 38,510,429 | <p>I'd suggest using <code>sudo</code> to drop privileges rather than doing so yourself -- that's a bit more thorough where possible, modifying effective as opposed to only real uid and gid. (To modify the full set yourself, you might try changing <code>setuid()</code> to <code>setreuid()</code>, and likewise <code>setgid()</code> to <code>setregid()</code>).</p>
<p>...this would mean passing something to Popen akin to the following:</p>
<pre><code>["sudo", "-u", "your_username_here", "--"] + cmd_args
</code></pre>
| 1 | 2016-07-21T17:11:58Z | [
"python",
"linux",
"bash",
"python-3.x",
"sudo"
] |
Python: TypeError: 'list' object is not callable on global variable | 38,510,214 | <p>I am currently in the process of programming a text-based adventure in Python as a learning exercise. I want "help" to be a global command, stored as values in a list, that can be called at (essentially) any time. As the player enters a new room, or the help options change, I reset the <code>help_commands</code> list with the new values. However, when I debug the following script, I get a <code>'list' object is not callable</code> TypeError. </p>
<p>I have gone over my code time and time again and can't seem to figure out what's wrong. I'm somewhat new to Python, so I assume it's something simple I'm overlooking. </p>
<pre><code>player = {
"name": "",
"gender": "",
"race": "",
"class": "",
"HP": 10,
}
global help_commands
help_commands = ["Save", "Quit", "Other"]
def help():
sub_help = '|'.join(help_commands)
print "The following commands are avalible: " + sub_help
def help_test():
help = ["Exit [direction], Open [object], Talk to [Person], Use [Item]"]
print "Before we go any further, I'd like to know a little more about you."
print "What is your name, young adventurer?"
player_name = raw_input(">> ").lower()
if player_name == "help":
help()
else:
player['name'] = player_name
print "It is nice to meet you, ", player['name'] + "."
help_test()
</code></pre>
<p>Edit:</p>
<p>You're like my Python guru, Moses. That fixed my problem, however now I can't get the values in help_commands to be overwritten by the new commands:</p>
<pre><code>player = {
"name": "",
"gender": "",
"race": "",
"class": "",
"HP": 10,
}
# global help_commands
help_commands = ["Save", "Quit", "Other"]
def help():
sub_help = ' | '.join(help_commands)
return "The following commands are avalible: " + sub_help
def help_test():
print help()
help_commands = ["Exit [direction], Open [object], Talk to [Person], Use [Item]"]
print help()
print "Before we go any further, I'd like to know a little more about you."
print "What is your name, young adventurer?"
player_name = raw_input(">> ").lower()
if player_name == "help":
help()
else:
player['name'] = player_name
print "It is nice to meet you, ", player['name'] + "."
help_test()
</code></pre>
<p>Thoughts?</p>
| -1 | 2016-07-21T16:59:43Z | 38,510,242 | <p>You are mixing the name of a list with that of a function:</p>
<pre><code>help = ["Exit [direction], Open [object], Talk to [Person], Use [Item]"]
</code></pre>
<p>And then:</p>
<pre><code>def help():
sub_help = '|'.join(help_commands)
print "The following commands are avalible: " + sub_help
</code></pre>
<p>The name <code>help</code> in the current scope (which references a list) is being treated as a callable, which is not the case.</p>
<p>Consider <em>renaming</em> the list or better still, both, since the name <code>help</code> is already being used by a builtin function.</p>
| 5 | 2016-07-21T17:01:11Z | [
"python",
"python-2.7"
] |
selenium not showing pop up when script is running | 38,510,246 | <p>I am using python-selenium bindings to automate webpage. I am using following line of code to press <code>ENTER</code> button and invoke a pop up:</p>
<pre><code>driver.find_element_by_xpath("xpath_of_element").send_keys(u'\ue007')
</code></pre>
<p>The Test Case is pass but it donot invoke the pop-up when the script is running. DO anyone know why?</p>
| 0 | 2016-07-21T17:01:35Z | 38,522,945 | <p>You should try using <code>click()</code> instead of <code>send_keys()</code> as below :-</p>
<pre><code>driver.find_element_by_xpath("xpath_of_element").click()
</code></pre>
<p><strong>Edited</strong> :- if in your case pop-up occurred by keyboard events try as below :-</p>
<pre><code>from selenium.webdriver.common.keys import Keys
driver.find_element_by_xpath("xpath_of_element").send_keys(Keys.ENTER)
</code></pre>
<p>Hope it helps..:)</p>
| 0 | 2016-07-22T09:30:11Z | [
"python",
"selenium",
"selenium-webdriver"
] |
the usage or API of tf.app.flags | 38,510,339 | <p>When reading the <a href="https://github.com/tensorflow/tensorflow/blob/e008ecf12607f691952a9bfe8971f406b30bc56e/tensorflow/models/image/cifar10/cifar10_train.py#L129" rel="nofollow">cifar10 example</a>, I can see the following code segment, which is said to follow the google commandline standard. But in specific, what does this code segment do? I did not find the API document to cover something like <code>tf.app.flags.DEFINE_string</code></p>
<pre><code>FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('train_dir', '/tmp/cifar10_train',
"""Directory where to write event logs """
"""and checkpoint.""")
tf.app.flags.DEFINE_integer('max_steps', 1000000,
"""Number of batches to run.""")
tf.app.flags.DEFINE_boolean('log_device_placement', False,
"""Whether to log device placement.""")
</code></pre>
| -1 | 2016-07-21T17:07:07Z | 38,513,531 | <p>My experience with TensorFlow is that looking at the source code is often more useful than Ctrl+F in the API doc. I keep PyCharm open with the TensorFlow project, and can easily search for either example of how to do something (e.g., custom reader).</p>
<p>In this particular case, you want to look at what's going on in <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/platform/flags.py" rel="nofollow">tensorflow/python/platform/flags.py</a>. It's really just a thin wrapper around argparse.ArgumentParser(). In particular, all of the DEFINE_* end up adding arguments to a _global_parser, for example, through this helper function:</p>
<pre class="lang-py prettyprint-override"><code>def _define_helper(flag_name, default_value, docstring, flagtype):
"""Registers 'flag_name' with 'default_value' and 'docstring'."""
_global_parser.add_argument("--" + flag_name,
default=default_value,
help=docstring,
type=flagtype)
</code></pre>
<p>So their flags API is mostly the same as what you find for <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">ArgumentParser</a>.</p>
| 0 | 2016-07-21T20:13:53Z | [
"python",
"tensorflow",
"conv-neural-network"
] |
Passing a Python list of strings to Applescript? | 38,510,374 | <p>I have a Python script that evaluates certain directories on my hard-drive for criteria matching files. It returns a list of strings, containing the file names.<br>
In Applescript, I call the Python script with <code>do shell script "path-to-script.py"</code>.<br>
If I print the list inside the Python script and run the script from Applescript, it appears as a single string <em>(i.e. "['string1', 'string2', ..., 'stringX']")</em> in the results dialog of the Script Editor App. </p>
<p>Does anybody know, how to pass this Python list to an identical Applescript list?</p>
<p>Thanks.</p>
| 0 | 2016-07-21T17:09:09Z | 38,510,527 | <p>The most straightforward way to do this is to have the Python script print the list items on separate lines:</p>
<pre><code>print("\n".join(list_of_files))
</code></pre>
<p>And in AppleScript, break those lines up into a list:</p>
<pre><code>set AppleScript's text item delimiters to return
set list_of_files to text items of (do shell script "path-to-script.py")
</code></pre>
| 1 | 2016-07-21T17:18:13Z | [
"python",
"list",
"applescript"
] |
Passing a Python list of strings to Applescript? | 38,510,374 | <p>I have a Python script that evaluates certain directories on my hard-drive for criteria matching files. It returns a list of strings, containing the file names.<br>
In Applescript, I call the Python script with <code>do shell script "path-to-script.py"</code>.<br>
If I print the list inside the Python script and run the script from Applescript, it appears as a single string <em>(i.e. "['string1', 'string2', ..., 'stringX']")</em> in the results dialog of the Script Editor App. </p>
<p>Does anybody know, how to pass this Python list to an identical Applescript list?</p>
<p>Thanks.</p>
| 0 | 2016-07-21T17:09:09Z | 38,785,155 | <p>It would be good practice to save Applescript's text item delimiters to a variable first and restore them after you have done what you want. Also enclose it all in a try block to avoid leaving the text delimiters in an unexpected state for any other scripts that may be run. i.e.</p>
<pre><code>try
set oldDelims to AppleScript's text item delimiters
-- do your stuff
--restore default delimiters:
set AppleScript's text item delimiters to oldDelims
on error
set AppleScript's text item delimiters to oldDelims
end try
</code></pre>
| 0 | 2016-08-05T08:54:17Z | [
"python",
"list",
"applescript"
] |
why is my Python program slowing down my computer | 38,510,688 | <p>I have a small program in python that collect probe requests and send ssids and macs to a server. But it slows down my computer after few minutes. I have tried to add dict so that I will make a POST only when it is necessary.
But the problem still the same: after few minutes, my computer is slowing down. I have tried also with raspberry pi and the result is the same.</p>
<p>Please tell me what is wrong here.</p>
<p>this is the code</p>
<pre><code>#!/usr/bin/env python
from scapy.all import *
import json
import requests
macSsid = {}
def handler(pkt):
url = 'http://10.10.10.10:3000/ssids'
headers = {'content-type': 'application/json'}
if pkt.haslayer(Dot11):
if pkt.type == 0 and pkt.subtype == 4:
if pkt.info :
print "Client MAC = %s probe request =%s" % (pkt.addr2, pkt.info)
if pkt.addr2 not in macSsid:
macSsid[pkt.addr2] = []
macSsid[pkt.addr2].append(pkt.info)
r = requests.post(url, data = json.dumps({"mac": pkt.addr2, "ssid": pkt.info }), headers = headers)
else:
if pkt.info not in macSsid[pkt.addr2]:
macSsid[pkt.addr2].append(pkt.info)
r = requests.post(url, data = json.dumps({"mac": pkt.addr2, "ssid": pkt.info }), headers = headers)
while 1:
try:
exc_info = sys.exc_info()
sniff(iface="mon0", prn = handler)
except Exception, err:
traceback.print_exception(*exc_info)
</code></pre>
<p>Please tell me what is wrong here.</p>
| 0 | 2016-07-21T17:27:39Z | 38,512,460 | <p>Your program is using too much memory. This is because you aren't clearing your macSsid dictionary. If you delete the entries after you use them (using <code>del</code>), your program will use less memory and thus stop slowing down your computer.</p>
| 0 | 2016-07-21T19:05:19Z | [
"python",
"performance"
] |
why is my Python program slowing down my computer | 38,510,688 | <p>I have a small program in python that collect probe requests and send ssids and macs to a server. But it slows down my computer after few minutes. I have tried to add dict so that I will make a POST only when it is necessary.
But the problem still the same: after few minutes, my computer is slowing down. I have tried also with raspberry pi and the result is the same.</p>
<p>Please tell me what is wrong here.</p>
<p>this is the code</p>
<pre><code>#!/usr/bin/env python
from scapy.all import *
import json
import requests
macSsid = {}
def handler(pkt):
url = 'http://10.10.10.10:3000/ssids'
headers = {'content-type': 'application/json'}
if pkt.haslayer(Dot11):
if pkt.type == 0 and pkt.subtype == 4:
if pkt.info :
print "Client MAC = %s probe request =%s" % (pkt.addr2, pkt.info)
if pkt.addr2 not in macSsid:
macSsid[pkt.addr2] = []
macSsid[pkt.addr2].append(pkt.info)
r = requests.post(url, data = json.dumps({"mac": pkt.addr2, "ssid": pkt.info }), headers = headers)
else:
if pkt.info not in macSsid[pkt.addr2]:
macSsid[pkt.addr2].append(pkt.info)
r = requests.post(url, data = json.dumps({"mac": pkt.addr2, "ssid": pkt.info }), headers = headers)
while 1:
try:
exc_info = sys.exc_info()
sniff(iface="mon0", prn = handler)
except Exception, err:
traceback.print_exception(*exc_info)
</code></pre>
<p>Please tell me what is wrong here.</p>
| 0 | 2016-07-21T17:27:39Z | 38,514,595 | <p>I believe it is caused by this line:</p>
<pre><code> if pkt.info not in macSsid[pkt.addr2]:
</code></pre>
<p>As the list referenced by macSsid[pkt.addr2] gets larger, the cost of doing an iterative search on a python list becomes very high. This is a list, not a dictionary, so there is no index, and python has to check each element in order until either the matching element is found, or it has checked every element in the list.</p>
<p>I recommend changing it to a dictionary for faster operation,</p>
<pre><code> macSsid[pkt.addr2] = {}
macSsid[pkt.addr2][pkt.info] = 1 # the 1 is just a placeholder,
# so if you want to store e.g. a repeat count, this would allow it
</code></pre>
<p>And the corresponding change when adding pkt.info in the else clause.</p>
<p>Changing to an indexed type will allow index-based lookups, rather than iterating the list. I believe there are indexed-list types in Python, but I don't use them much, since the extra storage for metrics or similar data has always been a benefit in addition to the indexed lookups.</p>
<p>Your use-case is probably exaggerating the effect as well, since I suspect you will have a high probability of not finding a match for the pkt.info, and therefore each time it searches the list, it will have to check every element before concluding that it doesn't exist.</p>
<p>Consider the cost of adding the first 1000 elements to a list: each new element requires searching the previous set before adding, requiring half a million comparisons on those new elements alone, not including any repeated elements that you don't add. Elements that already exist could require checking more than the statistical mean if the network packets use sequential identifiers rather than completely-random identifiers, which is the case with most network protocols.</p>
<p>Note also that this will seem to slow down suddenly at the point when the list will no longer fit entirely in CPU cache. At that point, your performance will usually drop suddenly by anywhere from 10x to 100x, depending on the specs of your machine.</p>
<p>The reason this appears to affect the rest of your computer is because the CPU is blocked while waiting for each memory fetch operation to complete, and the constant memory fetch operations slow down your memory controller. The core that is running your python program will be blocked entirely, and your memory bus will be nearly saturated, causing other applications to seem slow as well.</p>
| 0 | 2016-07-21T21:23:12Z | [
"python",
"performance"
] |
lxml - Default name spaces | 38,510,693 | <p>I am trying to parse an xml file using <code>lxml</code>.</p>
<pre><code>my_tree = etree.parse(file)
my_root = my_tree.getroot()
for child in my_root:
print(child.tag)
# {some default namespace}Prop
# {some default namespace}Prop
# {some default namespace}Stuff
# ...
</code></pre>
<p>Ideally, I just want to get all the elements I want with something like</p>
<pre><code>my_root.findall('Prop', my_root.nsmap)
</code></pre>
<p>but this is returning an empty list. I noticed that the <code>my_root.nsmap</code> dictionary had a None item with the default namespace.</p>
<pre><code>nsmap = {None: 'default namespace', ...}
</code></pre>
<p>I found a quick workaround by copying the nsmap and adding a 'default' item with the same value as the None item, and then I do</p>
<pre><code>my_root.findall('default:Prop', new_map)
</code></pre>
<p>This feels very hackish. Why is None even in the namespace map? Is there some straightforward method in lxml the automatically uses the default namespace?</p>
<p>Edit: The xml I am looking at is along the lines of</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ScenarioProps xmlns="http://filler.com/default.xsd" xmlns:ns2="http://filler.com/ns.xsd" id="Test">
<Prop id="Wi-Fi">
<ns2:Position x="0.0" y="0.0" z="0.0"/>
<ns2:Orientation roll="0.0" pitch="0.0" yaw="0.0"/>
</Prop>
</ScenarioProps>
</code></pre>
| 1 | 2016-07-21T17:27:53Z | 38,511,267 | <p>I just use a helper class. <code>context</code> is the document, <code>my</code> is the namespace, and <code>key</code> is the tag name.</p>
<pre><code>found = self.context.find('.//{%s}%s' % (self.my, key))
</code></pre>
| 1 | 2016-07-21T17:59:35Z | [
"python",
"xml",
"lxml"
] |
lxml - Default name spaces | 38,510,693 | <p>I am trying to parse an xml file using <code>lxml</code>.</p>
<pre><code>my_tree = etree.parse(file)
my_root = my_tree.getroot()
for child in my_root:
print(child.tag)
# {some default namespace}Prop
# {some default namespace}Prop
# {some default namespace}Stuff
# ...
</code></pre>
<p>Ideally, I just want to get all the elements I want with something like</p>
<pre><code>my_root.findall('Prop', my_root.nsmap)
</code></pre>
<p>but this is returning an empty list. I noticed that the <code>my_root.nsmap</code> dictionary had a None item with the default namespace.</p>
<pre><code>nsmap = {None: 'default namespace', ...}
</code></pre>
<p>I found a quick workaround by copying the nsmap and adding a 'default' item with the same value as the None item, and then I do</p>
<pre><code>my_root.findall('default:Prop', new_map)
</code></pre>
<p>This feels very hackish. Why is None even in the namespace map? Is there some straightforward method in lxml the automatically uses the default namespace?</p>
<p>Edit: The xml I am looking at is along the lines of</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ScenarioProps xmlns="http://filler.com/default.xsd" xmlns:ns2="http://filler.com/ns.xsd" id="Test">
<Prop id="Wi-Fi">
<ns2:Position x="0.0" y="0.0" z="0.0"/>
<ns2:Orientation roll="0.0" pitch="0.0" yaw="0.0"/>
</Prop>
</ScenarioProps>
</code></pre>
| 1 | 2016-07-21T17:27:53Z | 38,512,138 | <p>Hackish or not, you have to specify a prefix. <strong>XPath 1.0</strong>, which is what lxml supports, does not have a concept of default namespace (it works differently in <strong>XPath 2.0</strong>, but that does not apply here).</p>
<p>The other option is to not bother with prefixes at all. Use the fully qualified element name in "Clark notation" instead: </p>
<pre><code> my_root.findall('{http://filler.com/default.xsd}Prop').
</code></pre>
<p>See also <a href="http://lxml.de/FAQ.html#how-can-i-specify-a-default-namespace-for-xpath-expressions" rel="nofollow">http://lxml.de/FAQ.html#how-can-i-specify-a-default-namespace-for-xpath-expressions</a>.</p>
| 1 | 2016-07-21T18:47:22Z | [
"python",
"xml",
"lxml"
] |
lxml - Default name spaces | 38,510,693 | <p>I am trying to parse an xml file using <code>lxml</code>.</p>
<pre><code>my_tree = etree.parse(file)
my_root = my_tree.getroot()
for child in my_root:
print(child.tag)
# {some default namespace}Prop
# {some default namespace}Prop
# {some default namespace}Stuff
# ...
</code></pre>
<p>Ideally, I just want to get all the elements I want with something like</p>
<pre><code>my_root.findall('Prop', my_root.nsmap)
</code></pre>
<p>but this is returning an empty list. I noticed that the <code>my_root.nsmap</code> dictionary had a None item with the default namespace.</p>
<pre><code>nsmap = {None: 'default namespace', ...}
</code></pre>
<p>I found a quick workaround by copying the nsmap and adding a 'default' item with the same value as the None item, and then I do</p>
<pre><code>my_root.findall('default:Prop', new_map)
</code></pre>
<p>This feels very hackish. Why is None even in the namespace map? Is there some straightforward method in lxml the automatically uses the default namespace?</p>
<p>Edit: The xml I am looking at is along the lines of</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ScenarioProps xmlns="http://filler.com/default.xsd" xmlns:ns2="http://filler.com/ns.xsd" id="Test">
<Prop id="Wi-Fi">
<ns2:Position x="0.0" y="0.0" z="0.0"/>
<ns2:Orientation roll="0.0" pitch="0.0" yaw="0.0"/>
</Prop>
</ScenarioProps>
</code></pre>
| 1 | 2016-07-21T17:27:53Z | 39,132,809 | <p>you can "automatically" redefine your default namespace with something like:</p>
<pre><code>{k if k is not None else 'default':v for k,v in my_root.nsmap.items()}
</code></pre>
<p>which gets a namespace dictionary with the key None replaced by "default" and leaves all other keys untouched:</p>
<pre><code>{'default': 'http://filler.com/default.xsd', 'ns2': 'http://filler.com/ns.xsd'}
</code></pre>
<p>your example would look as follows:</p>
<pre><code>from lxml import etree
import StringIO
f = StringIO.StringIO('''
<ScenarioProps xmlns="http://filler.com/default.xsd" xmlns:ns2="http://filler.com/ns.xsd" id="Test">
<Prop id="Wi-Fi">
<ns2:Position x="0.0" y="0.0" z="0.0"/>
<ns2:Orientation roll="0.0" pitch="0.0" yaw="0.0"/>
</Prop>
</ScenarioProps>
''')
parser = etree.XMLParser()
my_tree = etree.parse(f, parser)
my_root = my_tree.getroot()
my_tree.getroot().nsmap
nsmap = {k if k is not None else 'default':v for k,v in my_root.nsmap.items()}
my_root.findall('default:Prop', nsmap)
</code></pre>
| 1 | 2016-08-24T20:50:13Z | [
"python",
"xml",
"lxml"
] |
How to add album art to mp3 file using python 3? | 38,510,694 | <p>I was wondering what module to use for setting an image as the album art for a particular mp3 file. Mutagen seemed to be a popular choice, but it doesn't seem to work on python 3 and I can't find any documentation.</p>
| 0 | 2016-07-21T17:27:58Z | 39,316,853 | <p>Here's a modified version of the code I use. You will want to change the <code>example.mp3</code> and <code>cover.jpg</code> (and perhaps the mime type too):</p>
<pre><code>import eyed3
audiofile = eyed3.load('example.mp3')
if (audiofile.tag == None):
audiofile.initTag()
audiofile.tag.images.set(3, open('cover.jpg','rb').read(), 'image/jpeg')
</code></pre>
<p><code>tag.images.set()</code> takes three arguments:</p>
<ul>
<li><strong>Picture Type</strong>: This is the type of image it is. <code>3</code> is the code for the front cover art. You can <a href="http://id3.org/id3v2.3.0#Attached_picture" rel="nofollow">find them all here</a>.</li>
<li><strong>Image Data</strong>: This is the binary data of your image. In the example, I load this in using <code>open().read()</code>.</li>
<li><strong>Mime Type</strong>: This is the type of file the binary data is. If it's a <code>jpg</code> file, you'll want <code>image/jpeg</code>, and if it's a <code>png</code> file, you'll want <code>image/png</code>.</li>
</ul>
| 1 | 2016-09-04T12:21:42Z | [
"python",
"audio",
"python-3.4",
"eyed3"
] |
Error using tensorflow: needs protobuf 3.0.0 but finds 2.6.1 - pip3 shows 3.0.0b2 installed | 38,510,795 | <p>running my newest python code (which uses keras/tensorflow), I get this error:</p>
<pre><code>[libprotobuf FATAL google/protobuf/stubs/common.cc:61] This program requires version 3.0.0 of the Protocol Buffer runtime library, but the installed version is 2.6.1. Please update your library. If you compiled the program yourself, make sure that your headers are from the same version of Protocol Buffers as your link-time library. (Version verification failed in "external/protobuf/src/google/protobuf/any.pb.cc".) terminate called after throwing an instance of 'google::protobuf::FatalException' what(): This program requires version 3.0.0 of the Protocol Buffer runtime library, but the installed version is 2.6.1. Please update your library. If you compiled the program yourself, make sure that your headers are from the same version of Protocol Buffers as your link-time library. (Version verification failed in "external/protobuf/src/google/protobuf/any.pb.cc".)
</code></pre>
<p>However, when doing pip3 list I get:</p>
<pre><code>protobuf (3.0.0b2)
tensorflow (0.9.0)
</code></pre>
<p>(among others)</p>
<p>I'm using Ubuntu 16.04, running CUDA 7.5 on a Nvidia 1070 GTX.
I have updated to the latest versions of all relevant packages for my code and I have uninstalled and reinstalled protobuf and tensorflow.</p>
<p>This error only occurs only with code I wrote today, not with any other code that I ran on this machine before. So there is probably something wrong with my code, but the error message is not really pointing me there.</p>
<p>Can anybody help? Thanks.</p>
| 0 | 2016-07-21T17:33:59Z | 38,678,009 | <p>I'm using Ubuntu 16.04, with tensorflow 0.90 installed from source, with cuda 8.0RC & cudann5. I had this exact same error with some keras code which utilised the tensorflow backend.</p>
<p>It's not 100% clear where the problem lies, but it doesn't appear when running any tensorflow code directly, nor with skflow. So far I have only encountered the problem while using keras, but after exploring the keras backend code, I cannot see anything that looks suspicious. </p>
<p><strong>However</strong>, I do have a solution which works for me. As Chris suggested, if I ensure that the very first import that occurs is <code>import tensorflow as tf</code>, it loads as expected and everything works. My guess is that there is some module conflict where some other packages are loading in a different version of protobuf before tensorflow can, perhaps.</p>
| 1 | 2016-07-30T20:03:42Z | [
"python",
"version",
"tensorflow",
"protocol-buffers"
] |
Dictionary to list with lists inside and print to csv | 38,510,815 | <p>I have a dictionary I wish to turn into a list containing lists so that I can write into a csv, but what ever I do, it doesn't work.</p>
<p>I used sorted(dllist.items()) to sort them as </p>
<pre><code>[(key1, value1), (key2, value2), ... ,(keyN, valueN)]
</code></pre>
<p>This is what I have,</p>
<pre><code>dict = [('aaa', [5787, 40, 1161, 1222]),
('aab', [6103, 69, 810, 907]),
('aac', [3081, 41, 559, 638]),
('aae', [1011000, 191, 411, 430])]
</code></pre>
<p>I want it to be </p>
<pre><code>list = [(aaa, 5787, 40, 1161, 1222),
('aab',6103, 69, 810, 907),
('aac', 3081, 41, 559, 638),
('aae', 1011000, 191, 411, 430)]
</code></pre>
<p>What am doing wrong? and how do I do it easiest to store it in a csv as a row for each element?</p>
| 0 | 2016-07-21T17:35:25Z | 38,510,903 | <p>Given the output from <code>sorted</code>, this does it:</p>
<pre><code>>>> my_dict = [('aaa', [5787, 40, 1161, 1222]), ('aab', [6103, 69, 810, 907]), ('aac', [3081, 41, 559, 638]), ('aae', [1011000, 191, 411, 430])]
>>> my_list = [tuple([i[0]] + i[1]) for i in my_dict]
>>>
>>> my_list
[('aaa', 5787, 40, 1161, 1222), ('aab', 6103, 69, 810, 907), ('aac', 3081, 41, 559, 638), ('aae', 1011000, 191, 411, 430)]
</code></pre>
<p>I have used <code>my_list</code> and <code>my_dict</code> in place of <code>list</code> and <code>dict</code> respectively to avoid <em>shadowing</em> the builtin names.</p>
<p>The code that does the trick:</p>
<pre><code>[tuple([i[0]] + i[1]) for i in my_dict]
# |<- put first item in a list
# |<- join with second item
</code></pre>
<p>puts the <em>first item</em> in each <code>tuple</code> in a list and <em>concatenates</em> with the second item in the tuple which is already a list. The operation is repeated on all tuples in a list comprehension.</p>
<hr>
<p>Given a <em>csv</em> <code>writer</code> object, you can then use:</p>
<pre><code>writer.writerows(my_list)
</code></pre>
<p>To write all the items into your <em>csv</em> file at a go.</p>
| 0 | 2016-07-21T17:40:22Z | [
"python",
"csv",
"dictionary"
] |
Dictionary to list with lists inside and print to csv | 38,510,815 | <p>I have a dictionary I wish to turn into a list containing lists so that I can write into a csv, but what ever I do, it doesn't work.</p>
<p>I used sorted(dllist.items()) to sort them as </p>
<pre><code>[(key1, value1), (key2, value2), ... ,(keyN, valueN)]
</code></pre>
<p>This is what I have,</p>
<pre><code>dict = [('aaa', [5787, 40, 1161, 1222]),
('aab', [6103, 69, 810, 907]),
('aac', [3081, 41, 559, 638]),
('aae', [1011000, 191, 411, 430])]
</code></pre>
<p>I want it to be </p>
<pre><code>list = [(aaa, 5787, 40, 1161, 1222),
('aab',6103, 69, 810, 907),
('aac', 3081, 41, 559, 638),
('aae', 1011000, 191, 411, 430)]
</code></pre>
<p>What am doing wrong? and how do I do it easiest to store it in a csv as a row for each element?</p>
| 0 | 2016-07-21T17:35:25Z | 38,510,910 | <p>You can add tuples (which appends them to each other) and you can convert lists into tuples. So, the following works for me:</p>
<pre><code>>>> x = [('a', [1,2,3]), ('b', [4,5,6])]
>>> x
[('a', [1, 2, 3]), ('b', [4, 5, 6])]
>>> y = [(i,) + tuple(j) for i, j in x]
>>> y
[('a', 1, 2, 3), ('b', 4, 5, 6)]
</code></pre>
| 0 | 2016-07-21T17:40:45Z | [
"python",
"csv",
"dictionary"
] |
Dictionary to list with lists inside and print to csv | 38,510,815 | <p>I have a dictionary I wish to turn into a list containing lists so that I can write into a csv, but what ever I do, it doesn't work.</p>
<p>I used sorted(dllist.items()) to sort them as </p>
<pre><code>[(key1, value1), (key2, value2), ... ,(keyN, valueN)]
</code></pre>
<p>This is what I have,</p>
<pre><code>dict = [('aaa', [5787, 40, 1161, 1222]),
('aab', [6103, 69, 810, 907]),
('aac', [3081, 41, 559, 638]),
('aae', [1011000, 191, 411, 430])]
</code></pre>
<p>I want it to be </p>
<pre><code>list = [(aaa, 5787, 40, 1161, 1222),
('aab',6103, 69, 810, 907),
('aac', 3081, 41, 559, 638),
('aae', 1011000, 191, 411, 430)]
</code></pre>
<p>What am doing wrong? and how do I do it easiest to store it in a csv as a row for each element?</p>
| 0 | 2016-07-21T17:35:25Z | 38,510,991 | <p>Given my assumption about what your dictionary looks like, this should do the conversion you want and write the output to a CSV file:</p>
<pre><code>import csv
d = { 'aaa': [5787, 40, 1161, 1222], 'aab': [6103, 69, 810, 907] }
rows = [[k] + v for k, v in sorted(d.items())]
with open("out.csv", "w") as out:
writer = csv.writer(out)
for row in rows:
writer.writerow(row)
# out.csv:
# aaa,5787,40,1161,1222
# aab,6103,69,810,907
</code></pre>
| 0 | 2016-07-21T17:45:00Z | [
"python",
"csv",
"dictionary"
] |
to redirect to URL which accepts POST requests only in django | 38,510,832 | <p>I am currently working on a project based on django framework which requires apis to be built that accept POST requests only except one or two which can recieve GET requests. One of those apis, say /x/, is invoked on the submission of form with method type as POST. The view attached to this api /x/ modifies the request and then needs to invoke another API(say /y/) or view which again accepts POST requests only. My code is as follows : </p>
<p><strong>views.py</strong></p>
<pre><code>from django.template import RequestContext
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
import logging
#print "__name__ : " + __name__
logger = logging.getLogger('django.request')
logger_info = logging.getLogger('correct_info')
#to_be_commented
@api_view(['POST','GET'])
def load_filter(request):
context = RequestContext(request)
if request.method == 'POST':
print request.data
filter_list = request.POST.getlist('profile')
print filter_list
stdd_filters = ['gender','state','country','examEnrolled','examDefault','examSelected']
profFilters = {}
#profFilters['filters'] = {}
for flter in stdd_filters:
if flter in filter_list:
profFilters[flter] = request.POST.getlist(flter)
else:
profFilters[flter] = []
print profFilters
if not request.POST._mutable:
request.POST._mutable = True
request.POST['filters'] = profFilters
if 'AND' in request.data:
print "TRUE AND"
**#problem here**
#return redirect('profile_filter_and')
return HttpResponseRedirect('../filtered/and/')
elif request.method == 'GET':
return render(request,"filters.html",{})
@api_view(['POST'])
def profile_filter_and(request):
if request.method == POST:
#entire code
</code></pre>
<p>I have tried both redirect and HttpResponseRedirect methods but both of them call the url or view functions as a GET request due to which I get the following error :</p>
<pre><code>HTTP 405 Method Not Allowed
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept
{
"detail": "Method \"GET\" not allowed."
}
</code></pre>
<p>whereas I want the redirection as POST request to the url or view since it accepts only POST requests. I have tried searching about the same on Internet but haven't got anything fruitful. I am newbie in developing apis in django. So, Please Help. </p>
| 0 | 2016-07-21T17:36:19Z | 38,511,160 | <p>"I have tried both redirect and HttpResponseRedirect methods but both of them call the url or view functions as a GET"</p>
<p>This is because redirecting POST data is considered bad design choice and is not supported by Django in any obvious way. Check out this answer to similar question:</p>
<p><a href="http://stackoverflow.com/a/3024528/4400065">http://stackoverflow.com/a/3024528/4400065</a></p>
<p>One simple solution to your problem would be passing data to function, instead of sending antoher HTTP request.</p>
| 1 | 2016-07-21T17:53:58Z | [
"python",
"django",
"redirect",
"http-post"
] |
Pandas cumsum on groupby not behaving as expected | 38,510,860 | <p>I have a dataframe like this:</p>
<pre><code>df = pd.DataFrame({'prob':np.random.uniform(0,1,size), 'target':np.random.randint(0,2, size=size),
'pred':np.random.randint(0,2, size=size)})
</code></pre>
<p>That I want to compute <code>cumsum</code> of a <code>groupby</code> of a <code>qcut</code>:</p>
<pre><code>df['box'] = pd.qcut(df['prob'], 10)
</code></pre>
<p>My expectation would be to calculate the cumulative function for each group, in order, but instead is calculating a sum for each element:</p>
<pre><code>df['target_1'] = 1- df['target']
ch_curve = df.groupby('box').target.cumsum()/float(df.target.sum())
nch_curve = df.groupby('box').target_1.cumsum()/float(df.target_1.sum())
</code></pre>
<p>with the answer</p>
<pre><code>0 0.000000
1 0.018182
2 0.018182
3 0.018182
4 0.000000
5 0.018182
6 0.018182
7 0.018182
8 0.036364
9 0.018182
10 0.000000
11 0.018182
12 0.018182
13 0.036364
14 0.000000
15 0.036364
16 0.036364
17 0.036364
18 0.054545
19 0.000000
20 0.000000
21 0.018182
22 0.018182
23 0.05454
</code></pre>
<p>instead of </p>
<pre><code>'(0.0, 0.1)' 0.04
'(0.1, 0.2)' 0.12 #(0.08 + previous 0.04 )
'(0.2, 0.3)' 0.17 #(0.05 + previous 0.12 )
</code></pre>
| 0 | 2016-07-21T17:37:33Z | 38,511,161 | <p>You want to calculate the percentage for each group and <strong>then</strong> take the cumsum. </p>
<p>In your original code <code>df.groupby('box').target.cumsum()</code> will take the <code>cumsum</code> of each group - so you will have one element for each of the elements in the grouped DataFrame. Then the division will be broadcast across all of these elements.</p>
<p>Instead you want to get one summary statistic for each group and then take the <code>cumsum</code> across these statistics.</p>
<pre><code>ch_curve = (df.groupby('box').target.sum() / df.target.sum()).cumsum()
nch_curve = (df.groupby('box').target_1.sum() / df.target_1.sum()).cumsum()
</code></pre>
| 4 | 2016-07-21T17:54:01Z | [
"python",
"pandas"
] |
Python vs Java Loop | 38,510,897 | <p>I am working through some problems on HackerRank, and I thought I would try implementing the same solution in Python that I had already solved correctly in Java. Although my code almost exactly mirrors my previous Python solution, I am getting an out of bounds exception in the <code>if input_str[i-1] == input_str[i]</code> line. Is there different behavior in a Python loop that might be causing this discrepancy? The test cases are the same across both. </p>
<pre><code>public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
solve(input);
}
public static void solve(String str) {
String s = new String(str);
for (int i=1; i < s.length(); i++) {
if (s.charAt(i-1) == s.charAt(i)) {
s = s.substring(0, i-1) + s.substring(i+1, s.length());
i = 0;
}
if (s.length() == 0) {
System.out.println("Empty String");
return;
}
}
System.out.println(s);
}
}
</code></pre>
<p>And this is the code for the same problem, but using Python 2.7.</p>
<pre><code>input_str = raw_input()
for i in xrange(1, len(input_str)):
if input_str[i-1] == input_str[i]:
input_str = input_str[0:i-1] + input_str[i+1:len(input_str)]
i = 0
if len(input_str) == 0:
print "Empty String"
break
print input_str
</code></pre>
| 1 | 2016-07-21T17:40:09Z | 38,510,962 | <p>In the Java loop, <code>s.length()</code> is recalculated every iteration. In Python, <code>len(input_str)</code> is only calculated once and does not reflect the correct length after you've modified <code>input_str</code> in the <code>if</code> block.</p>
<p>Similarly, assigning <code>i = 0</code> does not work the way you want it to. <code>i</code> will take on the next value in the <code>xrange</code>, ignoring your attempted reset of its value.</p>
| 5 | 2016-07-21T17:43:42Z | [
"java",
"python",
"string",
"for-loop"
] |
Python vs Java Loop | 38,510,897 | <p>I am working through some problems on HackerRank, and I thought I would try implementing the same solution in Python that I had already solved correctly in Java. Although my code almost exactly mirrors my previous Python solution, I am getting an out of bounds exception in the <code>if input_str[i-1] == input_str[i]</code> line. Is there different behavior in a Python loop that might be causing this discrepancy? The test cases are the same across both. </p>
<pre><code>public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
solve(input);
}
public static void solve(String str) {
String s = new String(str);
for (int i=1; i < s.length(); i++) {
if (s.charAt(i-1) == s.charAt(i)) {
s = s.substring(0, i-1) + s.substring(i+1, s.length());
i = 0;
}
if (s.length() == 0) {
System.out.println("Empty String");
return;
}
}
System.out.println(s);
}
}
</code></pre>
<p>And this is the code for the same problem, but using Python 2.7.</p>
<pre><code>input_str = raw_input()
for i in xrange(1, len(input_str)):
if input_str[i-1] == input_str[i]:
input_str = input_str[0:i-1] + input_str[i+1:len(input_str)]
i = 0
if len(input_str) == 0:
print "Empty String"
break
print input_str
</code></pre>
| 1 | 2016-07-21T17:40:09Z | 38,513,156 | <p>I believe you are wasting a lot of time and system resources by doing it that way. A better solution would be to change the algorithm into one that only iterates <code>input_str</code> only once. In which case, you get <code>O(n)</code> execution time. My edited code looks thus:</p>
<pre><code>input_str = input()
input_strR = input_str[0]
for i in range(1, len(input_str)):
if input_str[i-1] != input_str[i]:
input_strR = input_strR + input_str[i]
if len(input_str) == 0:
print ("Empty String")
break
print (input_strR)
</code></pre>
<p>In this case, a new variable was introduced and all first characters were added while duplicates were dropped.</p>
| 1 | 2016-07-21T19:49:08Z | [
"java",
"python",
"string",
"for-loop"
] |
Python vs Java Loop | 38,510,897 | <p>I am working through some problems on HackerRank, and I thought I would try implementing the same solution in Python that I had already solved correctly in Java. Although my code almost exactly mirrors my previous Python solution, I am getting an out of bounds exception in the <code>if input_str[i-1] == input_str[i]</code> line. Is there different behavior in a Python loop that might be causing this discrepancy? The test cases are the same across both. </p>
<pre><code>public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
solve(input);
}
public static void solve(String str) {
String s = new String(str);
for (int i=1; i < s.length(); i++) {
if (s.charAt(i-1) == s.charAt(i)) {
s = s.substring(0, i-1) + s.substring(i+1, s.length());
i = 0;
}
if (s.length() == 0) {
System.out.println("Empty String");
return;
}
}
System.out.println(s);
}
}
</code></pre>
<p>And this is the code for the same problem, but using Python 2.7.</p>
<pre><code>input_str = raw_input()
for i in xrange(1, len(input_str)):
if input_str[i-1] == input_str[i]:
input_str = input_str[0:i-1] + input_str[i+1:len(input_str)]
i = 0
if len(input_str) == 0:
print "Empty String"
break
print input_str
</code></pre>
| 1 | 2016-07-21T17:40:09Z | 38,513,636 | <p>I would build on funaquarius24 and not even use indexes:</p>
<pre><code>input_str = raw_input()
result = input_str[0]
for c in input_str[1:]:
if c != result[-1]:
result += c
print(result)
</code></pre>
| 0 | 2016-07-21T20:20:16Z | [
"java",
"python",
"string",
"for-loop"
] |
Is `if x:` completely equivalent to `if bool(x) is True:`? | 38,510,964 | <p>For a small testing framework we are writing I'm trying to provide some utility functions.</p>
<p>One of them is supposed to be equivalent to <code>if x:</code> but if that is <strong>completely</strong> equivallent to <code>if bool(x) is True:</code> then I could only provide one function to check <code>if x is True:</code> and <code>if x:</code>.</p>
<p>Is the negation of that also equivalent? <code>if bool(x) is False:</code> equal to <code>if not x:</code>?</p>
| 5 | 2016-07-21T17:44:01Z | 38,510,993 | <p><code>if x:</code> is <em>completely</em> equivalent to testing for the boolean truth value, yes.</p>
<p>From the <a href="https://docs.python.org/2/reference/compound_stmts.html#the-if-statement" rel="nofollow"><code>if</code> statement documentation</a>:</p>
<blockquote>
<p>It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section <a href="https://docs.python.org/2/reference/expressions.html#booleans" rel="nofollow">Boolean operations</a> for the definition of true and false)</p>
</blockquote>
<p>where the <a href="https://docs.python.org/2/reference/expressions.html#booleans" rel="nofollow"><em>Boolean operations</em> section</a> details how truth is defined. The <a href="https://docs.python.org/2/library/functions.html#bool" rel="nofollow"><code>bool()</code> function</a> follows those exact same rules:</p>
<blockquote>
<p>Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure.</p>
</blockquote>
<p>The Standard Types documentation has a <a href="https://docs.python.org/2/library/stdtypes.html#truth-value-testing" rel="nofollow"><em>Truth Value Testing</em> section</a>:</p>
<blockquote>
<p>Any object can be tested for truth value, for use in an <code>if</code> or <code>while</code> condition or as operand of the Boolean operations below.</p>
</blockquote>
<p><code>not</code> simply inverts that same truth value; so if <code>x</code> is considered true by the above rules <code>not x</code> returns <code>False</code>, and <code>True</code> otherwise.</p>
<p>Be careful: in Python 2, the built-in names <code>False</code> and <code>True</code> can be <em>masked</em> by setting a global:</p>
<pre><code>>>> True = False
>>> True
False
</code></pre>
<p>and thus <code>is</code> identity tests may be fooled by that re-assignment as well. Python 3 makes <code>False</code> and <code>True</code> keywords.</p>
<p>Your utility function should not need to use <code>bool(x) is True</code> or <code>bool(x) is False</code>. All you need is <code>bool(x)</code> and <code>not bool(x)</code>, as these <em>already</em> produce <code>True</code> and <code>False</code> objects. <code>bool()</code> and <code>not</code> can't return anything else, using <code>is True</code> or <code>is False</code> on these is extremely redundant.</p>
<p>Last but not least, try not to re-invent the testing wheel. The Python standard library comes with a <code>unittest</code> library; it has both <code>assertTrue</code> and <code>assertFalse</code> functions, and the <a href="https://hg.python.org/cpython/file/2.7/Lib/unittest/case.py#l412" rel="nofollow">implementation of these functions</a> just use <code>if</code> and <code>if not</code>.</p>
| 6 | 2016-07-21T17:45:03Z | [
"python"
] |
Is `if x:` completely equivalent to `if bool(x) is True:`? | 38,510,964 | <p>For a small testing framework we are writing I'm trying to provide some utility functions.</p>
<p>One of them is supposed to be equivalent to <code>if x:</code> but if that is <strong>completely</strong> equivallent to <code>if bool(x) is True:</code> then I could only provide one function to check <code>if x is True:</code> and <code>if x:</code>.</p>
<p>Is the negation of that also equivalent? <code>if bool(x) is False:</code> equal to <code>if not x:</code>?</p>
| 5 | 2016-07-21T17:44:01Z | 38,510,997 | <p>Yes. These are equivalent. The rules used by <code>if</code> are the same as those used by <code>bool</code>. <code>not</code> simply inverts these values without changing the logic for determining truthiness or falseness.</p>
| 2 | 2016-07-21T17:45:24Z | [
"python"
] |
Is `if x:` completely equivalent to `if bool(x) is True:`? | 38,510,964 | <p>For a small testing framework we are writing I'm trying to provide some utility functions.</p>
<p>One of them is supposed to be equivalent to <code>if x:</code> but if that is <strong>completely</strong> equivallent to <code>if bool(x) is True:</code> then I could only provide one function to check <code>if x is True:</code> and <code>if x:</code>.</p>
<p>Is the negation of that also equivalent? <code>if bool(x) is False:</code> equal to <code>if not x:</code>?</p>
| 5 | 2016-07-21T17:44:01Z | 38,512,053 | <p>additionally to the answer of @Martijn, if what you are building are some class, you can define what behavior you want it to have in a truth testing case like <code>ìf x</code> by defining <code>__bool__</code> function. </p>
<pre><code>>>> class A:
pass
>>> a=A()
>>> if a:
print("this instance class is truthish")
this instance class is truthish
>>> a is True
False
>>> bool(a) is True
True
>>>
</code></pre>
<p>the default behavior for a user defined class is to always be true in a truth test, to change that just define <code>__bool__</code> (<code>__nonzero__</code> in python 2) so it adjust accordingly to the semantic of the class, like for example:</p>
<pre><code>>>> class Switch:
def __init__(self, state="off"):
self.state = state
def __bool__(self):
if self.state == "on":
return True
return False
>>> x=Switch()
>>> if x:
print("this instance class is truthish")
>>> x is True
False
>>> bool(x) is True
False
>>> x.state="on"
>>> if x:
print("this instance class is truthish")
this instance class is truthish
>>> x is True
False
>>> bool(x) is True
True
>>>
</code></pre>
| 1 | 2016-07-21T18:42:43Z | [
"python"
] |
Read CSV file and filter results | 38,510,966 | <p>Im writing a script where one of its functions is to read a CSV file that contain URLs on one of its rows. Unfortunately the system that create those CSVs doesn't put double-quotes on values inside the URL column so when the URL contain commas it breaks all my csv parsing. </p>
<p>This is the code I'm using: </p>
<pre><code>with open(accesslog, 'r') as csvfile, open ('results.csv', 'w') as enhancedcsv:
reader = csv.DictReader(csvfile)
for row in reader:
self.uri = (row['URL'])
self.OriCat = (row['Category'])
self.query(self.uri)
print self.URL+","+self.ServerIP+","+self.OriCat+","+self.NewCat"
</code></pre>
<p>This is a sample URL that is breaking up the parsing - this URL comes on the row named "URL". (note the commas at the end)</p>
<pre><code>ams1-ib.adnxs.com/ww=1238&wh=705&ft=2&sv=43&tv=view5-1&ua=chrome&pl=mac&x=1468251839064740641,439999,v,mac,webkit_chrome,view5-1,0,,2,
</code></pre>
<p>The following row after the URL always come with a numeric value between parenthesis. Ex: (9999) so this could be used to define when the URL with commas end. </p>
<p>How can i deal with a situation like this using the csv module? </p>
| 0 | 2016-07-21T17:44:09Z | 38,511,672 | <p>Have you considered using Pandas to read your data in?</p>
<p>Another possible solution would be to use regular expressions to pre-process the data...</p>
<pre><code>#make a list of everything you want to change
old = re.findall(regex, f.read())
#append quotes and create a new list
new = []
for url in old:
url2 = "\""+url+"\""
new.append(url2)
#combine the lists
old_new = list(zip(old,new))
#Then use the list to update the file:
f = open(filein,'r')
filedata = f.read()
f.close()
for old,new in old_new:
newdata = filedata.replace(old,new)
f = open(filein,'w')
f.write(newdata)
f.close()
</code></pre>
| 0 | 2016-07-21T18:21:56Z | [
"python",
"csv",
"parsing"
] |
Read CSV file and filter results | 38,510,966 | <p>Im writing a script where one of its functions is to read a CSV file that contain URLs on one of its rows. Unfortunately the system that create those CSVs doesn't put double-quotes on values inside the URL column so when the URL contain commas it breaks all my csv parsing. </p>
<p>This is the code I'm using: </p>
<pre><code>with open(accesslog, 'r') as csvfile, open ('results.csv', 'w') as enhancedcsv:
reader = csv.DictReader(csvfile)
for row in reader:
self.uri = (row['URL'])
self.OriCat = (row['Category'])
self.query(self.uri)
print self.URL+","+self.ServerIP+","+self.OriCat+","+self.NewCat"
</code></pre>
<p>This is a sample URL that is breaking up the parsing - this URL comes on the row named "URL". (note the commas at the end)</p>
<pre><code>ams1-ib.adnxs.com/ww=1238&wh=705&ft=2&sv=43&tv=view5-1&ua=chrome&pl=mac&x=1468251839064740641,439999,v,mac,webkit_chrome,view5-1,0,,2,
</code></pre>
<p>The following row after the URL always come with a numeric value between parenthesis. Ex: (9999) so this could be used to define when the URL with commas end. </p>
<p>How can i deal with a situation like this using the csv module? </p>
| 0 | 2016-07-21T17:44:09Z | 38,532,633 | <p>You will have to do it a little more manually. Try this</p>
<pre><code>def process(lines, delimiter=','):
header = None
url_index_from_start = None
url_index_from_end = None
for line in lines:
if not header:
header = [l.strip() for l in line.split(delimiter)]
url_index_from_start = header.index('URL')
url_index_from_end = len(header)-url_index_from_start
else:
data = [l.strip() for l in line.split(delimiter)]
url_from_start = url_index_from_start
url_from_end = len(data)-url_index_from_end
values = data[:url_from_start] + data[url_from_end+1:] + [delimiter.join(data[url_from_start:url_from_end+1])]
keys = header[:url_index_from_start] + header[url_index_from_end+1:] + [header[url_index_from_start]]
yield dict(zip(keys, values))
</code></pre>
<p>Usage:</p>
<pre><code>lines = ['Header1, Header2, URL, Header3',
'Content1, "Content2", abc,abc,,abc, Content3']
result = list(process(lines))
assert result[0]['Header1'] == 'Content1'
assert result[0]['Header2'] == '"Content2"'
assert result[0]['Header3'] == 'Content3'
assert result[0]['URL'] == 'abc,abc,,abc'
print(result)
</code></pre>
<p>Result:</p>
<pre><code>>>> [{'URL': 'abc,abc,,abc', 'Header2': '"Content2"', 'Header3': 'Content3', 'Header1': 'Content1'}]
</code></pre>
| 1 | 2016-07-22T17:54:37Z | [
"python",
"csv",
"parsing"
] |
Is there an alternative for sys.exit() in python? | 38,511,096 | <pre><code>try:
x="blaabla"
y="nnlfa"
if x!=y:
sys.exit()
else:
print("Error!")
except Exception:
print(Exception)
</code></pre>
<p>I'm not asking about why it is throwing an error. I know that it raises <code>exceptions.SystemExit</code>. I was wondering if there was another way to exit?</p>
| -3 | 2016-07-21T17:50:38Z | 38,511,414 | <p><code>os._exit()</code> will do a low level process exit without <code>SystemExit</code> or normal python exit processing.</p>
| 1 | 2016-07-21T18:08:15Z | [
"python",
"python-3.x",
"try-except"
] |
Is there an alternative for sys.exit() in python? | 38,511,096 | <pre><code>try:
x="blaabla"
y="nnlfa"
if x!=y:
sys.exit()
else:
print("Error!")
except Exception:
print(Exception)
</code></pre>
<p>I'm not asking about why it is throwing an error. I know that it raises <code>exceptions.SystemExit</code>. I was wondering if there was another way to exit?</p>
| -3 | 2016-07-21T17:50:38Z | 38,512,740 | <p>Some questions like that should really be accompanied by the real intention behind the code. The reason is that some problems should be solved completely differently. In the body of the script, the <code>return</code> can be used to quit the script. From another point of view, you can just remember the situation in a variable and implement the wanted behaviour after the <code>try/except</code> construct. Or your <code>except</code> may test more explicit kind of an exception.</p>
<p>The code below shows one variation with the variable. The variable is assigned a function (the assigned function is not called here). The function is called (via the variable) only after the <code>try/except</code>:</p>
<pre><code>#!python3
import sys
def do_nothing():
print('Doing nothing.')
def my_exit():
print('sys.exit() to be called')
sys.exit()
fn = do_nothing # Notice that it is not called. The function is just
# given another name.
try:
x = "blaabla"
y = "nnlfa"
if x != y:
fn = my_exit # Here a different function is given the name fn.
# You can directly assign fn = sys.exit; the my_exit
# just adds the print to visualize.
else:
print("Error!")
except Exception:
print(Exception)
# Now the function is to be called. Or it is equivalent to calling do_nothing(),
# or it is equivalent to calling my_exit().
fn()
</code></pre>
| 0 | 2016-07-21T19:24:09Z | [
"python",
"python-3.x",
"try-except"
] |
ACK & TCP Window on Ubuntu | 38,511,136 | <p>Good evening,</p>
<p>I am working on a project which is using eventlet <a href="http://eventlet.net/" rel="nofollow">http://eventlet.net/</a> ontop of wsgi in Python to create a websocket server. So far everything is working well. We did some deep level packet analysis today however and noticed something odd. We are trying to minimize the outbound data from the server. At the moment it only seems to send ACK's which is taking up much of the data outbound at the moment (around 1M per hour).</p>
<p>No matter what we set the receive window too on the Ubuntu sysctl file an ACK is being sent to the client at the same time (after 5 packets). We want to make this window larger such that maybe 1 ACK is sent every 15 packets these packets are 1440 Bytes in size </p>
<p>Below are our sysctl settings for the TCP send and receive buffers</p>
<pre><code>net.core.wmem_max = 4194304
net.core.rmem_max = 6291456
net.ipv4.tcp_rmem = 4096 2097152 6291456
net.ipv4.tcp_wmem = 4096 1048576 4194304
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_sack = 1
net.core.netdev_max_backlog = 5000
</code></pre>
<p>As you will see we have scaling enabled, with it enabled the server is setting a Win=8159 in its Ack however even with it disabled and a default of 64k being sent in the servers ACK window the ACK is actually being sent back to the client around every 7k.</p>
<p>Is there something fundamental we are missing here? Can a client set a buffer limit at which it will no longer send data unless it receive an ACK? Is there some sort of time limit at which a ACK is sent regardless of the received buffer size?</p>
<p>Thank you for your help.</p>
| 0 | 2016-07-21T17:52:44Z | 38,514,795 | <blockquote>
<p>Is there some sort of time limit at which a ACK is sent regardless of the received buffer size?</p>
</blockquote>
<p>ACK is being sent to give a feedback from receiver, if sender will not receive ACK during some time (estimated RTT) it guesses that packet is lost and will retransmit this packet again. In basic tcp version, ACK will be sent in response to every packet, but as optimization many OS implements delayed ACK. Receiver will wait some time before sending ACK, and if receiver will receive another packet during this timeout, it will generate only one ACK (with largest number) for those packets that was received during this time. Because of this ACK will be sent regardless any receiver buffer. On linux you can disable delayed ACK via <code>TCP_QUICKACK</code> socket option, in this case every received packet will generate ACK packet. On some versions of linux you also can change this timeout, but this could cause unnecessary data retransmission. </p>
<blockquote>
<p>Can a client set a buffer limit at which it will no longer send data unless it receive an ACK?</p>
</blockquote>
<p>It possible via changing send buffer. If send buffer is full next write operations would block (in case of blocking client). Every ACK will free packet from send buffer and will allow next write operations.</p>
| 1 | 2016-07-21T21:37:57Z | [
"python",
"sockets",
"ubuntu",
"networking",
"tcp"
] |
Parsing Multiple .json files | 38,511,163 | <p>I am trying to parse multiple files dealing with "Mike's Pies" as you can see in the code below. I have written it to where I get the desired output, now I would like to parse all the files named "Mike's Pies"</p>
<pre><code> import json
import sys
import glob
with open("Mike's Pies.20130201.json") as json_data:
data = json.load(json_data)
#Keep all orders with variable of r
for r in data ["orders"]:
orderName = r["orderPlacer"]["name"]
#Print with address to acquire the housenumber/street/city/state
address = r["address"]["houseNumber"]
street = r["address"]["street"]
city = r["address"]["city"]
state = r["address"]["state"]
Mikes = "Mike's Pies,"
output = str(orderName) + ", " + str(address) + " " + str(street) +
" " + str(city) + " " + str(state) + ", " + Mikes + " "
length = len(r["pizzas"])
for i in range (0,length):
#if length >= 1 print r["pizzas"][1]["name"]
#if i!=length:
pizza = ((r["pizzas"][i]["name"].strip("\n"))).strip(" ")
if(i!=length-1):
output += pizza + ", "
else:
output += pizza
print(output+"\n")
</code></pre>
| 0 | 2016-07-21T17:54:10Z | 38,511,280 | <p>It sounds like you have code which works on <code>"Mike's Pies.20130201.json"</code>, and you want to run that code on <em>every</em> file that starts with "Mike's Pies" and ends with "json", regardless of the timestamp-like bit in the middle. Am I right? You can get all matching filenames with <code>glob</code> and parse them one after the other.</p>
<pre><code>for filename in glob.glob("Mike's Pies.*.json"):
with open(filename) as json_data:
data = json.load(json_data)
#etc etc... Insert rest of code here
</code></pre>
| 1 | 2016-07-21T18:00:21Z | [
"python"
] |
While debugging, how to print all variables (which is in list format) who are trainable in Tensorflow? | 38,511,166 | <p>While debugging, how to print all variables (which is in list format) who are trainable in Tensorflow?</p>
<p>For instance,</p>
<pre><code> tvars = tf.trainable_variables()
</code></pre>
<p>I want to check all the variables in tvars (which is list type).</p>
<p>I've already tried the below code which returns error,</p>
<pre><code> myvars = session.run([tvars])
print(myvars)
</code></pre>
| 0 | 2016-07-21T17:54:19Z | 38,580,555 | <p>Since <code>tf.trainable_variables()</code> returns a list of <code>tf.Variable</code> objects, you should be able to pass its result straight to <code>Session.run()</code>:</p>
<pre><code>tvars = tf.trainable_variables()
tvars_vals = sess.run(tvars)
for var, val in zip(tvars, tvars_vals):
print(var.name, val) # Prints the name of the variable alongside its value.
</code></pre>
| 1 | 2016-07-26T03:28:56Z | [
"python",
"tensorflow"
] |
How to declare variables to be used in multiple modules in python | 38,511,192 | <p>This question has probably been asked before, but the other posts I found on Stack Overflow mainly dealt with changing global variables and importing functions etc. Perhaps my wording wasn't right when I did a quick search.</p>
<p>I am starting to code in Python, and I was wondering what the most efficient and proper way to do the following is.</p>
<p>I have a parent module that I am importing to other modules. It has the structure:</p>
<pre><code># some import statements go here
# Constants that need to be the same for all objects
a = 1
b = 2
...
# A class with some useful functions
class Def():
def __init__(self):
...
</code></pre>
<p>I am importing this module in some others, to use the functions in the Def class. But I also want all the modules importing it to have access to the constants that I declared outside the class. </p>
<p>I declared them outside, as I want those values to be used wherever I called them in that module. I did not want to attach them to objects (and have to refer to them as self.a, self.b etc.) and they will be constants throughout every module I am using. </p>
<p>Some of the options I am considering are:</p>
<ol>
<li>Declare these as global variables in a separate class, and import
that class in every module </li>
<li>Use <code>from parentmodule import *</code></li>
</ol>
<p>I am not sure if either of these will work, and if there is a standard way of doing this. Conflicts in names of variables while doing the latter will not be a problem, because of the nature of the constants. In the context of my program, they are physical constants with unique names that will not be used to represent other variables.</p>
<p>Apologies if the question is too basic/previously asked, and thank you for your help. </p>
| 0 | 2016-07-21T17:55:45Z | 38,511,405 | <p>Importing the whole module will act as a sort of namespace, and it seems to me to be the simplest way to do it. So you have "mystuff.py":</p>
<pre><code>a = 1
b = 2
def MyFunc():
....
</code></pre>
<p>Then in your other modules:</p>
<pre><code>import mystuff
print mystuff.a
print mystuff.b
mystuff.MyFunc()
</code></pre>
<p>Your solution to:</p>
<pre><code>from mystuff import *
</code></pre>
<p>Works, but possibly conflicts and I'm thinking isn't what people consider "pythonic."</p>
| 1 | 2016-07-21T18:08:05Z | [
"python",
"class",
"import",
"global-variables",
"constants"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.